repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
luislenes/EgresadosWeb
src/java/com/egresados/servlet/SaveAnswers.java
5900
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.egresados.servlet; import com.egresados.dao.DaoHistorialDeEncuestas; import com.egresados.dao.DaoRespuesta; import com.egresados.model.Egresado; import com.egresados.model.HistorialDeEncuestas; import com.egresados.model.Respuesta; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * * @author Luis */ @WebServlet(name = "SaveAnswers", urlPatterns = {"/SaveAnswers"}) public class SaveAnswers extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); JSONObject messageResponse = new JSONObject(); HttpSession session = request.getSession(false); if (session != null) { if (session.getAttribute("usuario") instanceof Egresado) { Egresado egresado = (Egresado) session.getAttribute("usuario"); String jsonString = request.getParameter("doc"); if (jsonString != null) { JSONParser parser = new JSONParser(); try { Object temp = parser.parse(jsonString); if (temp instanceof JSONObject) { JSONObject json = (JSONObject) temp; HistorialDeEncuestas historial = new HistorialDeEncuestas((String)json.get("codePoll"), egresado); JSONArray answers = (JSONArray) json.get("answers"); for (Object item : answers) { JSONObject answer = (JSONObject) item; Respuesta respuesta; if ((String)answer.get("option")!=null && !"".equals((String)answer.get("option"))) { respuesta = new Respuesta( (String) answer.get("codeQuestion"), (String) json.get("codePoll"), (String) answer.get("content"), egresado.getCodigo(), (String)answer.get("option")); }else{ respuesta = new Respuesta( (String) answer.get("codeQuestion"), (String) json.get("codePoll"), (String) answer.get("content"), egresado.getCodigo()); } historial.getRespuestas().add(respuesta); } DaoHistorialDeEncuestas.getInstance().insert(historial); for (Respuesta respuesta : historial.getRespuestas()) { DaoRespuesta.getInstance().insert(respuesta); } messageResponse.put("message", "Se ha enviado la encuesta correctamente!"); messageResponse.put("icon", "icon-good"); messageResponse.put("state", "success"); messageResponse.put("success", json); } else { messageResponse.put("message", "Error al parsear los parametros obtenidos."); messageResponse.put("icon", "icon-error"); messageResponse.put("state", "error"); } } catch (ParseException | SQLException ex) { Logger.getLogger(CreatePoll.class.getName()).log(Level.SEVERE, null, ex); messageResponse.put("message", ex.getMessage()); messageResponse.put("icon", "icon-error"); messageResponse.put("state", "error"); } }else { messageResponse.put("message", "Parametros de entrada no reconocidos."); messageResponse.put("icon", "icon-error"); messageResponse.put("state", "error"); } }else { messageResponse.put("message", "Para acceder a esta operación debes ser un usuario egresado."); messageResponse.put("icon", "icon-error"); messageResponse.put("state", "error"); } }else { messageResponse.put("message", "Para acceder a esta operación necesitas estas loggeado."); messageResponse.put("icon", "icon-error"); messageResponse.put("state", "error"); } try (PrintWriter out = response.getWriter()) { out.print(messageResponse.toString()); } } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
gpl-2.0
Craft---/Chef-Artifactory-Client
recipes/default.rb
108
chef_gem 'artifactory' do action :nothing end.run_action(:install) Gem.clear_paths require 'artifactory'
gpl-2.0
pehohlva/qt-gmail-access
Drupalmail/parser/3rdparty/kcodecs.cpp
6764
/* Copyright (C) 2000-2001 Dawit Alemayehu <[email protected]> Copyright (C) 2001 Rik Hemsley (rikkus) <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. The encoding and decoding utilities in MCodecs with the exception of quoted-printable are based on the java implementation in HTTPClient package by Ronald Tschalär Copyright (C) 1996-1999. // krazy:exclude=copyright The quoted-printable codec as described in RFC 2045, section 6.7. is by Rik Hemsley (C) 2001. */ #include "kcodecs.h" #include <stdio.h> #include <string.h> #ifdef _MSC_VER #define strcasecmp stricmp #define strncasecmp strnicmp #endif #include <stdlib.h> //#include <kdebug.h> #include <QtCore/QIODevice> namespace MCodecs { static const char hexChars[16] ={ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; static const unsigned int maxQPLineLength = 76; } // namespace MCodecs /******************************** MCodecs ********************************/ // strchr(3) for broken systems. static int rikFindChar(register const char * _s, const char c) { register const char * s = _s; while (true) { if ((0 == *s) || (c == *s)) break; ++s; if ((0 == *s) || (c == *s)) break; ++s; if ((0 == *s) || (c == *s)) break; ++s; if ((0 == *s) || (c == *s)) break; ++s; } return s - _s; } QByteArray MCodecs::quotedPrintableEncode(const QByteArray& in, bool useCRLF) { QByteArray out; quotedPrintableEncode(in, out, useCRLF); return out; } void MCodecs::quotedPrintableEncode(const QByteArray& in, QByteArray& out, bool useCRLF) { out.resize(0); if (in.isEmpty()) return; char *cursor; const char *data; unsigned int lineLength; unsigned int pos; const unsigned int length = in.size(); const unsigned int end = length - 1; ///// qDebug() << in << " arriva \n"; // Reasonable guess for output size when we're encoding // mostly-ASCII data. It doesn't really matter, because // the underlying allocation routines are quite efficient, // but it's nice to have 0 allocations in many cases. out.resize((length * 12) / 10); cursor = out.data(); data = in.data(); lineLength = 0; pos = 0; for (unsigned int i = 0; i < length; i++) { unsigned char c(data[i]); // check if we have to enlarge the output buffer, use // a safety margin of 16 byte pos = cursor - out.data(); if (out.size() - pos < 16) { out.resize(out.size() + 4096); cursor = out.data() + pos; } // Plain ASCII chars just go straight out. if ((c >= 33) && (c <= 126) && ('=' != c)) { *cursor++ = c; ++lineLength; } // Spaces need some thought. We have to encode them at eol (or eof). else if (' ' == c) { if ( (i >= length) || ((i < end) && ((useCRLF && ('\r' == data[i + 1]) && ('\n' == data[i + 2])) || (!useCRLF && ('\n' == data[i + 1])))) ) { *cursor++ = '='; *cursor++ = '2'; *cursor++ = '0'; lineLength += 3; } else { *cursor++ = ' '; ++lineLength; } } // If we find a line break, just let it through. else if ((useCRLF && ('\r' == c) && (i < end) && ('\n' == data[i + 1])) || (!useCRLF && ('\n' == c))) { lineLength = 0; if (useCRLF) { *cursor++ = '\r'; *cursor++ = '\n'; ++i; } else { *cursor++ = '\n'; } } // Anything else is converted to =XX. else { *cursor++ = '='; *cursor++ = hexChars[c / 16]; *cursor++ = hexChars[c % 16]; lineLength += 3; } // If we're approaching the maximum line length, do a soft line break. if ((lineLength > maxQPLineLength) && (i < end)) { if (useCRLF) { *cursor++ = '='; *cursor++ = '\r'; *cursor++ = '\n'; } else { *cursor++ = '='; *cursor++ = '\n'; } lineLength = 0; } } out.truncate(cursor - out.data()); } QByteArray MCodecs::quotedPrintableDecode(const QByteArray & in) { QByteArray out; QByteArray chunk = in; chunk.replace(QByteArray("=\n\r"),QByteArray()); chunk.replace(QByteArray("=\n"),QByteArray()); quotedPrintableDecode(chunk, out); return out; } void MCodecs::quotedPrintableDecode(const QByteArray& in, QByteArray& out) { // clear out the output buffer out.resize(0); if (in.isEmpty()) return; char *cursor; const unsigned int length = in.size(); out.resize(length); cursor = out.data(); for (unsigned int i = 0; i < length; i++) { char c(in[i]); if ('=' == c) { if (i < length - 2) { char c1 = in[i + 1]; char c2 = in[i + 2]; if (('\n' == c1) || ('\r' == c1 && '\n' == c2)) { // Soft line break. No output. if ('\r' == c1) i += 2; // CRLF line breaks else i += 1; } else { // =XX encoded byte. int hexChar0 = rikFindChar(hexChars, c1); int hexChar1 = rikFindChar(hexChars, c2); if (hexChar0 < 16 && hexChar1 < 16) { *cursor++ = char((hexChar0 * 16) | hexChar1); i += 2; } } } } else { *cursor++ = c; } } out.truncate(cursor - out.data()); }
gpl-2.0
HuangYuNan/thcsvr
expansions/script/c28011.lua
4524
--秘封 宇佐见莲子 function c28011.initial_effect(c) c:EnableReviveLimit() --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(28011,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_HAND) e2:SetCost(c28011.spcost) e2:SetTarget(c28011.sptg) e2:SetOperation(c28011.spop) c:RegisterEffect(e2) --Activate local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(28011,1)) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1) e3:SetTarget(c28011.target) e3:SetOperation(c28011.operation) c:RegisterEffect(e3) --special summon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(28011,2)) e4:SetCategory(CATEGORY_TOGRAVE+CATEGORY_SPECIAL_SUMMON) e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_CHAIN_UNIQUE) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e4:SetCode(EVENT_DESTROY) e4:SetRange(LOCATION_REMOVED) e4:SetCondition(c28011.scon) e4:SetCost(c28011.cost) e4:SetTarget(c28011.stg) e4:SetOperation(c28011.sop) c:RegisterEffect(e4) end function c28011.rfilter(c) return c:IsSetCard(0x211) and c:IsAbleToRemoveAsCost() end function c28011.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c28011.rfilter,tp,LOCATION_GRAVE,0,2,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c28011.rfilter,tp,LOCATION_GRAVE,0,2,2,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c28011.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,true,true) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c28011.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,true,true,POS_FACEUP)>0 then c:CompleteProcedure() end end function c28011.cfilter(c) return not c:IsPublic() end function c28011.jfilter(c) return c:IsAbleToRemove() or c:IsDestructable() end function c28011.filter1(c) return c:IsSetCard(0x208) and c:IsAbleToRemove() and c:IsFaceup() end function c28011.filter2(c) return not c:IsSetCard(0x208) and c:IsDestructable() and c:IsFaceup() end function c28011.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c28011.cfilter,tp,LOCATION_HAND,0,1,nil) and Duel.IsExistingMatchingCard(c28011.jfilter,tp,0,LOCATION_MZONE,1,nil) end end function c28011.operation(e,tp,eg,ep,ev,re,r,rp) if Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)==0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM) local g=Duel.SelectMatchingCard(tp,c28011.cfilter,tp,LOCATION_HAND,0,1,1,nil) Duel.ConfirmCards(1-tp,g) if g:GetFirst():IsSetCard(0x208) then local sg1=Duel.SelectMatchingCard(tp,c28011.filter2,tp,0,LOCATION_MZONE,1,1,e:GetHandler()) Duel.Destroy(sg1,REASON_EFFECT) else local sg2=Duel.SelectMatchingCard(tp,c28011.filter1,tp,0,LOCATION_MZONE,1,1,e:GetHandler()) Duel.Remove(sg2,POS_FACEUP,REASON_EFFECT) end Duel.ShuffleHand(tp) end function c28011.filter(c,tp) return c:IsSetCard(0xc211) and c:GetControler()==tp and c:GetReasonPlayer()==1-tp end function c28011.scon(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c28011.filter,1,nil,tp) end function c28011.costfilter(c) return c:IsSetCard(0x211) and c:IsAbleToGraveAsCost() and c:IsFaceup() end function c28011.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c28011.costfilter,tp,LOCATION_REMOVED,0,9,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c28011.costfilter,tp,LOCATION_REMOVED,0,9,9,e:GetHandler()) Duel.SendtoGrave(g,REASON_COST) end function c28011.stg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingMatchingCard(aux.TRUE,tp,0xf,0xf,1,nil) end local g=Duel.GetMatchingGroup(aux.TRUE,tp,0xf,0xf,nil) Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,g,g:GetCount(),0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c28011.sop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(aux.TRUE,tp,0xf,0xf,nil) Duel.SendtoGrave(g,REASON_EFFECT) local c=e:GetHandler() if Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
PJosepherum/mediawiki
includes/mail/UserMailer.php
13287
<?php /** * Classes used to send e-mails * * 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. * http://www.gnu.org/copyleft/gpl.html * * @file * @author <[email protected]> * @author <[email protected]> * @author Tim Starling * @author Luke Welling [email protected] */ /** * Collection of static functions for sending mail */ class UserMailer { private static $mErrorString; /** * Send mail using a PEAR mailer * * @param UserMailer $mailer * @param string $dest * @param string $headers * @param string $body * * @return Status */ protected static function sendWithPear( $mailer, $dest, $headers, $body ) { $mailResult = $mailer->send( $dest, $headers, $body ); # Based on the result return an error string, if ( PEAR::isError( $mailResult ) ) { wfDebug( "PEAR::Mail failed: " . $mailResult->getMessage() . "\n" ); return Status::newFatal( 'pear-mail-error', $mailResult->getMessage() ); } else { return Status::newGood(); } } /** * Creates a single string from an associative array * * @param array $headers Associative Array: keys are header field names, * values are ... values. * @param string $endl The end of line character. Defaults to "\n" * * Note RFC2822 says newlines must be CRLF (\r\n) * but php mail naively "corrects" it and requires \n for the "correction" to work * * @return string */ static function arrayToHeaderString( $headers, $endl = "\n" ) { $strings = array(); foreach ( $headers as $name => $value ) { // Prevent header injection by stripping newlines from value $value = self::sanitizeHeaderValue( $value ); $strings[] = "$name: $value"; } return implode( $endl, $strings ); } /** * Create a value suitable for the MessageId Header * * @return string */ static function makeMsgId() { global $wgSMTP, $wgServer; $msgid = uniqid( wfWikiID() . ".", true ); /* true required for cygwin */ if ( is_array( $wgSMTP ) && isset( $wgSMTP['IDHost'] ) && $wgSMTP['IDHost'] ) { $domain = $wgSMTP['IDHost']; } else { $url = wfParseUrl( $wgServer ); $domain = $url['host']; } return "<$msgid@$domain>"; } /** * This function will perform a direct (authenticated) login to * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an * array of parameters. It requires PEAR:Mail to do that. * Otherwise it just uses the standard PHP 'mail' function. * * @param MailAddress|MailAddress[] $to Recipient's email (or an array of them) * @param MailAddress $from Sender's email * @param string $subject Email's subject. * @param string $body Email's text or Array of two strings to be the text and html bodies * @param MailAddress $replyto Optional reply-to email (default: null). * @param string $contentType Optional custom Content-Type (default: text/plain; charset=UTF-8) * @throws MWException * @throws Exception * @return Status */ public static function send( $to, $from, $subject, $body, $replyto = null, $contentType = 'text/plain; charset=UTF-8' ) { global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams, $wgAllowHTMLEmail; $mime = null; if ( !is_array( $to ) ) { $to = array( $to ); } // mail body must have some content $minBodyLen = 10; // arbitrary but longer than Array or Object to detect casting error // body must either be a string or an array with text and body if ( !( !is_array( $body ) && strlen( $body ) >= $minBodyLen ) && !( is_array( $body ) && isset( $body['text'] ) && isset( $body['html'] ) && strlen( $body['text'] ) >= $minBodyLen && strlen( $body['html'] ) >= $minBodyLen ) ) { // if it is neither we have a problem return Status::newFatal( 'user-mail-no-body' ); } if ( !$wgAllowHTMLEmail && is_array( $body ) ) { // HTML not wanted. Dump it. $body = $body['text']; } wfDebug( __METHOD__ . ': sending mail to ' . implode( ', ', $to ) . "\n" ); # Make sure we have at least one address $has_address = false; foreach ( $to as $u ) { if ( $u->address ) { $has_address = true; break; } } if ( !$has_address ) { return Status::newFatal( 'user-mail-no-addy' ); } # Forge email headers # ------------------- # # WARNING # # DO NOT add To: or Subject: headers at this step. They need to be # handled differently depending upon the mailer we are going to use. # # To: # PHP mail() first argument is the mail receiver. The argument is # used as a recipient destination and as a To header. # # PEAR mailer has a recipient argument which is only used to # send the mail. If no To header is given, PEAR will set it to # to 'undisclosed-recipients:'. # # NOTE: To: is for presentation, the actual recipient is specified # by the mailer using the Rcpt-To: header. # # Subject: # PHP mail() second argument to pass the subject, passing a Subject # as an additional header will result in a duplicate header. # # PEAR mailer should be passed a Subject header. # # -- hashar 20120218 $headers['From'] = $from->toString(); $returnPath = $from->address; $extraParams = $wgAdditionalMailParams; // Hook to generate custom VERP address for 'Return-Path' Hooks::run( 'UserMailerChangeReturnPath', array( $to, &$returnPath ) ); # Add the envelope sender address using the -f command line option when PHP mail() is used. # Will default to the $from->address when the UserMailerChangeReturnPath hook fails and the # generated VERP address when the hook runs effectively. $extraParams .= ' -f ' . $returnPath; $headers['Return-Path'] = $returnPath; if ( $replyto ) { $headers['Reply-To'] = $replyto->toString(); } $headers['Date'] = MWTimestamp::getLocalInstance()->format( 'r' ); $headers['Message-ID'] = self::makeMsgId(); $headers['X-Mailer'] = 'MediaWiki mailer'; $headers['List-Unsubscribe'] = '<' . SpecialPage::getTitleFor( 'Preferences' ) ->getFullURL( '', false, PROTO_CANONICAL ) . '>'; # Line endings need to be different on Unix and Windows due to # the bug described at http://trac.wordpress.org/ticket/2603 if ( wfIsWindows() ) { $endl = "\r\n"; } else { $endl = "\n"; } if ( is_array( $body ) ) { // we are sending a multipart message wfDebug( "Assembling multipart mime email\n" ); if ( !stream_resolve_include_path( 'Mail/mime.php' ) ) { wfDebug( "PEAR Mail_Mime package is not installed. Falling back to text email.\n" ); // remove the html body for text email fall back $body = $body['text']; } else { require_once 'Mail/mime.php'; if ( wfIsWindows() ) { $body['text'] = str_replace( "\n", "\r\n", $body['text'] ); $body['html'] = str_replace( "\n", "\r\n", $body['html'] ); } $mime = new Mail_mime( array( 'eol' => $endl, 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8' ) ); $mime->setTXTBody( $body['text'] ); $mime->setHTMLBody( $body['html'] ); $body = $mime->get(); // must call get() before headers() $headers = $mime->headers( $headers ); } } if ( $mime === null ) { // sending text only, either deliberately or as a fallback if ( wfIsWindows() ) { $body = str_replace( "\n", "\r\n", $body ); } $headers['MIME-Version'] = '1.0'; $headers['Content-type'] = ( is_null( $contentType ) ? 'text/plain; charset=UTF-8' : $contentType ); $headers['Content-transfer-encoding'] = '8bit'; } $ret = Hooks::run( 'AlternateUserMailer', array( $headers, $to, $from, $subject, $body ) ); if ( $ret === false ) { // the hook implementation will return false to skip regular mail sending return Status::newGood(); } elseif ( $ret !== true ) { // the hook implementation will return a string to pass an error message return Status::newFatal( 'php-mail-error', $ret ); } if ( is_array( $wgSMTP ) ) { # # PEAR MAILER # if ( !stream_resolve_include_path( 'Mail.php' ) ) { throw new MWException( 'PEAR mail package is not installed' ); } require_once 'Mail.php'; MediaWiki\suppressWarnings(); // Create the mail object using the Mail::factory method $mail_object =& Mail::factory( 'smtp', $wgSMTP ); if ( PEAR::isError( $mail_object ) ) { wfDebug( "PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n" ); MediaWiki\restoreWarnings(); return Status::newFatal( 'pear-mail-error', $mail_object->getMessage() ); } wfDebug( "Sending mail via PEAR::Mail\n" ); $headers['Subject'] = self::quotedPrintable( $subject ); # When sending only to one recipient, shows it its email using To: if ( count( $to ) == 1 ) { $headers['To'] = $to[0]->toString(); } # Split jobs since SMTP servers tends to limit the maximum # number of possible recipients. $chunks = array_chunk( $to, $wgEnotifMaxRecips ); foreach ( $chunks as $chunk ) { $status = self::sendWithPear( $mail_object, $chunk, $headers, $body ); # FIXME : some chunks might be sent while others are not! if ( !$status->isOK() ) { MediaWiki\restoreWarnings(); return $status; } } MediaWiki\restoreWarnings(); return Status::newGood(); } else { # # PHP mail() # if ( count( $to ) > 1 ) { $headers['To'] = 'undisclosed-recipients:;'; } $headers = self::arrayToHeaderString( $headers, $endl ); wfDebug( "Sending mail via internal mail() function\n" ); self::$mErrorString = ''; $html_errors = ini_get( 'html_errors' ); ini_set( 'html_errors', '0' ); set_error_handler( 'UserMailer::errorHandler' ); try { $safeMode = wfIniGetBool( 'safe_mode' ); foreach ( $to as $recip ) { if ( $safeMode ) { $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers ); } else { $sent = mail( $recip, self::quotedPrintable( $subject ), $body, $headers, $extraParams ); } } } catch ( Exception $e ) { restore_error_handler(); throw $e; } restore_error_handler(); ini_set( 'html_errors', $html_errors ); if ( self::$mErrorString ) { wfDebug( "Error sending mail: " . self::$mErrorString . "\n" ); return Status::newFatal( 'php-mail-error', self::$mErrorString ); } elseif ( !$sent ) { // mail function only tells if there's an error wfDebug( "Unknown error sending mail\n" ); return Status::newFatal( 'php-mail-error-unknown' ); } else { return Status::newGood(); } } } /** * Set the mail error message in self::$mErrorString * * @param int $code Error number * @param string $string Error message */ static function errorHandler( $code, $string ) { self::$mErrorString = preg_replace( '/^mail\(\)(\s*\[.*?\])?: /', '', $string ); } /** * Strips bad characters from a header value to prevent PHP mail header injection attacks * @param string $val String to be santizied * @return string */ public static function sanitizeHeaderValue( $val ) { return strtr( $val, array( "\r" => '', "\n" => '' ) ); } /** * Converts a string into a valid RFC 822 "phrase", such as is used for the sender name * @param string $phrase * @return string */ public static function rfc822Phrase( $phrase ) { // Remove line breaks $phrase = self::sanitizeHeaderValue( $phrase ); // Remove quotes $phrase = str_replace( '"', '', $phrase ); return '"' . $phrase . '"'; } /** * Converts a string into quoted-printable format * @since 1.17 * * From PHP5.3 there is a built in function quoted_printable_encode() * This method does not duplicate that. * This method is doing Q encoding inside encoded-words as defined by RFC 2047 * This is for email headers. * The built in quoted_printable_encode() is for email bodies * @param string $string * @param string $charset * @return string */ public static function quotedPrintable( $string, $charset = '' ) { # Probably incomplete; see RFC 2045 if ( empty( $charset ) ) { $charset = 'UTF-8'; } $charset = strtoupper( $charset ); $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ? $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff='; $replace = $illegal . '\t ?_'; if ( !preg_match( "/[$illegal]/", $string ) ) { return $string; } $out = "=?$charset?Q?"; $out .= preg_replace_callback( "/([$replace])/", array( __CLASS__, 'quotedPrintableCallback' ), $string ); $out .= '?='; return $out; } protected static function quotedPrintableCallback( $matches ) { return sprintf( "=%02X", ord( $matches[1] ) ); } }
gpl-2.0
wang159/CS541
project_4/yu/src/query/Describe.java
638
package query; import parser.AST_Describe; /** * Execution plan for describing tables. */ class Describe implements Plan { /** * Optimizes the plan, given the parsed query. * * @throws QueryException if table doesn't exist */ public Describe(AST_Describe tree) throws QueryException { } // public Describe(AST_Describe tree) throws QueryException /** * Executes the plan and prints applicable output. */ public void execute() { // print the output message System.out.println("(Not implemented)"); } // public void execute() } // class Describe implements Plan
gpl-2.0
Saftemand/S_DW_Continuous_Deployment_Test
S_DW_Continuous_Deployment_test/Admin/Content/Designer/EditDesign.js
3633
var submitted = false; var initialized = false; function init() { for (i = 0; i < document.getElementById("LayoutForm").elements.length; i++) { if (document.getElementById("LayoutForm").elements[i].id) { var value = elementValue(document.getElementById("LayoutForm").elements[i]); window[document.getElementById("LayoutForm").elements[i].id] = value; //Event.observe(document.getElementById("LayoutForm").elements[i], 'change', changed); } } initialized = true; } function changed() { alert("changed..."); } function checkSubmit(variable) { if (!submitted) { var value = elementValue(document.getElementById(variable)); if (window[variable] != value) { //alert(variable + ': ' + window[variable] + ': ' + value); submitAndReload(); if (variable == 'ColorSets') { setTimeout("window.location.reload();", 300); } } } window[variable] = elementValue(document.getElementById(variable)); } function elementValue(element) { if (element.type == "checkbox") { return element.checked; } else { return element.value; } } function apply(force) { if (!initialized) { init(); } submitted = false; if (force) { submitAndReload() } //alert('!'); for (i = 0; i < document.getElementById("LayoutForm").elements.length; i++) { if (document.getElementById("LayoutForm").elements[i].id) { checkSubmit(document.getElementById("LayoutForm").elements[i].id); } } //colorFrame refreshColors(); //window.parent.document.getElementById('basicColor').value //setTimeout("basicColor = document.getElementById('basicColor').value;", 1000); if (document.getElementById('previewFrame').src.indexOf('efault.aspx') == -1 && force == true) { setTimeout("document.getElementById('previewFrame').src = '/default.aspx?dt=12';", 100); } } function submitAndReload() { //alert(document.getElementById('previewFrame').document.location); submitted = true; document.LayoutForm.submit(); var src = document.getElementById('previewFrame').contentWindow.location.href; if (src.indexOf("?dt") > 0) { src = src.substring(0, src.indexOf("?dt")); } if (src.indexOf("&dt") > 0) { src = src.substring(0, src.indexOf("&dt")); } //src = src + "?dt=" & new Date().getTime(); //alert(document.getElementById('previewFrame').contentWindow.location.href + ': ' + src); //setTimeout("document.getElementById('previewFrame').src = document.getElementById('previewFrame').src;", 500); document.getElementById('previewFrame').contentWindow.location.reload(); //alert(); } function close() { window.close(); } function setSelected(color, item) { document.getElementById('RichColorSelect').value = color; item.parentNode.parentNode.id = color; } function refreshColors() { refreshColor('LogoBackgroundColor'); refreshColor('LogoPrimaryColor'); refreshColor('LogoSecondaryColor'); refreshColor('NavigationBackgroundColor'); refreshColor('FormBackgroundColor'); refreshColor('BodyBackgroundColor'); refreshColor('CallToActionColor'); refreshColor('NavigationFontColor'); refreshColor('H1FontColor'); refreshColor('H2FontColor'); refreshColor('H3FontColor'); refreshColor('TextFontColor'); } function refreshColor(selectName) { var key = 'colorgroups'; var regex = new RegExp("[\\?&]" + key + "=([^&#]*)"); var qs = ''; qs = regex.exec(document.getElementById(selectName + 'Frame').src); if (qs == null) { qs = new Array('', ''); } document.getElementById(selectName + 'Frame').src = 'ColorGen.aspx?colorgroups=' + qs[1] + '&parent=' + selectName + '&hex=' + document.getElementById('basicColor').value.replace("#", ""); }
gpl-2.0
beauxq/expressions
Evaluator.cpp
11128
#include "Evaluator.h" #include <string> #include <cctype> #include <stack> #include <stdexcept> #include <queue> #include "Token.h" const int Evaluator::FIRST_NON_WHITE = 33; // first char that prints non-white void Evaluator::store_exp(const std::string& input) { /** stores string in expression */ expression = input; cursor = 0; } int Evaluator::read_int() { /** reads an integer out of the expression from the cursor */ int to_return = 0; while (isdigit(expression[cursor])) // this is safe, returns false, for the end of the string (ISO/IEC 14882:2011 21.4.5) { to_return *= 10; to_return += (expression[cursor] - '0'); // convert from ascii ++cursor; } return to_return; } void Evaluator::eat_white() { /** moves cursor to next non-whitespace, printable character or end */ while ((cursor < expression.size()) && (expression[cursor] < FIRST_NON_WHITE)) ++cursor; } std::string Evaluator::cursor_str(int where /* = -1 */) const { /** returns a cursor position for error message */ if (where == -1) where = cursor; return " @ char: " + std::to_string(where); } std::queue<Token> Evaluator::make_tokens() { /** tokenizes expression into a queue of operators and operands */ std::queue<Token> tokens; bool next_is_binary = false; eat_white(); while (cursor < expression.size()) { if (next_is_binary) { next_is_binary = false; switch (expression[cursor]) { case '^': case '*': case '/': case '%': case '+': case '-': // simplest binary operators tokens.push(Token(expression[cursor], cursor)); ++cursor; break; case '>': if (expression[cursor+1] == '=') // >= { tokens.push(Token('g', cursor)); cursor += 2; } else // just > { tokens.push(Token('>', cursor)); ++cursor; } break; case '<': if (expression[cursor+1] == '=') // <= { tokens.push(Token('l', cursor)); cursor += 2; } else // just < { tokens.push(Token('<', cursor)); ++cursor; } break; case '=': case '&': case '|': if (expression[cursor+1] != expression[cursor]) // need 2 in a row throw std::invalid_argument("Invalid operator" + cursor_str()); tokens.push(Token(expression[cursor], cursor)); cursor += 2; break; case '!': if (expression[cursor+1] != '=') // != throw std::invalid_argument("Unary operator not allowed" + cursor_str()); tokens.push(Token('x', cursor)); cursor += 2; break; case ')': next_is_binary = true; // still need another binary after this tokens.push(Token(')', cursor)); ++cursor; break; default: throw std::invalid_argument("Binary operator required" + cursor_str()); } } else // integer or unary { if (isdigit(expression[cursor])) // integer { tokens.push(Token(read_int(), cursor)); next_is_binary = true; } else // unary { switch (expression[cursor]) { case '(': case '!': tokens.push(Token(expression[cursor], cursor)); ++cursor; break; case '+': if (expression[cursor+1] != '+') throw std::invalid_argument("Binary operator not allowed" + cursor_str()); tokens.push(Token('i', cursor)); // increment cursor += 2; break; case '-': if (expression[cursor+1] == '-') { tokens.push(Token('d', cursor)); // decrement cursor += 2; break; } // not decrement, has to be negative tokens.push(Token('n', cursor)); // negative ++cursor; break; default: if (tokens.empty()) throw std::invalid_argument("Must begin with integer or unary operator or open parenthesis" + cursor_str()); throw std::invalid_argument("Integer or unary operator or open parenthesis required" + cursor_str()); } } } eat_white(); } if (! next_is_binary) // expression has to end where a binary operator would come next { if (tokens.empty()) throw std::invalid_argument("Empty expression" + cursor_str()); throw std::invalid_argument("Expression must end with integer (or close parenthesis)" + cursor_str()); } return tokens; } // the algorithm of this function is inspired by Dr. Kuhail's examples, adapted and modified void Evaluator::process_operator(std::stack<int>& operands, std::stack<Token>& operators, const Token& operator_) const { /** handles order of operations for this operator compared to other operators on the operator stack */ if (operators.empty() || (operator_.operat == '(')) { if (operator_.operat == ')') throw std::invalid_argument("Unmatched close parenthesis" + cursor_str(operator_.location)); operators.push(operator_); } else // stack not empty and not open parenthesis { if ((operator_ > operators.top()) || (operator_.is_unary)) // all unary > other unary (even though same precedence #) operators.push(operator_); else // operator_ has lower (or equal) precedence than top { // evaluate all stacked operators with equal // or higher precedence than operator_ while (! operators.empty() && (operators.top().operat != '(') && (operator_ <= operators.top())) { // evaluate top operator and put result on operand stack operands.push(evaluate_one_operator(operands, operators.top())); operators.pop(); } // assert: operator stack empty or // top of stack is '(' or // operator_ precedence > top of stack if (operator_.operat == ')') { if (!operators.empty() && (operators.top().operat == '(')) operators.pop(); else // stack empty throw std::invalid_argument("Unmatched close parenthesis" + cursor_str(operator_.location)); } else // operator_ not parentheses and greater precedence than top operators.push(operator_); } } } int Evaluator::eval_tokens(std::queue<Token>& tokens) const { /** evaluate the expression from queue of tokens */ std::stack<int> operands; std::stack<Token> operators; while (! tokens.empty()) { if (tokens.front().is_integer) operands.push(tokens.front().integer); else // is operator process_operator(operands, operators, tokens.front()); tokens.pop(); } // assert: operator stack has no close parentheses, // if stack has open parentheses, it is invalid expression // (evaluate_one_operator will handle this) // else: only binary and unary operators // in order of precedence // highest at top of stack while (! operators.empty()) { operands.push(evaluate_one_operator(operands, operators.top())); operators.pop(); } // assert: operands has only 1 integer // (because the validity of the expression was checked // when making the tokens and processing operators) return operands.top(); } int Evaluator::evaluate_one_operator(std::stack<int>& operands, const Token& operator_) const { /** evaluates the operator with operands from the operand stack */ if (operator_.operat == '(') throw std::invalid_argument("Unmatched open parenthesis" + cursor_str(operator_.location)); int lhs, rhs, result; // pull needed operands rhs = operands.top(); operands.pop(); if (! operator_.is_unary) { lhs = operands.top(); operands.pop(); } // evaluate switch (operator_.operat) { case '!': return (! rhs); case 'i': return rhs + 1; case 'd': return rhs - 1; case 'n': return rhs * (-1); case '^': if ((lhs == 0) && (rhs == 0)) throw std::invalid_argument("Undefined expression 0^0" + cursor_str(operator_.location)); if ((lhs == 0) || (lhs == 1)) // 0 ^ rhs 1 ^ rhs not 0^0 return lhs; if (lhs == -1) // -1 ^ rhs { if (rhs % 2) // odd return -1; else // even return 1; } if (rhs < 0) // negative exponent with lhs != -1,0,1 throw std::invalid_argument("Non-integer expression (negative exponent)" + cursor_str(operator_.location)); result = 1; for (int i = rhs; i > 0; --i) result *= lhs; return result; case '*': return lhs * rhs; case '/': if (rhs == 0) throw std::invalid_argument("Division by zero" + cursor_str(operator_.location)); return lhs / rhs; case '%': return lhs % rhs; case '+': return lhs + rhs; case '-': return lhs - rhs; case '>': return (lhs > rhs); case 'g': return (lhs >= rhs); case '<': return (lhs < rhs); case 'l': return (lhs <= rhs); case '=': return (lhs == rhs); case 'x': return (lhs != rhs); case '&': return (lhs && rhs); case '|': return (lhs || rhs); default: throw std::invalid_argument("How did I get here? This shouldn't be possible!" + cursor_str(operator_.location)); } } int Evaluator::eval() { /** translate the stored expression into tokens and evaluate the tokens */ cursor = 0; std::queue<Token> tokens = make_tokens(); return eval_tokens(tokens); } int Evaluator::eval(const std::string& input) { /** store a new expression and evaluate it */ store_exp(input); return eval(); }
gpl-2.0
kirill-oficerov/romaksenia
wp-content/themes/simple-catch/content.php
4158
<?php /** * This is the template that displays content for index and archive page * * @package Catch Themes * @subpackage Simple_Catch * @since Simple Catch 1.3.2 */ global $wp_object_cache; get_header(); ?> <script type="text/javascript"> if($ == undefined) { var $ = jQuery; } (function($) { $(function() { // wdPrettyPhoto(); }); })(jQuery); </script> <?php if ( have_posts() ) : while( have_posts() ): the_post(); ?> <?php global $post; ?> <div <?php post_class(); ?> > <div class="col8"> <div style="float: left; margin-right: -150px; width: 100%; "> <h2 class="entry-title" style="margin: 10px 150px 3px 0px; "> <a href="<?php the_permalink() ?>" title="" rel="bookmark" ><?php the_title(); ?></a> </h2> </div> <?php $excerpt = the_excerpt(false); $content = mb_substr($excerpt, 3); $content = mb_substr($content, 0, -5); echo '<script type="text/javascript" src="//yandex.st/share/share.js" charset="utf-8"></script> <div class="yashare-auto-init" data-yashareL10n="ru" data-yashareType="none" data-yashareQuickServices="vkontakte,facebook,twitter,odnoklassniki,lj,gplus,pinterest"></div>' ?> <div class="clear" style="height: 1px; width: 1px; "></div> <div class="clear" style="height: 1px; width: 1px; "></div> <div style="text-align: right; float: left; margin: 0 15px 0 0;"> <? $picture = get_the_post_thumbnail( null, 'featured', '' ); if(!empty($picture)) { $pictureSrc = array(); preg_match('/src="[^"]+"/', $picture, $pictureSrc); $settings = unserialize($post->settings); $fullSizeImage = substr($pictureSrc[0], 4); if($settings) { if(isset($settings['width']) && isset($settings['height'])) { $width = $settings['width']; $height = $settings['height']; $picture = str_replace('<img', '<img style="width:' . $width . 'px; height:' . $height . 'px;"', $picture); } $matches = array(); preg_match('/"(.*wp-content.uploads).*$/', $fullSizeImage, $matches); $thumbnailSrc = $matches[1] . '/' . $settings['featuredImageName']; $picture = str_replace($fullSizeImage, '"' . $thumbnailSrc . '"', $picture); } ?> <!-- <a rel="prettyPhoto" href=--><?//=$fullSizeImage?><!-- title="--><?php //the_title_attribute( 'echo=0' ) ?><!--">--> <a href="<?php the_permalink() ?>"><?php echo $picture ?></a> <!-- </a>--> <? } ?> </div> <div class="post-excerpt" style="margin: 5px 0 0 0; overflow: hidden; font-size: 16px;"> <div class="post_date"><?=(date('d.m.Y', strtotime($post->post_date)))?></div> <? $matches = array(); preg_match('~<a[^>]+readmore[^>]*>Далее</a>~', $content, $matches); $content = str_replace($matches[0], '', $content); echo $content; if(strpos(substr($content, -10, 10), '<br />') === false) { echo "<br />"; } ?> <br> </div> <?=$matches[0]?> </div> <div class="row-end"></div> </div><!-- .post --> <hr /> <?php endwhile; // Checking WP Page Numbers plugin exist if ( function_exists('wp_pagenavi' ) ) : wp_pagenavi(); // Checking WP-PageNaviplugin exist elseif ( function_exists('wp_page_numbers' ) ) : wp_page_numbers(); else: global $wp_query; if ( $wp_query->max_num_pages > 1 ) : ?> <ul class="default-wp-page"> <li class="previous"><? next_posts_link( 'Предыдущие' );?></li> <li class="next"><? previous_posts_link('Следующие'); ?></li> <div class="clear" style="margin-bottom: 10px;"></div> </ul> <?php endif; endif; ?> <?php else : ?> <div class="post"> <h2>К сожалению, в этой категории ещё нет статей. Но будут обязательно!</h2> </div><!-- .post --> <?php endif; ?>
gpl-2.0
pacificpelican/bigLake
header.php
2091
<?php /** * The header for our theme. * * Displays all of the <head> section and everything up till <div id="content"> * * @package greenlake */ ?><!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div class="supermegacontainer" id="containerzero"> <div class="megacontainer row" id="containerport"> <div class="toptiermenu" id="menu4"> <nav id="site-navigation" class="main-navigation" role="navigation"> <button class="menu-toggle" aria-controls="menu" aria-expanded="false">☰</button> <?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?> </nav><!-- #site-navigation --> </div><!-- .menu4 --> <div id="page" class="hfeed site"> <a class="skip-link screen-reader-text" href="#content"><?php _e( 'Skip to content', '_s' ); ?></a> <?php if ( get_header_image() ) : ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"> <img src="<?php header_image(); ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" height="<?php echo esc_attr( get_custom_header()->height ); ?>" alt=""> </a> <?php endif; // End header image check. ?> <div id="mn" class="keycontainer"> <header id="masthead" class="site-header" role="banner"> </header><!-- #masthead --> <div id="nav-holder"> <nav class="top-bar" data-topbar> <ul class="title-area"> <li class="name"> <h1 class="ballingertitle" id="ballingerblogtitle"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> </li> <li class="toggle-topbar menu-icon"> <a href="#"><span></span></a> </li> </ul> <section class="top-bar-section"> <ul class="right"> <?php wp_nav_menu( array( 'theme_location' => 'lower' ) ); ?> </ul> </section> </nav> </div><!-- #nav-holder --> <div id="content" class="site-content">
gpl-2.0
UkuAndla/Wordpress-theme
wp-content/themes/bootstrap2wordpress/wp-content/themes/bootstrap-to-wordpress/page-home.php
14796
<?php /* Template Name: Home Page */ get_header(); ?> <!-- HERO ================================================== --> <section id="hero" data-type="background" data-speed="5"> <article> <div class="container clearfix"> <div class="row"> <div class="col-sm-5"> <img src="assets/img/logo-badge.png" alt="Bootstrap to Wordpress" class="logo"> </div><!-- col --> <div class="col-sm-7 hero-text"> <h1>Bootstrap to WordPress</h1> <p class="lead">Earn An Extra $1k - $5k a Month by Learning to Code Your Very Own Responsive &amp; Custom WordPress Websites with Bootstrap</p> <div id="price-timeline"> <div class="price active"> <h4>Pre-Launch Price <small>Ends soon!</small></h4> <span>$149</span> </div><!-- end price --> <div class="price"> <h4>Launch Price <small>Coming soon!</small></h4> <span>$299</span> </div><!-- end price --> <div class="price"> <h4>Final Price <small>Coming soon!</small></h4> <span>$399</span> </div><!-- end price --> </div><!-- price-timeline --> <p><a class="btn btn-lg btn-danger" href="/" role="button">Enroll now &raquo;</a></p> </div><!-- col --> </div><!-- row --> </div><!-- container --> </article> </section> <!-- OPT IN SECTION ================================================== --> <section id="optin"> <div class="container"> <div class="row"> <div class="col-sm-8"> <p class="lead"><strong>Subscribe to our mailing list.</strong> We'll send something special as a thank you.</p> </div><!-- end col --> <div class="col-sm-4"> <button class="btn btn-success btn-lg btn-block" data-toggle="modal" data-target="#myModal"> Click here to subscribe </button> </div><!-- end col --> </div><!-- row --> </div><!-- container --> </section><!-- optin --> <!-- BOOST YOUR INCOME ================================================== --> <section id="boost-income"> <div class="container"> <div class="section-header"> <img src="assets/img/icon-boost.png" alt="Chart"> <h2>How You Can Boost Your Income</h2> </div><!-- section-header --> <p class="lead">Whether you&rsquo;re a freelance designer, entrepreneur, employee for a company, code hobbyist, or looking for a new career &mdash; this course gives you an immensely valuable skill that will enable you to either:</p> <div class="row"> <div class="col-sm-6"> <h3>Make money on the side</h3> <p>So you can save up for that Hawaiian vacation you&rsquo;ve been wanting, help pay off your debt, your car, your mortgage, or simply just to have bonus cash laying around.</p> </div><!-- end col --> <div class="col-sm-6"> <h3>Create a full-time income</h3> <p>WordPress developers have options. Many developers make a generous living off of creating custom WordPress themes and selling them on websites like ThemeForest. Freelance designers and developers can also take on WordPress projects and make an extra $1,000 - $5,000+ per month.</p> </div><!-- end col --> </div><!-- row --> </div><!-- container --> </section><!-- boost-income --> <!-- WHO BENEFITS ================================================== --> <section id="who-benefits"> <div class="container"> <div class="section-header"> <img src="assets/img/icon-pad.png" alt="Pad and pencil"> <h2>Who Should Take This Course?</h2> </div><!-- section-header --> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <h3>Graphic &amp; Web Designers</h3> <p>Graphic designers are extremely talented, but ask them to code their designs and they'll freeze up! This leaves them with no other choice but to hire a web developer. Any professional graphic designers knows web developers can be expensive.</p> <p>If you&rsquo;re a designer, learning to code your own WordPress websites can change your business entirely! Now, not only are you a great designer, but you're a skillful developer, too! This puts you in a position to <strong>make an extra $1,000 - $5,000 per project.</strong></p> <h3>Entrepreneurs</h3> <p>Entrepreneurs have big dreams, and in many cases, shoestring budgets. In order to survive in the cut-throat world of the Startup company, it&rsquo;s a necessity to have a world-class website. However, world-class websites come with a large price tag.</p> <p>If you can learn how to build a high-quality startup website by yourself, then you&rsquo;ve just saved yourself a lot of cash, <strong>tens of thousands of dollars in many cases.</strong></p> <h3>Employees</h3> <p>Any company knows the education &amp; training of their employees is key to a thriving team.</p> <p>Depending on the type of company you work for, if you understand how to code, and can develop CMS driven websites, that gives you <strong>negotiating power for a better position, or a higher salary.</strong></p> <h3>Code Hobbyists</h3> <p>It&rsquo;s fun to learn challenging new skills. Code hobbyists can add dynamic websites to their arsenal of tools to play with &mdash; you can even <strong>sell WordPress themes and plugins for cash!</strong> The possibilities are truly endless.</p> <h3>People Looking for a New Career</h3> <p>Are you out of work? Looking for a more rewarding job? Desire a career that can allow you to work almost anywhere in the world? Becoming a Web Developer might be the answer for you.</p> <p><strong>Web developers are paid well, anywhere from $33,000 to more than $105,000 per year.</strong> They get to work at amazing companies that are changing the world, or they enjoy the ability to start their own companies, become location-independent and work from home, from coffee shops, in an airplane, on the beach, or wherever they want!</p> </div><!-- end col --> </div><!-- row --> </div><!-- container --> </section><!-- who-benefits --> <!-- COURSE FEATURES ================================================== --> <section id="course-features"> <div class="container"> <div class="section-header"> <img src="assets/img/icon-rocket.png" alt="Rocket"> <h2>Course Features</h2> </div><!-- section-header --> <div class="row"> <div class="col-sm-2"> <i class="ci ci-computer"></i> <h4>Lifetime access to 80+ lectures</h4> </div><!-- end col --> <div class="col-sm-2"> <i class="ci ci-watch"></i> <h4>10+ hours of HD video content</h4> </div><!-- end col --> <div class="col-sm-2"> <i class="ci ci-calendar"></i> <h4>30-day money back guarantee</h4> </div><!-- end col --> <div class="col-sm-2"> <i class="ci ci-community"></i> <h4>Access to a community of like-minded students</h4> </div><!-- end col --> <div class="col-sm-2"> <i class="ci ci-instructor"></i> <h4>Direct access to the instructor</h4> </div><!-- end col --> <div class="col-sm-2"> <i class="ci ci-device"></i> <h4>Accessible content on your mobile devices</h4> </div><!-- end col --> </div><!-- row --> </div><!-- container --> </section><!-- course-features --> <!-- PROJECT FEATURES ================================================== --> <section id="project-features"> <div class="container"> <h2>Final Project Features</h2> <p class="lead">Throughout this entire course, you work towards building an incredibly beautiful website. Want to see the website <strong>you</strong> are going to build? <em>You're looking at it!</em> The website you're using right now is the website you will have built entirely by yourself, by the end of this course.</p> <div class="row"> <div class="col-sm-4"> <img src="assets/img/icon-design.png" alt="Design"> <h3>Sexy &amp; Modern Design</h3> <p>You get to work with a modern, professional quality design &amp; layout.</p> </div><!-- col --> <div class="col-sm-4"> <img src="assets/img/icon-code.png" alt="Code"> <h3>Quality HTML5 &amp; CSS3</h3> <p>You'll learn how hand-craft a stunning website with valid, semantic and beautiful HTML5 &amp; CSS3.</p> </div><!-- col --> <div class="col-sm-4"> <img src="assets/img/icon-cms.png" alt="CMS"> <h3>Easy-to-use CMS</h3> <p>Allow your clients to easily update their websites by converting your static websites to dynamic websites, using WordPress.</p> </div><!-- col --> </div><!-- row --> </div><!-- container --> </section><!-- project-features --> <!-- VIDEO FEATURETTE ================================================== --> <section id="featurette"> <div class="container"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <h2>Watch the Course Introduction</h2> <iframe width="100%" height="415" src="//www.youtube.com/embed/q-mJJsnOHew" frameborder="0" allowfullscreen></iframe> </div><!-- end col --> </div><!-- row --> </div><!-- container --> </section><!-- featurette --> <!-- INSTRUCTOR ================================================== --> <section id="instructor"> <div class="container"> <div class="row"> <div class="col-sm-8 col-md-6"> <div class="row"> <div class="col-lg-8"> <h2>Your Instructor <small>Brad Hussey</small></h2> </div><!-- end col --> <div class="col-lg-4"> <a href="https://twitter.com/bradhussey" class="badge social twitter" target="_blank"><i class="fa fa-twitter"></i></a> <a href="https://facebook.com/bradhussey" class="badge social facebook" target="_blank"><i class="fa fa-facebook"></i></a> <a href="https://plus.google.com/+BradHussey" class="badge social gplus" target="_blank"><i class="fa fa-google-plus"></i></a> </div><!-- end col --> </div><!-- row --> <p class="lead">A highly skilled professional, Brad Hussey is a passionate and experienced web designer, developer, blogger and digital entrepreneur.<p> <p>Hailing from North Of The Wall (Yellowknife, Canada), Brad made the trek to the Wet Coast (Vancouver, Canada) to educate and equip himself with the necessary skills to become a spearhead in his trade of solving problems on the web, crafting design solutions, and speaking in code.</p> <p>Brad's determination and love for what he does has landed him in some pretty interesting places with some neat people. He's had the privilege of working with, and providing solutions for, numerous businesses, big &amp; small, across the Americas.</p> <p>Brad builds custom websites, and provides design solutions for a wide-array of clientele at his company, Brightside Studios. He regularly blogs about passive income, living your life to the fullest, and provides premium quality web design tutorials and courses for tens of thousands of amazing people desiring to master their craft.</p> <hr> <h3>The Numbers <small>They Don't Lie</small></h3> <div class="row"> <div class="col-xs-4"> <div class="num"> <div class="num-content"> 41,000+ <span>students</span> </div><!-- num-content --> </div><!-- num --> </div><!-- end col --> <div class="col-xs-4"> <div class="num"> <div class="num-content"> 568 <span>reviews</span> </div><!-- num-content --> </div><!-- num --> </div><!-- end col --> <div class="col-xs-4"> <div class="num"> <div class="num-content"> 8 <span>courses</span> </div><!-- num-content --> </div><!-- num --> </div><!-- end col --> </div><!-- row --> </div><!-- end col --> </div><!-- row --> </div><!-- container --> </section><!-- instructor --> <!-- TESTIMONIALS ================================================== --> <section id="kudos"> <div class="container"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <h2>What People Are Saying About Brad</h2> <!-- TESTIMONIAL --> <div class="row testimonial"> <div class="col-sm-4"> <img src="assets/img/brennan.jpg" alt="Brennan"> </div><!-- end col --> <div class="col-sm-8"> <blockquote> These videos are well created, concise, fast-paced, easy to follow, and just funny enough to keep you chuckling as you're slamming out lines of code. I've taken 3 courses from this instructor. Whenever I have questions he is right there with a simple solution or a helpful suggestion to keep me going forward with the course work. <cite>&mdash; Brennan, graduate of all of Brad's courses</cite> </blockquote> </div><!-- end col --> </div><!-- row --> <!-- TESTIMONIAL --> <div class="row testimonial"> <div class="col-sm-4"> <img src="assets/img/ben.png" alt="Illustration of a man with a moustache"> </div><!-- end col --> <div class="col-sm-8"> <blockquote> I found Brad to be a great teacher, and a very inspiring person. It's clear he is very passionate about helping designers learn to code, and I look forward to more courses from him! <cite>&mdash; Ben, graduate of Build a Website from Scratch with HTML &amp; CSS</cite> </blockquote> </div><!-- end col --> </div><!-- row --> <!-- TESTIMONIAL --> <div class="row testimonial"> <div class="col-sm-4"> <img src="assets/img/aj.png" alt="Illustration of a man with a beard"> </div><!-- end col --> <div class="col-sm-8"> <blockquote> Brad is amazing and I honestly think he's the best tutor of all the courses I have taken on Udemy. Will definitely be following him in the future. Thanks Brad! <cite>&mdash; AJ, graduate of Code a Responsive Website with Bootstrap 3</cite> </blockquote> </div><!-- end col --> </div><!-- row --> <!-- TESTIMONIAL --> <div class="row testimonial"> <div class="col-sm-4"> <img src="assets/img/ernest.png" alt="Illustration of a man with a goatee"> </div><!-- end col --> <div class="col-sm-8"> <blockquote> Brad is an excellent instructor. His content is super high quality, and you can see the love and care put into every section. The tutorials are the perfect length, and you feel like your doing something right out the gate! I really can't believe this is free. I highly recommend taking advantage of this course. <cite>&mdash; Ernest, graduate of Code Dynamic Websites with PHP</cite> </blockquote> </div><!-- end col --> </div><!-- row --> </div><!-- end col --> </div><!-- row --> </div><!-- container --> </section><!-- kudos --> <?php get_footer(); ?>
gpl-2.0
kunj1988/Magento2
dev/tests/functional/tests/app/Magento/ConfigurableProduct/Test/Block/Product/View/ConfigurableOptions.php
7880
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\ConfigurableProduct\Test\Block\Product\View; use Magento\Catalog\Test\Block\Product\View\CustomOptions; use Magento\ConfigurableProduct\Test\Fixture\ConfigurableProduct; use Magento\Mtf\Client\Locator; use Magento\Mtf\Fixture\FixtureInterface; use Magento\Mtf\Client\Element\SimpleElement; /** * Class ConfigurableOptions * Form of configurable options product */ class ConfigurableOptions extends CustomOptions { /** * Option selector * * @var string */ protected $optionSelector = '//*[./label[contains(.,"%s")]]//select'; /** * Selector for price block. * * @var string */ protected $priceBlock = '.product-info-price .price-box'; /** * Selector for tier prices. * * @var string */ private $tierPricesSelector = '.prices-tier li'; /** * Locator for configurable option element. * * @var string */ private $configurableOptionElement = '#product-options-wrapper > * > .configurable'; /** * Get configurable product options * * @param FixtureInterface|null $product [optional] * @return array * @throws \Exception */ public function getOptions(FixtureInterface $product) { /** @var ConfigurableProduct $product */ $attributesData = $product->hasData('configurable_attributes_data') ? $product->getConfigurableAttributesData()['attributes_data'] : []; $listOptions = $this->getListOptions(); $result = []; foreach ($attributesData as $option) { $title = $option['label']; if (!isset($listOptions[$title])) { throw new \Exception("Can't find option: \"{$title}\""); } /** @var SimpleElement $optionElement */ $optionElement = $listOptions[$title]; $typeMethod = preg_replace('/[^a-zA-Z]/', '', $option['frontend_input']); $getTypeData = 'get' . ucfirst(strtolower($typeMethod)) . 'Data'; $optionData = $this->$getTypeData($optionElement); $optionData['title'] = $title; $optionData['type'] = $option['frontend_input']; $optionData['is_require'] = $optionElement->find($this->required, Locator::SELECTOR_XPATH)->isVisible() ? 'Yes' : 'No'; $result[$title] = $optionData; // Select first attribute option to be able proceed with next attribute $this->selectOption($title, $optionData['options'][0]['title']); } return $result; } /** * Get configurable attributes options prices * * @param FixtureInterface $product * @return array */ public function getOptionsPrices(FixtureInterface $product) { /** @var ConfigurableProduct $product */ $attributesData = []; $productVariations = []; if ($product->hasData('configurable_attributes_data')) { $attributesData = $product->getConfigurableAttributesData()['attributes_data']; $productVariations = $product->getConfigurableAttributesData()['matrix']; } $productVariations = array_keys($productVariations); $result = []; foreach ($productVariations as $variation) { $variationOptions = explode(' ', $variation); //Select all options specified in variation $this->chooseOptions($variationOptions, $attributesData); $result[$variation]['price'] = $this->getOptionPrice(); $tierPrices = $this->getOptionTierPrices(); if (count($tierPrices) > 0) { $result[$variation]['tierPrices'] = $tierPrices; } } return $result; } /** * Get option price * * @return null|string */ protected function getOptionPrice() { $priceBlock = $this->getPriceBlock(); $price = ($priceBlock->isOldPriceVisible()) ? $priceBlock->getOldPrice() : $priceBlock->getPrice(); return $price; } /** * Get tier prices of all variations * * @return array */ private function getOptionTierPrices() { $prices = []; $tierPricesNodes = $this->_rootElement->getElements($this->tierPricesSelector); foreach ($tierPricesNodes as $node) { preg_match('#^[^\d]+(\d+)[^\d]+(\d+(?:(?:,\d+)*)+(?:.\d+)*).*#i', $node->getText(), $matches); $prices[] = [ 'qty' => isset($matches[1]) ? $matches[1] : null, 'price_qty' => isset($matches[2]) ? $matches[2] : null, ]; } return $prices; } /** * Get block price. * * @return \Magento\Catalog\Test\Block\Product\Price */ protected function getPriceBlock() { /** @var \Magento\Catalog\Test\Block\Product\Price $priceBlock */ $priceBlock = $this->blockFactory->create( \Magento\Catalog\Test\Block\Product\Price::class, ['element' => $this->_rootElement->find($this->priceBlock)] ); return $priceBlock; } /** * Select option from the select element. * * @param string $attributeTitle * @param string $optionTitle */ protected function selectOption($attributeTitle, $optionTitle) { $this->_rootElement->find(sprintf($this->optionSelector, $attributeTitle), Locator::SELECTOR_XPATH, 'select') ->setValue($optionTitle); } /** * Choose options of the configurable product * * @param $variationOptions * @param $attributesData * @return void */ protected function chooseOptions($variationOptions, $attributesData) { //Select all options specified in variation foreach ($variationOptions as $variationSelection) { list ($attribute, $option) = explode(':', $variationSelection); $attributeTitle = $attributesData[$attribute]['label']; $optionTitle = $attributesData[$attribute]['options'][$option]['label']; $this->selectOption($attributeTitle, $optionTitle); } } /** * Get present options * * @return array */ public function getPresentOptions() { $options = []; $optionElements = $this->_rootElement->getElements($this->configurableOptionElement); foreach ($optionElements as $optionElement) { $title = $optionElement->find($this->title)->getText(); $options[$title] = $optionElement; } return $options; } /** * Check if the options container is visible or not * * @return bool */ public function isVisible() { return $this->_rootElement->find($this->optionsContext, Locator::SELECTOR_XPATH)->isVisible(); } /** * Select configurable product option by it index * * @param FixtureInterface $product * @param string $variation * @return void */ public function selectConfigurableOption(FixtureInterface $product, $variation) { /** @var ConfigurableProduct $product */ $attributesData = []; $productVariations = []; if ($product->hasData('configurable_attributes_data')) { $attributesData = $product->getConfigurableAttributesData()['attributes_data']; $productVariations = $product->getConfigurableAttributesData()['matrix']; } if (array_key_exists($variation, $productVariations)) { $variationOption = explode(' ', $variation); //Select option specified in variation $this->chooseOptions($variationOption, $attributesData); } } }
gpl-2.0
ljh198275823/500-SteelRoll-Inventory
Source/LJH.Inventory.BLL/WareHouseBLL.cs
2253
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using LJH.Inventory.BusinessModel; using LJH.Inventory.BusinessModel.SearchCondition; using LJH.GeneralLibrary.Core.DAL; using LJH.Inventory.WebApiClient.WebApiClient; using Newtonsoft.Json; namespace LJH.Inventory.WebApiClient { public class WareHouseBLL : BLLBase<string, WareHouse> { #region 构造函数 public WareHouseBLL(string repoUri) : base(repoUri) { } #endregion #region 公共方法 public CommandResult Merge(string source, string des, string opt) { try { if (TokenInfo.Current == null || TokenInfo.Current.NeedNewToken()) GetToken(Operator.Current.ID, Operator.Current.Password); using (var client = new GZipWebClient()) { string url = GetControllerUrl() + "Merge"; client.Encoding = System.Text.Encoding.UTF8; client.Headers.Add("accept", "application/json"); client.Headers.Add("content-type", "application/json;"); client.Headers.Add("Authorization", string.Format("{0} {1}", "Bearer", TokenInfo.Current.Token)); var content = JsonConvert.SerializeObject(new EntityMergeInfo() { Source = source, Des = des, Operator = opt }); var retBytes = client.UploadString(url, "POST", content); return new CommandResult(ResultCode.Successful, string.Empty); } } catch (Exception ex) { if (ex is WebException) { var wex = ex as WebException; var response = wex.Response as System.Net.HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) TokenInfo.Current = null; //如果是未授权,则清掉当前Token } LJH.GeneralLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex); return new CommandResult(ResultCode.Fail, ex.Message); } } #endregion } }
gpl-2.0
Falcury/java-labs
FirstProject/src/tutorials/SimpleOpenGLRenderer.java
1052
package tutorials; import static org.lwjgl.opengl.GL11.*; import org.lwjgl.opengl.*; import org.lwjgl.*; public class SimpleOpenGLRenderer { public SimpleOpenGLRenderer() { try { Display.setDisplayMode(new DisplayMode(640, 480)); Display.setTitle("Hello World!"); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } // Initialization code for OpenGL glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 640, 480, 0, 1, -1); glMatrixMode(GL_MODELVIEW); while (!Display.isCloseRequested()) { // Render glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBegin(GL_LINES); glVertex2i(100, 100); glVertex2i(200, 200); glEnd(); glBegin(GL_QUADS); glVertex2i(300, 300); glVertex2i(350, 300); glVertex2i(350, 350); glVertex2i(300, 350); glEnd(); Display.update(); Display.sync(60); } Display.destroy(); System.exit(0); } public static void main(String[] args) { new SimpleOpenGLRenderer(); } }
gpl-2.0
jonreycas/enjambre
mod/user_support/actions/help/delete.php
620
<?php $guid = (int) get_input("guid", 0); if(!empty($guid) && ($entity = get_entity($guid))){ if(elgg_instanceof($entity, "object", UserSupportHelp::SUBTYPE, "UserSupportHelp")){ if($entity->delete()){ system_message(elgg_echo("user_support:action:help:delete:success")); } else { register_error(elgg_echo("user_support:action:help:delete:error:delete")); } } else { register_error("InvalidClassException:NotValidElggStar", array($guid, "UserSupportHelp")); } } else { register_error(elgg_echo("InvalidParameterException:MissingParameter")); } forward(REFERER);
gpl-2.0
commsy/commsy
src/Model/TimePulseTemplate.php
4005
<?php namespace App\Model; /** * Data class that represents a time pulse template * * Time pulse templates are used to generate the actual time pulse entries * (as labels via cs_time_manager) * @see TimePulsesService */ class TimePulseTemplate { /** * @var integer|null */ private $id; /** * @var integer */ private $contextId; /** * @var string|null */ private $titleGerman; /** * @var string|null */ private $titleEnglish; /** * @var integer */ private $startDay; /** * @var integer */ private $startMonth; /** * @var integer */ private $endDay; /** * @var integer */ private $endMonth; /** * @return int|null */ public function getId(): ?int { return $this->id; } /** * @param int $id */ public function setId(int $id): TimePulseTemplate { $this->id = $id; return $this; } /** * @return int */ public function getContextId(): int { return $this->contextId; } /** * @param int $contextId */ public function setContextId(int $contextId): TimePulseTemplate { $this->contextId = $contextId; return $this; } /** * @return string|null */ public function getTitleGerman(): ?string { return $this->titleGerman; } /** * @param string $titleGerman */ public function setTitleGerman(string $titleGerman): TimePulseTemplate { $this->titleGerman = $titleGerman; return $this; } /** * @return string|null */ public function getTitleEnglish(): ?string { return $this->titleEnglish; } /** * @param string $titleEnglish */ public function setTitleEnglish(string $titleEnglish): TimePulseTemplate { $this->titleEnglish = $titleEnglish; return $this; } /** * @return int|null */ public function getStartDay(): ?int { return $this->startDay; } /** * @param int $startDay */ public function setStartDay(int $startDay): TimePulseTemplate { $this->startDay = $startDay; return $this; } /** * @return int|null */ public function getStartMonth(): ?int { return $this->startMonth; } /** * @param int $startMonth */ public function setStartMonth(int $startMonth): TimePulseTemplate { $this->startMonth = $startMonth; return $this; } /** * @return int|null */ public function getEndDay(): ?int { return $this->endDay; } /** * @param int $endDay */ public function setEndDay(int $endDay): TimePulseTemplate { $this->endDay = $endDay; return $this; } /** * @return int|null */ public function getEndMonth(): ?int { return $this->endMonth; } /** * @param int $endMonth */ public function setEndMonth(int $endMonth): TimePulseTemplate { $this->endMonth = $endMonth; return $this; } /** * Comparison callback for sorting two items first by start month & day, then by end month & day * * @param TimePulseTemplate $a first item * @param TimePulseTemplate $b second item * @return int compare result */ public function compare(TimePulseTemplate $a, TimePulseTemplate $b) { $cmp = $a->getStartMonth() <=> $b->getStartMonth(); if ($cmp !== 0) { return $cmp; } $cmp = $a->getStartDay() <=> $b->getStartDay(); if ($cmp !== 0) { return $cmp; } $cmp = $a->getEndMonth() <=> $b->getEndMonth(); if ($cmp !== 0) { return $cmp; } $cmp = $a->getEndDay() <=> $b->getEndDay(); return $cmp; } }
gpl-2.0
jmescuderojustel/nodejs-tdd-base
source/server/common/errorMessages.js
303
var errorMessages = { emailFieldRequired: "Email field is required", passwordFieldRequired: "Password field is required", emailFieldIsNotCorrect: "Email field is not in a correct format", mongodb:{ duplicatekey: "duplicate key error" } }; module.exports = errorMessages;
gpl-2.0
terminalcloud/apps
others/nightmarejs_example.js
681
var Nightmare = require('nightmare'); var exec = require('child_process').exec; // Receive arguments from the console. var arguments = process.argv.slice(2); console.log("Searching: " + arguments); new Nightmare() .goto('http://yahoo.com') .type('input[title="Search"]', arguments) .click('.searchsubmit') // Wait until the page loads, then take a screenshot. .wait() .screenshot('./scr.jpg') .run(function (err, nightmare) { if (err) return console.log(err); console.log('Displaying results'); // Fork the process to show the screenshot in the IDE browser. exec('/srv/cloudlabs/scripts/display.sh scr.jpg'); console.log('Done!'); });
gpl-2.0
niw/chemr
CHMDocument.rb
11685
#!rake ;# require "uri" class CHMWindowController < NSWindowController ib_outlet :webview ib_outlet :list ib_outlet :tree ib_outlet :drawer ib_outlet :search def windowDidLoad @chm = self.document.chm uri = URI(self.document.fileURL.absoluteString) browse @chm.home @now = @index = @chm.index.to_a.sort_by {|k,v| k} # cache init_hash @list.setDataSource(self) @list.setDoubleAction("clicked_") @list.setAction("clicked_") @tree.setAction("treeclicked_") @search.setDelegate(self) @drawer.open searchActivate(nil) load_condition end KEY_LENGTH = 2 def init_hash @hash = Hash.new{[]} @index.each do |k, v| key = k[0, KEY_LENGTH].downcase @hash[key] <<= [k, v] end end def windowWillClose(sender) save_condition end def load_condition category = NSUserDefaults.standardUserDefaults[:documents] if category config = category[self.document.fileURL.absoluteString] if config self.window.setFrame_display(NSRect.new(*config[:frame].to_ruby), false) size = @drawer.contentSize size.width = config[:drawer_width].to_f @drawer.setContentSize(size) @search.stringValue = config[:search] @search.currentEditor.setSelectedRange(NSRange.new(@search.stringValue.length, 0)) controlTextDidChange(nil) browse(config[:url]) else config = category[:last] if config frame = self.window.frame frame.size = NSSize.new(*config[:frame].to_ruby[2..3]) self.window.setFrame_display(frame, false) size = @drawer.contentSize size.width = config[:drawer_width].to_i @drawer.setContentSize(size) end end end end def save_condition userdef = NSUserDefaults.standardUserDefaults category = userdef[:documents] category = category ? category.to_ruby : {} config = { :frame => self.window.frame.to_a.flatten, :search => @search.stringValue, :drawer_width => @drawer.contentSize.width, :url => @webview.mainFrameURL, } category[self.document.fileURL.absoluteString.to_s] = config category['last'] = config userdef[:documents] = category userdef.synchronize log @webview.mainFrameURL end # OutlineView # * outlineView:child:ofItem: # * outlineView:isItemExpandable: # * outlineView:numberOfChildrenOfItem: # * outlineView:objectValueForTableColumn:byItem: # * outlineView:setObjectValue:forTableColumn:byItem: def outlineView_child_ofItem(ov, index, item) (item || @topics)[:children][index] end def outlineView_isItemExpandable(ov, item) (item || @topics)[:children].length.nonzero? end def outlineView_numberOfChildrenOfItem(ov, item) (item || @topics)[:children].length end def outlineView_objectValueForTableColumn_byItem(ov, column, item) item[:name] end def treeclicked(sender) path = sender.itemAtRow(sender.selectedRow)[:local] log "Tree Clicked: #{path}" browse path unless path.empty? end # Tableview def numberOfRowsInTableView(table) @now.length end def tableView_objectValueForTableColumn_row(table, column, row) @now[row][0] end def tableView_setObjectValue_forTableColumn_row(table, value, column, row) end def tableView_willDisplayCell_forTableColumn_row(table, cell, column, row) end def textShouldBeginEditing(text) true end def textShouldEndEditing(text) true end def acceptsFirstResponder true end # TabView def tabView_willSelectTabViewItem(sender, item) log item.label if item.label == "Tree" # http://subtech.g.hatena.ne.jp/cho45/20071025#c1193355031 # > OutlineView は DataSource に、ノードの値が変わらない限り、 # > 同じ NSString を返すように期待してるようです。 # NSDictionary で保持するように @topics = NSDictionary.dictionaryWithDictionary(@chm.topics || {:children => []}) @tree.setDataSource(self) end end # general def controlTextDidChange(anot) filtering @search.stringValue @list.selectRowIndexes_byExtendingSelection(NSIndexSet.alloc.initWithIndex(0), false) end def controlTextDidEndEditing(anot) log "end #{@now.first.inspect}" end def jumpToCurrent(sender) clicked(sender) end def fast_filter(keyword) keyword = keyword.to_s if /[A-Z]/ === keyword r = /^#{Regexp.escape(keyword)}/ else r = /^#{Regexp.escape(keyword)}/i end key = keyword[0,KEY_LENGTH].downcase if keyword.length.zero? @index else if keyword.length < KEY_LENGTH result = @hash.keys.select{|k| k[0, key.length] == key}.map{|k| @hash[k]}.inject([]){|a,b| a + b} else result = @hash[key].to_a end result.select{|k,v| r === k}.sort_by{|k,v| k.length} end end def filtering(str) @now = fast_filter(str) @search_thread.kill rescue nil if @now.length.zero? @now << ["Loading...", [""]] @search_thread = Thread.start(str) do |str| r = /(#{str.split(//).map {|c| Regexp.escape(c) }.join(").*?(")})/i @now = @index.sort_by {|k,v| # 文字が前のほうに集っているほど高ランクになるように m = r.match(k) !m ? Float::MAX : (0...m.size).map {|i| m.begin(i) }.inject {|p,i| p + i } }.first(30) @list.reloadData end @list.usesAlternatingRowBackgroundColors = false @list.backgroundColor = NSColor.objc_send( :colorWithCalibratedRed, 0.95, :green, 0.90, :blue, 0.90, :alpha, 1 ) else @list.usesAlternatingRowBackgroundColors = true end @list.reloadData end def clicked(sender) if @now[@list.selectedRow] browse @now[@list.selectedRow][1].first end end def browse(path) return unless path case path when /^http:/ r = NSURLRequest.requestWithURL NSURL.URLWithString(path.to_s) log path @webview.mainFrame.loadRequest r else path = "/#{path}" unless path[0] == ?/ h = @webview.stringByEvaluatingJavaScriptFromString("location.pathname+location.hash") unless path == h r = NSURLRequest.requestWithURL CHMInternalURLProtocol.url_for(@chm, path) log r @webview.mainFrame.loadRequest r end end end def completion(sender) return if @search.stringValue.empty? return if @now.empty? common = "" keys = @now.map{|k,v| k.split(//)} if @search.stringValue.to_s =~ /[A-Z]/ keys[0].zip(*keys[1..-1]) do |a| m = a.first if a.all? {|v| m == v} common << m else break end end else keys[0].zip(*keys[1..-1]) do |a| m = a.first.downcase if a.all? {|v| v && (m == v.downcase)} common << m else break end end end if common.length > @search.stringValue.length @search.stringValue = common end end # from menu def searchActivate(sender) log "activate" if @search.window @search.window.makeFirstResponder(@search) end end def nextCandidate(sender) if @list.selectedRow <= @now.size @list.selectRowIndexes_byExtendingSelection(NSIndexSet.alloc.initWithIndex(@list.selectedRow+1), false) @list.scrollRowToVisible(@list.selectedRow) clicked(nil) end end def prevCandidate(sender) if @list.selectedRow > 0 @list.selectRowIndexes_byExtendingSelection(NSIndexSet.alloc.initWithIndex(@list.selectedRow-1), false) @list.scrollRowToVisible(@list.selectedRow) clicked(nil) end end def jumpToHome(sender) browse @chm.home end def performFindPanelAction(sender) log "performFindPanelAction" # @webview.performFindPanelAction(sender) # なぜかうごかない text = @search.stringValue @webview.objc_send( :searchFor, text, :direction, true, :caseSensitive, false, :wrap, false ) end # from MySearchWindow def process_keybinds(e) if NSInputManager.currentInputManager return false unless NSInputManager.currentInputManager.markedRange.empty? end key = key_string(e) log "keyDown (#{e.characters}:#{e.charactersIgnoringModifiers}) -> '#{key}'" keybinds = { "C-j" => self.method(:nextCandidate), "C-n" => self.method(:nextCandidate), "C-k" => self.method(:prevCandidate), "C-p" => self.method(:prevCandidate), "\r" => self.method(:jumpToCurrent), "\t" => self.method(:completion), " " => Proc.new {|s| @webview.stringByEvaluatingJavaScriptFromString <<-JS window.scrollBy(0, 200); JS }, "S- " => Proc.new {|s| @webview.stringByEvaluatingJavaScriptFromString <<-JS window.scrollBy(0, -200); JS }, "C-\r" => Proc.new {|s| @now = (@chm.search(@search.stringValue) || []).map {|title,url| [title, [url]] } @list.reloadData }, "C-u" => Proc.new {|s| @search.stringValue = "" }, "G-[" => Proc.new {|s| @webview.goBack }, "G-]" => Proc.new {|s| @webview.goForward }, "G-=" => Proc.new {|s| @webview.makeTextLarger(self) }, "G--" => Proc.new {|s| @webview.makeTextSmaller(self) }, } (1..9).each do |i| keybinds["G-#{i}"] = Proc.new {|s| dc = NSDocumentController.sharedDocumentController if dc.documents[i-1] log(dc.documents[i-1].windowControllers) dc.documents[i-1].windowControllers.first.showWindow(self) end } end eval(ChemrConfig.instance.keybinds, binding) if keybinds.key?(key) keybinds[key].call(self) true else false end end def key_string(e) key = "" m = e.modifierFlags key << "S-" if m & NSShiftKeyMask > 0 key << "C-" if m & NSControlKeyMask > 0 key << "M-" if m & NSAlternateKeyMask > 0 key << "G-" if m & NSCommandKeyMask > 0 # TODO key << e.charactersIgnoringModifiers.to_s key end # webview policyDelegate # def webView_decidePolicyForNavigationAction_request_frame_decisionListener( # sender, # actionInformation, # request, # frame, # listener # ) # # if CHMInternalURLProtocol.canHandleURL(request.URL) # listener.use # else # NSWorkspace.sharedWorkspace.openURL(request.URL) # listener.ignore # end # end # # def webView_decidePolicyForNewWindowAction_request_newFrameName_decisionListener( # sender, # actionInformation, # request, # frameName, # listener # ) # if CHMInternalURLProtocol.canHandleURL(request.URL) # listener.use # else # NSWorkspace.sharedWorkspace.openURL(request.URL) # listener.ignore # end # end # webview loading delegate def webView_resource_didFinishLoadingFromDataSource(sender, id, datasource) # log "loaded" end # debug def needsPanelToBecomeKey true end end class CHMDocument < NSDocument attr_reader :chm #- (void)makeWindowControllers def makeWindowControllers c = CHMWindowController.alloc.initWithWindowNibName("CHMDocument") self.addWindowController(c) end #- (BOOL)readFromURL:(NSURL *)inAbsoluteURL ofType:(NSString *)inTypeName error:(NSError **)outError def readFromURL_ofType_error(url, type, error) path = Pathname.new(url.path.to_s) if path.directory? @chm = CHMBundle.new(path) else @chm = Chmlib::Chm.new(path.to_s) end true end #- (BOOL)writeToURL:(NSURL *)inAbsoluteURL ofType:(NSString *)inTypeName error:(NSError **)outError def writeToURL_ofType_error(url, type, error) false end #- (void)windowControllerDidLoadWindowNib:(NSWindowController *)windowController def windowControllerDidLoadWindowNib(cont) log "wCDLWN", cont end # def dataRepresentationOfType(aType) # end # # def loadDataRepresentation_ofType(data, aType) # end def displayName dc = NSDocumentController.sharedDocumentController i = dc.documents.index(self) + 1 cmd = [8984].pack("U") "#{cmd}#{i}| #{@chm.title}" end def windowControllerWillLoadNib(cont) log cont end def winwowNibName "CHMDocument" end end class MySearchWindow < NSWindow def sendEvent(e) if e.oc_type == NSKeyDown return if delegate.process_keybinds(e) end super_sendEvent(e) end end
gpl-2.0
rcorral/joomla-platform
libraries/legacy/error/error.php
23601
<?php /** * @package Joomla.Platform * @subpackage Error * * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; // Error Definition: Illegal Options define('JERROR_ILLEGAL_OPTIONS', 1); // Error Definition: Callback does not exist define('JERROR_CALLBACK_NOT_CALLABLE', 2); // Error Definition: Illegal Handler define('JERROR_ILLEGAL_MODE', 3); /** * Error Handling Class * * This class is inspired in design and concept by patErrorManager <http://www.php-tools.net> * * patErrorManager contributors include: * - gERD Schaufelberger <[email protected]> * - Sebastian Mordziol <[email protected]> * - Stephan Schmidt <[email protected]> * * @package Joomla.Platform * @subpackage Error * @since 11.1 * @deprecated 12.1 Use PHP Exception */ abstract class JError { /** * Legacy error handling marker * * @var boolean True to enable legacy error handling using JError, false to use exception handling. This flag * is present to allow an easy transition into exception handling for code written against the * existing JError API in Joomla. * @since 11.1 */ public static $legacy = false; /** * Array of message levels * * @var array * @since 11.1 */ protected static $levels = array(E_NOTICE => 'Notice', E_WARNING => 'Warning', E_ERROR => 'Error'); protected static $handlers = array( E_NOTICE => array('mode' => 'ignore'), E_WARNING => array('mode' => 'ignore'), E_ERROR => array('mode' => 'ignore') ); protected static $stack = array(); /** * Method for retrieving the last exception object in the error stack * * @param boolean $unset True to remove the error from the stack. * * @return mixed Last exception object in the error stack or boolean false if none exist * * @deprecated 12.1 * @since 11.1 */ public static function getError($unset = false) { // Deprecation warning. JLog::add('JError::getError() is deprecated.', JLog::WARNING, 'deprecated'); if (!isset(self::$stack[0])) { return false; } if ($unset) { $error = array_shift(self::$stack); } else { $error = &self::$stack[0]; } return $error; } /** * Method for retrieving the exception stack * * @return array Chronological array of errors that have been stored during script execution * * @deprecated 12.1 * @since 11.1 */ public static function getErrors() { // Deprecation warning. JLog::add('JError::getErrors() is deprecated.', JLog::WARNING, 'deprecated'); return self::$stack; } /** * Method to add non-JError thrown JExceptions to the JError stack for debugging purposes * * @param JException &$e Add an exception to the stack. * * @return void * * @since 11.1 * @deprecated 12.1 */ public static function addToStack(JException &$e) { // Deprecation warning. JLog::add('JError::addToStack() is deprecated.', JLog::WARNING, 'deprecated'); self::$stack[] = &$e; } /** * Create a new JException object given the passed arguments * * @param integer $level The error level - use any of PHP's own error levels for * this: E_ERROR, E_WARNING, E_NOTICE, E_USER_ERROR, * E_USER_WARNING, E_USER_NOTICE. * @param string $code The application-internal error code for this error * @param string $msg The error message, which may also be shown the user if need be. * @param mixed $info Optional: Additional error information (usually only * developer-relevant information that the user should never see, * like a database DSN). * @param boolean $backtrace Add a stack backtrace to the exception. * * @return mixed The JException object * * @since 11.1 * @deprecated 12.1 Use PHP Exception * @see JException */ public static function raise($level, $code, $msg, $info = null, $backtrace = false) { // Deprecation warning. JLog::add('JError::raise() is deprecated.', JLog::WARNING, 'deprecated'); // Build error object $exception = new JException($msg, $code, $level, $info, $backtrace); return self::throwError($exception); } /** * Throw an error * * @param object &$exception An exception to throw. * * @return reference * * @deprecated 12.1 Use PHP Exception * @see JException * @since 11.1 */ public static function throwError(&$exception) { // Deprecation warning. JLog::add('JError::throwError() is deprecated.', JLog::WARNING, 'deprecated'); static $thrown = false; // If thrown is hit again, we've come back to JError in the middle of throwing another JError, so die! if ($thrown) { self::handleEcho($exception, array()); // Inifite loop. jexit(); } $thrown = true; $level = $exception->get('level'); // See what to do with this kind of error $handler = self::getErrorHandling($level); $function = 'handle' . ucfirst($handler['mode']); if (is_callable(array('JError', $function))) { $reference = call_user_func_array(array('JError', $function), array(&$exception, (isset($handler['options'])) ? $handler['options'] : array())); } else { // This is required to prevent a very unhelpful white-screen-of-death jexit( 'JError::raise -> Static method JError::' . $function . ' does not exist.' . ' Contact a developer to debug' . '<br /><strong>Error was</strong> ' . '<br />' . $exception->getMessage() ); } // We don't need to store the error, since JException already does that for us! // Remove loop check $thrown = false; return $reference; } /** * Wrapper method for the raise() method with predefined error level of E_ERROR and backtrace set to true. * * @param string $code The application-internal error code for this error * @param string $msg The error message, which may also be shown the user if need be. * @param mixed $info Optional: Additional error information (usually only * developer-relevant information that the user should * never see, like a database DSN). * * @return object $error The configured JError object * * @deprecated 12.1 Use PHP Exception * @see raise() * @since 11.1 */ public static function raiseError($code, $msg, $info = null) { // Deprecation warning. JLog::add('JError::raiseError() is deprecated.', JLog::WARNING, 'deprecated'); return self::raise(E_ERROR, $code, $msg, $info, true); } /** * Wrapper method for the {@link raise()} method with predefined error level of E_WARNING and * backtrace set to false. * * @param string $code The application-internal error code for this error * @param string $msg The error message, which may also be shown the user if need be. * @param mixed $info Optional: Additional error information (usually only * developer-relevant information that * the user should never see, like a database DSN). * * @return object The configured JError object * * @deprecated 12.1 Use PHP Exception * @see JError * @see raise() * @since 11.1 */ public static function raiseWarning($code, $msg, $info = null) { // Deprecation warning. JLog::add('JError::raiseWarning() is deprecated.', JLog::WARNING, 'deprecated'); return self::raise(E_WARNING, $code, $msg, $info); } /** * Wrapper method for the {@link raise()} method with predefined error * level of E_NOTICE and backtrace set to false. * * @param string $code The application-internal error code for this error * @param string $msg The error message, which may also be shown the user if need be. * @param mixed $info Optional: Additional error information (usually only * developer-relevant information that the user * should never see, like a database DSN). * * @return object The configured JError object * * @deprecated 12.1 Use PHP Exception * @see raise() * @since 11.1 */ public static function raiseNotice($code, $msg, $info = null) { // Deprecation warning. JLog::add('JError::raiseNotice() is deprecated.', JLog::WARNING, 'deprecated'); return self::raise(E_NOTICE, $code, $msg, $info); } /** * Method to get the current error handler settings for a specified error level. * * @param integer $level The error level to retrieve. This can be any of PHP's * own error levels, e.g. E_ALL, E_NOTICE... * * @return array All error handling details * * @deprecated 12.1 Use PHP Exception * @since 11.1 */ public static function getErrorHandling($level) { // Deprecation warning. JLog::add('JError::getErrorHandling() is deprecated.', JLog::WARNING, 'deprecated'); return self::$handlers[$level]; } /** * Method to set the way the JError will handle different error levels. Use this if you want to override the default settings. * * Error handling modes: * - ignore * - echo * - verbose * - die * - message * - log * - callback * * You may also set the error handling for several modes at once using PHP's bit operations. * Examples: * - E_ALL = Set the handling for all levels * - E_ERROR | E_WARNING = Set the handling for errors and warnings * - E_ALL ^ E_ERROR = Set the handling for all levels except errors * * @param integer $level The error level for which to set the error handling * @param string $mode The mode to use for the error handling. * @param mixed $options Optional: Any options needed for the given mode. * * @return mixed True on success or a JException object if failed. * * @deprecated 12.1 Use PHP Exception * @since 11.1 */ public static function setErrorHandling($level, $mode, $options = null) { // Deprecation warning. JLog::add('JError::setErrorHandling() is deprecated.', JLog::WARNING, 'deprecated'); $levels = self::$levels; $function = 'handle' . ucfirst($mode); if (!is_callable(array('JError', $function))) { return self::raiseError(E_ERROR, 'JError:' . JERROR_ILLEGAL_MODE, 'Error Handling mode is not known', 'Mode: ' . $mode . ' is not implemented.'); } foreach ($levels as $eLevel => $eTitle) { if (($level & $eLevel) != $eLevel) { continue; } // Set callback options if ($mode == 'callback') { if (!is_array($options)) { return self::raiseError(E_ERROR, 'JError:' . JERROR_ILLEGAL_OPTIONS, 'Options for callback not valid'); } if (!is_callable($options)) { $tmp = array('GLOBAL'); if (is_array($options)) { $tmp[0] = $options[0]; $tmp[1] = $options[1]; } else { $tmp[1] = $options; } return self::raiseError( E_ERROR, 'JError:' . JERROR_CALLBACK_NOT_CALLABLE, 'Function is not callable', 'Function:' . $tmp[1] . ' scope ' . $tmp[0] . '.' ); } } // Save settings self::$handlers[$eLevel] = array('mode' => $mode); if ($options != null) { self::$handlers[$eLevel]['options'] = $options; } } return true; } /** * Method that attaches the error handler to JError * * @return void * * @deprecated 12.1 * @see set_error_handler * @since 11.1 */ public static function attachHandler() { // Deprecation warning. JLog::add('JError::getErrorHandling() is deprecated.', JLog::WARNING, 'deprecated'); set_error_handler(array('JError', 'customErrorHandler')); } /** * Method that detaches the error handler from JError * * @return void * * @deprecated 12.1 * @see restore_error_handler * @since 11.1 */ public static function detachHandler() { // Deprecation warning. JLog::add('JError::detachHandler() is deprecated.', JLog::WARNING, 'deprecated'); restore_error_handler(); } /** * Method to register a new error level for handling errors * * This allows you to add custom error levels to the built-in * - E_NOTICE * - E_WARNING * - E_NOTICE * * @param integer $level Error level to register * @param string $name Human readable name for the error level * @param string $handler Error handler to set for the new error level [optional] * * @return boolean True on success; false if the level already has been registered * * @deprecated 12.1 * @since 11.1 */ public static function registerErrorLevel($level, $name, $handler = 'ignore') { // Deprecation warning. JLog::add('JError::registerErrorLevel() is deprecated.', JLog::WARNING, 'deprecated'); if (isset(self::$levels[$level])) { return false; } self::$levels[$level] = $name; self::setErrorHandling($level, $handler); return true; } /** * Translate an error level integer to a human readable string * e.g. E_ERROR will be translated to 'Error' * * @param integer $level Error level to translate * * @return mixed Human readable error level name or boolean false if it doesn't exist * * @deprecated 12.1 * @since 11.1 */ public static function translateErrorLevel($level) { // Deprecation warning. JLog::add('JError::translateErrorLevel() is deprecated.', JLog::WARNING, 'deprecated'); if (isset(self::$levels[$level])) { return self::$levels[$level]; } return false; } /** * Ignore error handler * - Ignores the error * * @param object &$error Exception object to handle * @param array $options Handler options * * @return object The exception object * * @deprecated 12.1 * @see raise() * @since 11.1 */ public static function handleIgnore(&$error, $options) { // Deprecation warning. JLog::add('JError::handleIgnore() is deprecated.', JLog::WARNING, 'deprecated'); return $error; } /** * Echo error handler * - Echos the error message to output * * @param object &$error Exception object to handle * @param array $options Handler options * * @return object The exception object * * @deprecated 12.1 * @see raise() * @since 11.1 */ public static function handleEcho(&$error, $options) { // Deprecation warning. JLog::add('JError::handleEcho() is deprecated.', JLog::WARNING, 'deprecated'); $level_human = self::translateErrorLevel($error->get('level')); // If system debug is set, then output some more information. if (defined('JDEBUG')) { $backtrace = $error->getTrace(); $trace = ''; for ($i = count($backtrace) - 1; $i >= 0; $i--) { if (isset($backtrace[$i]['class'])) { $trace .= sprintf("\n%s %s %s()", $backtrace[$i]['class'], $backtrace[$i]['type'], $backtrace[$i]['function']); } else { $trace .= sprintf("\n%s()", $backtrace[$i]['function']); } if (isset($backtrace[$i]['file'])) { $trace .= sprintf(' @ %s:%d', $backtrace[$i]['file'], $backtrace[$i]['line']); } } } if (isset($_SERVER['HTTP_HOST'])) { // Output as html echo "<br /><b>jos-$level_human</b>: " . $error->get('message') . "<br />\n" . (defined('JDEBUG') ? nl2br($trace) : ''); } else { // Output as simple text if (defined('STDERR')) { fwrite(STDERR, "J$level_human: " . $error->get('message') . "\n"); if (defined('JDEBUG')) { fwrite(STDERR, $trace); } } else { echo "J$level_human: " . $error->get('message') . "\n"; if (defined('JDEBUG')) { echo $trace; } } } return $error; } /** * Verbose error handler * - Echos the error message to output as well as related info * * @param object &$error Exception object to handle * @param array $options Handler options * * @return object The exception object * * @deprecated 12.1 * @see raise() * @since 11.1 */ public static function handleVerbose(&$error, $options) { // Deprecation warning. JLog::add('JError::handleVerbose() is deprecated.', JLog::WARNING, 'deprecated'); $level_human = self::translateErrorLevel($error->get('level')); $info = $error->get('info'); if (isset($_SERVER['HTTP_HOST'])) { // Output as html echo "<br /><b>J$level_human</b>: " . $error->get('message') . "<br />\n"; if ($info != null) { echo "&#160;&#160;&#160;" . $info . "<br />\n"; } echo $error->getBacktrace(true); } else { // Output as simple text echo "J$level_human: " . $error->get('message') . "\n"; if ($info != null) { echo "\t" . $info . "\n"; } } return $error; } /** * Die error handler * - Echos the error message to output and then dies * * @param object &$error Exception object to handle * @param array $options Handler options * * @return object The exception object * * @deprecated 12.1 * @see raise() * @since 11.1 */ public static function handleDie(&$error, $options) { // Deprecation warning. JLog::add('JError::handleDie() is deprecated.', JLog::WARNING, 'deprecated'); $level_human = self::translateErrorLevel($error->get('level')); if (isset($_SERVER['HTTP_HOST'])) { // Output as html jexit("<br /><b>J$level_human</b>: " . $error->get('message') . "<br />\n"); } else { // Output as simple text if (defined('STDERR')) { fwrite(STDERR, "J$level_human: " . $error->get('message') . "\n"); jexit(); } else { jexit("J$level_human: " . $error->get('message') . "\n"); } } return $error; } /** * Message error handler * Enqueues the error message into the system queue * * @param object &$error Exception object to handle * @param array $options Handler options * * @return object The exception object * * @deprecated 12.1 * @see raise() * @since 11.1 */ public static function handleMessage(&$error, $options) { // Deprecation warning. JLog::add('JError::hanleMessage() is deprecated.', JLog::WARNING, 'deprecated'); $appl = JFactory::getApplication(); $type = ($error->get('level') == E_NOTICE) ? 'notice' : 'error'; $appl->enqueueMessage($error->get('message'), $type); return $error; } /** * Log error handler * Logs the error message to a system log file * * @param object &$error Exception object to handle * @param array $options Handler options * * @return object The exception object * * @deprecated 12.1 * @see raise() * @since 11.1 */ public static function handleLog(&$error, $options) { // Deprecation warning. JLog::add('JError::handleLog() is deprecated.', JLog::WARNING, 'deprecated'); static $log; if ($log == null) { $fileName = date('Y-m-d') . '.error.log'; $options['format'] = "{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}"; $log = JLog::getInstance($fileName, $options); } $entry['level'] = $error->get('level'); $entry['code'] = $error->get('code'); $entry['message'] = str_replace(array("\r", "\n"), array('', '\\n'), $error->get('message')); $log->addEntry($entry); return $error; } /** * Callback error handler * - Send the error object to a callback method for error handling * * @param object &$error Exception object to handle * @param array $options Handler options * * @return object The exception object * * @deprecated 12.1 * @see raise() * @since 11.1 */ public static function handleCallback(&$error, $options) { // Deprecation warning. JLog::add('JError::handleCallback() is deprecated.', JLog::WARNING, 'deprecated'); return call_user_func($options, $error); } /** * Display a custom error page and exit gracefully * * @param object &$error Exception object * * @return void * * @deprecated 12.1 * @since 11.1 */ public static function customErrorPage(&$error) { // Deprecation warning. JLog::add('JError::customErrorPage() is deprecated.', JLog::WARNING, 'deprecated'); // Initialise variables. $app = JFactory::getApplication(); $document = JDocument::getInstance('error'); if ($document) { $config = JFactory::getConfig(); // Get the current template from the application $template = $app->getTemplate(); // Push the error object into the document $document->setError($error); @ob_end_clean(); $document->setTitle(JText::_('Error') . ': ' . $error->get('code')); $data = $document->render(false, array('template' => $template, 'directory' => JPATH_THEMES, 'debug' => $config->get('debug'))); // Failsafe to get the error displayed. if (empty($data)) { self::handleEcho($error, array()); } else { // Do not allow cache JResponse::allowCache(false); JResponse::setBody($data); echo JResponse::toString(); } } else { // Just echo the error since there is no document // This is a common use case for Command Line Interface applications. self::handleEcho($error, array()); } $app->close(0); } /** * Display a message to the user * * @param integer $level The error level - use any of PHP's own error levels * for this: E_ERROR, E_WARNING, E_NOTICE, E_USER_ERROR, * E_USER_WARNING, E_USER_NOTICE. * @param string $msg Error message, shown to user if need be. * * @return void * * @deprecated 12.1 * @since 11.1 */ public static function customErrorHandler($level, $msg) { // Deprecation warning. JLog::add('JError::customErrorHandler() is deprecated.', JLog::WARNING, 'deprecated'); self::raise($level, '', $msg); } /** * Render the backtrace * * @param integer $error The error * * @return string Contents of the backtrace * * @deprecated 12.1 * @since 11.1 */ public static function renderBacktrace($error) { // Deprecation warning. JLog::add('JError::renderBacktrace() is deprecated.', JLog::WARNING, 'deprecated'); $contents = null; $backtrace = $error->getTrace(); if (is_array($backtrace)) { ob_start(); $j = 1; echo '<table cellpadding="0" cellspacing="0" class="Table">'; echo ' <tr>'; echo ' <td colspan="3" class="TD"><strong>Call stack</strong></td>'; echo ' </tr>'; echo ' <tr>'; echo ' <td class="TD"><strong>#</strong></td>'; echo ' <td class="TD"><strong>Function</strong></td>'; echo ' <td class="TD"><strong>Location</strong></td>'; echo ' </tr>'; for ($i = count($backtrace) - 1; $i >= 0; $i--) { echo ' <tr>'; echo ' <td class="TD">' . $j . '</td>'; if (isset($backtrace[$i]['class'])) { echo ' <td class="TD">' . $backtrace[$i]['class'] . $backtrace[$i]['type'] . $backtrace[$i]['function'] . '()</td>'; } else { echo ' <td class="TD">' . $backtrace[$i]['function'] . '()</td>'; } if (isset($backtrace[$i]['file'])) { echo ' <td class="TD">' . $backtrace[$i]['file'] . ':' . $backtrace[$i]['line'] . '</td>'; } else { echo ' <td class="TD">&#160;</td>'; } echo ' </tr>'; $j++; } echo '</table>'; $contents = ob_get_contents(); ob_end_clean(); } return $contents; } }
gpl-2.0
ARudik/feelpp.cln
src/integer/hash/cl_I_hashcode.cc
875
// cl_I hashcode(). // General includes. #include "base/cl_sysdep.h" // Specification. #include "integer/cl_I.h" // Implementation. namespace cln { unsigned long hashcode (const cl_I& x) { var unsigned long code = 0x814BE3A5; // We walk through all limbs. It may take some time for very large // integers, but it's better than completely ignoring some limbs. if (fixnump(x)) { #if (cl_value_len <= intLsize) code += FN_to_V(x); #elif (cl_word_size==64) code += FN_to_Q(x); code ^= (code >> 32); #endif code &= 0xFFFFFFFF; } else { var const uintD* MSDptr; var uintC len; BN_to_NDS_nocopy(x, MSDptr=,len=,); for (; len > 0; len--) { var uintD c = msprefnext(MSDptr); code = (code << 5) | (code >> 27); // rotate left 5 bits code += (long)c << 16; code ^= (long)c; code &= 0xFFFFFFFF; } } return code; } } // namespace cln
gpl-2.0
wizhippo/TagsBundle
tests/Core/Base/Container/ApiLoader/RepositoryFactory.php
2974
<?php namespace Netgen\TagsBundle\Tests\Core\Base\Container\ApiLoader; use eZ\Publish\Core\Base\Container\ApiLoader\FieldTypeCollectionFactory; use eZ\Publish\Core\Base\Container\ApiLoader\FieldTypeNameableCollectionFactory; use eZ\Publish\Core\Base\Container\ApiLoader\RepositoryFactory as BaseRepositoryFactory; use eZ\Publish\Core\Search\Common\BackgroundIndexer; use eZ\Publish\SPI\Persistence\Handler as PersistenceHandler; use eZ\Publish\SPI\Search\Handler as SearchHandler; class RepositoryFactory extends BaseRepositoryFactory { /** * Collection of fieldTypes, lazy loaded via a closure. * * @var \eZ\Publish\Core\Base\Container\ApiLoader\FieldTypeNameableCollectionFactory */ protected $fieldTypeNameableCollectionFactory; /** * @var string */ private $repositoryClass; public function __construct( $repositoryClass, FieldTypeCollectionFactory $fieldTypeCollectionFactory, FieldTypeNameableCollectionFactory $fieldTypeNameableCollectionFactory ) { $this->repositoryClass = $repositoryClass; $this->fieldTypeCollectionFactory = $fieldTypeCollectionFactory; $this->fieldTypeNameableCollectionFactory = $fieldTypeNameableCollectionFactory; } /** * Builds the main repository, heart of eZ Publish API. * * This always returns the true inner Repository, please depend on ezpublish.api.repository and not this method * directly to make sure you get an instance wrapped inside Signal / Cache / * functionality. * * @param \eZ\Publish\SPI\Persistence\Handler $persistenceHandler * @param \eZ\Publish\SPI\Search\Handler $searchHandler * @param \eZ\Publish\Core\Search\Common\BackgroundIndexer $backgroundIndexer * * @return \eZ\Publish\API\Repository\Repository */ public function buildRepository( PersistenceHandler $persistenceHandler, SearchHandler $searchHandler, BackgroundIndexer $backgroundIndexer ) { $repository = new $this->repositoryClass( $persistenceHandler, $searchHandler, $backgroundIndexer, array( 'fieldType' => $this->fieldTypeCollectionFactory->getFieldTypes(), 'nameableFieldTypes' => $this->fieldTypeNameableCollectionFactory->getNameableFieldTypes(), 'role' => array( 'policyMap' => array('tags' => array('add' => array('Tag' => true))), 'limitationTypes' => $this->roleLimitations, ), 'languages' => $this->container->getParameter('languages'), ) ); /** @var \eZ\Publish\API\Repository\Repository $repository */ $anonymousUser = $repository->getUserService()->loadUser( $this->container->getParameter('anonymous_user_id') ); $repository->setCurrentUser($anonymousUser); return $repository; } }
gpl-2.0
remyoudompheng/surf-1
yaccsrc/Script.cc
22695
/* * surf - visualizing algebraic curves and algebraic surfaces * Copyright (C) 1996-1997 Friedrich-Alexander-Universitaet * Erlangen-Nuernberg * 1997-2000 Johannes Gutenberg-Universitaet Mainz * Authors: Stephan Endrass, Hans Huelf, Ruediger Oertel, * Kai Schneider, Ralf Schmitt, Johannes Beigel * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /************************************************************************** Projectteam 'Qualifizierung und Weiterentwicklung eines Software-Pakets zur Darstellung reell-algebraischer Kurven und Flächen' from Fachhochschule Frankfurt am Main (University of Applied Sciences) Authors: Marcus Scherer, Jonas Heil, Sven Sperner Changes: add support for saving color ps,eps and pdf. add support for saving b/w pdf. add support for automatic file extensions. Date: Wintersemester 2009/2010 Last changed: 2010/01/14 **************************************************************************/ #include <assert.h> #include <stdio.h> #include <iostream> #include <unistd.h> #include "FileWriter.h" #include "TreePolynom.h" #include "Misc.h" #include "Document.h" #include "Script.h" #include "polylexyacc.h" #include "gui_config.h" #include "init_parser.h" #include "DrawFunc.h" #include "TSDrawingArea.h" #include "SurfaceCalc.h" #include "DrawCurve.h" #include "SymbolTable.h" #include "addDefaultSymbols.h" #include "bit_buffer.h" #include "float_buffer.h" #include "dither.h" #include "ps.h" #include "eps.h" #include "xbitmap.h" #include "tiffprint.h" #include "Thread.h" #include "MultiVariatePolynom.h" #include "RootFinder3d.h" #include "GuiThread.h" #include "SymbolTable.h" #include "symtab.h" // #define DEBUG #include "debug.h" using namespace std; TSDrawingArea *Script::display = 0; RgbBuffer *Script::buffer = 0; bit_buffer *Script::bitbuffer = 0; float_buffer *Script::zbuffer = 0; float_buffer *Script::zbuffer3d = 0; SymbolTable *Script::defaultValues = 0; Preview Script::preview; Condition scriptRunning; /* extern "C" */ void symtab_delete_element(symtab *); static void replaceCommand (const char *name, void (*func) (void)) { symtab *st = symtab_find_name (name); if (st) { DMESS("replacing command " << name); symtab_delete_element(st); } else { DMESS("adding new command " << name); } symtab_add_surface_name (name, SYM_COMMAND, 1, (void*)func); } SymbolTable &Script::getDefaultValues() { if (defaultValues == 0) { defaultValues = new SymbolTable(); addDefaultSymbols(*defaultValues); } return *defaultValues; } void *Script::startThread (void *data) { ExecuteScriptStruct *ess = (ExecuteScriptStruct *) data; // int i; // for (i=0; i<4; i++) { // main_mosaic_choice_data[i] = ess->preview[i]; // } preview = ess->preview; beforeScriptExecution(); if (ess->firstPart) { if (internalExecuteScript (ess->firstPart)!=0) { Misc::alert ("internal error."); } } assert(ess->secondPart); ess->parse_result = internalExecuteScript (ess->secondPart, ess->executeUserScriptCommands); ess->error_begin = error_begin_char; ess->error_end = char_number; ess->errorString = yyerrorstring; if (ess->parse_result == 0) { internalExecuteScript (ess->thirdPart); } scriptRunning.lock(); scriptRunning.value = 0; scriptRunning.unlock(); if (ess->doneCallback) { ess->doneCallback (ess); } return 0; } bool Script::isScriptRunning () { if (!scriptRunning.tryLock()) { return true; } else if (scriptRunning.value != 0) { scriptRunning.unlock(); return true; } else { scriptRunning.unlock(); return false; } } bool Script::startScriptExecution(ExecuteScriptStruct *ess) { if (!scriptRunning.tryLock()) { Misc::alert("another script is running."); } else if (scriptRunning.value != 0) { scriptRunning.unlock(); Misc::alert("another script is running."); } else { scriptRunning.value = 1; scriptRunning.unlock(); setDisplay (ess->drawingArea); ess->thread = new Thread(); ess->thread->start (startThread, ess); return true; } return false; } TSDrawingArea *Script::getDisplay() { return display; } void Script::setDisplay (TSDrawingArea *_display) { display = _display; } void Script::beforeScriptExecution() { int i; for( i=0; i<MAIN_SURFACE_AMOUNT_NUM; i++ ) { main_formula_pxyz_data[i].n = 0; } ostrstream str; str << getDefaultValues() << ends; internalExecuteScript (str.str()); // symtab_set_default(); error_begin_char = 0; char_number=0; symtab_delete_user_names( ); *zbuffer = -10.0; } int Script::internalExecuteScript (const char *str, bool runCommands) { if (str==0) return 0; char *main_formula_data = 0; surface_run_commands = runCommands; int parse_result; main_formula_data = (char *) str; set_the_yyinput (main_formula_data, 1, 1 ); scan_labels( main_formula_data ); do { if (Thread::shouldStop()) { parse_result = 0; break; } yyrestart( stdin ); goto_flag = FALSE; parse_result = yyparse( ); if( goto_flag ) { set_the_yyinput( &(main_formula_data[goto_label]), goto_label+1,goto_line ); } } while ( goto_flag ); // if (parse_result) { // Misc::alert("Syntax error in script"); // printf ("%20s\n", str+char_number); // } return parse_result; } void Script::executeScriptFromFile (const char *name) { BEGIN("Script::executeScriptFromFile"); Thread::setDoing ("executing script..."); const char *str = Document::readFile(name); display=0; beforeScriptExecution(); internalExecuteScript(str); delete str; } void Script::init() { BEGIN("Script::init"); // addDefaultSymbols (getDefaultValues()); init_surface_main_commands(); init_surface_main_variables(); draw_func_init_parser(); addNewCommands(); buffer = new RgbBuffer (main_width_data, main_height_data); bitbuffer = new bit_buffer(); bitbuffer->setSize (main_width_data, main_height_data); zbuffer = new float_buffer (main_width_data, main_height_data); *zbuffer = -10.0; // FIXME } void Script::deinit() { delete buffer; delete bitbuffer; delete zbuffer; delete defaultValues; symtab_delete_total(); } void Script::addNewCommands() { replaceCommand("set_size", setSize); replaceCommand("draw_surface", drawSurface); replaceCommand("save_color_image", saveColorImage); replaceCommand("clear_screen", clearScreen); replaceCommand("save_dithered_image", saveDitheredImage); replaceCommand("dither_surface", ditherSurface); replaceCommand("cut_with_surface", cutWithSurface); replaceCommand("resultant", computeResultant); replaceCommand("dither_curve", ditherCurve); replaceCommand("clear_pixmap", clearPixmap); } // // --- Commands // void Script::setSize() { checkVariables(); BEGIN("Script::setSize"); if(buffer->getWidth() != main_width_data || buffer->getHeight() != main_height_data) { buffer->Realloc(main_width_data, main_height_data); if (display) { display->setSize(main_width_data, main_height_data); } buffer->Realloc(main_width_data, main_height_data); } } extern double Y_AXIS_LR_ROTATE; void Script::drawSurface() { checkVariables(); setSize(); BEGIN("Script::drawSurface"); TRACE(main_width_data); TRACE(main_height_data); if (getDisplay()) { getDisplay()->showColorAreaWindow(); getDisplay()->setSize (main_width_data, main_height_data); } Y_AXIS_LR_ROTATE = 0.0; SurfaceCalc sc; sc.setDisplay (getDisplay()); sc.setPreview (getPreview()); getBuffer()->clearTags(); *getZBuffer() = -10.0; sc.surface_calculate(0, 0, main_width_data, main_height_data, *getBuffer()); if( display_numeric.stereo_eye ) { // ----------------- // Draw a 3D image // ----------------- RgbBuffer *intensity = getBuffer(); *Script::getZBuffer3d() = -10.0; Y_AXIS_LR_ROTATE= 2*atan( display_numeric.stereo_eye/ (2*position_numeric.spectator_z) ); intensity->StereoLeft( ); int back =(int)( 0.299*((float)(color_background_data[RED])) +0.587*((float)(color_background_data[GREEN])) +0.114*((float)(color_background_data[BLUE]))); float distf = display_numeric.stereo_z*display_numeric.stereo_eye/ position_numeric.spectator_z; int dist = (int)(distf*((float) (min(main_width_data,main_height_data)))/20.0); SurfaceCalc sc; sc.setDisplay (getDisplay()); sc.setPreview (getPreview()); sc.surface_calculate(0, 0, main_width_data, main_height_data,*getBuffer()); intensity->StereoRight( display_numeric.stereo_red,display_numeric.stereo_green, display_numeric.stereo_blue,dist,back ); if (GuiThread::haveGUI()) getDisplay()->drawRgbBuffer (*intensity); } } void Script::saveColorImage () { if (Thread::shouldStop()) return; checkVariables(); BEGIN("Script::saveColorImage"); Thread::setDoing ("saving color image..."); if (!surface_filename_data) { Misc::alert ("no filename given."); } // const char *name = surface_filename_data; /* Fuck, fuck, fuck...why cant I just have working exceptions with * every every version of gcc I can think of (especially 2.7.x)... * I got internal compiler errors when trying to use them. * I could have just thrown an exception in FileWriter if the file couldnt * be opened. But now Ive got to open the file too early... */ if (color_output_data == color_output_xwd_data) { strcat(surface_filename_data, ".xwd"); } else if (color_output_data == color_output_sun_data) { strcat(surface_filename_data, ".ras"); } else if (color_output_data == color_output_ppm_data) { strcat(surface_filename_data, ".ppm"); } else if (color_output_data == color_output_jpeg_data) { strcat(surface_filename_data, ".jpg"); } else if (color_output_data == color_output_postscript_data) { strcat(surface_filename_data, ".ps"); } else if (color_output_data == color_output_encapsulatedpostscript_data) { strcat(surface_filename_data, ".eps"); } else if (color_output_data == color_output_pdf_data) { strcat(surface_filename_data, ".pdf"); } FileWriter fw (surface_filename_data); FILE *f = fw.openFile(); if (f==0) { Misc::alert ("Could not open file for writing..."); return; } if (color_output_data == color_output_xwd_data) { if (colormap_output_data == colormap_output_true_color_data) { buffer->write_as_xwd24 (fw.openFile()); } else if (colormap_output_data==colormap_output_optimized_data) { buffer->write_as_xwd8_optimized (fw.openFile(), !display_color_dither_data, display_dither_value_data); } else { buffer->write_as_xwd8_netscape (fw.openFile()); } } else if (color_output_data == color_output_sun_data) { if (colormap_output_data == colormap_output_true_color_data) { buffer->write_as_sun24 (fw.openFile()); } else if (colormap_output_data==colormap_output_optimized_data) { buffer->write_as_sun8_optimized (fw.openFile(), !display_color_dither_data, display_dither_value_data); } else { buffer->write_as_sun8_netscape (fw.openFile()); } } else if (color_output_data == color_output_ppm_data) { buffer->write_as_ppm (fw.openFile()); } else if (color_output_data == color_output_jpeg_data) { buffer->write_as_jpeg (fw.openFile()); } else if (color_output_data == color_output_postscript_data) { buffer->write_as_ps (fw.openFile(),print_color_resolution_array_data[print_color_resolution_data]); } else if (color_output_data == color_output_encapsulatedpostscript_data) { buffer->write_as_eps (fw.openFile(),print_color_resolution_array_data[print_color_resolution_data]); } else if (color_output_data == color_output_pdf_data) { buffer->write_as_pdf (fw.openFile(),print_color_resolution_array_data[print_color_resolution_data], fw.getName()); } } void Script::clearScreen() { if (Thread::shouldStop()) return; checkVariables(); // FIXME: clearing visible parts ??? RgbBuffer *intensity = getBuffer(); float_buffer *zbuffer = getZBuffer(); *intensity = (byte)(-print_background_data); if (getDisplay()) { getDisplay()->showColorAreaWindow(); getDisplay()->setSize(main_width_data, main_height_data); getDisplay()->drawSquare(0,0, intensity->getWidth(),0,0,0); getDisplay()->displayRectangle(0,0,intensity->getWidth(), intensity->getHeight()); GuiThread::executeCommands(); } // main_newcolor_init ( ); intensity->NullInit_three( ); *zbuffer = (float)clip_numeric.clip_back; } // should there really be any difference between the two ???? void Script::clearPixmap() { if (Thread::shouldStop()) return; checkVariables(); // FIXME: clearing visible parts ??? RgbBuffer *intensity = getBuffer(); float_buffer *zbuffer = getZBuffer(); *intensity = (byte)(-print_background_data); if (getDisplay()) { getDisplay()->showColorAreaWindow(); // getDisplay()->setSize(main_width_data, main_height_data); getDisplay()->drawSquare(0, 0, intensity->getWidth(),0.0,0,0); // getDisplay()->displayRectangle(0,0,intensity->getWidth(), intensity->getHeight()); // GuiThread::executeCommands(); } // main_newcolor_init ( ); intensity->NullInit_three( ); intensity->clearTags(); *zbuffer = (float)clip_numeric.clip_back; } void Script::saveDitheredImage() { if (Thread::shouldStop()) return; checkVariables(); BEGIN("Script::saveDitheredImage"); Thread::setDoing ("saving dithered image..."); bit_buffer *pixel = getBitBuffer(); switch( print_output_data ) { case 0 : strcat(surface_filename_data, ".ps"); break; case 1 : strcat(surface_filename_data, ".eps"); break; case 2 : strcat(surface_filename_data, ".bmp"); break; case 3 : strcat(surface_filename_data, ".tiff"); break; case 5: strcat(surface_filename_data, ".pgm"); break; case 6: strcat(surface_filename_data, ".pbm"); break; case 7: strcat(surface_filename_data, ".pdf"); break; default : Misc::alert ("dither_file_format out of range. no saving done."); break; } char *name = surface_filename_data; if (name == 0) return; FileWriter fw (name); // see comments above in saveColorImage FILE *f=fw.openFile(); if (f==0) { Misc::alert ("Could not open file for writing..."); return; } switch( print_output_data ) { case 0 : psprint (*pixel, fw.openFile(), print_resolution_array_data[print_resolution_data]); break; case 1 : epsprint (*pixel, fw.openFile(), print_resolution_array_data[print_resolution_data] ); break; case 2 : bitmapprint (*pixel, fw.openFile(), fw.getName()); break; case 3 : if (fw.isWritingToPipe()) { Misc::alert ("Tiff images can only be written to a file."); return; } tiffprint (*pixel, name, print_resolution_array_data[print_resolution_data]); break; case 5: pixel->write_as_pgm (fw.openFile()); break; case 6: pixel->write_as_pbm (fw.openFile()); break; case 7: pdfprint (*pixel, fw.openFile(), print_resolution_array_data[print_resolution_data], fw.getName()); break; default : Misc::alert ("dither_file_format out of range. no saving done."); break; } } void Script::ditherSurface() { if (Thread::shouldStop()) return; checkVariables(); BEGIN("ditherSurface"); Thread::setDoing ("dithering surface..."); float_buffer fbuffer (main_width_data, main_height_data); bit_buffer *pixel = getBitBuffer(); pixel->setSize (main_width_data, main_height_data); // sk :copy gray_values from rgb_buffer to buffer(float_buffer) copy_rgb_to_float(*getBuffer(), fbuffer, print_background_data); if( print_enhance_data == 0) { fbuffer.EnhanceEdges( print_alpha_data ); } if( print_tone_data == 0) { fbuffer.AdjustToneScale(); } if( print_gamma_data != 1.0 && print_gamma_correction_data == 1) { fbuffer.CorrectGamma( 1.0/print_gamma_data ); } dither_pixel_radius_adjust (fbuffer, (float)print_p_radius_data/100.0); if (print_dither_data == print_dither_floyd_steinberg_data) { dither_floyd_steinberg (fbuffer, *pixel, print_random_weights_data, print_weight_data, print_serpentine_raster_data); } else if (print_dither_data == print_dither_jarvis_judis_ninke_data) { dither_jarvis_judis_ninke (fbuffer, *pixel, print_random_weights_data, print_weight_data, print_serpentine_raster_data); } else if (print_dither_data == print_dither_stucki_data) { dither_stucki (fbuffer, *pixel, print_random_weights_data, print_weight_data, print_serpentine_raster_data); } else if (print_dither_data == print_dither_ordered_dither_data) { dither_clustered (fbuffer, *pixel, print_pattern_size_data); } else if (print_dither_data == print_dither_dispersed_dither_data) { dither_dispersed (fbuffer, *pixel, print_pattern_size_data); } else if (print_dither_data == print_dither_dot_diffusion_data) { dither_dot_diffusion (fbuffer, *pixel, print_barons_data); } else if (print_dither_data == print_dither_smooth_dot_diffusion_data) { dither_smooth_dot_diffusion (fbuffer, *pixel, print_barons_data); } else { Misc::alert ("dithering_method out of range. no dithering done."); } if (getDisplay()) { getDisplay()->showDitherAreaWindow(); getDisplay()->drawBitbuffer(*pixel); } } void Script::ditherCurve() { int width = getBuffer()->getWidth(); int height = getBuffer()->getHeight(); std::cerr << width << ", " << height << "\n"; float_buffer buffer (width, height); // copy gray_values from rgb_buffer to float_buffer copy_rgb_to_float_curve(*getBuffer(), buffer); dither_brute (buffer, *getBitBuffer()); if (getDisplay()) { getDisplay()->showDitherAreaWindow(); getDisplay()->setSize(width, height); getDisplay()->drawBitbuffer(*getBitBuffer()); } } void Script::checkVariables() { if (numeric_epsilon_data <= 0) { ostrstream cerr; cerr << "WARNING: epsilon = " << numeric_epsilon_data << " <= 0. Setting epsilon to 0.00001" << endl; numeric_epsilon_data = 0.00001; Misc::alert(cerr); } if (main_width_data <= 0) { ostrstream cerr; cerr << "WARNING: width = " << main_width_data << " <= 0. Setting width to 200" << endl; main_width_data = 200; Misc::alert(cerr); } if (main_height_data <= 0) { ostrstream cerr; cerr << "WARNING: height = " << main_height_data << " <= 0. Setting height to 200" << endl; main_height_data = 200; Misc::alert(cerr); } } #include "resultant.h" void Script::computeResultant() { SurfaceCalc sc; Polyxyz p1 (sc.sf_ds.getFormula (curve_surface_nr_data)->pxyz); CanvasDataStruct cds; cds.initWith_polyxyz (&sym_cutsurfaces[0]); Polyxyz p2 (cds.pxyz); resultant(p1,p2); return; } void Script::cutWithSurface() { setSize(); if (getDisplay()) { getDisplay()->showColorAreaWindow(); getDisplay()->setSize (main_width_data, main_height_data); } WindowGeometry wingeo = WindowGeometry(main_width_data, main_height_data); Y_AXIS_LR_ROTATE = 0.0; checkVariables(); Script::getBuffer()->clearCurveTags( ); Polyx::SetStatics( numeric_epsilon_data, numeric_iterations_data, numeric_root_finder_data, true ); Script::getZBuffer()->Realloc(main_width_data, main_height_data); SurfaceCalc sc; sc.setDisplay(Script::getDisplay()); Polyxyz p1 (sc.sf_ds.getFormula (curve_surface_nr_data)->pxyz); CanvasDataStruct cds; cds.initWith_polyxyz (&sym_cutsurfaces[0]); Polyxyz p2 (cds.pxyz); DrawCurve dc; dc.setCurveWidthAndGamma (curve_width_data, curve_gamma_data); NewClip *clip = NewClip::createSimpleClip (position_perspective_data, clip_data); clip->init(); dc.setClip (clip); dc.setGeometry (wingeo); dc.setPolys (p1,p2); for (int i=1; i<sizeof(sym_cutsurfaces)/sizeof(sym_cutsurfaces[0]); i++) { if (sym_cutsurfaces[i].n > 0) { CanvasDataStruct cds; cds.initWith_polyxyz (&sym_cutsurfaces[i]); Polyxyz p3 (cds.pxyz); dc.setAdditionalPoly (p3); } } dc.setBuffers (Script::getBuffer(), Script::getZBuffer()); dc.drawCurve(0,0,main_width_data, main_height_data, sym_cut_distance); sc.CalculateCurveOnSurface(0,0,main_width_data,main_height_data,*Script::getBuffer(), *Script::getZBuffer() ); delete clip; if( display_numeric.stereo_eye ) { // ----------------- // Draw a 3D image // ----------------- // Script::getBuffer()->clearTags( ); Script::getBuffer()->clearCurveTags( ); Y_AXIS_LR_ROTATE= 2*atan( display_numeric.stereo_eye/ (2*position_numeric.spectator_z) ); //int back =(int)( 0.299*((float)(color_background_data[RED])) // +0.587*((float)(color_background_data[GREEN])) // +0.114*((float)(color_background_data[BLUE]))); //float distf = display_numeric.stereo_z*display_numeric.stereo_eye/ // position_numeric.spectator_z; //int dist = (int)(distf*((float) // (min(main_width_data,main_height_data)))/20.0); SurfaceCalc sc; sc.setDisplay(Script::getDisplay()); Polyxyz p1 (sc.sf_ds.getFormula (curve_surface_nr_data)->pxyz); CanvasDataStruct cds; cds.initWith_polyxyz (&sym_cutsurfaces[0]); Polyxyz p2 (cds.pxyz); DrawCurve dc; dc.setCurveWidthAndGamma (curve_width_data, curve_gamma_data); NewClip *clip = NewClip::createSimpleClip (position_perspective_data, clip_data); clip->init(); dc.setClip (clip); dc.setGeometry (wingeo); dc.setPolys (p1,p2); for (int i=1; i<sizeof(sym_cutsurfaces)/sizeof(sym_cutsurfaces[0]); i++) { if (sym_cutsurfaces[i].n > 0) { CanvasDataStruct cds; cds.initWith_polyxyz (&sym_cutsurfaces[i]); Polyxyz p3 (cds.pxyz); dc.setAdditionalPoly (p3); } } Script::getZBuffer3d()->Realloc(main_width_data, main_height_data); dc.setBuffers (Script::getBuffer(), Script::getZBuffer3d()); dc.drawCurve(0,0,main_width_data, main_height_data,sym_cut_distance ); sc.CalculateCurveOnSurface(0,0,main_width_data,main_height_data,*Script::getBuffer(), *Script::getZBuffer3d() ); delete clip; } }
gpl-2.0
johnpmitsch/katello
test/services/katello/applicability/applicable_content_helper_test.rb
8214
require 'katello_test_helper' module Katello module Service module Applicability class ApplicableContentHelperTest < ActiveSupport::TestCase FIXTURES_FILE = File.join(Katello::Engine.root, "test", "fixtures", "pulp", "rpms.yml") def trigger_evrs(packages) packages.each do |package| epoch = package.epoch package.update(epoch: "999999999") package.update(epoch: epoch) end end def bound_repos(host) host.content_facet.bound_repositories.collect do |repo| repo.library_instance_id.nil? ? repo.id : repo.library_instance_id end end def setup @repo = katello_repositories(:fedora_17_x86_64) @host = FactoryBot.build(:host, :with_content, :with_subscription, :content_view => katello_content_views(:library_dev_view), :lifecycle_environment => katello_environments(:library)) @host.save! @rpm_one = katello_rpms(:one) @rpm_two = katello_rpms(:two) @rpm_three = katello_rpms(:three) @rpm_one_two = katello_rpms(:one_two) @rpm1 = Rpm.where(nvra: "one-1.0-1.el7.x86_64").first @rpm2 = Rpm.where(nvra: "one-1.0-2.el7.x86_64").first @erratum = Erratum.find_by(errata_id: "RHBA-2014-013") @module_stream = ModuleStream.find_by(name: "Ohio") HostAvailableModuleStream.create(host_id: @host.id, available_module_stream_id: AvailableModuleStream.find_by(name: "Ohio").id, status: "enabled") @installed_package1 = InstalledPackage.create(name: @rpm1.name, nvra: @rpm1.nvra, epoch: @rpm1.epoch, version: @rpm1.version, release: @rpm1.release, arch: @rpm1.arch) @installed_package2 = InstalledPackage.create(name: @rpm2.name, nvra: @rpm2.nvra, epoch: @rpm2.epoch, version: @rpm2.version, release: @rpm2.release, arch: @rpm2.arch) trigger_evrs([@rpm_one, @rpm_two, @rpm_three, @rpm1, @rpm2, @installed_package1, @installed_package2]) HostInstalledPackage.create(host_id: @host.id, installed_package_id: @installed_package1.id) HostInstalledPackage.create(host_id: @host.id, installed_package_id: @installed_package2.id) ErratumPackage.create(erratum_id: @erratum.id, nvrea: @rpm2.nvra, name: @rpm2.name, filename: @rpm2.filename) Katello::ContentFacetRepository.create(content_facet_id: @host.content_facet.id, repository_id: @repo.id) Katello::RepositoryErratum.create(erratum_id: @erratum.id, repository_id: @repo.id) end def teardown ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).remove(@rpm2.id) ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).remove(@erratum.id) @rpm_one.update(modular: false) @rpm_one_two.update(modular: false) ModuleStreamRpm.delete_all end def test_rpm_content_ids_returns_something package_content_ids = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).fetch_content_ids assert_equal [@rpm2.id], package_content_ids end def test_rpm_content_ids_returns_nothing @installed_package1.destroy ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).calculate_and_import package_content_ids = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).fetch_content_ids assert_empty package_content_ids end def test_erratum_content_ids_returns_something ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).calculate_and_import erratum_content_ids = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Erratum, bound_repos(@host)).fetch_content_ids assert_equal [@erratum.id], erratum_content_ids end def test_erratum_content_ids_returns_nothing erratum_content_ids = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Erratum, bound_repos(@host)).fetch_content_ids assert_empty erratum_content_ids end def test_applicable_differences_adds_rpm_id rpm_differences = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).applicable_differences assert_equal [[@rpm2.id], []], rpm_differences end def test_applicable_differences_adds_and_removes_no_rpm_ids ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).calculate_and_import rpm_differences = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).applicable_differences assert_equal [[], []], rpm_differences end def test_applicable_differences_removes_rpm_id ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).calculate_and_import @installed_package1.destroy rpm_differences = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).applicable_differences assert_equal [[], [@rpm2.id]], rpm_differences end def test_applicable_differences_adds_erratum_id ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).calculate_and_import erratum_differences = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Erratum, bound_repos(@host)).applicable_differences assert_equal [[@erratum.id], []], erratum_differences end def test_applicable_differences_adds_and_removes_no_errata_ids erratum_differences = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Erratum, bound_repos(@host)).applicable_differences assert_equal [[], []], erratum_differences end def test_applicable_differences_remove_erratum_id ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).calculate_and_import ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Erratum, bound_repos(@host)).calculate_and_import @installed_package1.destroy ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).calculate_and_import erratum_differences = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Erratum, bound_repos(@host)).applicable_differences assert_equal [[], [@erratum.id]], erratum_differences end def test_applicable_differences_adds_rpm_in_module @rpm_one.update(modular: true) @rpm_one_two.update(modular: true) ModuleStreamRpm.create(module_stream_id: @module_stream.id, rpm_id: @rpm_one.id) ModuleStreamRpm.create(module_stream_id: @module_stream.id, rpm_id: @rpm_one_two.id) rpm_differences = ::Katello::Applicability::ApplicableContentHelper.new(@host.content_facet, ::Katello::Rpm, bound_repos(@host)).applicable_differences assert_equal [[@rpm_one_two.id], []], rpm_differences end end end end end
gpl-2.0
opieproject/opie
i18n/pt/qpe.ts
14521
<!DOCTYPE TS><TS> <context> <name>@default</name> <message> <source>Language</source> <translation>Idioma</translation> </message> <message> <source>Time and Date</source> <translation>Hora e Data</translation> </message> <message> <source>Personal Information</source> <translation>Informação Pessoal</translation> </message> <message> <source>DocTab</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AppLauncher</name> <message> <source>Application Problem</source> <translation>Problema na Aplicação</translation> </message> <message> <source>&lt;p&gt;%1 is not responding.&lt;/p&gt;</source> <translation>&lt;p&gt;A aplicação %1 não está a responder.&lt;/p&gt;</translation> </message> <message> <source>&lt;p&gt;Would you like to force the application to exit?&lt;/p&gt;</source> <translation>&lt;p&gt;Quer forçar o término da aplicação?&lt;/p&gt;</translation> </message> <message> <source>&lt;qt&gt;&lt;p&gt;Fast loading has been disabled for this application. Tap and hold the application icon to reenable it.&lt;/qt&gt;</source> <translation>&lt;qt&gt;&lt;p&gt;Foi desactivado o carregamento rápido da aplicação. Toque e espere no icon da aplicação para reactivar.&lt;/qt&gt;</translation> </message> <message> <source>&lt;qt&gt;&lt;b&gt;%1&lt;/b&gt; was terminated due to signal code %2&lt;/qt&gt;</source> <translation>&lt;qt&gt;&lt;b&gt;A aplicação %1 terminou com o código %2.&lt;/qt&gt;</translation> </message> <message> <source>Application terminated</source> <translation>A aplicação terminou</translation> </message> <message> <source>Application not found</source> <translation>Não foi encontrada a aplicação</translation> </message> <message> <source>&lt;qt&gt;Could not locate application &lt;b&gt;%1&lt;/b&gt;&lt;/qt&gt;</source> <translation>&lt;qt&gt;Não foi possível localizar a aplicação &lt;b&gt;%1&lt;/b&gt;&lt;/qt&gt;</translation> </message> <message> <source>Error</source> <translation>Erro</translation> </message> <message> <source>&lt;qt&gt;Could not find the application %1&lt;/qt&gt;</source> <translation>&lt;qt&gt;Não foi possível encontrar a aplicação %1&lt;/qt&gt;</translation> </message> <message> <source>OK</source> <translation>Ok</translation> </message> </context> <context> <name>Calibrate</name> <message> <source>Touch the crosshairs firmly and accurately to calibrate your screen.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DesktopPowerAlerter</name> <message> <source>Battery Status</source> <translation>Estado da Bateria</translation> </message> <message> <source>Low Battery</source> <translation>Bateria Fraca</translation> </message> </context> <context> <name>FirstUse</name> <message> <source>&lt;&lt; Back</source> <translation>&lt;&lt; Voltar</translation> </message> <message> <source>Next &gt;&gt;</source> <translation>Próxima &gt;&gt;</translation> </message> <message> <source>Tap anywhere on the screen to continue.</source> <translation>Toque no ecrâ para continuar.</translation> </message> <message> <source>Please wait, loading %1 settings.</source> <translation>Aguarde um momento. A carregar a configuração de %1.</translation> </message> <message> <source>Please wait...</source> <translation>Aguarde um momento...</translation> </message> <message> <source>Finish</source> <translation>Finalizar</translation> </message> </context> <context> <name>InputMethods</name> <message> <source>Unicode</source> <translation>Unicode</translation> </message> </context> <context> <name>Launcher</name> <message> <source>Launcher</source> <translation>Execução</translation> </message> <message> <source>Documents</source> <translation>Documentos</translation> </message> <message> <source> - Launcher</source> <translation>- Execução</translation> </message> <message> <source>No application</source> <translation>Nenhuma aplicação</translation> </message> <message> <source>&lt;p&gt;No application is defined for this document.&lt;p&gt;Type is %1.</source> <translation>&lt;p&gt;Não há nenhuma aplicação definida para este tipo de documento.&lt;p&gt;O tipo do documento é %1.</translation> </message> <message> <source>OK</source> <translation>Ok</translation> </message> <message> <source>View as text</source> <translation>Ver como texto</translation> </message> </context> <context> <name>LauncherTabWidget</name> <message> <source>&lt;b&gt;Finding Documents...&lt;/b&gt;</source> <translation>&lt;b&gt;A procurar documentos...&lt;/b&gt;</translation> </message> <message> <source>Icon View</source> <translation>Vista em Icones</translation> </message> <message> <source>List View</source> <translation>Vista em Lista</translation> </message> <message> <source>&lt;b&gt;The Documents Tab&lt;p&gt;has been disabled.&lt;p&gt;Use Settings-&gt;Launcher-&gt;DocTab&lt;p&gt;to reenable it.&lt;/b&gt;&lt;/center&gt;</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LauncherView</name> <message> <source>All types</source> <translation>Todos os tipos</translation> </message> <message> <source>Document View</source> <translation>Vista de Documentos</translation> </message> </context> <context> <name>Mediadlg</name> <message> <source>A new storage media detected:</source> <translation type="unfinished"></translation> </message> <message> <source>What should I do with it?</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MediumMountSetting::MediumMountWidget</name> <message> <source>Configure this medium. The changes will go into effect when the application gets closed. To update the Document Tab you need to remove and insert this medium.</source> <translation type="unfinished"></translation> </message> <message> <source>Which media files</source> <translation type="unfinished"></translation> </message> <message> <source>Audio</source> <translation type="unfinished"></translation> </message> <message> <source>All</source> <translation type="unfinished"></translation> </message> <message> <source>Image</source> <translation type="unfinished"></translation> </message> <message> <source>Text</source> <translation type="unfinished"></translation> </message> <message> <source>Video</source> <translation type="unfinished"></translation> </message> <message> <source>Limit search to:</source> <translation type="unfinished"></translation> </message> <message> <source>Add</source> <translation type="unfinished"></translation> </message> <message> <source>Remove</source> <translation type="unfinished"></translation> </message> <message> <source>Scan whole media</source> <translation type="unfinished"></translation> </message> <message> <source>Always check this medium</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QueuedRequestRunner</name> <message> <source>Processing Queued Requests</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SafeMode</name> <message> <source>Safe Mode</source> <translation>Modo Salvaguarda</translation> </message> <message> <source>Plugin Manager...</source> <translation>Gestor de &quot;Plugins&quot;...</translation> </message> <message> <source>Restart Qtopia</source> <translation>Reiniciar Opie</translation> </message> <message> <source>Help...</source> <translation>Ajuda...</translation> </message> </context> <context> <name>Server</name> <message> <source>USB Lock</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ServerApplication</name> <message> <source>Information</source> <translation>Informação</translation> </message> <message> <source>&lt;p&gt;The system date doesn&apos;t seem to be valid. (%1)&lt;/p&gt;&lt;p&gt;Do you want to correct the clock ?&lt;/p&gt;</source> <translation>&lt;p&gt;A data do sistema não parece ser válida. (%1)&lt;/p&gt;&lt;p&gt;Deseja acertar o relógio?&lt;/p&gt;</translation> </message> <message> <source>business card</source> <translation>Cartão de Visita</translation> </message> <message> <source>Safe Mode</source> <translation>Modo de Salvaguarda</translation> </message> <message> <source>&lt;P&gt;A system startup error occurred, and the system is now in Safe Mode. Plugins are not loaded in Safe Mode. You can use the Plugin Manager to disable plugins that cause system error.</source> <translation>&lt;p&gt;Ocorreu um erro ao iniciar. O sistema está agora em modo de salvaguarda e os &quot;plugins&quot; não foram carregados. Poderá usar o gestor de &quot;plugins&quot; para desactivar os que estiverem a causar o erro.</translation> </message> <message> <source>OK</source> <translation>Ok</translation> </message> <message> <source>Plugin Manager...</source> <translation>Gestor de &quot;Plugins&quot;...</translation> </message> <message> <source>Memory Status</source> <translation>Estado da Memória</translation> </message> <message> <source>Memory Low Please save data.</source> <translation>Memória Baixa Grave os seus dados.</translation> </message> <message> <source>Critical Memory Shortage Please end this application immediately.</source> <translation>Memória Criticamente em Baixo Termine esta aplicação imediatamente.</translation> </message> <message> <source>WARNING</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;p&gt;The battery level is critical!&lt;p&gt;Keep power off until AC is restored</source> <translation type="unfinished"></translation> </message> <message> <source>Ok</source> <translation type="unfinished"></translation> </message> <message> <source>The battery is running very low. </source> <translation type="unfinished"></translation> </message> <message> <source>&lt;p&gt;The Back-up battery is very low&lt;p&gt;Please charge the back-up battery</source> <translation type="unfinished"></translation> </message> <message> <source>Suspending...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ShutdownImpl</name> <message> <source>Shutdown...</source> <translation>A desligar...</translation> </message> <message> <source>Terminate</source> <translation>Terminar</translation> </message> <message> <source>Terminate Opie</source> <translation>Terminar o Opie</translation> </message> <message> <source>Reboot</source> <translation>Reiniciar Dispositivo</translation> </message> <message> <source>Restart Opie</source> <translation>Reiniciar Opie</translation> </message> <message> <source>Cancel</source> <translation>Cancelar</translation> </message> <message> <source>Shutdown</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SyncAuthentication</name> <message> <source>Sync Connection</source> <translation>Ligação de Sincronização</translation> </message> <message> <source>Deny</source> <translation>Rejeitar</translation> </message> <message> <source>&lt;p&gt;An unrecognized system is requesting access to this device.&lt;p&gt;If you have just initiated a Sync for the first time, this is normal.</source> <translation>&lt;p&gt;Um sistema sem autorização está a requisitar acesso a este dispositivo.&lt;p&gt;É normal se for o primeiro acesso para sincronização.</translation> </message> <message> <source>Allow</source> <translation>Permitir</translation> </message> <message> <source>&lt;qt&gt;&lt;p&gt;An unauthorized system is requesting access to this device.&lt;p&gt;You chose IntelliSync so you may allow or deny this connection.&lt;/qt&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;p&gt;An unauthorized system is requesting access to this device with no password.&lt;p&gt;If you are using a version of Qtopia Desktop older than 1.5.1, please upgrade.&lt;p&gt;Otherwise, check that the correct sync application is selected in the Security settings, and ensure that a sync password has been set in the sync application if it allows one.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SyncDialog</name> <message> <source>Abort</source> <translation>Abortar</translation> </message> <message> <source>Syncing:</source> <translation>A Sincronizar:</translation> </message> </context> </TS>
gpl-2.0
JackDavidson/TabMaker
src/wolf/games/mobile/tabmaker/TabEditorActivity.java
19586
package wolf.games.mobile.tabmaker; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.andengine.engine.camera.Camera; import org.andengine.engine.options.EngineOptions; import org.andengine.engine.options.ScreenOrientation; import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.andengine.entity.modifier.MoveModifier; import org.andengine.entity.primitive.Line; import org.andengine.entity.primitive.Rectangle; import org.andengine.entity.scene.IOnSceneTouchListener; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.Background; import org.andengine.entity.text.Text; import org.andengine.entity.util.FPSLogger; import org.andengine.input.touch.TouchEvent; import org.andengine.input.touch.controller.MultiTouch; import org.andengine.opengl.font.Font; import org.andengine.opengl.font.FontFactory; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.ui.activity.SimpleBaseGameActivity; import org.andengine.util.modifier.ease.EaseExponentialOut; import wolf.games.mobile.shared.SharedData; import wolf.games.mobile.shared.TabPortion; import wolf.games.mobile.tabmaker.menu.MenuManager; import wolf.games.mobile.tools.ManageableSprite; import wolf.games.mobile.tools.SDCardWriter; import wolf.games.mobile.tools.SplitableString; import wolf.games.mobile.tools.SpriteManager; import wolf.games.mobile.tools.XMLParser; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Environment; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class TabEditorActivity extends SimpleBaseGameActivity implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== protected static final int width = 1280; static int height; protected static final float pxLetterWidth = 50; protected static final float pxselectorLetterHeight = 80; protected float pxStringHeight = 90; private static float PxPerLetter; private int stringPositionOffset = 0; // =========================================================== // Fields // =========================================================== private static int numTimesAppOpened = 0; protected SpriteManager mSpriteManager; private BitmapTextureAtlas mBitmapTextureAtlas; ManageableSprite modifyBackgroundSprite; protected Scene mScene; protected int yVal = 0; protected int numStrings = 13; private int numTextLines = 2; public TabObject mTabObject; TabPortion mTabPortion; protected ManageableSprite bigMove; protected Font mFont; Text elapsedText = null; Map<Integer, Text> stringsMap; private Map<Integer, Text> selectorTextMap; protected Map<Integer, Character> selectorMap; protected int activeString = 0; public int activeChar = 0; private int totalSelectables = 16; protected boolean selectorOpen = false; MenuManager mMenuManager; protected EditorActions currentAction = EditorActions.EDITOR; Line line = null; Rectangle mRectangle = null; Rectangle mSelectionRectangle = null; ManageableSprite selectionCircle; int selectionStartChar = 0; int selectionEndChar = 0; private Line charSelectLine = null; float lastDownX; float lastDownY; float pxToNativeRatio; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // we need a map to contain each string. @Override public EngineOptions onCreateEngineOptions() { SharedData.textClipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE); // Toast.makeText(this, "Touch the screen to add objects.", // Toast.LENGTH_LONG).show(); Display display = getWindowManager().getDefaultDisplay(); int tempWidth = display.getWidth(); // deprecated pxToNativeRatio = tempWidth / width; height = display.getHeight(); // deprecated float heightWidthRatio = (float) height / (float) tempWidth; height = (int) ((Integer) width * heightWidthRatio); final Camera camera = new Camera(0, 0, width, height); EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(width, height), camera); engineOptions.getAudioOptions().setNeedsMusic(true); engineOptions.getTouchOptions().setNeedsMultiTouch(true); if (MultiTouch.isSupported(this)) { if (MultiTouch.isSupportedDistinct(this)) { } else { Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\n(You just can't do some extra stuff)", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)", Toast.LENGTH_LONG).show(); } // showNotification(); return engineOptions; } @Override public void onCreateResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 64, 128, TextureOptions.BILINEAR); this.mBitmapTextureAtlas.load(); stringsMap = new HashMap<Integer, Text>(10); selectorTextMap = new HashMap<Integer, Text>(10); selectorMap = new HashMap<Integer, Character>(20); } @Override public Scene onCreateScene() { // currentAction.registerOnChangeListener(runnable) this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new Background(.9f, .9f, .9f)); this.mScene.setOnSceneTouchListener(this); mSpriteManager = new SpriteManager(this, mScene); // mPuck = mSpriteManager.makeNewSprite("KnockItArt/puck.png", 0, 0, 0, // yVal);//134x134, at 0, 0 // yVal += 134; mSelectionRectangle = new Rectangle(-200, 0, 0, 0, this.getVertexBufferObjectManager()); mSelectionRectangle.setColor(0, 1, 0); mScene.attachChild(mSelectionRectangle); mFont = FontFactory.create(getFontManager(), getTextureManager(), 500, 500, TextureOptions.BILINEAR, Typeface.create(Typeface.MONOSPACE, Typeface.BOLD), SharedData.defaultFontSize); mFont.load(); /* * this initializes a new tabObject, with a bunch of dashes. Actual loading is handled by * MenuManager.seleftafiletoload() */ mTabObject = new TabObject(numStrings, numTextLines, 50); // elapsedText = new Text(0, 25, mFont, defaultString, 300, // getVertexBufferObjectManager()); mFont.prepareLetters('1', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'i', 'm', 'e', 'L', ' ', 'm', 't', ':', '.'); // mScene.attachChild(elapsedText); modifyBackgroundSprite = mSpriteManager.makeNewSprite("TabMakerArt/selectionBackground.jpg", -100, 360, 200, 0) .attachChild();// ,200 x 200 at 0, 135 selectionCircle = mSpriteManager.makeNewSprite("TabMakerArt/greenCircle.png", -100, 360, 0, yVal).attachChild();// ,200 // x // 200 // at // 0, // 135 selectionCircle.getSprite().setZIndex(1); // modifyBackgroundSprite.getSprite().setAlpha(.8f); modifyBackgroundSprite.getSprite().setZIndex(1); yVal += 90; // yVal += 720; mRectangle = new Rectangle(-200, 0, pxLetterWidth - 5, pxselectorLetterHeight + 4, this.getVertexBufferObjectManager()); mRectangle.setColor(0, 1, 0); mRectangle.setZIndex(1); mScene.attachChild(mRectangle); setupSelector(); mMenuManager = new MenuManager(mSpriteManager); if (SharedData.makingNewTab) { /* * String defaultNumStrings = * PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("DefaultNumStr", "6"); try{ * this.mTabObject.numStrings = Integer.valueOf(defaultNumStrings); }catch (Exception e){ Log.e("stuff", * e.toString()); this.mTabObject.numStrings = 6; } setUpStringTexts(); */ askForFileName(); } else { // setUpStringTexts(); // if(there is a recovery file with the error flag set, etc..) XMLParser mXMLParser = new XMLParser(); mXMLParser.loadFile(Environment.getExternalStorageDirectory() + "/TabMaker/MyTabs/Recover.xml"); if (mXMLParser.getElement("ExitFailedFlag") != null) { TabParser mTabParser = new TabParser(Environment.getExternalStorageDirectory() + "/TabMaker/MyTabs", "Recover.xml", 6); /* then pass the tab parser (which now has the parsed tab) to the tabObject */ mTabObject.loadFromParser(mTabParser); /* yeah, i know this is a really bad way to give the file name to everything */ SharedData.activeFile = mXMLParser.getElement("name"); /* allocate the memory needed for display of the strings */ setUpStringTexts(); updateStrings(); } else { mMenuManager.selectFileToLoad(6, mTabObject, this); } } return this.mScene; } protected void askForFileName() { mMenuManager.enterFileName(this, mTabObject); } public void setUpStringTexts() { int lengthOfStrings = this.mTabObject.getStringLength(); int lengthOfTexts = 0; if (lengthOfStrings <= 1000) { lengthOfTexts = 2000; } else { lengthOfTexts = lengthOfStrings + 500; } numStrings = this.mTabObject.getNumStrings(); String defaultString = "-"; for (int i = 0; i < 50; i++) { defaultString += "-"; } pxStringHeight = (height - 120) / numStrings; if (this.mTabObject.numStrings >= 9) { stringPositionOffset = -20; } for (int i = 0; i < numStrings; i++) { final Text stringText = new Text(0, pxStringHeight * i + stringPositionOffset, mFont, defaultString, lengthOfTexts, getVertexBufferObjectManager()); stringsMap.put(i, stringText); mScene.attachChild(stringText); } mScene.sortChildren(); updateStrings(); } public void addSpace(int spaceAmount) { mTabObject.insertSpace(activeChar, spaceAmount); updateStrings(); } protected int getSelectedCharHeight(final TouchEvent pSceneTouchEvent) { int selectedCharacter; int selectedCharHeight = 0; for (int i = 0; i < (totalSelectables / 2); i++) { if (pSceneTouchEvent.getY() > i * pxselectorLetterHeight) selectedCharHeight = i; else break; } if (pSceneTouchEvent.getX() < modifyBackgroundSprite.getPositionX()) { // going to be one of the even ones selectedCharacter = selectedCharHeight * 2; } else { // going to be one of the odd ones selectedCharacter = selectedCharHeight * 2 + 1; } return selectedCharacter; } protected void findSelectedChar(final TouchEvent pSceneTouchEvent) { for (int i = 0; i < mTabObject.getNumStrings(); i++) { if (pSceneTouchEvent.getY() > i * pxStringHeight) activeString = i; else break; } for (int i = 0; i < mTabObject.getStringLength(); i++) { if (pSceneTouchEvent.getX() - stringsMap.get(0).getX() > i * pxLetterWidth) activeChar = i; else break; } } private void setupSelector() { selectorMap.put(0, '0'); selectorMap.put(1, '1'); selectorMap.put(2, '2'); selectorMap.put(3, '3'); selectorMap.put(4, '4'); selectorMap.put(5, '5'); selectorMap.put(6, '6'); selectorMap.put(7, '7'); selectorMap.put(8, '8'); selectorMap.put(9, '9'); selectorMap.put(10, '?'); selectorMap.put(11, 'h'); selectorMap.put(12, 'p'); selectorMap.put(13, 'x'); selectorMap.put(14, '-'); selectorMap.put(15, 'b'); for (int i = 0; i < totalSelectables; i++) { if (i % 2 == 0) { // number is even final Text stringText = new Text(-200, (pxselectorLetterHeight * i) / 2, mFont, selectorMap.get(i).toString(), 1, getVertexBufferObjectManager()); selectorTextMap.put(i, stringText); mScene.attachChild(stringText); stringText.setZIndex(1); } else { // number is odd final Text stringText = new Text(-200, (pxselectorLetterHeight * (i - 1)) / 2, mFont, selectorMap.get(i).toString(), 1, getVertexBufferObjectManager()); selectorTextMap.put(i, stringText); mScene.attachChild(stringText); stringText.setZIndex(1); } } } void moveSelectorOnScreen() { modifyBackgroundSprite.setPosition(activeChar * pxLetterWidth + stringsMap.get(0).getX() + (pxLetterWidth / 2), 360); selectorOpen = true; for (int i = 0; i < totalSelectables; i++) { Text selectorMapObject = selectorTextMap.get(i); if (i % 2 == 0) { // number is even selectorMapObject.setPosition( activeChar * pxLetterWidth + stringsMap.get(0).getX() - (pxLetterWidth / 2), selectorMapObject.getY()); } else { selectorMapObject.setPosition( activeChar * pxLetterWidth + stringsMap.get(0).getX() + (pxLetterWidth / 2), selectorMapObject.getY()); } } selectionCircle.setPosition((activeChar + 1) * pxLetterWidth + stringsMap.get(0).getX() - (pxLetterWidth / 2), activeString * pxStringHeight + 50 + stringPositionOffset); bigMove.setPosition(bigMove.getPositionX(), height + 500); } public void moveSelectorOffScreen() { selectorOpen = false; modifyBackgroundSprite.setPosition(-200, 320); for (int i = 0; i < totalSelectables; i++) { Text selectorMapObject = selectorTextMap.get(i); selectorMapObject.setPosition(-200, selectorMapObject.getY()); } mRectangle.setPosition(-200, 0); selectionCircle.setPosition(-200, 0); if (!PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getBoolean("DisableBigMove", true)) bigMove.setPosition(bigMove.getPositionX(), height - 270); // considerShowingAdd(); } @Override public void onResumeGame() { Log.e("", "resume"); SharedData.exitingCorrectly = false; Log.e("", "" + SharedData.exitingCorrectly); super.onResumeGame(); /* * if (new File(this.getFilesDir() + "/" + "userInfo").isFile()) { SplitableString testSplitable = new * SplitableString( SDCardWriter.readFile(this.getFilesDir() + "/" + "userInfo")); * testSplitable.SplitByChar(','); numTimesAppOpened = Integer.valueOf(testSplitable.getStringAt(1)); * numTimesAppOpened++; if (numTimesAppOpened == 7 || numTimesAppOpened == 20) { //Intent pleaseRateScreen = new * Intent("wolf.games.mobile.KnockIt.PLEASERATESCREEN"); //startActivityForResult(pleaseRateScreen, 0); } } * SDCardWriter.writeFile(this.getFilesDir() + "/", "userInfo", numTimesAppOpened + ","); */ SharedData.canWriteRecoveryFile = false; } public void updateStrings() { for (int i = 0; i < mTabObject.getNumStrings(); i++) { updateString(i); } } public void updateString(int stringNum) { stringsMap.get(stringNum).setText(mTabObject.getString(stringNum)); } @Override public void onPauseGame() { if (handler != null) { handler.removeCallbacksAndMessages(null); } Log.e("", "pause"); Log.e("", "" + SharedData.exitingCorrectly); if (SharedData.canWriteRecoveryFile) SDCardWriter.writeFile(Environment.getExternalStorageDirectory() + "/TabMaker/MyTabs/", "Recover.xml", mTabObject.exportToString(true)); super.onPauseGame(); } @Override public void onWindowFocusChanged(boolean pHasWindowFocus) { super.onWindowFocusChanged(pHasWindowFocus); } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if (pKeyCode == KeyEvent.KEYCODE_BACK && pEvent.getAction() == KeyEvent.ACTION_DOWN) { SharedData.exitingCorrectly = true; SharedData.canWriteRecoveryFile = true; Log.e("", "back"); Log.e("", "" + SharedData.exitingCorrectly); /* otherwise, returns super down below */ if (mTabObject.canUndo() || mTabObject.canRedo()) { mMenuManager.onQuit(this); return true; } } if (pKeyCode == KeyEvent.KEYCODE_MENU) { if (pEvent.getAction() == KeyEvent.ACTION_DOWN) { } return true; } return super.onKeyDown(pKeyCode, pEvent); } @Override public void onDestroy() { // cancelNotification(32); super.onDestroy(); } TabEditorActivity getContext() { return this; } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { return false; } /** * strategy: split the entire tab */ String exportToString() { String entireFile = ""; Map<Integer, String> eachLine = new HashMap<Integer, String>(100); int offset = 0; int length = 0; String topString = mTabObject.getString(0); /* loop through each character of the top most string */ for (int x = 0; x <= topString.length(); x++) { /* if we are on the last character */ if (x == topString.length()) { /* then go through each string */ for (int i = 0; i < mTabObject.getNumStrings(); i++) { /* Now, lets add the strings to the map (the pieces from the last 'N' to the end) */ if (!mTabObject.getString(i).substring(offset, offset + length).equals("")) { eachLine.put(eachLine.size(), mTabObject.getString(i).substring(offset, offset + length)); Log.e("stuff", "added line: " + mTabObject.getString(i).substring(offset, offset + length)); } } /* if we encounted an 'N' then its time to split into another piece */ } else if (topString.charAt(x) == 'N') { /* loop through each string */ for (int i = 0; i < mTabObject.getNumStrings(); i++) { /* and add everything from the last 'N' up to this 'N' to the map */ eachLine.put(eachLine.size(), mTabObject.getString(i).substring(offset, offset + length)); Log.e("stuff", "added line: " + mTabObject.getString(i).substring(offset, offset + length)); } /* update the position of the last encountered 'N' */ offset = length + offset + 1; length = 0; } else { /* otherwise, keep counting up the length of the string since the last 'N' */ length++; } } for (int i = 0; i < eachLine.size(); i++) { /* start with the denotation on each line. grab the appropriate denotation, and add it */ int stringNumber = (i) % mTabObject.getNumStrings(); entireFile += mTabObject.getDenotation(stringNumber); Log.v("Editor Activity Exporting", "string: " + stringNumber + " denotation will be: " + mTabObject.getDenotation(stringNumber)); entireFile += eachLine.get(i) + '\n'; Log.v("stuff", "line is : " + eachLine.get(i)); if (stringNumber == (mTabObject.getNumStrings() - 1)) { /* add a new line after writing each piece of the tab (after you write #strings from eachLine) */ entireFile += '\n'; Log.e("stuff", "added line:" + '\n'); } } return entireFile; } private Handler handler = null; public void setUpDefaultStringDenotation() { mTabObject.setDefaultDenotation(); } protected EditorActions getCA() { return currentAction; } protected void setCA(EditorActions currentAction) { this.currentAction = currentAction; } }
gpl-2.0
vividoranje/drupal6
sites/all/modules/civicrm/CRM/Admin/Form/Setting/Mapping.php
3391
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 3.1 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2010 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007. | | | | CiviCRM is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the GNU Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2010 * $Id$ * */ require_once 'CRM/Admin/Form/Setting.php'; /** * This class generates form components for Mapping and Geocoding * */ class CRM_Admin_Form_Setting_Mapping extends CRM_Admin_Form_Setting { /** * Function to build the form * * @return None * @access public */ public function buildQuickForm( ) { CRM_Utils_System::setTitle(ts('Settings - Mapping Provider')); $map = CRM_Core_SelectValues::mapProvider(); $this->addElement('select','mapProvider', ts('Map Provider'),array('' => '- select -') + $map); $this->add('text','mapAPIKey', ts('Provider Key'), null); parent::buildQuickForm(); } /** * global form rule * * @param array $fields the input form values * @return true if no errors, else array of errors * @access public * @static */ static function formRule(&$fields) { $errors = array(); if ( ! CRM_Utils_System::checkPHPVersion( 5, false ) ) { $errors['_qf_default'] = ts( 'Mapping features require PHP version 5 or greater' ); } if ( !$fields['mapAPIKey'] && $fields['mapProvider'] != '' ) { $errors['mapAPIKey'] = "API key is a required field"; } return $errors; } /** * This function is used to add the rules (mainly global rules) for form. * All local rules are added near the element * * @param null * * @return void * @access public */ function addRules( ) { $this->addFormRule( array( 'CRM_Admin_Form_Setting_Mapping', 'formRule' ) ); } }
gpl-2.0
QuielSimoes/minhagrana
app/src/Controller/LogsController.php
3235
<?php namespace App\Controller; use App\Controller\AppController; /** * Logs Controller * * @property \App\Model\Table\LogsTable $Logs */ class LogsController extends AppController { /** * Index method * * @return void */ public function index() { $this->paginate = [ 'contain' => ['Users'] ]; $this->set('logs', $this->paginate($this->Logs)); $this->set('_serialize', ['logs']); } /** * View method * * @param string|null $id Log id. * @return void * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function view($id = null) { $log = $this->Logs->get($id, [ 'contain' => ['Users'] ]); $this->set('log', $log); $this->set('_serialize', ['log']); } /** * Add method * * @return void Redirects on successful add, renders view otherwise. */ public function add() { $log = $this->Logs->newEntity(); if ($this->request->is('post')) { $log = $this->Logs->patchEntity($log, $this->request->data); if ($this->Logs->save($log)) { $this->Flash->success(__('The log has been saved.')); return $this->redirect(['action' => 'index']); } else { $this->Flash->error(__('The log could not be saved. Please, try again.')); } } $users = $this->Logs->Users->find('list', ['limit' => 200]); $this->set(compact('log', 'users')); $this->set('_serialize', ['log']); } /** * Edit method * * @param string|null $id Log id. * @return void Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $log = $this->Logs->get($id, [ 'contain' => [] ]); if ($this->request->is(['patch', 'post', 'put'])) { $log = $this->Logs->patchEntity($log, $this->request->data); if ($this->Logs->save($log)) { $this->Flash->success(__('The log has been saved.')); return $this->redirect(['action' => 'index']); } else { $this->Flash->error(__('The log could not be saved. Please, try again.')); } } $users = $this->Logs->Users->find('list', ['limit' => 200]); $this->set(compact('log', 'users')); $this->set('_serialize', ['log']); } /** * Delete method * * @param string|null $id Log id. * @return void Redirects to index. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $log = $this->Logs->get($id); if ($this->Logs->delete($log)) { $this->Flash->success(__('The log has been deleted.')); } else { $this->Flash->error(__('The log could not be deleted. Please, try again.')); } return $this->redirect(['action' => 'index']); } }
gpl-2.0
chisimba/modules
webpresent/classes/dbwebpresentdownloadcounter_class_inc.php
13870
<?php // security check - must be included in all scripts if (! /** * Description for $GLOBALS * @global unknown $GLOBALS['kewl_entry_point_run'] * @name $kewl_entry_point_run */ $GLOBALS['kewl_entry_point_run']){ die("You cannot view this page directly"); } class dbwebpresentdownloadcounter extends dbtable { /** * Method to construct the class. */ public function init() { parent::init('tbl_webpresent_downloads'); $this->loadClass('link', 'htmlelements'); } public function addDownload($id, $type) { return $this->insert(array( 'fileid' => $id, 'filetype' => $type, 'datedownloaded' => date('Y-m-d'), 'datetimedownloaded' => strftime('%Y-%m-%d %H:%M:%S', mktime()), )); } /** * Method to the the most downloaded presentations for today * @return array List of Most downloaded Presentations for Today */ public function getMostDownloadedToday() { $sql = 'SELECT count(tbl_webpresent_downloads.id) as viewcount, tbl_webpresent_files.* FROM tbl_webpresent_downloads, tbl_webpresent_files WHERE (tbl_webpresent_files.id = tbl_webpresent_downloads.fileid AND datedownloaded=\''.date('Y-m-d').'\' ) GROUP BY tbl_webpresent_downloads.fileid Order by viewcount desc limit 5'; return $this->getArray($sql); } /** * Method to the the most downloaded presentations this week * @return array List of Most downloaded Presentations this week */ public function getMostDownloadedThisWeek() { // Get Start Of Week $startOfWeek = date('Y-m-d'); // Load Date Time Class $objDateTime = $this->getObject('dateandtime', 'utilities'); // Get Previous Day 7 times for ($i=1; $i <= 7; $i++) { $startOfWeek = $objDateTime->previousDay($startOfWeek ); } // SQL $sql = 'SELECT count(tbl_webpresent_downloads.id) as viewcount, tbl_webpresent_files.* FROM tbl_webpresent_downloads, tbl_webpresent_files WHERE (tbl_webpresent_files.id = tbl_webpresent_downloads.fileid AND datedownloaded > \''.$startOfWeek .'\' ) GROUP BY tbl_webpresent_downloads.fileid Order by viewcount desc limit 5'; return $this->getArray($sql); } /** * Method to the the most downloaded presentations of all time * @return array List of Most downloaded Presentations of all time */ public function getMostDownloadedAllTime() { $sql = 'SELECT count(tbl_webpresent_downloads.id) as viewcount, tbl_webpresent_files.* FROM tbl_webpresent_downloads, tbl_webpresent_files WHERE (tbl_webpresent_files.id = tbl_webpresent_downloads.fileid ) GROUP BY tbl_webpresent_downloads.fileid Order by viewcount DESC LIMIT 5'; return $this->getArray($sql); } /** * Method to return stats requested via an Ajax Call * @param string $period Period of Data Requested * @return string Data in Formatted Table */ public function getAjaxData($period) { switch ($period) { case 'alltime': $files = $this->getMostDownloadedAllTime(); break; case 'week': $files = $this->getMostDownloadedThisWeek(); break; default: $files = $this->getMostDownloadedToday(); break; } return $this->prepContent($files, $period); } /** * Method to get the Most Downloaded Presentations in non formated way * * It is designed to present showing "No records today" * * This is displayed on the home page. It first checks if there was * any downloads for today, if not try week, if not show all time stats * * @return string */ public function getMostDownloadedList() { // Check Today $files = $this->getMostDownloadedToday(); if (count($files) > 0) { return $this->prepContent2($files, 'today'); } $files = $this->getMostDownloadedThisWeek(); if (count($files) > 0) { return $this->prepContent2($files, 'week'); } return $this->getMostDownloadedAllTimeList(); } /** * Method to get the Most Downloaded Presentations as a table * * It is designed to present showing "No records today" * * This is displayed on the home page. It first checks if there was * any downloads for today, if not try week, if not show all time stats * * @return string */ public function getMostDownloadedTable() { // Check Today $files = $this->getMostDownloadedToday(); if (count($files) > 0) { return $this->getDataFormatted($files, 'today'); } $files = $this->getMostDownloadedThisWeek(); if (count($files) > 0) { return $this->getDataFormatted($files, 'week'); } return $this->getMostDownloadedAllTimeTable(); } /** * Method to get the Most Downloaded Today Presentations as a table * @return string */ public function getMostDownloadedTodayTable() { $files = $this->getMostDownloadedToday(); return $this->getDataFormatted($files, 'today'); } /** * Method to get the Most Downloaded This Week Presentations as a table * @return string */ public function getMostDownloadedThisWeekTable() { $files = $this->getMostDownloadedThisWeek(); return $this->getDataFormatted($files, 'week'); } /** * Method to get the Most Viewed All Time Presentations in second format * @return string */ public function getMostDownloadedAllTimeList() { $files = $this->getMostDownloadedAllTime(); return $this->prepContent2($files, 'alltime'); } /** * Method to get the Most Viewed All Time Presentations as a table * @return string */ public function getMostDownloadedAllTimeTable() { $files = $this->getMostDownloadedAllTime(); return $this->getDataFormatted($files, 'alltime'); } /** * Method to get to take data and a period and convert them into a featurebox for display * @param array $data List of presentations * @param string $period Period Data is for * @return string */ private function getDataFormatted($data, $period) { $objFeatureBox = $this->newObject('featurebox', 'navigation'); $objIcon = $this->newObject('geticon', 'htmlelements'); $objIcon->setIcon('loading_circles'); $content = '<div id="loading_downloads" style="display:none;">'.$objIcon->show().'</div><div id="data_downloads">'.$this->prepContent($data, $period).'</div>'; return $objFeatureBox->show('Most Downloaded', $content); } /** * Method to get to take data and a period and convert them into a table for display, as well as links to other periods * @param array $data List of presentations * @param string $period Period Data is for * @return string */ private function prepContent($data, $period) { // Create Empty String $content = ''; // Convert to Lowercase, just in case $period = strtolower($period); // Create Array of Permitted Types $permittedTypes = array ('today', 'week', 'alltime'); // Check that period is valid, if not, show daily result if (!in_array($period, $permittedTypes)) { $period = 'today'; } // If no results, return notice to user if (count($data) == 0) { switch ($period) { case 'alltime': $str = 'No presentations have been downloaded on this site'; break; case 'week': $str = 'No presentations have been downloaded this week'; break; default: $str = 'No presentations have been downloaded today'; break; } $content = '<div class="noRecordsMessage">'.$str.'</div>'; // Else start creating a table } else { $table = $this->newObject('htmltable', 'htmlelements'); $counter = 0; $this->loadClass('link', 'htmlelements'); foreach ($data as $file) { $counter++; $table->startRow(); $table->addCell($counter.'.', 20, 'top', 'center'); $fileLink = new link ($this->uri(array('action'=>'view', 'id'=>$file['id']))); $fileLink->link = $file['title']; $table->addCell($fileLink->show()); $table->addCell($file['viewcount'], 20, 'top', 'center'); $table->endRow(); } $content = $table->show(); } // Start creating links to other periods, current period should not be a link // Today if ($period == 'today') { $allLinks[] = 'Today'; } else { $link = new link('javascript:getData(\'downloads\', \'today\');'); $link->link = 'Today'; $allLinks[] = $link->show(); } // This Week if ($period == 'week') { $allLinks[] = 'This Week'; } else { $link = new link('javascript:getData(\'downloads\', \'week\');'); $link->link = 'This Week'; $allLinks[] = $link->show(); } // All Time if ($period == 'alltime') { $allLinks[] = 'All Time'; } else { $link = new link('javascript:getData(\'downloads\', \'alltime\');'); $link->link = 'All Time'; $allLinks[] = $link->show(); } if (count($allLinks) > 0) { $linksContent = '<p align="right">'; $divider = ''; foreach ($allLinks as $link) { $linksContent .= $divider.$link; $divider = ' | '; } $linksContent .= '</p>'; } // Return Links + Content return $linksContent.$content; } /** * Method to get to take data and a period and convert them into a list for display, as well as links to other periods * @param array $data List of presentations * @param string $period Period Data is for * @return string */ private function prepContent2($data, $period) { // Create Empty String $content = ''; // Convert to Lowercase, just in case $period = strtolower($period); // Create Array of Permitted Types $permittedTypes = array ('today', 'week', 'alltime'); // Check that period is valid, if not, show daily result if (!in_array($period, $permittedTypes)) { $period = 'today'; } // If no results, return notice to user if (count($data) == 0) { switch ($period) { case 'alltime': $str = 'No presentations have been downloaded on this site'; break; case 'week': $str = 'No presentations have been downloaded this week'; break; default: $str = 'No presentations have been downloaded today'; break; } $content = '<div class="noRecordsMessage">'.$str.'</div>'; // Else start creating a table } else { $table = $this->newObject('htmltable', 'htmlelements'); $counter = 0; $this->loadClass('link', 'htmlelements'); $filetitle='Presentation'; $result=''; foreach ($data as $file) { if ($file['title'] == '') { $filetitle.='-'.$counter; } else { $filetitle = $file['title']; } $counter++; $result.="<li>"; $fileLink = new link ($this->uri(array('action'=>'view', 'id'=>$file['id']))); $fileLink->link = $filetitle; $result.=$fileLink->show(); $result.=' - '.$file['viewcount']; $result.="</li>"; } $content = $result; } // Start creating links to other periods, current period should not be a link // Today if ($period == 'today') { $allLinks[] = 'Today'; } else { $link = new link('javascript:getData(\'views\', \'today\');'); $link->link = 'Today'; $allLinks[] = $link->show(); } // This Week if ($period == 'week') { $allLinks[] = 'This Week'; } else { $link = new link('javascript:getData(\'views\', \'week\');'); $link->link = 'This Week'; $allLinks[] = $link->show(); } // All Time if ($period == 'alltime') { $allLinks[] = 'All Time'; } else { $link = new link('javascript:getData(\'views\', \'alltime\');'); $link->link = 'All Time'; $allLinks[] = $link->show(); } if (count($allLinks) > 0) { $linksContent = '<p align="right">'; $divider = ''; foreach ($allLinks as $link) { $linksContent .= $divider.$link; $divider = ' | '; } $linksContent .= '</p>'; } // Return Links + Content return $content; } } ?>
gpl-2.0
gsergiu/music-genres
music-genre/src/main/java/eu/europeana/dbpedia/connection/DBPediaClientConfiguration.java
2076
package eu.europeana.dbpedia.connection; import java.io.InputStream; import java.util.Properties; import eu.europeana.api.client.exception.TechnicalRuntimeException; public class DBPediaClientConfiguration{ private static final String MUSIC_GENRES_PROPERTIES_FILE = "/music-genre.properties"; private static final String PROP_DBPEDIA_API_KEY = "dbpedia.apiKey"; /** * Accessor method for the singleton * * @return */ public static synchronized DBPediaClientConfiguration getInstance() { singleton = new DBPediaClientConfiguration(); singleton.loadProperties(); return singleton; } //local attributes private static Properties properties = null; private static DBPediaClientConfiguration singleton; /** * Hide the default constructor */ DBPediaClientConfiguration() { } /** * Laizy loading of configuration properties */ public synchronized void loadProperties() { try { properties = new Properties(); InputStream resourceAsStream = getClass().getResourceAsStream( MUSIC_GENRES_PROPERTIES_FILE); if (resourceAsStream != null) getProperties().load(resourceAsStream); else throw new TechnicalRuntimeException( "No properties file found in classpath! " + MUSIC_GENRES_PROPERTIES_FILE); } catch (Exception e) { throw new TechnicalRuntimeException( "Cannot read configuration file: " + MUSIC_GENRES_PROPERTIES_FILE, e); } } /** * provides access to the configuration properties. It is not recommended to * use the properties directly, but the * * @return */ Properties getProperties() { return properties; } /** * * @return the name of the file storing the client configuration */ String getConfigurationFile() { return MUSIC_GENRES_PROPERTIES_FILE; } /** * This method provides access to the API key defined in the configuration * file * @see PROP_FREEBASE_API_KEY * * @return */ public String getApiKey() { return getProperties().getProperty(PROP_DBPEDIA_API_KEY); } }
gpl-2.0
jade58/Songs-Lyrics-Script
js/custom.js
12341
/* * * Custom JavaScript * Product: KnowledgeBase WordPress Theme * * */ jQuery(document).ready(function(e) { $ = jQuery; /*-----------------------------------------------------------------------------------*/ /* Menu Dropdown Control /*-----------------------------------------------------------------------------------*/ $('.main-nav li').hover(function(){ $(this).children('ul').stop(true, true).slideDown(500); },function(){ $(this).children('ul').stop(true, true).slideUp(500); }); $('.sub-menu li').click(function(){ window.location = $(this).children('a').attr('href'); }); /*-----------------------------------------------------------------------------------*/ /* CSS Fixes /*-----------------------------------------------------------------------------------*/ //$(".flickr-photos > a:nth-child(3n+3) img").css("marginLeft","0px"); /*-----------------------------------------------------------------------------------*/ /* Apply Class on search form widget inputs /*-----------------------------------------------------------------------------------*/ $("#searchform #s").addClass("span3 search-query"); $("#searchform #searchsubmit").addClass("btn"); /*-----------------------------------------------------------------------------------*/ /* Page's Nav /*-----------------------------------------------------------------------------------*/ $(".pages-nav a").addClass("btn"); /*-----------------------------------------------------------------------------------*/ /* Tags Cloud /*-----------------------------------------------------------------------------------*/ $('.tagcloud a').removeAttr('style').addClass('btn btn-mini'); /*-----------------------------------------------------------------------------------*/ /* Flickr Feed /*-----------------------------------------------------------------------------------*/ $('#basicuse').jflickrfeed({ limit: 9, qstrings: { id: '52617155@N08' }, itemTemplate: '<a href="{{image_b}}" title="{{title}}" data-rel="prettyPhoto[flickrg]"><img src="{{image_s}}" alt="{{title}}" /></a>' }, function(data){ $('a[data-rel]').each(function() { $(this).attr('rel', $(this).data('rel')); }); $("a[rel^='prettyPhoto']").prettyPhoto({ deeplinking: false, social_tools: false, overlay_gallery: false }); }); /*-----------------------------------------------------------------------------------*/ /* Pretty Photo Lightbox /*-----------------------------------------------------------------------------------*/ if( jQuery().prettyPhoto ) { $(".pretty-photo").prettyPhoto({ deeplinking: false, social_tools: false }); $('a[data-rel]').each(function() { $(this).attr('rel', $(this).data('rel')); }); $("a[rel^='prettyPhoto']").prettyPhoto({ deeplinking: false, social_tools: false }); } /* ---------------------------------------------------- */ /* Accordion /* ---------------------------------------------------- */ $(function() { $('.accordion dt').click(function(){ $(this).siblings('dt').removeClass('current'); $(this).addClass('current').next('dd').slideDown(500).siblings('dd').slideUp(500); }); }); /* ---------------------------------------------------- */ /* Toggle /* ---------------------------------------------------- */ $(function() { $('dl.toggle dt').click(function(){ if($(this).hasClass('current')){ $(this).removeClass('current').next('dd').slideUp(500); } else{ $(this).addClass('current').next('dd').slideDown(500); } }); }); /*-----------------------------------------------------------------------------------*/ /* Scroll to Top /*-----------------------------------------------------------------------------------*/ $(function() { $(window).scroll(function () { if(!$('body').hasClass('probably-mobile')) { if ($(this).scrollTop() > 50) { $('a#scroll-top').fadeIn(); } else { $('a#scroll-top').fadeOut(); } } else { $('a#scroll-top').fadeOut(); } }); $('a#scroll-top').on('click', function(){ if(!$('body').hasClass('probably-mobile')) { $('html, body').animate({scrollTop:0}, 'slow' ); return false; } }); }); // Twitter Fetcher Target Code twitterFetcher.fetch('353252568291504128', 'twitter_update_list', 2, true, false, true, dateFormatter, false); /* ---------------------------------------------------- */ /* Tabs /* ---------------------------------------------------- */ $(function(){ var $tabsNav = $('.tabs-nav'), $tabsNavLis = $tabsNav.children('li'); $tabsNav.each(function(){ var $this = $(this); $this.next().children('.tab-content').stop(true,true).hide() .first().show(); $this.children('li').first().addClass('active').stop(true,true).show(); }); $tabsNavLis.on('click', function(e) { var $this = $(this); $this.siblings().removeClass('active').end() .addClass('active'); var idx = $this.parent().children().index($this); $this.parent().next().children('.tab-content').stop(true,true).hide().eq(idx).fadeIn(); e.preventDefault(); }); }); /* ---------------------------------------------------- */ /* Responsive Tables by ZURB /* Foundation v2.1.4 http://foundation.zurb.com /* ---------------------------------------------------- */ var switched = false; var updateTables = function() { if (($(window).width() < 767) && !switched ){ switched = true; $("table.responsive").each(function(i, element) { splitTable($(element)); }); return true; } else if (switched && ($(window).width() > 767)) { switched = false; $("table.responsive").each(function(i, element) { unsplitTable($(element)); }); } }; $(window).load(updateTables); $(window).bind("resize", updateTables); function splitTable(original) { original.wrap("<div class='table-wrapper' />"); var copy = original.clone(); copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none"); copy.removeClass("responsive"); original.closest(".table-wrapper").append(copy); copy.wrap("<div class='pinned' />"); original.wrap("<div class='scrollable' />"); } function unsplitTable(original) { original.closest(".table-wrapper").find(".pinned").remove(); original.unwrap(); original.unwrap(); } /* ---------------------------------------------------- */ /* Like Button JS /* ---------------------------------------------------- */ $('#like-it-form .like-it').click(function(){ var likeButton = $(this); var likeHtml = likeButton.html(); var likeNum = parseInt(likeHtml, 10); likeNum++; likeButton.html(likeNum); // $('#like-it-form').ajaxSubmit(options); }); /*-----------------------------------------------------------------------------------*/ /* FAQs /*-----------------------------------------------------------------------------------*/ $('.faq-item').not('.faq-item.active').find('.faq-answer').slideUp('slow'); $('.faq-item').first().addClass('active').find('.faq-answer').slideDown('slow'); $('.faq-question, .faq-icon').click(function(e){ e.preventDefault(); var $this = $(this); var $parent = $this.parent('.faq-item'); if( $parent.hasClass('active') ) { $parent.removeClass('active').find('.faq-answer').slideUp('slow'); } else { $parent.addClass('active').find('.faq-answer').slideDown('slow'); } }); /*-----------------------------------------------------------------------------------*/ /* Contact Form 7 /*-----------------------------------------------------------------------------------*/ $('.wpcf7-textarea').addClass('span6'); $('.wpcf7-submit').addClass('btn'); /*-----------------------------------------------------------------------------------*/ /* Search Form Validation /*-----------------------------------------------------------------------------------*/ $('#search-form').validate({ errorLabelContainer: $("#search-error-container") }); /*-----------------------------------------------------------------------------------*/ /* Responsive Nav /*-----------------------------------------------------------------------------------*/ var $mainNav = $('.main-nav > div').children('ul'); var optionsList = '<option value="" selected>Go to...</option>'; $mainNav.find('li').each(function() { var $this = $(this), $anchor = $this.children('a'), depth = $this.parents('ul').length - 1, indent = ''; if( depth ) { while( depth > 0 ) { indent += ' - '; depth--; } } optionsList += '<option value="' + $anchor.attr('href') + '">' + indent + ' ' + $anchor.text() + '</option>'; }).end(); $('.main-nav > div').after('<select class="responsive-nav">' + optionsList + '</select>'); $('.responsive-nav').on('change', function() { window.location = $(this).val(); }); /*----------------------------------------------------------------------------------*/ /* Contact Form AJAX validation and submition /* Validation Plugin : http://bassistance.de/jquery-plugins/jquery-plugin-validation/ /* Form Ajax Plugin : http://www.malsup.com/jquery/form/ /*---------------------------------------------------------------------------------- */ if(jQuery().validate && jQuery().ajaxSubmit) { // Contact Form Handling var contact_options = { target: '#message-sent', beforeSubmit: function(){ $('#contact-loader').fadeIn('fast'); $('#message-sent').fadeOut('fast'); }, success: function(){ $('#contact-loader').fadeOut('fast'); $('#message-sent').fadeIn('fast'); $('#contact-form').resetForm(); } }; $('#contact-form').validate({ errorLabelContainer: $("div.error-container"), submitHandler: function(form) { $(form).ajaxSubmit(contact_options); } }); } /*-----------------------------------------------------------------------------------*/ /* Live Search /*-----------------------------------------------------------------------------------*/ if(jQuery().liveSearch){ jQuery('#s').liveSearch({url: 'search.php?livesearch=used&s='}); } });
gpl-2.0
DarrenTsung/duckproject
KnightsOfTheFarm/Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Popups.cs
2164
using UnityEngine; using Vexe.Editor.Helpers; using Vexe.Runtime.Extensions; namespace Vexe.Editor.GUIs { public abstract partial class BaseGUI { public int Popup(int selectedIndex, string[] displayedOptions) { return Popup(selectedIndex, displayedOptions, null); } public int Popup(int selectedIndex, string[] displayedOptions, Layout option) { return Popup(string.Empty, selectedIndex, displayedOptions, option); } public int Popup(string text, int selectedIndex, string[] displayedOptions) { return Popup(text, selectedIndex, displayedOptions, null); } public int Popup(string text, int selectedIndex, string[] displayedOptions, Layout option) { return Popup(text, selectedIndex, displayedOptions, GUIStyles.Popup, option); } public abstract int Popup(string text, int selectedIndex, string[] displayedOptions, GUIStyle style, Layout option); public string Tag(string tag) { return Tag(string.Empty, tag); } public string Tag(string content, string tag) { return Tag(content, tag, null); } public string Tag(string content, string tag, Layout layout) { return Tag(GetContent(content), tag, GUIStyles.Popup, layout); } public abstract string Tag(GUIContent content, string tag, GUIStyle style, Layout layout); public string TextFieldDropDown(string text, string[] displayedOptions) { return TextFieldDropDown(text, displayedOptions, null); } public string TextFieldDropDown(string text, string[] displayedOptions, Layout option) { return TextFieldDropDown(string.Empty, text, displayedOptions, option); } public string TextFieldDropDown(string label, string text, string[] displayedOptions) { return TextFieldDropDown(label, text, displayedOptions, null); } public string TextFieldDropDown(string label, string text, string[] displayedOptions, Layout option) { return TextFieldDropDown(GetContent(label), text, displayedOptions, option); } public abstract string TextFieldDropDown(GUIContent label, string text, string[] displayedOptions, Layout option); } }
gpl-2.0
stevenc99/Serious-Engine
Sources/Engine/Models/RenderModel.cpp
27928
/* Copyright (c) 2002-2012 Croteam Ltd. 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 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 "Engine/StdH.h" #include <Engine/Base/Statistics_Internal.h> #include <Engine/Math/Float.h> #include <Engine/Models/ModelObject.h> #include <Engine/Models/ModelData.h> #include <Engine/Models/ModelProfile.h> #include <Engine/Models/RenderModel.h> #include <Engine/Models/Model_internal.h> #include <Engine/Graphics/DrawPort.h> #include <Engine/Base/Lists.inl> #include <Engine/Math/OBBox.h> #include <Engine/Base/ListIterator.inl> #include <Engine/Templates/StaticStackArray.cpp> CStaticStackArray<CRenderModel> _armRenderModels; // texture used for simple model shadows CTextureObject _toSimpleModelShadow; static INDEX _iRenderingType = 0; // 0=none, 1=view, 2=mask extern FLOAT mdl_fLODMul; extern FLOAT mdl_fLODAdd; extern INDEX mdl_iShadowQuality; CAnyProjection3D _aprProjection; CDrawPort *_pdp = NULL; UBYTE *_pubMask = NULL; SLONG _slMaskWidth = 0; SLONG _slMaskHeight = 0; static enum FPUPrecisionType _fpuOldPrecision; // begin/end model rendering to screen void BeginModelRenderingView( CAnyProjection3D &prProjection, CDrawPort *pdp) { ASSERT( _iRenderingType==0 && _pdp==NULL); // set 3D projection _iRenderingType = 1; _pdp = pdp; prProjection->ObjectPlacementL() = CPlacement3D(FLOAT3D(0,0,0), ANGLE3D(0,0,0)); prProjection->Prepare(); // in case of mirror projection, move mirror clip plane a bit father from the mirrored models, // so we have less clipping (for instance, player feet) if( prProjection->pr_bMirror) prProjection->pr_plMirrorView.pl_distance -= 0.06f; // -0.06 is because entire projection is offseted by +0.05 _aprProjection = prProjection; _pdp->SetProjection( _aprProjection); // make FPU precision low _fpuOldPrecision = GetFPUPrecision(); SetFPUPrecision(FPT_24BIT); // prepare common arrays for simple shadows rendering _avtxCommon.PopAll(); _atexCommon.PopAll(); _acolCommon.PopAll(); // eventually setup truform extern INDEX gap_bForceTruform; extern INDEX ogl_bTruformLinearNormals; if( ogl_bTruformLinearNormals) ogl_bTruformLinearNormals = 1; if( gap_bForceTruform) { gap_bForceTruform = 1; gfxSetTruform( _pGfx->gl_iTessellationLevel, ogl_bTruformLinearNormals); } } void EndModelRenderingView( BOOL bRestoreOrtho/*=TRUE*/) { ASSERT( _iRenderingType==1 && _pdp!=NULL); // assure that FPU precision was low all the model rendering time, then revert to old FPU precision ASSERT( GetFPUPrecision()==FPT_24BIT); SetFPUPrecision(_fpuOldPrecision); // restore front face direction gfxFrontFace(GFX_CCW); // render all batched shadows extern void RenderBatchedSimpleShadows_View(void); RenderBatchedSimpleShadows_View(); // back to 2D projection? if( bRestoreOrtho) _pdp->SetOrtho(); _iRenderingType = 0; _pdp = NULL; // eventually disable re-enable clipping gfxEnableClipping(); if( _aprProjection->pr_bMirror || _aprProjection->pr_bWarp) gfxEnableClipPlane(); } // begin/end model rendering to shadow mask void BeginModelRenderingMask( CAnyProjection3D &prProjection, UBYTE *pubMask, SLONG slMaskWidth, SLONG slMaskHeight) { ASSERT( _iRenderingType==0); _iRenderingType = 2; _aprProjection = prProjection; _pubMask = pubMask; _slMaskWidth = slMaskWidth; _slMaskHeight = slMaskHeight; } void EndModelRenderingMask(void) { ASSERT( _iRenderingType==2); _iRenderingType = 0; } // calculate models bounding box (needed for simple shadows and trivial rejection of in-fog/haze-case) static void CalculateBoundingBox( CModelObject *pmo, CRenderModel &rm) { if( rm.rm_ulFlags & RMF_BBOXSET) return; // get model's data and lerp info rm.rm_pmdModelData = (CModelData*)pmo->GetData(); pmo->GetFrame( rm.rm_iFrame0, rm.rm_iFrame1, rm.rm_fRatio); // calculate projection model bounding box in object space const FLOAT3D &vMin0 = rm.rm_pmdModelData->md_FrameInfos[rm.rm_iFrame0].mfi_Box.Min(); const FLOAT3D &vMax0 = rm.rm_pmdModelData->md_FrameInfos[rm.rm_iFrame0].mfi_Box.Max(); const FLOAT3D &vMin1 = rm.rm_pmdModelData->md_FrameInfos[rm.rm_iFrame1].mfi_Box.Min(); const FLOAT3D &vMax1 = rm.rm_pmdModelData->md_FrameInfos[rm.rm_iFrame1].mfi_Box.Max(); rm.rm_vObjectMinBB = Lerp( vMin0, vMin1, rm.rm_fRatio); rm.rm_vObjectMaxBB = Lerp( vMax0, vMax1, rm.rm_fRatio); rm.rm_vObjectMinBB(1) *= pmo->mo_Stretch(1); rm.rm_vObjectMaxBB(1) *= pmo->mo_Stretch(1); rm.rm_vObjectMinBB(2) *= pmo->mo_Stretch(2); rm.rm_vObjectMaxBB(2) *= pmo->mo_Stretch(2); rm.rm_vObjectMinBB(3) *= pmo->mo_Stretch(3); rm.rm_vObjectMaxBB(3) *= pmo->mo_Stretch(3); rm.rm_ulFlags |= RMF_BBOXSET; } CRenderModel::CRenderModel(void) { rm_ulFlags = 0; rm_colBlend = C_WHITE|0xFF; (INDEX&)rm_fDistanceFactor = 12345678; // mip factor readjustment needed rm_iTesselationLevel = 0; } CRenderModel::~CRenderModel(void) { if( !(rm_ulFlags&RMF_ATTACHMENT)) _armRenderModels.PopAll(); } // set placement of the object void CRenderModel::SetObjectPlacement( const CPlacement3D &pl) { rm_vObjectPosition = pl.pl_PositionVector; MakeRotationMatrixFast( rm_mObjectRotation, pl.pl_OrientationAngle); } void CRenderModel::SetObjectPlacement( const FLOAT3D &v, const FLOATmatrix3D &m) { rm_vObjectPosition = v; rm_mObjectRotation = m; } // set modelview matrix if not already set void CRenderModel::SetModelView(void) { _pfModelProfile.StartTimer( CModelProfile::PTI_VIEW_SETMODELVIEW); _pfModelProfile.IncrementTimerAveragingCounter( CModelProfile::PTI_VIEW_SETMODELVIEW); // adjust clipping to frustum if( rm_ulFlags & RMF_INSIDE) gfxDisableClipping(); else gfxEnableClipping(); // adjust clipping to mirror-plane (if any) extern INDEX gap_iOptimizeClipping; if( gap_iOptimizeClipping>0 && (_aprProjection->pr_bMirror || _aprProjection->pr_bWarp)) { if( rm_ulFlags & RMF_INMIRROR) gfxDisableClipPlane(); else gfxEnableClipPlane(); } // make transform matrix const FLOATmatrix3D &m = rm_mObjectToView; const FLOAT3D &v = rm_vObjectToView; FLOAT glm[16]; glm[0] = m(1,1); glm[4] = m(1,2); glm[ 8] = m(1,3); glm[12] = v(1); glm[1] = m(2,1); glm[5] = m(2,2); glm[ 9] = m(2,3); glm[13] = v(2); glm[2] = m(3,1); glm[6] = m(3,2); glm[10] = m(3,3); glm[14] = v(3); glm[3] = 0; glm[7] = 0; glm[11] = 0; glm[15] = 1; gfxSetViewMatrix(glm); // all done _pfModelProfile.StopTimer( CModelProfile::PTI_VIEW_SETMODELVIEW); } // transform a vertex in model with lerping void CModelObject::UnpackVertex( CRenderModel &rm, const INDEX iVertex, FLOAT3D &vVertex) { if( ((CModelData*)GetData())->md_Flags & MF_COMPRESSED_16BIT) { // get 16 bit packed vertices const SWPOINT3D &vsw0 = rm.rm_pFrame16_0[iVertex].mfv_SWPoint; const SWPOINT3D &vsw1 = rm.rm_pFrame16_1[iVertex].mfv_SWPoint; // convert them to float and lerp between them vVertex(1) = (Lerp( (FLOAT)vsw0(1), (FLOAT)vsw1(1), rm.rm_fRatio) -rm.rm_vOffset(1)) * rm.rm_vStretch(1); vVertex(2) = (Lerp( (FLOAT)vsw0(2), (FLOAT)vsw1(2), rm.rm_fRatio) -rm.rm_vOffset(2)) * rm.rm_vStretch(2); vVertex(3) = (Lerp( (FLOAT)vsw0(3), (FLOAT)vsw1(3), rm.rm_fRatio) -rm.rm_vOffset(3)) * rm.rm_vStretch(3); } else { // get 8 bit packed vertices const SBPOINT3D &vsb0 = rm.rm_pFrame8_0[iVertex].mfv_SBPoint; const SBPOINT3D &vsb1 = rm.rm_pFrame8_1[iVertex].mfv_SBPoint; // convert them to float and lerp between them vVertex(1) = (Lerp( (FLOAT)vsb0(1), (FLOAT)vsb1(1), rm.rm_fRatio) -rm.rm_vOffset(1)) * rm.rm_vStretch(1); vVertex(2) = (Lerp( (FLOAT)vsb0(2), (FLOAT)vsb1(2), rm.rm_fRatio) -rm.rm_vOffset(2)) * rm.rm_vStretch(2); vVertex(3) = (Lerp( (FLOAT)vsb0(3), (FLOAT)vsb1(3), rm.rm_fRatio) -rm.rm_vOffset(3)) * rm.rm_vStretch(3); } } // Create render model structure for rendering an attached model BOOL CModelObject::CreateAttachment( CRenderModel &rmMain, CAttachmentModelObject &amo) { _pfModelProfile.StartTimer( CModelProfile::PTI_CREATEATTACHMENT); _pfModelProfile.IncrementTimerAveragingCounter( CModelProfile::PTI_CREATEATTACHMENT); CRenderModel &rmAttached = *amo.amo_prm; rmAttached.rm_ulFlags = rmMain.rm_ulFlags&(RMF_FOG|RMF_HAZE|RMF_WEAPON) | RMF_ATTACHMENT; // get the position rmMain.rm_pmdModelData->md_aampAttachedPosition.Lock(); const CAttachedModelPosition &amp = rmMain.rm_pmdModelData->md_aampAttachedPosition[amo.amo_iAttachedPosition]; rmMain.rm_pmdModelData->md_aampAttachedPosition.Unlock(); // copy common values rmAttached.rm_vLightDirection = rmMain.rm_vLightDirection; rmAttached.rm_fDistanceFactor = rmMain.rm_fDistanceFactor; rmAttached.rm_colLight = rmMain.rm_colLight; rmAttached.rm_colAmbient = rmMain.rm_colAmbient; rmAttached.rm_colBlend = rmMain.rm_colBlend; // unpack the reference vertices FLOAT3D vCenter, vFront, vUp; const INDEX iCenter = amp.amp_iCenterVertex; const INDEX iFront = amp.amp_iFrontVertex; const INDEX iUp = amp.amp_iUpVertex; UnpackVertex( rmMain, iCenter, vCenter); UnpackVertex( rmMain, iFront, vFront); UnpackVertex( rmMain, iUp, vUp); // create front and up direction vectors FLOAT3D vY = vUp - vCenter; FLOAT3D vZ = vCenter - vFront; // project center and directions from object to absolute space const FLOATmatrix3D &mO2A = rmMain.rm_mObjectRotation; const FLOAT3D &vO2A = rmMain.rm_vObjectPosition; vCenter = vCenter*mO2A +vO2A; vY = vY *mO2A; vZ = vZ *mO2A; // make a rotation matrix from the direction vectors FLOAT3D vX = vY*vZ; vY = vZ*vX; vX.Normalize(); vY.Normalize(); vZ.Normalize(); FLOATmatrix3D mOrientation; mOrientation(1,1) = vX(1); mOrientation(1,2) = vY(1); mOrientation(1,3) = vZ(1); mOrientation(2,1) = vX(2); mOrientation(2,2) = vY(2); mOrientation(2,3) = vZ(2); mOrientation(3,1) = vX(3); mOrientation(3,2) = vY(3); mOrientation(3,3) = vZ(3); // adjust for relative placement of the attachment FLOAT3D vOffset; FLOATmatrix3D mRelative; MakeRotationMatrixFast( mRelative, amo.amo_plRelative.pl_OrientationAngle); vOffset(1) = amo.amo_plRelative.pl_PositionVector(1) * mo_Stretch(1); vOffset(2) = amo.amo_plRelative.pl_PositionVector(2) * mo_Stretch(2); vOffset(3) = amo.amo_plRelative.pl_PositionVector(3) * mo_Stretch(3); FLOAT3D vO = vCenter + vOffset * mOrientation; mOrientation *= mRelative; // convert absolute to relative orientation rmAttached.SetObjectPlacement( vO, mOrientation); // done here if clipping optimizations are not allowed extern INDEX gap_iOptimizeClipping; if( gap_iOptimizeClipping<1) { gap_iOptimizeClipping = 0; _pfModelProfile.StopTimer( CModelProfile::PTI_CREATEATTACHMENT); return TRUE; } // test attachment to frustum and/or mirror FLOAT3D vHandle; _aprProjection->PreClip( vO, vHandle); CalculateBoundingBox( &amo.amo_moModelObject, rmAttached); // compose view-space bounding box and sphere of an attacment const FLOAT fR = Max( rmAttached.rm_vObjectMinBB.Length(), rmAttached.rm_vObjectMaxBB.Length()); const FLOATobbox3D boxEntity( FLOATaabbox3D(rmAttached.rm_vObjectMinBB, rmAttached.rm_vObjectMaxBB), vHandle, _aprProjection->pr_ViewerRotationMatrix*mOrientation); // frustum test? if( gap_iOptimizeClipping>1) { // test sphere against frustrum INDEX iFrustumTest = _aprProjection->TestSphereToFrustum(vHandle,fR); if( iFrustumTest==0) { // test box if sphere cut one of frustum planes iFrustumTest = _aprProjection->TestBoxToFrustum(boxEntity); } // mark if attachment is fully inside frustum if( iFrustumTest>0) rmAttached.rm_ulFlags |= RMF_INSIDE; else if( iFrustumTest<0) { // if completely outside of frustum // signal skip rendering only if doesn't have any attachments _pfModelProfile.StopTimer( CModelProfile::PTI_CREATEATTACHMENT); return !amo.amo_moModelObject.mo_lhAttachments.IsEmpty(); } } // test sphere against mirror/warp plane (if any) if( _aprProjection->pr_bMirror || _aprProjection->pr_bWarp) { INDEX iMirrorPlaneTest; const FLOAT fPlaneDistance = _aprProjection->pr_plMirrorView.PointDistance(vHandle); if( fPlaneDistance < -fR) iMirrorPlaneTest = -1; else if( fPlaneDistance > +fR) iMirrorPlaneTest = +1; else { // test box if sphere cut mirror plane iMirrorPlaneTest = (INDEX) (boxEntity.TestAgainstPlane(_aprProjection->pr_plMirrorView)); } // mark if attachment is fully inside mirror if( iMirrorPlaneTest>0) rmAttached.rm_ulFlags |= RMF_INMIRROR; else if( iMirrorPlaneTest<0) { // if completely outside mirror // signal skip rendering only if doesn't have any attachments _pfModelProfile.StopTimer( CModelProfile::PTI_CREATEATTACHMENT); return !amo.amo_moModelObject.mo_lhAttachments.IsEmpty(); } } // all done _pfModelProfile.StopTimer( CModelProfile::PTI_CREATEATTACHMENT); return TRUE; } //-------------------------------------------------------------------------------------------- /* * Render model using preferences given trough _mrpModelRenderPrefs global variable */ //-------------------------------------------------------------------------------------------- // transform model to view space static void PrepareView( CRenderModel &rm) { // prepare projections const FLOATmatrix3D &mViewer = _aprProjection->pr_ViewerRotationMatrix; const FLOAT3D &vViewer = _aprProjection->pr_vViewerPosition; FLOATmatrix3D &m = rm.rm_mObjectToView; // if half face forward if( rm.rm_pmdModelData->md_Flags&MF_HALF_FACE_FORWARD) { // get the y-axis vector of object rotation FLOAT3D vY(rm.rm_mObjectRotation(1,2), rm.rm_mObjectRotation(2,2), rm.rm_mObjectRotation(3,2)); // find z axis of viewer FLOAT3D vViewerZ( mViewer(3,1), mViewer(3,2), mViewer(3,3)); // calculate x and z axis vectors to make object head towards viewer FLOAT3D vX = (-vViewerZ)*vY; vX.Normalize(); FLOAT3D vZ = vY*vX; // compose the rotation matrix back from those angles m(1,1) = vX(1); m(1,2) = vY(1); m(1,3) = vZ(1); m(2,1) = vX(2); m(2,2) = vY(2); m(2,3) = vZ(2); m(3,1) = vX(3); m(3,2) = vY(3); m(3,3) = vZ(3); // add viewer rotation to that m = mViewer * m; } // if full face forward else if( rm.rm_pmdModelData->md_Flags&MF_FACE_FORWARD) { // use just object banking for rotation FLOAT fSinP = -rm.rm_mObjectRotation(2,3); FLOAT fCosP = Sqrt(1-fSinP*fSinP); FLOAT fSinB, fCosB; if( fCosP>0.001f) { const FLOAT f1oCosP = 1.0f/fCosP; fSinB = rm.rm_mObjectRotation(2,1)*f1oCosP; fCosB = rm.rm_mObjectRotation(2,2)*f1oCosP; } else { fSinB = 0.0f; fCosB = 1.0f; } m(1,1) = +fCosB; m(1,2) = -fSinB; m(1,3) = 0; m(2,1) = +fSinB; m(2,2) = +fCosB; m(2,3) = 0; m(3,1) = 0; m(3,2) = 0; m(3,3) = 1; } // if normal model else { // use viewer and object orientation m = mViewer * rm.rm_mObjectRotation; } // find translation vector rm.rm_vObjectToView = rm.rm_vObjectPosition - vViewer; rm.rm_vObjectToView *= mViewer; } // render bounding box static void RenderWireframeBox( FLOAT3D vMinVtx, FLOAT3D vMaxVtx, COLOR col) { // only for OpenGL (for now) if( _pGfx->gl_eCurrentAPI!=GAT_OGL) return; // prepare wireframe OpenGL settings gfxDisableDepthTest(); gfxDisableDepthWrite(); gfxDisableBlend(); gfxDisableAlphaTest(); gfxDisableTexture(); // fill vertex array so it represents bounding box FLOAT3D vBoxVtxs[8]; vBoxVtxs[0] = FLOAT3D( vMinVtx(1), vMinVtx(2), vMinVtx(3)); vBoxVtxs[1] = FLOAT3D( vMaxVtx(1), vMinVtx(2), vMinVtx(3)); vBoxVtxs[2] = FLOAT3D( vMaxVtx(1), vMinVtx(2), vMaxVtx(3)); vBoxVtxs[3] = FLOAT3D( vMinVtx(1), vMinVtx(2), vMaxVtx(3)); vBoxVtxs[4] = FLOAT3D( vMinVtx(1), vMaxVtx(2), vMinVtx(3)); vBoxVtxs[5] = FLOAT3D( vMaxVtx(1), vMaxVtx(2), vMinVtx(3)); vBoxVtxs[6] = FLOAT3D( vMaxVtx(1), vMaxVtx(2), vMaxVtx(3)); vBoxVtxs[7] = FLOAT3D( vMinVtx(1), vMaxVtx(2), vMaxVtx(3)); // connect vertices into lines of bounding box INDEX iBoxLines[12][2]; iBoxLines[ 0][0] = 0; iBoxLines[ 0][1] = 1; iBoxLines[ 1][0] = 1; iBoxLines[ 1][1] = 2; iBoxLines[ 2][0] = 2; iBoxLines[ 2][1] = 3; iBoxLines[ 3][0] = 3; iBoxLines[ 3][1] = 0; iBoxLines[ 4][0] = 0; iBoxLines[ 4][1] = 4; iBoxLines[ 5][0] = 1; iBoxLines[ 5][1] = 5; iBoxLines[ 6][0] = 2; iBoxLines[ 6][1] = 6; iBoxLines[ 7][0] = 3; iBoxLines[ 7][1] = 7; iBoxLines[ 8][0] = 4; iBoxLines[ 8][1] = 5; iBoxLines[ 9][0] = 5; iBoxLines[ 9][1] = 6; iBoxLines[10][0] = 6; iBoxLines[10][1] = 7; iBoxLines[11][0] = 7; iBoxLines[11][1] = 4; // for all vertices in bounding box glCOLOR(col); pglBegin( GL_LINES); for( INDEX i=0; i<12; i++) { // get starting and ending vertices of one line FLOAT3D &v0 = vBoxVtxs[iBoxLines[i][0]]; FLOAT3D &v1 = vBoxVtxs[iBoxLines[i][1]]; pglVertex3f( v0(1), v0(2), v0(3)); pglVertex3f( v1(1), v1(2), v1(3)); } pglEnd(); OGL_CHECKERROR; } // setup CRenderModel class for rendering one model and eventually it's shadow(s) void CModelObject::SetupModelRendering( CRenderModel &rm) { _sfStats.IncrementCounter( CStatForm::SCI_MODELS); _pfModelProfile.StartTimer( CModelProfile::PTI_INITMODELRENDERING); _pfModelProfile.IncrementTimerAveragingCounter( CModelProfile::PTI_INITMODELRENDERING); // get model's data and lerp info rm.rm_pmdModelData = (CModelData*)GetData(); GetFrame( rm.rm_iFrame0, rm.rm_iFrame1, rm.rm_fRatio); const INDEX ctVertices = rm.rm_pmdModelData->md_VerticesCt; if( rm.rm_pmdModelData->md_Flags & MF_COMPRESSED_16BIT) { // set pFrame to point to last and next frames' vertices rm.rm_pFrame16_0 = &rm.rm_pmdModelData->md_FrameVertices16[rm.rm_iFrame0 *ctVertices]; rm.rm_pFrame16_1 = &rm.rm_pmdModelData->md_FrameVertices16[rm.rm_iFrame1 *ctVertices]; } else { // set pFrame to point to last and next frames' vertices rm.rm_pFrame8_0 = &rm.rm_pmdModelData->md_FrameVertices8[rm.rm_iFrame0 *ctVertices]; rm.rm_pFrame8_1 = &rm.rm_pmdModelData->md_FrameVertices8[rm.rm_iFrame1 *ctVertices]; } // obtain current rendering preferences rm.rm_rtRenderType = _mrpModelRenderPrefs.GetRenderType(); // remember blending color rm.rm_colBlend = MulColors( rm.rm_colBlend, mo_colBlendColor); // get decompression/stretch factors FLOAT3D &vDataStretch = rm.rm_pmdModelData->md_Stretch; rm.rm_vStretch(1) = vDataStretch(1) * mo_Stretch(1); rm.rm_vStretch(2) = vDataStretch(2) * mo_Stretch(2); rm.rm_vStretch(3) = vDataStretch(3) * mo_Stretch(3); rm.rm_vOffset = rm.rm_pmdModelData->md_vCompressedCenter; // check if object is inverted (in mirror) BOOL bXInverted = rm.rm_vStretch(1) < 0; BOOL bYInverted = rm.rm_vStretch(2) < 0; BOOL bZInverted = rm.rm_vStretch(3) < 0; rm.rm_ulFlags &= ~RMF_INVERTED; if( bXInverted != bYInverted != bZInverted != _aprProjection->pr_bInverted) rm.rm_ulFlags |= RMF_INVERTED; // prepare projections _pfModelProfile.StartTimer( CModelProfile::PTI_INITPROJECTION); _pfModelProfile.IncrementTimerAveragingCounter( CModelProfile::PTI_INITPROJECTION); PrepareView(rm); _pfModelProfile.StopTimer( CModelProfile::PTI_INITPROJECTION); // get mip factor from projection (if needed) if( (INDEX&)rm.rm_fDistanceFactor==12345678) { FLOAT3D vObjectAbs; _aprProjection->PreClip( rm.rm_vObjectPosition, vObjectAbs); rm.rm_fDistanceFactor = _aprProjection->MipFactor( Min(vObjectAbs(3), 0.0f)); } // adjust mip factor in case of dynamic stretch factor if( mo_Stretch != FLOAT3D(1,1,1)) { rm.rm_fMipFactor = rm.rm_fDistanceFactor - Log2( Max(mo_Stretch(1),Max(mo_Stretch(2),mo_Stretch(3)))); } else { rm.rm_fMipFactor = rm.rm_fDistanceFactor; } // adjust mip factor by custom settings rm.rm_fMipFactor = rm.rm_fMipFactor*mdl_fLODMul +mdl_fLODAdd; // get current mip model using mip factor rm.rm_iMipLevel = GetMipModel( rm.rm_fMipFactor); mo_iLastRenderMipLevel = rm.rm_iMipLevel; // get current vertices mask rm.rm_pmmiMip = &rm.rm_pmdModelData->md_MipInfos[rm.rm_iMipLevel]; // don't allow any shading, if shading is turned off if( rm.rm_rtRenderType & RT_SHADING_NONE) { rm.rm_colAmbient = C_WHITE|CT_OPAQUE; rm.rm_colLight = C_BLACK; } // calculate light vector as seen from model, so that vertex normals // do not need to be transformed for lighting calculations FLOAT fLightDirection=(rm.rm_vLightDirection).Length(); if( fLightDirection>0.001f) { rm.rm_vLightDirection /= fLightDirection; } else { rm.rm_vLightDirection = FLOAT3D(0,0,0); } rm.rm_vLightObj = rm.rm_vLightDirection * !rm.rm_mObjectRotation; // precalculate rendering data if needed extern void PrepareModelForRendering( CModelData &md); PrepareModelForRendering( *rm.rm_pmdModelData); // done with setup if viewing from this model if( rm.rm_ulFlags&RMF_SPECTATOR) { _pfModelProfile.StopTimer( CModelProfile::PTI_INITMODELRENDERING); return; } _pfModelProfile.StartTimer( CModelProfile::PTI_INITATTACHMENTS); // for each attachment on this model object FOREACHINLIST( CAttachmentModelObject, amo_lnInMain, mo_lhAttachments, itamo) { _pfModelProfile.IncrementTimerAveragingCounter( CModelProfile::PTI_INITATTACHMENTS); CAttachmentModelObject *pamo = itamo; // create new render model structure pamo->amo_prm = &_armRenderModels.Push(); const BOOL bVisible = CreateAttachment( rm, *pamo); if( !bVisible) { // skip if not visible pamo->amo_prm = NULL; _armRenderModels.Pop(); continue; } // prepare if visible _pfModelProfile.StopTimer( CModelProfile::PTI_INITMODELRENDERING); _pfModelProfile.StopTimer( CModelProfile::PTI_INITATTACHMENTS); pamo->amo_moModelObject.SetupModelRendering( *pamo->amo_prm); _pfModelProfile.StartTimer( CModelProfile::PTI_INITATTACHMENTS); _pfModelProfile.StartTimer( CModelProfile::PTI_INITMODELRENDERING); } // all done _pfModelProfile.StopTimer( CModelProfile::PTI_INITATTACHMENTS); _pfModelProfile.StopTimer( CModelProfile::PTI_INITMODELRENDERING); } // render model void CModelObject::RenderModel( CRenderModel &rm) { // skip invisible models if( mo_Stretch == FLOAT3D(0,0,0)) return; _pfModelProfile.StartTimer( CModelProfile::PTI_RENDERMODEL); _pfModelProfile.IncrementTimerAveragingCounter( CModelProfile::PTI_RENDERMODEL); // cluster shadows rendering? if( _iRenderingType==2) { RenderModel_Mask(rm); _pfModelProfile.StopTimer( CModelProfile::PTI_RENDERMODEL); return; } ASSERT( _iRenderingType==1); // if we should draw polygons and model if( !(rm.rm_ulFlags&RMF_SPECTATOR) && (!(rm.rm_rtRenderType&RT_NO_POLYGON_FILL) || (rm.rm_rtRenderType&RT_WIRE_ON) || (rm.rm_rtRenderType&RT_HIDDEN_LINES)) ) { // eventually calculate projection model bounding box in object space (needed for fog/haze trivial rejection) if( rm.rm_ulFlags&(RMF_FOG|RMF_HAZE)) CalculateBoundingBox( this, rm); // render complete model rm.SetModelView(); RenderModel_View(rm); } // if we should draw current frame bounding box if( _mrpModelRenderPrefs.BBoxFrameVisible()) { // get min and max coordinates of bounding box FLOAT3D vMin = rm.rm_pmdModelData->md_FrameInfos[rm.rm_iFrame0].mfi_Box.Min(); FLOAT3D vMax = rm.rm_pmdModelData->md_FrameInfos[rm.rm_iFrame0].mfi_Box.Max(); rm.SetModelView(); RenderWireframeBox( vMin, vMax, C_dMAGENTA|CT_OPAQUE); } // if we should draw all frames bounding box if( _mrpModelRenderPrefs.BBoxAllVisible()) { // calculate all frames bounding box FLOATaabbox3D aabbMax; for( INDEX i=0; i<rm.rm_pmdModelData->md_FramesCt; i++) { aabbMax |= rm.rm_pmdModelData->md_FrameInfos[i].mfi_Box; } // pass min and max coordinates of all frames bounding box rm.SetModelView(); RenderWireframeBox( aabbMax.Min(), aabbMax.Max(), C_dGRAY|CT_OPAQUE); } // render each attachment on this model object FOREACHINLIST( CAttachmentModelObject, amo_lnInMain, mo_lhAttachments, itamo) { // calculate bounding box of an attachment CAttachmentModelObject *pamo = itamo; if( pamo->amo_prm==NULL) continue; // skip view-rejected attachments _pfModelProfile.StopTimer( CModelProfile::PTI_RENDERMODEL); pamo->amo_moModelObject.RenderModel( *pamo->amo_prm); _pfModelProfile.StartTimer( CModelProfile::PTI_RENDERMODEL); } // done _pfModelProfile.StopTimer( CModelProfile::PTI_RENDERMODEL); } //-------------------------------------------------------------------------------------------- /* * Render shadow of model */ //-------------------------------------------------------------------------------------------- void CModelObject::RenderShadow( CRenderModel &rm, const CPlacement3D &plLight, const FLOAT fFallOff, const FLOAT fHotSpot, const FLOAT fIntensity, const FLOATplane3D &plShadowPlane) { // if shadows are not rendered for current mip or model is half/full face-forward, do nothing if( !HasShadow(rm.rm_iMipLevel) || (rm.rm_pmdModelData->md_Flags&(MF_FACE_FORWARD|MF_HALF_FACE_FORWARD))) return; ASSERT( _iRenderingType==1); ASSERT( fIntensity>=0 && fIntensity<=1); _pfModelProfile.StartTimer( CModelProfile::PTI_RENDERSHADOW); _pfModelProfile.IncrementTimerAveragingCounter( CModelProfile::PTI_RENDERSHADOW); _sfStats.IncrementCounter( CStatForm::SCI_MODELSHADOWS); // call driver function for drawing shadows rm.SetModelView(); RenderShadow_View( rm, plLight, fFallOff, fHotSpot, fIntensity, plShadowPlane); // render shadow or each attachment on this model object FOREACHINLIST( CAttachmentModelObject, amo_lnInMain, mo_lhAttachments, itamo) { CAttachmentModelObject *pamo = itamo; if( pamo->amo_prm==NULL) continue; // skip view-rejected attachments _pfModelProfile.StopTimer( CModelProfile::PTI_RENDERSHADOW); pamo->amo_moModelObject.RenderShadow( *pamo->amo_prm, plLight, fFallOff, fHotSpot, fIntensity, plShadowPlane); _pfModelProfile.StartTimer( CModelProfile::PTI_RENDERSHADOW); } _pfModelProfile.StopTimer( CModelProfile::PTI_RENDERSHADOW); } // simple shadow rendering void CModelObject::AddSimpleShadow( CRenderModel &rm, const FLOAT fIntensity, const FLOATplane3D &plShadowPlane) { // if shadows are not rendered for current mip, model is half/full face-forward, // intensitiy is too low or projection is not perspective - do nothing! if( !HasShadow(rm.rm_iMipLevel) || fIntensity<0.01f || !_aprProjection.IsPerspective() || (rm.rm_pmdModelData->md_Flags&(MF_FACE_FORWARD|MF_HALF_FACE_FORWARD))) return; ASSERT( _iRenderingType==1); ASSERT( fIntensity>0 && fIntensity<=1); // do some rendering _pfModelProfile.StartTimer( CModelProfile::PTI_RENDERSIMPLESHADOW); _pfModelProfile.IncrementTimerAveragingCounter( CModelProfile::PTI_RENDERSIMPLESHADOW); _sfStats.IncrementCounter( CStatForm::SCI_MODELSHADOWS); // calculate projection model bounding box in object space (if needed) CalculateBoundingBox( this, rm); // add one simple shadow to batch list AddSimpleShadow_View( rm, fIntensity, plShadowPlane); // all done _pfModelProfile.StopTimer( CModelProfile::PTI_RENDERSIMPLESHADOW); }
gpl-2.0
imfaber/imfaber_v2
modules/backend/widgets/Form.php
20028
<?php namespace Backend\Widgets; use App; use Str; use Lang; use Form as FormHelper; use Input; use Event; use Backend\Classes\FormField; use Backend\Classes\WidgetBase; use Backend\Classes\WidgetManager; use System\Classes\ApplicationException; /** * Form Widget * Used for building back end forms and renders a form. * * @package october\backend * @author Alexey Bobkov, Samuel Georges */ class Form extends WidgetBase { /** * {@inheritDoc} */ public $defaultAlias = 'form'; /** * @var Model Form model object. */ public $model; /** * @var array Dataset containing field values, if none supplied, model is used. */ public $data; /** * @var boolean Determines if field definitions have been created. */ private $fieldsDefined = false; /** * @var array Collection of all fields used in this form. */ public $allFields = []; /** * @var array Collection of all form widgets used in this form. */ public $formWidgets = []; /** * @var array Collection of fields not contained in a tab. */ protected $outsideFields = []; /** * @var array Collection of fields inside the primary tabs. */ protected $primaryTabs = []; /** * @var array Collection of fields inside the secondary tabs. */ protected $secondaryTabs = []; /** * @var string If the field element names should be contained in an array. * Eg: <input name="nameArray[fieldName]" /> */ public $arrayName; /** * @var string The context of this form, fields that do not belong * to this context will not be shown. */ protected $activeContext = null; /** * @var string Active session key, used for editing forms and deferred bindings. */ public $sessionKey; /** * @var bool Render this form with uneditable preview data. */ public $previewMode = false; /** * @var Backend\Classes\WidgetManager */ protected $widgetManager; /** * Initialize the widget, called by the constructor and free from its parameters. */ public function init() { $this->widgetManager = WidgetManager::instance(); $this->arrayName = $this->getConfig('arrayName'); $this->activeContext = $this->getConfig('context'); $this->validateModel(); } /** * Ensure fields are defined and form widgets are registered so they can * also be bound to the controller this allows their AJAX features to * operate. * @return void */ public function bindToController() { $this->defineFormFields(); parent::bindToController(); } /** * {@inheritDoc} */ public function loadAssets() { $this->addJs('js/form.js', 'core'); } /** * Renders the widget. * * Options: * - preview: Render this form as an uneditable preview. Default: false * - section: Which form section to render. Default: null * - outside: Renders the Outside Fields area. * - primary: Renders the Primary Tabs area. * - secondary: Renders the Secondary Tabs area. * - null: Renders all sections */ public function render($options = []) { if (isset($options['preview'])) $this->previewMode = $options['preview']; /* * Determine the partial to use based on the supplied section option */ $section = (isset($options['section'])) ? $options['section'] : null; switch (strtolower($section)) { case 'outside': $targetPartial = 'form_outside_fields'; break; case 'primary': $targetPartial = 'form_primary_tabs'; break; case 'secondary': $targetPartial = 'form_secondary_tabs'; break; default: $targetPartial = 'form'; break; } $this->prepareVars(); return $this->makePartial($targetPartial); } /** * Renders a single form field */ public function renderField($field) { if (is_string($field)) { if (!isset($this->allFields[$field])) throw new ApplicationException(Lang::get('backend::lang.form.missing_definition', compact('field'))); $field = $this->allFields[$field]; } $this->prepareVars(); return $this->makePartial('field', ['field' => $field]); } /** * Renders the HTML element for a field */ public function renderFieldElement($field) { return $this->makePartial('field_'.$field->type, ['field' => $field]); } /** * Validate the supplied form model. * @return void */ protected function validateModel() { $this->model = $this->getConfig('model'); if (!$this->model) throw new ApplicationException(Lang::get('backend::lang.form.missing_model', ['class'=>get_class($this->controller)])); $this->data = (object)$this->getConfig('data', $this->model); return $this->model; } /** * Prepares the list data */ public function prepareVars() { $this->defineFormFields(); $this->vars['sessionKey'] = $this->getSessionKey(); $this->vars['outsideFields'] = $this->outsideFields; $this->vars['primaryTabs'] = $this->primaryTabs; $this->vars['secondaryTabs'] = $this->secondaryTabs; } /** * Creates a flat array of form fields from the configuration. * Also slots fields in to their respective tabs. */ protected function defineFormFields() { if ($this->fieldsDefined) return; /* * Extensibility */ Event::fire('backend.form.extendFieldsBefore', [$this]); $this->fireEvent('form.extendFieldsBefore', $this); /* * Outside fields */ if (!isset($this->config->fields) || !is_array($this->config->fields)) $this->config->fields = []; $this->addFields($this->config->fields); /* * Primary Tabs + Fields */ if (!isset($this->config->tabs['fields']) || !is_array($this->config->tabs['fields'])) $this->config->tabs['fields'] = []; $this->addFields($this->config->tabs['fields'], 'primary'); /* * Secondary Tabs + Fields */ if (!isset($this->config->secondaryTabs['fields']) || !is_array($this->config->secondaryTabs['fields'])) $this->config->secondaryTabs['fields'] = []; $this->addFields($this->config->secondaryTabs['fields'], 'secondary'); /* * Extensibility */ Event::fire('backend.form.extendFields', [$this]); $this->fireEvent('form.extendFields', $this); /* * Convert automatic spanned fields */ $this->processAutoSpan($this->outsideFields); foreach ($this->primaryTabs as $fields) $this->processAutoSpan($fields); foreach ($this->secondaryTabs as $fields) $this->processAutoSpan($fields); /* * Bind all form widgets to controller */ foreach ($this->allFields as $field) { if ($field->type != 'widget') continue; $widget = $this->makeFormWidget($field); $widget->bindToController(); } $this->fieldsDefined = true; } /** * Converts fields with a span set to 'auto' as either * 'left' or 'right' depending on the previous field. */ protected function processAutoSpan($fields) { $prevSpan = null; foreach ($fields as $field) { if (strtolower($field->span) == 'auto') { if ($prevSpan == 'left') $field->span = 'right'; else $field->span = 'left'; } $prevSpan = $field->span; } } /** * Programatically add fields, used internally and for extensibility. */ public function addFields(array $fields, $addToArea = null) { foreach ($fields as $name => $config) { $defaultTab = Lang::get('backend::lang.form.undefined_tab'); if (!is_array($config)) $tab = $defaultTab; elseif (!isset($config['tab'])) $tab = $config['tab'] = $defaultTab; else $tab = $config['tab']; $fieldObj = $this->makeFormField($name, $config); /* * Check that the form field matches the active context */ if ($fieldObj->context !== null) { $context = (is_array($fieldObj->context)) ? $fieldObj->context : [$fieldObj->context]; if (!in_array($this->getContext(), $context)) continue; } $this->allFields[$name] = $fieldObj; switch (strtolower($addToArea)) { case 'primary': $this->primaryTabs[$tab][$name] = $fieldObj; break; case 'secondary': $this->secondaryTabs[$tab][$name] = $fieldObj; break; default: $this->outsideFields[$name] = $fieldObj; break; } } } public function addTabFields(array $fields) { return $this->addFields($fields, 'primary'); } public function addSecondaryTabFields(array $fields) { return $this->addFields($fields, 'secondary'); } /** * Creates a form field object from name and configuration. */ protected function makeFormField($name, $config) { $label = (isset($config['label'])) ? $config['label'] : null; list($fieldName, $fieldContext) = $this->getFieldName($name); $field = new FormField($fieldName, $label); if ($fieldContext) $field->context = $fieldContext; $field->arrayName = $this->arrayName; $field->idPrefix = $this->getId(); /* * Simple widget field, only widget type is supplied */ if (is_string($config) && $this->isFormWidget($config) !== false) { $field->displayAs('widget', ['widget' => $config]); return $field; } /* * Simple field, only field type is supplied */ elseif (is_string($config)) { $field->displayAs($config); return $field; } /* * Defined field type */ $fieldType = isset($config['type']) ? $config['type'] : null; if (!is_string($fieldType) && !is_null($fieldType)) throw new ApplicationException(Lang::get('backend::lang.field.invalid_type', ['type'=>gettype($fieldType)])); /* * Process basic options */ if (isset($config['span'])) $field->span($config['span']); if (isset($config['context'])) $field->context = $config['context']; if (isset($config['size'])) $field->size($config['size']); if (isset($config['tab'])) $field->tab($config['tab']); if (isset($config['commentAbove'])) $field->comment($config['commentAbove'], 'above'); if (isset($config['comment'])) $field->comment($config['comment']); if (isset($config['placeholder'])) $field->placeholder = $config['placeholder']; if (isset($config['default'])) $field->defaults = $config['default']; if (isset($config['cssClass'])) $field->cssClass = $config['cssClass']; if (isset($config['attributes'])) $field->attributes = $config['attributes']; if (isset($config['path'])) $field->path = $config['path']; if (array_key_exists('required', $config)) $field->required = $config['required']; if (array_key_exists('disabled', $config)) $field->disabled = $config['disabled']; if (array_key_exists('stretch', $config)) $field->stretch = $config['stretch']; /* * Set field value */ $field->value = $this->getFieldValue($field); /* * Widget with options */ if ($this->isFormWidget($fieldType) !== false) { $fieldOptions = (isset($config['options'])) ? $config['options'] : []; $fieldOptions['widget'] = $fieldType; $field->displayAs('widget', $fieldOptions); } /* * Simple field with options */ elseif (strlen($fieldType)) { $fieldOptions = (isset($config['options'])) ? $config['options'] : null; $studlyField = studly_case(strtolower($fieldType)); if (method_exists($this, 'eval'.$studlyField.'Options')) $fieldOptions = $this->{'eval'.$studlyField.'Options'}($field, $fieldOptions); $field->displayAs($fieldType, $fieldOptions); } return $field; } private function isFormWidget($fieldType) { if ($fieldType === null) return false; if (strpos($fieldType, '\\')) return true; $widgetClass = $this->widgetManager->resolveFormWidget($fieldType); if (!class_exists($widgetClass)) return false; if (is_subclass_of($widgetClass, 'Backend\Classes\FormWidgetBase')) return true; return false; } /** * Makes a widget object from a form field object. */ public function makeFormWidget($field) { if ($field->type != 'widget') return null; if (isset($this->formWidgets[$field->columnName])) return $this->formWidgets[$field->columnName]; $widgetConfig = $this->makeConfig($field->options); $widgetConfig->alias = $this->alias . studly_case($field->columnName); $widgetConfig->sessionKey = $this->getSessionKey(); $widgetName = $widgetConfig->widget; $widgetClass = $this->widgetManager->resolveFormWidget($widgetName); if (!class_exists($widgetClass)) { throw new ApplicationException(Lang::get('backend::lang.widget.not_registered', [ 'name' => $widgetClass ])); } $widget = new $widgetClass($this->controller, $this->model, $field, $widgetConfig); return $this->formWidgets[$field->columnName] = $widget; } /** * Parses a field's name * @param stirng $field Field name * @return array [columnName, context] */ public function getFieldName($field) { if (strpos($field, '@') === false) return [$field, null]; return explode('@', $field); } /** * Looks up the column */ public function getFieldValue($field) { if (is_string($field)) { if (!isset($this->allFields[$field])) throw new ApplicationException(Lang::get('backend::lang.form.missing_definition', compact('field'))); $field = $this->allFields[$field]; } $columnName = $field->columnName; if (!$this->model->exists) $defaultValue = strlen($field->defaults) ? $field->defaults : null; else $defaultValue = (isset($this->data->{$columnName})) ? $this->data->{$columnName} : null; /* * Array field name, eg: field[key][key2][key3] */ $keyParts = Str::evalHtmlArray($columnName); /* * First part will be the field name, pop it off. */ $fieldName = array_shift($keyParts); if (!isset($this->data->{$fieldName})) return $defaultValue; $result = $this->data->{$fieldName}; /* * Loop the remaining key parts and build a result. * This won't execute for standard field names. */ foreach ($keyParts as $key) { if (is_array($result)) { if (!array_key_exists($key, $result)) return $defaultValue; $result = $result[$key]; } else { if (!isset($result->{$key})) return $defaultValue; $result = $result->{$key}; } } return $result; } /** * Returns postback data from a submitted form. */ public function getSaveData() { $data = ($this->arrayName) ? post($this->arrayName) : post(); if (!$data) $data = []; /* * Boolean fields (checkbox, switch) won't be present value FALSE */ foreach ($this->allFields as $field) { if ($field->type != 'switch' && $field->type != 'checkbox') continue; /* * Handle HTML array, eg: item[key][another] */ $columnParts = Str::evalHtmlArray($field->columnName); $columnDotted = implode('.', $columnParts); $columnValue = array_get($data, $columnDotted, 0); array_set($data, $columnDotted, $columnValue); } /* * Give widgets an opportunity to process the data. */ foreach ($this->formWidgets as $field => $widget) { $widgetValue = array_key_exists($field, $data) ? $data[$field] : null; $data[$field] = $widget->getSaveData($widgetValue); } return $data; } /** * Evaluate and validate dropdown field options. */ public function evalDropdownOptions($field, $fieldOptions) { return $this->getOptionsFromModel($field, $fieldOptions); } /** * Evaluate and validate radio field options. */ public function evalRadioOptions($field, $fieldOptions) { return $this->getOptionsFromModel($field, $fieldOptions); } /** * Evaluate and validate checkbox list field options. */ public function evalCheckboxlistOptions($field, $fieldOptions) { return $this->getOptionsFromModel($field, $fieldOptions); } /** * Looks at the model for defined options. */ private function getOptionsFromModel($field, $fieldOptions) { if (is_array($fieldOptions) && is_callable($fieldOptions)) { $fieldOptions = call_user_func($fieldOptions, $this, $field); } if (!is_array($fieldOptions) && !$fieldOptions) { $methodName = 'get'.studly_case($field->columnName).'Options'; if (!method_exists($this->model, $methodName) && !method_exists($this->model, 'getDropdownOptions')) throw new ApplicationException(Lang::get('backend::lang.field.options_method_not_exists', ['model'=>get_class($this->model), 'method'=>$methodName, 'field'=>$field->columnName])); if (method_exists($this->model, $methodName)) $fieldOptions = $this->model->$methodName($field->value); else $fieldOptions = $this->model->getDropdownOptions($field->columnName, $field->value); } elseif (is_string($fieldOptions)) { if (!method_exists($this->model, $fieldOptions)) throw new ApplicationException(Lang::get('backend::lang.field.options_method_not_exists', ['model'=>get_class($this->model), 'method'=>$fieldOptions, 'field'=>$field->columnName])); $fieldOptions = $this->model->$fieldOptions($field->value, $field->columnName); } return $fieldOptions; } /** * Returns the active session key. */ public function getSessionKey() { if ($this->sessionKey) return $this->sessionKey; if (post('_session_key')) return $this->sessionKey = post('_session_key'); return $this->sessionKey = FormHelper::getSessionKey(); } /** * Returns the active context for displaying the form. */ public function getContext() { return $this->activeContext; } }
gpl-2.0
hodorogandrei/contesteasyplatform
admiasi/include/ip2country_files/151.php
2004
<?php //- $ranges=Array( "2533359616" => array("2533375999","UA"), "2533376000" => array("2533392383","HU"), "2533392384" => array("2533425151","RO"), "2533425152" => array("2539978751","IT"), "2539978752" => array("2540240895","US"), "2540240896" => array("2540306431","FI"), "2540306432" => array("2540896255","US"), "2540896256" => array("2540961791","GB"), "2540961792" => array("2541223935","US"), "2541223936" => array("2541289471","CH"), "2541289472" => array("2541682687","US"), "2541682688" => array("2541748223","CH"), "2541748224" => array("2541813759","US"), "2541813760" => array("2541879295","GB"), "2541879296" => array("2541944831","AU"), "2541944832" => array("2542075903","US"), "2542075904" => array("2542141439","GB"), "2542141440" => array("2542206975","US"), "2542206976" => array("2542272511","TR"), "2542272512" => array("2542338047","DE"), "2542338048" => array("2543583231","US"), "2543583232" => array("2543648767","SE"), "2543648768" => array("2543714303","NO"), "2543779840" => array("2544500735","US"), "2544500736" => array("2544566271","GB"), "2544566272" => array("2544631807","US"), "2544697344" => array("2544828415","US"), "2544828416" => array("2544893951","EU"), "2544893952" => array("2544959487","GB"), "2544959488" => array("2545025023","SE"), "2545025024" => array("2545090559","AU"), "2545090560" => array("2545156095","US"), "2545156096" => array("2545221631","GB"), "2545221632" => array("2545287167","US"), "2545287168" => array("2545352703","GB"), "2545352704" => array("2545418239","CH"), "2545418240" => array("2545483775","NL"), "2545483776" => array("2545614847","US"), "2545614848" => array("2545680383","NO"), "2545680384" => array("2545745919","US"), "2545745920" => array("2545811455","DE"), "2545811456" => array("2547187711","US"), "2547187712" => array("2547318783","GB"), "2547318784" => array("2547515391","US"), "2547515392" => array("2547515399","DK"), "2547516416" => array("2547517439","CH"), "2547519488" => array("2547523583","CH"), ); ?>
gpl-2.0
mua/Radial-Engine
src/engine/rePlayer.cpp
4906
#include "rePlayer.h" #include "reBody.h" #include "btBulletDynamicsCommon.h" #include "reRadial.h" #include "reInput.h" #include "reCamera.h" #include "rePTerrain.h" #include "reNoise.h" #include "reLight.h" rePlayer::rePlayer(reBody* body) { this->body = body ? body : new reBody; add(body, true); add(camera = new rePointCamera, true); add(light = new reLight, true); light->angles(reVec3(-56,-103,0)); light->distance(6); light->farPlane(1000); //light->perspective(false); camera->angles(reVec3(-22,131,0)); camera->distance(10); camera->farPlane(1000); } rePlayer::~rePlayer() { } std::string rePlayer::className() { return "rePlayer"; } reMat4 directionalRotate(reVec3 a, reVec3 b) { return glm::rotate(reMat4(), glm::degrees(acos(glm::dot(a, b))), glm::normalize(glm::cross(a, b))); } void rePlayer::messageProcess( reMessageDispatcher* sender, reMessage* message ) { reVec3 deltaAngle(0,0,0); float rs = .5f; switch (message->id) { case reM_TIMER: if (model()) { reVec3 dirZ = reVec3(model()->worldTransform().matrix * reVec4(0,0,-1, 0)); reVec3 dirX = reVec3(model()->worldTransform().matrix * reVec4(1,0,0, 0)); if (reRadial::shared()->input()->keyStates['W']) { body->btBody->applyCentralForce(toBullet(dirZ * 50.0f)); } if (reRadial::shared()->input()->keyStates['S']) { body->btBody->applyCentralForce(toBullet(dirZ * -50.0f)); } if (reRadial::shared()->input()->keyStates[' ']) { body->btBody->applyCentralForce(toBullet(dirX * 1.0f)); //reVec4 f = worldTransform().matrix * reVec4(0,-200,0,0); //btVector3 bf(f.x, f.y, f.z); //body->btBody->applyCentralForce(bf); } if (reRadial::shared()->input()->keyStates['A']) { reVec3 v = reVec3(glm::rotate(reMat4(), rs, reVec3(0,1,0)) * reVec4(fromBullet(body->btBody->getLinearVelocity()), 0)); body->btBody->setLinearVelocity(toBullet(v)); model()->transform(glm::rotate(reMat4(), rs, reVec3(0,1,0)) * model()->transform().matrix); //body->btBody->applyCentralForce(toBullet(f)); } if (reRadial::shared()->input()->keyStates['D']) { reVec3 v = reVec3(glm::rotate(reMat4(), -rs, reVec3(0,1,0)) * reVec4(fromBullet(body->btBody->getLinearVelocity()), 0)); body->btBody->setLinearVelocity(toBullet(v)); model()->transform(glm::rotate(reMat4(), -rs, reVec3(0,1,0)) * model()->transform().matrix); //deltaAngle += reVec3(0,-1,0); //model()->transform(glm::rotate(reMat4(), -1.0f, reVec3(0,1,0)) * model()->transform().matrix); } reVec3 pos = worldTransform().position(); camera->lookAt(pos); light->lookAt(pos); if (pos.y < calculateVertex(reVec4(pos,1)).y) { //__debugbreak(); } break; } } if (glm::length(fromBullet(body->btBody->getLinearVelocity()))) { reVec3 dir = glm::normalize(fromBullet(body->btBody->getLinearVelocity())); if (!dir.z) { return; } float yaw = dir.z < 0 ? glm::atan(dir.x / dir.z) : M_PI - glm::atan(dir.x / -dir.z); float pitch = glm::atan(dir.y / abs(dir.z)); reMat4 y(glm::rotate(reMat4(), glm::degrees(yaw), reVec3(0,1,0))); reMat4 p(glm::rotate(reMat4(), glm::degrees(pitch), reVec3(1,0,0))); model()->children->at(0)->transform(p); reVec3 da = reVec3(0, glm::degrees(yaw), 0) - camera->lookAngles(); camera->lookAngles(camera->lookAngles() + da / 5.0f ); } } void rePlayer::runControl() { rePTerrain * terrain = root()->findObject<rePTerrain>(); terrain->camera = camera; terrain->player = this; btTransform t = body->btBody->getWorldTransform(); t.setOrigin(btVector3(-1195.6633, 8.5251445, -1118.4236)); //body->btBody->setWorldTransform(t); //body->btBody->setLinearVelocity(btVector3(-8.97472, -72.7783, 38.4226)/5); } void rePlayer::afterLoad() { btTransform transform; transform.setIdentity(); body->compoundShape->addChildShape(transform, new btSphereShape(0.7f)); observe(reRadial::shared()->input(), reM_KEY_PRESS); observe(reRadial::shared()->input(), reM_KEY_UP); observe(reRadial::shared(), reM_TIMER); /* btTransform transform; transform.setIdentity(); transform.setRotation(btQuaternion(0,glm::radians(90.0f),0)); transform.setOrigin(btVector3(0.3f,0,0)); body->compoundShape->addChildShape(transform, new btCapsuleShape(.3f, 1.0f)); transform.setOrigin(btVector3(-0.3f,0,0)); body->compoundShape->addChildShape(transform, new btCapsuleShape(.3f, 1.0f)); body->btBody->setCcdMotionThreshold(1e-7f); body->btBody->setCcdSweptSphereRadius(0.5f); body->btBody->setDamping(0.0f, 1.0f); body->btBody->setAnisotropicFriction(btVector3(1,0,0)); */ body->btBody->setAngularFactor(0); body->btBody->setCcdMotionThreshold(0.01); body->btBody->setCcdSweptSphereRadius(0.8f); //body->btBody->setCenterOfMassTransform(btTransform::getIdentity()); //body->btBody->setDamping(0, 100000); } reNode* rePlayer::model() { return children->count() ? children->at(0) : 0; }
gpl-2.0
oat-sa/extension-tao-delivery
controller/DeliveryServer.php
18431
<?php /** * 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; under version 2 * of the License (non-upgradable). * * 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. * * Copyright (c) 2002-2008 (original work) Public Research Centre Henri Tudor & University of Luxembourg (under the project TAO & TAO2); * 2008-2010 (update and modification) Deutsche Institut für Internationale Pädagogische Forschung (under the project TAO-TRANSFER); * 2009-2012 (update and modification) Public Research Centre Henri Tudor (under the project TAO-SUSTAIN & TAO-DEV); * */ namespace oat\taoDelivery\controller; use common_exception_NotFound; use common_exception_Unauthorized; use common_ext_Extension; use common_Logger; use common_exception_Error; use common_session_SessionManager; use core_kernel_classes_Resource; use oat\generis\model\GenerisRdf; use oat\generis\model\OntologyRdf; use oat\oatbox\event\EventManager; use oat\oatbox\service\ServiceManager; use oat\tao\model\event\LogoutSucceedEvent; use oat\tao\model\mvc\DefaultUrlService; use oat\tao\model\routing\AnnotationReader\security; use oat\taoDelivery\helper\Delivery as DeliveryHelper; use oat\taoDelivery\model\AssignmentService; use oat\taoDelivery\model\execution\DeliveryExecutionConfig; use oat\taoDelivery\model\authorization\AuthorizationService; use oat\taoDelivery\model\authorization\AuthorizationProvider; use oat\taoDelivery\model\execution\DeliveryExecution; use oat\taoDelivery\model\execution\DeliveryServerService; use oat\taoDelivery\model\execution\ServiceProxy; use oat\taoDelivery\model\fields\DeliveryFieldsService; use oat\taoDelivery\models\classes\ReturnUrlService; use oat\taoDelivery\model\authorization\UnAuthorizedException; use oat\tao\helpers\Template; use oat\taoDelivery\model\execution\StateServiceInterface; use tao_helpers_I18n; /** * DeliveryServer Controller * * @author CRP Henri Tudor - TAO Team - {@link http://www.tao.lu} * @package taoDelivery * @license GPLv2 http://www.opensource.org/licenses/gpl-2.0.php */ class DeliveryServer extends \tao_actions_CommonModule { private const PROPERTY_INTERFACE_LANGUAGE = 'http://www.tao.lu/Ontologies/TAODelivery.rdf#InterfaceLanguage'; /** * constructor: initialize the service and the default data * @security("hide") */ public function __construct() { $this->service = ServiceManager::getServiceManager()->get(DeliveryServerService::SERVICE_ID); } /** * @return DeliveryExecution */ protected function getCurrentDeliveryExecution() { $id = \tao_helpers_Uri::decode($this->getRequestParameter('deliveryExecution')); return $this->getExecutionService()->getDeliveryExecution($id); } /** * Set a view with the list of process instances (both started or finished) and available process definitions * * @access public * @author CRP Henri Tudor - TAO Team - {@link http://www.tao.lu} * @param processDefinitionUri * @return void * @throws \common_exception_Error */ public function index() { $this->resetOverwrittenLanguage(); $user = common_session_SessionManager::getSession()->getUser(); /** * Retrieve resumable deliveries (via delivery execution) */ $resumableData = []; foreach ($this->getDeliveryServer()->getResumableDeliveries($user) as $de) { $resumableData[] = DeliveryHelper::buildFromDeliveryExecution($de); } $this->setData('resumableDeliveries', $resumableData); $assignmentService = $this->getServiceLocator()->get(AssignmentService::SERVICE_ID); $deliveryData = []; foreach ($assignmentService->getAssignments($user) as $delivery) { $deliveryData[] = DeliveryHelper::buildFromAssembly($delivery, $user); } $this->setData('availableDeliveries', $deliveryData); /** * Header & footer info */ $this->setData('showControls', $this->showControls()); $this->setData('userLabel', common_session_SessionManager::getSession()->getUserLabel()); // Require JS config $this->setData('client_config_url', $this->getClientConfigUrl()); $this->setData('client_timeout', $this->getClientTimeout()); $loaderRenderer = new \Renderer(Template::getTemplate('DeliveryServer/blocks/loader.tpl', 'taoDelivery')); $loaderRenderer->setData('client_config_url', $this->getClientConfigUrl()); $loaderRenderer->setData('parameters', ['messages' => $this->getViewDataFromRequest()]); /* @var $urlRouteService DefaultUrlService */ $urlRouteService = $this->getServiceManager()->get(DefaultUrlService::SERVICE_ID); $this->setData('logout', $urlRouteService->getUrl('logoutDelivery', [])); /** * Layout template + real template inclusion */ $this->setData('additional-header', $loaderRenderer); $this->setData('content-template', 'DeliveryServer/index.tpl'); $this->setData('content-extension', 'taoDelivery'); $this->setData('title', __('TAO: Test Selection')); $this->setView('DeliveryServer/layout.tpl', 'taoDelivery'); } /** * Get data from request to be passed to renderer * @return array */ protected function getViewDataFromRequest() { $lookupParams = ['warning', 'error']; $result = []; foreach ($lookupParams as $lookupParam) { if ($this->getRequest()->hasParameter($lookupParam) && !empty($this->getRequest()->getParameter($lookupParam))) { $result[] = [ 'level' => $lookupParam, 'content' => $this->getRequest()->getParameter($lookupParam), 'timeout' => -1 ]; } } return $result; } /** * Init a delivery execution from the current delivery. * * @throws common_exception_Unauthorized * @return DeliveryExecution the selected execution * @throws \common_exception_Error */ protected function _initDeliveryExecution() { $compiledDelivery = new core_kernel_classes_Resource(\tao_helpers_Uri::decode($this->getRequestParameter('uri'))); $user = common_session_SessionManager::getSession()->getUser(); $assignmentService = $this->getServiceLocator()->get(AssignmentService::SERVICE_ID); $this->verifyDeliveryStartAuthorized($compiledDelivery->getUri()); //check if the assignment allows the user to start the delivery and the authorization provider if (!$assignmentService->isDeliveryExecutionAllowed($compiledDelivery->getUri(), $user)) { throw new common_exception_Unauthorized(); } $stateService = $this->getServiceLocator()->get(StateServiceInterface::SERVICE_ID); /** @var DeliveryExecution $deliveryExecution */ $deliveryExecution = $stateService->createDeliveryExecution($compiledDelivery->getUri(), $user, $compiledDelivery->getLabel()); return $deliveryExecution; } /** * Init the selected delivery execution and forward to the execution screen */ public function initDeliveryExecution(): void { try { $deliveryExecution = $this->_initDeliveryExecution(); //if authorized we can move to this URL. $this->redirect(_url('runDeliveryExecution', null, null, ['deliveryExecution' => $deliveryExecution->getIdentifier()])); } catch (UnAuthorizedException $e) { $this->redirect($e->getErrorPage()); } catch (common_exception_Unauthorized $e) { $this->returnJson( [ 'success' => false, 'message' => __('You are no longer allowed to take this test') ], 403 ); } } /** * Displays the execution screen * * @throws \common_Exception * @throws common_exception_Error * @throws common_exception_NotFound * @throws common_exception_Unauthorized */ public function runDeliveryExecution(): void { $deliveryExecution = $this->getCurrentDeliveryExecution(); // Sets the deliveryId to session. if (!$this->hasSessionAttribute(DeliveryExecution::getDeliveryIdSessionKey($deliveryExecution->getIdentifier()))) { $this->setSessionAttribute( DeliveryExecution::getDeliveryIdSessionKey($deliveryExecution->getIdentifier()), $deliveryExecution->getDelivery()->getUri() ); } try { $this->verifyDeliveryExecutionAuthorized($deliveryExecution); } catch (UnAuthorizedException $e) { $this->redirect($e->getErrorPage()); return; } $userUri = common_session_SessionManager::getSession()->getUserUri(); if ($deliveryExecution->getUserIdentifier() != $userUri) { throw new common_exception_Error('User ' . $userUri . ' is not the owner of the execution ' . $deliveryExecution->getIdentifier()); } $delivery = $deliveryExecution->getDelivery(); $this->initResultServer($delivery, $deliveryExecution->getIdentifier(), $userUri); $deliveryExecutionStateService = $this->getServiceManager()->get(StateServiceInterface::SERVICE_ID); $deliveryExecutionStateService->run($deliveryExecution); /** * Use particular delivery container */ $container = $this->getDeliveryServer()->getDeliveryContainer($deliveryExecution); $this->overrideInterfaceLanguage($delivery); // Require JS config $container->setData('client_config_url', $this->getClientConfigUrl()); $container->setData('client_timeout', $this->getClientTimeout()); // Delivery params $container->setData('returnUrl', $this->getReturnUrl()); $container->setData('finishUrl', $this->getfinishDeliveryExecutionUrl($deliveryExecution)); $this->setData('additional-header', $container->getContainerHeader()); $this->setData('container-body', $container->getContainerBody()); /** @var DeliveryExecutionConfig $deliveryExecutionConfig */ $deliveryExecutionConfig = $this->getServiceLocator()->get(DeliveryExecutionConfig::class); /** * Delivery header & footer info */ $this->setData('userLabel', common_session_SessionManager::getSession()->getUserLabel()); $this->setData('showControls', $this->showControls()); $this->setData('hideHomeButton', $deliveryExecutionConfig->isHomeButtonHidden()); $this->setData('hideLogoutButton', $deliveryExecutionConfig->isLogoutButtonHidden()); $this->setData('returnUrl', $this->getReturnUrl()); /* @var $urlRouteService DefaultUrlService */ $urlRouteService = $this->getServiceManager()->get(DefaultUrlService::SERVICE_ID); $this->setData('logout', $urlRouteService->getUrl('logoutDelivery', [])); /** * Layout template + real template inclusion */ $this->setData('content-template', 'DeliveryServer/runDeliveryExecution.tpl'); $this->setData('content-extension', 'taoDelivery'); $this->setData('title', $this->getDeliveryFieldsService()->getDeliveryExecutionPageTitle($delivery)); $this->setView('DeliveryServer/layout.tpl', 'taoDelivery'); } /** * Finish the delivery execution * * @throws common_exception_Error * @throws common_exception_NotFound */ public function finishDeliveryExecution() { $deliveryExecution = $this->getCurrentDeliveryExecution(); if ($deliveryExecution->getUserIdentifier() == common_session_SessionManager::getSession()->getUserUri()) { $stateService = $this->getServiceManager()->get(StateServiceInterface::SERVICE_ID); $stateService->finish($deliveryExecution); } else { common_Logger::w('Non owner ' . common_session_SessionManager::getSession()->getUserUri() . ' tried to finish deliveryExecution ' . $deliveryExecution->getIdentifier()); } $this->redirect($this->getReturnUrl()); } /** * Initialize the result server using the delivery configuration and for this results session submission * * @param $compiledDelivery * @param $executionIdentifier * @param $userUri */ protected function initResultServer($compiledDelivery, $executionIdentifier, $userUri) { $this->getDeliveryServer()->initResultServer($compiledDelivery, $executionIdentifier, $userUri); } /** * Defines if the top and bottom action menu should be displayed or not * * @return boolean */ protected function showControls() { return true; } /** * Defines the returning URL in the top-right corner action menu * * @return string * @throws common_exception_NotFound */ protected function getReturnUrl() { if ($this->getServiceLocator()->has(ReturnUrlService::SERVICE_ID)) { $deliveryExecution = $this->getCurrentDeliveryExecution(); return $this->getServiceLocator()->get(ReturnUrlService::SERVICE_ID)->getReturnUrl($deliveryExecution->getIdentifier()); } return _url('index', 'DeliveryServer', 'taoDelivery'); } /** * Defines the URL of the finish delivery execution action * @param DeliveryExecution $deliveryExecution * @return string */ protected function getfinishDeliveryExecutionUrl(DeliveryExecution $deliveryExecution) { return _url('finishDeliveryExecution', null, null, ['deliveryExecution' => $deliveryExecution->getIdentifier()]); } /** * Gives you the authorization provider for the given execution. * * @return AuthorizationProvider */ protected function getAuthorizationProvider() { $authService = $this->getServiceLocator()->get(AuthorizationService::SERVICE_ID); return $authService->getAuthorizationProvider(); } /** * Verify if the start of the delivery is allowed. * Throws an exception if not * * @param string $deliveryId * @throws UnAuthorizedException * @throws \common_exception_Error * @throws \common_exception_Unauthorized */ protected function verifyDeliveryStartAuthorized($deliveryId) { $user = common_session_SessionManager::getSession()->getUser(); $this->getAuthorizationProvider()->verifyStartAuthorization($deliveryId, $user); } /** * Check wether the delivery execution is authorized to run * Throws an exception if not * * @param DeliveryExecution $deliveryExecution * @return boolean * @throws \common_exception_Unauthorized * @throws \common_exception_Error * @throws UnAuthorizedException */ protected function verifyDeliveryExecutionAuthorized(DeliveryExecution $deliveryExecution): void { $user = common_session_SessionManager::getSession()->getUser(); $this->getAuthorizationProvider()->verifyResumeAuthorization($deliveryExecution, $user); } public function logout(): void { $eventManager = $this->getServiceLocator()->get(EventManager::SERVICE_ID); $logins = common_session_SessionManager::getSession()->getUser()->getPropertyValues(GenerisRdf::PROPERTY_USER_LOGIN); $eventManager->trigger(new LogoutSucceedEvent(current($logins))); common_session_SessionManager::endSession(); /* @var $urlRouteService DefaultUrlService */ $urlRouteService = $this->getServiceLocator()->get(DefaultUrlService::SERVICE_ID); $this->redirect($urlRouteService->getRedirectUrl('logoutDelivery')); } protected function getDeliveryServer(): DeliveryServerService { return $this->service = $this->getServiceLocator()->get(DeliveryServerService::SERVICE_ID); } protected function getExecutionService(): ServiceProxy { return ServiceProxy::singleton(); } protected function getDeliveryFieldsService(): DeliveryFieldsService { return $this->getServiceLocator()->get(DeliveryFieldsService::SERVICE_ID); } private function overrideInterfaceLanguage(core_kernel_classes_Resource $delivery): void { $deliveryLanguage = $delivery->getProperty(self::PROPERTY_INTERFACE_LANGUAGE); if (!$deliveryLanguage->exists()) { $this->resetOverwrittenLanguage(); return; } $deliveryLanguage = $delivery->getOnePropertyValue($deliveryLanguage); if (empty($deliveryLanguage)) { $this->resetOverwrittenLanguage(); return; } $resource = $delivery->getResource($deliveryLanguage); $language = (string)$resource->getOnePropertyValue( $delivery->getProperty(OntologyRdf::RDF_VALUE) ); if (empty($language)) { $this->resetOverwrittenLanguage(); return; } $this->setSessionAttribute('overrideInterfaceLanguage', $language); tao_helpers_I18n::init(new common_ext_Extension('taoDelivery'), $language); } private function resetOverwrittenLanguage(): void { if (!$this->hasSessionAttribute('overrideInterfaceLanguage')) { return; } $this->removeSessionAttribute('overrideInterfaceLanguage'); tao_helpers_I18n::init( new common_ext_Extension('taoDelivery'), common_session_SessionManager::getSession()->getInterfaceLanguage() ); } }
gpl-2.0
tuffnerdstuff/xbmc-plugins
src/plugin.video.superrtl.now/default.py
6542
import xbmcplugin import xbmcgui import sys import urllib, urllib2 import time import re from htmlentitydefs import name2codepoint as n2cp thisPlugin = int(sys.argv[1]) urlHost = "http://www.superrtlnow.de" ajaxUrl = "/xajaxuri.php" # -----regexContent------- # [0] is url (/foo.php) # [1] is name (foo is bar) # ------------------------ # -----regexSeries-------- # [0] is class even or odd # [1] is url to videourl # [2] is title # [3] is time # All content is in! # the free-content will be filtered in code (paytype) regexContent = '<div class="seriennavi_free" style=""><a href="(.*?)".*?>FREE.*?</div>.*?<div style="" class="seriennavi_link">.*?">(.*?)</a>.*?</div>' #regexSeries = '<div class="line (even|odd)"><div onclick="link\(\'(.*?)\'\); return false;".*?<a href=".*?" title=".*?">(.*?)</a>.*?class="time">(.*?</div>.*?)</div>.*?class="minibutton">(.*?)</a></div></div>' regexSeries = '<div onclick="link\(\'(.*?)\'\); return false;".*?a href=.*?>(.*?)</a> .*?class="time">.*?<div.*?/div>\s*(.*?)\s*</div>.*?class="minibutton">(.*?)</a>' regexVideoData = "data:'(.*?)'" regexXML = '<filename.*?><!\[CDATA\[(.*?)\]\]></filename>' regexTextOnly = '<\s*\/?\s*\s*.*?>' regexTabVars = '<select\s*?onchange.*?xajax_show_top_and_movies.*?\'(.*?)\'.*?\'(.*?)\'.*?\'(.*?)\'.*?\'(.*?)\'.*?\'(.*?)\'.*?>(.*?)</select>' regexTabEntry = '<option.*?value=\'(\d)\'.*?>' # ------------------------ def showContent(): global thisPlugin content = getUrl(urlHost) match = re.compile(regexContent,re.DOTALL).findall(content) for m in match: addDirectoryItem(m[1].strip(), {"urlS": m[0]}) #print m[0] print "--- showContent ok" xbmcplugin.endOfDirectory(thisPlugin) def showSeries(urlS): global thisPlugin content = getUrl(urlS) vars = re.compile(regexTabVars,re.DOTALL).search(content) if vars: tabVars = "&xajaxargs[]="+vars.group(1)+"&xajaxargs[]="+vars.group(2)+"&xajaxargs[]="+vars.group(3)+"&xajaxargs[]="+vars.group(4)+"&xajaxargs[]="+vars.group(5)+"&xajax=show_top_and_movies&xajaxr="+str(time.time()).replace('.','') tabentries = re.compile(regexTabEntry,re.DOTALL).findall(vars.group(6)) content = "" for te in tabentries: ajcon = postUrl(urlHost+ajaxUrl,"xajaxargs[]="+te+tabVars); content += ajcon; match = re.compile(regexSeries,re.DOTALL).findall(content) print match for m in match: print m if "kostenlos" in m[3]: ##xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=m[3]+" "+decode_htmlentities(m[2]), isFolder=False) addPlayableItem(decode_htmlentities(m[1])+" - "+remHTML(m[2]), {"urlV": m[0], "vidN": m[1]}) ##print m[2] print "--- showSeries ok" xbmcplugin.endOfDirectory(thisPlugin) def showVideo(urlV, vidN): print "--- showVideo" global thisPlugin print "--- "+urlV content = getUrl(urlV) match=re.compile(regexVideoData).findall(content) xmlUrl = urlHost+urllib.unquote(match[0]) #print "--- "+xmlUrl contentB = getUrl(xmlUrl) #print contentB matchfilename = re.compile(regexXML).findall(contentB) splitted = matchfilename[0].split('/') print "------DebugOutput showVideo--" print splitted # ----- videoUrl=splitted[0]+"//"+splitted[2]+"/"+splitted[3]+"/" videoUrlB=splitted[2]+"/"+splitted[3]+"/" addpre="" if splitted[5][-4:-1] == ".f4": addpre="mp4:" if splitted[5][-4:-1] == ".fl": splitted[5]=splitted[5][0:-4] playpath = addpre+splitted[4]+"/"+splitted[5] print "playPath -- "+playpath swfUrl = "http://www.superrtlnow.de/includes/vodplayer.swf" pageUrl = "http://www.superrtlnow.de/p" fullData=videoUrl+' swfVfy=1 playpath='+playpath+' app=superrtlnow/_definst_ pageUrl='+pageUrl+'/ tcUrl='+videoUrl+' swfUrl='+swfUrl print fullData print "------------" listitem = xbmcgui.ListItem(path=fullData) return xbmcplugin.setResolvedUrl(thisPlugin, True, listitem) # ------ helper ------ def remHTML(text): result = re.compile(regexTextOnly,re.DOTALL).sub('',text) return result def postUrl(url, values): req = urllib2.Request(url) response = urllib2.urlopen(req, values) link=response.read() response.close() return link def getUrl(url): req = urllib2.Request(url) response = urllib2.urlopen(req) link=response.read() response.close() return link def addDirectoryItem(name, parameters={},pic=""): li = xbmcgui.ListItem(name,iconImage="DefaultFolder.png", thumbnailImage=pic) url = sys.argv[0] + '?' + urllib.urlencode(parameters) return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=True) def addPlayableItem(name, parameters={},pic=""): li = xbmcgui.ListItem(name,iconImage="DefaultFolder.png", thumbnailImage=pic) li.setInfo( type="Video", infoLabels={ "Title": name } ) li.setProperty('IsPlayable', 'true') url = sys.argv[0] + '?' + urllib.urlencode(parameters) return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=False) def parameters_string_to_dict(parameters): ''' Convert parameters encoded in a URL to a dict. ''' paramDict = {} if parameters: paramPairs = parameters[1:].split("&") for paramsPair in paramPairs: paramSplits = paramsPair.split('=') if (len(paramSplits)) == 2: paramDict[paramSplits[0]] = paramSplits[1] return paramDict def substitute_entity(match): ent = match.group(3) if match.group(1) == "#": if match.group(2) == '': return unichr(int(ent)) elif match.group(2) == 'x': return unichr(int('0x'+ent, 16)) else: cp = n2cp.get(ent) if cp: return unichr(cp) else: return match.group() def decode_htmlentities(string): entity_re = re.compile(r'&(#?)(x?)(\w+);') return entity_re.subn(substitute_entity, string)[0] # ----- main ----- params = parameters_string_to_dict(sys.argv[2]) urlSeries = str(params.get("urlS", "")) urlVideo = str(params.get("urlV", "")) vidName = str(params.get("vidN", "")) if not sys.argv[2]: # new start ok = showContent() else: if urlSeries: newUrl = urlHost + urllib.unquote(urlSeries) print newUrl ok = showSeries(newUrl) if urlVideo: newUrl = urlHost + decode_htmlentities(urllib.unquote(urlVideo)) print newUrl ok = showVideo(newUrl, decode_htmlentities(urllib.unquote_plus(vidName)))
gpl-2.0
juancasantito/prueba
sites/default/files/php/twig/4d294ac9_node.html.twig_03ce5d4a6977aab87fc4508974010eddef7aeaa8ded52c8cab927e0c3e628518/e46307e36d5d92f8fc06ba78737c40ed97363cc2eb280aadf7b392e7bfd69b85.php
12579
<?php /* core/themes/bartik/templates/node.html.twig */ class __TwigTemplate_1204c4e91238d60e7e8fcfb5638aa80ba0a0cc176ed5a607b8f57ac950c1d3e1 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array("set" => 70, "if" => 84, "trans" => 94); $filters = array("clean_class" => 72); $functions = array("attach_library" => 80); try { $this->env->getExtension('sandbox')->checkSecurity( array('set', 'if', 'trans'), array('clean_class'), array('attach_library') ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 70 $context["classes"] = array(0 => "node", 1 => ("node--type-" . \Drupal\Component\Utility\Html::getClass($this->getAttribute( // line 72 (isset($context["node"]) ? $context["node"] : null), "bundle", array()))), 2 => (($this->getAttribute( // line 73 (isset($context["node"]) ? $context["node"] : null), "isPromoted", array(), "method")) ? ("node--promoted") : ("")), 3 => (($this->getAttribute( // line 74 (isset($context["node"]) ? $context["node"] : null), "isSticky", array(), "method")) ? ("node--sticky") : ("")), 4 => (( !$this->getAttribute( // line 75 (isset($context["node"]) ? $context["node"] : null), "isPublished", array(), "method")) ? ("node--unpublished") : ("")), 5 => (( // line 76 (isset($context["view_mode"]) ? $context["view_mode"] : null)) ? (("node--view-mode-" . \Drupal\Component\Utility\Html::getClass((isset($context["view_mode"]) ? $context["view_mode"] : null)))) : ("")), 6 => "clearfix"); // line 80 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->env->getExtension('drupal_core')->attachLibrary("classy/node"), "html", null, true)); echo " <article"; // line 81 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true)); echo "> <header> "; // line 83 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["title_prefix"]) ? $context["title_prefix"] : null), "html", null, true)); echo " "; // line 84 if ( !(isset($context["page"]) ? $context["page"] : null)) { // line 85 echo " <h2"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["title_attributes"]) ? $context["title_attributes"] : null), "addClass", array(0 => "node__title"), "method"), "html", null, true)); echo "> <a href=\""; // line 86 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["url"]) ? $context["url"] : null), "html", null, true)); echo "\" rel=\"bookmark\">"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["label"]) ? $context["label"] : null), "html", null, true)); echo "</a> </h2> "; } // line 89 echo " "; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["title_suffix"]) ? $context["title_suffix"] : null), "html", null, true)); echo " "; // line 90 if ((isset($context["display_submitted"]) ? $context["display_submitted"] : null)) { // line 91 echo " <div class=\"node__meta\"> "; // line 92 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["author_picture"]) ? $context["author_picture"] : null), "html", null, true)); echo " <span"; // line 93 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["author_attributes"]) ? $context["author_attributes"] : null), "html", null, true)); echo "> "; // line 94 echo t("Submitted by @author_name on @date", array("@author_name" => (isset($context["author_name"]) ? $context["author_name"] : null), "@date" => (isset($context["date"]) ? $context["date"] : null), )); // line 95 echo " </span> "; // line 96 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["metadata"]) ? $context["metadata"] : null), "html", null, true)); echo " </div> "; } // line 99 echo " </header> <div"; // line 100 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["content_attributes"]) ? $context["content_attributes"] : null), "addClass", array(0 => "node__content", 1 => "clearfix"), "method"), "html", null, true)); echo "> "; // line 101 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["content"]) ? $context["content"] : null), "html", null, true)); echo " </div> </article> "; } public function getTemplateName() { return "core/themes/bartik/templates/node.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 114 => 101, 110 => 100, 107 => 99, 101 => 96, 98 => 95, 96 => 94, 92 => 93, 88 => 92, 85 => 91, 83 => 90, 78 => 89, 70 => 86, 65 => 85, 63 => 84, 59 => 83, 54 => 81, 50 => 80, 48 => 76, 47 => 75, 46 => 74, 45 => 73, 44 => 72, 43 => 70,); } } /* {#*/ /* /***/ /* * @file*/ /* * Bartik's theme implementation to display a node.*/ /* **/ /* * Available variables:*/ /* * - node: The node entity with limited access to object properties and methods.*/ /* * Only method names starting with "get", "has", or "is" and a few common*/ /* * methods such as "id", "label", and "bundle" are available. For example:*/ /* * - node.getCreatedTime() will return the node creation timestamp.*/ /* * - node.hasField('field_example') returns TRUE if the node bundle includes*/ /* * field_example. (This does not indicate the presence of a value in this*/ /* * field.)*/ /* * - node.isPublished() will return whether the node is published or not.*/ /* * Calling other methods, such as node.delete(), will result in an exception.*/ /* * See \Drupal\node\Entity\Node for a full list of public properties and*/ /* * methods for the node object.*/ /* * - label: The title of the node.*/ /* * - content: All node items. Use {{ content }} to print them all,*/ /* * or print a subset such as {{ content.field_example }}. Use*/ /* * {{ content|without('field_example') }} to temporarily suppress the printing*/ /* * of a given child element.*/ /* * - author_picture: The node author user entity, rendered using the "compact"*/ /* * view mode.*/ /* * - metadata: Metadata for this node.*/ /* * - date: Themed creation date field.*/ /* * - author_name: Themed author name field.*/ /* * - url: Direct URL of the current node.*/ /* * - display_submitted: Whether submission information should be displayed.*/ /* * - attributes: HTML attributes for the containing element.*/ /* * The attributes.class element may contain one or more of the following*/ /* * classes:*/ /* * - node: The current template type (also known as a "theming hook").*/ /* * - node--type-[type]: The current node type. For example, if the node is an*/ /* * "Article" it would result in "node--type-article". Note that the machine*/ /* * name will often be in a short form of the human readable label.*/ /* * - node--view-mode-[view_mode]: The View Mode of the node; for example, a*/ /* * teaser would result in: "node--view-mode-teaser", and*/ /* * full: "node--view-mode-full".*/ /* * The following are controlled through the node publishing options.*/ /* * - node--promoted: Appears on nodes promoted to the front page.*/ /* * - node--sticky: Appears on nodes ordered above other non-sticky nodes in*/ /* * teaser listings.*/ /* * - node--unpublished: Appears on unpublished nodes visible only to site*/ /* * admins.*/ /* * - title_attributes: Same as attributes, except applied to the main title*/ /* * tag that appears in the template.*/ /* * - content_attributes: Same as attributes, except applied to the main*/ /* * content tag that appears in the template.*/ /* * - author_attributes: Same as attributes, except applied to the author of*/ /* * the node tag that appears in the template.*/ /* * - title_prefix: Additional output populated by modules, intended to be*/ /* * displayed in front of the main title tag that appears in the template.*/ /* * - title_suffix: Additional output populated by modules, intended to be*/ /* * displayed after the main title tag that appears in the template.*/ /* * - view_mode: View mode; for example, "teaser" or "full".*/ /* * - teaser: Flag for the teaser state. Will be true if view_mode is 'teaser'.*/ /* * - page: Flag for the full page state. Will be true if view_mode is 'full'.*/ /* * - readmore: Flag for more state. Will be true if the teaser content of the*/ /* * node cannot hold the main body content.*/ /* * - logged_in: Flag for authenticated user status. Will be true when the*/ /* * current user is a logged-in member.*/ /* * - is_admin: Flag for admin user status. Will be true when the current user*/ /* * is an administrator.*/ /* **/ /* * @see template_preprocess_node()*/ /* *//* */ /* #}*/ /* {%*/ /* set classes = [*/ /* 'node',*/ /* 'node--type-' ~ node.bundle|clean_class,*/ /* node.isPromoted() ? 'node--promoted',*/ /* node.isSticky() ? 'node--sticky',*/ /* not node.isPublished() ? 'node--unpublished',*/ /* view_mode ? 'node--view-mode-' ~ view_mode|clean_class,*/ /* 'clearfix',*/ /* ]*/ /* %}*/ /* {{ attach_library('classy/node') }}*/ /* <article{{ attributes.addClass(classes) }}>*/ /* <header>*/ /* {{ title_prefix }}*/ /* {% if not page %}*/ /* <h2{{ title_attributes.addClass('node__title') }}>*/ /* <a href="{{ url }}" rel="bookmark">{{ label }}</a>*/ /* </h2>*/ /* {% endif %}*/ /* {{ title_suffix }}*/ /* {% if display_submitted %}*/ /* <div class="node__meta">*/ /* {{ author_picture }}*/ /* <span{{ author_attributes }}>*/ /* {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}*/ /* </span>*/ /* {{ metadata }}*/ /* </div>*/ /* {% endif %}*/ /* </header>*/ /* <div{{ content_attributes.addClass('node__content', 'clearfix') }}>*/ /* {{ content }}*/ /* </div>*/ /* </article>*/ /* */
gpl-2.0
evamichalcak/doartystuff
wp-content/plugins/event-rocket/embedding/embed-organizers.php
2130
<?php defined( 'ABSPATH' ) or exit(); class EventRocket_EmbedOrganizersShortcode { /** * @var EventRocket_OrganizerLister */ protected $finder; /** * Sets up the [event_embed] shortcode. * * The actual shortcode name can be changed from "event_embed" to pretty much anything, using * the eventrocket_embed_events_shortcode_name filter. */ public function __construct() { $shortcode = apply_filters( 'eventrocket_embed_organizers_shortcode_name', 'organizer_embed' ); add_shortcode( $shortcode, array( $this, 'embed' ) ); } /** * Provides an alternative means of querying for events: any results that are found are * returned in an array (which may be empty, if nothing is found). * * @param array $params * @param string $content * @return array */ public function obtain( array $params, $content = '' ) { $this->embed( $params, $content ); return $this->finder->results(); } /** * Provides a programmatic means of embedding events. The output is returned as a string. * * @param array $params * @param string $content * @return string */ public function get( array $params, $content = '' ) { return $this->embed( $params, $content ); } /** * Provides a programmatic means of embedding events. The output is printed directly. * * @param array $params * @param string $content */ public function render( array $params, $content = '' ) { echo $this->embed( $params, $content ); } /** * Embedded events request and shortcode handler. * * @param $params * @param $content * @return string */ public function embed( $params, $content ) { $params = ! empty( $params ) && is_array( $params ) ? $params : array(); $content = trim( $content ); $this->finder = new EventRocket_OrganizerLister( $params, $content ); return $this->finder->output(); } } /** * @return EventRocket_EmbedVenuesShortcode */ function organizer_embed() { static $object = null; if ( null === $object ) $object = new EventRocket_EmbedOrganizersShortcode; return $object; } // Call once to ensure the [event-embed] object is created organizer_embed();
gpl-2.0
bmatusiak/repairshopr-mobile-app
www/assets/plugins/api/api.js
2877
define(function() { var pluginName = "api"; plugin.provides = [pluginName]; plugin.consumes = ["settings","user"]; return plugin; function plugin(options, imports, register) { var settings = imports.settings var user = imports.user.get; $.put = function(url, data, callback, type) { if ($.isFunction(data)) { type = type || callback, callback = data, data = {} } return $.ajax({ url: url, type: 'PUT', success: callback, data: data, contentType: type }); } $.delete = function(url, data, callback, type) { if ($.isFunction(data)) { type = type || callback, callback = data, data = {} } return $.ajax({ url: url, type: 'DELETE', success: callback, data: data, contentType: type }); } var api = { get:function(location,data,done,fail,always){ data.api_key = user().user_token; $.get("https://"+ user().subdomain+".repairshopr.com/api/v1"+location, data).done(done).fail(fail).always(always); }, put:function(location,data,done,fail,always){ data.api_key = user().user_token; $.put("https://"+ user().subdomain+".repairshopr.com/api/v1"+location, data).done(done).fail(fail).always(always); }, delete:function(location,data,done,fail,always){ data.api_key = user().user_token; $.delete("https://"+ user().subdomain+".repairshopr.com/api/v1"+location, data).done(done).fail(fail).always(always); }, post:function(location,data,done,fail,always){ data.api_key = user().user_token; $.post("https://"+ user().subdomain+".repairshopr.com/api/v1"+location, data).done(done).fail(fail).always(always); } }; api.customers = function(done,fail,always){ api.get("/customers",done,fail,always); }; api.customer = function(id,done,fail,always){ api.get("/customers/"+id,done,fail,always); }; api.tickets = function(data,done,fail,always){ api.get("/tickets",data,done,fail,always); }; api.ticket = function(number,done,fail,always){ api.get("/tickets",{ number:number },done,fail,always); }; (function() { var regObject = {}; regObject[plugin.provides[0]] = api; register(null, regObject); })(); } });
gpl-2.0
gaving/ftf
src/net/brokentrain/ftf/ui/gui/dialog/ServiceDialog.java
4743
package net.brokentrain.ftf.ui.gui.dialog; import net.brokentrain.ftf.core.services.SearchService; import net.brokentrain.ftf.core.services.WebSearchService; import net.brokentrain.ftf.ui.gui.properties.ViewServiceProperties; import net.brokentrain.ftf.ui.gui.properties.ViewWebServiceProperties; import net.brokentrain.ftf.ui.gui.util.FontUtil; import net.brokentrain.ftf.ui.gui.util.LayoutUtil; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; public class ServiceDialog extends Dialog { private static final int dialogMinWidth = 400; private SearchService service; private String title; private TabFolder tabFolder; private TabItem infoItem; public ServiceDialog(SearchService service, Shell parentShell, String title) { super(parentShell); this.title = title; this.service = service; } @Override protected void buttonPressed(int buttonId) { super.buttonPressed(buttonId); } @Override protected void configureShell(Shell shell) { shell.setLayout(LayoutUtil.createGridLayout(1, 0, 5)); shell.setText(title); shell.setSize(0, 0); } @Override protected void createButtonsForButtonBar(Composite parent) { ((GridLayout) parent.getLayout()).marginHeight = 5; ((GridLayout) parent.getLayout()).marginWidth = 10; createButton(parent, IDialogConstants.OK_ID, "OK", true).setFont( FontUtil.dialogFont); } @Override protected Control createDialogArea(Composite parent) { Composite baseComposite = (Composite) super.createDialogArea(parent); baseComposite.setLayout(LayoutUtil.createFillLayout(5, 5)); baseComposite .setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tabFolder = new TabFolder(baseComposite, SWT.TOP); tabFolder.setFont(FontUtil.dialogFont); infoItem = new TabItem(tabFolder, SWT.NONE); infoItem.setText("Information"); Composite infoContentHolder = new Composite(tabFolder, SWT.NONE); infoContentHolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); infoContentHolder.setLayout(LayoutUtil.createGridLayout(1, 5, 0)); /* View basic service properties */ new ViewServiceProperties(infoContentHolder, service); if (service instanceof WebSearchService) { TabItem webItem = new TabItem(tabFolder, SWT.NONE); webItem.setText("Web Properties"); Composite webContentHolder = new Composite(tabFolder, SWT.NONE); webContentHolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); webContentHolder.setLayout(LayoutUtil.createGridLayout(1, 5, 0)); new ViewWebServiceProperties(webContentHolder, service); webItem.setControl(webContentHolder); } infoItem.setControl(infoContentHolder); return baseComposite; } @Override protected int getShellStyle() { int style = SWT.TITLE | SWT.BORDER | SWT.RESIZE | SWT.APPLICATION_MODAL | getDefaultOrientation(); return style; } @Override protected void initializeBounds() { initializeBounds(true); } protected void initializeBounds(boolean updateLocation) { super.initializeBounds(); Point currentSize = getShell().getSize(); Point bestSize = getShell().computeSize( convertHorizontalDLUsToPixels(dialogMinWidth), SWT.DEFAULT); Point location = (updateLocation == true) ? getInitialLocation(bestSize) : getShell().getLocation(); if (bestSize.y > currentSize.y) { getShell() .setBounds(location.x, location.y, bestSize.x, bestSize.y); } getShell().setMinimumSize(bestSize.x, bestSize.y); } @Override protected void setButtonLayoutData(Button button) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); data.widthHint = Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); button.setLayoutData(data); } }
gpl-2.0
therockwee/corporate
wp-content/themes/carservice/contact_form.php
6392
<?php //contact form function cs_theme_contact_form_shortcode($atts) { extract(shortcode_atts(array( "id" => "contact_form", "top_margin" => "none", "el_class" => "" ), $atts)); $output = ""; $output .= '<form class="contact-form ' . ($top_margin!="none" ? esc_attr($top_margin) : '') . ($el_class!="" ? ' ' . esc_attr($el_class) : '') . '" id="' . esc_attr($id) . '" method="post" action="#"> <div class="vc_row wpb_row vc_inner"> <fieldset class="vc_col-sm-6 wpb_column vc_column_container"> <div class="block"> <input class="text_input" name="name" type="text" value="' . esc_html__("Your Name *", 'carservice') . '" placeholder="' . esc_html__("Your Name *", 'carservice') . '"> </div> <div class="block"> <input class="text_input" name="email" type="text" value="' . esc_html__("Your Email *", 'carservice') . '" placeholder="' . esc_html__("Your Email *", 'carservice') . '"> </div> <div class="block"> <input class="text_input" name="phone" type="text" value="' . esc_html__("Your Phone", 'carservice') . '" placeholder="' . esc_html__("Your Phone", 'carservice') . '"> </div> </fieldset> <fieldset class="vc_col-sm-6 wpb_column vc_column_container"> <div class="block"> <textarea class="margin_top_10" name="message" placeholder="' . esc_html__("Message *", 'carservice') . '">' . __("Message *", 'carservice') . '</textarea> </div> </fieldset> </div> <div class="vc_row wpb_row vc_inner margin-top-30"> <fieldset class="vc_col-sm-6 wpb_column vc_column_container"> <p>' . __("We will contact you within one business day.", 'carservice') . '</p> </fieldset> <fieldset class="vc_col-sm-6 wpb_column vc_column_container align-right"> <input type="hidden" name="action" value="theme_contact_form"> <input type="hidden" name="id" value="' . esc_attr($id) . '"> <div class="vc_row wpb_row vc_inner margin-top-20 padding-bottom-20"> <a class="more submit-contact-form" href="#" title="' . esc_html__("SEND MESSAGE", 'carservice') . '"><span>' . __("SEND MESSAGE", 'carservice') . '</span></a> </div> </fieldset> </div> </form>'; return $output; } add_shortcode("cs_contact_form", "cs_theme_contact_form_shortcode"); //visual composer function cs_theme_contact_form_vc_init() { wpb_map( array( "name" => __("Contact form", 'carservice'), "base" => "cs_contact_form", "class" => "", "controls" => "full", "show_settings_on_create" => true, "icon" => "icon-wpb-layer-contact-form", "category" => __('Carservice', 'carservice'), "params" => array( array( "type" => "textfield", "class" => "", "heading" => __("Id", 'carservice'), "param_name" => "id", "value" => "contact_form", "description" => __("Please provide unique id for each contact form on the same page/post", 'carservice') ), array( "type" => "dropdown", "class" => "", "heading" => __("Top margin", 'carservice'), "param_name" => "top_margin", "value" => array(__("None", 'carservice') => "none", __("Page (small)", 'carservice') => "page-margin-top", __("Section (large)", 'carservice') => "page-margin-top-section") ), array( 'type' => 'textfield', 'heading' => __( 'Extra class name', 'js_composer' ), 'param_name' => 'el_class', 'description' => __( 'If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.', 'js_composer' ) ) ) )); } add_action("init", "cs_theme_contact_form_vc_init"); //contact form submit function cs_theme_contact_form() { ob_start(); global $theme_options; $result = array(); $result["isOk"] = true; if($_POST["name"]!="" && $_POST["name"]!=__("Your Name *", 'carservice') && $_POST["email"]!="" && $_POST["email"]!=__("Your Email *", 'carservice') && preg_match("#^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$#", $_POST["email"]) && $_POST["message"]!="" && $_POST["message"]!=__("Message *", 'carservice')) { $values = array( "name" => $_POST["name"], "phone" => ($_POST["phone"]!=__("Your Phone", 'carservice') ? $_POST["phone"] : ""), "email" => $_POST["email"], "message" => $_POST["message"] ); if((bool)ini_get("magic_quotes_gpc")) $values = array_map("stripslashes", $values); $values = array_map("htmlspecialchars", $values); $headers[] = 'From: ' . $values["name"] . ' <' . $values["email"] . '>' . "\r\n"; $headers[] = 'Content-type: text/html'; $subject = $theme_options["cf_email_subject"]; $subject = str_replace("[name]", $values["name"], $subject); $subject = str_replace("[email]", $values["email"], $subject); $subject = str_replace("[phone]", $values["phone"], $subject); $subject = str_replace("[message]", $values["message"], $subject); $body = $theme_options["cf_template"]; $body = str_replace("[name]", $values["name"], $body); $body = str_replace("[email]", $values["email"], $body); $body = str_replace("[phone]", $values["phone"], $body); $body = str_replace("[message]", $values["message"], $body); $body = str_replace("[form_data]", "", $body); if(wp_mail($theme_options["cf_admin_name"] . ' <' . $theme_options["cf_admin_email"] . '>', $subject, $body, $headers)) $result["submit_message"] = __("Thank you for contacting us", 'carservice'); else { $result["isOk"] = false; $result["submit_message"] = __("Sorry, we can't send this message", 'carservice'); } } else { $result["isOk"] = false; if($_POST["name"]=="" || $_POST["name"]==__("Your Name *", 'carservice')) $result["error_name"] = __("Please enter your name.", 'carservice'); if($_POST["email"]=="" || $_POST["email"]==__("Your Email *", 'carservice') || !preg_match("#^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$#", $_POST["email"])) $result["error_email"] = __("Please enter valid e-mail.", 'carservice'); if($_POST["message"]=="" || $_POST["message"]==__("Message *", 'carservice')) $result["error_message"] = __("Please enter your message.", 'carservice'); } $system_message = ob_get_clean(); $result["system_message"] = $system_message; echo @json_encode($result); exit(); } add_action("wp_ajax_theme_contact_form", "cs_theme_contact_form"); add_action("wp_ajax_nopriv_theme_contact_form", "cs_theme_contact_form"); ?>
gpl-2.0
arkev/IntelligentMode
wp-content/themes/florida-wp/inc/shortcodes/doublepromo.php
969
<?php // Picture Box function webnus_doublepromo( $attributes, $content = null ) { extract(shortcode_atts(array( "title" => '', "text" => '', "link_text" =>'', "link_link" =>'#', "img" =>'', "img_alt" =>'', "last" =>'', ), $attributes)); if(is_numeric($img)){ $img = wp_get_attachment_url( $img ); } $out = '<article class="dpromo col-md-6 ' . (( 'true' == $last)?'dpromo2 omega':'') . '">'; $out .= '<div class="'.(( 'true' == $last )?'brdr-l1 pad-l40':'pad-r10').'">'; $out .= '<h4><strong>' . $title . '</strong></h4>'; $out .= '<img src="' . $img . '" class="alignright" alt="' . $img_alt . '">'; $out .= '<p>' . $text . '</p>'; if(!empty($link_link) && !empty($link_text)) $out .= '<a href="' . $link_link . '" class="magicmore">' . $link_text . '</a>'; $out .= '</div>'; $out .= '</article>'; return $out; } add_shortcode('doublepromo', 'webnus_doublepromo'); ?>
gpl-2.0
hsgui/interest-only
euler/83_path_sum_four_ways.cpp
2398
#include<stdio.h> #include<stdlib.h> #include<queue> #include<vector> #include<utility> class Item{ public: int priority; int row; int column; Item(int priority, int row, int column): priority(priority), row(row), column(column){} }; class ItemComparer{ public: bool operator() (const Item& l, const Item& r) const{ return l.priority > r.priority; } }; /* https://projecteuler.net/problem=82 */ void PathSumFourWays_83() { int row = 80, column = 80; int i, j; int matrix[row][column]; // read data from file for (i=0; i < row; i++) for (j = 0; j < column; j++){ if (j < column - 1) scanf("%d,", &matrix[i][j]); else scanf("%d", &matrix[i][j]); } // initial all values to undefined; int minimal[row][column]; for (i = 0; i < row; i++){ for (j = 0; j < column; j++){ minimal[i][j] = -1; } } std::priority_queue<Item, std::vector<Item>, ItemComparer> pq; Item start(matrix[0][0], 0, 0); Item end(-1, row-1, column-1); minimal[start.row][start.column] = matrix[start.row][start.column]; pq.push(start); int priority; std::pair<int, int> direction; std::vector<std::pair<int, int>> directions; std::pair<int, int> up(0, -1); std::pair<int, int> down(0, 1); std::pair<int, int> left(-1, 0); std::pair<int, int> right(1, 0); directions.push_back(up); directions.push_back(down); directions.push_back(left); directions.push_back(right); while (!pq.empty()){ Item item = pq.top(); pq.pop(); if (item.row == end.row && item.column == end.column) break; for (std::vector<std::pair<int, int>>::iterator it = directions.begin(); it != directions.end(); it++){ direction = *it; int r = item.row + direction.first; int c = item.column + direction.second; if (r >=0 && r < row && c >= 0 && c < column){ priority = item.priority + matrix[r][c]; // if the point is not seem ever or has larger priority if (minimal[r][c] == -1 || minimal[r][c] > priority){ minimal[r][c] = priority; Item i(priority, r, c); // same items with different priorities may exist in pq; // but it will affect the final result pq.push(i); } } } } printf("%d\n", minimal[end.row][end.column]); } int main() { PathSumFourWays_83(); }
gpl-2.0
TheTypoMaster/Scaper
openjdk/corba/src/share/classes/com/sun/corba/se/pept/transport/ConnectionCache.java
1578
/* * Copyright 2001-2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.corba.se.pept.transport; /** * @author Harold Carr */ public interface ConnectionCache { public String getCacheType(); public void stampTime(Connection connection); public long numberOfConnections(); public long numberOfIdleConnections(); public long numberOfBusyConnections(); public boolean reclaim(); } // End of file.
gpl-2.0
linusmotu/Viaje
ViajeUi/src/com/viaje/main/CreatePopupMenu.java
35667
package com.viaje.main; import java.util.Calendar; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.otpxmlgetterUI.UtilsUI; import com.viaje.main.R; import com.viaje.webinterface.JSONWebInterface; /* 20130914 Pop Up menu button is clicked */ public class CreatePopupMenu extends UiMainActivity implements OnClickListener { Context mContext; UiMainActivity mUiMainActivity; Activity mActivity; private PopupWindow popupMenu; private PopupWindow popupCollision; private PopupWindow popupFlood; private PopupWindow popupTraffic; private PopupWindow popupSectionBlock; private PopupWindow popupCrime; private PopupWindow popupConstruction; private boolean PopUpMenuIsShowing = false; private RelativeLayout viewGroupLocation = null; private Button btn_heavy; private Button btn_standstill; private Button btn_minor_collision; private Button btn_major_collision; private Button btn_patv; private Button btn_nplv; private Button btn_npav; private Button btn_moderate; private Button btn_report_collision; private Button btn_report_flood; private Button btn_report_traffic; private Button btn_report_block; private Button btn_report_construction; private Button btn_report_crime; private SharedPreferences settings; private String currentLocation; private String latitude; private String longitude; private int userId; private int hour; private int minute; private int am_pm; private double lat; private double lon; private String username; public CreatePopupMenu(Context context, Activity activity) { this.mContext = context; //this.mUiMainActivity = uiMainActivity; this.mActivity = activity; } public void showPopup() { System.out.println("viaje show popup menu"); /* Flag to indicate that popup window is showing */ setPopUpMenuIsShowing(true); /* Hide enter location when popup is shown */ viewGroupLocation = (RelativeLayout) mActivity.findViewById(R.id.enter_location_field); if(viewGroupLocation != null) { viewGroupLocation.setVisibility(View.GONE); } new JSONWebInterface(); /* Get coordinates from Pref */ settings = mContext.getSharedPreferences("ViajePrefs", Context.MODE_PRIVATE); userId = settings.getInt("userId", -1); currentLocation = settings.getString("CurrentLocation", "unknown"); latitude = settings.getString("Latitude", "0.0"); longitude = settings.getString("Longitude", "0.0"); lat = Double.parseDouble(latitude); lon = Double.parseDouble(longitude); Calendar c = Calendar.getInstance(); hour = c.get(Calendar.HOUR); minute = c.get(Calendar.MINUTE); am_pm = c.get(Calendar.AM_PM); username = settings.getString("username", ""); /* TODO modify animation of popup window */ RelativeLayout viewGroup = (RelativeLayout) mActivity.findViewById(R.id.layout_report_incident); LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View reportIncidentLayout = layoutInflater.inflate(R.layout.activity_show_report_incident_pop_up, viewGroup); popupMenu = new PopupWindow(mContext); popupMenu.setContentView(reportIncidentLayout); popupMenu.setBackgroundDrawable(new ColorDrawable(0)); popupMenu.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); //popupMenu.setFocusable(true); /* When this is set to TRUE, popup window is dismissed when user clicks outside window */ popupMenu.showAtLocation(reportIncidentLayout, Gravity.CENTER, 0, 0); popupMenu.setOutsideTouchable(false); /* Report Incident click */ ImageButton close = (ImageButton) reportIncidentLayout.findViewById(R.id.button_close); close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { popupMenu.dismiss(); if(viewGroupLocation != null) { viewGroupLocation.setVisibility(View.VISIBLE); } setPopUpMenuIsShowing(false); } }); Button construction = (Button) reportIncidentLayout.findViewById(R.id.button_construction); Button collision = (Button) reportIncidentLayout.findViewById(R.id.button_collision); Button crime = (Button) reportIncidentLayout.findViewById(R.id.button_crime); Button flood = (Button) reportIncidentLayout.findViewById(R.id.button_flood); Button traffic = (Button) reportIncidentLayout.findViewById(R.id.button_traffic); Button roadblock = (Button) reportIncidentLayout.findViewById(R.id.button_roadblock); construction.setOnClickListener(this); collision.setOnClickListener(this); crime.setOnClickListener(this); flood.setOnClickListener(this); traffic.setOnClickListener(this); roadblock.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_collision: //Toast.makeText(mContext, "collision", Toast.LENGTH_SHORT).show(); closeMainPopUp(); showCollisionPopUpWindow(); break; case R.id.button_construction: //Toast.makeText(mContext, "construction", Toast.LENGTH_SHORT).show(); closeMainPopUp(); showConstructionPopUpWindow(); break; case R.id.button_crime: //Toast.makeText(mContext, "crime", Toast.LENGTH_SHORT).show(); closeMainPopUp(); showCrimeBlockPopUpWindow(); break; case R.id.button_flood: //Toast.makeText(mContext, "flood", Toast.LENGTH_SHORT).show(); closeMainPopUp(); showFloodPopUpWindow(); break; case R.id.button_traffic: //Toast.makeText(mContext, "traffic", Toast.LENGTH_SHORT).show(); closeMainPopUp(); showTrafficPopUpWindow(); break; case R.id.button_roadblock: //Toast.makeText(mContext, "roadblock", Toast.LENGTH_SHORT).show(); closeMainPopUp(); showSectionBlockBlockPopUpWindow(); break; } //Go to report incident layout? } /* Use setContentView(View contentView) to change content of popup window */ /* 20130914 Pop Up Window button is clicked */ public void showCollisionPopUpWindow() { /* TODO modify animation of popup window */ RelativeLayout viewGroupCollision = (RelativeLayout) mActivity.findViewById(R.id.layout_report_collision); LayoutInflater layoutInflaterCollision = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View reportCollisionLayout = layoutInflaterCollision.inflate(R.layout.popupwindow_collision, viewGroupCollision); popupCollision = new PopupWindow(mContext); popupCollision.setContentView(reportCollisionLayout); popupCollision.setBackgroundDrawable(new ColorDrawable(0)); popupCollision.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupCollision.showAtLocation(reportCollisionLayout, Gravity.CENTER, 0, 0); popupCollision.setOutsideTouchable(false); TextView location = (TextView) reportCollisionLayout.findViewById(R.id.location); location.setText(currentLocation); location.postInvalidate(); TextView time = (TextView) reportCollisionLayout.findViewById(R.id.time); String new_minute; if(minute < 10) { new_minute = "0" + Integer.toString(minute); } else { new_minute = Integer.toString(minute); } time.setText(Integer.toString(hour) + ":" + new_minute + (am_pm == 1 ? " pm" : " am")); btn_report_collision = (Button) reportCollisionLayout.findViewById(R.id.button_send); btn_report_collision.setEnabled(false); final TextView txt_collision_title = (TextView) reportCollisionLayout.findViewById(R.id.ReportTitle); btn_minor_collision = (Button) reportCollisionLayout.findViewById(R.id.button_collision_minor); btn_minor_collision.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); /* Set text to minor collision */ Button otherButton = (Button)reportCollisionLayout.findViewById(R.id.button_collision_major); if (otherButton.isSelected()) { otherButton.setSelected(false); } if (btn_minor_collision.isSelected()) { txt_collision_title.setText("Collision"); btn_minor_collision.setSelected(false); btn_report_collision.setEnabled(false); } else{ txt_collision_title.setText("Minor Collision"); btn_minor_collision.setSelected(true); btn_report_collision.setEnabled(true); } } }); btn_major_collision = (Button) reportCollisionLayout.findViewById(R.id.button_collision_major); btn_major_collision.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); /* Set text to minor collision */ Button otherButton = (Button)reportCollisionLayout.findViewById(R.id.button_collision_minor); if (otherButton.isSelected()) { otherButton.setSelected(false); } if (btn_major_collision.isSelected()) { txt_collision_title.setText("Collision"); btn_major_collision.setSelected(false); btn_report_collision.setEnabled(false); } else{ txt_collision_title.setText("Major Collision"); btn_major_collision.setSelected(true); btn_report_collision.setEnabled(true); } } }); btn_report_collision.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ closePopup(); setPopUpMenuIsShowing(false); ReportIncidentTask report = new ReportIncidentTask(userId, "incident", lat, lon, currentLocation, txt_collision_title.getText().toString()); report.execute(); } }); Button btn_cancel = (Button) reportCollisionLayout.findViewById(R.id.button_cancel); btn_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ returnPopUpWhenCancel(); } }); } /* 20130914 Pop Up Window button is clicked */ public void showFloodPopUpWindow() { /* TODO modify animation of popup window */ RelativeLayout viewGroupFlood = (RelativeLayout) mActivity.findViewById(R.id.layout_report_flood); LayoutInflater layoutInflaterFlood = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View reportFloodLayout = layoutInflaterFlood.inflate(R.layout.popupwindow_flood, viewGroupFlood); popupFlood = new PopupWindow(mContext); popupFlood.setContentView(reportFloodLayout); popupFlood.setBackgroundDrawable(new ColorDrawable(0)); popupFlood.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupFlood.showAtLocation(reportFloodLayout, Gravity.CENTER, 0, 0); popupFlood.setOutsideTouchable(false); TextView location = (TextView) reportFloodLayout.findViewById(R.id.location); location.setText(currentLocation); location.postInvalidate(); TextView time = (TextView) reportFloodLayout.findViewById(R.id.time); String new_minute; if(minute < 10) { new_minute = "0" + Integer.toString(minute); } else { new_minute = Integer.toString(minute); } time.setText(Integer.toString(hour) + ":" + new_minute + (am_pm == 1 ? " pm" : " am")); btn_report_flood = (Button) reportFloodLayout.findViewById(R.id.button_send); btn_report_flood.setEnabled(false); final TextView txt_flood_title = (TextView) reportFloodLayout.findViewById(R.id.ReportTitle); btn_patv = (Button) reportFloodLayout.findViewById(R.id.button_patv); btn_patv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportFloodLayout.findViewById(R.id.button_nplv); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportFloodLayout.findViewById(R.id.button_npav); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_patv.isSelected()) { txt_flood_title.setText("Flood"); btn_patv.setSelected(false); btn_report_flood.setEnabled(false); } else{ txt_flood_title.setText("PATV Flood"); btn_patv.setSelected(true); btn_report_flood.setEnabled(true); } } }); btn_nplv = (Button) reportFloodLayout.findViewById(R.id.button_nplv); btn_nplv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportFloodLayout.findViewById(R.id.button_patv); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportFloodLayout.findViewById(R.id.button_npav); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_nplv.isSelected()) { txt_flood_title.setText("Flood"); btn_nplv.setSelected(false); btn_report_flood.setEnabled(false); } else{ txt_flood_title.setText("NPLV Flood"); btn_nplv.setSelected(true); btn_report_flood.setEnabled(true); } } }); btn_npav = (Button) reportFloodLayout.findViewById(R.id.button_npav); btn_npav.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportFloodLayout.findViewById(R.id.button_patv); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportFloodLayout.findViewById(R.id.button_nplv); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_npav.isSelected()) { txt_flood_title.setText("Flood"); btn_npav.setSelected(false); v.setEnabled(false); } else{ txt_flood_title.setText("NPAV Flood"); btn_npav.setSelected(true); btn_report_flood.setEnabled(true); } } }); btn_report_flood.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ closePopup(); setPopUpMenuIsShowing(false); ReportIncidentTask report = new ReportIncidentTask(userId, "incident", lat, lon, currentLocation, txt_flood_title.getText().toString()); report.execute(); } }); Button btn_cancel = (Button) reportFloodLayout.findViewById(R.id.button_cancel); btn_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ returnPopUpWhenCancel(); } }); } /* 20130914 Pop Up Window button is clicked */ public void showTrafficPopUpWindow() { /* TODO modify animation of popup window */ RelativeLayout viewGroupTraffic = (RelativeLayout) mActivity.findViewById(R.id.layout_report_traffic); LayoutInflater layoutInflaterTraffic = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View reportTrafficLayout = layoutInflaterTraffic.inflate(R.layout.popupwindow_traffic, viewGroupTraffic); popupTraffic = new PopupWindow(mContext); popupTraffic.setContentView(reportTrafficLayout); popupTraffic.setBackgroundDrawable(new ColorDrawable(0)); popupTraffic.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupTraffic.showAtLocation(reportTrafficLayout, Gravity.CENTER, 0, 0); popupTraffic.setOutsideTouchable(false); TextView location = (TextView) reportTrafficLayout.findViewById(R.id.location); location.setText(currentLocation); location.postInvalidate(); TextView time = (TextView) reportTrafficLayout.findViewById(R.id.time); String new_minute; if(minute < 10) { new_minute = "0" + Integer.toString(minute); } else { new_minute = Integer.toString(minute); } time.setText(Integer.toString(hour) + ":" + new_minute + (am_pm == 1 ? " pm" : " am")); btn_report_traffic = (Button) reportTrafficLayout.findViewById(R.id.button_send); btn_report_traffic.setEnabled(false); final TextView txt_traffic_title = (TextView) reportTrafficLayout.findViewById(R.id.ReportTitle); btn_moderate = (Button) reportTrafficLayout.findViewById(R.id.button_moderate); btn_moderate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportTrafficLayout.findViewById(R.id.button_heavy); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportTrafficLayout.findViewById(R.id.button_standstill); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_moderate.isSelected()) { txt_traffic_title.setText("Traffic"); btn_moderate.setSelected(false); btn_report_traffic.setEnabled(false); } else{ txt_traffic_title.setText("Moderate Traffic"); btn_moderate.setSelected(true); btn_report_traffic.setEnabled(true); } } }); btn_heavy = (Button) reportTrafficLayout.findViewById(R.id.button_heavy); btn_heavy.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportTrafficLayout.findViewById(R.id.button_moderate); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportTrafficLayout.findViewById(R.id.button_standstill); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_heavy.isSelected()) { txt_traffic_title.setText("Traffic"); btn_heavy.setSelected(false); btn_report_traffic.setEnabled(false); } else{ txt_traffic_title.setText("Heavy Traffic"); btn_heavy.setSelected(true); btn_report_traffic.setEnabled(true); } } }); btn_standstill = (Button) reportTrafficLayout.findViewById(R.id.button_standstill); btn_standstill.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportTrafficLayout.findViewById(R.id.button_moderate); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportTrafficLayout.findViewById(R.id.button_heavy); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_standstill.isSelected()) { txt_traffic_title.setText("Traffic"); btn_standstill.setSelected(false); btn_report_traffic.setEnabled(false); } else{ txt_traffic_title.setText("Standstill Traffic"); btn_standstill.setSelected(true); btn_report_traffic.setEnabled(true); } } }); btn_report_traffic = (Button) reportTrafficLayout.findViewById(R.id.button_send); btn_report_traffic.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ closePopup(); setPopUpMenuIsShowing(false); ReportIncidentTask report = new ReportIncidentTask(userId, "incident", lat, lon, currentLocation, txt_traffic_title.getText().toString()); report.execute(); /* Send report in background */ } }); Button btn_cancel = (Button) reportTrafficLayout.findViewById(R.id.button_cancel); btn_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ returnPopUpWhenCancel(); } }); } public void showSectionBlockBlockPopUpWindow() { /* TODO modify animation of popup window */ RelativeLayout viewGroupSectionBlock = (RelativeLayout) mActivity.findViewById(R.id.layout_report_road_block); LayoutInflater layoutInflaterSectionBlock = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View reportSectionBlockLayout = layoutInflaterSectionBlock.inflate(R.layout.popupwindow_roadblock, viewGroupSectionBlock); popupSectionBlock = new PopupWindow(mContext); popupSectionBlock.setContentView(reportSectionBlockLayout); popupSectionBlock.setBackgroundDrawable(new ColorDrawable(0)); popupSectionBlock.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupSectionBlock.showAtLocation(reportSectionBlockLayout, Gravity.CENTER, 0, 0); popupSectionBlock.setOutsideTouchable(false); TextView location = (TextView) reportSectionBlockLayout.findViewById(R.id.location); location.setText(currentLocation); location.postInvalidate(); TextView time = (TextView) reportSectionBlockLayout.findViewById(R.id.time); String new_minute; if(minute < 10) { new_minute = "0" + Integer.toString(minute); } else { new_minute = Integer.toString(minute); } time.setText(Integer.toString(hour) + ":" + new_minute + (am_pm == 1 ? " pm" : " am")); btn_report_block = (Button) reportSectionBlockLayout.findViewById(R.id.button_send); btn_report_block.setEnabled(false); final TextView txt_traffic_title = (TextView) reportSectionBlockLayout.findViewById(R.id.ReportTitle); final Button btn_one = (Button) reportSectionBlockLayout.findViewById(R.id.button_block_lane_1); btn_one.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportSectionBlockLayout.findViewById(R.id.button_block_lane_2); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportSectionBlockLayout.findViewById(R.id.button_block_lane_3); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_one.isSelected()) { txt_traffic_title.setText("No. of Lanes Blocked"); btn_one.setSelected(false); btn_report_block.setEnabled(false); } else{ txt_traffic_title.setText("One Lane Blocked"); btn_one.setSelected(true); btn_report_block.setEnabled(true); } } }); final Button btn_two = (Button) reportSectionBlockLayout.findViewById(R.id.button_block_lane_2); btn_two.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportSectionBlockLayout.findViewById(R.id.button_block_lane_1); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportSectionBlockLayout.findViewById(R.id.button_block_lane_3); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_two.isSelected()) { txt_traffic_title.setText("No. of Lanes Blocked"); btn_two.setSelected(false); btn_report_block.setEnabled(false); } else{ txt_traffic_title.setText("Two Lanes Blocked"); btn_two.setSelected(true); btn_report_block.setEnabled(true); } } }); final Button btn_three = (Button) reportSectionBlockLayout.findViewById(R.id.button_block_lane_3); btn_three.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportSectionBlockLayout.findViewById(R.id.button_block_lane_1); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportSectionBlockLayout.findViewById(R.id.button_block_lane_2); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_three.isSelected()) { txt_traffic_title.setText("No. of Lanes Blocked"); btn_three.setSelected(false); btn_report_block.setEnabled(false); } else{ /* 20130929 */ txt_traffic_title.setText("More Lanes Blocked"); btn_three.setSelected(true); btn_report_block.setEnabled(true); } } }); btn_report_block.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ closePopup(); setPopUpMenuIsShowing(false); ReportIncidentTask report = new ReportIncidentTask(userId, "incident", lat, lon, currentLocation, txt_traffic_title.getText().toString()); report.execute(); /* Send report in background */ } }); Button btn_cancel = (Button) reportSectionBlockLayout.findViewById(R.id.button_cancel); btn_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ returnPopUpWhenCancel(); } }); } public void showConstructionPopUpWindow() { /* TODO modify animation of popup window */ RelativeLayout viewGroupConstruction = (RelativeLayout) mActivity.findViewById(R.id.layout_report_construction); LayoutInflater layoutInflaterConstruction = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View reportConstructionLayout = layoutInflaterConstruction.inflate(R.layout.popupwindow_construction, viewGroupConstruction); popupConstruction = new PopupWindow(mContext); popupConstruction.setContentView(reportConstructionLayout); popupConstruction.setBackgroundDrawable(new ColorDrawable(0)); popupConstruction.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupConstruction.showAtLocation(reportConstructionLayout, Gravity.CENTER, 0, 0); popupConstruction.setOutsideTouchable(false); TextView location = (TextView) reportConstructionLayout.findViewById(R.id.location); location.setText(currentLocation); location.postInvalidate(); TextView time = (TextView) reportConstructionLayout.findViewById(R.id.time); String new_minute; if(minute < 10) { new_minute = "0" + Integer.toString(minute); } else { new_minute = Integer.toString(minute); } time.setText(Integer.toString(hour) + ":" + new_minute + (am_pm == 1 ? " pm" : " am")); btn_report_construction= (Button) reportConstructionLayout.findViewById(R.id.button_send); btn_report_construction.setEnabled(false); final TextView txt_traffic_title = (TextView) reportConstructionLayout.findViewById(R.id.ReportTitle); final Button btn_street_light = (Button) reportConstructionLayout.findViewById(R.id.button_street_light); btn_street_light.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportConstructionLayout.findViewById(R.id.button_traffic_light); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportConstructionLayout.findViewById(R.id.button_bumpy_road); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_street_light.isSelected()) { txt_traffic_title.setText("Construction"); btn_street_light.setSelected(false); btn_report_construction.setEnabled(false); } else{ txt_traffic_title.setText("Fix Street Light"); btn_street_light.setSelected(true); btn_report_construction.setEnabled(true); } } }); final Button btn_traffic_light = (Button) reportConstructionLayout.findViewById(R.id.button_traffic_light); btn_traffic_light.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportConstructionLayout.findViewById(R.id.button_street_light); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportConstructionLayout.findViewById(R.id.button_bumpy_road); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_traffic_light.isSelected()) { txt_traffic_title.setText("Construction"); btn_traffic_light.setSelected(false); btn_report_construction.setEnabled(false); } else{ txt_traffic_title.setText("Fix Traffic Light"); btn_traffic_light.setSelected(true); btn_report_construction.setEnabled(true); } } }); final Button btn_bumpy_road = (Button) reportConstructionLayout.findViewById(R.id.button_bumpy_road); btn_bumpy_road.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //popupCollision.dismiss(); Button otherButton1 = (Button)reportConstructionLayout.findViewById(R.id.button_street_light); if (otherButton1.isSelected()) { otherButton1.setSelected(false); } Button otherButton2 = (Button)reportConstructionLayout.findViewById(R.id.button_traffic_light); if (otherButton2.isSelected()) { otherButton2.setSelected(false); } if (btn_bumpy_road.isSelected()) { txt_traffic_title.setText("Construction"); btn_bumpy_road.setSelected(false); btn_report_construction.setEnabled(false); } else{ txt_traffic_title.setText("Fix Road"); btn_bumpy_road.setSelected(true); btn_report_construction.setEnabled(true); } } }); btn_report_construction.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ closePopup(); setPopUpMenuIsShowing(false); ReportIncidentTask report = new ReportIncidentTask(userId, "incident", lat, lon, currentLocation, txt_traffic_title.getText().toString()); report.execute(); /* Send report in background */ } }); Button btn_cancel = (Button) reportConstructionLayout.findViewById(R.id.button_cancel); btn_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ returnPopUpWhenCancel(); } }); } public void showCrimeBlockPopUpWindow() { /* TODO modify animation of popup window */ RelativeLayout viewGroupCrime = (RelativeLayout) mActivity.findViewById(R.id.layout_report_crime); LayoutInflater layoutInflaterCrime = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View reportCrimeLayout = layoutInflaterCrime.inflate(R.layout.popupwindow_crime, viewGroupCrime); popupCrime = new PopupWindow(mContext); popupCrime.setContentView(reportCrimeLayout); popupCrime.setBackgroundDrawable(new ColorDrawable(0)); popupCrime.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupCrime.showAtLocation(reportCrimeLayout, Gravity.CENTER, 0, 0); popupCrime.setOutsideTouchable(false); TextView location = (TextView) reportCrimeLayout.findViewById(R.id.location); location.setText(currentLocation); location.postInvalidate(); TextView time = (TextView) reportCrimeLayout.findViewById(R.id.time); String new_minute; if(minute < 10) { new_minute = "0" + Integer.toString(minute); } else { new_minute = Integer.toString(minute); } time.setText(Integer.toString(hour) + ":" + new_minute + (am_pm == 1 ? " pm" : " am")); btn_report_crime = (Button) reportCrimeLayout.findViewById(R.id.button_send); btn_report_crime.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ closePopup(); setPopUpMenuIsShowing(false); ReportIncidentTask report = new ReportIncidentTask(userId, "report", lat, lon, currentLocation, "HELP"); report.execute(); /* Send report in background */ } }); Button btn_cancel = (Button) reportCrimeLayout.findViewById(R.id.button_cancel); btn_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Close pop up */ returnPopUpWhenCancel(); } }); } public void closePopup() { closeEnterLocationView(); closeMainPopUp(); //Should close all other children as well if(popupTraffic != null) { popupTraffic.dismiss(); } if(popupCollision != null) { popupCollision.dismiss(); } if(popupFlood != null) { popupFlood.dismiss(); } if(popupSectionBlock!= null){ popupSectionBlock.dismiss(); } if(popupCrime != null){ popupCrime.dismiss(); } if (popupConstruction != null){ popupConstruction.dismiss(); } setPopUpMenuIsShowing(false); } public void returnPopUpWhenCancel(){ if(popupTraffic != null) { popupTraffic.dismiss(); } if(popupCollision != null) { popupCollision.dismiss(); } if(popupFlood != null) { popupFlood.dismiss(); } if(popupSectionBlock!= null){ popupSectionBlock.dismiss(); } if(popupCrime != null){ popupCrime.dismiss(); } if (popupConstruction != null){ popupConstruction.dismiss(); } showPopup(); } public void closeMainPopUp(){ if (popupMenu != null) { popupMenu.dismiss(); } } public boolean isPopUpMenuIsShowing() { return PopUpMenuIsShowing; } public void setPopUpMenuIsShowing(boolean popUpMenuIsShowing) { PopUpMenuIsShowing = popUpMenuIsShowing; } public void closeEnterLocationView(){ if(viewGroupLocation != null) { viewGroupLocation.setVisibility(View.VISIBLE); } } class ReportIncidentTask extends AsyncTask<Void, Void, String> { int userId; String type; double lat; double lon; String location; String desc; public ReportIncidentTask(int userId, String type, double lat, double lon, String location, String desc) { this.userId = userId; this.type = type; this.lat = lat; this.lon = lon; this.location = location; this.desc = desc; } @Override protected String doInBackground(Void... params) { UtilsUI util = new UtilsUI(); String str; JSONWebInterface webInterface = new JSONWebInterface(); if(util.isNetworkAvailable(mContext)) { str = webInterface.sendPostReportRequest(userId, "incident", lat, lon, location, desc, username); } else { Toast.makeText(mContext, "No network connection", Toast.LENGTH_SHORT).show(); str = ""; } return str; } @Override protected void onPostExecute(String result) { // } } }
gpl-2.0
Huluzai/DoonSketch
inkscape-0.48.5/src/ui/dialog/glyphs.cpp
36006
/** * Glyph selector dialog. */ /* Authors: * Jon A. Cruz * * Copyright (C) 2010 Jon A. Cruz * Released under GNU GPL, read the file 'COPYING' for more information */ #include <vector> #include <glibmm/i18n.h> #include <gtkmm/entry.h> #include <gtkmm/iconview.h> #include <gtkmm/label.h> #include <gtkmm/liststore.h> #include <gtkmm/scrolledwindow.h> #include <gtkmm/table.h> #include <gtkmm/treemodelcolumn.h> #include <gtkmm/widget.h> #include <gtk/gtk.h> #include "glyphs.h" #include "desktop.h" #include "document.h" // for sp_document_done() #include "libnrtype/font-instance.h" #include "sp-flowtext.h" #include "sp-text.h" #include "verbs.h" #include "widgets/font-selector.h" #include "text-editing.h" namespace Inkscape { namespace UI { namespace Dialog { GlyphsPanel &GlyphsPanel::getInstance() { return *new GlyphsPanel(); } #if GLIB_CHECK_VERSION(2,14,0) static std::map<GUnicodeScript, Glib::ustring> & getScriptToName() { static bool init = false; static std::map<GUnicodeScript, Glib::ustring> mappings; if (!init) { init = true; mappings[G_UNICODE_SCRIPT_INVALID_CODE] = _("all"); mappings[G_UNICODE_SCRIPT_COMMON] = _("common"); mappings[G_UNICODE_SCRIPT_INHERITED] = _("inherited"); mappings[G_UNICODE_SCRIPT_ARABIC] = _("Arabic"); mappings[G_UNICODE_SCRIPT_ARMENIAN] = _("Armenian"); mappings[G_UNICODE_SCRIPT_BENGALI] = _("Bengali"); mappings[G_UNICODE_SCRIPT_BOPOMOFO] = _("Bopomofo"); mappings[G_UNICODE_SCRIPT_CHEROKEE] = _("Cherokee"); mappings[G_UNICODE_SCRIPT_COPTIC] = _("Coptic"); mappings[G_UNICODE_SCRIPT_CYRILLIC] = _("Cyrillic"); mappings[G_UNICODE_SCRIPT_DESERET] = _("Deseret"); mappings[G_UNICODE_SCRIPT_DEVANAGARI] = _("Devanagari"); mappings[G_UNICODE_SCRIPT_ETHIOPIC] = _("Ethiopic"); mappings[G_UNICODE_SCRIPT_GEORGIAN] = _("Georgian"); mappings[G_UNICODE_SCRIPT_GOTHIC] = _("Gothic"); mappings[G_UNICODE_SCRIPT_GREEK] = _("Greek"); mappings[G_UNICODE_SCRIPT_GUJARATI] = _("Gujarati"); mappings[G_UNICODE_SCRIPT_GURMUKHI] = _("Gurmukhi"); mappings[G_UNICODE_SCRIPT_HAN] = _("Han"); mappings[G_UNICODE_SCRIPT_HANGUL] = _("Hangul"); mappings[G_UNICODE_SCRIPT_HEBREW] = _("Hebrew"); mappings[G_UNICODE_SCRIPT_HIRAGANA] = _("Hiragana"); mappings[G_UNICODE_SCRIPT_KANNADA] = _("Kannada"); mappings[G_UNICODE_SCRIPT_KATAKANA] = _("Katakana"); mappings[G_UNICODE_SCRIPT_KHMER] = _("Khmer"); mappings[G_UNICODE_SCRIPT_LAO] = _("Lao"); mappings[G_UNICODE_SCRIPT_LATIN] = _("Latin"); mappings[G_UNICODE_SCRIPT_MALAYALAM] = _("Malayalam"); mappings[G_UNICODE_SCRIPT_MONGOLIAN] = _("Mongolian"); mappings[G_UNICODE_SCRIPT_MYANMAR] = _("Myanmar"); mappings[G_UNICODE_SCRIPT_OGHAM] = _("Ogham"); mappings[G_UNICODE_SCRIPT_OLD_ITALIC] = _("Old Italic"); mappings[G_UNICODE_SCRIPT_ORIYA] = _("Oriya"); mappings[G_UNICODE_SCRIPT_RUNIC] = _("Runic"); mappings[G_UNICODE_SCRIPT_SINHALA] = _("Sinhala"); mappings[G_UNICODE_SCRIPT_SYRIAC] = _("Syriac"); mappings[G_UNICODE_SCRIPT_TAMIL] = _("Tamil"); mappings[G_UNICODE_SCRIPT_TELUGU] = _("Telugu"); mappings[G_UNICODE_SCRIPT_THAANA] = _("Thaana"); mappings[G_UNICODE_SCRIPT_THAI] = _("Thai"); mappings[G_UNICODE_SCRIPT_TIBETAN] = _("Tibetan"); mappings[G_UNICODE_SCRIPT_CANADIAN_ABORIGINAL] = _("Canadian Aboriginal"); mappings[G_UNICODE_SCRIPT_YI] = _("Yi"); mappings[G_UNICODE_SCRIPT_TAGALOG] = _("Tagalog"); mappings[G_UNICODE_SCRIPT_HANUNOO] = _("Hanunoo"); mappings[G_UNICODE_SCRIPT_BUHID] = _("Buhid"); mappings[G_UNICODE_SCRIPT_TAGBANWA] = _("Tagbanwa"); mappings[G_UNICODE_SCRIPT_BRAILLE] = _("Braille"); mappings[G_UNICODE_SCRIPT_CYPRIOT] = _("Cypriot"); mappings[G_UNICODE_SCRIPT_LIMBU] = _("Limbu"); mappings[G_UNICODE_SCRIPT_OSMANYA] = _("Osmanya"); mappings[G_UNICODE_SCRIPT_SHAVIAN] = _("Shavian"); mappings[G_UNICODE_SCRIPT_LINEAR_B] = _("Linear B"); mappings[G_UNICODE_SCRIPT_TAI_LE] = _("Tai Le"); mappings[G_UNICODE_SCRIPT_UGARITIC] = _("Ugaritic"); mappings[G_UNICODE_SCRIPT_NEW_TAI_LUE] = _("New Tai Lue"); mappings[G_UNICODE_SCRIPT_BUGINESE] = _("Buginese"); mappings[G_UNICODE_SCRIPT_GLAGOLITIC] = _("Glagolitic"); mappings[G_UNICODE_SCRIPT_TIFINAGH] = _("Tifinagh"); mappings[G_UNICODE_SCRIPT_SYLOTI_NAGRI] = _("Syloti Nagri"); mappings[G_UNICODE_SCRIPT_OLD_PERSIAN] = _("Old Persian"); mappings[G_UNICODE_SCRIPT_KHAROSHTHI] = _("Kharoshthi"); mappings[G_UNICODE_SCRIPT_UNKNOWN] = _("unassigned"); mappings[G_UNICODE_SCRIPT_BALINESE] = _("Balinese"); mappings[G_UNICODE_SCRIPT_CUNEIFORM] = _("Cuneiform"); mappings[G_UNICODE_SCRIPT_PHOENICIAN] = _("Phoenician"); mappings[G_UNICODE_SCRIPT_PHAGS_PA] = _("Phags-pa"); mappings[G_UNICODE_SCRIPT_NKO] = _("N'Ko"); #if GLIB_CHECK_VERSION(2,14,0) mappings[G_UNICODE_SCRIPT_KAYAH_LI] = _("Kayah Li"); mappings[G_UNICODE_SCRIPT_LEPCHA] = _("Lepcha"); mappings[G_UNICODE_SCRIPT_REJANG] = _("Rejang"); mappings[G_UNICODE_SCRIPT_SUNDANESE] = _("Sundanese"); mappings[G_UNICODE_SCRIPT_SAURASHTRA] = _("Saurashtra"); mappings[G_UNICODE_SCRIPT_CHAM] = _("Cham"); mappings[G_UNICODE_SCRIPT_OL_CHIKI] = _("Ol Chiki"); mappings[G_UNICODE_SCRIPT_VAI] = _("Vai"); mappings[G_UNICODE_SCRIPT_CARIAN] = _("Carian"); mappings[G_UNICODE_SCRIPT_LYCIAN] = _("Lycian"); mappings[G_UNICODE_SCRIPT_LYDIAN] = _("Lydian"); #endif // GLIB_CHECK_VERSION(2,14,0) } return mappings; } #endif // GLIB_CHECK_VERSION(2,14,0) typedef std::pair<gunichar, gunichar> Range; typedef std::pair<Range, Glib::ustring> NamedRange; static std::vector<NamedRange> & getRanges() { static bool init = false; static std::vector<NamedRange> ranges; if (!init) { init = true; ranges.push_back(std::make_pair(std::make_pair(0x0000, 0xFFFD), _("all"))); ranges.push_back(std::make_pair(std::make_pair(0x0000, 0x007F), _("Basic Latin"))); ranges.push_back(std::make_pair(std::make_pair(0x0080, 0x00FF), _("Latin-1 Supplement"))); ranges.push_back(std::make_pair(std::make_pair(0x0100, 0x017F), _("Latin Extended-A"))); ranges.push_back(std::make_pair(std::make_pair(0x0180, 0x024F), _("Latin Extended-B"))); ranges.push_back(std::make_pair(std::make_pair(0x0250, 0x02AF), _("IPA Extensions"))); ranges.push_back(std::make_pair(std::make_pair(0x02B0, 0x02FF), _("Spacing Modifier Letters"))); ranges.push_back(std::make_pair(std::make_pair(0x0300, 0x036F), _("Combining Diacritical Marks"))); ranges.push_back(std::make_pair(std::make_pair(0x0370, 0x03FF), _("Greek and Coptic"))); ranges.push_back(std::make_pair(std::make_pair(0x0400, 0x04FF), _("Cyrillic"))); ranges.push_back(std::make_pair(std::make_pair(0x0500, 0x052F), _("Cyrillic Supplement"))); ranges.push_back(std::make_pair(std::make_pair(0x0530, 0x058F), _("Armenian"))); ranges.push_back(std::make_pair(std::make_pair(0x0590, 0x05FF), _("Hebrew"))); ranges.push_back(std::make_pair(std::make_pair(0x0600, 0x06FF), _("Arabic"))); ranges.push_back(std::make_pair(std::make_pair(0x0700, 0x074F), _("Syriac"))); ranges.push_back(std::make_pair(std::make_pair(0x0750, 0x077F), _("Arabic Supplement"))); ranges.push_back(std::make_pair(std::make_pair(0x0780, 0x07BF), _("Thaana"))); ranges.push_back(std::make_pair(std::make_pair(0x07C0, 0x07FF), _("NKo"))); ranges.push_back(std::make_pair(std::make_pair(0x0800, 0x083F), _("Samaritan"))); ranges.push_back(std::make_pair(std::make_pair(0x0900, 0x097F), _("Devanagari"))); ranges.push_back(std::make_pair(std::make_pair(0x0980, 0x09FF), _("Bengali"))); ranges.push_back(std::make_pair(std::make_pair(0x0A00, 0x0A7F), _("Gurmukhi"))); ranges.push_back(std::make_pair(std::make_pair(0x0A80, 0x0AFF), _("Gujarati"))); ranges.push_back(std::make_pair(std::make_pair(0x0B00, 0x0B7F), _("Oriya"))); ranges.push_back(std::make_pair(std::make_pair(0x0B80, 0x0BFF), _("Tamil"))); ranges.push_back(std::make_pair(std::make_pair(0x0C00, 0x0C7F), _("Telugu"))); ranges.push_back(std::make_pair(std::make_pair(0x0C80, 0x0CFF), _("Kannada"))); ranges.push_back(std::make_pair(std::make_pair(0x0D00, 0x0D7F), _("Malayalam"))); ranges.push_back(std::make_pair(std::make_pair(0x0D80, 0x0DFF), _("Sinhala"))); ranges.push_back(std::make_pair(std::make_pair(0x0E00, 0x0E7F), _("Thai"))); ranges.push_back(std::make_pair(std::make_pair(0x0E80, 0x0EFF), _("Lao"))); ranges.push_back(std::make_pair(std::make_pair(0x0F00, 0x0FFF), _("Tibetan"))); ranges.push_back(std::make_pair(std::make_pair(0x1000, 0x109F), _("Myanmar"))); ranges.push_back(std::make_pair(std::make_pair(0x10A0, 0x10FF), _("Georgian"))); ranges.push_back(std::make_pair(std::make_pair(0x1100, 0x11FF), _("Hangul Jamo"))); ranges.push_back(std::make_pair(std::make_pair(0x1200, 0x137F), _("Ethiopic"))); ranges.push_back(std::make_pair(std::make_pair(0x1380, 0x139F), _("Ethiopic Supplement"))); ranges.push_back(std::make_pair(std::make_pair(0x13A0, 0x13FF), _("Cherokee"))); ranges.push_back(std::make_pair(std::make_pair(0x1400, 0x167F), _("Unified Canadian Aboriginal Syllabics"))); ranges.push_back(std::make_pair(std::make_pair(0x1680, 0x169F), _("Ogham"))); ranges.push_back(std::make_pair(std::make_pair(0x16A0, 0x16FF), _("Runic"))); ranges.push_back(std::make_pair(std::make_pair(0x1700, 0x171F), _("Tagalog"))); ranges.push_back(std::make_pair(std::make_pair(0x1720, 0x173F), _("Hanunoo"))); ranges.push_back(std::make_pair(std::make_pair(0x1740, 0x175F), _("Buhid"))); ranges.push_back(std::make_pair(std::make_pair(0x1760, 0x177F), _("Tagbanwa"))); ranges.push_back(std::make_pair(std::make_pair(0x1780, 0x17FF), _("Khmer"))); ranges.push_back(std::make_pair(std::make_pair(0x1800, 0x18AF), _("Mongolian"))); ranges.push_back(std::make_pair(std::make_pair(0x18B0, 0x18FF), _("Unified Canadian Aboriginal Syllabics Extended"))); ranges.push_back(std::make_pair(std::make_pair(0x1900, 0x194F), _("Limbu"))); ranges.push_back(std::make_pair(std::make_pair(0x1950, 0x197F), _("Tai Le"))); ranges.push_back(std::make_pair(std::make_pair(0x1980, 0x19DF), _("New Tai Lue"))); ranges.push_back(std::make_pair(std::make_pair(0x19E0, 0x19FF), _("Khmer Symbols"))); ranges.push_back(std::make_pair(std::make_pair(0x1A00, 0x1A1F), _("Buginese"))); ranges.push_back(std::make_pair(std::make_pair(0x1A20, 0x1AAF), _("Tai Tham"))); ranges.push_back(std::make_pair(std::make_pair(0x1B00, 0x1B7F), _("Balinese"))); ranges.push_back(std::make_pair(std::make_pair(0x1B80, 0x1BBF), _("Sundanese"))); ranges.push_back(std::make_pair(std::make_pair(0x1C00, 0x1C4F), _("Lepcha"))); ranges.push_back(std::make_pair(std::make_pair(0x1C50, 0x1C7F), _("Ol Chiki"))); ranges.push_back(std::make_pair(std::make_pair(0x1CD0, 0x1CFF), _("Vedic Extensions"))); ranges.push_back(std::make_pair(std::make_pair(0x1D00, 0x1D7F), _("Phonetic Extensions"))); ranges.push_back(std::make_pair(std::make_pair(0x1D80, 0x1DBF), _("Phonetic Extensions Supplement"))); ranges.push_back(std::make_pair(std::make_pair(0x1DC0, 0x1DFF), _("Combining Diacritical Marks Supplement"))); ranges.push_back(std::make_pair(std::make_pair(0x1E00, 0x1EFF), _("Latin Extended Additional"))); ranges.push_back(std::make_pair(std::make_pair(0x1F00, 0x1FFF), _("Greek Extended"))); ranges.push_back(std::make_pair(std::make_pair(0x2000, 0x206F), _("General Punctuation"))); ranges.push_back(std::make_pair(std::make_pair(0x2070, 0x209F), _("Superscripts and Subscripts"))); ranges.push_back(std::make_pair(std::make_pair(0x20A0, 0x20CF), _("Currency Symbols"))); ranges.push_back(std::make_pair(std::make_pair(0x20D0, 0x20FF), _("Combining Diacritical Marks for Symbols"))); ranges.push_back(std::make_pair(std::make_pair(0x2100, 0x214F), _("Letterlike Symbols"))); ranges.push_back(std::make_pair(std::make_pair(0x2150, 0x218F), _("Number Forms"))); ranges.push_back(std::make_pair(std::make_pair(0x2190, 0x21FF), _("Arrows"))); ranges.push_back(std::make_pair(std::make_pair(0x2200, 0x22FF), _("Mathematical Operators"))); ranges.push_back(std::make_pair(std::make_pair(0x2300, 0x23FF), _("Miscellaneous Technical"))); ranges.push_back(std::make_pair(std::make_pair(0x2400, 0x243F), _("Control Pictures"))); ranges.push_back(std::make_pair(std::make_pair(0x2440, 0x245F), _("Optical Character Recognition"))); ranges.push_back(std::make_pair(std::make_pair(0x2460, 0x24FF), _("Enclosed Alphanumerics"))); ranges.push_back(std::make_pair(std::make_pair(0x2500, 0x257F), _("Box Drawing"))); ranges.push_back(std::make_pair(std::make_pair(0x2580, 0x259F), _("Block Elements"))); ranges.push_back(std::make_pair(std::make_pair(0x25A0, 0x25FF), _("Geometric Shapes"))); ranges.push_back(std::make_pair(std::make_pair(0x2600, 0x26FF), _("Miscellaneous Symbols"))); ranges.push_back(std::make_pair(std::make_pair(0x2700, 0x27BF), _("Dingbats"))); ranges.push_back(std::make_pair(std::make_pair(0x27C0, 0x27EF), _("Miscellaneous Mathematical Symbols-A"))); ranges.push_back(std::make_pair(std::make_pair(0x27F0, 0x27FF), _("Supplemental Arrows-A"))); ranges.push_back(std::make_pair(std::make_pair(0x2800, 0x28FF), _("Braille Patterns"))); ranges.push_back(std::make_pair(std::make_pair(0x2900, 0x297F), _("Supplemental Arrows-B"))); ranges.push_back(std::make_pair(std::make_pair(0x2980, 0x29FF), _("Miscellaneous Mathematical Symbols-B"))); ranges.push_back(std::make_pair(std::make_pair(0x2A00, 0x2AFF), _("Supplemental Mathematical Operators"))); ranges.push_back(std::make_pair(std::make_pair(0x2B00, 0x2BFF), _("Miscellaneous Symbols and Arrows"))); ranges.push_back(std::make_pair(std::make_pair(0x2C00, 0x2C5F), _("Glagolitic"))); ranges.push_back(std::make_pair(std::make_pair(0x2C60, 0x2C7F), _("Latin Extended-C"))); ranges.push_back(std::make_pair(std::make_pair(0x2C80, 0x2CFF), _("Coptic"))); ranges.push_back(std::make_pair(std::make_pair(0x2D00, 0x2D2F), _("Georgian Supplement"))); ranges.push_back(std::make_pair(std::make_pair(0x2D30, 0x2D7F), _("Tifinagh"))); ranges.push_back(std::make_pair(std::make_pair(0x2D80, 0x2DDF), _("Ethiopic Extended"))); ranges.push_back(std::make_pair(std::make_pair(0x2DE0, 0x2DFF), _("Cyrillic Extended-A"))); ranges.push_back(std::make_pair(std::make_pair(0x2E00, 0x2E7F), _("Supplemental Punctuation"))); ranges.push_back(std::make_pair(std::make_pair(0x2E80, 0x2EFF), _("CJK Radicals Supplement"))); ranges.push_back(std::make_pair(std::make_pair(0x2F00, 0x2FDF), _("Kangxi Radicals"))); ranges.push_back(std::make_pair(std::make_pair(0x2FF0, 0x2FFF), _("Ideographic Description Characters"))); ranges.push_back(std::make_pair(std::make_pair(0x3000, 0x303F), _("CJK Symbols and Punctuation"))); ranges.push_back(std::make_pair(std::make_pair(0x3040, 0x309F), _("Hiragana"))); ranges.push_back(std::make_pair(std::make_pair(0x30A0, 0x30FF), _("Katakana"))); ranges.push_back(std::make_pair(std::make_pair(0x3100, 0x312F), _("Bopomofo"))); ranges.push_back(std::make_pair(std::make_pair(0x3130, 0x318F), _("Hangul Compatibility Jamo"))); ranges.push_back(std::make_pair(std::make_pair(0x3190, 0x319F), _("Kanbun"))); ranges.push_back(std::make_pair(std::make_pair(0x31A0, 0x31BF), _("Bopomofo Extended"))); ranges.push_back(std::make_pair(std::make_pair(0x31C0, 0x31EF), _("CJK Strokes"))); ranges.push_back(std::make_pair(std::make_pair(0x31F0, 0x31FF), _("Katakana Phonetic Extensions"))); ranges.push_back(std::make_pair(std::make_pair(0x3200, 0x32FF), _("Enclosed CJK Letters and Months"))); ranges.push_back(std::make_pair(std::make_pair(0x3300, 0x33FF), _("CJK Compatibility"))); ranges.push_back(std::make_pair(std::make_pair(0x3400, 0x4DBF), _("CJK Unified Ideographs Extension A"))); ranges.push_back(std::make_pair(std::make_pair(0x4DC0, 0x4DFF), _("Yijing Hexagram Symbols"))); ranges.push_back(std::make_pair(std::make_pair(0x4E00, 0x9FFF), _("CJK Unified Ideographs"))); ranges.push_back(std::make_pair(std::make_pair(0xA000, 0xA48F), _("Yi Syllables"))); ranges.push_back(std::make_pair(std::make_pair(0xA490, 0xA4CF), _("Yi Radicals"))); ranges.push_back(std::make_pair(std::make_pair(0xA4D0, 0xA4FF), _("Lisu"))); ranges.push_back(std::make_pair(std::make_pair(0xA500, 0xA63F), _("Vai"))); ranges.push_back(std::make_pair(std::make_pair(0xA640, 0xA69F), _("Cyrillic Extended-B"))); ranges.push_back(std::make_pair(std::make_pair(0xA6A0, 0xA6FF), _("Bamum"))); ranges.push_back(std::make_pair(std::make_pair(0xA700, 0xA71F), _("Modifier Tone Letters"))); ranges.push_back(std::make_pair(std::make_pair(0xA720, 0xA7FF), _("Latin Extended-D"))); ranges.push_back(std::make_pair(std::make_pair(0xA800, 0xA82F), _("Syloti Nagri"))); ranges.push_back(std::make_pair(std::make_pair(0xA830, 0xA83F), _("Common Indic Number Forms"))); ranges.push_back(std::make_pair(std::make_pair(0xA840, 0xA87F), _("Phags-pa"))); ranges.push_back(std::make_pair(std::make_pair(0xA880, 0xA8DF), _("Saurashtra"))); ranges.push_back(std::make_pair(std::make_pair(0xA8E0, 0xA8FF), _("Devanagari Extended"))); ranges.push_back(std::make_pair(std::make_pair(0xA900, 0xA92F), _("Kayah Li"))); ranges.push_back(std::make_pair(std::make_pair(0xA930, 0xA95F), _("Rejang"))); ranges.push_back(std::make_pair(std::make_pair(0xA960, 0xA97F), _("Hangul Jamo Extended-A"))); ranges.push_back(std::make_pair(std::make_pair(0xA980, 0xA9DF), _("Javanese"))); ranges.push_back(std::make_pair(std::make_pair(0xAA00, 0xAA5F), _("Cham"))); ranges.push_back(std::make_pair(std::make_pair(0xAA60, 0xAA7F), _("Myanmar Extended-A"))); ranges.push_back(std::make_pair(std::make_pair(0xAA80, 0xAADF), _("Tai Viet"))); ranges.push_back(std::make_pair(std::make_pair(0xABC0, 0xABFF), _("Meetei Mayek"))); ranges.push_back(std::make_pair(std::make_pair(0xAC00, 0xD7AF), _("Hangul Syllables"))); ranges.push_back(std::make_pair(std::make_pair(0xD7B0, 0xD7FF), _("Hangul Jamo Extended-B"))); ranges.push_back(std::make_pair(std::make_pair(0xD800, 0xDB7F), _("High Surrogates"))); ranges.push_back(std::make_pair(std::make_pair(0xDB80, 0xDBFF), _("High Private Use Surrogates"))); ranges.push_back(std::make_pair(std::make_pair(0xDC00, 0xDFFF), _("Low Surrogates"))); ranges.push_back(std::make_pair(std::make_pair(0xE000, 0xF8FF), _("Private Use Area"))); ranges.push_back(std::make_pair(std::make_pair(0xF900, 0xFAFF), _("CJK Compatibility Ideographs"))); ranges.push_back(std::make_pair(std::make_pair(0xFB00, 0xFB4F), _("Alphabetic Presentation Forms"))); ranges.push_back(std::make_pair(std::make_pair(0xFB50, 0xFDFF), _("Arabic Presentation Forms-A"))); ranges.push_back(std::make_pair(std::make_pair(0xFE00, 0xFE0F), _("Variation Selectors"))); ranges.push_back(std::make_pair(std::make_pair(0xFE10, 0xFE1F), _("Vertical Forms"))); ranges.push_back(std::make_pair(std::make_pair(0xFE20, 0xFE2F), _("Combining Half Marks"))); ranges.push_back(std::make_pair(std::make_pair(0xFE30, 0xFE4F), _("CJK Compatibility Forms"))); ranges.push_back(std::make_pair(std::make_pair(0xFE50, 0xFE6F), _("Small Form Variants"))); ranges.push_back(std::make_pair(std::make_pair(0xFE70, 0xFEFF), _("Arabic Presentation Forms-B"))); ranges.push_back(std::make_pair(std::make_pair(0xFF00, 0xFFEF), _("Halfwidth and Fullwidth Forms"))); ranges.push_back(std::make_pair(std::make_pair(0xFFF0, 0xFFFF), _("Specials"))); } return ranges; } class GlyphColumns : public Gtk::TreeModel::ColumnRecord { public: Gtk::TreeModelColumn<gunichar> code; Gtk::TreeModelColumn<Glib::ustring> name; GlyphColumns() { add(code); add(name); } }; GlyphColumns *GlyphsPanel::getColumns() { static GlyphColumns *columns = new GlyphColumns(); return columns; } /** * Constructor */ GlyphsPanel::GlyphsPanel(gchar const *prefsPath) : Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_GLYPHS, "", false), store(Gtk::ListStore::create(*getColumns())), iconView(0), entry(0), label(0), insertBtn(0), #if GLIB_CHECK_VERSION(2,14,0) scriptCombo(0), #endif // GLIB_CHECK_VERSION(2,14,0) fsel(0), targetDesktop(0), deskTrack(), instanceConns(), desktopConns() { Gtk::Table *table = new Gtk::Table(3, 1, false); _getContents()->pack_start(*Gtk::manage(table), Gtk::PACK_EXPAND_WIDGET); guint row = 0; // ------------------------------- GtkWidget *fontsel = sp_font_selector_new(); fsel = SP_FONT_SELECTOR(fontsel); sp_font_selector_set_font(fsel, sp_font_selector_get_font(fsel), 12.0); gtk_widget_set_size_request (fontsel, 0, 150); g_signal_connect( G_OBJECT(fontsel), "font_set", G_CALLBACK(fontChangeCB), this ); table->attach(*Gtk::manage(Glib::wrap(fontsel)), 0, 3, row, row + 1, Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL); row++; // ------------------------------- #if GLIB_CHECK_VERSION(2,14,0) { Gtk::Label *label = new Gtk::Label(_("Script: ")); table->attach( *Gtk::manage(label), 0, 1, row, row + 1, Gtk::SHRINK, Gtk::SHRINK); scriptCombo = new Gtk::ComboBoxText(); for (std::map<GUnicodeScript, Glib::ustring>::iterator it = getScriptToName().begin(); it != getScriptToName().end(); ++it) { scriptCombo->append_text(it->second); } scriptCombo->set_active_text(getScriptToName()[G_UNICODE_SCRIPT_INVALID_CODE]); sigc::connection conn = scriptCombo->signal_changed().connect(sigc::mem_fun(*this, &GlyphsPanel::rebuild)); instanceConns.push_back(conn); Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_TOP, 0.0, 0.0); align->add(*Gtk::manage(scriptCombo)); table->attach( *Gtk::manage(align), 1, 2, row, row + 1, Gtk::FILL|Gtk::EXPAND, Gtk::SHRINK); } row++; #endif // GLIB_CHECK_VERSION(2,14,0) // ------------------------------- { Gtk::Label *label = new Gtk::Label(_("Range: ")); table->attach( *Gtk::manage(label), 0, 1, row, row + 1, Gtk::SHRINK, Gtk::SHRINK); rangeCombo = new Gtk::ComboBoxText(); for ( std::vector<NamedRange>::iterator it = getRanges().begin(); it != getRanges().end(); ++it ) { rangeCombo->append_text(it->second); } rangeCombo->set_active_text(getRanges()[1].second); sigc::connection conn = rangeCombo->signal_changed().connect(sigc::mem_fun(*this, &GlyphsPanel::rebuild)); instanceConns.push_back(conn); Gtk::Alignment *align = new Gtk::Alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_TOP, 0.0, 0.0); align->add(*Gtk::manage(rangeCombo)); table->attach( *Gtk::manage(align), 1, 2, row, row + 1, Gtk::FILL|Gtk::EXPAND, Gtk::SHRINK); } row++; // ------------------------------- GlyphColumns *columns = getColumns(); iconView = new Gtk::IconView(store); iconView->set_text_column(columns->name); //iconView->set_columns(16); sigc::connection conn; conn = iconView->signal_item_activated().connect(sigc::mem_fun(*this, &GlyphsPanel::glyphActivated)); instanceConns.push_back(conn); conn = iconView->signal_selection_changed().connect(sigc::mem_fun(*this, &GlyphsPanel::glyphSelectionChanged)); instanceConns.push_back(conn); Gtk::ScrolledWindow *scroller = new Gtk::ScrolledWindow(); scroller->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS); scroller->add(*Gtk::manage(iconView)); table->attach(*Gtk::manage(scroller), 0, 3, row, row + 1, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL); row++; // ------------------------------- Gtk::HBox *box = new Gtk::HBox(); entry = new Gtk::Entry(); conn = entry->signal_changed().connect(sigc::mem_fun(*this, &GlyphsPanel::calcCanInsert)); instanceConns.push_back(conn); entry->set_width_chars(18); box->pack_start(*Gtk::manage(entry), Gtk::PACK_SHRINK); Gtk::Label *pad = new Gtk::Label(" "); box->pack_start(*Gtk::manage(pad), Gtk::PACK_SHRINK); label = new Gtk::Label(" "); box->pack_start(*Gtk::manage(label), Gtk::PACK_SHRINK); pad = new Gtk::Label(""); box->pack_start(*Gtk::manage(pad), Gtk::PACK_EXPAND_WIDGET); insertBtn = new Gtk::Button(_("Append")); conn = insertBtn->signal_clicked().connect(sigc::mem_fun(*this, &GlyphsPanel::insertText)); instanceConns.push_back(conn); #if GTK_CHECK_VERSION(2,18,0) //gtkmm 2.18 insertBtn->set_can_default(); #endif insertBtn->set_sensitive(false); box->pack_end(*Gtk::manage(insertBtn), Gtk::PACK_SHRINK); table->attach( *Gtk::manage(box), 0, 3, row, row + 1, Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK); row++; // ------------------------------- show_all_children(); restorePanelPrefs(); // Connect this up last conn = deskTrack.connectDesktopChanged( sigc::mem_fun(*this, &GlyphsPanel::setTargetDesktop) ); instanceConns.push_back(conn); deskTrack.connect(GTK_WIDGET(gobj())); } GlyphsPanel::~GlyphsPanel() { for (std::vector<sigc::connection>::iterator it = instanceConns.begin(); it != instanceConns.end(); ++it) { it->disconnect(); } instanceConns.clear(); for (std::vector<sigc::connection>::iterator it = desktopConns.begin(); it != desktopConns.end(); ++it) { it->disconnect(); } desktopConns.clear(); } void GlyphsPanel::setDesktop(SPDesktop *desktop) { Panel::setDesktop(desktop); deskTrack.setBase(desktop); } void GlyphsPanel::setTargetDesktop(SPDesktop *desktop) { if (targetDesktop != desktop) { if (targetDesktop) { for (std::vector<sigc::connection>::iterator it = desktopConns.begin(); it != desktopConns.end(); ++it) { it->disconnect(); } desktopConns.clear(); } targetDesktop = desktop; if (targetDesktop && targetDesktop->selection) { sigc::connection conn = desktop->selection->connectChanged(sigc::hide(sigc::bind(sigc::mem_fun(*this, &GlyphsPanel::readSelection), true, true))); desktopConns.push_back(conn); // Text selection within selected items has changed: conn = desktop->connectToolSubselectionChanged(sigc::hide(sigc::bind(sigc::mem_fun(*this, &GlyphsPanel::readSelection), true, false))); desktopConns.push_back(conn); // Must check flags, so can't call performUpdate() directly. conn = desktop->selection->connectModified(sigc::hide<0>(sigc::mem_fun(*this, &GlyphsPanel::selectionModifiedCB))); desktopConns.push_back(conn); readSelection(true, true); } } } void GlyphsPanel::insertText() { SPItem *textItem = 0; for (const GSList *item = targetDesktop->selection->itemList(); item; item = item->next ) { if (SP_IS_TEXT(item->data) || SP_IS_FLOWTEXT(item->data)) { textItem = SP_ITEM(item->data); break; } } if (textItem) { Glib::ustring glyphs; if (entry->get_text_length() > 0) { glyphs = entry->get_text(); } else { Gtk::IconView::ArrayHandle_TreePaths itemArray = iconView->get_selected_items(); if (!itemArray.empty()) { Gtk::TreeModel::Path const & path = *itemArray.begin(); Gtk::ListStore::iterator row = store->get_iter(path); gunichar ch = (*row)[getColumns()->code]; glyphs = ch; } } if (!glyphs.empty()) { Glib::ustring combined; gchar *str = sp_te_get_string_multiline(textItem); if (str) { combined = str; g_free(str); str = 0; } combined += glyphs; sp_te_set_repr_text_multiline(textItem, combined.c_str()); sp_document_done(targetDesktop->doc(), SP_VERB_CONTEXT_TEXT, _("Append text")); } } } void GlyphsPanel::glyphActivated(Gtk::TreeModel::Path const & path) { Gtk::ListStore::iterator row = store->get_iter(path); gunichar ch = (*row)[getColumns()->code]; Glib::ustring tmp; tmp += ch; int startPos = 0; int endPos = 0; if (entry->get_selection_bounds(startPos, endPos)) { // there was something selected. entry->delete_text(startPos, endPos); } startPos = entry->get_position(); entry->insert_text(tmp, -1, startPos); entry->set_position(startPos); } void GlyphsPanel::glyphSelectionChanged() { Gtk::IconView::ArrayHandle_TreePaths itemArray = iconView->get_selected_items(); if (itemArray.empty()) { label->set_text(" "); } else { Gtk::TreeModel::Path const & path = *itemArray.begin(); Gtk::ListStore::iterator row = store->get_iter(path); gunichar ch = (*row)[getColumns()->code]; Glib::ustring scriptName; #if GLIB_CHECK_VERSION(2,14,0) GUnicodeScript script = g_unichar_get_script(ch); std::map<GUnicodeScript, Glib::ustring> mappings = getScriptToName(); if (mappings.find(script) != mappings.end()) { scriptName = mappings[script]; } #endif gchar * tmp = g_strdup_printf("U+%04X %s", ch, scriptName.c_str()); label->set_text(tmp); } calcCanInsert(); } void GlyphsPanel::fontChangeCB(SPFontSelector * /*fontsel*/, font_instance * /*font*/, GlyphsPanel *self) { if (self) { self->rebuild(); } } void GlyphsPanel::selectionModifiedCB(guint flags) { bool style = ((flags & ( SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG )) != 0 ); bool content = ((flags & ( SP_OBJECT_CHILD_MODIFIED_FLAG | SP_TEXT_CONTENT_MODIFIED_FLAG )) != 0 ); readSelection(style, content); } void GlyphsPanel::calcCanInsert() { int items = 0; for (const GSList *item = targetDesktop->selection->itemList(); item; item = item->next ) { if (SP_IS_TEXT(item->data) || SP_IS_FLOWTEXT(item->data)) { ++items; } } bool enable = (items == 1); if (enable) { enable &= (!iconView->get_selected_items().empty() || (entry->get_text_length() > 0)); } if (enable != insertBtn->is_sensitive()) { insertBtn->set_sensitive(enable); } } void GlyphsPanel::readSelection( bool updateStyle, bool /*updateContent*/ ) { calcCanInsert(); if (targetDesktop && updateStyle) { //SPStyle *query = sp_style_new(SP_ACTIVE_DOCUMENT); //int result_family = sp_desktop_query_style(targetDesktop, query, QUERY_STYLE_PROPERTY_FONTFAMILY); //int result_style = sp_desktop_query_style(targetDesktop, query, QUERY_STYLE_PROPERTY_FONTSTYLE); //int result_numbers = sp_desktop_query_style(targetDesktop, query, QUERY_STYLE_PROPERTY_FONTNUMBERS); //sp_style_unref(query); } } void GlyphsPanel::rebuild() { font_instance *font = fsel ? sp_font_selector_get_font(fsel) : 0; if (font) { //double sp_font_selector_get_size (SPFontSelector *fsel); #if GLIB_CHECK_VERSION(2,14,0) GUnicodeScript script = G_UNICODE_SCRIPT_INVALID_CODE; Glib::ustring scriptName = scriptCombo->get_active_text(); std::map<GUnicodeScript, Glib::ustring> items = getScriptToName(); for (std::map<GUnicodeScript, Glib::ustring>::iterator it = items.begin(); it != items.end(); ++it) { if (scriptName == it->second) { script = it->first; break; } } #endif // GLIB_CHECK_VERSION(2,14,0) // Disconnect the model while we update it. Simple work-around for 5x+ performance boost. Glib::RefPtr<Gtk::ListStore> tmp = Gtk::ListStore::create(*getColumns()); iconView->set_model(tmp); gunichar lower = 0x0001; gunichar upper = 0xFFFD; int active = rangeCombo->get_active_row_number(); if (active >= 0) { lower = getRanges()[active].first.first; upper = getRanges()[active].first.second; } std::vector<gunichar> present; for (gunichar ch = lower; ch <= upper; ch++) { int glyphId = font->MapUnicodeChar(ch); if (glyphId > 0) { #if GLIB_CHECK_VERSION(2,14,0) if ((script == G_UNICODE_SCRIPT_INVALID_CODE) || (script == g_unichar_get_script(ch))) { present.push_back(ch); } #else present.push_back(ch); #endif } } GlyphColumns *columns = getColumns(); store->clear(); for (std::vector<gunichar>::iterator it = present.begin(); it != present.end(); ++it) { Gtk::ListStore::iterator row = store->append(); Glib::ustring tmp; tmp += *it; (*row)[columns->code] = *it; (*row)[columns->name] = tmp; } // Reconnect the model once it has been updated: iconView->set_model(store); } } } // namespace Dialogs } // namespace UI } // namespace Inkscape /* Local Variables: mode:c++ c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) indent-tabs-mode:nil fill-column:99 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :
gpl-2.0
adaoex/zf2-phpbol
src/PHPBol/Boleto/Factory.php
1280
<?php /* * This file is part of PHPBol. * * (c) 2011 Francisco Luz & Rafael Goulart * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPBol\Boleto; /** * Abstração para Boletos * Contém funções elementares para todos Templates * * @package phpbol * @subpackage boleto * @author Francisco Luz <[email protected]> * @author Rafael Goulart <[email protected]> */ class Factory { /** * Constructor * * set private to avoid directly instatiation to implement * Factory Design Pattern **/ private function __construct() { } /** * Factory * Permite a criação do boleto com definição apenas do layout * * @param string $layout O layout bancário para instanciar * somente a parte específica, será instanciado * \PHPBol\Boleto\Boleto$layout * @param mixed $dados Array com dados ou null * * @return PHPBol\Boleto\AbstractBoleto */ static public function create($layout, $dados=null) { // Criando nome da classe $classe = "\PHPBol\Boleto\Boleto{$layout}"; return new $classe($dados); } }
gpl-2.0
matthiasbeyer/docplus
functions.php
91
<?php if ( function_exists('register_sidebars') ) register_sidebars(3); ?>
gpl-2.0
ETSGlobal/ezpublish_built
kernel/state/module.php
4708
<?php /** * @copyright Copyright (C) 1999-2011 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version 2011.12 * @package kernel */ $Module = array( 'name' => 'eZContentObjectState', 'variable_params' => false ); $ViewList = array(); $ViewList['assign'] = array( 'default_navigation_part' => 'ezsetupnavigationpart', 'script' => 'assign.php', 'params' => array( 'ObjectID', 'SelectedStateID' ), 'functions' => array( 'assign' ), 'single_post_actions' => array( 'AssignButton' => 'Assign' ), 'post_action_parameters' => array( 'Assign' => array( 'ObjectID' => 'ObjectID', 'SelectedStateIDList' => 'SelectedStateIDList', 'RedirectRelativeURI' => 'RedirectRelativeURI' ) ) ); $ViewList['groups'] = array( 'default_navigation_part' => 'ezsetupnavigationpart', 'script' => 'groups.php', 'params' => array(), 'functions' => array( 'administrate' ), 'unordered_params' => array( 'offset' => 'Offset' ), 'single_post_actions' => array( 'CreateButton' => 'Create', 'RemoveButton' => 'Remove' ), 'post_action_parameters' => array( 'Remove' => array( 'RemoveIDList' => 'RemoveIDList' ) ) ); $ViewList['group'] = array( 'default_navigation_part' => 'ezsetupnavigationpart', 'script' => 'group.php', 'params' => array( 'GroupIdentifier', 'Language' ), 'functions' => array( 'administrate' ), 'single_post_actions' => array( 'CreateButton' => 'Create', 'UpdateOrderButton' => 'UpdateOrder', 'EditButton' => 'Edit', 'RemoveButton' => 'Remove' ), 'post_action_parameters' => array( 'UpdateOrder' => array( 'Order' => 'Order' ), 'Remove' => array( 'RemoveIDList' => 'RemoveIDList' ) ) ); $ViewList['group_edit'] = array( 'default_navigation_part' => 'ezsetupnavigationpart', 'script' => 'group_edit.php', 'ui_context' => 'edit', 'params' => array( 'GroupIdentifier' ), 'functions' => array( 'administrate' ), 'single_post_actions' => array( 'StoreButton' => 'Store', 'CancelButton' => 'Cancel' ) ); $ViewList['view'] = array( 'default_navigation_part' => 'ezsetupnavigationpart', 'script' => 'view.php', 'params' => array( 'GroupIdentifier', 'StateIdentifier', 'Language' ), 'functions' => array( 'administrate' ), 'single_post_actions' => array( 'EditButton' => 'Edit' ) ); $ViewList['edit'] = array( 'default_navigation_part' => 'ezsetupnavigationpart', 'script' => 'edit.php', 'ui_context' => 'edit', 'params' => array( 'GroupIdentifier', 'StateIdentifier' ), 'functions' => array( 'administrate' ), 'single_post_actions' => array( 'StoreButton' => 'Store', 'CancelButton' => 'Cancel' ) ); $ClassID = array( 'name'=> 'Class', 'values'=> array(), 'class' => 'eZContentClass', 'function' => 'fetchList', 'parameter' => array( 0, false, false, array( 'name' => 'asc' ) ) ); $SectionID = array( 'name'=> 'Section', 'values'=> array(), 'class' => 'eZSection', 'function' => 'fetchList', 'parameter' => array( false ) ); $Assigned = array( 'name'=> 'Owner', 'values'=> array( array( 'Name' => 'Self', 'value' => '1') ) ); $AssignedGroup = array( 'name'=> 'Group', 'single_select' => true, 'values'=> array( array( 'Name' => 'Self', 'value' => '1') ) ); $Node = array( 'name'=> 'Node', 'values'=> array() ); $Subtree = array( 'name'=> 'Subtree', 'values'=> array() ); $stateLimitations = eZContentObjectStateGroup::limitations(); $NewState = array( 'name' => 'NewState', 'values' => array(), 'class' => 'eZContentObjectState', 'function' => 'limitationList', 'parameter' => array() ); $FunctionList = array(); $FunctionList['administrate'] = array(); $FunctionList['assign'] = array( 'Class' => $ClassID, 'Section' => $SectionID, 'Owner' => $Assigned, 'Group' => $AssignedGroup, 'Node' => $Node, 'Subtree' => $Subtree ); $FunctionList['assign'] = array_merge( $FunctionList['assign'], $stateLimitations, array( 'NewState' => $NewState ) ); ?>
gpl-2.0
Broadsheetie/Broadsheet-wordpress
wp-content/plugins/most-comments/most-comments.php
4320
<?php /* Plugin Name: Most Comments Plugin URI: http://www.brandinfection.com Description: Most Comments as a function and in a Widget Version: 1.1 Author: Nader Cserny Author URI: http://www.brandinfection.com/ */ ### Use WordPress 2.6 Constants if (!defined('WP_CONTENT_DIR')) { define( 'WP_CONTENT_DIR', ABSPATH.'wp-content'); } if (!defined('WP_CONTENT_URL')) { define('WP_CONTENT_URL', get_option('siteurl').'/wp-content'); } if (!defined('WP_PLUGIN_DIR')) { define('WP_PLUGIN_DIR', WP_CONTENT_DIR.'/plugins'); } if (!defined('WP_PLUGIN_URL')) { define('WP_PLUGIN_URL', WP_CONTENT_URL.'/plugins'); } ### Function: Most Comments Option Menu add_action('admin_menu', 'most_comments_menu'); function most_comments_menu() { if (function_exists('add_options_page')) { add_options_page(__('Most Comments', 'most_comments'), __('Most Comments', 'most_comments'), 'manage_options', 'most-comments/most-comments-options.php') ; } } function most_comments($limit = 5, $show_pass_post = 0, $duration = 0, $exclude_nocomments = 1, $display = true, $category = 0) { global $wpdb; $most_comments_options = get_option('most_comments_options'); $temp = ''; $category = $most_comments_options['from_category']; $most_comments = wp_cache_get('most_comments'); if ($most_comments === false) { if ($category == 0) { $request = "SELECT ID, post_title, comment_count FROM $wpdb->posts"; $request .= " WHERE post_status = 'publish'"; if ($show_pass_post != 0) $request .= " AND post_password =''"; if ($duration != "" || $duration > 0) $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date "; } else { $request = "SELECT * FROM $wpdb->posts LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id = $category"; if ($show_pass_post != 0) $request .= " AND $wpdb->posts.post_password =''"; if ($duration != "" || $duration > 0) $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < $wpdb->posts.post_date "; } $request .= " ORDER BY comment_count DESC"; if ($limit != 0) { $request .= " LIMIT $limit"; } $posts = $wpdb->get_results($request); if ($posts) { foreach ($posts as $post) { $post_title = stripslashes($post->post_title); $comment_count = $post->comment_count; $permalink = get_permalink($post->ID); if ($most_comments_options['exclude_nocomments'] == 0) { $temp = stripslashes($most_comments_options['most_comments_template']); $temp = str_replace("%COMMENT_COUNT%", $comment_count, $temp); $temp = str_replace("%POST_TITLE%", $post_title, $temp); $temp = str_replace("%POST_URL%", $permalink, $temp); } else { if ($comment_count != 0) { $temp = stripslashes($most_comments_options['most_comments_template']); $temp = str_replace("%COMMENT_COUNT%", $comment_count, $temp); $temp = str_replace("%POST_TITLE%", $post_title, $temp); $temp = str_replace("%POST_URL%", $permalink.'?utm_source=internal&utm_medium=web&utm_content=most_commented', $temp); } else { $temp = ''; } } $most_comments .= $temp; } } else { $most_comments .= '<li>None found</li>'; } wp_cache_set('most_comments', $most_comments); } if($display) { echo $most_comments; } else { return $most_comments; } } ### Function: Post Views Options add_action('activate_most-comments/most-comments.php', 'most_comments_init'); function most_comments_init() { // Add Options $most_comments_options = array(); $most_comments_options['limit'] = 5; $most_comments_options['duration'] = 30; $most_comments_options['show_pass_post'] = 0; $most_comments_options['exclude_nocomments'] = 1; $most_comments_options['from_category'] = 0; $most_comments_options['most_comments_template'] = '<li><a href="%POST_URL%" title="%POST_TITLE%">%POST_TITLE%</a> - %COMMENT_COUNT% '.__('comments', 'most-comments').'</li>'; add_option('most_comments_options', $most_comments_options, 'Most Comments Options'); }
gpl-2.0
halfline/gnome-shell
js/perf/core.js
8758
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const System = imports.system; const Main = imports.ui.main; const Scripting = imports.ui.scripting; // This performance script measure the most important (core) performance // metrics for the shell. By looking at the output metrics of this script // someone should be able to get an idea of how well the shell is performing // on a particular system. let METRICS = { overviewLatencyFirst: { description: "Time to first frame after triggering overview, first time", units: "us" }, overviewFpsFirst: { description: "Frame rate when going to the overview, first time", units: "frames / s" }, overviewLatencySubsequent: { description: "Time to first frame after triggering overview, second time", units: "us"}, overviewFpsSubsequent: { description: "Frames rate when going to the overview, second time", units: "frames / s" }, overviewFps5Windows: { description: "Frames rate when going to the overview, 5 windows open", units: "frames / s" }, overviewFps10Windows: { description: "Frames rate when going to the overview, 10 windows open", units: "frames / s" }, overviewFps5Maximized: { description: "Frames rate when going to the overview, 5 maximized windows open", units: "frames / s" }, overviewFps10Maximized: { description: "Frames rate when going to the overview, 10 maximized windows open", units: "frames / s" }, overviewFps5Alpha: { description: "Frames rate when going to the overview, 5 alpha-transparent windows open", units: "frames / s" }, overviewFps10Alpha: { description: "Frames rate when going to the overview, 10 alpha-transparent windows open", units: "frames / s" }, usedAfterOverview: { description: "Malloc'ed bytes after the overview is shown once", units: "B" }, leakedAfterOverview: { description: "Additional malloc'ed bytes the second time the overview is shown", units: "B" }, applicationsShowTimeFirst: { description: "Time to switch to applications view, first time", units: "us" }, applicationsShowTimeSubsequent: { description: "Time to switch to applications view, second time", units: "us"} }; let WINDOW_CONFIGS = [ { width: 640, height: 480, alpha: false, maximized: false, count: 1, metric: 'overviewFpsSubsequent' }, { width: 640, height: 480, alpha: false, maximized: false, count: 5, metric: 'overviewFps5Windows' }, { width: 640, height: 480, alpha: false, maximized: false, count: 10, metric: 'overviewFps10Windows' }, { width: 640, height: 480, alpha: false, maximized: true, count: 5, metric: 'overviewFps5Maximized' }, { width: 640, height: 480, alpha: false, maximized: true, count: 10, metric: 'overviewFps10Maximized' }, { width: 640, height: 480, alpha: true, maximized: false, count: 5, metric: 'overviewFps5Alpha' }, { width: 640, height: 480, alpha: true, maximized: false, count: 10, metric: 'overviewFps10Alpha' } ]; function run() { Scripting.defineScriptEvent("overviewShowStart", "Starting to show the overview"); Scripting.defineScriptEvent("overviewShowDone", "Overview finished showing"); Scripting.defineScriptEvent("afterShowHide", "After a show/hide cycle for the overview"); Scripting.defineScriptEvent("applicationsShowStart", "Starting to switch to applications view"); Scripting.defineScriptEvent("applicationsShowDone", "Done switching to applications view"); // Enable recording of timestamps for different points in the frame cycle global.frame_timestamps = true; Main.overview.connect('shown', () => { Scripting.scriptEvent('overviewShowDone'); }); yield Scripting.sleep(1000); for (let i = 0; i < 2 * WINDOW_CONFIGS.length; i++) { // We go to the overview twice for each configuration; the first time // to calculate the mipmaps for the windows, the second time to get // a clean set of numbers. if ((i % 2) == 0) { let config = WINDOW_CONFIGS[i / 2]; yield Scripting.destroyTestWindows(); for (let k = 0; k < config.count; k++) yield Scripting.createTestWindow({ width: config.width, height: config.height, alpha: config.alpha, maximized: config.maximized }); yield Scripting.waitTestWindows(); yield Scripting.sleep(1000); yield Scripting.waitLeisure(); } Scripting.scriptEvent('overviewShowStart'); Main.overview.show(); yield Scripting.waitLeisure(); Main.overview.hide(); yield Scripting.waitLeisure(); System.gc(); yield Scripting.sleep(1000); Scripting.collectStatistics(); Scripting.scriptEvent('afterShowHide'); } yield Scripting.destroyTestWindows(); yield Scripting.sleep(1000); Main.overview.show(); yield Scripting.waitLeisure(); for (let i = 0; i < 2; i++) { Scripting.scriptEvent('applicationsShowStart'); Main.overview._dash.showAppsButton.checked = true; yield Scripting.waitLeisure(); Scripting.scriptEvent('applicationsShowDone'); Main.overview._dash.showAppsButton.checked = false; yield Scripting.waitLeisure(); } } let showingOverview = false; let finishedShowingOverview = false; let overviewShowStart; let overviewFrames; let overviewLatency; let mallocUsedSize = 0; let overviewShowCount = 0; let firstOverviewUsedSize; let haveSwapComplete = false; let applicationsShowStart; let applicationsShowCount = 0; function script_overviewShowStart(time) { showingOverview = true; finishedShowingOverview = false; overviewShowStart = time; overviewFrames = 0; } function script_overviewShowDone(time) { // We've set up the state at the end of the zoom out, but we // need to wait for one more frame to paint before we count // ourselves as done. finishedShowingOverview = true; } function script_applicationsShowStart(time) { applicationsShowStart = time; } function script_applicationsShowDone(time) { applicationsShowCount++; if (applicationsShowCount == 1) METRICS.applicationsShowTimeFirst.value = time - applicationsShowStart; else METRICS.applicationsShowTimeSubsequent.value = time - applicationsShowStart; } function script_afterShowHide(time) { if (overviewShowCount == 1) { METRICS.usedAfterOverview.value = mallocUsedSize; } else { METRICS.leakedAfterOverview.value = mallocUsedSize - METRICS.usedAfterOverview.value; } } function malloc_usedSize(time, bytes) { mallocUsedSize = bytes; } function _frameDone(time) { if (showingOverview) { if (overviewFrames == 0) overviewLatency = time - overviewShowStart; overviewFrames++; } if (finishedShowingOverview) { showingOverview = false; finishedShowingOverview = false; overviewShowCount++; let dt = (time - (overviewShowStart + overviewLatency)) / 1000000; // If we see a start frame and an end frame, that would // be 1 frame for a FPS computation, hence the '- 1' let fps = (overviewFrames - 1) / dt; if (overviewShowCount == 1) { METRICS.overviewLatencyFirst.value = overviewLatency; METRICS.overviewFpsFirst.value = fps; } else if (overviewShowCount == 2) { METRICS.overviewLatencySubsequent.value = overviewLatency; } // Other than overviewFpsFirst, we collect FPS metrics the second // we show each window configuration. overviewShowCount is 1,2,3... if (overviewShowCount % 2 == 0) { let config = WINDOW_CONFIGS[(overviewShowCount / 2) - 1]; METRICS[config.metric].value = fps; } } } function glx_swapComplete(time, swapTime) { haveSwapComplete = true; _frameDone(swapTime); } function clutter_stagePaintDone(time) { // If we aren't receiving GLXBufferSwapComplete events, then we approximate // the time the user sees a frame with the time we finished doing drawing // commands for the frame. This doesn't take into account the time for // the GPU to finish painting, and the time for waiting for the buffer // swap, but if this are uniform - every frame takes the same time to draw - // then it won't upset our FPS calculation, though the latency value // will be slightly too low. if (!haveSwapComplete) _frameDone(time); }
gpl-2.0
NPLPackages/main
script/ide/MotionEx/MotionRender_SpellCastViewer.lua
22274
--[[ Title: Author(s): Leio Date: 2011/06/10 Desc: based on script/apps/Aries/Pipeline/SpellCastViewer/SpellCastViewerPage.lua use the lib: ------------------------------------------------------------ NPL.load("(gl)script/ide/MotionEx/MotionRender_SpellCastViewer.lua"); local MotionRender_SpellCastViewer = commonlib.gettable("MotionEx.MotionRender_SpellCastViewer"); ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Combat/CombatCameraView.lua"); NPL.load("(gl)script/kids/3DMapSystemApp/mcml/PageCtrl.lua"); NPL.load("(gl)script/apps/Aries/Combat/main.lua"); NPL.load("(gl)script/apps/Aries/Combat/SpellCast.lua"); -- create class local MotionRender_SpellCastViewer = commonlib.gettable("MotionEx.MotionRender_SpellCastViewer"); local CombatCameraView = commonlib.gettable("MotionEx.CombatCameraView"); local page; local SpellCast = MyCompany.Aries.Combat.SpellCast; MotionRender_SpellCastViewer.play_id_map = {}; function MotionRender_SpellCastViewer.BuildID() local self = MotionRender_SpellCastViewer; local uid = ParaGlobal.GenerateUniqueID(); self.play_id_map[uid] = uid; return uid; end -- on init show the current avatar in pe:avatar function MotionRender_SpellCastViewer.OnInit() -- some code driven audio files for backward compatible AudioEngine.Init(); -- set max concurrent sounds AudioEngine.SetGarbageCollectThreshold(10) -- load wave description resources AudioEngine.LoadSoundWaveBank("config/Aries/Audio/AriesRegionBGMusics.bank.xml"); end function MotionRender_SpellCastViewer.RemoveTestArena() NPL.load("(gl)script/apps/Aries/Combat/ObjectManager.lua"); MyCompany.Aries.Combat.ObjectManager.DestroyArenaObj(9991); MyCompany.Aries.Quest.NPC.DeleteNPCCharacter(39001, 10091); MyCompany.Aries.Quest.NPC.DeleteNPCCharacter(39001, 10092); MyCompany.Aries.Quest.NPC.DeleteNPCCharacter(39001, 10093); MyCompany.Aries.Quest.NPC.DeleteNPCCharacter(39001, 10094); local i = 1; for i = 1, 4 do local _obj = ParaScene.GetCharacter(tostring(1234560 + i)); if(_obj and _obj:IsValid() == true) then ParaScene.Delete(_obj); end local _obj = ParaScene.GetCharacter(tostring(1234560 + i).."+driver"); if(_obj and _obj:IsValid() == true) then ParaScene.Delete(_obj); end end end --NOTE:added by leio 2011/05/21 --[[ NPL.load("(gl)script/apps/Aries/Combat/CombatCameraView.lua"); local CombatCameraView = commonlib.gettable("MotionEx.CombatCameraView"); CombatCameraView.enabled = true; NPL.load("(gl)script/ide/MotionEx/MotionRender_SpellCastViewer.lua"); local MotionRender_SpellCastViewer = commonlib.gettable("MotionEx.MotionRender_SpellCastViewer"); local character_list = { [1] = {AssetFile = "character/v3/Elf/Female/ElfFemale.xml", Scale="1" }, [2] = {AssetFile = "character/v3/Elf/Female/ElfFemale.xml",Scale="1" }, [3] = {AssetFile = "character/v3/Elf/Female/ElfFemale.xml",Scale="1" }, [4] = {AssetFile = "character/v3/Elf/Female/ElfFemale.xml",Scale="1" }, [5] = {AssetFile = "character/v5/10mobs/HaqiTown/BlazeHairMonster/BlazeHairMonster.x",Scale="1" }, [6] = {AssetFile = "character/v5/10mobs/HaqiTown/EvilSnowman/EvilSnowman.x",Scale="1" }, [7] = {AssetFile = "character/v5/10mobs/HaqiTown/FireRockyOgre/FireRockyOgre_02.x",Scale="1" }, [8] = {AssetFile = "character/v5/10mobs/HaqiTown/RedCrab/RedCrab.x",Scale="1" }, } MotionRender_SpellCastViewer.RemoveTestArena() -- some code driven audio files for backward compatible AudioEngine.Init(); -- set max concurrent sounds AudioEngine.SetGarbageCollectThreshold(10) -- load wave description resources AudioEngine.LoadSoundWaveBank("config/Aries/Audio/AriesRegionBGMusics.bank.xml"); MotionRender_SpellCastViewer.CreateArena(x, y, z,character_list,function() MotionRender_SpellCastViewer.TestSpellFromFile("config/Aries/Spells/Storm_SingleAttack_Level1.xml",1,5); end); --]] function MotionRender_SpellCastViewer.CreateArena(x, y, z,character_list,callbackFunc) if(not character_list)then return end NPL.load("(gl)script/apps/Aries/Quest/NPC.lua"); NPL.load("(gl)script/apps/Aries/Combat/ObjectManager.lua"); if(SystemInfo.GetField("name") == "Taurus") then -- for taurus only NPL.load("(gl)script/kids/3DMapSystemItem/ItemManager.lua"); Map3DSystem.Item.ItemManager.GlobalStoreTemplates[10001] = { assetfile = "character/v3/PurpleDragonMajor/Female/PurpleDragonMajorFemale.xml", }; end -- for SentientGroupIDs NPL.load("(gl)script/apps/Aries/Pet/main.lua"); --MyCompany.Aries.Combat.ObjectManager.SyncEssentialCombatResource(function() local p_x, p_y, p_z; if(x and y and z) then p_x = x; p_y = y; p_z = z; else p_x, p_y, p_z = ParaScene.GetPlayer():GetPosition(); end NPL.load("(gl)script/apps/Aries/Combat/MsgHandler.lua"); local MsgHandler = commonlib.gettable("MyCompany.Aries.Combat.MsgHandler"); local arena_meta = MsgHandler.Get_arena_meta_data_by_id(9991); arena_meta.mode = "pve" MyCompany.Aries.Combat.ObjectManager.CreateArenaObj(9991, {x = p_x, y = p_y, z = p_z}, true, true); -- bForceVisible, bMovieArena -- if nid is not available it is a Taurus project character -- create a character local i; for i = 1, 8 do local node = character_list[i]; if(node)then if(node.CCSInfoStr == "myself") then if(SystemInfo.GetField("name") == "Taurus") then -- for taurus only node.CCSInfoStr = nil; else node.CCSInfoStr = Map3DSystem.UI.CCS.GetCCSInfoString(); end end local Scale = tonumber(node.Scale) or 1; if( i <= 4)then local nid_name = tostring(1234560 + i); local AssetFile = node.AssetFile or "character/v3/Elf/Female/ElfFemale.xml"; local CCSInfoStr = node.CCSInfoStr or "0#1#0#2#1#@0#F#0#0#0#0#0#F#0#0#0#0#9#F#0#0#0#0#9#F#0#0#0#0#10#F#0#0#0#0#8#F#0#0#0#0#0#F#0#0#0#0#@1#10001#0#3#11009#0#0#0#0#0#0#0#0#1072#1073#1074#0#0#0#0#0#0#0#0#"; local player = ParaScene.GetObject(nid_name); if(player:IsValid() == false) then Map3DSystem.SendMessage_obj({type = Map3DSystem.msg.OBJ_CreateObject, silentmode = true, SkipHistory = true, obj_params = { name = nid_name, AssetFile = AssetFile, CCSInfoStr = CCSInfoStr, x = p_x, -- y = p_y, y = -10000, -- this will fix a bug when the arena model is not fully loaded, the character will not be visible. z = p_z, IsCharacter = true, IsPersistent = false, -- do not save an GSL agent when saving scene scaling = Scale, }, }) --local player = ParaScene.GetObject(nid_name); --if(player:IsValid() == true) then --Map3DSystem.UI.CCS.ApplyCCSInfoString(player, CCSInfoStr); --end end MyCompany.Aries.Combat.ObjectManager.MountPlayerOnSlot(1234560 + i, 9991, i); else local AssetFile = node.AssetFile or "character/v5/10mobs/HaqiTown/BlazeHairMonster/BlazeHairMonster.x"; local params = { position = {p_x, p_y, p_z}, assetfile_char = AssetFile, instance = 10090 + i - 4, name = "", scaling = Scale, --scale_char = Scale, }; local NPC = MyCompany.Aries.Quest.NPC; local char_buffslot = NPC.CreateNPCCharacter(39001, params); MyCompany.Aries.Combat.ObjectManager.MountNPCOnSlot(39001, 10090 + i - 4, 9991, i); end end end if(callbackFunc)then callbackFunc(); end --end) end function MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) -- if the arena is created use the arena object to play spell effect local caster; local target; if(not caster_id) then caster = {isPlayer = true, nid = 1234561, slotid = caster_id}; else if(caster_id >= 1 and caster_id <= 4) then caster = {isPlayer = true, nid = 1234560 + caster_id, slotid = caster_id}; elseif(caster_id >= 5 and caster_id <= 8) then caster = {isPlayer = false, npc_id = 39001, instance = 10090 + (caster_id - 4), slotid = caster_id}; end end if(not target_id) then target = {isPlayer = false, npc_id = 39001, instance = 10091, slotid = target_id}; else if(target_id >= 1 and target_id <= 4) then target = {isPlayer = true, nid = 1234560 + target_id, slotid = target_id}; elseif(target_id >= 5 and target_id <= 8) then target = {isPlayer = false, npc_id = 39001, instance = 10090 + (target_id - 4), slotid = target_id}; end end return caster,target; end local charm_key_id_mapping = { ["Fire_FireDamageBlade"] = 11, ["Fire_AreaAccuracyWeakness"] = 12, ["Fire_FireDispellWeakness"] = 13, ["Storm_StormAccuracyBlade"] = 14, ["Storm_StormDamageBlade"] = 15, ["Storm_StormDispellWeakness"] = 16, ["Ice_IceDamageBlade"] = 17, ["Ice_IceDispellWeakness"] = 18, ["Life_LifeDamageBlade"] = 19, ["Life_AreaAccuracyBlade"] = 20, ["Life_HealBlade"] = 21, ["Life_LifeDispellWeakness"] = 22, ["Death_DeathDamageBlade"] = 23, ["Death_AreaDamageWeakness"] = 24, ["Death_HealWeakness"] = 25, ["Death_DeathDispellWeakness"] = 26, }; local ward_key_id_mapping = { ["Fire_FireDamageTrap"] = 21, ["Fire_FirePrism"] = 22, ["Fire_FireGreatShield"] = 23, ["Storm_StormDamageTrap"] = 24, ["Storm_AreaDamageTrap"] = 25, ["Storm_StormGreatShield"] = 26, ["Ice_GlobalShield"] = 27, ["Ice_IceDamageTrap"] = 28, ["Ice_IcePrism"] = 29, ["Ice_Absorb_LevelX"] = 30, ["Ice_StunAbsorb"] = 31, ["Ice_IceGreatShield"] = 32, ["Life_Absorb_Level3"] = 33, ["Life_LifePrism"] = 34, ["Life_Absorb_Level3"] = 35, ["Life_LifeDamageTrap"] = 36, ["Life_LifeGreatShield"] = 37, ["Death_SymmetryGlobalTrap_Target"] = 38, ["Death_SymmetryGlobalTrap_Caster"] = 39, ["Death_DeathDamageTrap"] = 40, ["Death_DeathPrism"] = 41, ["Death_GlobalDamageTrap"] = 42, ["Death_DeathGreatShield"] = 43, }; function MotionRender_SpellCastViewer.TestSpellFromFile(file, caster_id, target_id) --force load all cameras motion file CombatCameraView.ForceLoadAllCameras(); local key = string.match(file, [[([^/]-)%.xml$]]); if(not key) then log("error: invalid key name for MotionRender_SpellCastViewer.TestSpellFromFile file="..file.."\n") return; end NPL.load("(gl)script/apps/Aries/Quest/NPC.lua"); NPL.load("(gl)script/apps/Aries/Combat/ObjectManager.lua"); NPL.load("(gl)script/apps/Aries/Combat/SpellPlayer.lua"); local SpellPlayer = MyCompany.Aries.Combat.SpellPlayer; ---- test destory arena object --MyCompany.Aries.Combat.ObjectManager.DestroyArenaObj(9991) local bArenaCreated = MyCompany.Aries.Combat.ObjectManager.IsArenaObjCreated(9991); local commentfile = string.gsub(file, "%.xml$", ".comment.xml"); MotionRender_SpellCastViewer.StopSpellCasting(); local playing_id = MotionRender_SpellCastViewer.BuildID(); if(bArenaCreated == true) then if(key == "Death_SymmetryGlobalTrap") then -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{100}}, {{ target_wards = tostring(ward_key_id_mapping[key.."_Target"])..",6,6,", last_target_wards = "0,6,6", target_charms = "1,2,", last_target_charms = "0,2", caster_wards = tostring(ward_key_id_mapping[key.."_Caster"])..",6,6,", last_caster_wards = "0,6,6", caster_charms = "1,2,", last_caster_charms = "0,2" }}, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "area") and (string.find(string.lower(file), "blade") or string.find(string.lower(file), "weakness"))) then -- area attack or area heal local targets = {}; if(target_id <= 4) then local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 1); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 2); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 3); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 4); table.insert(targets, target); elseif(target_id >= 5) then local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 5); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 6); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 7); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 8); table.insert(targets, target); end local caster, __ = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_multiple(9991, caster, targets, file, {{100, 200, 300, 400}}, { {target_wards = "6,6,6,", last_target_wards = "0,0,6", target_charms = tostring(charm_key_id_mapping[key])..",2", last_target_charms = "0,2,"}, {target_wards = "6,6,6,", last_target_wards = "0,0,6", target_charms = tostring(charm_key_id_mapping[key])..",2", last_target_charms = "0,2,"}, {target_wards = "6,6,6,", last_target_wards = "0,0,6", target_charms = tostring(charm_key_id_mapping[key])..",2", last_target_charms = "0,2,"}, {target_wards = "6,6,6,", last_target_wards = "0,0,6", target_charms = tostring(charm_key_id_mapping[key])..",2", last_target_charms = "0,2,"}, }, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "area") and (string.find(string.lower(file), "shield") or string.find(string.lower(file), "prism") or string.find(string.lower(file), "absorb") or string.find(string.lower(file), "trap"))) then -- area attack or area heal local targets = {}; if(target_id <= 4) then local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 1); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 2); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 3); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 4); table.insert(targets, target); elseif(target_id >= 5) then local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 5); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 6); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 7); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 8); table.insert(targets, target); end local caster, __ = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_multiple(9991, caster, targets, file, {{100, 200, 300, 400}}, { {target_wards = tostring(ward_key_id_mapping[key])..",6,6,", last_target_wards = "0,6,6", target_charms = "1,2,", last_target_charms = "1,2"}, {target_wards = tostring(ward_key_id_mapping[key])..",6,6,", last_target_wards = "0,6,6", target_charms = "1,2,", last_target_charms = "1,2"}, {target_wards = tostring(ward_key_id_mapping[key])..",6,6,", last_target_wards = "0,6,6", target_charms = "1,2,", last_target_charms = "1,2"}, {target_wards = tostring(ward_key_id_mapping[key])..",6,6,", last_target_wards = "0,6,6", target_charms = "1,2,", last_target_charms = "1,2"}, }, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "area")) then -- area attack or area heal local targets = {}; if(target_id <= 4) then local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 1); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 2); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 3); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 4); table.insert(targets, target); elseif(target_id >= 5) then local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 5); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 6); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 7); table.insert(targets, target); local _, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, 8); table.insert(targets, target); end local caster, __ = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_multiple(9991, caster, targets, file, {{100, 200, 300, 400}}, nil, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "singleattackwithlifetap")) then -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{100},{25}}, nil, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "singleattackwithpercent")) then -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{200},{100}}, nil, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "singleattackwithimmolate")) then -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{600},{250}}, nil, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "singlehealwithimmolate")) then -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{700},{250}}, nil, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "stealpositivecharm")) then -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{100}}, {{target_wards = "6,6,6,", last_target_wards = "0,0,6", target_charms = "0,2,", last_target_charms = "1,2", caster_wards = "6,6,6,", last_caster_wards = "0,0,6", caster_charms = "1,2,", last_caster_charms = "0,2"}}, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "stealpositiveward")) then -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{100}}, {{target_wards = "0,6,6,", last_target_wards = "6,6,6", target_charms = "0,2,", last_target_charms = "1,2", caster_wards = "6,6,6,", last_caster_wards = "0,6,6", caster_charms = "1,2,", last_caster_charms = "0,2"}}, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "blade") or string.find(string.lower(file), "weakness")) then -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{100}}, {{ target_wards = "6,6,6,", last_target_wards = "0,6,6", target_charms = tostring(charm_key_id_mapping[key])..",2,", last_target_charms = "0,2", caster_wards = "6,6,6,", last_caster_wards = "0,6,6", caster_charms = "1,2,", last_caster_charms = "0,2" }}, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); elseif(string.find(string.lower(file), "shield") or string.find(string.lower(file), "trap") or string.find(string.lower(file), "prism") or string.find(string.lower(file), "absorb")) then -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{100}}, {{ target_wards = tostring(ward_key_id_mapping[key])..",6,6,", last_target_wards = "0,6,6", target_charms = "0,2,", last_target_charms = "0,2", caster_wards = "6,6,6,", last_caster_wards = "0,6,6", caster_charms = "1,2,", last_caster_charms = "0,2" }}, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); else -- single spell local caster, target = MotionRender_SpellCastViewer.GetCasterAndTarget(caster_id, target_id) SpellPlayer.PlaySpellEffect_single(9991, caster, target, file, {{100}}, {{target_wards = "6,6,6,", last_target_wards = "0,0,6", target_charms = "1,2,", last_target_charms = "0,2", caster_wards = "6,6,6,", last_caster_wards = "0,0,6", caster_charms = "1,2,", last_caster_charms = "0,2"}}, MotionRender_SpellCastViewer.SpellFinishedCallback, nil, true, nil, playing_id); end else -- if the arena is not created, use the character and the selected object as the caster and the target local caster_char = ParaScene.GetPlayer(); local target_char = System.obj.GetObject("selection"); if(caster_char and caster_char:IsValid() == true and target_char and target_char:IsValid() == true) then --SpellCast.FaceEachOther(caster_char, target_char) SpellCast.EntitySpellCast(nil, caster_char, nil, target_char, nil, file); end end end function MotionRender_SpellCastViewer.StopSpellCasting() local self = MotionRender_SpellCastViewer; ParaScene.GetAttributeObject():CallField("ClearParticles"); local k,uid; for k,uid in pairs(self.play_id_map) do SpellCast.StopSpellCasting(uid); end self.play_id_map = {}; end function MotionRender_SpellCastViewer.SpellFinishedCallback() --do nothing end
gpl-2.0
xstatic/jaxfoodie
sites/all/themes/illusion/templates/node/testimonials/node--view--testimonials--block-home.tpl.php
1315
<?php global $default_img; $image = $default_img; if(isset($node->field_image['und'])) { $image = file_create_url($node->field_image['und'][0]['uri']); } ?> <div> <!--quote--> <blockquote class="r_corners relative type_2 fs_large color_dark m_bottom_20"> <?php print $node->body['und'][0]['value']; ?> </blockquote> <div class="d_table w_full"> <div class="d_table_cell"> <!--author photo--> <div class="d_inline_m circle wrapper m_right_10"> <img src="<?php echo $image; ?>" alt=""> </div> <!--author name--> <div class="d_inline_m"> <b class="fs_large d_block color_light"><?php echo $node->field_client['und'][0]['value']; ?></b> <p class="fs_medium color_grey_light_2"><?php echo $node->field_regency['und'][0]['value']; ?>, <?php echo $node->field_company['und'][0]['value']; ?></p> </div> </div> <div class="d_table_cell t_align_r v_align_m d_mxs_none"> <button class="circle icon_wrap_size_5 color_grey_light d_inline_m color_blue_hover m_right_5 tr_all t_nav_prev"> <i class="icon-left-open-big"></i> </button> <button class="circle icon_wrap_size_5 color_grey_light d_inline_m color_blue_hover tr_all t_nav_next"> <i class="icon-right-open-big"></i> </button> </div> </div> </div>
gpl-2.0
PodcastScience/ps-home
wp-content/themes/iblog/page_fullwidth.php
153
<?php /* Template Name: PS Page FullWidth */ ?> <?php get_header(); ?> <?php get_template_part('library/template_fullwidth');?> <?php get_footer(); ?>
gpl-2.0
yyl/btc-price-analysis
googletrend.py
3750
#!/usr/bin/python import pandas as pd import datetime import numpy as np import scipy as sp import os import matplotlib.pyplot as plt import matplotlib import scriptine ## non-standard import import secrets os.chdir(secrets.ROOT) ##### constants time_format = "%Y-%m-%dT%H:%M:%S" def parseWeek(w): """parse data from google trend""" return w.split(" - ")[1] def truthLabel(cur,prev): """add rise/fall groundtruth label to price data""" if cur == prev: return 0 elif cur > prev: return 1 else: return -1 def preprocess(): """preprocessing step of google trend classifier; return a DataFrame""" ## read search interest index (SII) data trend = pd.read_csv("./data/trend.csv", converters={0:parseWeek}) trend['Week'] = pd.to_datetime(trend['Week']) trend.set_index(['Week'], inplace=True) trend.columns = ['search'] ## read bitcoin price data data = pd.read_csv("./data/price.csv", names=['time', 'price'], index_col='time', parse_dates=[0], date_parser=lambda x: datetime.datetime.strptime(x[:-6], time_format)) bpi = data.resample('w-sat', how='ohlc') bpi.index.name = 'Week' ## use weekly close price only bpi = pd.DataFrame(bpi['price']['close']) ## merge two datasets trend_bpi = pd.merge(trend, bpi, how='right', left_index=True, right_index=True) trend_bpi.columns = ['SII', 'close_price'] trend_bpi = trend_bpi['2012':] ## add ground truth label to weekly price trend_bpi['truth'] = np.vectorize(truthLabel)(trend_bpi.close_price, trend_bpi.close_price.shift(1)) return trend_bpi def algorithm(data, delta_t, diff, inverse=False): """rule-based classifier with google trend search data. Search index rises => price will fall next week. Keyword arguments: data -- DataFrame used to generate prediction delta_t -- the number of weeks in calculating rolling_SII diff -- the threshold of difference between current SII and previous rolling SII inverse -- change the algorithm so that search index rises => price will rise next week """ ## compute rolling mean of SII given delta_t data['rolling_SII'] = pd.rolling_mean(data.SII, delta_t) ## shift rolling mean one week ahead data['rolling_SII_shifted'] = data.rolling_SII.shift(1) ## calculate difference of current SII and rolling SII (shifted) data['SII_diff'] = data.SII - data.rolling_SII_shifted ## generate prediction, which is also order signal data['order'] = 0 if not inverse: ## SII_diff >= diff => search interest rises this week => price rises next week data.loc[data.SII_diff >= diff, 'order'] = -1 ## SII_diff < diff => search interest falls this week => price falls next week data.loc[data.SII_diff < diff, 'order'] = 1 else: ## SII_diff >= diff => search interest rises this week => price rises next week data.loc[data.SII_diff >= diff, 'order'] = 1 ## SII_diff < diff => search interest falls this week => price falls next week data.loc[data.SII_diff < diff, 'order'] = -1 #return data def evaluate(trend_bpi): """return true positive rate anf false positive rate""" ## calculate evaluation metric ## price rise as positive class, fall as negative true_positive = trend_bpi[(trend_bpi.truth==1)&(trend_bpi.order==1)].order.count() false_negative = trend_bpi[(trend_bpi.truth==1)&(trend_bpi.order==-1)].order.count() false_positive = trend_bpi[(trend_bpi.truth==-1)&(trend_bpi.order==1)].order.count() true_negative = trend_bpi[(trend_bpi.truth==-1)&(trend_bpi.order==-1)].order.count() ## true positive rate and false positive rate (used to plot ROC) tp_rate = float(true_positive) /(true_positive+false_negative) fp_rate = float(false_positive) /(true_negative+false_positive) # print "TPR: %f, FPR: %f" % (tp_rate, fp_rate) return tp_rate, fp_rate
gpl-2.0
gppezzi/easybuild-framework
easybuild/toolchains/cgmpich.py
1564
## # Copyright 2013-2019 Ghent University # # This file is triple-licensed under GPLv2 (see below), MIT, and # BSD three-clause licenses. # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for cgompi compiler toolchain (includes Clang, GFortran and MPICH). :author: Dmitri Gribenko (National Technical University of Ukraine "KPI") """ from easybuild.toolchains.clanggcc import ClangGcc from easybuild.toolchains.mpi.mpich import Mpich class Cgmpich(ClangGcc, Mpich): """Compiler toolchain with Clang, GFortran and MPICH.""" NAME = 'cgmpich' SUBTOOLCHAIN = ClangGcc.NAME
gpl-2.0
jrwren/nepenthes
modules/vuln-optix/OPTIXBindDialogue.cpp
3377
/******************************************************************************** * Nepenthes * - finest collection - * * * * Copyright (C) 2005 Paul Baecher & Markus Koetter * * 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. * * * contact [email protected] * *******************************************************************************/ /* $Id$ */ #include "vuln-optix.hpp" #include "OPTIXBindDialogue.hpp" #include "OPTIXDownloadHandler.hpp" #include "SocketManager.hpp" #include "Message.hpp" #include "DownloadManager.hpp" #include "LogManager.hpp" #include "Utilities.hpp" #include "DialogueFactoryManager.hpp" #ifdef STDTAGS #undef STDTAGS #endif #define STDTAGS l_mod using namespace nepenthes; /** * Dialogue::Dialogue(Socket *) * construktor for the OPTIXBindDialogue, creates a new OPTIXBindDialogue * * * * @param socket the Socket the Dialogue has to use */ OPTIXBindDialogue::OPTIXBindDialogue(Socket *socket, OPTIXDownloadHandler *handler) { m_Socket = socket; m_DialogueName = "OPTIXBindDialogue"; m_DialogueDescription = "Optix Bindport Dialogue so we can handle timeouts"; m_ConsumeLevel = CL_ASSIGN; m_DownloadHandler = handler; } OPTIXBindDialogue::~OPTIXBindDialogue() { m_DownloadHandler->setDialogue(NULL); m_DownloadHandler->setSocket(NULL); } /** * Dialogue::incomingData(Message *) * * @param msg the Message the Socker received. * * * @return CL_ASSIGN */ ConsumeLevel OPTIXBindDialogue::incomingData(Message *msg) { return CL_ASSIGN; } /** * Dialogue::outgoingData(Message *) * as we are not interested in these socket actions * we simply return CL_DROP to show the socket * * @param msg * * @return CL_DROP */ ConsumeLevel OPTIXBindDialogue::outgoingData(Message *msg) { return m_ConsumeLevel; } /** * Dialogue::handleTimeout(Message *) * as we are not interested in these socket actions * we simply return CL_DROP to show the socket * * @param msg * * @return CL_DROP */ ConsumeLevel OPTIXBindDialogue::handleTimeout(Message *msg) { return CL_DROP; } /** * Dialogue::connectionLost(Message *) * as we are not interested in these socket actions * we simply return CL_DROP to show the socket * * @param msg * * @return CL_DROP */ ConsumeLevel OPTIXBindDialogue::connectionLost(Message *msg) { return CL_DROP; } /** * Dialogue::connectionShutdown(Message *) * as we are not interested in these socket actions * we simply return CL_DROP to show the socket * * @param msg * * @return CL_DROP */ ConsumeLevel OPTIXBindDialogue::connectionShutdown(Message *msg) { return CL_DROP; }
gpl-2.0
sudheendrachari/sudheendrachari.github.io
bookmyshow-notify/mail.js
1271
(function(module) { var nodemailer = require('nodemailer'); var generator = require('xoauth2').createXOAuth2Generator({ user: '', clientId: '', clientSecret: '', refreshToken: '', accessToken: '' // optional }); // listen for token updates // you probably want to store these to a db generator.on('token', function(token) { console.log('New token for %s: %s', token.user, token.accessToken); }); // login var transporter = nodemailer.createTransport(({ service: 'gmail', auth: { xoauth2: generator } })); var mailOptions = { from: '', to: '', subject: 'hello world!' }; var sendMail = function(movie_name) { mailOptions.subject = 'BMS-APP Alert'; mailOptions.text = movie_name; // send mail transporter.sendMail(mailOptions, function(error, info){ if(error){ return console.log(error); } console.log('Mail sent to : ' + mailOptions.to +'\n' + info.response); console.log('Exiting BMS-APP'); process.exit(); }); }; module.exports = { sendMail: sendMail }; })(module);
gpl-2.0
sjhalaz/hypertable
src/cc/Common/md5.cc
13515
/** * Copyright (C) 2007 Doug Judd (Zvents, Inc.) * * This file is part of Hypertable. * * Hypertable 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 any later version. * * Hypertable 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. */ /* * The MD5 algorithm was designed by Ron Rivest in 1991. * * http://www.ietf.org/rfc/rfc1321.txt */ #define SELF_TEST 1 #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 #endif #include <string.h> #include <stdio.h> #include <stdint.h> #include "md5.h" /* * Translation Table as described in RFC 4648 */ static const char mb64_charset[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; /* * 32-bit integer manipulation macros (little endian) */ #ifndef GET_UINT32_LE #define GET_UINT32_LE(n,b,i) \ { \ (n) = ( (unsigned long) (b)[(i) ] ) \ | ( (unsigned long) (b)[(i) + 1] << 8 ) \ | ( (unsigned long) (b)[(i) + 2] << 16 ) \ | ( (unsigned long) (b)[(i) + 3] << 24 ); \ } #endif #ifndef PUT_UINT32_LE #define PUT_UINT32_LE(n,b,i) \ { \ (b)[(i) ] = (unsigned char) ( (n) ); \ (b)[(i) + 1] = (unsigned char) ( (n) >> 8 ); \ (b)[(i) + 2] = (unsigned char) ( (n) >> 16 ); \ (b)[(i) + 3] = (unsigned char) ( (n) >> 24 ); \ } #endif /* * MD5 context setup */ void md5_starts( md5_context *ctx ) { ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; } static void md5_process( md5_context *ctx, const unsigned char data[64] ) { unsigned long X[16], A, B, C, D; GET_UINT32_LE( X[0], data, 0 ); GET_UINT32_LE( X[1], data, 4 ); GET_UINT32_LE( X[2], data, 8 ); GET_UINT32_LE( X[3], data, 12 ); GET_UINT32_LE( X[4], data, 16 ); GET_UINT32_LE( X[5], data, 20 ); GET_UINT32_LE( X[6], data, 24 ); GET_UINT32_LE( X[7], data, 28 ); GET_UINT32_LE( X[8], data, 32 ); GET_UINT32_LE( X[9], data, 36 ); GET_UINT32_LE( X[10], data, 40 ); GET_UINT32_LE( X[11], data, 44 ); GET_UINT32_LE( X[12], data, 48 ); GET_UINT32_LE( X[13], data, 52 ); GET_UINT32_LE( X[14], data, 56 ); GET_UINT32_LE( X[15], data, 60 ); #define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) #define P(a,b,c,d,k,s,t) \ { \ a += F(b,c,d) + X[k] + t; a = S(a,s) + b; \ } A = ctx->state[0]; B = ctx->state[1]; C = ctx->state[2]; D = ctx->state[3]; #define F(x,y,z) (z ^ (x & (y ^ z))) P( A, B, C, D, 0, 7, 0xD76AA478 ); P( D, A, B, C, 1, 12, 0xE8C7B756 ); P( C, D, A, B, 2, 17, 0x242070DB ); P( B, C, D, A, 3, 22, 0xC1BDCEEE ); P( A, B, C, D, 4, 7, 0xF57C0FAF ); P( D, A, B, C, 5, 12, 0x4787C62A ); P( C, D, A, B, 6, 17, 0xA8304613 ); P( B, C, D, A, 7, 22, 0xFD469501 ); P( A, B, C, D, 8, 7, 0x698098D8 ); P( D, A, B, C, 9, 12, 0x8B44F7AF ); P( C, D, A, B, 10, 17, 0xFFFF5BB1 ); P( B, C, D, A, 11, 22, 0x895CD7BE ); P( A, B, C, D, 12, 7, 0x6B901122 ); P( D, A, B, C, 13, 12, 0xFD987193 ); P( C, D, A, B, 14, 17, 0xA679438E ); P( B, C, D, A, 15, 22, 0x49B40821 ); #undef F #define F(x,y,z) (y ^ (z & (x ^ y))) P( A, B, C, D, 1, 5, 0xF61E2562 ); P( D, A, B, C, 6, 9, 0xC040B340 ); P( C, D, A, B, 11, 14, 0x265E5A51 ); P( B, C, D, A, 0, 20, 0xE9B6C7AA ); P( A, B, C, D, 5, 5, 0xD62F105D ); P( D, A, B, C, 10, 9, 0x02441453 ); P( C, D, A, B, 15, 14, 0xD8A1E681 ); P( B, C, D, A, 4, 20, 0xE7D3FBC8 ); P( A, B, C, D, 9, 5, 0x21E1CDE6 ); P( D, A, B, C, 14, 9, 0xC33707D6 ); P( C, D, A, B, 3, 14, 0xF4D50D87 ); P( B, C, D, A, 8, 20, 0x455A14ED ); P( A, B, C, D, 13, 5, 0xA9E3E905 ); P( D, A, B, C, 2, 9, 0xFCEFA3F8 ); P( C, D, A, B, 7, 14, 0x676F02D9 ); P( B, C, D, A, 12, 20, 0x8D2A4C8A ); #undef F #define F(x,y,z) (x ^ y ^ z) P( A, B, C, D, 5, 4, 0xFFFA3942 ); P( D, A, B, C, 8, 11, 0x8771F681 ); P( C, D, A, B, 11, 16, 0x6D9D6122 ); P( B, C, D, A, 14, 23, 0xFDE5380C ); P( A, B, C, D, 1, 4, 0xA4BEEA44 ); P( D, A, B, C, 4, 11, 0x4BDECFA9 ); P( C, D, A, B, 7, 16, 0xF6BB4B60 ); P( B, C, D, A, 10, 23, 0xBEBFBC70 ); P( A, B, C, D, 13, 4, 0x289B7EC6 ); P( D, A, B, C, 0, 11, 0xEAA127FA ); P( C, D, A, B, 3, 16, 0xD4EF3085 ); P( B, C, D, A, 6, 23, 0x04881D05 ); P( A, B, C, D, 9, 4, 0xD9D4D039 ); P( D, A, B, C, 12, 11, 0xE6DB99E5 ); P( C, D, A, B, 15, 16, 0x1FA27CF8 ); P( B, C, D, A, 2, 23, 0xC4AC5665 ); #undef F #define F(x,y,z) (y ^ (x | ~z)) P( A, B, C, D, 0, 6, 0xF4292244 ); P( D, A, B, C, 7, 10, 0x432AFF97 ); P( C, D, A, B, 14, 15, 0xAB9423A7 ); P( B, C, D, A, 5, 21, 0xFC93A039 ); P( A, B, C, D, 12, 6, 0x655B59C3 ); P( D, A, B, C, 3, 10, 0x8F0CCC92 ); P( C, D, A, B, 10, 15, 0xFFEFF47D ); P( B, C, D, A, 1, 21, 0x85845DD1 ); P( A, B, C, D, 8, 6, 0x6FA87E4F ); P( D, A, B, C, 15, 10, 0xFE2CE6E0 ); P( C, D, A, B, 6, 15, 0xA3014314 ); P( B, C, D, A, 13, 21, 0x4E0811A1 ); P( A, B, C, D, 4, 6, 0xF7537E82 ); P( D, A, B, C, 11, 10, 0xBD3AF235 ); P( C, D, A, B, 2, 15, 0x2AD7D2BB ); P( B, C, D, A, 9, 21, 0xEB86D391 ); #undef F ctx->state[0] += A; ctx->state[1] += B; ctx->state[2] += C; ctx->state[3] += D; } /* * MD5 process buffer */ void md5_update( md5_context *ctx, const unsigned char *input, int ilen ) { int fill; unsigned long left; if( ilen <= 0 ) return; left = ctx->total[0] & 0x3F; fill = 64 - left; ctx->total[0] += ilen; ctx->total[0] &= 0xFFFFFFFF; if( ctx->total[0] < (unsigned long) ilen ) ctx->total[1]++; if( left && ilen >= fill ) { memcpy( (void *) (ctx->buffer + left), (void *) input, fill ); md5_process( ctx, ctx->buffer ); input += fill; ilen -= fill; left = 0; } while( ilen >= 64 ) { md5_process( ctx, input ); input += 64; ilen -= 64; } if( ilen > 0 ) { memcpy( (void *) (ctx->buffer + left), (void *) input, ilen ); } } static const unsigned char md5_padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* * MD5 final digest */ void md5_finish( md5_context *ctx, unsigned char output[16] ) { unsigned long last, padn; unsigned long high, low; unsigned char msglen[8]; high = ( ctx->total[0] >> 29 ) | ( ctx->total[1] << 3 ); low = ( ctx->total[0] << 3 ); PUT_UINT32_LE( low, msglen, 0 ); PUT_UINT32_LE( high, msglen, 4 ); last = ctx->total[0] & 0x3F; padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last ); md5_update( ctx, (unsigned char *) md5_padding, padn ); md5_update( ctx, msglen, 8 ); PUT_UINT32_LE( ctx->state[0], output, 0 ); PUT_UINT32_LE( ctx->state[1], output, 4 ); PUT_UINT32_LE( ctx->state[2], output, 8 ); PUT_UINT32_LE( ctx->state[3], output, 12 ); } /* * Output = MD5( file contents ) */ int md5_file( char *path, unsigned char output[16] ) { FILE *f; size_t n; md5_context ctx; unsigned char buf[1024]; if( ( f = fopen( path, "rb" ) ) == NULL ) return( 1 ); md5_starts( &ctx ); while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 ) md5_update( &ctx, buf, (int) n ); md5_finish( &ctx, output ); fclose( f ); return( 0 ); } /* * Output = MD5( input buffer ) */ void md5_csum( const unsigned char *input, int ilen, unsigned char output[16] ) { md5_context ctx; md5_starts( &ctx ); md5_update( &ctx, input, ilen ); md5_finish( &ctx, output ); } /* * Output = HMAC-MD5( input buffer, hmac key ) */ void md5_hmac( unsigned char *key, int keylen, const unsigned char *input, int ilen, unsigned char output[16] ) { int i; md5_context ctx; unsigned char k_ipad[64]; unsigned char k_opad[64]; unsigned char tmpbuf[16]; memset( k_ipad, 0x36, 64 ); memset( k_opad, 0x5C, 64 ); for( i = 0; i < keylen; i++ ) { if( i >= 64 ) break; k_ipad[i] ^= key[i]; k_opad[i] ^= key[i]; } md5_starts( &ctx ); md5_update( &ctx, k_ipad, 64 ); md5_update( &ctx, input, ilen ); md5_finish( &ctx, tmpbuf ); md5_starts( &ctx ); md5_update( &ctx, k_opad, 64 ); md5_update( &ctx, tmpbuf, 16 ); md5_finish( &ctx, output ); memset( k_ipad, 0, 64 ); memset( k_opad, 0, 64 ); memset( tmpbuf, 0, 16 ); memset( &ctx, 0, sizeof( md5_context ) ); } static const char _md5_src[] = "_md5_src"; static const char hex_digits[] = "0123456789ABCDEF"; void md5_hex(const void *input, size_t len, char output[33]) { md5_context ctx; unsigned char digest[16]; md5_starts(&ctx); md5_update(&ctx, (const unsigned char *)input, len); md5_finish(&ctx, digest); int index, j=0; for (int i=0; i<16; i++) { index = (digest[i] & 0xF0) >> 4; output[j++] = hex_digits[index]; index = digest[i] & 0x0F; output[j++] = hex_digits[index]; } output[j] = 0; } void md5_string(const char *input, char output[33]) { md5_hex(input, strlen(input), output); } int64_t md5_hash(const char *input) { md5_context ctx; unsigned char digest[16]; int64_t hash; md5_starts(&ctx); md5_update(&ctx, (const unsigned char *)input, strlen(input)); md5_finish(&ctx, digest); memcpy(&hash, digest, sizeof(int64_t)); return hash; } void digest_to_trunc_modified_base64(const char digest[16], char output[17]) { int digest_pos=0; int output_pos=0; while (digest_pos < 12) { // Convert next 3 bytes of digest into 4 bytes of 6 bit chars output[output_pos] = (digest[digest_pos] & 0xfc) >> 2; output[output_pos+1] = ((digest[digest_pos] & 0x03) << 4) | ((digest[digest_pos+1] & 0xf0) >> 4); output[output_pos+2] = ((digest[digest_pos+1] & 0x0f) << 2) | ((digest[digest_pos+2] & 0xc0) >> 6); output[output_pos+3] = digest[digest_pos+2] & 0x3f; // Convert 6 bit chars to modified base64 char for(int ii=0; ii<4; ++ii) output[output_pos+ii] = mb64_charset[(unsigned)output[output_pos+ii]]; output_pos += 4; digest_pos += 3; } output[16]='\0'; } void md5_trunc_modified_base64(const char *input, char output[17]) { md5_context ctx; unsigned char digest[16]; size_t len = strlen(input); md5_starts(&ctx); md5_update(&ctx, (const unsigned char *)input, len); md5_finish(&ctx, digest); digest_to_trunc_modified_base64((const char *)digest, output); } #ifdef SELF_TEST /* * RFC 1321 test vectors */ static const char md5_test_str[7][81] = { { "" }, { "a" }, { "abc" }, { "message digest" }, { "abcdefghijklmnopqrstuvwxyz" }, { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" }, { "12345678901234567890123456789012345678901234567890123456789012" \ "345678901234567890" } }; static const unsigned char md5_test_sum[7][16] = { { 0xD4, 0x1D, 0x8C, 0xD9, 0x8F, 0x00, 0xB2, 0x04, 0xE9, 0x80, 0x09, 0x98, 0xEC, 0xF8, 0x42, 0x7E }, { 0x0C, 0xC1, 0x75, 0xB9, 0xC0, 0xF1, 0xB6, 0xA8, 0x31, 0xC3, 0x99, 0xE2, 0x69, 0x77, 0x26, 0x61 }, { 0x90, 0x01, 0x50, 0x98, 0x3C, 0xD2, 0x4F, 0xB0, 0xD6, 0x96, 0x3F, 0x7D, 0x28, 0xE1, 0x7F, 0x72 }, { 0xF9, 0x6B, 0x69, 0x7D, 0x7C, 0xB7, 0x93, 0x8D, 0x52, 0x5A, 0x2F, 0x31, 0xAA, 0xF1, 0x61, 0xD0 }, { 0xC3, 0xFC, 0xD3, 0xD7, 0x61, 0x92, 0xE4, 0x00, 0x7D, 0xFB, 0x49, 0x6C, 0xCA, 0x67, 0xE1, 0x3B }, { 0xD1, 0x74, 0xAB, 0x98, 0xD2, 0x77, 0xD9, 0xF5, 0xA5, 0x61, 0x1C, 0x2C, 0x9F, 0x41, 0x9D, 0x9F }, { 0x57, 0xED, 0xF4, 0xA2, 0x2B, 0xE3, 0xC9, 0x55, 0xAC, 0x49, 0xDA, 0x2E, 0x21, 0x07, 0xB6, 0x7A } }; /* * Checkup routine */ int md5_self_test( void ) { int i; unsigned char md5sum[16]; for( i = 0; i < 7; i++ ) { printf( " MD5 test #%d: ", i + 1 ); md5_csum( (unsigned char *) md5_test_str[i], strlen( md5_test_str[i] ), md5sum ); if( memcmp( md5sum, md5_test_sum[i], 16 ) != 0 ) { printf( "failed\n" ); return( 1 ); } printf( "passed\n" ); } printf( "\n" ); return( 0 ); } #else int md5_self_test( void ) { return( 0 ); } #endif
gpl-2.0
carlosway89/testshop
lang/german/original_sections/admin/gm_pdf_action.lang.inc.php
7169
<?php /* -------------------------------------------------------------- gm_pdf_action.lang.inc.php 2015-01-02 gm Gambio GmbH http://www.gambio.de Copyright (c) 2015 Gambio GmbH Released under the GNU General Public License (Version 2) [http://www.gnu.org/licenses/gpl-2.0.html] -------------------------------------------------------------- */ $t_language_text_section_content_array = array ( 'BUTTON_SAVE' => 'Speichern', 'ERROR_NOT_NUMERIC' => ' muss numerisch sein!', 'GM_LOGO_PDF_USE' => 'Logo verwenden?', 'GM_PDF_ORDER_STATUS_INVOICE' => 'Bestellstatus nach Rechnungserstellung', 'GM_PDF_ORDER_STATUS_INVOICE_DATE' => 'Bestellstatus, der zur Ermittlung des Rechnungsdatum verwendet werden soll', 'GM_PDF_ORDER_STATUS_INVOICE_MAIL' => 'Bestellstatus nach E-Mail Rechnungsversand', 'GM_PDF_ORDER_STATUS_NOT' => 'nicht ändern', 'GM_PDF_TITLE_ALLOW_COPYING' => 'Kopieren der internen Texte und Grafiken erlauben', 'GM_PDF_TITLE_ALLOW_MODIFYING' => 'Modifizieren des PDF-Dokumentes erlauben', 'GM_PDF_TITLE_ALLOW_NOTIFYING' => 'Kommentieren des PDF-Dokumentes erlauben', 'GM_PDF_TITLE_ALLOW_PRINTING' => 'Drucken des PDF-Dokumentes erlauben', 'GM_PDF_TITLE_BOTTOM_MARGIN' => 'Einzug unten', 'GM_PDF_TITLE_CANCEL_FONT_FACE' => 'Storno-Hinweis', 'GM_PDF_TITLE_CELL_HEIGHT' => 'Höhe der Zellen', 'GM_PDF_TITLE_CHOOSE_LOGO' => 'Logo auswählen', 'GM_PDF_TITLE_COMPANY_ADRESS_LEFT' => 'Firmenadresse links', 'GM_PDF_TITLE_COMPANY_ADRESS_RIGHT' => 'Firmenadresse rechts', 'GM_PDF_TITLE_COMPANY_LEFT_FONT_FACE' => 'Firmenadresse links', 'GM_PDF_TITLE_COMPANY_RIGHT_FONT_FACE' => 'Firmenadresse rechts', 'GM_PDF_TITLE_CONDITIONS' => 'AGB', 'GM_PDF_TITLE_CONDITIONS_FONT_FACE' => 'AGB/Widerruf', 'GM_PDF_TITLE_CUSTOMER_ADR_POS' => 'mm Einzug der Kunden Adresse nach oben', 'GM_PDF_TITLE_CUSTOMER_FONT_FACE' => 'Kundenadresse', 'GM_PDF_TITLE_DEFAULT_FONT_FACE' => 'Standardschrift', 'GM_PDF_TITLE_DISPLAY_LAYOUT' => 'Seitenlayout der PDF im Reader', 'GM_PDF_TITLE_DISPLAY_ZOOM' => 'Zoomfaktor der PDF im Reader', 'GM_PDF_TITLE_DRAW_COLOR' => 'Farbe für Linien', 'GM_PDF_TITLE_EMAIL_SUBJECT' => 'E-Mail Betreff', 'GM_PDF_TITLE_EMAIL_SUBJECT_INFO' => '<small>Platzhalter: Rechnungsnr: {INVOICE_ID} Bestellnr: {ORDER_ID} Bestelldatum: {DATE}</small>', 'GM_PDF_TITLE_EMAIL_TEXT' => 'Nachricht', 'GM_PDF_TITLE_EMAIL_TEXT_INFO' => '<small>Platzhalter: Anrede: {SALUTATION} Kundenname: {CUSTOMER} Rechnungsnr: {INVOICE_ID} Bestellnr: {ORDER_ID} Bestelldatum: {DATE}</small>', 'GM_PDF_TITLE_FIX_HEADER' => 'Kopfteil fixieren?', 'GM_PDF_TITLE_FOOTER_CELL_1' => 'Fussteil erste Spalte', 'GM_PDF_TITLE_FOOTER_CELL_2' => 'Fussteil zweite Spalte', 'GM_PDF_TITLE_FOOTER_CELL_3' => 'Fussteil dritte Spalte', 'GM_PDF_TITLE_FOOTER_CELL_4' => 'Fussteil vierte Spalte', 'GM_PDF_TITLE_FOOTER_FONT_FACE' => 'Fussteil', 'GM_PDF_TITLE_HEADING_CONDITIONS' => 'Überschrift AGB', 'GM_PDF_TITLE_HEADING_CONDITIONS_FONT_FACE' => 'Überschrift AGB/Widerruf', 'GM_PDF_TITLE_HEADING_FONT_FACE' => 'Überschrift', 'GM_PDF_TITLE_HEADING_INFO_TEXT_INVOICE' => 'Überschrift Rechnungshinweis', 'GM_PDF_TITLE_HEADING_INFO_TEXT_PACKINGSLIP' => 'Überschrift Lieferhinweis', 'GM_PDF_TITLE_HEADING_INVOICE' => 'Überschrift Rechnung', 'GM_PDF_TITLE_HEADING_MARGIN_BOTTOM' => 'Einzug der Überschrift nach unten', 'GM_PDF_TITLE_HEADING_MARGIN_TOP' => 'Einzug der Überschrift nach oben', 'GM_PDF_TITLE_HEADING_ORDER_FONT_FACE' => 'Bestell-Tabellenkopf', 'GM_PDF_TITLE_HEADING_ORDER_INFO_FONT_FACE' => 'Überschrift Hinweis', 'GM_PDF_TITLE_HEADING_PACKINGSLIP' => 'Überschrift Lieferschein', 'GM_PDF_TITLE_HEADING_WITHDRAWAL' => 'Überschrift Widerruf', 'GM_PDF_TITLE_INFO_TEXT_INVOICE' => 'Hinweistext Rechnung', 'GM_PDF_TITLE_INFO_TEXT_PACKINGSLIP' => 'Hinweistext Lieferschein', 'GM_PDF_TITLE_INFO_TITLE_INVOICE' => 'Hinweistitel Rechnung', 'GM_PDF_TITLE_INFO_TITLE_PACKINGSLIP' => 'Hinweistitel Lieferschein', 'GM_PDF_TITLE_LEFT_MARGIN' => 'Einzug links', 'GM_PDF_TITLE_ORDER_FONT_FACE' => 'Bestell-Tabelle', 'GM_PDF_TITLE_ORDER_INFO_FONT_FACE' => 'Hinweistext', 'GM_PDF_TITLE_ORDER_INFO_MARGIN_TOP' => 'Einzug des Hinweises nach oben', 'GM_PDF_TITLE_ORDER_TOTAL_FONT_FACE' => 'Bestell-Zusammenfassung', 'GM_PDF_TITLE_RIGHT_MARGIN' => 'Einzug rechts', 'GM_PDF_TITLE_TOP_MARGIN' => 'Einzug oben', 'GM_PDF_TITLE_USE_CONDITIONS' => 'AGB verwenden?', 'GM_PDF_TITLE_USE_CUSTOMER_CODE' => 'Kundennummer verwenden?', 'GM_PDF_TITLE_USE_CUSTOMER_COMMENT' => 'Kundenkommentar verwenden?', 'GM_PDF_TITLE_USE_DATE' => 'aktuelles Datum verwenden?', 'GM_PDF_TITLE_USE_FOOTER' => 'Fussteil verwenden?', 'GM_PDF_TITLE_USE_HEADER' => 'Kopfteil verwenden?', 'GM_PDF_TITLE_USE_INFO' => 'Hinweis verwenden?', 'GM_PDF_TITLE_USE_INFO_TEXT' => 'Hinweistext verwenden?', 'GM_PDF_TITLE_USE_INVOICE_CODE' => 'Rechnungsummer verwenden?', 'GM_PDF_TITLE_USE_ORDER_CODE' => 'Bestellnummer verwenden?', 'GM_PDF_TITLE_USE_ORDER_DATE' => 'Bestelldatum verwenden?', 'GM_PDF_TITLE_USE_PACKING_CODE' => 'Liefernummer verwenden?', 'GM_PDF_TITLE_USE_PRODUCTS_MODEL' => 'Spalte "Artikel Nr" Verwenden?', 'GM_PDF_TITLE_USE_PROTECTION' => 'PDF Dokument schützen?', 'GM_PDF_TITLE_USE_WITHDRAWAL' => 'Widerruf verwenden?', 'GM_PDF_TITLE_WITHDRAWAL' => 'Widerruf', 'MENU_TITLE_CONDITIONS' => 'AGB/Widerruf', 'MENU_TITLE_CONF' => 'Konfiguration', 'MENU_TITLE_CONTENT' => 'Inhalt', 'MENU_TITLE_DISPLAY' => 'Anzeige', 'MENU_TITLE_EMAIL_TEXT' => 'E-Mail Rechnung', 'MENU_TITLE_FONTS' => 'Schriften', 'MENU_TITLE_FOOTER' => 'Fussteil', 'MENU_TITLE_HEADER' => 'Kopfteil', 'MENU_TITLE_INVOICING' => 'Bestellstatus und Rechnungsdatum', 'MENU_TITLE_LAYOUT' => 'Layout', 'MENU_TITLE_LOGO' => 'Logo', 'MENU_TITLE_ORDER_INFO' => 'Hinweistexte', 'MENU_TITLE_PREVIEW' => 'Vorschau', 'MENU_TITLE_PROTECTION' => 'Sicherheit', 'NOTE_PREVIEW' => 'Bitte beachten Sie, dass in der Vorschau die Rechnungs- bzw. die Lieferscheinnummer nicht generiert werden.<br />Dies geschieht nur unter "Bestellungen". Angezeigt wird jeweils die bereits generierte bzw. vorläufige Nummer.', 'PROCEED' => 'Aktualisiert', 'SELECT_CHOOSE' => 'Wählen', 'SELECT_CUSTOMER' => 'Kunde: ', 'SELECT_DISPLAY_LAYOUT_CONTINUOUS' => 'fortlaufend', 'SELECT_DISPLAY_LAYOUT_DEFAULT' => 'Einstellung des Readers', 'SELECT_DISPLAY_LAYOUT_SINGLE' => 'Seite für Seite', 'SELECT_DISPLAY_LAYOUT_TWO' => 'Zwei Seiten nebeneinander', 'SELECT_DISPLAY_OUTPUT' => 'Ausgabemodus', 'SELECT_DISPLAY_OUTPUT_D' => 'PDF herunterladen', 'SELECT_DISPLAY_OUTPUT_I' => 'PDF im Browser ausgeben', 'SELECT_DISPLAY_ZOOM_DEFAULT' => 'Einstellung des Readers', 'SELECT_DISPLAY_ZOOM_FULLPAGE' => 'volle Seite', 'SELECT_DISPLAY_ZOOM_FULLWIDTH' => 'volle Breite', 'SELECT_DISPLAY_ZOOM_REAL' => '100%', 'SELECT_FONT_STYLE_' => 'kein Stil', 'SELECT_FONT_STYLE_B' => 'fett', 'SELECT_FONT_STYLE_I' => 'kursiv', 'SELECT_FONT_STYLE_U' => 'unterstrichen', 'SELECT_ORDERS' => 'Bestellnr.: ', 'SELECT_USE_0' => 'nein', 'SELECT_USE_1' => 'ja', 'TITLE_INVOICE' => 'Rechnung', 'TITLE_PACKINGSLIP' => 'Lieferschein', 'USE_DATE_INVOICE' => 'Rechnungserstellung', 'USE_DATE_INVOICE_MAIL' => 'E-Mail Rechnungsversand ' );
gpl-2.0
dmchdev/dranik
testheader.py
949
Before: from selenium import webdriver driver = webdriver.Chrome() #driver = webdriver.Firefox() driver.implicitly_wait(20) def handleAlert(): try: alert = driver.switch_to_alert() alert.dismiss() except Exception: pass After: driver.close() driver.quit() # from selenium import webdriver # from selenium.webdriver.support.ui import WebDriverWait # from selenium.webdriver.support import expected_conditions as EC # from selenium.common.exceptions import TimeoutException # browser = webdriver.Firefox() # browser.get("url") # browser.find_the_element_by_id("add_button").click() # try: # WebDriverWait(browser, 3).until(EC.alert_is_present(), # 'Timed out waiting for PA creation ' + # 'confirmation popup to appear.') # alert = browser.switch_to_alert() # alert.accept() # print "alert accepted" # except TimeoutException: # print "no alert"
gpl-2.0
dset0x/inspire-next
inspire/modules/deposit/forms.py
15147
# -*- coding: utf-8 -*- ## ## This file is part of INSPIRE. ## Copyright (C) 2014 CERN. ## ## INSPIRE 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. ## ## INSPIRE 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 INSPIRE; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # """Contains forms related to INSPIRE submission.""" from wtforms import validators from wtforms.widgets import html_params, HTMLString, HiddenInput from invenio.base.i18n import _ from invenio.base.globals import cfg from invenio.modules.deposit import fields from invenio.modules.deposit.form import WebDepositForm from invenio.modules.deposit.field_widgets import plupload_widget, \ ColumnInput, \ ExtendedListWidget, \ ItemWidget from invenio.modules.deposit.autocomplete_utils import kb_dynamic_autocomplete from .fields import ArXivField # from .fields import ISBNField from .validators.dynamic_fields import AuthorsValidation from .filters import clean_empty_list # # Field class names # ARTICLE_CLASS = " article-related" THESIS_CLASS = " thesis-related" CHAPTER_CLASS = " chapter-related" BOOK_CLASS = " book-related" PROCEEDINGS_CLASS = " proceedings-related" # # Custom field widgets # def importdata_button(field, **dummy_kwargs): """Import data button.""" html = u'<button %s data-target="%s">%s</button>' % \ (html_params(id="importData", class_="btn btn-success btn-large", name="importData", type="button"), '#myModal', _('Auto import')) return HTMLString(html) def skip_importdata(field, **dummy_kwargs): """Skip Import data button.""" html = u'<button %s>%s</button>' % \ (html_params(id="skipImportData", class_="btn btn-link", name="skipImportData", type="button"), _('Skip, and fill the form manually')) return HTMLString(html) # # Group buttons of import and skip # def import_buttons_widget(field, **dummy_kwargs): """Buttons for import data and skip""" html_skip = skip_importdata(field) html_import = importdata_button(field) html = [u'<div class="pull-right">' + html_skip + html_import + u'</div>'] return HTMLString(u''.join(html)) # # Tooltips on disabled elements require wrapper elements # def wrap_nonpublic_note(field, **dummy_kwargs): """Proceedings box with tooltip.""" html = u'<div class="tooltip-wrapper" data-toggle="tooltip"' \ 'title="%s"><textarea %s></textarea></div>' % \ (_('Journal Information already exists'), html_params(id="nonpublic_note", class_="form-control nonpublic_note", name="nonpublic_note")) return HTMLString(html) def radiochoice_buttons(field, **dummy_kwargs): """Radio choice buttons.""" html = '' for choice, value in field.choices: html += u'<label class="btn btn-default"> \ <input type="radio" name="%s" id="%s"> \ %s</label>' % (choice, choice, value) html = [u'<div class="btn-group" data-toggle="buttons">' + html + u'</div>'] return HTMLString(u''.join(html)) def defensedate_widget(field, **kwargs): """Date widget fot thesis.""" field_id = kwargs.pop('id', field.id) html = [u'<div class="row %s"><div class="col-xs-5 col-sm-3">\ <input class="datepicker form-control" %s type="text">\ </div></div' % (THESIS_CLASS, html_params(id=field_id, name=field_id, value=field.data or ''))] return HTMLString(u''.join(html)) def institutions_kb_mapper(val): """Return object ready to autocomplete affiliations.""" return { 'value': "%s" % val, 'fields': { "affiliation": val, } } def journal_title_kb_mapper(val): """Return object ready to autocomplete journal titles.""" return { 'value': "%s" % val, 'fields': { "journal_title": val, } } def experiment_kb_mapper(val): """Return object ready to autocomplete experiments.""" return { 'value': "%s" % val, 'fields': { "experiment": val, } } class AuthorInlineForm(WebDepositForm): """Author inline form.""" name = fields.TextField( widget_classes='form-control', widget=ColumnInput(class_="col-xs-6", description="Family name, First name"), # validators=[ # validators.Required(), # ], export_key='full_name', ) affiliation = fields.TextField( autocomplete=kb_dynamic_autocomplete("InstitutionsCollection", mapper=institutions_kb_mapper), placeholder='Start typing for suggestions', autocomplete_limit=5, widget_classes='form-control', widget=ColumnInput(class_="col-xs-4 col-pad-0", description="Affiliation"), export_key='affiliation', ) class UrlInlineForm(WebDepositForm): """Url inline form.""" url = fields.TextField( widget_classes='form-control', widget=ColumnInput(class_="col-xs-10"), export_key='full_url', placeholder='http://www.example.com', ) class LiteratureForm(WebDepositForm): """Literature form fields.""" # captcha = RecaptchaField() doi = fields.DOIField( label=_('DOI'), processors=[], export_key='doi', description='e.g. 10.1234/foo.bar or doi:10.1234/foo.bar', placeholder='' ) arxiv_id = ArXivField( label=_('arXiv ID'), ) # isbn = ISBNField( # label=_('ISBN'), # widget_classes='form-control', # ) import_buttons = fields.SubmitField( label=_(' '), widget=import_buttons_widget ) types_of_doc = [("article", _("Article/Conference paper")), ("thesis", _("Thesis"))] # ("chapter", _("Book Chapter")), # ("book", _("Book")), # ("proceedings", _("Proceedings"))] type_of_doc = fields.SelectField( label='Type of Document', choices=types_of_doc, default="article", #widget=radiochoice_buttons, widget_classes='form-control', validators=[validators.Required()], ) title = fields.TitleField( label=_('Title'), widget_classes="form-control", validators=[validators.Required()], export_key='title', ) title_arXiv = fields.TitleField( export_key='title_arXiv', widget_classes="hidden", widget=HiddenInput(), ) title_translation = fields.TitleField( label=_('Translated Title'), description='Original title translated to english language.', widget_classes="form-control", export_key='title_translation', ) authors = fields.DynamicFieldList( fields.FormField( AuthorInlineForm, widget=ExtendedListWidget( item_widget=ItemWidget(), html_tag='div', ), ), label='Authors', add_label='Add another author', min_entries=1, widget_classes='', export_key='authors', validators=[AuthorsValidation], ) collaboration = fields.TextField( label=_('Collaboration'), widget_classes="form-control" ) experiment = fields.TextField( placeholder=_("Start typing for suggestions"), label=_('Experiment'), widget_classes="form-control", autocomplete=kb_dynamic_autocomplete("dynamic_experiments", mapper=experiment_kb_mapper) ) # this should be a prefilled dropdown subject = fields.SelectMultipleField( label=_('Subject'), widget_classes="form-control", export_key='subject_term', filters=[clean_empty_list] ) abstract = fields.TextAreaField( label=_('Abstract'), default='', widget_classes="form-control", export_key='abstract', ) page_nr = fields.TextField( label=_('Number of Pages'), widget_classes="form-control", export_key='page_nr' ) languages = [("en", _("English")), ("fre", _("French")), ("ger", _("German")), ("dut", _("Dutch")), ("ita", _("Italian")), ("spa", _("Spanish")), ("por", _("Portuguese")), ("gre", _("Greek")), ("slo", _("Slovak")), ("cze", _("Czech")), ("hun", _("Hungarian")), ("pol", _("Polish")), ("nor", _("Norwegian")), ("swe", _("Swedish")), ("fin", _("Finnish")), ("rus", _("Russian")), ("oth", _("Other"))] language = fields.LanguageField( label=_("Language"), choices=languages ) conf_name = fields.TextField( placeholder=_("Start typing for suggestions"), label=_('Conference Information'), description=_('Conference name, acronym, place, date'), widget_classes="form-control" ) conference_id = fields.TextField( export_key='conference_id', widget_classes="hidden", widget=HiddenInput(), ) license_url = fields.TextField( label=_('License URL'), export_key='license_url', widget_classes="hidden", widget=HiddenInput(), ) # ============== # Thesis related # ============== supervisors = fields.DynamicFieldList( fields.FormField( AuthorInlineForm, widget=ExtendedListWidget( item_widget=ItemWidget(), html_tag='div', ), ), label=_('Supervisors'), add_label=_('Add another supervisor'), min_entries=1, export_key='supervisors', widget_classes=THESIS_CLASS, ) defense_date = fields.Date( label=_('Date of Defense'), description='Format: YYYY-MM-DD.', widget=defensedate_widget, ) degree_type = fields.TextField( label=_('Degree type'), widget_classes="form-control" + THESIS_CLASS, ) university = fields.TextField( label=_('University'), widget_classes="form-control" + THESIS_CLASS, ) # ============ # Journal Info # ============ journal_title = fields.TextField( placeholder=_("Start typing for suggestions"), label=_('Journal Title'), widget_classes="form-control", autocomplete=kb_dynamic_autocomplete("dynamic_journal_titles", mapper=journal_title_kb_mapper) ) page_range = fields.TextField( label=_('Page Range'), description=_('e.g. 1-100'), widget_classes="form-control" ) article_id = fields.TextField( label=_('Article ID'), widget_classes="form-control" ) volume = fields.TextField( label=_('Volume'), widget_classes="form-control" ) year = fields.TextField( label=_('Year'), widget_classes="form-control" ) issue = fields.TextField( label=_('Issue'), widget_classes="form-control" ) nonpublic_note = fields.TextAreaField( label=_('Proceedings'), description='Editors, title of proceedings, publisher, year of publication, page range', widget=wrap_nonpublic_note ) note = fields.TextAreaField( export_key='note', widget_classes="hidden", widget=HiddenInput(), ) # ==================== # Fulltext Information # ==================== file_field = fields.FileUploadField( label="", widget=plupload_widget, export_key=False ) url = fields.DynamicFieldList( fields.FormField( UrlInlineForm, widget=ExtendedListWidget( item_widget=ItemWidget(), html_tag='div', ), ), #validators=[validators.URL(), validators.Optional, ], label=_('External URL'), add_label=_('Add another url'), min_entries=1, export_key='url', widget_classes='', ) # ok_to_upload = fields.BooleanField( # label=_('I ensure the file is free to be uploaded.'), # default=False, # validators=[required_if('file_field', # [lambda x: bool(x.strip()), ], # non-empty # message="It's required to check this box." # ), # required_if('url', # [lambda x: bool(x.strip()), ], # non-empty # message="It's required to check this box." # ), # ] # ) # # Form Configuration # _title = _("Literature submission") # Group fields in categories groups = [ ('Import from existing source', ['arxiv_id', 'doi', 'import_buttons']), ('Document Type', ['captcha', 'type_of_doc', ]), ('Basic Information', ['title', 'title_arXiv', 'language', 'title_translation', 'authors', 'collaboration', 'experiment', 'abstract', 'page_nr', 'subject', 'supervisors', 'defense_date', 'degree_type', 'university', 'license_url']), ('Conference Information', ['conf_name', 'conference_id']), ('Journal Information', ['journal_title', 'volume', 'issue', 'page_range', 'article_id', 'year']), ('Proceedings Information (not published in journal)', ['nonpublic_note', 'note']), ('Upload/link files', ['file_field', 'url']), ] field_sizes = { 'file_field': 'col-md-12', 'type_of_doc': 'col-xs-4', 'wrap_nonpublic_note': 'col-md-9', } def __init__(self, *args, **kwargs): """Constructor.""" super(LiteratureForm, self).__init__(*args, **kwargs) from invenio.modules.knowledge.api import get_kb_mappings self.subject.choices = [(x['value'], x['value']) for x in get_kb_mappings(cfg["DEPOSIT_INSPIRE_SUBJECTS_KB"])]
gpl-2.0
felipebravom/TwitterSentLex
src/weka/filters/unsupervised/attribute/LDAFilter.java
11812
package weka.filters.unsupervised.attribute; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Vector; import java.util.regex.Pattern; import cc.mallet.pipe.CharSequence2TokenSequence; import cc.mallet.pipe.CharSequenceLowercase; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.SerialPipes; import cc.mallet.pipe.TokenSequence2FeatureSequence; import cc.mallet.pipe.TokenSequenceRemoveStopwords; import cc.mallet.pipe.iterator.StringArrayIterator; import cc.mallet.topics.ParallelTopicModel; import cc.mallet.topics.TopicInferencer; import cc.mallet.types.InstanceList; import weka.core.*; import weka.core.Capabilities.*; import weka.filters.*; public class LDAFilter extends SimpleBatchFilter { /** * */ private static final long serialVersionUID = 864281599421580096L; /** the model */ private ParallelTopicModel model; /** the training data and the pipes */ private InstanceList instances; /** default number of topics */ protected int numberOfTopics=10; /** the index of the string attribute to be processed */ protected int textIndex=1; /** alpha sum parameter */ protected double alphaSum=1.0; /** beta parameter */ protected double beta=0.01; /** number of threads */ protected int numThreads=1; /** number of iterations */ protected int numIterations=1500; /** number of words to display */ protected int numDispWords=5; // Number of words to display per topic /** * Returns a string describing this clusterer * * @return a description of the evaluator suitable for displaying in the * explorer/experimenter gui */ public String globalInfo() { return " A wrapper class for the Latent Dirichlet Allocation algorithm for topic modelling implemented in the Mallet library." + " http://mallet.cs.umass.edu/lassification."; } @Override public Capabilities getCapabilities() { Capabilities result = new Capabilities(this); result.disableAll(); // attributes result.enableAllAttributes(); result.enable(Capability.MISSING_VALUES); // class result.enableAllClasses(); result.enable(Capability.MISSING_CLASS_VALUES); result.enable(Capability.NO_CLASS); result.setMinimumNumberInstances(0); return result; } /** * Gets an enumeration describing the available options. * * @return an enumeration of all the available options. */ @Override public Enumeration<Option> listOptions() { Vector<Option> result = new Vector<Option>(); result.addElement(new Option("\t Text index.\n" + "\t(default: " + this.numberOfTopics + ")", "D", 1, "-D")); result.addElement(new Option("\t Number of topics.\n" + "\t(default: " + this.numberOfTopics + ")", "N", 1, "-N")); result.addElement(new Option("\t AlphaSum.\n" + "\t(default: " + this.alphaSum + ")", "A", 1, "-A")); result.addElement(new Option("\t Beta.\n" + "\t(default: " + this.beta + ")", "B", 1, "-B")); result.addElement(new Option("\t numThreads.\n" + "\t(default: " + this.numThreads + ")", "P", 1, "-P")); result.addElement(new Option("\t numIterations.\n" + "\t(default: " + this.numIterations + ")", "I", 1, "-I")); result.addElement(new Option("\t numDispWords.\n" + "\t(default: " + this.numDispWords + ")", "W", 1, "-W")); result.addAll(Collections.list(super.listOptions())); return result.elements(); } /** * returns the options of the current setup * * @return the current options */ @Override public String[] getOptions() { Vector<String> result = new Vector<String>(); result.add("-D"); result.add("" + this.textIndex); result.add("-N"); result.add("" + this.numberOfTopics); result.add("-A"); result.add("" + this.alphaSum); result.add("-B"); result.add("" + this.beta); result.add("-P"); result.add("" + this.numThreads); result.add("-I"); result.add("" + this.numIterations); result.add("-W"); result.add("" + this.numDispWords); Collections.addAll(result, super.getOptions()); return result.toArray(new String[result.size()]); } /** * Parses the options for this object. * <p/> * * <!-- options-start --> <!-- options-end --> * * @param options * the options to use * @throws Exception * if setting of options fails */ @Override public void setOptions(String[] options) throws Exception { String textIndexOption = Utils.getOption('D', options); if (textIndexOption.length() > 0) { String[] textIndexSpec = Utils.splitOptions(textIndexOption); if (textIndexSpec.length == 0) { throw new IllegalArgumentException( "Invalid index"); } int textIndexValue = Integer.parseInt(textIndexSpec[0]); this.setTextIndex(textIndexValue); } String numTopicsOption = Utils.getOption('N', options); if (numTopicsOption.length() > 0) { String[] numTopicsSpec = Utils.splitOptions(numTopicsOption); if (numTopicsSpec.length == 0) { throw new IllegalArgumentException( "Invalid number of topics specification"); } int numOfTopics = Integer.parseInt(numTopicsSpec[0]); this.setNumberOfTopics(numOfTopics); } String alphaSumOption = Utils.getOption('A', options); if (alphaSumOption.length() > 0) { String[] alphaSumSpec = Utils.splitOptions(alphaSumOption); if (alphaSumSpec.length == 0) { throw new IllegalArgumentException( "Invalid number of AlphaSum"); } double alphaSumValue = Double.parseDouble(alphaSumSpec[0]); this.setAlphaSum(alphaSumValue); } String betaOption = Utils.getOption('B', options); if (betaOption.length() > 0) { String[] betaSpec = Utils.splitOptions(betaOption); if (betaSpec.length == 0) { throw new IllegalArgumentException( "Invalid number of beta"); } double betaValue = Double.parseDouble(betaSpec[0]); this.setBeta(betaValue); } String numThreadsOption = Utils.getOption('P', options); if (numThreadsOption.length() > 0) { String[] numThreadsSpec = Utils.splitOptions(numThreadsOption); if (numThreadsSpec.length == 0) { throw new IllegalArgumentException( "Invalid number of numThreads"); } int numThreadsValue = Integer.parseInt(numThreadsSpec[0]); this.setNumThreads(numThreadsValue); } String numIterationsOption = Utils.getOption('I', options); if (numIterationsOption.length() > 0) { String[] numIterationsSpec = Utils.splitOptions(numIterationsOption); if (numIterationsSpec.length == 0) { throw new IllegalArgumentException( "Invalid number of numIterations"); } int numIterationsValue = Integer.parseInt(numIterationsSpec[0]); this.setNumIterations(numIterationsValue); } String numDispWordsOption = Utils.getOption('W', options); if (numDispWordsOption.length() > 0) { String[] numDispWordsSpec = Utils.splitOptions(numDispWordsOption); if (numDispWordsSpec.length == 0) { throw new IllegalArgumentException( "Invalid number of numDispWords"); } int numDispWordsValue = Integer.parseInt(numDispWordsSpec[0]); this.setNumDispWords(numDispWordsValue); } super.setOptions(options); Utils.checkForRemainingOptions(options); } protected Instances determineOutputFormat(Instances inputFormat) { Instances result = new Instances(inputFormat, 0); ArrayList<String> label = new ArrayList<String>(); for(int i=0;i<this.numberOfTopics;i++){ label.add("topic-"+i); } result.insertAttributeAt(new Attribute("topic-Class", label),result.numAttributes()); for(int i=0;i<this.numberOfTopics;i++){ result.insertAttributeAt(new Attribute("topic-"+i), result.numAttributes()); } return result; } public void buildTopicModel(Instances data) throws Exception { Attribute attrCont = data.attribute(this.getTextIndex()-1); String[] documents=new String[data.numInstances()]; for (int i = 0; i < data.numInstances(); i++) { documents[i] = data.instance(i).stringValue(attrCont); } ArrayList<Pipe> pipeList = new ArrayList<Pipe>(); // Pipes: lowercase, tokenize, remove stopwords, map to features pipeList.add(new CharSequenceLowercase()); pipeList.add(new CharSequence2TokenSequence(Pattern .compile("\\p{L}[\\p{L}\\p{P}]+\\p{L}"))); pipeList.add(new TokenSequenceRemoveStopwords(new File( "resources/stopwords.txt"), "UTF-8", false, false, false)); pipeList.add(new TokenSequence2FeatureSequence()); this.instances = new InstanceList(new SerialPipes(pipeList)); this.instances.addThruPipe(new StringArrayIterator(documents)); // data, // label, // name // fields // Create a model with 100 topics, alpha_t = 0.01, beta_w = 0.01 // Note that the first parameter is passed as the sum over topics, while // the second is the parameter for a single dimension of the Dirichlet prior. this.model = new ParallelTopicModel(this.numberOfTopics, this.alphaSum, this.beta); this.model.addInstances(instances); // Use two parallel samplers, which each look at one half the corpus and combine // statistics after every iteration. this.model.setNumThreads(this.numThreads); // Run the model for 50 iterations and stop (this is for testing only, // for real applications, use 1000 to 2000 iterations) this.model.setNumIterations(this.numIterations); this.model.estimate(); } public double[] topicsForInstance(Instance instance) throws Exception { Attribute attrCont = instance.dataset().attribute(this.getTextIndex()-1); String content=instance.stringValue(attrCont); InstanceList testing = new InstanceList(this.instances.getPipe()); testing.addThruPipe(new cc.mallet.types.Instance(content, null, "test instance", null)); TopicInferencer inferencer = this.model.getInferencer(); double[] testProbabilities = inferencer.getSampledDistribution(testing.get(0), 10, 1, 5); return testProbabilities; } protected Instances process(Instances inst) { Instances result = new Instances(determineOutputFormat(inst), 0); try { //build the topic model with the first batch if(!this.isFirstBatchDone()) this.buildTopicModel(inst); for (int i = 0; i < inst.numInstances(); i++) { double[] values = new double[result.numAttributes()]; for (int n = 0; n < inst.numAttributes(); n++) values[n] = inst.instance(i).value(n); double[] topics=this.topicsForInstance(inst.instance(i)); values[inst.numAttributes()]=Utils.maxIndex(topics); for(int j=0;j<topics.length;j++){ values[values.length - topics.length +j] = topics[j]; } result.add(new DenseInstance(1, values)); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public void setNumberOfTopics(int t){ this.numberOfTopics=t; } public int getNumberOfTopics(){ return this.numberOfTopics; } public double getAlphaSum(){ return this.alphaSum; } public void setAlphaSum(double alphaSum){ this.alphaSum=alphaSum; } public double getBeta(){ return this.beta; } public void setBeta(double beta){ this.beta=beta; } public int getNumThreads(){ return this.numThreads; } public void setNumThreads(int numThreads){ this.numThreads=numThreads; } public int getNumIterations(){ return this.numIterations; } public void setNumIterations(int numIterations){ this.numIterations=numIterations; } public int getNumDispWords(){ return this.numDispWords; } public void setNumDispWords(int numDispWordsValue) { this.numDispWords=numDispWordsValue; } public int getTextIndex() { return textIndex; } public void setTextIndex(int textIndex) { this.textIndex = textIndex; } public static void main(String[] args) { runFilter(new LDAFilter(), args); } }
gpl-2.0
banielTimes/date-poller
src/main/java/de/datepoller/actions/ShowPollAction.java
1839
package de.datepoller.actions; import com.opensymphony.xwork2.ActionSupport; import de.datepoller.domain.Poll; import de.datepoller.domain.User; import de.datepoller.services.PollService; import de.datepoller.services.UserService; import org.apache.struts2.interceptor.ServletRequestAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import javax.servlet.http.HttpServletRequest; /** * Created by dsy on 09.11.14. */ public class ShowPollAction extends ActionSupport implements ServletRequestAware { private HttpServletRequest httpServletRequest; @Autowired private UserService userService; @Autowired private PollService pollService; private String id; private Poll poll; private User user; public String getId() { return id; } public void setId(String id) { this.id = id; } public Poll getPoll() { return poll; } public void setPoll(Poll poll) { this.poll = poll; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String execute() throws Exception { String username = SecurityContextHolder.getContext().getAuthentication().getName(); user = userService.findUserByUsername(username); id = getHttpServletRequest().getParameter("id"); Long pollId = Long.parseLong(id); poll = pollService.findPollById(pollId); return SUCCESS; } @Override public void setServletRequest(HttpServletRequest httpServletRequest) { this.httpServletRequest = httpServletRequest; } public HttpServletRequest getHttpServletRequest() { return httpServletRequest; } }
gpl-2.0
DevCabin/SPARK
inc/class-tgm-plugin-activation.php
123160
<?php /** * Plugin installation and activation for WordPress themes. * * Please note that this is a drop-in library for a theme or plugin. * The authors of this library (Thomas, Gary and Juliette) are NOT responsible * for the support of your plugin or theme. Please contact the plugin * or theme author for support. * * @package TGM-Plugin-Activation * @version 2.6.1 for parent theme GrowthSpark for publication on WordPress.org * @link http://tgmpluginactivation.com/ * @author Thomas Griffin, Gary Jones, Juliette Reinders Folmer * @copyright Copyright (c) 2011, Thomas Griffin * @license GPL-2.0+ */ /* Copyright 2011 Thomas Griffin (thomasgriffinmedia.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ if ( ! class_exists( 'TGM_Plugin_Activation' ) ) { /** * Automatic plugin installation and activation library. * * Creates a way to automatically install and activate plugins from within themes. * The plugins can be either bundled, downloaded from the WordPress * Plugin Repository or downloaded from another external source. * * @since 1.0.0 * * @package TGM-Plugin-Activation * @author Thomas Griffin * @author Gary Jones */ class TGM_Plugin_Activation { /** * TGMPA version number. * * @since 2.5.0 * * @const string Version number. */ const TGMPA_VERSION = '2.6.1'; /** * Regular expression to test if a URL is a WP plugin repo URL. * * @const string Regex. * * @since 2.5.0 */ const WP_REPO_REGEX = '|^http[s]?://wordpress\.org/(?:extend/)?plugins/|'; /** * Arbitrary regular expression to test if a string starts with a URL. * * @const string Regex. * * @since 2.5.0 */ const IS_URL_REGEX = '|^http[s]?://|'; /** * Holds a copy of itself, so it can be referenced by the class name. * * @since 1.0.0 * * @var TGM_Plugin_Activation */ public static $instance; /** * Holds arrays of plugin details. * * @since 1.0.0 * @since 2.5.0 the array has the plugin slug as an associative key. * * @var array */ public $plugins = array(); /** * Holds arrays of plugin names to use to sort the plugins array. * * @since 2.5.0 * * @var array */ protected $sort_order = array(); /** * Whether any plugins have the 'force_activation' setting set to true. * * @since 2.5.0 * * @var bool */ protected $has_forced_activation = false; /** * Whether any plugins have the 'force_deactivation' setting set to true. * * @since 2.5.0 * * @var bool */ protected $has_forced_deactivation = false; /** * Name of the unique ID to hash notices. * * @since 2.4.0 * * @var string */ public $id = 'tgmpa'; /** * Name of the query-string argument for the admin page. * * @since 1.0.0 * * @var string */ protected $menu = 'tgmpa-install-plugins'; /** * Parent menu file slug. * * @since 2.5.0 * * @var string */ public $parent_slug = 'themes.php'; /** * Capability needed to view the plugin installation menu item. * * @since 2.5.0 * * @var string */ public $capability = 'edit_theme_options'; /** * Default absolute path to folder containing bundled plugin zip files. * * @since 2.0.0 * * @var string Absolute path prefix to zip file location for bundled plugins. Default is empty string. */ public $default_path = ''; /** * Flag to show admin notices or not. * * @since 2.1.0 * * @var boolean */ public $has_notices = true; /** * Flag to determine if the user can dismiss the notice nag. * * @since 2.4.0 * * @var boolean */ public $dismissable = true; /** * Message to be output above nag notice if dismissable is false. * * @since 2.4.0 * * @var string */ public $dismiss_msg = ''; /** * Flag to set automatic activation of plugins. Off by default. * * @since 2.2.0 * * @var boolean */ public $is_automatic = false; /** * Optional message to display before the plugins table. * * @since 2.2.0 * * @var string Message filtered by wp_kses_post(). Default is empty string. */ public $message = ''; /** * Holds configurable array of strings. * * Default values are added in the constructor. * * @since 2.0.0 * * @var array */ public $strings = array(); /** * Holds the version of WordPress. * * @since 2.4.0 * * @var int */ public $wp_version; /** * Holds the hook name for the admin page. * * @since 2.5.0 * * @var string */ public $page_hook; /** * Adds a reference of this object to $instance, populates default strings, * does the tgmpa_init action hook, and hooks in the interactions to init. * * {@internal This method should be `protected`, but as too many TGMPA implementations * haven't upgraded beyond v2.3.6 yet, this gives backward compatibility issues. * Reverted back to public for the time being.}} * * @since 1.0.0 * * @see TGM_Plugin_Activation::init() */ public function __construct() { // Set the current WordPress version. $this->wp_version = $GLOBALS['wp_version']; // Announce that the class is ready, and pass the object (for advanced use). do_action_ref_array( 'tgmpa_init', array( $this ) ); // When the rest of WP has loaded, kick-start the rest of the class. add_action( 'init', array( $this, 'init' ) ); } /** * Magic method to (not) set protected properties from outside of this class. * * {@internal hackedihack... There is a serious bug in v2.3.2 - 2.3.6 where the `menu` property * is being assigned rather than tested in a conditional, effectively rendering it useless. * This 'hack' prevents this from happening.}} * * @see https://github.com/TGMPA/TGM-Plugin-Activation/blob/2.3.6/tgm-plugin-activation/class-tgm-plugin-activation.php#L1593 * * @since 2.5.2 * * @param string $name Name of an inaccessible property. * @param mixed $value Value to assign to the property. * @return void Silently fail to set the property when this is tried from outside of this class context. * (Inside this class context, the __set() method if not used as there is direct access.) */ public function __set( $name, $value ) { return; } /** * Magic method to get the value of a protected property outside of this class context. * * @since 2.5.2 * * @param string $name Name of an inaccessible property. * @return mixed The property value. */ public function __get( $name ) { return $this->{$name}; } /** * Initialise the interactions between this class and WordPress. * * Hooks in three new methods for the class: admin_menu, notices and styles. * * @since 2.0.0 * * @see TGM_Plugin_Activation::admin_menu() * @see TGM_Plugin_Activation::notices() * @see TGM_Plugin_Activation::styles() */ public function init() { /** * By default TGMPA only loads on the WP back-end and not in an Ajax call. Using this filter * you can overrule that behaviour. * * @since 2.5.0 * * @param bool $load Whether or not TGMPA should load. * Defaults to the return of `is_admin() && ! defined( 'DOING_AJAX' )`. */ if ( true !== apply_filters( 'tgmpa_load', ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) ) { return; } // Load class strings. $this->strings = array( 'page_title' => __( 'Install Required Plugins', 'growthspark' ), 'menu_title' => __( 'Install Plugins', 'growthspark' ), /* translators: %s: plugin name. */ 'installing' => __( 'Installing Plugin: %s', 'growthspark' ), /* translators: %s: plugin name. */ 'updating' => __( 'Updating Plugin: %s', 'growthspark' ), 'oops' => __( 'Something went wrong with the plugin API.', 'growthspark' ), 'notice_can_install_required' => _n_noop( /* translators: 1: plugin name(s). */ 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.', 'growthspark' ), 'notice_can_install_recommended' => _n_noop( /* translators: 1: plugin name(s). */ 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.', 'growthspark' ), 'notice_ask_to_update' => _n_noop( /* translators: 1: plugin name(s). */ 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.', 'growthspark' ), 'notice_ask_to_update_maybe' => _n_noop( /* translators: 1: plugin name(s). */ 'There is an update available for: %1$s.', 'There are updates available for the following plugins: %1$s.', 'growthspark' ), 'notice_can_activate_required' => _n_noop( /* translators: 1: plugin name(s). */ 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.', 'growthspark' ), 'notice_can_activate_recommended' => _n_noop( /* translators: 1: plugin name(s). */ 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.', 'growthspark' ), 'install_link' => _n_noop( 'Begin installing plugin', 'Begin installing plugins', 'growthspark' ), 'update_link' => _n_noop( 'Begin updating plugin', 'Begin updating plugins', 'growthspark' ), 'activate_link' => _n_noop( 'Begin activating plugin', 'Begin activating plugins', 'growthspark' ), 'return' => __( 'Return to Required Plugins Installer', 'growthspark' ), 'dashboard' => __( 'Return to the Dashboard', 'growthspark' ), 'plugin_activated' => __( 'Plugin activated successfully.', 'growthspark' ), 'activated_successfully' => __( 'The following plugin was activated successfully:', 'growthspark' ), /* translators: 1: plugin name. */ 'plugin_already_active' => __( 'No action taken. Plugin %1$s was already active.', 'growthspark' ), /* translators: 1: plugin name. */ 'plugin_needs_higher_version' => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'growthspark' ), /* translators: 1: dashboard link. */ 'complete' => __( 'All plugins installed and activated successfully. %1$s', 'growthspark' ), 'dismiss' => __( 'Dismiss this notice', 'growthspark' ), 'notice_cannot_install_activate' => __( 'There are one or more required or recommended plugins to install, update or activate.', 'growthspark' ), 'contact_admin' => __( 'Please contact the administrator of this site for help.', 'growthspark' ), ); do_action( 'tgmpa_register' ); /* After this point, the plugins should be registered and the configuration set. */ // Proceed only if we have plugins to handle. if ( empty( $this->plugins ) || ! is_array( $this->plugins ) ) { return; } // Set up the menu and notices if we still have outstanding actions. if ( true !== $this->is_tgmpa_complete() ) { // Sort the plugins. array_multisort( $this->sort_order, SORT_ASC, $this->plugins ); add_action( 'admin_menu', array( $this, 'admin_menu' ) ); add_action( 'admin_head', array( $this, 'dismiss' ) ); // Prevent the normal links from showing underneath a single install/update page. add_filter( 'install_plugin_complete_actions', array( $this, 'actions' ) ); add_filter( 'update_plugin_complete_actions', array( $this, 'actions' ) ); if ( $this->has_notices ) { add_action( 'admin_notices', array( $this, 'notices' ) ); add_action( 'admin_init', array( $this, 'admin_init' ), 1 ); add_action( 'admin_enqueue_scripts', array( $this, 'thickbox' ) ); } } // If needed, filter plugin action links. add_action( 'load-plugins.php', array( $this, 'add_plugin_action_link_filters' ), 1 ); // Make sure things get reset on switch theme. add_action( 'switch_theme', array( $this, 'flush_plugins_cache' ) ); if ( $this->has_notices ) { add_action( 'switch_theme', array( $this, 'update_dismiss' ) ); } // Setup the force activation hook. if ( true === $this->has_forced_activation ) { add_action( 'admin_init', array( $this, 'force_activation' ) ); } // Setup the force deactivation hook. if ( true === $this->has_forced_deactivation ) { add_action( 'switch_theme', array( $this, 'force_deactivation' ) ); } } /** * Hook in plugin action link filters for the WP native plugins page. * * - Prevent activation of plugins which don't meet the minimum version requirements. * - Prevent deactivation of force-activated plugins. * - Add update notice if update available. * * @since 2.5.0 */ public function add_plugin_action_link_filters() { foreach ( $this->plugins as $slug => $plugin ) { if ( false === $this->can_plugin_activate( $slug ) ) { add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_activate' ), 20 ); } if ( true === $plugin['force_activation'] ) { add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_deactivate' ), 20 ); } if ( false !== $this->does_plugin_require_update( $slug ) ) { add_filter( 'plugin_action_links_' . $plugin['file_path'], array( $this, 'filter_plugin_action_links_update' ), 20 ); } } } /** * Remove the 'Activate' link on the WP native plugins page if the plugin does not meet the * minimum version requirements. * * @since 2.5.0 * * @param array $actions Action links. * @return array */ public function filter_plugin_action_links_activate( $actions ) { unset( $actions['activate'] ); return $actions; } /** * Remove the 'Deactivate' link on the WP native plugins page if the plugin has been set to force activate. * * @since 2.5.0 * * @param array $actions Action links. * @return array */ public function filter_plugin_action_links_deactivate( $actions ) { unset( $actions['deactivate'] ); return $actions; } /** * Add a 'Requires update' link on the WP native plugins page if the plugin does not meet the * minimum version requirements. * * @since 2.5.0 * * @param array $actions Action links. * @return array */ public function filter_plugin_action_links_update( $actions ) { $actions['update'] = sprintf( '<a href="%1$s" title="%2$s" class="edit">%3$s</a>', esc_url( $this->get_tgmpa_status_url( 'update' ) ), esc_attr__( 'This plugin needs to be updated to be compatible with your theme.', 'growthspark' ), esc_html__( 'Update Required', 'growthspark' ) ); return $actions; } /** * Handles calls to show plugin information via links in the notices. * * We get the links in the admin notices to point to the TGMPA page, rather * than the typical plugin-install.php file, so we can prepare everything * beforehand. * * WP does not make it easy to show the plugin information in the thickbox - * here we have to require a file that includes a function that does the * main work of displaying it, enqueue some styles, set up some globals and * finally call that function before exiting. * * Down right easy once you know how... * * Returns early if not the TGMPA page. * * @since 2.1.0 * * @global string $tab Used as iframe div class names, helps with styling * @global string $body_id Used as the iframe body ID, helps with styling * * @return null Returns early if not the TGMPA page. */ public function admin_init() { if ( ! $this->is_tgmpa_page() ) { return; } if ( isset( $_REQUEST['tab'] ) && 'plugin-information' === $_REQUEST['tab'] ) { // Needed for install_plugin_information(). require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; wp_enqueue_style( 'plugin-install' ); global $tab, $body_id; $body_id = 'plugin-information'; // @codingStandardsIgnoreStart $tab = 'plugin-information'; // @codingStandardsIgnoreEnd install_plugin_information(); exit; } } /** * Enqueue thickbox scripts/styles for plugin info. * * Thickbox is not automatically included on all admin pages, so we must * manually enqueue it for those pages. * * Thickbox is only loaded if the user has not dismissed the admin * notice or if there are any plugins left to install and activate. * * @since 2.1.0 */ public function thickbox() { if ( ! get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) ) { add_thickbox(); } } /** * Adds submenu page if there are plugin actions to take. * * This method adds the submenu page letting users know that a required * plugin needs to be installed. * * This page disappears once the plugin has been installed and activated. * * @since 1.0.0 * * @see TGM_Plugin_Activation::init() * @see TGM_Plugin_Activation::install_plugins_page() * * @return null Return early if user lacks capability to install a plugin. */ public function admin_menu() { // Make sure privileges are correct to see the page. if ( ! current_user_can( 'install_plugins' ) ) { return; } $args = apply_filters( 'tgmpa_admin_menu_args', array( 'parent_slug' => $this->parent_slug, // Parent Menu slug. 'page_title' => $this->strings['page_title'], // Page title. 'menu_title' => $this->strings['menu_title'], // Menu title. 'capability' => $this->capability, // Capability. 'menu_slug' => $this->menu, // Menu slug. 'function' => array( $this, 'install_plugins_page' ), // Callback. ) ); $this->add_admin_menu( $args ); } /** * Add the menu item. * * {@internal IMPORTANT! If this function changes, review the regex in the custom TGMPA * generator on the website.}} * * @since 2.5.0 * * @param array $args Menu item configuration. */ protected function add_admin_menu( array $args ) { $this->page_hook = add_theme_page( $args['page_title'], $args['menu_title'], $args['capability'], $args['menu_slug'], $args['function'] ); } /** * Echoes plugin installation form. * * This method is the callback for the admin_menu method function. * This displays the admin page and form area where the user can select to install and activate the plugin. * Aborts early if we're processing a plugin installation action. * * @since 1.0.0 * * @return null Aborts early if we're processing a plugin installation action. */ public function install_plugins_page() { // Store new instance of plugin table in object. $plugin_table = new TGMPA_List_Table; // Return early if processing a plugin installation action. if ( ( ( 'tgmpa-bulk-install' === $plugin_table->current_action() || 'tgmpa-bulk-update' === $plugin_table->current_action() ) && $plugin_table->process_bulk_actions() ) || $this->do_plugin_install() ) { return; } // Force refresh of available plugin information so we'll know about manual updates/deletes. wp_clean_plugins_cache( false ); ?> <div class="tgmpa wrap"> <h1><?php echo esc_html( get_admin_page_title() ); ?></h1> <?php $plugin_table->prepare_items(); ?> <?php if ( ! empty( $this->message ) && is_string( $this->message ) ) { echo wp_kses_post( $this->message ); } ?> <?php $plugin_table->views(); ?> <form id="tgmpa-plugins" action="" method="post"> <input type="hidden" name="tgmpa-page" value="<?php echo esc_attr( $this->menu ); ?>" /> <input type="hidden" name="plugin_status" value="<?php echo esc_attr( $plugin_table->view_context ); ?>" /> <?php $plugin_table->display(); ?> </form> </div> <?php } /** * Installs, updates or activates a plugin depending on the action link clicked by the user. * * Checks the $_GET variable to see which actions have been * passed and responds with the appropriate method. * * Uses WP_Filesystem to process and handle the plugin installation * method. * * @since 1.0.0 * * @uses WP_Filesystem * @uses WP_Error * @uses WP_Upgrader * @uses Plugin_Upgrader * @uses Plugin_Installer_Skin * @uses Plugin_Upgrader_Skin * * @return boolean True on success, false on failure. */ protected function do_plugin_install() { if ( empty( $_GET['plugin'] ) ) { return false; } // All plugin information will be stored in an array for processing. $slug = $this->sanitize_key( urldecode( $_GET['plugin'] ) ); if ( ! isset( $this->plugins[ $slug ] ) ) { return false; } // Was an install or upgrade action link clicked? if ( ( isset( $_GET['tgmpa-install'] ) && 'install-plugin' === $_GET['tgmpa-install'] ) || ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) ) { $install_type = 'install'; if ( isset( $_GET['tgmpa-update'] ) && 'update-plugin' === $_GET['tgmpa-update'] ) { $install_type = 'update'; } check_admin_referer( 'tgmpa-' . $install_type, 'tgmpa-nonce' ); // Pass necessary information via URL if WP_Filesystem is needed. $url = wp_nonce_url( add_query_arg( array( 'plugin' => urlencode( $slug ), 'tgmpa-' . $install_type => $install_type . '-plugin', ), $this->get_tgmpa_url() ), 'tgmpa-' . $install_type, 'tgmpa-nonce' ); $method = ''; // Leave blank so WP_Filesystem can populate it as necessary. if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, array() ) ) ) { return true; } if ( ! WP_Filesystem( $creds ) ) { request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, array() ); // Setup WP_Filesystem. return true; } /* If we arrive here, we have the filesystem. */ // Prep variables for Plugin_Installer_Skin class. $extra = array(); $extra['slug'] = $slug; // Needed for potentially renaming of directory name. $source = $this->get_download_url( $slug ); $api = ( 'repo' === $this->plugins[ $slug ]['source_type'] ) ? $this->get_plugins_api( $slug ) : null; $api = ( false !== $api ) ? $api : null; $url = add_query_arg( array( 'action' => $install_type . '-plugin', 'plugin' => urlencode( $slug ), ), 'update.php' ); if ( ! class_exists( 'Plugin_Upgrader', false ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; } $title = ( 'update' === $install_type ) ? $this->strings['updating'] : $this->strings['installing']; $skin_args = array( 'type' => ( 'bundled' !== $this->plugins[ $slug ]['source_type'] ) ? 'web' : 'upload', 'title' => sprintf( $title, $this->plugins[ $slug ]['name'] ), 'url' => esc_url_raw( $url ), 'nonce' => $install_type . '-plugin_' . $slug, 'plugin' => '', 'api' => $api, 'extra' => $extra, ); unset( $title ); if ( 'update' === $install_type ) { $skin_args['plugin'] = $this->plugins[ $slug ]['file_path']; $skin = new Plugin_Upgrader_Skin( $skin_args ); } else { $skin = new Plugin_Installer_Skin( $skin_args ); } // Create a new instance of Plugin_Upgrader. $upgrader = new Plugin_Upgrader( $skin ); // Perform the action and install the plugin from the $source urldecode(). add_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1, 3 ); if ( 'update' === $install_type ) { // Inject our info into the update transient. $to_inject = array( $slug => $this->plugins[ $slug ] ); $to_inject[ $slug ]['source'] = $source; $this->inject_update_info( $to_inject ); $upgrader->upgrade( $this->plugins[ $slug ]['file_path'] ); } else { $upgrader->install( $source ); } remove_filter( 'upgrader_source_selection', array( $this, 'maybe_adjust_source_dir' ), 1 ); // Make sure we have the correct file path now the plugin is installed/updated. $this->populate_file_path( $slug ); // Only activate plugins if the config option is set to true and the plugin isn't // already active (upgrade). if ( $this->is_automatic && ! $this->is_plugin_active( $slug ) ) { $plugin_activate = $upgrader->plugin_info(); // Grab the plugin info from the Plugin_Upgrader method. if ( false === $this->activate_single_plugin( $plugin_activate, $slug, true ) ) { return true; // Finish execution of the function early as we encountered an error. } } $this->show_tgmpa_version(); // Display message based on if all plugins are now active or not. if ( $this->is_tgmpa_complete() ) { echo '<p>', sprintf( esc_html( $this->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'growthspark' ) . '</a>' ), '</p>'; echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>'; } else { echo '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>'; } return true; } elseif ( isset( $this->plugins[ $slug ]['file_path'], $_GET['tgmpa-activate'] ) && 'activate-plugin' === $_GET['tgmpa-activate'] ) { // Activate action link was clicked. check_admin_referer( 'tgmpa-activate', 'tgmpa-nonce' ); if ( false === $this->activate_single_plugin( $this->plugins[ $slug ]['file_path'], $slug ) ) { return true; // Finish execution of the function early as we encountered an error. } } return false; } /** * Inject information into the 'update_plugins' site transient as WP checks that before running an update. * * @since 2.5.0 * * @param array $plugins The plugin information for the plugins which are to be updated. */ public function inject_update_info( $plugins ) { $repo_updates = get_site_transient( 'update_plugins' ); if ( ! is_object( $repo_updates ) ) { $repo_updates = new stdClass; } foreach ( $plugins as $slug => $plugin ) { $file_path = $plugin['file_path']; if ( empty( $repo_updates->response[ $file_path ] ) ) { $repo_updates->response[ $file_path ] = new stdClass; } // We only really need to set package, but let's do all we can in case WP changes something. $repo_updates->response[ $file_path ]->slug = $slug; $repo_updates->response[ $file_path ]->plugin = $file_path; $repo_updates->response[ $file_path ]->new_version = $plugin['version']; $repo_updates->response[ $file_path ]->package = $plugin['source']; if ( empty( $repo_updates->response[ $file_path ]->url ) && ! empty( $plugin['external_url'] ) ) { $repo_updates->response[ $file_path ]->url = $plugin['external_url']; } } set_site_transient( 'update_plugins', $repo_updates ); } /** * Adjust the plugin directory name if necessary. * * The final destination directory of a plugin is based on the subdirectory name found in the * (un)zipped source. In some cases - most notably GitHub repository plugin downloads -, this * subdirectory name is not the same as the expected slug and the plugin will not be recognized * as installed. This is fixed by adjusting the temporary unzipped source subdirectory name to * the expected plugin slug. * * @since 2.5.0 * * @param string $source Path to upgrade/zip-file-name.tmp/subdirectory/. * @param string $remote_source Path to upgrade/zip-file-name.tmp. * @param \WP_Upgrader $upgrader Instance of the upgrader which installs the plugin. * @return string $source */ public function maybe_adjust_source_dir( $source, $remote_source, $upgrader ) { if ( ! $this->is_tgmpa_page() || ! is_object( $GLOBALS['wp_filesystem'] ) ) { return $source; } // Check for single file plugins. $source_files = array_keys( $GLOBALS['wp_filesystem']->dirlist( $remote_source ) ); if ( 1 === count( $source_files ) && false === $GLOBALS['wp_filesystem']->is_dir( $source ) ) { return $source; } // Multi-file plugin, let's see if the directory is correctly named. $desired_slug = ''; // Figure out what the slug is supposed to be. if ( false === $upgrader->bulk && ! empty( $upgrader->skin->options['extra']['slug'] ) ) { $desired_slug = $upgrader->skin->options['extra']['slug']; } else { // Bulk installer contains less info, so fall back on the info registered here. foreach ( $this->plugins as $slug => $plugin ) { if ( ! empty( $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) && $plugin['name'] === $upgrader->skin->plugin_names[ $upgrader->skin->i ] ) { $desired_slug = $slug; break; } } unset( $slug, $plugin ); } if ( ! empty( $desired_slug ) ) { $subdir_name = untrailingslashit( str_replace( trailingslashit( $remote_source ), '', $source ) ); if ( ! empty( $subdir_name ) && $subdir_name !== $desired_slug ) { $from_path = untrailingslashit( $source ); $to_path = trailingslashit( $remote_source ) . $desired_slug; if ( true === $GLOBALS['wp_filesystem']->move( $from_path, $to_path ) ) { return trailingslashit( $to_path ); } else { return new WP_Error( 'rename_failed', esc_html__( 'The remote plugin package does not contain a folder with the desired slug and renaming did not work.', 'growthspark' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'growthspark' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) ); } } elseif ( empty( $subdir_name ) ) { return new WP_Error( 'packaged_wrong', esc_html__( 'The remote plugin package consists of more than one file, but the files are not packaged in a folder.', 'growthspark' ) . ' ' . esc_html__( 'Please contact the plugin provider and ask them to package their plugin according to the WordPress guidelines.', 'growthspark' ), array( 'found' => $subdir_name, 'expected' => $desired_slug ) ); } } return $source; } /** * Activate a single plugin and send feedback about the result to the screen. * * @since 2.5.0 * * @param string $file_path Path within wp-plugins/ to main plugin file. * @param string $slug Plugin slug. * @param bool $automatic Whether this is an automatic activation after an install. Defaults to false. * This determines the styling of the output messages. * @return bool False if an error was encountered, true otherwise. */ protected function activate_single_plugin( $file_path, $slug, $automatic = false ) { if ( $this->can_plugin_activate( $slug ) ) { $activate = activate_plugin( $file_path ); if ( is_wp_error( $activate ) ) { echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>', '<p><a href="', esc_url( $this->get_tgmpa_url() ), '" target="_parent">', esc_html( $this->strings['return'] ), '</a></p>'; return false; // End it here if there is an error with activation. } else { if ( ! $automatic ) { // Make sure message doesn't display again if bulk activation is performed // immediately after a single activation. if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK. echo '<div id="message" class="updated"><p>', esc_html( $this->strings['activated_successfully'] ), ' <strong>', esc_html( $this->plugins[ $slug ]['name'] ), '.</strong></p></div>'; } } else { // Simpler message layout for use on the plugin install page. echo '<p>', esc_html( $this->strings['plugin_activated'] ), '</p>'; } } } elseif ( $this->is_plugin_active( $slug ) ) { // No simpler message format provided as this message should never be encountered // on the plugin install page. echo '<div id="message" class="error"><p>', sprintf( esc_html( $this->strings['plugin_already_active'] ), '<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>' ), '</p></div>'; } elseif ( $this->does_plugin_require_update( $slug ) ) { if ( ! $automatic ) { // Make sure message doesn't display again if bulk activation is performed // immediately after a single activation. if ( ! isset( $_POST['action'] ) ) { // WPCS: CSRF OK. echo '<div id="message" class="error"><p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), '<strong>' . esc_html( $this->plugins[ $slug ]['name'] ) . '</strong>' ), '</p></div>'; } } else { // Simpler message layout for use on the plugin install page. echo '<p>', sprintf( esc_html( $this->strings['plugin_needs_higher_version'] ), esc_html( $this->plugins[ $slug ]['name'] ) ), '</p>'; } } return true; } /** * Echoes required plugin notice. * * Outputs a message telling users that a specific plugin is required for * their theme. If appropriate, it includes a link to the form page where * users can install and activate the plugin. * * Returns early if we're on the Install page. * * @since 1.0.0 * * @global object $current_screen * * @return null Returns early if we're on the Install page. */ public function notices() { // Remove nag on the install page / Return early if the nag message has been dismissed or user < author. if ( ( $this->is_tgmpa_page() || $this->is_core_update_page() ) || get_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, true ) || ! current_user_can( apply_filters( 'tgmpa_show_admin_notice_capability', 'publish_posts' ) ) ) { return; } // Store for the plugin slugs by message type. $message = array(); // Initialize counters used to determine plurality of action link texts. $install_link_count = 0; $update_link_count = 0; $activate_link_count = 0; $total_required_action_count = 0; foreach ( $this->plugins as $slug => $plugin ) { if ( $this->is_plugin_active( $slug ) && false === $this->does_plugin_have_update( $slug ) ) { continue; } if ( ! $this->is_plugin_installed( $slug ) ) { if ( current_user_can( 'install_plugins' ) ) { $install_link_count++; if ( true === $plugin['required'] ) { $message['notice_can_install_required'][] = $slug; } else { $message['notice_can_install_recommended'][] = $slug; } } if ( true === $plugin['required'] ) { $total_required_action_count++; } } else { if ( ! $this->is_plugin_active( $slug ) && $this->can_plugin_activate( $slug ) ) { if ( current_user_can( 'activate_plugins' ) ) { $activate_link_count++; if ( true === $plugin['required'] ) { $message['notice_can_activate_required'][] = $slug; } else { $message['notice_can_activate_recommended'][] = $slug; } } if ( true === $plugin['required'] ) { $total_required_action_count++; } } if ( $this->does_plugin_require_update( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) { if ( current_user_can( 'update_plugins' ) ) { $update_link_count++; if ( $this->does_plugin_require_update( $slug ) ) { $message['notice_ask_to_update'][] = $slug; } elseif ( false !== $this->does_plugin_have_update( $slug ) ) { $message['notice_ask_to_update_maybe'][] = $slug; } } if ( true === $plugin['required'] ) { $total_required_action_count++; } } } } unset( $slug, $plugin ); // If we have notices to display, we move forward. if ( ! empty( $message ) || $total_required_action_count > 0 ) { krsort( $message ); // Sort messages. $rendered = ''; // As add_settings_error() wraps the final message in a <p> and as the final message can't be // filtered, using <p>'s in our html would render invalid html output. $line_template = '<span style="display: block; margin: 0.5em 0.5em 0 0; clear: both;">%s</span>' . "\n"; if ( ! current_user_can( 'activate_plugins' ) && ! current_user_can( 'install_plugins' ) && ! current_user_can( 'update_plugins' ) ) { $rendered = esc_html( $this->strings['notice_cannot_install_activate'] ) . ' ' . esc_html( $this->strings['contact_admin'] ); $rendered .= $this->create_user_action_links_for_notice( 0, 0, 0, $line_template ); } else { // If dismissable is false and a message is set, output it now. if ( ! $this->dismissable && ! empty( $this->dismiss_msg ) ) { $rendered .= sprintf( $line_template, wp_kses_post( $this->dismiss_msg ) ); } // Render the individual message lines for the notice. foreach ( $message as $type => $plugin_group ) { $linked_plugins = array(); // Get the external info link for a plugin if one is available. foreach ( $plugin_group as $plugin_slug ) { $linked_plugins[] = $this->get_info_link( $plugin_slug ); } unset( $plugin_slug ); $count = count( $plugin_group ); $linked_plugins = array_map( array( 'TGMPA_Utils', 'wrap_in_em' ), $linked_plugins ); $last_plugin = array_pop( $linked_plugins ); // Pop off last name to prep for readability. $imploded = empty( $linked_plugins ) ? $last_plugin : ( implode( ', ', $linked_plugins ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'growthspark' ) . ' ' . $last_plugin ); $rendered .= sprintf( $line_template, sprintf( translate_nooped_plural( $this->strings[ $type ], $count, 'growthspark' ), $imploded, $count ) ); } unset( $type, $plugin_group, $linked_plugins, $count, $last_plugin, $imploded ); $rendered .= $this->create_user_action_links_for_notice( $install_link_count, $update_link_count, $activate_link_count, $line_template ); } // Register the nag messages and prepare them to be processed. add_settings_error( 'tgmpa', 'tgmpa', $rendered, $this->get_admin_notice_class() ); } // Admin options pages already output settings_errors, so this is to avoid duplication. if ( 'options-general' !== $GLOBALS['current_screen']->parent_base ) { $this->display_settings_errors(); } } /** * Generate the user action links for the admin notice. * * @since 2.6.0 * * @param int $install_count Number of plugins to install. * @param int $update_count Number of plugins to update. * @param int $activate_count Number of plugins to activate. * @param int $line_template Template for the HTML tag to output a line. * @return string Action links. */ protected function create_user_action_links_for_notice( $install_count, $update_count, $activate_count, $line_template ) { // Setup action links. $action_links = array( 'install' => '', 'update' => '', 'activate' => '', 'dismiss' => $this->dismissable ? '<a href="' . esc_url( wp_nonce_url( add_query_arg( 'tgmpa-dismiss', 'dismiss_admin_notices' ), 'tgmpa-dismiss-' . get_current_user_id() ) ) . '" class="dismiss-notice" target="_parent">' . esc_html( $this->strings['dismiss'] ) . '</a>' : '', ); $link_template = '<a href="%2$s">%1$s</a>'; if ( current_user_can( 'install_plugins' ) ) { if ( $install_count > 0 ) { $action_links['install'] = sprintf( $link_template, translate_nooped_plural( $this->strings['install_link'], $install_count, 'growthspark' ), esc_url( $this->get_tgmpa_status_url( 'install' ) ) ); } if ( $update_count > 0 ) { $action_links['update'] = sprintf( $link_template, translate_nooped_plural( $this->strings['update_link'], $update_count, 'growthspark' ), esc_url( $this->get_tgmpa_status_url( 'update' ) ) ); } } if ( current_user_can( 'activate_plugins' ) && $activate_count > 0 ) { $action_links['activate'] = sprintf( $link_template, translate_nooped_plural( $this->strings['activate_link'], $activate_count, 'growthspark' ), esc_url( $this->get_tgmpa_status_url( 'activate' ) ) ); } $action_links = apply_filters( 'tgmpa_notice_action_links', $action_links ); $action_links = array_filter( (array) $action_links ); // Remove any empty array items. if ( ! empty( $action_links ) ) { $action_links = sprintf( $line_template, implode( ' | ', $action_links ) ); return apply_filters( 'tgmpa_notice_rendered_action_links', $action_links ); } else { return ''; } } /** * Get admin notice class. * * Work around all the changes to the various admin notice classes between WP 4.4 and 3.7 * (lowest supported version by TGMPA). * * @since 2.6.0 * * @return string */ protected function get_admin_notice_class() { if ( ! empty( $this->strings['nag_type'] ) ) { return sanitize_html_class( strtolower( $this->strings['nag_type'] ) ); } else { if ( version_compare( $this->wp_version, '4.2', '>=' ) ) { return 'notice-warning'; } elseif ( version_compare( $this->wp_version, '4.1', '>=' ) ) { return 'notice'; } else { return 'updated'; } } } /** * Display settings errors and remove those which have been displayed to avoid duplicate messages showing * * @since 2.5.0 */ protected function display_settings_errors() { global $wp_settings_errors; settings_errors( 'tgmpa' ); foreach ( (array) $wp_settings_errors as $key => $details ) { if ( 'tgmpa' === $details['setting'] ) { unset( $wp_settings_errors[ $key ] ); break; } } } /** * Register dismissal of admin notices. * * Acts on the dismiss link in the admin nag messages. * If clicked, the admin notice disappears and will no longer be visible to this user. * * @since 2.1.0 */ public function dismiss() { if ( isset( $_GET['tgmpa-dismiss'] ) && check_admin_referer( 'tgmpa-dismiss-' . get_current_user_id() ) ) { update_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice_' . $this->id, 1 ); } } /** * Add individual plugin to our collection of plugins. * * If the required keys are not set or the plugin has already * been registered, the plugin is not added. * * @since 2.0.0 * * @param array|null $plugin Array of plugin arguments or null if invalid argument. * @return null Return early if incorrect argument. */ public function register( $plugin ) { if ( empty( $plugin['slug'] ) || empty( $plugin['name'] ) ) { return; } if ( empty( $plugin['slug'] ) || ! is_string( $plugin['slug'] ) || isset( $this->plugins[ $plugin['slug'] ] ) ) { return; } $defaults = array( 'name' => '', // String 'slug' => '', // String 'source' => 'repo', // String 'required' => false, // Boolean 'version' => '', // String 'force_activation' => false, // Boolean 'force_deactivation' => false, // Boolean 'external_url' => '', // String 'is_callable' => '', // String|Array. ); // Prepare the received data. $plugin = wp_parse_args( $plugin, $defaults ); // Standardize the received slug. $plugin['slug'] = $this->sanitize_key( $plugin['slug'] ); // Forgive users for using string versions of booleans or floats for version number. $plugin['version'] = (string) $plugin['version']; $plugin['source'] = empty( $plugin['source'] ) ? 'repo' : $plugin['source']; $plugin['required'] = TGMPA_Utils::validate_bool( $plugin['required'] ); $plugin['force_activation'] = TGMPA_Utils::validate_bool( $plugin['force_activation'] ); $plugin['force_deactivation'] = TGMPA_Utils::validate_bool( $plugin['force_deactivation'] ); // Enrich the received data. $plugin['file_path'] = $this->_get_plugin_basename_from_slug( $plugin['slug'] ); $plugin['source_type'] = $this->get_plugin_source_type( $plugin['source'] ); // Set the class properties. $this->plugins[ $plugin['slug'] ] = $plugin; $this->sort_order[ $plugin['slug'] ] = $plugin['name']; // Should we add the force activation hook ? if ( true === $plugin['force_activation'] ) { $this->has_forced_activation = true; } // Should we add the force deactivation hook ? if ( true === $plugin['force_deactivation'] ) { $this->has_forced_deactivation = true; } } /** * Determine what type of source the plugin comes from. * * @since 2.5.0 * * @param string $source The source of the plugin as provided, either empty (= WP repo), a file path * (= bundled) or an external URL. * @return string 'repo', 'external', or 'bundled' */ protected function get_plugin_source_type( $source ) { if ( 'repo' === $source || preg_match( self::WP_REPO_REGEX, $source ) ) { return 'repo'; } elseif ( preg_match( self::IS_URL_REGEX, $source ) ) { return 'external'; } else { return 'bundled'; } } /** * Sanitizes a string key. * * Near duplicate of WP Core `sanitize_key()`. The difference is that uppercase characters *are* * allowed, so as not to break upgrade paths from non-standard bundled plugins using uppercase * characters in the plugin directory path/slug. Silly them. * * @see https://developer.wordpress.org/reference/hooks/sanitize_key/ * * @since 2.5.0 * * @param string $key String key. * @return string Sanitized key */ public function sanitize_key( $key ) { $raw_key = $key; $key = preg_replace( '`[^A-Za-z0-9_-]`', '', $key ); /** * Filter a sanitized key string. * * @since 2.5.0 * * @param string $key Sanitized key. * @param string $raw_key The key prior to sanitization. */ return apply_filters( 'tgmpa_sanitize_key', $key, $raw_key ); } /** * Amend default configuration settings. * * @since 2.0.0 * * @param array $config Array of config options to pass as class properties. */ public function config( $config ) { $keys = array( 'id', 'default_path', 'has_notices', 'dismissable', 'dismiss_msg', 'menu', 'parent_slug', 'capability', 'is_automatic', 'message', 'strings', ); foreach ( $keys as $key ) { if ( isset( $config[ $key ] ) ) { if ( is_array( $config[ $key ] ) ) { $this->$key = array_merge( $this->$key, $config[ $key ] ); } else { $this->$key = $config[ $key ]; } } } } /** * Amend action link after plugin installation. * * @since 2.0.0 * * @param array $install_actions Existing array of actions. * @return false|array Amended array of actions. */ public function actions( $install_actions ) { // Remove action links on the TGMPA install page. if ( $this->is_tgmpa_page() ) { return false; } return $install_actions; } /** * Flushes the plugins cache on theme switch to prevent stale entries * from remaining in the plugin table. * * @since 2.4.0 * * @param bool $clear_update_cache Optional. Whether to clear the Plugin updates cache. * Parameter added in v2.5.0. */ public function flush_plugins_cache( $clear_update_cache = true ) { wp_clean_plugins_cache( $clear_update_cache ); } /** * Set file_path key for each installed plugin. * * @since 2.1.0 * * @param string $plugin_slug Optional. If set, only (re-)populates the file path for that specific plugin. * Parameter added in v2.5.0. */ public function populate_file_path( $plugin_slug = '' ) { if ( ! empty( $plugin_slug ) && is_string( $plugin_slug ) && isset( $this->plugins[ $plugin_slug ] ) ) { $this->plugins[ $plugin_slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $plugin_slug ); } else { // Add file_path key for all plugins. foreach ( $this->plugins as $slug => $values ) { $this->plugins[ $slug ]['file_path'] = $this->_get_plugin_basename_from_slug( $slug ); } } } /** * Helper function to extract the file path of the plugin file from the * plugin slug, if the plugin is installed. * * @since 2.0.0 * * @param string $slug Plugin slug (typically folder name) as provided by the developer. * @return string Either file path for plugin if installed, or just the plugin slug. */ protected function _get_plugin_basename_from_slug( $slug ) { $keys = array_keys( $this->get_plugins() ); foreach ( $keys as $key ) { if ( preg_match( '|^' . $slug . '/|', $key ) ) { return $key; } } return $slug; } /** * Retrieve plugin data, given the plugin name. * * Loops through the registered plugins looking for $name. If it finds it, * it returns the $data from that plugin. Otherwise, returns false. * * @since 2.1.0 * * @param string $name Name of the plugin, as it was registered. * @param string $data Optional. Array key of plugin data to return. Default is slug. * @return string|boolean Plugin slug if found, false otherwise. */ public function _get_plugin_data_from_name( $name, $data = 'slug' ) { foreach ( $this->plugins as $values ) { if ( $name === $values['name'] && isset( $values[ $data ] ) ) { return $values[ $data ]; } } return false; } /** * Retrieve the download URL for a package. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string Plugin download URL or path to local file or empty string if undetermined. */ public function get_download_url( $slug ) { $dl_source = ''; switch ( $this->plugins[ $slug ]['source_type'] ) { case 'repo': return $this->get_wp_repo_download_url( $slug ); case 'external': return $this->plugins[ $slug ]['source']; case 'bundled': return $this->default_path . $this->plugins[ $slug ]['source']; } return $dl_source; // Should never happen. } /** * Retrieve the download URL for a WP repo package. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string Plugin download URL. */ protected function get_wp_repo_download_url( $slug ) { $source = ''; $api = $this->get_plugins_api( $slug ); if ( false !== $api && isset( $api->download_link ) ) { $source = $api->download_link; } return $source; } /** * Try to grab information from WordPress API. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return object Plugins_api response object on success, WP_Error on failure. */ protected function get_plugins_api( $slug ) { static $api = array(); // Cache received responses. if ( ! isset( $api[ $slug ] ) ) { if ( ! function_exists( 'plugins_api' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; } $response = plugins_api( 'plugin_information', array( 'slug' => $slug, 'fields' => array( 'sections' => false ) ) ); $api[ $slug ] = false; if ( is_wp_error( $response ) ) { wp_die( esc_html( $this->strings['oops'] ) ); } else { $api[ $slug ] = $response; } } return $api[ $slug ]; } /** * Retrieve a link to a plugin information page. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string Fully formed html link to a plugin information page if available * or the plugin name if not. */ public function get_info_link( $slug ) { if ( ! empty( $this->plugins[ $slug ]['external_url'] ) && preg_match( self::IS_URL_REGEX, $this->plugins[ $slug ]['external_url'] ) ) { $link = sprintf( '<a href="%1$s" target="_blank">%2$s</a>', esc_url( $this->plugins[ $slug ]['external_url'] ), esc_html( $this->plugins[ $slug ]['name'] ) ); } elseif ( 'repo' === $this->plugins[ $slug ]['source_type'] ) { $url = add_query_arg( array( 'tab' => 'plugin-information', 'plugin' => urlencode( $slug ), 'TB_iframe' => 'true', 'width' => '640', 'height' => '500', ), self_admin_url( 'plugin-install.php' ) ); $link = sprintf( '<a href="%1$s" class="thickbox">%2$s</a>', esc_url( $url ), esc_html( $this->plugins[ $slug ]['name'] ) ); } else { $link = esc_html( $this->plugins[ $slug ]['name'] ); // No hyperlink. } return $link; } /** * Determine if we're on the TGMPA Install page. * * @since 2.1.0 * * @return boolean True when on the TGMPA page, false otherwise. */ protected function is_tgmpa_page() { return isset( $_GET['page'] ) && $this->menu === $_GET['page']; } /** * Determine if we're on a WP Core installation/upgrade page. * * @since 2.6.0 * * @return boolean True when on a WP Core installation/upgrade page, false otherwise. */ protected function is_core_update_page() { // Current screen is not always available, most notably on the customizer screen. if ( ! function_exists( 'get_current_screen' ) ) { return false; } $screen = get_current_screen(); if ( 'update-core' === $screen->base ) { // Core update screen. return true; } elseif ( 'plugins' === $screen->base && ! empty( $_POST['action'] ) ) { // WPCS: CSRF ok. // Plugins bulk update screen. return true; } elseif ( 'update' === $screen->base && ! empty( $_POST['action'] ) ) { // WPCS: CSRF ok. // Individual updates (ajax call). return true; } return false; } /** * Retrieve the URL to the TGMPA Install page. * * I.e. depending on the config settings passed something along the lines of: * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins * * @since 2.5.0 * * @return string Properly encoded URL (not escaped). */ public function get_tgmpa_url() { static $url; if ( ! isset( $url ) ) { $parent = $this->parent_slug; if ( false === strpos( $parent, '.php' ) ) { $parent = 'admin.php'; } $url = add_query_arg( array( 'page' => urlencode( $this->menu ), ), self_admin_url( $parent ) ); } return $url; } /** * Retrieve the URL to the TGMPA Install page for a specific plugin status (view). * * I.e. depending on the config settings passed something along the lines of: * http://example.com/wp-admin/themes.php?page=tgmpa-install-plugins&plugin_status=install * * @since 2.5.0 * * @param string $status Plugin status - either 'install', 'update' or 'activate'. * @return string Properly encoded URL (not escaped). */ public function get_tgmpa_status_url( $status ) { return add_query_arg( array( 'plugin_status' => urlencode( $status ), ), $this->get_tgmpa_url() ); } /** * Determine whether there are open actions for plugins registered with TGMPA. * * @since 2.5.0 * * @return bool True if complete, i.e. no outstanding actions. False otherwise. */ public function is_tgmpa_complete() { $complete = true; foreach ( $this->plugins as $slug => $plugin ) { if ( ! $this->is_plugin_active( $slug ) || false !== $this->does_plugin_have_update( $slug ) ) { $complete = false; break; } } return $complete; } /** * Check if a plugin is installed. Does not take must-use plugins into account. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True if installed, false otherwise. */ public function is_plugin_installed( $slug ) { $installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached). return ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ] ) ); } /** * Check if a plugin is active. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True if active, false otherwise. */ public function is_plugin_active( $slug ) { return ( ( ! empty( $this->plugins[ $slug ]['is_callable'] ) && is_callable( $this->plugins[ $slug ]['is_callable'] ) ) || is_plugin_active( $this->plugins[ $slug ]['file_path'] ) ); } /** * Check if a plugin can be updated, i.e. if we have information on the minimum WP version required * available, check whether the current install meets them. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True if OK to update, false otherwise. */ public function can_plugin_update( $slug ) { // We currently can't get reliable info on non-WP-repo plugins - issue #380. if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) { return true; } $api = $this->get_plugins_api( $slug ); if ( false !== $api && isset( $api->requires ) ) { return version_compare( $this->wp_version, $api->requires, '>=' ); } // No usable info received from the plugins API, presume we can update. return true; } /** * Check to see if the plugin is 'updatetable', i.e. installed, with an update available * and no WP version requirements blocking it. * * @since 2.6.0 * * @param string $slug Plugin slug. * @return bool True if OK to proceed with update, false otherwise. */ public function is_plugin_updatetable( $slug ) { if ( ! $this->is_plugin_installed( $slug ) ) { return false; } else { return ( false !== $this->does_plugin_have_update( $slug ) && $this->can_plugin_update( $slug ) ); } } /** * Check if a plugin can be activated, i.e. is not currently active and meets the minimum * plugin version requirements set in TGMPA (if any). * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True if OK to activate, false otherwise. */ public function can_plugin_activate( $slug ) { return ( ! $this->is_plugin_active( $slug ) && ! $this->does_plugin_require_update( $slug ) ); } /** * Retrieve the version number of an installed plugin. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string Version number as string or an empty string if the plugin is not installed * or version unknown (plugins which don't comply with the plugin header standard). */ public function get_installed_version( $slug ) { $installed_plugins = $this->get_plugins(); // Retrieve a list of all installed plugins (WP cached). if ( ! empty( $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version'] ) ) { return $installed_plugins[ $this->plugins[ $slug ]['file_path'] ]['Version']; } return ''; } /** * Check whether a plugin complies with the minimum version requirements. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return bool True when a plugin needs to be updated, otherwise false. */ public function does_plugin_require_update( $slug ) { $installed_version = $this->get_installed_version( $slug ); $minimum_version = $this->plugins[ $slug ]['version']; return version_compare( $minimum_version, $installed_version, '>' ); } /** * Check whether there is an update available for a plugin. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return false|string Version number string of the available update or false if no update available. */ public function does_plugin_have_update( $slug ) { // Presume bundled and external plugins will point to a package which meets the minimum required version. if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) { if ( $this->does_plugin_require_update( $slug ) ) { return $this->plugins[ $slug ]['version']; } return false; } $repo_updates = get_site_transient( 'update_plugins' ); if ( isset( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version ) ) { return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->new_version; } return false; } /** * Retrieve potential upgrade notice for a plugin. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string The upgrade notice or an empty string if no message was available or provided. */ public function get_upgrade_notice( $slug ) { // We currently can't get reliable info on non-WP-repo plugins - issue #380. if ( 'repo' !== $this->plugins[ $slug ]['source_type'] ) { return ''; } $repo_updates = get_site_transient( 'update_plugins' ); if ( ! empty( $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice ) ) { return $repo_updates->response[ $this->plugins[ $slug ]['file_path'] ]->upgrade_notice; } return ''; } /** * Wrapper around the core WP get_plugins function, making sure it's actually available. * * @since 2.5.0 * * @param string $plugin_folder Optional. Relative path to single plugin folder. * @return array Array of installed plugins with plugin information. */ public function get_plugins( $plugin_folder = '' ) { if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } return get_plugins( $plugin_folder ); } /** * Delete dismissable nag option when theme is switched. * * This ensures that the user(s) is/are again reminded via nag of required * and/or recommended plugins if they re-activate the theme. * * @since 2.1.1 */ public function update_dismiss() { delete_metadata( 'user', null, 'tgmpa_dismissed_notice_' . $this->id, null, true ); } /** * Forces plugin activation if the parameter 'force_activation' is * set to true. * * This allows theme authors to specify certain plugins that must be * active at all times while using the current theme. * * Please take special care when using this parameter as it has the * potential to be harmful if not used correctly. Setting this parameter * to true will not allow the specified plugin to be deactivated unless * the user switches themes. * * @since 2.2.0 */ public function force_activation() { foreach ( $this->plugins as $slug => $plugin ) { if ( true === $plugin['force_activation'] ) { if ( ! $this->is_plugin_installed( $slug ) ) { // Oops, plugin isn't there so iterate to next condition. continue; } elseif ( $this->can_plugin_activate( $slug ) ) { // There we go, activate the plugin. activate_plugin( $plugin['file_path'] ); } } } } /** * Forces plugin deactivation if the parameter 'force_deactivation' * is set to true and adds the plugin to the 'recently active' plugins list. * * This allows theme authors to specify certain plugins that must be * deactivated upon switching from the current theme to another. * * Please take special care when using this parameter as it has the * potential to be harmful if not used correctly. * * @since 2.2.0 */ public function force_deactivation() { $deactivated = array(); foreach ( $this->plugins as $slug => $plugin ) { /* * Only proceed forward if the parameter is set to true and plugin is active * as a 'normal' (not must-use) plugin. */ if ( true === $plugin['force_deactivation'] && is_plugin_active( $plugin['file_path'] ) ) { deactivate_plugins( $plugin['file_path'] ); $deactivated[ $plugin['file_path'] ] = time(); } } if ( ! empty( $deactivated ) ) { update_option( 'recently_activated', $deactivated + (array) get_option( 'recently_activated' ) ); } } /** * Echo the current TGMPA version number to the page. * * @since 2.5.0 */ public function show_tgmpa_version() { echo '<p style="float: right; padding: 0em 1.5em 0.5em 0;"><strong><small>', esc_html( sprintf( /* translators: %s: version number */ __( 'TGMPA v%s', 'growthspark' ), self::TGMPA_VERSION ) ), '</small></strong></p>'; } /** * Returns the singleton instance of the class. * * @since 2.4.0 * * @return \TGM_Plugin_Activation The TGM_Plugin_Activation object. */ public static function get_instance() { if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) { self::$instance = new self(); } return self::$instance; } } if ( ! function_exists( 'load_tgm_plugin_activation' ) ) { /** * Ensure only one instance of the class is ever invoked. * * @since 2.5.0 */ function load_tgm_plugin_activation() { $GLOBALS['tgmpa'] = TGM_Plugin_Activation::get_instance(); } } if ( did_action( 'plugins_loaded' ) ) { load_tgm_plugin_activation(); } else { add_action( 'plugins_loaded', 'load_tgm_plugin_activation' ); } } if ( ! function_exists( 'tgmpa' ) ) { /** * Helper function to register a collection of required plugins. * * @since 2.0.0 * @api * * @param array $plugins An array of plugin arrays. * @param array $config Optional. An array of configuration values. */ function tgmpa( $plugins, $config = array() ) { $instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); foreach ( $plugins as $plugin ) { call_user_func( array( $instance, 'register' ), $plugin ); } if ( ! empty( $config ) && is_array( $config ) ) { // Send out notices for deprecated arguments passed. if ( isset( $config['notices'] ) ) { _deprecated_argument( __FUNCTION__, '2.2.0', 'The `notices` config parameter was renamed to `has_notices` in TGMPA 2.2.0. Please adjust your configuration.' ); if ( ! isset( $config['has_notices'] ) ) { $config['has_notices'] = $config['notices']; } } if ( isset( $config['parent_menu_slug'] ) ) { _deprecated_argument( __FUNCTION__, '2.4.0', 'The `parent_menu_slug` config parameter was removed in TGMPA 2.4.0. In TGMPA 2.5.0 an alternative was (re-)introduced. Please adjust your configuration. For more information visit the website: http://tgmpluginactivation.com/configuration/#h-configuration-options.' ); } if ( isset( $config['parent_url_slug'] ) ) { _deprecated_argument( __FUNCTION__, '2.4.0', 'The `parent_url_slug` config parameter was removed in TGMPA 2.4.0. In TGMPA 2.5.0 an alternative was (re-)introduced. Please adjust your configuration. For more information visit the website: http://tgmpluginactivation.com/configuration/#h-configuration-options.' ); } call_user_func( array( $instance, 'config' ), $config ); } } } /** * WP_List_Table isn't always available. If it isn't available, * we load it here. * * @since 2.2.0 */ if ( ! class_exists( 'WP_List_Table' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php'; } if ( ! class_exists( 'TGMPA_List_Table' ) ) { /** * List table class for handling plugins. * * Extends the WP_List_Table class to provide a future-compatible * way of listing out all required/recommended plugins. * * Gives users an interface similar to the Plugin Administration * area with similar (albeit stripped down) capabilities. * * This class also allows for the bulk install of plugins. * * @since 2.2.0 * * @package TGM-Plugin-Activation * @author Thomas Griffin * @author Gary Jones */ class TGMPA_List_Table extends WP_List_Table { /** * TGMPA instance. * * @since 2.5.0 * * @var object */ protected $tgmpa; /** * The currently chosen view. * * @since 2.5.0 * * @var string One of: 'all', 'install', 'update', 'activate' */ public $view_context = 'all'; /** * The plugin counts for the various views. * * @since 2.5.0 * * @var array */ protected $view_totals = array( 'all' => 0, 'install' => 0, 'update' => 0, 'activate' => 0, ); /** * References parent constructor and sets defaults for class. * * @since 2.2.0 */ public function __construct() { $this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); parent::__construct( array( 'singular' => 'plugin', 'plural' => 'plugins', 'ajax' => false, ) ); if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'install', 'update', 'activate' ), true ) ) { $this->view_context = sanitize_key( $_REQUEST['plugin_status'] ); } add_filter( 'tgmpa_table_data_items', array( $this, 'sort_table_items' ) ); } /** * Get a list of CSS classes for the <table> tag. * * Overruled to prevent the 'plural' argument from being added. * * @since 2.5.0 * * @return array CSS classnames. */ public function get_table_classes() { return array( 'widefat', 'fixed' ); } /** * Gathers and renames all of our plugin information to be used by WP_List_Table to create our table. * * @since 2.2.0 * * @return array $table_data Information for use in table. */ protected function _gather_plugin_data() { // Load thickbox for plugin links. $this->tgmpa->admin_init(); $this->tgmpa->thickbox(); // Categorize the plugins which have open actions. $plugins = $this->categorize_plugins_to_views(); // Set the counts for the view links. $this->set_view_totals( $plugins ); // Prep variables for use and grab list of all installed plugins. $table_data = array(); $i = 0; // Redirect to the 'all' view if no plugins were found for the selected view context. if ( empty( $plugins[ $this->view_context ] ) ) { $this->view_context = 'all'; } foreach ( $plugins[ $this->view_context ] as $slug => $plugin ) { $table_data[ $i ]['sanitized_plugin'] = $plugin['name']; $table_data[ $i ]['slug'] = $slug; $table_data[ $i ]['plugin'] = '<strong>' . $this->tgmpa->get_info_link( $slug ) . '</strong>'; $table_data[ $i ]['source'] = $this->get_plugin_source_type_text( $plugin['source_type'] ); $table_data[ $i ]['type'] = $this->get_plugin_advise_type_text( $plugin['required'] ); $table_data[ $i ]['status'] = $this->get_plugin_status_text( $slug ); $table_data[ $i ]['installed_version'] = $this->tgmpa->get_installed_version( $slug ); $table_data[ $i ]['minimum_version'] = $plugin['version']; $table_data[ $i ]['available_version'] = $this->tgmpa->does_plugin_have_update( $slug ); // Prep the upgrade notice info. $upgrade_notice = $this->tgmpa->get_upgrade_notice( $slug ); if ( ! empty( $upgrade_notice ) ) { $table_data[ $i ]['upgrade_notice'] = $upgrade_notice; add_action( "tgmpa_after_plugin_row_{$slug}", array( $this, 'wp_plugin_update_row' ), 10, 2 ); } $table_data[ $i ] = apply_filters( 'tgmpa_table_data_item', $table_data[ $i ], $plugin ); $i++; } return $table_data; } /** * Categorize the plugins which have open actions into views for the TGMPA page. * * @since 2.5.0 */ protected function categorize_plugins_to_views() { $plugins = array( 'all' => array(), // Meaning: all plugins which still have open actions. 'install' => array(), 'update' => array(), 'activate' => array(), ); foreach ( $this->tgmpa->plugins as $slug => $plugin ) { if ( $this->tgmpa->is_plugin_active( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) { // No need to display plugins if they are installed, up-to-date and active. continue; } else { $plugins['all'][ $slug ] = $plugin; if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) { $plugins['install'][ $slug ] = $plugin; } else { if ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) { $plugins['update'][ $slug ] = $plugin; } if ( $this->tgmpa->can_plugin_activate( $slug ) ) { $plugins['activate'][ $slug ] = $plugin; } } } } return $plugins; } /** * Set the counts for the view links. * * @since 2.5.0 * * @param array $plugins Plugins order by view. */ protected function set_view_totals( $plugins ) { foreach ( $plugins as $type => $list ) { $this->view_totals[ $type ] = count( $list ); } } /** * Get the plugin required/recommended text string. * * @since 2.5.0 * * @param string $required Plugin required setting. * @return string */ protected function get_plugin_advise_type_text( $required ) { if ( true === $required ) { return __( 'Required', 'growthspark' ); } return __( 'Recommended', 'growthspark' ); } /** * Get the plugin source type text string. * * @since 2.5.0 * * @param string $type Plugin type. * @return string */ protected function get_plugin_source_type_text( $type ) { $string = ''; switch ( $type ) { case 'repo': $string = __( 'WordPress Repository', 'growthspark' ); break; case 'external': $string = __( 'External Source', 'growthspark' ); break; case 'bundled': $string = __( 'Pre-Packaged', 'growthspark' ); break; } return $string; } /** * Determine the plugin status message. * * @since 2.5.0 * * @param string $slug Plugin slug. * @return string */ protected function get_plugin_status_text( $slug ) { if ( ! $this->tgmpa->is_plugin_installed( $slug ) ) { return __( 'Not Installed', 'growthspark' ); } if ( ! $this->tgmpa->is_plugin_active( $slug ) ) { $install_status = __( 'Installed But Not Activated', 'growthspark' ); } else { $install_status = __( 'Active', 'growthspark' ); } $update_status = ''; if ( $this->tgmpa->does_plugin_require_update( $slug ) && false === $this->tgmpa->does_plugin_have_update( $slug ) ) { $update_status = __( 'Required Update not Available', 'growthspark' ); } elseif ( $this->tgmpa->does_plugin_require_update( $slug ) ) { $update_status = __( 'Requires Update', 'growthspark' ); } elseif ( false !== $this->tgmpa->does_plugin_have_update( $slug ) ) { $update_status = __( 'Update recommended', 'growthspark' ); } if ( '' === $update_status ) { return $install_status; } return sprintf( /* translators: 1: install status, 2: update status */ _x( '%1$s, %2$s', 'Install/Update Status', 'growthspark' ), $install_status, $update_status ); } /** * Sort plugins by Required/Recommended type and by alphabetical plugin name within each type. * * @since 2.5.0 * * @param array $items Prepared table items. * @return array Sorted table items. */ public function sort_table_items( $items ) { $type = array(); $name = array(); foreach ( $items as $i => $plugin ) { $type[ $i ] = $plugin['type']; // Required / recommended. $name[ $i ] = $plugin['sanitized_plugin']; } array_multisort( $type, SORT_DESC, $name, SORT_ASC, $items ); return $items; } /** * Get an associative array ( id => link ) of the views available on this table. * * @since 2.5.0 * * @return array */ public function get_views() { $status_links = array(); foreach ( $this->view_totals as $type => $count ) { if ( $count < 1 ) { continue; } switch ( $type ) { case 'all': /* translators: 1: number of plugins. */ $text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins', 'growthspark' ); break; case 'install': /* translators: 1: number of plugins. */ $text = _n( 'To Install <span class="count">(%s)</span>', 'To Install <span class="count">(%s)</span>', $count, 'growthspark' ); break; case 'update': /* translators: 1: number of plugins. */ $text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count, 'growthspark' ); break; case 'activate': /* translators: 1: number of plugins. */ $text = _n( 'To Activate <span class="count">(%s)</span>', 'To Activate <span class="count">(%s)</span>', $count, 'growthspark' ); break; default: $text = ''; break; } if ( ! empty( $text ) ) { $status_links[ $type ] = sprintf( '<a href="%s"%s>%s</a>', esc_url( $this->tgmpa->get_tgmpa_status_url( $type ) ), ( $type === $this->view_context ) ? ' class="current"' : '', sprintf( $text, number_format_i18n( $count ) ) ); } } return $status_links; } /** * Create default columns to display important plugin information * like type, action and status. * * @since 2.2.0 * * @param array $item Array of item data. * @param string $column_name The name of the column. * @return string */ public function column_default( $item, $column_name ) { return $item[ $column_name ]; } /** * Required for bulk installing. * * Adds a checkbox for each plugin. * * @since 2.2.0 * * @param array $item Array of item data. * @return string The input checkbox with all necessary info. */ public function column_cb( $item ) { return sprintf( '<input type="checkbox" name="%1$s[]" value="%2$s" id="%3$s" />', esc_attr( $this->_args['singular'] ), esc_attr( $item['slug'] ), esc_attr( $item['sanitized_plugin'] ) ); } /** * Create default title column along with the action links. * * @since 2.2.0 * * @param array $item Array of item data. * @return string The plugin name and action links. */ public function column_plugin( $item ) { return sprintf( '%1$s %2$s', $item['plugin'], $this->row_actions( $this->get_row_actions( $item ), true ) ); } /** * Create version information column. * * @since 2.5.0 * * @param array $item Array of item data. * @return string HTML-formatted version information. */ public function column_version( $item ) { $output = array(); if ( $this->tgmpa->is_plugin_installed( $item['slug'] ) ) { $installed = ! empty( $item['installed_version'] ) ? $item['installed_version'] : _x( 'unknown', 'as in: "version nr unknown"', 'growthspark' ); $color = ''; if ( ! empty( $item['minimum_version'] ) && $this->tgmpa->does_plugin_require_update( $item['slug'] ) ) { $color = ' color: #ff0000; font-weight: bold;'; } $output[] = sprintf( '<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Installed version:', 'growthspark' ) . '</p>', $color, $installed ); } if ( ! empty( $item['minimum_version'] ) ) { $output[] = sprintf( '<p><span style="min-width: 32px; text-align: right; float: right;">%1$s</span>' . __( 'Minimum required version:', 'growthspark' ) . '</p>', $item['minimum_version'] ); } if ( ! empty( $item['available_version'] ) ) { $color = ''; if ( ! empty( $item['minimum_version'] ) && version_compare( $item['available_version'], $item['minimum_version'], '>=' ) ) { $color = ' color: #71C671; font-weight: bold;'; } $output[] = sprintf( '<p><span style="min-width: 32px; text-align: right; float: right;%1$s">%2$s</span>' . __( 'Available version:', 'growthspark' ) . '</p>', $color, $item['available_version'] ); } if ( empty( $output ) ) { return '&nbsp;'; // Let's not break the table layout. } else { return implode( "\n", $output ); } } /** * Sets default message within the plugins table if no plugins * are left for interaction. * * Hides the menu item to prevent the user from clicking and * getting a permissions error. * * @since 2.2.0 */ public function no_items() { echo esc_html__( 'No plugins to install, update or activate.', 'growthspark' ) . ' <a href="' . esc_url( self_admin_url() ) . '"> ' . esc_html__( 'Return to the Dashboard', 'growthspark' ) . '</a>'; echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>'; } /** * Output all the column information within the table. * * @since 2.2.0 * * @return array $columns The column names. */ public function get_columns() { $columns = array( 'cb' => '<input type="checkbox" />', 'plugin' => __( 'Plugin', 'growthspark' ), 'source' => __( 'Source', 'growthspark' ), 'type' => __( 'Type', 'growthspark' ), ); if ( 'all' === $this->view_context || 'update' === $this->view_context ) { $columns['version'] = __( 'Version', 'growthspark' ); $columns['status'] = __( 'Status', 'growthspark' ); } return apply_filters( 'tgmpa_table_columns', $columns ); } /** * Get name of default primary column * * @since 2.5.0 / WP 4.3+ compatibility * @access protected * * @return string */ protected function get_default_primary_column_name() { return 'plugin'; } /** * Get the name of the primary column. * * @since 2.5.0 / WP 4.3+ compatibility * @access protected * * @return string The name of the primary column. */ protected function get_primary_column_name() { if ( method_exists( 'WP_List_Table', 'get_primary_column_name' ) ) { return parent::get_primary_column_name(); } else { return $this->get_default_primary_column_name(); } } /** * Get the actions which are relevant for a specific plugin row. * * @since 2.5.0 * * @param array $item Array of item data. * @return array Array with relevant action links. */ protected function get_row_actions( $item ) { $actions = array(); $action_links = array(); // Display the 'Install' action link if the plugin is not yet available. if ( ! $this->tgmpa->is_plugin_installed( $item['slug'] ) ) { /* translators: %2$s: plugin name in screen reader markup */ $actions['install'] = __( 'Install %2$s', 'growthspark' ); } else { // Display the 'Update' action link if an update is available and WP complies with plugin minimum. if ( false !== $this->tgmpa->does_plugin_have_update( $item['slug'] ) && $this->tgmpa->can_plugin_update( $item['slug'] ) ) { /* translators: %2$s: plugin name in screen reader markup */ $actions['update'] = __( 'Update %2$s', 'growthspark' ); } // Display the 'Activate' action link, but only if the plugin meets the minimum version. if ( $this->tgmpa->can_plugin_activate( $item['slug'] ) ) { /* translators: %2$s: plugin name in screen reader markup */ $actions['activate'] = __( 'Activate %2$s', 'growthspark' ); } } // Create the actual links. foreach ( $actions as $action => $text ) { $nonce_url = wp_nonce_url( add_query_arg( array( 'plugin' => urlencode( $item['slug'] ), 'tgmpa-' . $action => $action . '-plugin', ), $this->tgmpa->get_tgmpa_url() ), 'tgmpa-' . $action, 'tgmpa-nonce' ); $action_links[ $action ] = sprintf( '<a href="%1$s">' . esc_html( $text ) . '</a>', // $text contains the second placeholder. esc_url( $nonce_url ), '<span class="screen-reader-text">' . esc_html( $item['sanitized_plugin'] ) . '</span>' ); } $prefix = ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) ? 'network_admin_' : ''; return apply_filters( "tgmpa_{$prefix}plugin_action_links", array_filter( $action_links ), $item['slug'], $item, $this->view_context ); } /** * Generates content for a single row of the table. * * @since 2.5.0 * * @param object $item The current item. */ public function single_row( $item ) { parent::single_row( $item ); /** * Fires after each specific row in the TGMPA Plugins list table. * * The dynamic portion of the hook name, `$item['slug']`, refers to the slug * for the plugin. * * @since 2.5.0 */ do_action( "tgmpa_after_plugin_row_{$item['slug']}", $item['slug'], $item, $this->view_context ); } /** * Show the upgrade notice below a plugin row if there is one. * * @since 2.5.0 * * @see /wp-admin/includes/update.php * * @param string $slug Plugin slug. * @param array $item The information available in this table row. * @return null Return early if upgrade notice is empty. */ public function wp_plugin_update_row( $slug, $item ) { if ( empty( $item['upgrade_notice'] ) ) { return; } echo ' <tr class="plugin-update-tr"> <td colspan="', absint( $this->get_column_count() ), '" class="plugin-update colspanchange"> <div class="update-message">', esc_html__( 'Upgrade message from the plugin author:', 'growthspark' ), ' <strong>', wp_kses_data( $item['upgrade_notice'] ), '</strong> </div> </td> </tr>'; } /** * Extra controls to be displayed between bulk actions and pagination. * * @since 2.5.0 * * @param string $which 'top' or 'bottom' table navigation. */ public function extra_tablenav( $which ) { if ( 'bottom' === $which ) { $this->tgmpa->show_tgmpa_version(); } } /** * Defines the bulk actions for handling registered plugins. * * @since 2.2.0 * * @return array $actions The bulk actions for the plugin install table. */ public function get_bulk_actions() { $actions = array(); if ( 'update' !== $this->view_context && 'activate' !== $this->view_context ) { if ( current_user_can( 'install_plugins' ) ) { $actions['tgmpa-bulk-install'] = __( 'Install', 'growthspark' ); } } if ( 'install' !== $this->view_context ) { if ( current_user_can( 'update_plugins' ) ) { $actions['tgmpa-bulk-update'] = __( 'Update', 'growthspark' ); } if ( current_user_can( 'activate_plugins' ) ) { $actions['tgmpa-bulk-activate'] = __( 'Activate', 'growthspark' ); } } return $actions; } /** * Processes bulk installation and activation actions. * * The bulk installation process looks for the $_POST information and passes that * through if a user has to use WP_Filesystem to enter their credentials. * * @since 2.2.0 */ public function process_bulk_actions() { // Bulk installation process. if ( 'tgmpa-bulk-install' === $this->current_action() || 'tgmpa-bulk-update' === $this->current_action() ) { check_admin_referer( 'bulk-' . $this->_args['plural'] ); $install_type = 'install'; if ( 'tgmpa-bulk-update' === $this->current_action() ) { $install_type = 'update'; } $plugins_to_install = array(); // Did user actually select any plugins to install/update ? if ( empty( $_POST['plugin'] ) ) { if ( 'install' === $install_type ) { $message = __( 'No plugins were selected to be installed. No action taken.', 'growthspark' ); } else { $message = __( 'No plugins were selected to be updated. No action taken.', 'growthspark' ); } echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>'; return false; } if ( is_array( $_POST['plugin'] ) ) { $plugins_to_install = (array) $_POST['plugin']; } elseif ( is_string( $_POST['plugin'] ) ) { // Received via Filesystem page - un-flatten array (WP bug #19643). $plugins_to_install = explode( ',', $_POST['plugin'] ); } // Sanitize the received input. $plugins_to_install = array_map( 'urldecode', $plugins_to_install ); $plugins_to_install = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins_to_install ); // Validate the received input. foreach ( $plugins_to_install as $key => $slug ) { // Check if the plugin was registered with TGMPA and remove if not. if ( ! isset( $this->tgmpa->plugins[ $slug ] ) ) { unset( $plugins_to_install[ $key ] ); continue; } // For install: make sure this is a plugin we *can* install and not one already installed. if ( 'install' === $install_type && true === $this->tgmpa->is_plugin_installed( $slug ) ) { unset( $plugins_to_install[ $key ] ); } // For updates: make sure this is a plugin we *can* update (update available and WP version ok). if ( 'update' === $install_type && false === $this->tgmpa->is_plugin_updatetable( $slug ) ) { unset( $plugins_to_install[ $key ] ); } } // No need to proceed further if we have no plugins to handle. if ( empty( $plugins_to_install ) ) { if ( 'install' === $install_type ) { $message = __( 'No plugins are available to be installed at this time.', 'growthspark' ); } else { $message = __( 'No plugins are available to be updated at this time.', 'growthspark' ); } echo '<div id="message" class="error"><p>', esc_html( $message ), '</p></div>'; return false; } // Pass all necessary information if WP_Filesystem is needed. $url = wp_nonce_url( $this->tgmpa->get_tgmpa_url(), 'bulk-' . $this->_args['plural'] ); // Give validated data back to $_POST which is the only place the filesystem looks for extra fields. $_POST['plugin'] = implode( ',', $plugins_to_install ); // Work around for WP bug #19643. $method = ''; // Leave blank so WP_Filesystem can populate it as necessary. $fields = array_keys( $_POST ); // Extra fields to pass to WP_Filesystem. if ( false === ( $creds = request_filesystem_credentials( esc_url_raw( $url ), $method, false, false, $fields ) ) ) { return true; // Stop the normal page form from displaying, credential request form will be shown. } // Now we have some credentials, setup WP_Filesystem. if ( ! WP_Filesystem( $creds ) ) { // Our credentials were no good, ask the user for them again. request_filesystem_credentials( esc_url_raw( $url ), $method, true, false, $fields ); return true; } /* If we arrive here, we have the filesystem */ // Store all information in arrays since we are processing a bulk installation. $names = array(); $sources = array(); // Needed for installs. $file_paths = array(); // Needed for upgrades. $to_inject = array(); // Information to inject into the update_plugins transient. // Prepare the data for validated plugins for the install/upgrade. foreach ( $plugins_to_install as $slug ) { $name = $this->tgmpa->plugins[ $slug ]['name']; $source = $this->tgmpa->get_download_url( $slug ); if ( ! empty( $name ) && ! empty( $source ) ) { $names[] = $name; switch ( $install_type ) { case 'install': $sources[] = $source; break; case 'update': $file_paths[] = $this->tgmpa->plugins[ $slug ]['file_path']; $to_inject[ $slug ] = $this->tgmpa->plugins[ $slug ]; $to_inject[ $slug ]['source'] = $source; break; } } } unset( $slug, $name, $source ); // Create a new instance of TGMPA_Bulk_Installer. $installer = new TGMPA_Bulk_Installer( new TGMPA_Bulk_Installer_Skin( array( 'url' => esc_url_raw( $this->tgmpa->get_tgmpa_url() ), 'nonce' => 'bulk-' . $this->_args['plural'], 'names' => $names, 'install_type' => $install_type, ) ) ); // Wrap the install process with the appropriate HTML. echo '<div class="tgmpa">', '<h2 style="font-size: 23px; font-weight: 400; line-height: 29px; margin: 0; padding: 9px 15px 4px 0;">', esc_html( get_admin_page_title() ), '</h2> <div class="update-php" style="width: 100%; height: 98%; min-height: 850px; padding-top: 1px;">'; // Process the bulk installation submissions. add_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1, 3 ); if ( 'tgmpa-bulk-update' === $this->current_action() ) { // Inject our info into the update transient. $this->tgmpa->inject_update_info( $to_inject ); $installer->bulk_upgrade( $file_paths ); } else { $installer->bulk_install( $sources ); } remove_filter( 'upgrader_source_selection', array( $this->tgmpa, 'maybe_adjust_source_dir' ), 1 ); echo '</div></div>'; return true; } // Bulk activation process. if ( 'tgmpa-bulk-activate' === $this->current_action() ) { check_admin_referer( 'bulk-' . $this->_args['plural'] ); // Did user actually select any plugins to activate ? if ( empty( $_POST['plugin'] ) ) { echo '<div id="message" class="error"><p>', esc_html__( 'No plugins were selected to be activated. No action taken.', 'growthspark' ), '</p></div>'; return false; } // Grab plugin data from $_POST. $plugins = array(); if ( isset( $_POST['plugin'] ) ) { $plugins = array_map( 'urldecode', (array) $_POST['plugin'] ); $plugins = array_map( array( $this->tgmpa, 'sanitize_key' ), $plugins ); } $plugins_to_activate = array(); $plugin_names = array(); // Grab the file paths for the selected & inactive plugins from the registration array. foreach ( $plugins as $slug ) { if ( $this->tgmpa->can_plugin_activate( $slug ) ) { $plugins_to_activate[] = $this->tgmpa->plugins[ $slug ]['file_path']; $plugin_names[] = $this->tgmpa->plugins[ $slug ]['name']; } } unset( $slug ); // Return early if there are no plugins to activate. if ( empty( $plugins_to_activate ) ) { echo '<div id="message" class="error"><p>', esc_html__( 'No plugins are available to be activated at this time.', 'growthspark' ), '</p></div>'; return false; } // Now we are good to go - let's start activating plugins. $activate = activate_plugins( $plugins_to_activate ); if ( is_wp_error( $activate ) ) { echo '<div id="message" class="error"><p>', wp_kses_post( $activate->get_error_message() ), '</p></div>'; } else { $count = count( $plugin_names ); // Count so we can use _n function. $plugin_names = array_map( array( 'TGMPA_Utils', 'wrap_in_strong' ), $plugin_names ); $last_plugin = array_pop( $plugin_names ); // Pop off last name to prep for readability. $imploded = empty( $plugin_names ) ? $last_plugin : ( implode( ', ', $plugin_names ) . ' ' . esc_html_x( 'and', 'plugin A *and* plugin B', 'growthspark' ) . ' ' . $last_plugin ); printf( // WPCS: xss ok. '<div id="message" class="updated"><p>%1$s %2$s.</p></div>', esc_html( _n( 'The following plugin was activated successfully:', 'The following plugins were activated successfully:', $count, 'growthspark' ) ), $imploded ); // Update recently activated plugins option. $recent = (array) get_option( 'recently_activated' ); foreach ( $plugins_to_activate as $plugin => $time ) { if ( isset( $recent[ $plugin ] ) ) { unset( $recent[ $plugin ] ); } } update_option( 'recently_activated', $recent ); } unset( $_POST ); // Reset the $_POST variable in case user wants to perform one action after another. return true; } return false; } /** * Prepares all of our information to be outputted into a usable table. * * @since 2.2.0 */ public function prepare_items() { $columns = $this->get_columns(); // Get all necessary column information. $hidden = array(); // No columns to hide, but we must set as an array. $sortable = array(); // No reason to make sortable columns. $primary = $this->get_primary_column_name(); // Column which has the row actions. $this->_column_headers = array( $columns, $hidden, $sortable, $primary ); // Get all necessary column headers. // Process our bulk activations here. if ( 'tgmpa-bulk-activate' === $this->current_action() ) { $this->process_bulk_actions(); } // Store all of our plugin data into $items array so WP_List_Table can use it. $this->items = apply_filters( 'tgmpa_table_data_items', $this->_gather_plugin_data() ); } /* *********** DEPRECATED METHODS *********** */ /** * Retrieve plugin data, given the plugin name. * * @since 2.2.0 * @deprecated 2.5.0 use {@see TGM_Plugin_Activation::_get_plugin_data_from_name()} instead. * @see TGM_Plugin_Activation::_get_plugin_data_from_name() * * @param string $name Name of the plugin, as it was registered. * @param string $data Optional. Array key of plugin data to return. Default is slug. * @return string|boolean Plugin slug if found, false otherwise. */ protected function _get_plugin_data_from_name( $name, $data = 'slug' ) { _deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'TGM_Plugin_Activation::_get_plugin_data_from_name()' ); return $this->tgmpa->_get_plugin_data_from_name( $name, $data ); } } } if ( ! class_exists( 'TGM_Bulk_Installer' ) ) { /** * Hack: Prevent TGMPA v2.4.1- bulk installer class from being loaded if 2.4.1- is loaded after 2.5+. * * @since 2.5.2 * * {@internal The TGMPA_Bulk_Installer class was originally called TGM_Bulk_Installer. * For more information, see that class.}} */ class TGM_Bulk_Installer { } } if ( ! class_exists( 'TGM_Bulk_Installer_Skin' ) ) { /** * Hack: Prevent TGMPA v2.4.1- bulk installer skin class from being loaded if 2.4.1- is loaded after 2.5+. * * @since 2.5.2 * * {@internal The TGMPA_Bulk_Installer_Skin class was originally called TGM_Bulk_Installer_Skin. * For more information, see that class.}} */ class TGM_Bulk_Installer_Skin { } } /** * The WP_Upgrader file isn't always available. If it isn't available, * we load it here. * * We check to make sure no action or activation keys are set so that WordPress * does not try to re-include the class when processing upgrades or installs outside * of the class. * * @since 2.2.0 */ add_action( 'admin_init', 'tgmpa_load_bulk_installer' ); if ( ! function_exists( 'tgmpa_load_bulk_installer' ) ) { /** * Load bulk installer */ function tgmpa_load_bulk_installer() { // Silently fail if 2.5+ is loaded *after* an older version. if ( ! isset( $GLOBALS['tgmpa'] ) ) { return; } // Get TGMPA class instance. $tgmpa_instance = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); if ( isset( $_GET['page'] ) && $tgmpa_instance->menu === $_GET['page'] ) { if ( ! class_exists( 'Plugin_Upgrader', false ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; } if ( ! class_exists( 'TGMPA_Bulk_Installer' ) ) { /** * Installer class to handle bulk plugin installations. * * Extends WP_Upgrader and customizes to suit the installation of multiple * plugins. * * @since 2.2.0 * * {@internal Since 2.5.0 the class is an extension of Plugin_Upgrader rather than WP_Upgrader.}} * {@internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer to TGMPA_Bulk_Installer. * This was done to prevent backward compatibility issues with v2.3.6.}} * * @package TGM-Plugin-Activation * @author Thomas Griffin * @author Gary Jones */ class TGMPA_Bulk_Installer extends Plugin_Upgrader { /** * Holds result of bulk plugin installation. * * @since 2.2.0 * * @var string */ public $result; /** * Flag to check if bulk installation is occurring or not. * * @since 2.2.0 * * @var boolean */ public $bulk = false; /** * TGMPA instance * * @since 2.5.0 * * @var object */ protected $tgmpa; /** * Whether or not the destination directory needs to be cleared ( = on update). * * @since 2.5.0 * * @var bool */ protected $clear_destination = false; /** * References parent constructor and sets defaults for class. * * @since 2.2.0 * * @param \Bulk_Upgrader_Skin|null $skin Installer skin. */ public function __construct( $skin = null ) { // Get TGMPA class instance. $this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); parent::__construct( $skin ); if ( isset( $this->skin->options['install_type'] ) && 'update' === $this->skin->options['install_type'] ) { $this->clear_destination = true; } if ( $this->tgmpa->is_automatic ) { $this->activate_strings(); } add_action( 'upgrader_process_complete', array( $this->tgmpa, 'populate_file_path' ) ); } /** * Sets the correct activation strings for the installer skin to use. * * @since 2.2.0 */ public function activate_strings() { $this->strings['activation_failed'] = __( 'Plugin activation failed.', 'growthspark' ); $this->strings['activation_success'] = __( 'Plugin activated successfully.', 'growthspark' ); } /** * Performs the actual installation of each plugin. * * @since 2.2.0 * * @see WP_Upgrader::run() * * @param array $options The installation config options. * @return null|array Return early if error, array of installation data on success. */ public function run( $options ) { $result = parent::run( $options ); // Reset the strings in case we changed one during automatic activation. if ( $this->tgmpa->is_automatic ) { if ( 'update' === $this->skin->options['install_type'] ) { $this->upgrade_strings(); } else { $this->install_strings(); } } return $result; } /** * Processes the bulk installation of plugins. * * @since 2.2.0 * * {@internal This is basically a near identical copy of the WP Core * Plugin_Upgrader::bulk_upgrade() method, with minor adjustments to deal with * new installs instead of upgrades. * For ease of future synchronizations, the adjustments are clearly commented, but no other * comments are added. Code style has been made to comply.}} * * @see Plugin_Upgrader::bulk_upgrade() * @see https://core.trac.wordpress.org/browser/tags/4.2.1/src/wp-admin/includes/class-wp-upgrader.php#L838 * (@internal Last synced: Dec 31st 2015 against https://core.trac.wordpress.org/browser/trunk?rev=36134}} * * @param array $plugins The plugin sources needed for installation. * @param array $args Arbitrary passed extra arguments. * @return array|false Install confirmation messages on success, false on failure. */ public function bulk_install( $plugins, $args = array() ) { // [TGMPA + ] Hook auto-activation in. add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 ); $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->bulk = true; $this->install_strings(); // [TGMPA + ] adjusted. /* [TGMPA - ] $current = get_site_transient( 'update_plugins' ); */ /* [TGMPA - ] add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4); */ $this->skin->header(); // Connect to the Filesystem first. $res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) ); if ( ! $res ) { $this->skin->footer(); return false; } $this->skin->bulk_header(); /* * Only start maintenance mode if: * - running Multisite and there are one or more plugins specified, OR * - a plugin with an update available is currently active. * @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible. */ $maintenance = ( is_multisite() && ! empty( $plugins ) ); /* [TGMPA - ] foreach ( $plugins as $plugin ) $maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) ); */ if ( $maintenance ) { $this->maintenance_mode( true ); } $results = array(); $this->update_count = count( $plugins ); $this->update_current = 0; foreach ( $plugins as $plugin ) { $this->update_current++; /* [TGMPA - ] $this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true); if ( !isset( $current->response[ $plugin ] ) ) { $this->skin->set_result('up_to_date'); $this->skin->before(); $this->skin->feedback('up_to_date'); $this->skin->after(); $results[$plugin] = true; continue; } // Get the URL to the zip file. $r = $current->response[ $plugin ]; $this->skin->plugin_active = is_plugin_active($plugin); */ $result = $this->run( array( 'package' => $plugin, // [TGMPA + ] adjusted. 'destination' => WP_PLUGIN_DIR, 'clear_destination' => false, // [TGMPA + ] adjusted. 'clear_working' => true, 'is_multi' => true, 'hook_extra' => array( 'plugin' => $plugin, ), ) ); $results[ $plugin ] = $this->result; // Prevent credentials auth screen from displaying multiple times. if ( false === $result ) { break; } } //end foreach $plugins $this->maintenance_mode( false ); /** * Fires when the bulk upgrader process is complete. * * @since WP 3.6.0 / TGMPA 2.5.0 * * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might * be a Theme_Upgrader or Core_Upgrade instance. * @param array $data { * Array of bulk item update data. * * @type string $action Type of action. Default 'update'. * @type string $type Type of update process. Accepts 'plugin', 'theme', or 'core'. * @type bool $bulk Whether the update process is a bulk update. Default true. * @type array $packages Array of plugin, theme, or core packages to update. * } */ do_action( 'upgrader_process_complete', $this, array( 'action' => 'install', // [TGMPA + ] adjusted. 'type' => 'plugin', 'bulk' => true, 'plugins' => $plugins, ) ); $this->skin->bulk_footer(); $this->skin->footer(); // Cleanup our hooks, in case something else does a upgrade on this connection. /* [TGMPA - ] remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin')); */ // [TGMPA + ] Remove our auto-activation hook. remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 ); // Force refresh of plugin update information. wp_clean_plugins_cache( $parsed_args['clear_update_cache'] ); return $results; } /** * Handle a bulk upgrade request. * * @since 2.5.0 * * @see Plugin_Upgrader::bulk_upgrade() * * @param array $plugins The local WP file_path's of the plugins which should be upgraded. * @param array $args Arbitrary passed extra arguments. * @return string|bool Install confirmation messages on success, false on failure. */ public function bulk_upgrade( $plugins, $args = array() ) { add_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 ); $result = parent::bulk_upgrade( $plugins, $args ); remove_filter( 'upgrader_post_install', array( $this, 'auto_activate' ), 10 ); return $result; } /** * Abuse a filter to auto-activate plugins after installation. * * Hooked into the 'upgrader_post_install' filter hook. * * @since 2.5.0 * * @param bool $bool The value we need to give back (true). * @return bool */ public function auto_activate( $bool ) { // Only process the activation of installed plugins if the automatic flag is set to true. if ( $this->tgmpa->is_automatic ) { // Flush plugins cache so the headers of the newly installed plugins will be read correctly. wp_clean_plugins_cache(); // Get the installed plugin file. $plugin_info = $this->plugin_info(); // Don't try to activate on upgrade of active plugin as WP will do this already. if ( ! is_plugin_active( $plugin_info ) ) { $activate = activate_plugin( $plugin_info ); // Adjust the success string based on the activation result. $this->strings['process_success'] = $this->strings['process_success'] . "<br />\n"; if ( is_wp_error( $activate ) ) { $this->skin->error( $activate ); $this->strings['process_success'] .= $this->strings['activation_failed']; } else { $this->strings['process_success'] .= $this->strings['activation_success']; } } } return $bool; } } } if ( ! class_exists( 'TGMPA_Bulk_Installer_Skin' ) ) { /** * Installer skin to set strings for the bulk plugin installations.. * * Extends Bulk_Upgrader_Skin and customizes to suit the installation of multiple * plugins. * * @since 2.2.0 * * {@internal Since 2.5.2 the class has been renamed from TGM_Bulk_Installer_Skin to * TGMPA_Bulk_Installer_Skin. * This was done to prevent backward compatibility issues with v2.3.6.}} * * @see https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/class-wp-upgrader-skins.php * * @package TGM-Plugin-Activation * @author Thomas Griffin * @author Gary Jones */ class TGMPA_Bulk_Installer_Skin extends Bulk_Upgrader_Skin { /** * Holds plugin info for each individual plugin installation. * * @since 2.2.0 * * @var array */ public $plugin_info = array(); /** * Holds names of plugins that are undergoing bulk installations. * * @since 2.2.0 * * @var array */ public $plugin_names = array(); /** * Integer to use for iteration through each plugin installation. * * @since 2.2.0 * * @var integer */ public $i = 0; /** * TGMPA instance * * @since 2.5.0 * * @var object */ protected $tgmpa; /** * Constructor. Parses default args with new ones and extracts them for use. * * @since 2.2.0 * * @param array $args Arguments to pass for use within the class. */ public function __construct( $args = array() ) { // Get TGMPA class instance. $this->tgmpa = call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ); // Parse default and new args. $defaults = array( 'url' => '', 'nonce' => '', 'names' => array(), 'install_type' => 'install', ); $args = wp_parse_args( $args, $defaults ); // Set plugin names to $this->plugin_names property. $this->plugin_names = $args['names']; // Extract the new args. parent::__construct( $args ); } /** * Sets install skin strings for each individual plugin. * * Checks to see if the automatic activation flag is set and uses the * the proper strings accordingly. * * @since 2.2.0 */ public function add_strings() { if ( 'update' === $this->options['install_type'] ) { parent::add_strings(); /* translators: 1: plugin name, 2: action number 3: total number of actions. */ $this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)', 'growthspark' ); } else { /* translators: 1: plugin name, 2: error message. */ $this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while installing %1$s: <strong>%2$s</strong>.', 'growthspark' ); /* translators: 1: plugin name. */ $this->upgrader->strings['skin_update_failed'] = __( 'The installation of %1$s failed.', 'growthspark' ); if ( $this->tgmpa->is_automatic ) { // Automatic activation strings. $this->upgrader->strings['skin_upgrade_start'] = __( 'The installation and activation process is starting. This process may take a while on some hosts, so please be patient.', 'growthspark' ); /* translators: 1: plugin name. */ $this->upgrader->strings['skin_update_successful'] = __( '%1$s installed and activated successfully.', 'growthspark' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'growthspark' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'growthspark' ) . '</span>.</a>'; $this->upgrader->strings['skin_upgrade_end'] = __( 'All installations and activations have been completed.', 'growthspark' ); /* translators: 1: plugin name, 2: action number 3: total number of actions. */ $this->upgrader->strings['skin_before_update_header'] = __( 'Installing and Activating Plugin %1$s (%2$d/%3$d)', 'growthspark' ); } else { // Default installation strings. $this->upgrader->strings['skin_upgrade_start'] = __( 'The installation process is starting. This process may take a while on some hosts, so please be patient.', 'growthspark' ); /* translators: 1: plugin name. */ $this->upgrader->strings['skin_update_successful'] = esc_html__( '%1$s installed successfully.', 'growthspark' ) . ' <a href="#" class="hide-if-no-js" onclick="%2$s"><span>' . esc_html__( 'Show Details', 'growthspark' ) . '</span><span class="hidden">' . esc_html__( 'Hide Details', 'growthspark' ) . '</span>.</a>'; $this->upgrader->strings['skin_upgrade_end'] = __( 'All installations have been completed.', 'growthspark' ); /* translators: 1: plugin name, 2: action number 3: total number of actions. */ $this->upgrader->strings['skin_before_update_header'] = __( 'Installing Plugin %1$s (%2$d/%3$d)', 'growthspark' ); } } } /** * Outputs the header strings and necessary JS before each plugin installation. * * @since 2.2.0 * * @param string $title Unused in this implementation. */ public function before( $title = '' ) { if ( empty( $title ) ) { $title = esc_html( $this->plugin_names[ $this->i ] ); } parent::before( $title ); } /** * Outputs the footer strings and necessary JS after each plugin installation. * * Checks for any errors and outputs them if they exist, else output * success strings. * * @since 2.2.0 * * @param string $title Unused in this implementation. */ public function after( $title = '' ) { if ( empty( $title ) ) { $title = esc_html( $this->plugin_names[ $this->i ] ); } parent::after( $title ); $this->i++; } /** * Outputs links after bulk plugin installation is complete. * * @since 2.2.0 */ public function bulk_footer() { // Serve up the string to say installations (and possibly activations) are complete. parent::bulk_footer(); // Flush plugins cache so we can make sure that the installed plugins list is always up to date. wp_clean_plugins_cache(); $this->tgmpa->show_tgmpa_version(); // Display message based on if all plugins are now active or not. $update_actions = array(); if ( $this->tgmpa->is_tgmpa_complete() ) { // All plugins are active, so we display the complete string and hide the menu to protect users. echo '<style type="text/css">#adminmenu .wp-submenu li.current { display: none !important; }</style>'; $update_actions['dashboard'] = sprintf( esc_html( $this->tgmpa->strings['complete'] ), '<a href="' . esc_url( self_admin_url() ) . '">' . esc_html__( 'Return to the Dashboard', 'growthspark' ) . '</a>' ); } else { $update_actions['tgmpa_page'] = '<a href="' . esc_url( $this->tgmpa->get_tgmpa_url() ) . '" target="_parent">' . esc_html( $this->tgmpa->strings['return'] ) . '</a>'; } /** * Filter the list of action links available following bulk plugin installs/updates. * * @since 2.5.0 * * @param array $update_actions Array of plugin action links. * @param array $plugin_info Array of information for the last-handled plugin. */ $update_actions = apply_filters( 'tgmpa_update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info ); if ( ! empty( $update_actions ) ) { $this->feedback( implode( ' | ', (array) $update_actions ) ); } } /* *********** DEPRECATED METHODS *********** */ /** * Flush header output buffer. * * @since 2.2.0 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead * @see Bulk_Upgrader_Skin::flush_output() */ public function before_flush_output() { _deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' ); $this->flush_output(); } /** * Flush footer output buffer and iterate $this->i to make sure the * installation strings reference the correct plugin. * * @since 2.2.0 * @deprecated 2.5.0 use {@see Bulk_Upgrader_Skin::flush_output()} instead * @see Bulk_Upgrader_Skin::flush_output() */ public function after_flush_output() { _deprecated_function( __FUNCTION__, 'TGMPA 2.5.0', 'Bulk_Upgrader_Skin::flush_output()' ); $this->flush_output(); $this->i++; } } } } } } if ( ! class_exists( 'TGMPA_Utils' ) ) { /** * Generic utilities for TGMPA. * * All methods are static, poor-dev name-spacing class wrapper. * * Class was called TGM_Utils in 2.5.0 but renamed TGMPA_Utils in 2.5.1 as this was conflicting with Soliloquy. * * @since 2.5.0 * * @package TGM-Plugin-Activation * @author Juliette Reinders Folmer */ class TGMPA_Utils { /** * Whether the PHP filter extension is enabled. * * @see http://php.net/book.filter * * @since 2.5.0 * * @static * * @var bool $has_filters True is the extension is enabled. */ public static $has_filters; /** * Wrap an arbitrary string in <em> tags. Meant to be used in combination with array_map(). * * @since 2.5.0 * * @static * * @param string $string Text to be wrapped. * @return string */ public static function wrap_in_em( $string ) { return '<em>' . wp_kses_post( $string ) . '</em>'; } /** * Wrap an arbitrary string in <strong> tags. Meant to be used in combination with array_map(). * * @since 2.5.0 * * @static * * @param string $string Text to be wrapped. * @return string */ public static function wrap_in_strong( $string ) { return '<strong>' . wp_kses_post( $string ) . '</strong>'; } /** * Helper function: Validate a value as boolean * * @since 2.5.0 * * @static * * @param mixed $value Arbitrary value. * @return bool */ public static function validate_bool( $value ) { if ( ! isset( self::$has_filters ) ) { self::$has_filters = extension_loaded( 'filter' ); } if ( self::$has_filters ) { return filter_var( $value, FILTER_VALIDATE_BOOLEAN ); } else { return self::emulate_filter_bool( $value ); } } /** * Helper function: Cast a value to bool * * @since 2.5.0 * * @static * * @param mixed $value Value to cast. * @return bool */ protected static function emulate_filter_bool( $value ) { // @codingStandardsIgnoreStart static $true = array( '1', 'true', 'True', 'TRUE', 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', ); static $false = array( '0', 'false', 'False', 'FALSE', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF', ); // @codingStandardsIgnoreEnd if ( is_bool( $value ) ) { return $value; } elseif ( is_int( $value ) && ( 0 === $value || 1 === $value ) ) { return (bool) $value; } elseif ( ( is_float( $value ) && ! is_nan( $value ) ) && ( (float) 0 === $value || (float) 1 === $value ) ) { return (bool) $value; } elseif ( is_string( $value ) ) { $value = trim( $value ); if ( in_array( $value, $true, true ) ) { return true; } elseif ( in_array( $value, $false, true ) ) { return false; } else { return false; } } return false; } } // End of class TGMPA_Utils } // End of class_exists wrapper
gpl-2.0
miko2u/pukiwiki-plus-i18n
spam.ini.php
190409
<?php // $Id: spam.ini.php,v 1.80 2007/09/24 16:01:00 henoheno Exp $ // Spam-related setting // NOTE FOR ADMINISTRATORS: // // Host selection: // [1] '.example.org' prohibits ALL "example.org"-related FQDN // [2] '*.example.org' prohibits ONLY subdomains and hosts, EXCEPT "www.example.org" // [3] 'example.org' prohibits BOTH "example.org" and "www.example.org" // (Now you know, [1] = [2] + [3]) // // How to write multiple hosts as an group: // 'Group Name' => array('a.example.org', 'b.example.com', 'c.example.net'), // // How to write regular expression: // 'Group Name' => '#^(?:.*\.)?what-you-want\.com$#', // // Guideline to keep group names unique: // - Using capitalized letters, spaces, commas (etc) may suggest you // that probably be a group. // - Unique word examples: // [1] FQDN // [2] Mail address of the domain-name owner // [3] IP address, if these hosts have the same ones // [4] Something unique idea of you // // Reference: // http://en.wikipedia.org/wiki/Spamdexing // http://en.wikipedia.org/wiki/Domainers // http://en.wikipedia.org/wiki/Typosquatting // -------------------------------------------------- // List of the lists // FALSE = ignore them // TRUE = catch them // Commented out of the line = do nothing about it // 'pre': Before the other filters/checkers $blocklist['pre'] = array( 'goodhost' => FALSE, ); // 'list': Normal list $blocklist['list'] = array( 'A-1' => TRUE, // General redirection services //'A-2' => TRUE, // Dynamic DNS, Dynamic IP services, ... 'B-1' => TRUE, // Web spaces 'B-2' => TRUE, // Jacked contents, something implanted 'C' => TRUE, // Exclusive spam domains //'D' => TRUE, // "Third party in good faith"s 'E' => TRUE, // Affiliates, Hypes, Catalog retailers, Multi-level marketings, ... 'Z' => TRUE, // Yours ); // -------------------------------------------------- $blocklist['goodhost'] = array( // Sample setting of ignorance list 'IANA-examples' => '#^(?:.*\.)?example\.(?:com|net|org)$#', // PukiWiki-official/dev specific //'pukiwiki.sourceforge.jp', //'pukiwiki.org', // Temporary //'.logue.tk', // Well-known PukiWiki heavy user, Logue (Paid *.tk domain, Expire on 2008-12-01) //'.nyaa.tk', // (Paid *.tk domain, Expire on 2008-05-19) //'.wanwan.tk', // (Paid *.tk domain, Expire on 2008-04-21) by nyaa.tk //'emasaka.blog65.fc2.com', // Text-to-Impress converter //'ifastnet.com', // Server hosting //'threefortune.ifastnet.com', // Server hosting // Yours //'' //'' //'' ); // -------------------------------------------------- // A: Sample setting of // Existing URI redirection or masking services $blocklist['A-1'] = array( // A-1: General redirection services -- by HTML meta, HTML frame, JavaScript, // web-based proxy, DNS subdomains, etc // http://en.wikipedia.org/wiki/URL_redirection // // as known as cheap URI obscuring services today, // for spammers and affiliate users dazed by money. // // Messages from forerunners: // o-rly.net // "A URL REDIRECTION SERVICE GONE BAD" // "SORRY, TRULY" // smcurl.com // "Idiots were using smcURL to shrink URLs and // send them out via spam." // tinyclick.com // "...stop offering it's free services because // too many people were taking advantage of it" // xjs.org // "We have been forced to close this facility // due to a minority of knuckle draggers who // abused this web site." // // Please notify us about this list with reason: // http://pukiwiki.sourceforge.jp/dev/?BugTrack2/207 // '0nz.org', '0rz.tw', '0url.com', '0zed.info', '*.110mb.com', // by Speed Success, Inc. (110mb.server at gmail.com) '123.que.jp', '12url.org', '*.15h.com', '*.1dr.biz', '1K.pl' => array( '*.1k.pl', '*.5g.pl', '*.orq.pl', ), '1nk.us', '1url.org', '1url.in', '1webspace.org', '2Ch.net' => array( 'ime.nu', 'ime.st', ), '2ch2.net', '2hop4.com', '2s.ca', '2site.com', '2url.org', '301url.com', '32url.com', '.3dg.de', '*.4bb.ru', 'big5.51job.com', ///gate/big5/ '5jp.net', '.6url.com', '*.6x.to', '7ref.com', '82m.org', '*.8rf.com', '98.to', 'abbrv.co.uk', '*.abwb.org', 'acnw.de', 'Active.ws' => array( '*.321.cn', '*.4x2.net', 'active.ws', '*.better.ws', '*.here.ws', '*.mypiece.com', '*.official.ws', '*.ouch.ws', '*.premium.ws', '*.such.info', '*.true.ws', '*.visit.ws', ), 'affilitool.com', // 125.206.117.91(right-way.org) by noboru hamada (info at isosupport.net) 'aifam.com', 'All4WebMasters.pl' => array( '*.ovp.pl', '*.6-6-6.pl', ), 'amoo.org', 'web.archive.org', ///web/2 'Arzy.net' => array( // "(c) 2007 www.arzy.net", by urladmin at zvxr.com, DNS arzy.net 'jmp2.net', '2me.tw', ), 'ataja.es', 'ATBHost.com' => array( '*.atbhost.com', '*.bzhost.net', ), 'atk.jp', 'clearp.ath.cx', 'athomebiz.com', 'aukcje1.pl', 'beam.to', 'beermapping.com', 'besturl.in', 'bhomiyo.com', ///en.xliterate/ 64.209.134.9(web137.discountasp.net) by piyush at arborindia.com 'biglnk.com', 'bingr.com', 'bittyurl.com', '*.bizz.cc', '*.blo.pl', '*.bo.pl', 'briefurl.com', 'brokenscript.com', 'BucksoGen.com' => array( '*.bucksogen.com', '*.bulochka.org', '*.korzhik.org', '*.kovrizhka.org', '*.pirozhok.org', '*.plushka.org', '*.pryanik.org', '*.sushka.org', ), 'budgethosts.org', 'budu.com', // by peter.eder at imcworld.com '*.buzznet.com', '*.bydl.com', 'C-O.IN' => array( '*.c-o.cc', '*.c-o.in', '*.coz.in', '*.cq.bz', ), 'c64.ch', 'c711.com', '*.cej.pl', 'checkasite.net', 'url.chefhost.com', '*.chicappa.jp', 'chilicity.com', 'big5.china.com', ///gate/big5/ 'chopurl.com', 'christopherleestreet.com', 'cintcm.com', '*.cjb.net', 'clipurl.com', '*.co.nr', 'Comtech Enterprises ' => array( // comteche.com 'tinyurl.name', 'tinyurl.us', ), 'Cool168.com' => array( '*.cool158.com', '*.cool168.com', '*.ko168.com', '*.ko188.com', ), 'Coolurl.de' => array( 'coolurl.de', 'dornenboy.de', 'eyeqweb.com', 'hardcore-porn.de', 'maschinen-bluten-nicht.de', ), 'cutalink.com', '*.da.cx', '*.da.ru', 'dae2.com', 'dephine.org', 'desiurl.com', 'dhurl.com', 'digbig.com', 'Digipills.com' => array( '*.digipills.com', 'minilien.com', 'tinylink.com', ), '*.discutbb.com', 'DL.AM' => array( '*.cx.la', '*.dl.am', ), '*.dl.pl', '*.dmdns.com', 'doiop.com', 'drlinky.com', 'durl.us', '*.dvdonly.ru', '*.dynu.ca', 'dwarf.name', '*.eadf.com', '*.easyurl.net', 'easyurl.jp', // 124.38.169.39(*.ap124.ftth.ucom.ne.jp), e-mail:info at value-domain.com, // says "by ascentnet.co.jp". http://www.ascentnet.co.jp/press/?type=1&press=45 // This service seems to be opened at 2007/08/23 with "beta" sign. // easyurl.jp clearly point ascentnet.co.jp's 10 local rules: // "Keep continuing to seek originality and contribute it to local, // get/grow niche brands (in local), believe (local) people knows the answer, // observe (local) rule, create nothing to infringe (local) rule, keep 70% of // engeneers, and ..." http://www.ascentnet.co.jp/about/about_01.html // I'm so much impressed of the situation around this imported one today. 'elfurl.com', 'eny.pl', 'eTechFocus LLC' => array( // by eTechFocus LLC (thomask at etechfocus.com) '.mywiitime.com', '.surfindark.com', // webmaster at etechfocus.com '.surfinshade.com', '.surfinshadow.com', '.surfinwind.com', '.topsecretlive.com', ), '*.eu.org', 'F2B.be' => array( '*.f2b.be', '*.freakz.eu', '*.n0.be', '*.n3t.nl', '*.short.be', '*.ssr.be', '*.tweaker.eu', ), '*.fancyurl.com', 'Fanznet.jp' => array( // by takahashi nakaba (nakaba.takahashi at gmail.com) 'blue11.jp', 'fanznet.com', 'katou.in', 'mymap.in', 'saitou.in', 'satou.in', 'susan.in', ), '.fe.pl', // Redirection and subdomain 'ffwd.to', 'url.fibiger.org', 'FireMe.to' => array( 'fireme.to', 'nextdoor.to', 'ontheway.to', ), 'flingk.com', 'flog.jp', // careless redirector and bbs 'fm7.biz', 'fnbi.jp', '*.fnbi.jp', 'forgeturl.com', '*.free.bg', 'Freeservers.com' => array( // United Online Web Services, Inc. '*.4mg.com', '*.4t.com', '*.8m.com', '*.8m.net', '*.8k.com', '*.faithweb.com', '*.freehosting.net', '*.freeservers.com', '*.gq.nu', '*.htmlplanet.com', '*.itgo.com', '*.iwarp.com', '*.s5.com', '*.scriptmania.com', '*.tvheaven.com', ), '*.freewebpages.com', 'FreeWebServices.net' => array( // Host Department LLC '*.about.gs', // Dead? '*.about.tc', '*.about.vg', '*.aboutus.gs', '*.aboutus.ms', '*.aboutus.tc', '*.aboutus.vg', '*.biografi.biz', '*.biografi.info', '*.biografi.org', '*.biografi.us', '*.datadiri.biz', '*.datadiri.cc', '*.datadiri.com', '*.datadiri.info', '*.datadiri.net', '*.datadiri.org', '*.datadiri.tv', '*.datadiri.us', '*.ecv.gs', '*.ecv.ms', '*.ecv.tc', '*.ecv.vg', '*.eprofile.us', '*.go2net.ws', '*.hits.io', '*.hostingweb.us', '*.hub.io', '*.indo.bz', '*.indo.cc', '*.indo.gs', '*.indo.ms', '*.indo.tc', '*.indo.vg', '*.infinitehosting.net', '*.infinites.net', '*.lan.io', '*.max.io', '*.mycv.bz', '*.mycv.nu', '*.mycv.tv', '*.myweb.io', '*.ourprofile.biz', '*.ourprofile.info', '*.ourprofile.net', // Dead? '*.ourprofile.org', '*.ourprofile.us', '*.profil.bz', '*.profil.cc', '*.profil.cn', '*.profil.gs', '*.profil.in', '*.profil.ms', '*.profil.tc', '*.profil.tv', '*.profil.vg', // ? '*.site.io', '*.wan.io', '*.web-cam.ws', '*.webs.io', '*.zip.io', ), 'funkurl.com', // by Leonard Lyle (len at ballandchain.net) '*.fx.to', 'fyad.org', 'fype.com', 'gentleurl.net', 'Get2.us' => array( '*.get2.us', '*.hasballs.com', '*.ismyidol.com', '*.spotted.us', '*.went2.us', '*.wentto.us', ), 'glinki.com', '*.globalredirect.com', 'gnu.vu', '*.go.cc', //'Google.com' => array( // google.com/translate_c\?u=(?:http://)? //), 'goonlink.com', '.gourl.org', '.greatitem.com', 'gzurl.com', 'url.grillsportverein.de', 'Harudake.net' => array('*.hyu.jp'), 'Hattinger Linux User Group' => array('short.hatlug.de'), 'Hexten.net' => array('lyxus.net'), 'here.is', 'HispaVista.com' => array( '*.blogdiario.com', '*.hispavista.com', '.galeon.com', ), 'Home.pl' => array( // by Home.pl Sp. J. (info at home.pl), redirections and forums '*.8l.pl', '*.blg.pl', '*.czytajto.pl', '*.ryj.pl', '*.xit.pl', '*.xlc.pl', '*.hk.pl', '*.home.pl', '*.of.pl', ), 'hort.net', 'free4.hostrocket.com', '*.hotindex.ru', 'HotRedirect.com' => array( '*.coolhere.com', '*.homepagehere.com', '*.hothere.com', '*.mustbehere.com', '*.onlyhere.net', '*.pagehere.com', '*.surfhere.net', '*.zonehere.com', ), 'hotshorturl.com', 'hotwebcomics.com', ///search_redirect.php 'hurl.to', '*.hux.de', '*.i89.us', 'iat.net', // 74.208.58.130 by Tony Carter 'ibm.com', ///links (Correct it) '*.iceglow.com', 'go.id-tv.info', // 77.232.68.138(77-232-68-138.static.servage.net) by Max Million (max at id-tv.info) 'Ideas para Nuevos Mercados SL' => array( // NOTE: 'i4nm.com' by 'Ideas para Nuevos Mercados SL' (i4nm at i4nm.com) // NOTE: 'dominiosfree.com' by 'Ideas para nuevos mercados,sl' (dominiosfree at i4nm.com) // NOTE: 'red-es.com' by oscar florez (info at i4nm.com) // by edgar bortolin (oscar at i4nm.com) // by Edgar Bortolin (oscar at i4nm.com) // by oscar florez (oscar at i4nm.com) // by Oscar Florez (oscar at red-es.com) // by covadonga del valle (oscar at i4nm.com) '*.ar.gd', '*.ar.gs', // ns *.nora.net '*.ar.kz', // by oscar '*.ar.nu', // by Edgar '*.ar.tc', // by oscar '*.ar.vg', // by oscar '*.bo.kz', // by oscar '*.bo.nu', // by covadonga '*.bo.tc', // by oscar '*.bo.tf', // by Oscar '*.bo.vg', // by oscar '*.br.gd', '*.br.gs', // ns *.nora.net '*.br.nu', // by edgar '*.br.vg', // by oscar '*.ca.gs', // by oscar '*.ca.kz', // by oscar '*.cl.gd', // by oscar '*.cl.kz', // by oscar '*.cl.nu', // by edgar '*.cl.tc', // by oscar '*.cl.tf', // by Oscar '*.cl.vg', // by oscar '*.col.nu', // by Edgar '*.cr.gs', // ns *.nora.net '*.cr.kz', // by oscar '*.cr.nu', // by edgar '*.cr.tc', // by oscar '*.cu.tc', // by oscar '*.do.kz', // by oscar '*.do.nu', // by edgar '*.ec.kz', // by edgar '*.ec.nu', // by Edgar '*.ec.tf', // by Oscar '*.es.kz', // by oscar '*.eu.kz', // by oscar '*.gt.gs', // ns *.nora.net '*.gt.tc', // by oscar '*.gt.tf', // by Oscar '*.gt.vg', // by Oscar '*.hn.gs', // ns *.nora.net '*.hn.tc', // by oscar '*.hn.tf', // by Oscar '*.hn.vg', // by oscar '*.mx.gd', '*.mx.gs', // ns *.nora.net '*.mx.kz', // by oscar '*.mx.vg', // by oscar '*.ni.kz', // by oscar '*.pa.kz', // by oscar '*.pe.kz', // by oscar '*.pe.nu', // by Edgar '*.pr.kz', // by oscar '*.pr.nu', // by edgar '*.pt.gs', // ns *.nora.net '*.pt.kz', // by edgar '*.pt.nu', // by edgar '*.pt.tc', // by oscar '*.pt.tf', // by Oscar '*.py.gs', // ns *.nora.net '*.py.nu', // by edgar '*.py.tc', // by oscar '*.py.tf', // by Oscar '*.py.vg', // by oscar '*.sv.tc', // by oscar '*.usa.gs', // ns *.nora.net '*.uy.gs', // ns *.nora.net '*.uy.kz', // by oscar '*.uy.nu', // by edgar '*.uy.tc', // by oscar '*.uy.tf', // by Oscar '*.uy.vg', // by oscar '*.ve.gs', // by oscar '*.ve.tc', // by oscar '*.ve.tf', // by Oscar '*.ve.vg', // by oscar '*.ven.nu', // by edgar ), 'ie.to', 'igoto.co.uk', 'ilook.tw', 'indianpad.com', ///view/ 'iNetwork.co.il' => array( 'inetwork.co.il', // by NiL HeMo (exe at bezeqint.net) '.up2.co.il', // inetwork.co.il related, not classifiable, by roey blumshtein (roeyb76 at 017.net.il) '.dcn.co.il,', // up2.co.il related, not classifiable, by daniel chechik (ns_daniel0 at bezeqint.net) ), '*.infogami.com', 'infotop.jp', 'ipoo.org', 'IR.pl' => array( '*.aj.pl', '*.aliasy.org', '*.gu.pl', '*.hu.pl', '*.ir.pl', '*.jo.pl', '*.su.pl', '*.td.pl', '*.uk.pl', '*.uy.pl', '*.xa.pl', '*.zj.pl', ), 'irotator.com', '.iwebtool.com', 'j6.bz', 'jeeee.net', 'Jaze Redirect Services' => array( '*.arecool.net', '*.iscool.net', '*.isfun.net', '*.tux.nu', ), '*.jed.pl', 'JeremyJohnstone.com' => array('url.vg'), 'jemurl.com', 'jggj.net', 'jpan.jp', 'josh.nu', 'kat.cc', 'Kickme.to' => array( '.1024bit.at', '.128bit.at', '.16bit.at', '.256bit.at', '.32bit.at', '.512bit.at', '.64bit.at', '.8bit.at', '.adores.it', '.again.at', '.allday.at', '.alone.at', '.altair.at', '.american.at', '.amiga500.at', '.ammo.at', '.amplifier.at', '.amstrad.at', '.anglican.at', '.angry.at', '.around.at', '.arrange.at', '.australian.at', '.baptist.at', '.basque.at', '.battle.at', '.bazooka.at', '.berber.at', '.blackhole.at', '.booze.at', '.bosnian.at', '.brainiac.at', '.brazilian.at', '.bummer.at', '.burn.at', '.c-64.at', '.catalonian.at', '.catholic.at', '.chapel.at', '.chills.it', '.christiandemocrats.at', '.cname.at', '.colors.at', '.commodore.at', '.commodore64.at', '.communists.at', '.conservatives.at', '.conspiracy.at', '.cooldude.at', '.craves.it', '.croatian.at', '.cuteboy.at', '.dancemix.at', '.danceparty.at', '.dances.it', '.danish.at', '.dealing.at', '.deep.at', '.democrats.at', '.digs.it', '.divxlinks.at', '.divxmovies.at', '.divxstuff.at', '.dizzy.at', '.does.it', '.dork.at', '.drives.it', '.dutch.at', '.dvdlinks.at', '.dvdmovies.at', '.dvdstuff.at', '.emulators.at', '.end.at', '.english.at', '.eniac.at', '.error403.at', '.error404.at', '.evangelism.at', '.exhibitionist.at', '.faith.at', '.fight.at', '.finish.at', '.finnish.at', '.forward.at', '.freebie.at', '.freemp3.at', '.french.at', '.graduatejobs.at', '.greenparty.at', '.grunge.at', '.hacked.at', '.hang.at', '.hangup.at', '.has.it', '.hide.at', '.hindu.at', '.htmlpage.at', '.hungarian.at', '.icelandic.at', '.independents.at', '.invisible.at', '.is-chillin.it', '.is-groovin.it', '.japanese.at', '.jive.at', '.kickass.at', '.kickme.to', '.kindergarden.at', '.knows.it', '.kurd.at', '.labour.at', '.leech.at', '.liberals.at', '.linuxserver.at', '.liqour.at', '.lovez.it', '.makes.it', '.maxed.at', '.means.it', '.meltdown.at', '.methodist.at', '.microcomputers.at', '.mingle.at', '.mirror.at', '.moan.at', '.mormons.at', '.musicmix.at', '.nationalists.at', '.needz.it', '.nerds.at', '.neuromancer.at', '.newbie.at', '.nicepage.at', '.ninja.at', '.norwegian.at', '.ntserver.at', '.owns.it', '.paint.at', '.palestinian.at', '.phoneme.at', '.phreaking.at', '.playz.it', '.polish.at', '.popmusic.at', '.portuguese.at', '.powermac.at', '.processor.at', '.prospects.at', '.protestant.at', '.rapmusic.at', '.raveparty.at', '.reachme.at', '.reads.it', '.reboot.at', '.relaxed.at', '.republicans.at', '.researcher.at', '.reset.at', '.resolve.at', '.retrocomputers.at', '.rockparty.at', '.rocks.it', '.rollover.at', '.rough.at', '.rules.it', '.rumble.at', '.russian.at', '.says.it', '.scared.at', '.seikh.at', '.serbian.at', '.short.as', '.shows.it', '.silence.at', '.simpler.at', '.sinclair.at', '.singz.it', '.slowdown.at', '.socialists.at', '.spanish.at', '.split.at', '.stand.at', '.stoned.at', '.stumble.at', '.supercomputer.at', '.surfs.it', '.swedish.at', '.swims.it', '.synagogue.at', '.syntax.at', '.syntaxerror.at', '.techie.at', '.temple.at', '.thinkbig.at', '.thirsty.at', '.throw.at', '.toplist.at', '.trekkie.at', '.trouble.at', '.turkish.at', '.unexplained.at', '.unixserver.at', '.vegetarian.at', '.venture.at', '.verycool.at', '.vic-20.at', '.viewing.at', '.vintagecomputers.at', '.virii.at', '.vodka.at', '.wannabe.at', '.webpagedesign.at', '.wheels.at', '.whisper.at', '.whiz.at', '.wonderful.at', '.zor.org', '.zx80.at', '.zx81.at', '.zxspectrum.at', ), 'kisaweb.com', 'krotki.pl', 'kuerzer.de', '*.kupisz.pl', 'kuso.cc', '*.l8t.com', 'lame.name', 'lediga.st', 'liencourt.com', 'liteurl.com', 'linkachi.com', 'linkezy.com', 'linkfrog.net', 'linkook.com', 'linkzip.net', 'lispurl.com', 'lnk.in', 'makeashorterlink.com', 'MAX.ST' => array( // by Guet Olivier (oliguet at club-internet.fr), frame '*.3gp.fr', '*.gtx.fr', '*.ici.st', '*.max.st', '*.nn.cx', // ns *.sivit.org '*.site.cx', // ns *.sivit.org '*.user.fr', '*.zxr.fr', ), 'mcturl.com', 'memurl.com', 'Metamark.net' => array('xrl.us'), 'midgeturl.com', 'Minilink.org' => array('lnk.nu'), 'miniurl.org', 'miniurl.pl', 'mixi.bz', 'mo-v.jp', 'MoldData.md' => array( // Note: Some parts of '.md' ccTLD '.com.md', '.co.md', '.org.md', '.info.md', '.host.md', ), 'monster-submit.com', 'mooo.jp', 'murl.net', 'myactivesurf.net', 'mytinylink.com', 'myurl.in', 'myurl.com.tw', 'nanoref.com', 'Ne1.net' => array( '*.ne1.net', '*.r8.org', ), 'Nashville Linux Users Group' => array('nlug.org'), 'not2long.net', '*.notlong.com', '*.nuv.pl', 'ofzo.be', '*.ontheinter.net', 'ourl.org', 'ov2.net', // frame '*.ozonez.com', 'pagebang.com', 'palurl.com', '*.paulding.net', 'phpfaber.org', 'pnope.com', 'prettylink.com', 'PROXID.net' => array( // also xRelay.net '*.asso.ws', '*.corp.st', '*.euro.tm', '*.perso.tc', '*.site.tc', '*.societe.st', ), 'qrl.jp', 'qurl.net', 'qwer.org', 'readthisurl.com', // 67.15.58.36(win2k3.tuserver.com) by Zhe Hong Lim (zhehonglim at gmail.com) 'radiobase.net', 'Rakuten.co.jp' => array( 'pt.afl.rakuten.co.jp', ///c/ ), 'RedirectFree.com' => array( '*.red.tc', '*.redirectfree.com', '*.sky.tc', '*.the.vg', ), 'redirme.com', 'redirectme.to', 'relic.net', 'rezma.info', 'rio.st', 'rlink.org', '*.rmcinfo.fr', 'rubyurl.com', '*.runboard.com', 'runurl.com', 's-url.net', 's1u.net', 'SG5.co.uk' => array( '*.sg5.co.uk', '*.sg5.info', ), 'Shim.net' => array( '*.0kn.com', '*.2cd.net', '*.freebiefinders.net', '*.freegaming.org', '*.op7.net', '*.shim.net', '*.v9z.com', ), 'big5.shippingchina.com', 'shorl.com', 'shortenurl.com', 'shorterlink.com', 'shortlinks.co.uk', 'shorttext.com', 'shorturl-accessanalyzer.com', 'Shortify.com' => array( '74678439.com', 'shortify.com', ), 'shortlink.co.uk', 'ShortURL.com' => array( '*.1sta.com', '*.24ex.com', '*.2fear.com', '*.2fortune.com', '*.2freedom.com', '*.2hell.com', '*.2savvy.com', '*.2truth.com', '*.2tunes.com', '*.2ya.com', '*.alturl.com', '*.antiblog.com', '*.bigbig.com', '*.dealtap.com', '*.ebored.com', '*.echoz.com', '*.filetap.com', '*.funurl.com', '*.headplug.com', '*.hereweb.com', '*.hitart.com', '*.mirrorz.com', '*.shorturl.com', '*.spyw.com', '*.vze.com', ), 'shrinkalink.com', 'shrinkthatlink.com', 'shrinkurl.us', 'shrt.org', 'shrunkurl.com', 'shurl.org', 'shurl.net', 'sid.to', 'simurl.com', 'sitefwd.com', 'Sitelutions.com' => array( '*.assexy.as', '*.athersite.com', '*.athissite.com', '*.bestdeals.at', '*.byinter.net', '*.findhere.org', '*.fw.nu', '*.isgre.at', '*.isthebe.st', '*.kwik.to', '*.lookin.at', '*.lowestprices.at', '*.onthenet.as', '*.ontheweb.nu', '*.pass.as', '*.passingg.as', '*.redirect.hm', '*.rr.nu', '*.ugly.as', ), '*.skracaj.pl', 'skiltechurl.com', 'skocz.pl', 'slimurl.jp', 'slink.in', 'smallurl.eu', 'smurl.name', 'snipurl.com', 'sp-nov.net', 'splashblog.com', 'spod.cx', '*.spydar.com', 'Subdomain.gr' => array( '*.p2p.gr', '*.subdomain.gr', ), 'SURL.DK' => array('surl.dk'), // main page is: s-url.dk 'surl.se', 'surl.ws', 'symy.jp', 'tdurl.com', 'tighturl.com', 'tiniuri.com', 'tiny.cc', 'tiny.pl', 'tiny2go.com', 'tinylink.eu', 'tinylinkworld.com', 'tinypic.com', 'tinyr.us', 'TinyURL.com' => array( 'tinyurl.com', 'preview.tinyurl.com', 'tinyurl.co.uk', ), 'titlien.com', '*.tlg.pl', 'tlurl.com', 'link.toolbot.com', 'tnij.org', 'Tokelau ccTLD' => array('.tk'), 'toila.net', '*.toolbot.com', '*.torontonian.com', 'trimurl.com', 'ttu.cc', 'turl.jp', '*.tz4.com', 'U.TO' => array( // ns *.1004web.com, 1004web.com is owned by Moon Jae Bark (utomaster at gmail.com) = u.to master '*.1.to', '*.4.to', '*.5.to', '*.82.to', '*.s.to', '*.u.to', '*.ce.to', '*.cz.to', '*.if.to', '*.it.to', '*.kp.to', '*.ne.to', '*.ok.to', '*.pc.to', '*.tv.to', '*.dd.to', '*.ee.to', '*.hh.to', '*.kk.to', '*.mm.to', '*.qq.to', '*.xx.to', '*.zz.to', '*.ivy.to', '*.joa.to', '*.ever.to', '*.mini.to', ), 'uchinoko.in', 'Ulimit.com' => array( '*.be.tf', '*.best.cd', '*.bsd-fan.com', '*.c0m.st', '*.ca.tc', '*.clan.st', '*.com02.com', '*.en.st', '*.euro.st', '*.fr.fm', '*.fr.st', '*.fr.vu', '*.gr.st', '*.ht.st', '*.int.ms', '*.it.st', '*.java-fan.com', '*.linux-fan.com', '*.mac-fan.com', '*.mp3.ms', '*.qc.tc', '*.sp.st', '*.suisse.st', '*.t2u.com', '*.unixlover.com', '*.zik.mu', ), '*.uni.cc', 'UNONIC.com' => array( '*.at.tf', // AlpenNIC '*.bg.tf', '*.ca.tf', '*.ch.tf', // AlpenNIC '*.cz.tf', '*.de.tf', // AlpenNIC '*.edu.tf', '*.eu.tf', '*.int.tf', '*.net.tf', '*.pl.tf', '*.ru.tf', '*.sg.tf', '*.us.tf', ), 'Up.pl' => array( '.69.pl', // by nsk101869 '.crack.pl', // by nsk101869 '.film.pl', // by sibr19002 '.h2o.pl', // by nsk101869 '.hostessy.pl', // by nsk101869 '.komis.pl', // by nsk101869 '.laski.pl', // by nsk101869 '.modelki.pl', // by nsk101869 '.muzyka.pl', // by sibr19002 '.nastolatki.pl', // by nsk101869 '.obuwie.pl', // by nsk101869 '.prezes.com', // by Robert e (b2b at interia.pl) '.prokuratura.com', // by Robert Tofil (b2b at interia.pl) '.sexchat.pl', // by nsk101869 '.sexlive.pl', // by nsk101869 '.tv.pl', // by nsk101869 '.up.pl', // by nsk101869 '.video.pl', // by nsk101869 '.xp.pl', // nsk101869 ), '*.uploadr.com', 'url.ie', 'url4.net', 'url-c.com', 'urlbee.com', 'urlbounce.com', 'urlcut.com', 'urlcutter.com', 'urlic.com', 'urlin.it', 'urlkick.com', 'URLLogs.com' => array( '*.urllogs.com', // 67.15.219.253 by Javier Keeth (abuzant at gmail.com), ns *.pengs.com, 'Hosted by: Gossimer' '.12w.net', // 67.15.219.253 by Marvin Dreyer (marvin.dreyer at pengs.com), ns *.gossimer.com ), '*.urlproxy.com', 'urlser.com', 'urlsnip.com', 'urlzip.de', 'urlx.org', 'useurl.us', // by Edward Beauchamp (mail at ebvk.com) 'utun.jp', 'uxxy.com', '*.v27.net', 'V3.com by FortuneCity.com' => array( // http://www.v3.com/sub-domain-list.shtml '*.all.at', '*.back.to', '*.beam.at', '*.been.at', '*.bite.to', '*.board.to', '*.bounce.to', '*.bowl.to', '*.break.at', '*.browse.to', '*.change.to', '*.chip.ms', '*.connect.to', '*.crash.to', '*.cut.by', '*.direct.at', '*.dive.to', '*.drink.to', '*.drive.to', '*.drop.to', '*.easy.to', '*.everything.at', '*.fade.to', '*.fanclub.ms', '*.firstpage.de', '*.fly.to', '*.flying.to', '*.fortunecity.co.uk', '*.fortunecity.com', '*.forward.to', '*.fullspeed.to', '*.fun.ms', '*.gameday.de', '*.germany.ms', '*.get.to', '*.getit.at', '*.hard-ware.de', '*.hello.to', '*.hey.to', '*.hop.to', '*.how.to', '*.hp.ms', '*.jump.to', '*.kiss.to', '*.listen.to', '*.mediasite.de', '*.megapage.de', '*.messages.to', '*.mine.at', '*.more.at', '*.more.by', '*.move.to', '*.musicpage.de', '*.mypage.org', '*.mysite.de', '*.nav.to', '*.notrix.at', '*.notrix.ch', '*.notrix.de', '*.notrix.net', '*.on.to', '*.page.to', '*.pagina.de', '*.played.by', '*.playsite.de', '*.privat.ms', '*.quickly.to', '*.redirect.to', '*.rulestheweb.com', '*.run.to', '*.scroll.to', '*.seite.ms', '*.shortcut.to', '*.skip.to snap.to', '*.soft-ware.de', '*.start.at', '*.stick.by', '*.surf.to', '*.switch.to', '*.talk.to', '*.tip.nu', '*.top.ms', '*.transfer.to', '*.travel.to', '*.turn.to', '*.vacations.to', '*.videopage.de', '*.virtualpage.de', '*.w3.to', '*.walk.to', '*.warp9.to', '*.window.to', '*.yours.at', '*.zap.to', '*.zip.to', ), 'VDirect.com' => array( '*.emailme.net', '*.getto.net', '*.inetgames.com', '*.netbounce.com', '*.netbounce.net', '*.oneaddress.net', '*.snapto.net', '*.vdirect.com', '*.vdirect.net', '*.webrally.net', ), 'venturenetworking.com', // by Katharine Barbieri (domains at spyforce.com) 'vgo2.com', 'Voila.fr' => array('r.voila.fr'), // Fix it 'w3t.org', 'wapurl.co.uk', 'Wb.st' => array( '*.team.st', '*.wb.st', ), 'wbkt.net', 'WebAlias.com' => array( '*.andmuchmore.com', '*.browser.to', '*.escape.to', '*.fornovices.com', '*.fun.to', '*.got.to', '*.hottestpix.com', '*.imegastores.com', '*.latest-info.com', '*.learn.to', '*.moviefever.com', '*.mp3-archives.com', '*.myprivateidaho.com', '*.radpages.com', '*.remember.to', '*.resourcez.com', '*.return.to', '*.sail.to', '*.sports-reports.com', '*.stop.to', '*.thrill.to', '*.tophonors.com', '*.uncutuncensored.com', '*.up.to', '*.veryweird.com', '*.way.to', '*.web-freebies.com', '.webalias.com', '*.webdare.com', '*.xxx-posed.com', ), 'webmasterwise.com', 'witherst at hotmail.com' => array( // by Tim Withers '*.associates-program.com', '*.casinogopher.com', '*.ezpagez.com', '*.vgfaqs.com', ), 'wittylink.com', 'wiz.sc', // tiny.cc related 'X50.us' => array( '*.i50.de', '*.x50.us', ), 'big5.xinhuanet.com', ///gate/big5/ 'xhref.com', 'Xn6.net' => array( '*.9ax.net', '*.xn6.net', ), '*.xshorturl.com', // by Markus Lee (soul_s at list.ru) '.y11.net', 'YESNS.com' => array( // by Jae-Hwan Kwon (kwonjhpd at kornet.net) '*.yesns.com', '*.srv4u.net', //blogne.com ), 'yatuc.com', 'yep.it', 'yumlum.com', 'yurel.com', 'Z.la' => array( 'z.la', 't.z.la', ), 'zaable.com', 'zapurl.com', 'zarr.co.uk', 'zerourl.com', 'ZeroWeb.org' => array( '*.80t.com', '*.firez.org', '*.fizz.nu', '*.ingame.org', '*.irio.net', '*.v33.org', '*.zeroweb.org', ), 'zhukcity.ru', 'zippedurl.com', 'zr5.us', '*.zs.pl', '*.zu5.net', 'zuso.tw', '*.zwap.to', ); // -------------------------------------------------- $blocklist['A-2'] = array( // A-2: Dynamic DNS, Dynamic IP services, DNS vulnerabilities, or another DNS cases // //'*.dyndns.*', // Wildcard for dyndns // '*.ddo.jp', // by Kiyoshi Furukawa (furu at furu.jp) 'ddns.ru' => array('*.bpa.nu'), 'Dhs.org' => array( '*.2y.net', '*.dhs.org', ), '*.dnip.net', '*.dyndns.co.za', '*.dyndns.dk', '*.dyndns.nemox.net', 'DyDNS.com' => array( '*.ath.cx', '*.dnsalias.org', '*.dyndns.org', '*.homeip.net', '*.homelinux.net', '*.mine.nu', '*.shacknet.nu', ), '*.dtdns.net', // by jscott at sceiron.com '*.dynu.com', '*.dynup.net', '*.fdns.net', 'J-Speed.net' => array( '*.bne.jp', '*.ii2.cc', '*.jdyn.cc', '*.jspeed.jp', ), '*.mydyn.de', '*.nerdcamp.net', 'No-IP.com' => array( '*.bounceme.net', '*.hopto.org', '*.myftp.biz', '*.myftp.org', '*.myvnc.com', '*.no-ip.biz', '*.no-ip.info', '*.no-ip.org', '*.redirectme.net', '*.servebeer.com', '*.serveblog.net', '*.servecounterstrike.com', '*.serveftp.com', '*.servegame.com', '*.servehalflife.com', '*.servehttp.com', '*.servemp3.com', '*.servepics.com', '*.servequake.com', '*.sytes.net', '*.zapto.org', ), '*.opendns.be', 'Yi.org' => array( // by dns at whyi.org '*.yi.org', // 64.15.155.86(susicivus.crackerjack.net) // 72.55.129.46(redirect.yi.org) '*.whyi.org', '*.weedns.com', ), '*.zenno.info', '.cm', // 'Cameroon' ccTLD, sometimes used as typo of '.com', // and all non-recorded domains redirect to 'agoga.com' now // http://money.cnn.com/magazines/business2/business2_archive/2007/06/01/100050989/index.htm // http://agoga.com/aboutus.html ); // -------------------------------------------------- // B: Sample setting of: // Jacked (taken advantage of) and cleaning-less sites // // Please notify us about this list with reason: // http://pukiwiki.sourceforge.jp/dev/?BugTrack2%2F208 $blocklist['B-1'] = array( // B-1: Web spaces // // Messages from forerunners: // activefreehost.com // "We regret to inform you that ActiveFreeHost // free hosting service has is now closed (as of // September 18). We have been online for over // two and half years, but have recently decided // to take time for software improvement to fight // with server abuse, Spam advertisement and // fraud." // '*.0000host.com', // 68.178.200.154, ns *.3-hosting.net '*.007ihost.com', // 195.242.99.199(s199.softwarelibre.nl) '*.00bp.com', // 74.86.20.224(layeredpanel.com -> 195.242.99.195) by admin at 1kay.com '0Catch.com related' => array( '*.0catch.com', // 209.63.57.4 by Sam Parkinson (sam at 0catch.com), also zerocatch.com // 209.63.57.10(www1.0catch.com) by dan at 0catch.com, ns *.0catch.com '*.100freemb.com', // by Danny Ashworth '*.exactpages.com', '*.fcpages.com', '*.wtcsites.com', // 209.63.57.10(www1.0catch.com) by domains at netgears.com, ns *.0catch.com '*.741.com', '*.freecities.com', '*.freesite.org', '*.freewebpages.org', '*.freewebsitehosting.com', '*.jvl.com', // 209.63.57.10(www1.0catch.com) by luke at dcpages.com, ns *.0catch.com '*.freespaceusa.com', '*.usafreespace.com', // 209.63.57.10(www1.0catch.com) by rickybrown at usa.com, ns *.0catch.com '*.dex1.com', '*.questh.com', // 209.63.57.10(www1.0catch.com), ns *.0catch.com '*.00freehost.com', // by David Mccall (superjeeves at yahoo.com) '*.012webpages.com', // by support at 0catch.com '*.150m.com', '*.1sweethost.com', // by whois at bluehost.com '*.250m.com', // by jason at fahlman.net '*.9cy.com', // by paulw0t at gmail.com '*.angelcities.com', // by cliff at eccentrix.com '*.arcadepages.com', // by admin at site-see.com '*.e-host.ws', // by dns at jomax.net '*.envy.nu', // by Dave Ellis (dave at larryblackandassoc.com) '*.fw.bz', // by ben at kuehl.as '*.freewebportal.com', // by mmouneeb at hotmail.com '*.g0g.net', // by domains at seem.co.uk '*.galaxy99.net', // by admin at bagchi.org '*.greatnow.com', // by peo at peakspace.com '*.hautlynx.com', // by hlewis28 at juno.com '*.ibnsites.com', // by cmrojas at mail.com '*.just-allen.com', // by extremehype at msn.com '*.kogaryu.com', // by angelguerra at msn.com '*.maddsites.com', // by big.tone at maddhattentertainment.com '*.mindnmagick.com', // by tim at mind-n-magick.com '*.s4u.org', // by sung_wei_wang at yahoo.com '*.s-enterprize.com', '*.servetown.com', // by jonahbliss at earthlink.net '*.stinkdot.org', // by bluedot at ziplip.com '*.virtue.nu', // by dave at larryblackandassoc.com '*.zomi.net', // by sianpu at gmail.com ), '*.1asphost.com', // 216.55.133.18(216-55-133-18.dedicated.abac.net) by domains at dotster.com '100 Best Inc' => array( // by 100 Best Inc (info at 100best.com) // 66.235.204.7(h204-007.bluefishhosting.com) '*.2-hi.com', '*.20fr.com', '*.20ii.com', '*.20is.com', '*.20it.com', '*.20m.com', // by jlee at 100bestinc.com '*.20to.com', '*.2u-2.com', '*.3-st.com', '*.fws1.com', '*.fw-2.com', '*.inc5.com', '*.on-4.com', '*.st-3.com', '*.st20.com', '*.up-a.com', // 216.40.33.252(www-pd.mdnsservice.com) '*.0-st.com', '*.20me.com', ), '*.100foros.com', '*.12gbfree.com', // 75.126.176.194 by ashphama at yahoo.com '20six Weblog Services' => array( '.20six.nl', // by 20six weblog services (postmaster at 20six.nl) '.20six.co.uk', '.20six.fr', 'myblog.de', 'myblog.es', ), '*.250free.com', // by Brian Salisbury (domains at 250host.com) '*.275mb.com', // 204.15.10.144 by domains at febox.com '2Page.de' => array( '.dreipage.de', '.2page.de', ), '*.3-hosting.net', '*.5gbfree.com', // 75.126.153.58 by rob at roblist.co.uk '*.789mb.com', // 75.126.197.240(545mb.com -> 66.45.238.60, 66.45.238.61) by Nicholas Long (nicolas.g.long at gmail.com) '*.8000web.com', // 75.126.189.45 '*.9999mb.com', // 75.126.214.232 by allan Jerman (prodigy-airsoft at cox.net) 'aeonity.com', // by Emocium Solutions (creativenospam at gmail.com) 'Ai.NET' => array( '*.100free.com', // 205.134.188.54(development54.ai.net -> Non-existent) by support at ai.net '*.ai.net', // 205.134.163.4(aries.ai.net) by support at ai.net ), '*.aimoo.com', '*.alkablog.com', '*.alluwant.de', '.amkbb.com', 'AOL.com' => // http://about.aol.com/international_services '/^(?:chezmoi|home|homes|hometown|journals|user)\.' . '(?:aol|americaonline)\.' . '(?:ca|co\.uk|com|com\.au|com.mx|de)$/', // Rough but works 'Apple.com' => array('idisk.mac.com'), '*.askfaq.org', '.atfreeforum.com', // 216.224.120.14(kelsey.mykelsey1.com -> 216.224.120.10) '*.atwiki.com', // by Masakazu Ohno (s071011 at sys.wakayama-u.ac.jp) '*.asphost4free.com', 'basenow.com', 'BatCave.net' => array( '.batcave.net', // 64.22.112.226 '.freehostpro.com', // 64.22.112.226 ), '*.bb-fr.com', '.bbfast.com', // 72.52.135.174 by blogmaster2003 at gmail.com '*.beeplog.com', 'bestfreeforums.com', 'bestvotexxx.com', 'Bizcn.com' => '/.*\.w[0-9]+\.bizcn\.com$/', // XiaMen BizCn Computer & Network CO.,LTD 'Blog.com' => array( '*.blog.com', '*.blogandorra.com', // by admin.domains at co.blog.com '*.blogangola.com', // by admin.domains at co.blog.com ), '*.blog.com.es', '*.blog.hr', '*.blog-fx.com', '*.blogbeee.com', 'blogas.lt', 'blogbud.com', '*.blogburkinafaso.com', '*.blogcu.com', // by info at nokta.com 'blogfreely.com', '*.blogdrive.com', '*.blogg.de', 'bloggerblast.com', // by B. Kadrie (domains at starwhitehosting.com) 'bloggercrab.com', 'bloggers.nl', '*.bloggingmylife.com', '*.bloggles.info', '*.blogharbor.com', '*.bloguj.eu', 'bloguitos.com', 'blogosfer.com', '*.blogse.nl', // 85.17.41.16(srv1.blogse.nl) by ruben at mplay.nl '*.blogslive.net', '*.blogsome.com', // by Roger Galligan (roger.galligan at browseireland.com) '*.blogstream.com', 'blogyaz.com', 'bloodee.com', 'board-4you.de', 'boboard.com', // 66.29.54.116 by Excelsoft (shabiba at e4t.net) '*.boardhost.com', 'Bravenet.com' => array( '*.bravenet.com', '*.bravehost.com', ), '*.by.ru', // 217.16.29.50 by ag at near.ru, nthost.ru related? 'C2k.jp' => array( // by Makoto Okuse (webmaster at 2style.net) '.081.in', '.2style.in', '.bian.in', '.curl.in', '.ennui.in', '.jinx.in', '.loose.in', '.mist.in', '.muu.in', '.naive.in', '.panic.in', '.slum.in', // by 2style, ns *.click2k.net, *.2style.net '.2st.jp', '.betty.jp', '.cabin.jp', '.cult.jp', '.mippi.jp', '.purety.jp', '.rapa.jp', '.side-b.jp', '.web-box.jp', '.yea.jp', // by makoto okuse (webmaster at 2style.net), ns *.click2k.net, *.2style.net '.2style.net', '.click2k.net', '.houka5.com', // by click2k, ns *.click2k.net, *.2style.net '.psyco.jp', '.sweety.jp', '.2style.jp', // by click2k, ns *.2style.jp, *.2style.net '.cute.cd', // by Yuya Fukuda (count at kit.hi-ho.ne.jp), ns *.2style.jp, *.2style.net ), '*.canalblog.com', // 195.137.184.103 by dns-admin at pinacolaweb.com '*.chueca.com', 'city-forum.com', 'concepts-mall.com', '*.conforums.com', // by Roger Sutton (rogersutton at cox.net) 'connectedy.com', // 66.132.45.227(camilla.jtlnet.com) by astrader at insight.rr.com 'counterhit.de', '*.createforum.net', '*.creatuforo.com', // by Desafio Internet S.L. (david at soluwol.com) '*.createmybb.com', 'CwCity.de' => array( '.cwcity.de', '.cwsurf.de', ), 'dakrats.net', '*.dcswtech.com', '*.devil.it', '*.diaryland.com', 'digg.com', 'domains at galaxywave.net' => array( 'blogstation.net', '.phpbb-host.com', ), 'dotbb.be', '*.dox.hu', // dns at 1b.hu '*.eadf.com', '*.eblog.com.au', '*.ekiwi.de', '*.eamped.com', // Admin by Joe Hayes (joe_h_31028 at yahoo.com) '.easyfreeforum.com', // by XT Store Sas, Luca Lo Bascio (marketing at atomicshop.it) '*.ebloggy.com', 'enunblog.com', '*.epinoy.com', '*.ez-sites.ws', '*.ezbbforum.com', // 72.52.134.135 by blogmaster2003 at gmail.com '*.fathippohosting.com', // 208.101.3.192 'FC2.com' => array( 'Blogs' => '#^(?:.+\.)?blog[0-9]+\.fc2\.com$#', // Blogs, 'FOOBAR.blogN.fc2.com' and 'blogN.fc2.com/FOOBAR' // Many traps available: // bqdr.blog98.fc2.com, iframe // csfir.blog87.fc2.com, iframe // pppgamesk.blog100.fc2.com, iframe, broken Japanese // sippou2006.blog60.fc2.com, iframe // NOTE: 'blog.fc2.com' is not included '*.h.fc2.com', // Adult ), '*.fizwig.com', 'forum.ezedia.net', '*.extra.hu', // angelo at jasmin.hu '*.fanforum.cc', 'fingerprintmedia.com', '*.filelan.com', '*.fora.pl', '*.forka.eu', '*.foren-city.de', 'foren-gratis.de', '*.foros.tv', '*.forospace.com', 'foroswebgratis.com', '*.forum-on.de', '*.forum24.se', '*.forum5.com', // by Harry S (hsg944 at gmail.com) '.forum66.com', 'Forumotion.com' => array( '*.forumotion.com', // 75.126.156.15(s00.darkbb.com) '*.forumactif.com', // 91.121.41.79 '*.editboard.com', // 75.126.156.15 '*.sosblog.com', // 74.86.25.140 // 75.126.156.15 Used: forumotion.com, forumactif.com, editboard.com '*.0forum.biz', '*.1forum.biz', '*.1fr1.net', '*.1talk.net', '*.2forum.biz', '*.3forum.biz', '*.4forum.biz', '*.4rumer.com', '*.4rumer.net', '*.4umer.com', '*.4umer.net', '*.5forum.biz', '*.5forum.info', '*.5forum.net', '*.6forum.biz', '*.6forum.info', '*.77forum.com', '*.7forum.biz', '*.7forum.info', '*.7forum.net', '*.8forum.biz', '*.8forum.info', '*.8forum.net', '*.9forum.biz', '*.9forum.info', '*.activebb.net', '*.aforumfree.com', '*.all-forum.net', '*.all-up.com', '*.alldiscussion.net', '*.allgoo.net', '*.allgoo.us', '*.american-forum.net', '*.americantalk.net', '*.annuaire-forums.com', '*.asiafreeforum.com', '*.asianfreeforum.com', '*.azureforum.com', '*.azurforum.com', '*.bestcheapforum.com', '*.bestdiscussion.net', '*.bestgoo.com', '*.bestofforum.com', '*.bestofforum.net', '*.bestoforum.net', '*.bforum.biz', '*.big-forum.net', '*.board-poster.com', '*.board-realtors.com', '*.boardonly.com', '*.boardrealtors.net', '*.boardsmessage.com', '*.briceboard.com', '*.bubblelol.com', '*.buy-forum.com', '*.buy-talk.com', '*.buyforum.net', '*.buygoo.net', '*.buygoo.us', '*.camelscrew.com', '*.cheap-forum.com', '*.cheapforum.net', '*.chocoforum.com', '*.chocoforum.net', '*.clic-topic.com', '*.clicboard.com', '*.clictopic.com', '*.clictopic.net', '*.clictopics.com', '*.clubdiscussion.net', '*.coolbb.net', '*.crazy4us.com', '*.crazyfruits.net', '*.createmyboard.com', '*.crewcamel.com', '*.cyberfreeforum.com', '*.discutforum.com', '*.discutfree.com', '*.do-forum.com', '*.do-goo.com', '*.do-goo.net', '*.do-talk.com', '*.dodiscussion.com', '*.dogoo.us', '*.easydiscussion.net', '*.easyforumlive.com', '*.englishboard.net', '*.englishboards.com', '*.ephpbb.com', '*.eraseboard.net', '*.eraseboards.net', '*.euro-talk.net', '*.eurodiscussion.net', '*.eurogoo.com', '*.exchangesboard.com', '*.exprimetoi.net', '*.fairtopic.com', '*.fforum.biz', '*.fforumfree.com', '*.first-forum.com', '*.firstgoo.com', '*.fororama.com', '*.forum-2007.com', '*.forum-actif.net', '*.forum-free.biz', '*.forum-free.org', '*.forum-motion.com', '*.forum0.biz', '*.forum0.info', '*.forum0.net', '*.forum2.biz', '*.forum3.biz', '*.forum3.info', '*.forum5.info', '*.forum6.biz', '*.forum6.info', '*.forum7.biz', '*.forum777.com', '*.forum8.biz', '*.forum9.biz', '*.foruma.biz', '*.forumactif.biz', '*.forumactif.info', '*.forumactif.name', '*.forumactif.ws', '*.forumaction.net', '*.forumakers.com', '*.forumandco.com', '*.forumb.biz', '*.forumc.biz', '*.forumd.biz', '*.forumdediscussions.com', '*.forumdediscussions.net', '*.forume.biz', '*.forumeast.com', '*.forumf.biz', '*.forumfreek.com', '*.forumfreez.com', '*.forumg.biz', '*.forumh.biz', '*.forumh.net', '*.forumhope.com', '*.forumi.biz', '*.forumice.net', '*.foruminute.com', '*.forumj.biz', '*.forumj.net', '*.forumjonction.com', '*.forumk.biz', '*.foruml.biz', '*.forumm.biz', '*.forummotion.com', '*.forummotions.com', '*.forumn.biz', '*.forumn.net', '*.forumo.biz', '*.forumonline.biz', '*.forumotions.com', '*.forump.biz', '*.forump.info', '*.forumperso.com', '*.forumpersos.com', '*.forumplatinum.com', '*.forumpro.fr', '*.forumq.biz', '*.forumr.biz', '*.forumr.net', '*.forumrama.com', '*.forums-actifs.com', '*.forums-actifs.net', '*.forums1.net', '*.forumsactifs.com', '*.forumsactifs.net', '*.forumsfree.org', '*.forumsline.com', '*.forumsmakers.com', '*.forumsmotion.com', '*.forumsmotions.com', '*.forumt.biz', '*.forumv.biz', '*.forumvalue.com', '*.forumw.biz', '*.forumy.biz', '*.free-boards.net', '*.freediscussion.net', '*.freediscussions.net', '*.freeforum.me.uk', '*.freeforumboard.net', '*.freeforumfree.com', '*.freevideotalk.com', '*.frenchboard.com', '*.fruitsandco.com', '*.fullboards.com', '*.fullsubject.com', '*.fullsubject.net', '*.get-forum.net', '*.getdiscussion.com', '*.getgoo.net', '*.getgoo.us', '*.gettalk.net', '*.go-board.com', '*.go-board.net', '*.go-forum.net', '*.go-ogler.com', '*.gofreeforum.com', '*.gogoo.us', '*.goo-board.com', '*.goo-boys.com', '*.goo-dart.com', '*.goo-dole.com', '*.goo-done.com', '*.gooboards.com', '*.goodbb.net', '*.goodearths.com', '*.goodforum.net', '*.goodoles.com', '*.goodoolz.com', '*.gooforum.com', '*.gooforums.com', '*.googoolz.com', '*.great-forum.com', '*.heavenforum.com', '*.hforum.biz', '*.high-forums.com', '*.highbb.com', '*.highforum.net', '*.hightoxic.com', '*.homediscussion.net', '*.homegoo.com', '*.hooxs.com', '*.hot-me.com', '*.hot4um.com', '*.hotdiscussion.net', '*.hotgoo.net', '*.in-goo.com', '*.in-goo.net', '*.infodiscussion.net', '*.ingoo.us', '*.iowoi.com', '*.jforum.biz', '*.just-forum.net', '*.justboard.net', '*.justdiscussion.com', '*.justforum.net', '*.justgoo.com', '*.keuf.net', '*.lforum.biz', '*.lifediscussion.net', '*.lifeme.net', '*.lightbb.com', '*.logu2.com', '*.longdomaine.com', '*.lovediscussion.net', '*.lowcostforum.com', '*.make-free-forum.com', '*.makeforumfree.com', '*.makefreeforum.com', '*.mam9.com', '*.manageboard.com', '*.max2forum.com', '*.meabout.com', '*.megabb.com', '*.moncontact.com', '*.moninter.net', '*.motion-forum.net', '*.motionforum.net', '*.motionsforum.com', '*.mrforum.net', '*.msnboard.net', '*.msnyou.com', '*.my-free-board.com', '*.my-free-boards.com', '*.my-free-forum.com', '*.my-free-forums.com', '*.my-goo.com', '*.my-goo.net', '*.mydiscussionboard.com', '*.myfreeboard.net', '*.mygoo.org', '*.myrealboard.com', '*.netboarder.com', '*.netdiscussion.net', '*.netgoo.org', '*.new-forum.net', '*.newdiscussion.net', '*.newgoo.net', '*.nforum.biz', '*.nice-album.com', '*.nice-board.biz', '*.nice-board.com', '*.nice-board.net', '*.nice-boards.com', '*.nice-boards.net', '*.nice-forum.com', '*.nice-forum.net', '*.nice-forums.com', '*.nice-forums.net', '*.nice-gallery.net', '*.nice-subject.com', '*.nice-subjects.com', '*.nice-theme.com', '*.nice-topic.com', '*.nice-topics.com', '*.nicealbums.com', '*.niceboard.biz', '*.niceboard.net', '*.niceboards.net', '*.nicegalleries.net', '*.nicesubject.com', '*.nicesubjects.com', '*.nicetopic.net', '*.nicetopics.com', '*.nightforum.net', '*.nocost-forum.com', '*.nofeeforum.com', '*.one-forum.net', '*.onediscussion.net', '*.onegoo.us', '*.onlinegoo.com', '*.onlyquery.com', '*.open-board.com', '*.openu2.com', '*.othersboards.com', '*.own0.com', '*.pforum.biz', '*.phpbb9.com', '*.phpbbtest.com', '*.positifforum.com', '*.postalboard.com', '*.prodiscussion.net', '*.progoo.us', '*.pureforum.net', '*.qforum.biz', '*.quickbb.net', '*.realbb.net', '*.realfreeforum.com', '*.realmsn.com', '*.rforum.biz', '*.road2us.com', '*.roomforum.com', '*.saveboard.com', '*.screwcamel.com', '*.screwcamels.com', '*.sendboard.com', '*.sephorum.com', '*.sforum.biz', '*.shootboard.com', '*.shop-forum.net', '*.shopsubject.com', '*.simpleboard.net', '*.site-forums.com', '*.smileyforum.net', '*.sos-forum.net', '*.sos4um.com', '*.sos4um.net', '*.sosforum.net', '*.speedyforum.com', '*.stationforum.com', '*.subject-expert.com', '*.subject-line.com', '*.subject-tracer.com', '*.subjectchange.com', '*.subjectdeals.com', '*.subjectdebate.com', '*.subjectdone.com', '*.subjectonline.com', '*.subjectschange.com', '*.subjectsecrets.com', '*.super-forum.net', '*.talk-forums.com', '*.team-forum.net', '*.team-talk.net', '*.teamconvention.com', '*.teamgoo.net', '*.teensboards.com', '*.the-talk.net', '*.the-up.com', '*.thegoo.us', '*.thinksubject.com', '*.top-board.com', '*.top-forum.net', '*.top-me.com', '*.top-talk.net', '*.topdiscussion.com', '*.topgoo.net', '*.topic-board.com', '*.topic-board.net', '*.topic-debate.com', '*.topic-ideas.com', '*.topic-mail.com', '*.topic-zone.com', '*.topicboard.net', '*.topicboards.com', '*.topicmanager.com', '*.topicsolutions.net', '*.toxicfarm.com', '*.unlimitboard.com', '*.unlimitedboard.com', '*.unlimitedforum.com', '*.up-with.com', '*.up-your.com', '*.urealboard.com', '*.user-board.net', '*.userboard.net', '*.users-board.com', '*.users-board.net', '*.usersboard.com', '*.usersboard.net', '*.webgoo.us', '*.withboards.com', '*.withme.us', '*.worldgoo.com', '*.yahooboard.net', '*.yforum.biz', '*.yoo7.com', '*.youneed.us', '*.your-board.com', '*.your-talk.com', '*.yourme.net', '*.zforum.biz', // 75.126.156.15 redirect to forumactif.com '*.actifforum.com', '*.fr-bb.com', '*.superforum.fr', // 75.126.156.15 redirect to editboard.com '*.bbfr.net', '*.bbgraf.com', '*.cinebb.com', '*.darkbb.com', '*.dynamicbb.com', '*.zikforum.com', // 74.86.25.140 Used: sosblog.com '*.0-up.com', '*.0-yo.com', '*.04live.com', '*.06fr.com', '*.0fra.com', '*.0jet.com', '*.0yoo.com', '*.1toxic.com', '*.2k00.com', '*.2xik.com', '*.blog-2007.com', '*.blog-2008.com', '*.blog-2009.com', '*.blog-2010.com', '*.blog-actif.net', '*.blog-marley.com', '*.blog-talker.com', '*.blog2009.com', '*.blogactif.net', '*.blogalbums.com', '*.blogalerie.com', '*.blogaleries.com', '*.blogallerys.com', '*.blogandme.com', '*.blogandyou.com', '*.blogbubble.net', '*.blogdollz.com', '*.bloggeuse.net', '*.bloggeuses.com', '*.bloginstinct.com', '*.bloginternet.net', '*.blogmakers.net', '*.blogmarley.net', '*.blogminister.net', '*.blogmorane.com', '*.blognboard.com', '*.blogotek.net', '*.blogpas.com', '*.blogpublisher.net', '*.blogsalbum.com', '*.blogsalbums.com', '*.blogsfan.net', '*.blogsgallerys.com', '*.blogsitephp.com', '*.blogsland.net', '*.blogsmaker.com', '*.blogsmakers.com', '*.blogspeed.net', '*.blogsup.net', '*.blogsutil.com', '*.blogsutils.com', '*.blogsystem.net', '*.blogtalker.net', '*.blogtheque.net', '*.blogutil.com', '*.blogvsboard.com', '*.briceblog.com', '*.cibleblog.com', '*.cristalblog.com', '*.crystalblog.net', '*.dad-blog.com', '*.daddy-blog.com', '*.defaultblog.com', '*.discussionsblog.com', '*.dollzblog.com', '*.dtoxic.com', '*.easiestblog.net', '*.espaceblog.net', '*.exitblog.net', '*.expensiveblog.com', '*.extra-blog.net', '*.extrablog.net', '*.facileblog.com', '*.forblogger.com', '*.forumsblogs.com', '*.freephpblog.com', '*.fresh-blog.net', '*.galleryblog.net', '*.galleryblogs.net', '*.gallerysblog.com', '*.gallerysblogs.com', '*.hyper-blog.net', '*.hyper-blogger.com', '*.hyper-blogger.net', '*.hyperblogger.net', '*.instinctblog.com', '*.jeunblog.com', '*.jeuneblog.com', '*.judblog.com', '*.makeblog.net', '*.man-blog.net', '*.man-blogs.com', '*.man-blogs.net', '*.manblog.net', '*.manblog.org', '*.manblog.us', '*.manblogs.net', '*.mansblog.net', '*.mansblogs.com', '*.mansblogs.net', '*.meetingsblogs.com', '*.men-blog.net', '*.men-blogs.com', '*.men-blogs.net', '*.menblog.us', '*.menblogs.net', '*.mensblogs.net', '*.messaginblog.com', '*.monblogger.com', '*.mum-blog.com', '*.mummy-blog.com', '*.mummyblog.com', '*.myareablog.com', '*.myblog-online.net', '*.mybloginternet.com', '*.myblogland.com', '*.myblogmag.com', '*.myfreshblog.com', '*.myinternetblog.net', '*.myoverblog.com', '*.myoverblog.net', '*.mysharedblog.com', '*.nice-albums.com', '*.nice-galleries.com', '*.nicealbum.net', '*.nicegallery.net', '*.notreblogger.com', '*.outilblog.com', '*.over-blogger.com', '*.overblogger.com', '*.pasblog.com', '*.pasblog.net', '*.perfect-blog.net', '*.perfectblog.net', '*.phpblogsite.com', '*.phpmyblog.net', '*.plateformeblog.com', '*.playblogger.com', '*.publishmyblog.com', '*.pulseblog.net', '*.pulseblogs.com', '*.puretoxic.com', '*.reservedblog.com', '*.shareblog.net', '*.shareblogs.net', '*.shared-blogs.com', '*.sharedblog.net', '*.sharedblogs.net', '*.solideblog.com', '*.systemeblog.com', '*.talkmeblog.com', '*.toolsblog.net', '*.toxicplace.com', '*.ufreeblog.com', '*.uliveblog.com', '*.ultratoxic.com', '*.utilblog.com', '*.utilblogs.com', '*.utilsblog.com', '*.utilsblogs.com', '*.various-blog.com', '*.various-blog.net', '*.various-blogs.com', '*.various-blogs.net', '*.variusblog.com', '*.versusblog.com', '*.vieuxblog.com', '*.web-day.net', '*.whatsblog.net', '*.woman-blog.net', '*.woman-blogs.com', '*.woman-blogs.net', '*.womanblog.com', '*.womanblog.org', '*.womanblog.us', '*.womanblogs.net', '*.womansblogs.com', '*.womansblogs.net', '*.women-blog.net', '*.women-blogs.com', '*.women-blogs.net', '*.womenblog.us', '*.womenblogs.net', '*.womensblog.net', '*.womensblogs.net', '*.youblog.net', '*.yourliveblog.com', '*.yourweblog.net', ), '*.forumcommunity.net', '*.forumer.com', '*.forumfree.net', 'forumhosting.org', '*.forums.com', 'forumbolt.com', 'phpbb.forumgratis.com', '*.forumlivre.com', 'forumnow.com.br', '*.forumppl.com', 'Forumprofi.de' => '#^(?:.*\.)?forumprofi[0-9]*\.de$#', 'ForumUp' => '#^^(?:.*\.)?forumup\.' . '(?:at|be|ca|ch|co\.nz|co\.uk|co\.za|com|com\.au|com\.mx|cn|' . 'cz|de|dk|es|eu|fr|gr|hu|in|info|ir|it|jobs|jp|lt|' . 'lv|org|pl|name|net|nl|ro|ru|se|sk|tv|us|web\.tr)$#', '*.fory.pl', 'fotolog.com', '*.fr33webhost.com', '*.free-25.de', '*.free-bb.com', 'Free-Blog-Hosting.com' => array( 'free-blog-hosting.com', // by Robert Vigil (ridgecrestdomains at yahoo.com), ns *.phpwebhosting.com 'cheap-web-hosting-411.com', // by Robert Vigil, ns *.thisismyserver.net 'blog-tonite.com', // ns *.phpwebhosting.com 'blogznow.com', // ns *.phpwebhosting.com 'myblogstreet.com', // by Robert Vigil, ns *.phpwebhosting.com 'blogbeam.com', // by Robert Vigil, ns *.phpwebhosting.com ), '*.free-forums.org', // 209.62.43.2(ev1s-209-62-43-2.ev1servers.net) by Teodor Turbatu (tteo at zappmobile.ro) 'free-guestbook.net', '*.free-site-host.com', // by CGM-Electronics (chris at cgm-electronics.com) 'freebb.nl', '*.freeclans.de', '*.freelinuxhost.com', // by 100webspace.com '*.nofeehost.com', '*.freehyperspace.com', 'freeforum.at', // by Sandro Wilhelmy 'freeforumshosting.com', // by Adam Roberts (admin at skaidon.co.uk) '*.freeforums.org', // by 1&1 Internet, Inc. - 1and1.com '*.freemyforumadult.com', // 208.97.191.105(apache2-argon.willie.dreamhost.com) by sick at designsbysick.com '*.freewebhostingpro.com', '*.freehostingz.com', // no dns reply => 67.159.33.10 by Marx Lomas (marvellousmarx at hotmail.com) 'FreeWebHostingArea.com' => array( // or www.freewha.com '*.6te.net', '*.ueuo.com', '*.orgfree.com', ), '*.freewebpage.org', 'Freewebs.com' => array( // by inquiries at freewebs.com 'freewebs.com', 'freewebsfarms.com', ), '*.freewebspace.net.au', '*.freemyforum.com', // by messahost at gmail.com 'freepowerboards.com', '*.freepowerboards.com', '*.fsphost.com', // by Michael Renz (michael at fsphost.com) 'Funpic.de' => array( // by alexander at liemen.net '*.funpic.de', '*.funpic.org', ), 'gb-hoster.de', '*.genblogger.com', 'GetBetterHosting.com' => array( '*.30mb.com', // 207.210.82.74(cpanel.90megs.com) by 30MB Online (63681 at whois.gkg.net), introduced as one alternative of 90megs.com '*.90megs.com', // 207.210.82.75 by Get Better Hosting (admin at getbetterhosting.com) ), '*.goodboard.de', 'gossiping.net', '*.greatnuke.com', '*.guestbook.de', 'gwebspace.de', 'Google.com' => array( '*.blogspot.com', 'docs.google.com', 'groups-beta.google.com', ), 'guestbook.at', 'club.giovani.it', '*.gratis-server.de', 'healthcaregroup.com', '*.heliohost.org', 'Halverston Holdings Limited' => array( // pochta.ru?lng=en // Seems one of affiliates of RBC, RosBusinessConsulting (rbc.ru, rbcnews.com) '*.fromru.com', // by Lapeshkina Tatyana (noc at pochta.ru) '*.front.ru', // (domain at hc.ru) '*.hc.ru', // by (domain at hosting.rbc.ru, domaincredit at hosting.rbc.ru) '*.hotbox.ru', // (domain at hc.ru) '*.hotmail.ru', // (hosting at hc.ru) '*.krovatka.su', // (domain at hc.ru, hosting at hc.ru) '*.land.ru', // (domain at hc.ru) '*.mail15.com', // (hosting at hc.ru) '*.mail333.com', // (hosting at hc.ru) '*.newmail.ru', // (domain at hc.ru, hosting at hc.ru) '*.nightmail.ru', // (domain at hc.ru, hosting at hc.ru) '*.pisem.net', // (hosting at hc.ru) '*.pochta.ru', // (domain at hc.ru) '*.pochtamt.ru', // (domain at hc.ru) '*.pop3.ru', // (domain at hc.ru) '*.rbcmail.ru', // (domain at hc.ru) '*.smtp.ru', // (domain at hc.ru) ), '*.hiblogger.com', // by chiaokin at gmail.com '*.hit.bg', // by forumup.com ?? '*.homeblock.com', // 72.55.141.237(*.static.privatedns.com) '*.host-page.com', '*.hostingclub.de', 'forums.hspn.com', '*.httpsuites.com', '*.hut2.ru', 'ibfree.org', // 208.101.45.88 'IC.cz' => array( '*.ezin.cz', // internetcentrum at gmail.com, ns ignum.com, ignum.cz '*.hu.cz', // internetcentrum at gmail.com '*.hustej.net', // baz at bluedot.cz, dom-reg-joker at ignum.cz '*.ic.cz', // internetcentrum at gmail.com '*.kx.cz', // jan at karabina.cz, info at ignum.cz '*.own.cz', // internetcentrum at gmail.com '*.phorum.cz', // internetcentrum at gmail.com '*.tym.cz', // internetcentrum at gmail.com '*.tym.sk', // jobot at ignum.cz '*.wu.cz', // jan at karabina.cz, info at ignum.cz '*.yc.cz', // ivo at karabina.cz, jan at karabina.cz '*.yw.sk', // jobot at ignum.cz ), 'icedesigns at gmail.com' => array( // by Boling Jiang (icedesigns at gmail.com) '*.0moola.com', '*.3000mb.com', '.501megs.com', '*.teracities.com', '*.xoompages.com', ), '*.icspace.net', 'iEUROP.net' => array( '*.ibelgique.com', '*.iespana.es', '*.ifrance.com', '*.iitalia.com', '*.iquebec.com', '*.isuisse.com', ), '*.ihateclowns.net', '*.ii55.com', '*.ipbfree.com', '*.iphorum.com', '*.blog.ijijiji.com', '*.info.com', '*.informe.com', 'it168.com', '.iwannaforum.com', '*.jconserv.net', '*.jeeran.com', '*.jeun.fr', '*.joolo.com', '*.journalscape.com', '*.justfree.com', '*.blog.kataweb.it', '*.kaixo.com', // blogs.kaixo.com, blogak.kaixo.com '*.kokoom.com', 'koolpages.com', '*.ksiegagosci.info', 'Lide.cz' => array( '*.lide.cz', '*.sblog.cz', ), 'limmon.net', 'listible.com', ///list/ 'Livedoor.com' => array( 'blog.livedoor.jp', '*.blog.livedoor.com', // redirection ), '*.livejournal.com', '.load4.net', // 72.232.201.61(61.201.232.72.static.reverse.layeredtech.com), Says free web hosting but anonymous '*.logme.nl', 'lol.to', 'ltss.luton.ac.uk', 'Lycos.com' => array( '.angelfire.com', // angelfire.lycos.com '*.jubii.dk', // search., medlem. '*.jubiiblog.co.uk', '*.jubiiblog.com.es', // by Lycos Europe GmbH '*.jubiiblog.de', '*.jubiiblog.dk', '*.jubiiblog.fr', '*.jubiiblog.it', '*.jubiiblog.nl', '*.lycos.at', '*.lycos.ch', '*.lycos.co.uk', 'angelfire.lycos.com', '*.lycos.de', '*.lycos.es', '*.lycos.fr', '*.lycos.it', // by Lycos Europe GmbH '*.lycos.nl', '*.spray.se', '*.sprayblog.se', '*.tripod.com', ), '*.mastertopforum.com', 'mbga.jp', // by DeNA Co.,Ltd. (barshige at hq.bidders.co.jp, torigoe at hq.bidders.co.jp) '*.memebot.com', '*.messageboard.nl', 'mokono GmbH' => array( '*.blog.com.es', '*.blog.de', '*.blog.fr', '*.blog.co.uk', '*.blog.ca', '*.blogs.se', '*.blogs.fi', '*.blogs.no', '*.blogs.dk', '*.blogs.ro', '*.weblogs.pl', '*.weblogs.cz', '*.weblogs.hu', ), 'mojklc.com', 'MonForum.com' => array( '*.monforum.com', '*.monforum.fr', ), '*.multiforum.nl', // by Ron Warris (info at phpbbhost.nl) '*.my10gb.com', 'myblog.is', 'myblogma.com', '*.myblogvoice.com', 'myblogwiki.com', '*.myforum.ro', '*.myfreewebs.net', '*.mysite.com', '*.myxhost.com', '*.netfast.org', 'NetGears.com' => array( // by domains at netgears.com, ns *.northsky.com, seems 0Catch.com and northsky.com related '*.9k.com', // 64.39.31.55(netgears.com) '*.freewebspace.com', // 64.49.236.72 ), 'Netscape.com' => array('*.netscape.com'), 'users.newblog.com', 'neweconomics.info', '*.newsit.es', // 75.126.252.108 'Northsky.com' => array( // by hostmaster at northsky.com // northsky.com redirects to communityarchitect.com // 64.136.24.162(public-24-162.lax.ws.untd.com) by Mark Bishop '*.00author.com', '*.00band.com', '*.00books.com', '*.00cash.com', '*.00cd.com', '*.00dvd.com', '*.00family.com', '*.00game.com', '*.00home.com', '*.00it.com', '*.00me.com', '*.00movies.com', '*.00page.com', '*.00politics.com', '*.00sf.com', '*.00show.com', '*.00song.com', '*.00trek.com', '*.00video.com', '*.0me.com', '*.0pi.com', '*.happy-couple.com', '*.warp0.com', '*.50megs.com', // 64.136.25.170 // 64.136.25.171(mail.50megs.com) by Mark Bishop '*.00server.com', '*.communityarchitect.com', // Only mysite.com has a link to communityarchitect.com '*.fanspace.com', // 64.136.25.168 by Mark Bishop '*.00go.com', '*.00space.com', '*.00sports.com', ), '*.nm.ru', '*.obm.cn', // by xiaobak at yahoo.com.cn 'onlyfree.de', '*.ooblez.com', // by John Nolande (ooblez at hotmail.com) '*.ohost.de', 'Osemka.pl' => array( // by Osemka Internet Media (biuro at nazwa.pl) '.friko.pl', '.jak.pl', '.nazwa.pl', '*.prv.pl', // by NetArt (biuro at nazwa.pl) '.w8w.pl', '.za.pl', '.skysquad.net', // by Dorota Brzezinska (info at nazwa.pl) ), 'oyax.com', ///user_links.php '*.parlaris.com', '*.pathfinder.gr', '*.persianblog.com', '*.phorum.pl', 'Phpbb24.com' => array( // by Daniel Eriksson '*.createforum.us', // registry at webbland.se '*.forumportal.us', // registry at webbland.se '*.freeportal.us', // registry at network24.se '*.phpbb2.us', // daniel at danielos.com '*.phpbb24.com', // daniel at danielos.com '*.myforumportal.com', // daniel at webbland.se ), 'phpbb4you.com', 'phpbbcommunity.com', '*.phpbbx.de', '*.pochta.ru', '*.portbb.com', 'powerwebmaster.de', 'pro-board.com', // by SEM Optimization Services Ltd (2485 at coverage1.com) 'ProBoards' => '#^.*\.proboards[0-9]*\.com$#', '*.probook.de', '*.prohosting.com', // by Nick Wood (admin at dns-solutions.net) 'putfile.com', '*.quickfreehost.com', 'quizilla.com', '*.quotaless.com', '*.qupis.com', // by Xisto Corporation (shridhar at xisto.com) 'razyboard.com', '*.rbbloggers.com', // 88.85.78.82 by manager at vertona.com 'realhp.de', 'reddit.com', ///user/ 'rgbdesign at gmail.com' => array( // by RB2 (rgbdesign at gmail.com) '*.juicypornhost.com', '*.pornzonehost.com', '*.xhostar.com', ), 'RIN.ru' => array( '*.sbn.bz', '*.wol.bz', ), '*.sayt.ws', 'Seblg.com' => array( '*.seblg.com', // by Dao Lee (st at seblg.com) '*.xshorturl.org', // by Tonny Lee (admin at seblg.com) ), '*.seo-blog.org', '*.shoutpost.com', '*.siamforum.com', '*.siteburg.com', '*.sitehome.ru', '*.sitesfree.com', // support at livesearching.com '*.sitesled.com', 'skinnymoose.com', // by Steven Remington (admin at outdoorwebhosting.com) 'SmarTrans.com' => array( '.3w.to', '.aim.to', '.djmp.jp', '.nihongourl.nu', '.urljp.com', '.www1.to', '.www2.to', '.www3.to', ), '*.spazioforum.it', 'members.spboards.com', 'forums.speedguide.net', 'Sphosting.com' => array( // by admin at sphosting.com '*.hostinplace.com', // 66.197.204.233(sp3.sphosting.net -> 66.197.204.229) '*.sphosting.com', // 66.197.204.229(sp3.sphosting.net) '*.sphosting.net', // 66.197.204.229(*snip*), redirect to sphosting.com '*.spboards.com', // 66.197.146.104(sp2.sphosting.com -> Non-existent) 'spweblog.com', // 66.197.146.101(sp2.sphosting.com -> Non-existent) ), '*.spicyblogger.com', '*.spotbb.com', '*.squarespace.com', 'stickypond.com', 'stormloader.com', 'strikebang.com', '*.sultryserver.com', '*.t35.com', '*.talks.at', 'tabletpcbuzz.com', '*.talkthis.com', 'tbns.net', 'telasipforums.com', 'thestudentunderground.org', 'think.ubc.ca', '*.thumblogger.com', 'Topix.com' => array( 'topix.com', 'topix.net', ), 'forum.tourism-talk.com.au', 'tycho at e-lab.nl' => array( '*.234mb.com', // 195.242.99.206(s206.softwarelibre.nl -> 194.109.216.19) '*.1234mb.com', // 74.86.20.227(layeredpanel.com -> 195.242.99.195 -> s195.softwarelibre.nl) ), '*.tumblr.com', 'UcoZ Web-Services' => array( '*.3dn.ru', '*.clan.su', '*.moy.su', '*.my1.ru', '*.p0.ru', '*.pp.net.ua', '*.ucoz.co.uk', '*.ucoz.com', '*.ucoz.net', '*.ucoz.org', '*.ucoz.ru', '*.ws.co.ua', ), '*.unforo.net', '*.vdforum.ru', '*.vtost.com', '*.vidiac.com', 'Voila.fr' => array('.site.voila.fr'), 'volny.cz', 'voy.com', '*.welover.org', 'Web1000.com' => array( // http://www.web1000.com/register_new2.php '*.fasthost.tv', '*.hothost.tv', '*.isgreat.tv', '*.issexy.tv', '*.isterrible.tv', '*.somegood.tv', '*.adultnations.com', '*.alladultfemale.com', '*.alladultmale.com', '*.allbisexual.com', '*.allbreast.com', '*.allfeminism.com', '*.allmanpages.com', '*.allmendirect.com', '*.allphotoalbum.com', '*.allsexpages.com', '*.allwomanweb.com', '*.attorney-site.com', '*.bedclip.com', '*.bestfamilysite.com', '*.bestmusicpages.com', '*.bigmoron.com', '*.bourgeoisonline.com', '*.candyfrom.us', '*.cartoonhit.com', '*.cat-on-line.com', '*.chokesondick.com', '*.closeupsof.us', '*.cpa-site.com', '*.dampgirl.com', '*.dampgirls.com', '*.deepestfetish.com', '*.docspages.com', '*.dog-on-line.com', '*.dogcountries.com', '*.dognations.com', '*.doingitwith.us', '*.drenchedface.com', '*.drenchedlips.com', '*.drspages.com', '*.edogden.com', '*.eroticountry.com', '*.fasthost.tv', '*.fineststars.com', '*.foronlinegames.com', '*.forplanetearth.com', '*.freeadultparty.com', '*.freespeechsite.com', '*.gayadultxxx.com', '*.gaytaboo.com', '*.greatcookery.com', '*.greatrecipepages.com', '*.greatstreamingvideo.com', '*.hatesit.com', '*.hothost.tv', '*.iscrappy.com', '*.isgreat.tv', '*.issexy.tv', '*.isterrible.tv', '*.itinto.us', '*.japannudes.net', '*.jesussave.us', '*.jesussaveus.com', '*.labialand.com', '*.lettersfrom.us', '*.lookingat.us', '*.lunaticsworld.com', '*.microphallus.com', '*.mycatshow.com', '*.mydogshow.com', '*.myhardman.com', '*.mylawsite.net', '*.mylovething.com', '*.onasoapbox.com', '*.onlinepulpit.com', '*.petitionthegovernment.com', '*.photosfor.us', '*.picturetrades.com', '*.pleasekiss.us', '*.politicalemergency.com', '*.power-emergency.com', '*.prayingfor.us', '*.realbadidea.com', '*.realisticpolitics.com', '*.reallybites.com', '*.reallypumping.us', '*.reallyrules.com', '*.reallysuckass.com', '*.reallysucksass.com', '*.realsweetheart.com', '*.rottenass.com', '*.schoolreference.com', '*.sexheroes.com', '*.sharewith.us', '*.smutstars.com', '*.soakinglips.com', '*.somegood.tv', '*.songsfrom.us', '*.stinkingfart.com', '*.stinkyhands.com', '*.storiesfrom.us', '*.taboocountry.com', '*.television-series.com', '*.thisbelongsto.us', '*.totallyboning.us', '*.vaginasisters.com', '*.verydirtylaundry.com', '*.videosfor.us', '*.videosfrom.us', '*.videosof.us', '*.virtualdogshit.com', '*.web1000.com', '*.webpicturebook.com', '*.wronger.com', '*.xxxnations.com', '*.yourwaywith.us', ), 'webblog.ru', 'weblogmaniacs.com', '.webng.com', // www.*, www3.* '*.webnow.biz', // by Hsien I Fan (admin at servcomputing.com), ServComputing Inc. 'websitetoolbox.com', 'Welnet.de' => array( 'welnet.de', 'welnet4u.de', ), 'wh-gb.de', '*.wikidot.com', '*.wizhoo.com', // by Comp U Door (sales at comp-u-door.com) '*.wmjblogs.ru', '*.wordpress.com', '.wsboards.com', // by Chris Breen (Cbween at gmail.com) 'xeboards.com', // by Brian Shea (bshea at xeservers.com) '*.xforum.se', 'xfreeforum.com', '*.xhost.ro', // by domain-admin at listserv.rnc.ro '*.xoomwebs.com', '.freeblogs.xp.tl', '*.xphost.org', // by alex alex (alrusnac at hotmail.com) '*.ya.com', // 'geo.ya.com', 'blogs.ya.com', 'humano.ya.com', 'audio.ya.com'... 'Yahoo.com' => array( 'flickr.com', 'geocities.com', ), 'YANDEX, LLC.' => array( // noc at yandex.net '*.narod.ru', 'ya.ru', 'yandex.ru', ), '*.yeahost.com', 'yourfreebb.de', 'Your-Websites.com' => array( '*.your-websites.net', '*.web-space.ws', ), ); // -------------------------------------------------- $blocklist['B-2'] = array( // B-2: Jacked contents, something implanted // (e.g. some sort of blog comments, BBSes, forums, wikis) '*.3dm3.com', '3gmicro.com', // by Dean Anderson (dean at nobullcomputing.com) '*.1fr1.com', 'a4aid.org', 'aac.com', '*.aamad.org', 'ad-pecjak.si', 'agnt.org', 'alwanforthearts.org', '*.anchor.net.au', 'anewme.org', 'internetyfamilia.asturiastelecentros.com', 'Ball State University' => array('web.bsu.edu'), 'btofaq.net', ///v3/forum 'blepharospasm.org', 'nyweb.bowlnfun.dk', '*.buzznet.com', '*.canberra.net.au', 'castus.com', 'Case Western Reserve University' => array('case.edu'), 'ceval.de', 'codespeak.net', 'Colorado School of Mines' => array('ticc.mines.edu'), '*.colourware.co.uk', 'cpuisp.com', 'International Christian University' => array('icu.edu.ua'), '*.iphpbb.com', 'board-z.de', '*.board-z.de', 'California State University Stanislaus' => array('writing.csustan.edu'), 'cannon.co.za', 'columbosgarden.com', '*.communityhost.de', 'connectionone.org', 'deathwinds.com', 'deforum.org', 'delayedreaction.org', 'deproduction.org', 'dc503.org', 'dre-centro.pt', 'Duke University' => array('devel.linux.duke.edu'), '*.esen.edu.sv', 'forums.drumcore.com', 'dundeeunited.org', 'energyglass.com.ua', 'exclusivehotels.com', 'info.ems-rfid.com', 'farrowhosting.com', // by Paul Farrow (postmaster at farrowcomputing.com) 'fbwloc.com', '.fhmcsa.org.au', 'findyourwave.co.uk', 'frogcafe.net', 'plone4.fnal.gov', 'freeforen.com', 'funkdoc.com', 'funnyclipcentral.com', 'gearseds.com', 'generationrice.com', 'ghettojava.com', 'gnacademy.org', '*.goodboard.de', 'GreenDayVideo.net' => array( 'greendayvideo.net', 'espanol.greendayvideo.net', ), 'Hampton University' => array('calipsovalidation.hamptonu.edu'), 'Harvard Law School' => array('blogs.law.harvard.edu'), 'helpiammoving.com', 'homepage-dienste.com', 'Howard University' => array('networks.howard.edu'), 'hullandhull.com', 'Huntington University' => array('huntington.edu'), 'huskerink.com', '.hyba.info', 'inda.org', '*.indymedia.org', // by abdecom at riseup.net 'instantbulletin.com', 'internetincomeclub.com', '*.inventforum.com', 'Iowa State University' => array('boole.cs.iastate.edu'), 'ipwso.org', 'irha.info', // by David Rosenberg (drosen3 at luc.edu), 'ironmind.com', 'skkustp.itgozone.com', // hidden JavaScript 'jazz2online.com', '.jloo.org', 'Kazan State University' => array( 'dir.kzn.ru', 'sys.kcn.ru', ), 'test.kernel.org', 'kevindmurray.com', 'kroegjesroutes.nl', '.legion.org', 'Loyola Marymount University' => array('lmu.edu'), 'forum.lixium.fr', 'macfaq.net', 'me4x4.com', 'microbial-ecology.net', 'minsterscouts.org', 'morallaw.org', 'morerevealed.com', 'macronet.org', 'mamiya.co.uk', 'vcd.mmvcd.com', 'Monmouth College' => array('department.monm.edu'), 'mountainjusticemedia.org', '*.mybbland.com', 'mydlstore.com', '*.netboardz.com', 'North Carolina A&T State University' => array( 'ncat.edu', 'my.ncat.edu', 'hlc.ncat.edu', ), 'placetobe.org', 'users.nethit.pl', 'nightclubvip.net', 'njbodybuilding.com', 'nlen.org', 'Sacred Heart Catholic Primary School' => array('sacredheartpymble.nsw.edu.au'), 'offtextbooks.com', 'ofimatika.com', 'omakase-net', // iframe 'omikudzi.ru', 'openchemist.net', 'palungjit.com', 'pataphysics-lab.com', 'paypaldev.org', 'paullima.com', 'perl.org.br', 'pfff.co.uk', 'pix4online.co.uk', 'plone.dk', 'preform.dk', 'privatforum.de', 'publicityhound.net', 'qea.com', 'rbkdesign.com', 'rehoboth.com', 'rodee.org', 'ryanclark.org', '*.reallifelog.com', 'rkphunt.com', '.saasmar.ru', // Jacked. iframe to banep.info on root, etc 'sapphireblue.com', 'saskchamber.com', 'savevoorhees.org', 'selikoff.net', 'serbisyopilipino.org', 'setbb.com', 'sharejesusinternational.com', 'silver-tears.net', 'Saint Martin\'s University' => array('homepages.stmartin.edu'), '.softpress.com', 'southbound-inc.com', // There is a <html>.gif (img to it168.com) 'tehudar.ru', 'Tennessee Tech University' => array('manila.tntech.edu'), 'thebluebird.ws', 'theosis.org', '*.thoforum.com', 'troms-slekt.com', 'theedgeblueisland.com', 'toyshop.com.tw', // /images/sigui/ 'torontoplace.com', 'chat.travlang.com', 'trickropingbylassue.com', 'Truman State University' => array('mathbio.truman.edu'), 'tuathadedannan.org', 'txgotg.com', 'tzaneen.co.za', 'The University of North Dakota' => array( 'learn.aero.und.edu', 'ez.asn.und.edu', ), 'The University of Alabama' => array('bama.ua.edu'), 'unisonscotlandlaw.co.uk', 'University of California' => array('classes.design.ucla.edu'), 'University of Nebraska Lincoln' => array('ftp.ianr.unl.edu'), 'University of Northern Colorado' => array('unco.edu'), 'University of Toronto' => array( 'environment.utoronto.ca', 'grail.oise.utoronto.ca', 'utsc.utoronto.ca', ), 'urgentclick.com', 'vacant.org.uk', 'Villa Julie College' => array('www4.vjc.edu'), 'Vail Valley Foundation' => array('.vvf.org'), 'wabson.org', 'warping.to', // Seems (a redirection site, but now) taken advantage of 'webarch.com', // by WebArchitects (webarch at insync.net) 'weehob.com', 'West Virginia University Parkersburg' => array('wvup.edu'), 'williamsburgrentals.com', 'wolvas.org.uk', 'wookiewiki.org', 'xsgaming.com', // Jacked '.xthost.info', // by Michael Renz (dhost at mykuhl.de) 'Yahoo.com' => array( 'blog.360.yahoo.com', '*.groups.yahoo.com' ), 'yasushi.site.ne.jp', // One of mixedmedia.net' 'youthpeer.org', '*.zenburger.com', 'Zope/Python Users Group of Washington, DC' => array('zpugdc.org'), ); // -------------------------------------------------- $blocklist['C'] = array( // C: Sample setting of: // Exclusive spam domains // // Seems to have flavor of links, pills, gamble, online-games, erotic, // affiliates, finance, sending viruses, malicious attacks to browsers, // and/or mixed ones // // Please notify us about this list with reason: // http://pukiwiki.sourceforge.jp/dev/?BugTrack2/208 // C-1: Domain sets (seems to be) born to spam you // // All buziness-related spam //'.biz' // 'admin at seekforweb.com' => array( // by Boris (admin at seekforweb.com, bbmfree at yahoo.com) '.lovestoryx.com', '.loveaffairx.com', '.onmore.info', '.scfind.info', '.scinfo.info', '.webwork88.info', ), 'boss at bse-sofia.bg' => array( // by Boris '.htewbop.org', '.kimm--d.org', '.gtre--h.org', '.npou--k.org', '.bres--z.org', '.berk--p.org', '.bplo--s.org', '.basdpo.org', '.jisu--m.org', '.kire--z.org', '.mertnop.org', '.mooa--c.org', '.nake--h.org', '.noov--b.org', '.suke--y.org', '.vasdipv.org', '.vase--l.org', '.vertinds.org', ), 'pokurim at gamebox.net' => array( // by Thai Dong Changli '.aqq3.info', '.axa00.info', '.okweb11.org', '.okweb12.org', '.okweb13.org', '.okweb14.org', ), 'opezdol at gmail.com' => array( '.informazionicentro.info', '.notiziacentro.info', ), 'SomethingGen' => array( // 'CamsGen' by Lui Xeng Shou (camsgen at model-x.com) // 'CamsGen' by Sergey (buckster at hotpop.com) // 'BucksoGen', by Pronin Sergey (buckster at list.ru) // by Lee Chang (nebucha at model-x.com) '.adult-chat-world.info', // by Lui '.adult-chat-world.org', // by Lui '.adult-sex-chat.info', // by Lui '.adult-sex-chat.org', // by Lui '.adult-cam-chat.info', // by Lui '.adult-cam-chat.org', // by Lui '.dildo-chat.org', // by Lui '.dildo-chat.info', // by Lui // flirt-online.info is not CamsGen '.flirt-online.org', // by Lui '.live-adult-chat.info', // by Lui '.live-adult-chat.org', // by Lui '.sexy-chat-rooms.info', // by Lui '.sexy-chat-rooms.org', // by Lui '.swinger-sex-chat.info', // by Lui '.swinger-sex-chat.org', // by Lui '.nasty-sex-chat.info', // by Lui '.nasty-sex-chat.org', // by Lui '.camshost.info', // by Sergey '.camdoors.info', // by Sergey '.chatdoors.info', // by Sergey '.lebedi.info', // by Pronin '.loshad.info', // by Pronin '.porosenok.info', // by Pronin '.indyushonok.info', // by Pronin '.kotyonok.info', // by Pronin '.kozlyonok.info', // by Pronin '.magnoliya.info', // by Pronin '.svinka.info', // by Pronin '.svinya.info', // by Pronin '.zherebyonok.info', // 89.149.206.225 by Pronin '.medvezhonok.org', // 89.149.206.225 "BucksoGen 1.2b" '.adult-cam-chat-sex.info', // by Lee '.adult-chat-sex-cam.info', // 'CamsGen' by Lee '.live-chat-cam-sex.info', // 'CamsGen' by Lee '.live-nude-cam-chat.info', // 'CamsGen' by Lee '.live-sex-cam-nude-chat.info', // 'CamsGen' by Lee '.sex-cam-live-chat-web.info', // 'CamsGen' by Lee '.sex-chat-live-cam-nude.info', // 'CamsGen' by Lee '.sex-chat-porn-cam.info', // by Lee ), 'mital at topo20.org' => array( // by Marcello Italianore '.trevisos.org', '.topo20.org', ), 'WellCams.com' => array( '.j8v9.info', // by Boris Moiseev (borka at 132moiseev.com) '.wellcams.com', // by Sergey Sergiyenko (studioboss at gmail.com) '.wellcams.biz', // by Sergey Sergiyenko (studioboss at gmail.com) ), 'graz at rubli.biz' => array( // by Chinu Hua Dzin '.besturgent.org', '.googletalknow.org', '.montypythonltd.org', '.supersettlemet.org', '.thepythonfoxy.org', '.ukgamesyahoo.org', '.youryahoochat.org', ), 'kikimas at mail.net' => array( // Redirect to nb717.com etc '.dbsajax.org', '.acgt2005.org', '.gopikottoor.com', '.koosx.org', '.mmgz.org', '.zhiyehua.net', ), 'vdf at lovespb.com' => array( // by Andrey '.02psa.info', '.1818u.org', '.18ew.info', '.43sexx.org', '.56porn.org', '.6discount.info', '.78porn.org', // "UcoZ WEB-SERVICES" '.78rus.info', '.92ssex.org', // "ForumGenerator" '.93adult.org', // "ForumGenerator" '.aboutsr.info', '.aboutzw.info', '.all23.info', '.allvdf.info', '.buy-dge.info', '.buypo.info', '.canadausa.info', // "UcoZ WEB-SERVICES" '.cv83.info', '.cvwifw.info', '.dabouts.info', '.eplot.info', // by Beatrice C. Anderson (Beatrice.C.Anderson at spambob.com) '.fuck2z.info', // "UcoZ WEB-SERVICES"-like design '.free01sa.info', '.frees1.info', '.freexz.info', '.ifree-search.org', '.lovespb.info', '.myso2.info', '.nb74u.info', '.ohhh2.info', '.ol43.info', '.olala18.info', '.oursales.info', '.pasian1.info', '.pldk.info', '.po473.info', '.pornr.info', // "UcoZ WEB-SERVICES" '.poz2.info', '.qpf8j4d.info', '.saleqw.info', '.sexof.info', // "UcoZ WEB-SERVICES" '.sexz18.info', '.sexy69a.info', '.shedikc.info', '.spb78.info', '.usacanadauk.info', '.v782mks.info', '.vny0.info', '.wifes1.info', '.xranvam.info', '.zenitcx.info', '.zxolala.info', ), 'nike.borzoff at gmail.com' => array( // by Nike Borzoff, 'vdf at lovespb.com'-related '.care01.info', '.care02.info', '.care03.info', '.care04.info', '.care05.info', '.care06.info', '.care07.info', '.care08.info', '.care09.info', '.care10.info', '.kra1906.info', // "UcoZ WEB-SERVICES" '.klastar01.info', '.klastar02.info', '.klastar03.info', '.klastar04.info', '.klastar05.info', '.klastar06.info', '.klastar07.info', '.klastar08.info', '.klastar09.info', '.klastar10.info', '.um20ax01.info', '.um20ax02.info', '.um20ax03.info', '.um20ax04.info', '.um20ax05.info', '.um20ax06.info', '.um20ax07.info', '.um20ax08.info', '.um20ax09.info', '.um20ax10.info', ), 'forrass at gmail.com' => array( // by Ismail '.zmh01.info', '.zmh02.info', '.zmh03.info', '.zmh04.info', '.zmh05.info', '.zmh06.info', '.zmh07.info', '.zmh08.info', '.zmh09.info', '.zmh10.info', ), 'Varsylenko Vladimir and family' => array( // by Varsylenko Vladimir (vvm_kz at rambler.ru) // by David C. Lack (David.C.Lack at dodgeit.com) // by Kuzma V Safonov (admin at irtes.ru) // by Petrov Vladimir (vvm_kz at rambler.ru) // by LAURI FUNK (vvm_kz at rambler.ru) // 64.92.162.210(*.static.reverse.ltdomains.com) '.abrek.info', // by Petrov '.allsexonline.info', // by Varsylenko '.d1rnow.info', // by Petrov '.doxer.info', // Petrov '.freeforworld.info', // Varsylenko '.goodworksite.info', // Varsylenko '.onall.info', // by Varsylenko '.powersiteonline.info', // by Varsylenko '.rentmysite.info', // by Varsylenko '.sexdrink.info', // by Petrov '.siteszone.info', // by Varsylenko '.sfup.info', // by Petrov '.superfreedownload.info', // by Varsylenko '.superneeded.info', // by Varsylenko '.srup.info', // by Petrov // 66.235.185.143(*.svabuse.info) '.accommodationwiltshire.com', // by Petrov '.levines.info', // by Petrov '.sernost.info', // by Petrov '.sexvideosite.info', // by Petrov '.vvsag.info', // by Petrov // 81.0.195.134 '.michost.info', // by LAURI '.parther.info', // by LAURI // 88.214.202.100 '.gitsite.info', // by Petrov '.organiq.info', // by Petrov '.yoursitedh.info', // by Petrov // 217.11.233.58 by Petrov '.mp3vault.info', // DNS time out or failed '.bequeous.info', // by Davi '.sopius.info', // by Kuzma '.sovidopad.info', // by Kuzma '.yerap.info', // by Kuzma ), 'zhu1313 at mail.ru' => array( // by Andrey Zhurikov '.flywebs.com', '.hostrim.com', '.playbit.com', ), 'webmaster at dgo3d.info' => array( // by Son Dittman '.bsb3b.info', '.dgo3d.info', '.dgo5d.info', ), 'cooler.infomedia at gmail.com' => array( '.diabetescarelink.com', '.firstdebthelp.com', ), 'hostmaster at astrons.com' => array( // by Nikolajs Karpovs '.pokah.lv', '.astrons.com', ), 'seocool at bk.ru' => array( // by Skar '.implex3.com', '.implex6.info', '.softprof.org', ), 'Caslim.info' => array( '.caslim.info', // by jonn22 (jonnmarker at yandex.ru) '.tops.gen.in', // by Kosare (billing at caslim.info) ), 'foxwar at foxwar.ispvds.com' => array( // by Alexandr, Hiding google?q= '.777-poker.biz', '.porn-11.com', ), 'Conto.pl' => array( '.8x.pl', // domena at az.pl '.3x3.pl', // by biuro at nazwa.pl '.conto.pl', // by biuro at nazwa.pl '.guu.pl', // by conto.pl (domena at az.pl) '.xcx.pl', // domena at az.pl '.yo24.pl', // domena at az.pl ), 'mail at pcinc.cn' => array( // Domains by Lin Zhi Qiang // NOTE: pcinc.cn -- 125.65.112.13 by Lin Zhi Qiang (lin80 at 21cn.com) // 125.65.112.11 // The same IP: web001.cdnhost.cn, *.w19.cdnhost.cn 'shoopivdoor.w19.cdnhost.cn', // web001.cdnhost.cn '.shoopivdoor.com', // 125.65.112.12 // The same IP: web003.cdnhost.cn, *.w16.cdnhost.cn '.hosetaibei.com', '.playsese.com', // 125.65.112.13 // The same IP: web006.cdnhost.cn, *.w9.cdnhost.cn '.ahatena.com', '.asdsdgh-jp.com', '.conecojp.net', '.game-oekakibbs.com', '.geocitygame.com', '.gsisdokf.net', '.korunowish.com', '.netgamelivedoor.com', '.soultakerbbs.net', '.yahoo-gamebbs.com', '.ywdgigkb-jp.com', // 125.65.112.14 // The same IP: web007.cdnhost.cn, *.w12.cdnhost.cn '.acyberhome.com', '.bbs-qrcode.com', '.gamesroro.com', '.gameyoou.com', '.gangnu.com', '.goodclup.com', '.lineage321.com', '.linkcetou.com', '.love888888.com', '.ragnarok-bbs.com', '.ragnarok-game.com', '.rmt-navip.com', '.watcheimpress.com', // 125.65.112.15 // The same IP: web008.cdnhost.cn, *.w11.cdnhost.cn '.18girl-av.com', '.aurasoul-visjp.com', '.gamaniaech.com', '.game-mmobbs.com', '.gameslin.net', '.gemnnammobbs.com', '.gogolineage.net', '.grandchasse.com', '.jpragnarokonline.com', '.jprmthome.com', '.maplestorfy.com', '.netgamero.net', '.nothing-wiki.com', '.ourafamily.com', '.ragnarok-sara.com', '.rmt-lineagecanopus.com', '.rmt-ranloki.com', '.rogamesline.com', '.roprice.com', '.tuankong.com', '.twreatch.com', // 125.65.112.22 // The same IP: web013.cdnhost.cn '.lzy88588.com', '.ragnaroklink.com', // 125.65.112.24 '.rmtfane.com', '.fc2weday.com', '.nlftweb.com', // 125.65.112.27 '.i520i.com', '.sunwayto.com', // 125.65.112.31 // The same IP: web016.cdnhost.cn '.twyaooplay.com', // 125.65.112.32 // The same IP: web037.cdnhost.cn '.emeriss.com', '.raginfoy.com', '.ragnarokgvg.com', '.rentalbbs-livedoor.com', '.romaker.com', '.sagewikoo.com', '.samples112xrea.com', '.wiki-house.com', // 125.65.112.49 '.chaosx0.com', // 125.65.112.88 // The same IP: web015.cdnhost.cn '.a-hatena.com', '.biglobe-ne.com', '.blogplaync.com', '.din-or.com', '.dtg-gamania.com', '.fcty-net.com', '.game-fc2blog.com', '.gameurdr.com', '.getamped-garm.com', '.interzq.com', '.linbbs.com', // by zeng xianming (qqvod at qq.com). www.linbbs.com is the same ip of www.game-fc2blog.com(222.77.185.101) at 2007/03/11 '.luobuogood.com', '.ragnarok-search.com', '.rinku-livedoor.com', // 125.65.112.90 '.gtvxi.com', // 125.65.112.91 // The same IP: web004.cdnhost.cn '.6828teacup.com', '.blog-livedoor.net', '.cityblog-fc2web.com', '.deco030-cscblog.com', '.imbbs2t4u.com', '.k5dionne.com', '.lineagejp-game.com', '.mbspro6uic.com', '.slower-qth.com', '.wikiwiki-game.com', // 125.65.112.93 // The same IP: web022.cdnhost.cn '.aaa-livedoor.net', '.cityhokkai.com', // web022.cdnhost.cn '.fanavier.net', '.geocitylinks.com', // web022.cdnhost.cn '.kuronowish.net', // web022.cdnhost.cn '.ro-bot.net', // 125.65.112.95 // The same IP: web035.cdnhost.cn, web039.cdnhost.cn '.23styles.com', '.aehatena-jp.com', '.ameblog-jp.net', '.antuclt.com', '.blog-ekndesign.com', '.d-jamesinfo.com', '.editco-jp.com', '.ezbbsy.com', '.extd-web.com', '.fotblong.com', '.game62chjp.net', '.gamegohi.com', '.gamesmusic-realcgi.net', '.gamesragnaroklink.net', '.homepage-nifty.com', '.ie6xp.com', '.irisdti-jp.com', '.jklomo-jp.com', '.jpxpie6-7net.com', '.lian-game.com', '.lineage-bbs.com', '.lineage1bbs.com', '.livedoor-game.com', '.litcan.com', '.lovejpjp.com', '.m-phage.com', '.muantang.com', '.plusd-itmedia.com', '.runbal-fc2web.com', '.saussrea.com', '.tooalt.com', '.toriningena.net', '.yahoodoor-blog.com', '.yy14-kakiko.com', // 125.65.112.137 '.clublineage.com', // 228.14.153.219.broad.cq.cq.dynamic.163data.com.cn '.kaukoo.com', // 219.153.14.228, by zeng xianming (expshell at 163.com) '.linrmb.com', // 219.153.14.228, by zeng xianming (qqvod at qq.com) '.ptxk.com', // 222.73.236.239, by zeng xianming (zxmdiy at gmail.com) '.rormb.com', // 222.73.236.239, by zeng xianming (qqvod at qq.com) '.games-nifty.com', // 255.255.255.255 now '.homepage3-nifty.com', // 255.255.255.255 now ), 'caddd at 126.com' => array( '.chengzhibing.com', // by chen gzhibing '.jplinux.com', // by lian liang '.lineageink.com', // by cai zibing, iframe to goodclup.com '.lineagekin.com', // by cai zibing, iframe to goodclup.com '.tooplogui.com', // by zibing cai '.twsunkom.com', // by guo zhi wei '.twmsn-ga.com', // by guo zhi wei, iframe to grandchasse.com ), 'nuigiym2 at 163.com' => array( // by fly bg '.linainfo.net', // Seems IP not allocated now '.lineagalink.com', // 220.247.157.99 '.lineagecojp.com', // 61.139.126.10 '.ragnarokonlina.com', // 220.247.158.99 ), 'aakin at yandex.ru' => array( // 89.149.206.225(*.internetserviceteam.com) by Baer '.entirestar.com', '.superbuycheap.com', '.topdircet.com', ), 'newblog9 at gmail.com' => array( // by jiuhatu kou '.tianmieccp.com', '.xianqiao.net', ), 'm.frenzy at yahoo.com' => array( // by Michael '.p5v.org', '.j111.net', '.searchhunter.info', '.soft2you.info', '.top20health.info', '.top20ringtones.info', '.top20travels.info', '.v09v.info', '.x09x.info', '.zb-1.com', ), 'serega555serega555 at yandex.ru' => array( // by Lebedev Sergey '.bingogoldenpalace.info', '.ccarisoprodol.info', '.ezxcv.info', '.isuperdrug.com', '.pharmacif.info', '.pornsexteen.biz', '.ugfds.info', '.vviagra.info', ), 'anatolsenator at gmail.com' => array( // by Anatol '.cheapestviagraonline.info', '.buyphentermineworld.info' ), 'webmaster at mederotica.com' => array( '.listsitepro.com', // by VO Entertainment Inc (webmaster at mederotica.com) '.testviagra.org', // by Chong Li (chongli at mederotica.com) '.viagra-best.org', // by Chong Li (chongli at mederotica.com) '.viagra-kaufen.org', // by Chong Li (chongli at mederotica.com) ), 'gray at trafic.name' => array( // by Billing Name:Gray, Billing Email:gray at trafic.name '.auase.info', // by ilemavyq7461 at techie.com '.axeboxew.info', // by zygeu220 at writeme.com '.boluzuhy.info', // by pikico5419 at post.com '.ekafoloz.info', // by nuzunyly8401 at techie.com '.ejixyzeh.info', // by vubulyma5163 at consultant.com '.emyfyr.info', // by osiqabu9669 at writeme.com '.exidiqe.info', // by kufyca5475 at mail.com '.gerucovo.info', // by apegityk7224 at writeme.com '.gubiwu.info', // by lywunef6532 at iname.com '.ijizauax.info', // by ysauuz2341 at iname.com '.ixahagi.info', // 70.47.89.60 by famevi9827 at email.com '.jiuuz.info', // by meqil6549 at mail.com '.nudetar.info', // by vohepafi3536 at techie.com '.nipud.info', // by bohox9872 at mindless.com '.mejymik.info', // by fiqiji3529 at cheerful.com '.mylexus.info', // Billing Email is simhomer12300 at mail.com, but posted at the same time, and ns *.grayreseller.com '.olasep.info', // by lizon8506 at mail.com '.oueuidop.info', // by arytyb6913 at europe.com '.oviravy.info', // by amyuu3883 at london.com '.ovuri.info', // by exumaxyt1371 at consultant.com '.ragibe.info', // by ehome4458 at myself.com '.ucazib.info', // by gorare7222 at consultant.com '.udaxu.info', // by gubima4007 at usa.com '.ulycigop.info', // by unodyqil6241 at mindless.com '.vubiheq.info', // by uisujih5849 at hotmail.com '.xyloq.info', // 70.47.89.60 by yuunehi8586 at myself.com '.yvaxat.info', // by koqun9660 at mindless.com '.yxyzauiq.info', // by robemuq8455 at cheerful.com ), 'Carmodelrank.com etc' => array( // by Brianna Dunlord (briasmi at yahoo.com) // by Tim Rennei (TimRennei at yahoo.com), redirect to amaena.com (fake-antivirus) // by Alice T. Horst (Alice.T.Horst at pookmail.com) '.carmodelrank.com',// by Brianna '.cutestories.net', // by Brianna '.sturducs.com', '.bestother.info', // by Tim '.premiumcasinogames.com', // by Brianna) '.yaahooo.info', // by Alice ), 'aliacsandr at yahoo.com' => array( '.cubub.info', // "Free Web Hosting" ), 'aliacsandr85 at yahoo.com' => array( // by Dr. Portillo or Eva Sabina Lopez Castell '.xoomer.alice.it', // "Free Web Hosting" '.freebloghost.org', // "Free Web Hosting" by Dr. '.freeprohosting.org', // "Free Web Hosting" by Dr. '.googlebot-welcome.org', // "Free Web Hosting" by Dr. '.icesearch.org', // "Free Web Hosting" by Eva '.phpfreehosting.org', // "Free Web Hosting" by Dr. '.sashawww.info', // "Free Web Hosting" by Dr. '.sashawww-vip-vip.org', // "Free Web Hosting" by Dr. '.topadult10.org', // "Free Web Hosting" by Eva '.xer-vam.org', // "Ongline Catalog" by Dr. '.xxxse.info', // "Free Web Hosting" by Eva '.viagra-price.org', // by Eva '.vvsa.org', // "Free Web Hosting" by Eva '.free-webhosts.com', // "Free Web Hosting" by Free Webspace ), '.onegoodauto.org', // "Free Web Hosting" by sqrtv2 at gmail.com 'Something-Gamble' => array( // Gamble: Roulette, Casino, Poker, Keno, Craps, Baccarat '.atonlineroulette.com', // by Blaise Johns '.atroulette.com', // by Gino Sand '.betting-123.com', // by Joana Caceres '.betting-i.biz', // by Joaquina Angus '.casino-challenge.com', // by Maren Camara '.casino-gambling-i.biz', // by Giselle Nations '.casino-italian.com', // by Holley Yan '.casino123.net', // by Ta Baines '.casinohammamet.com', // by Inger Barhorst '.casinoqz.com', // by Berenice Snow '.casinos-777.net', // by Iona Ayotte '.crapsok.com', // by Devon Adair, '.dcasinoa.com', // by August Hawkinson '.e-poker-4u.com', // by Issac Leibowitz '.free-dvd-player.biz', // by Rosario Kidd '.florida-lottery-01.com', // by Romeo Dillon '.gaming-123.com', // by Jennifer Byrne '.kenogo.com', // by Adriane Bell '.mycaribbeanpoker.com', // by Andy Mullis '.onbaccarat.com', // by Kassandra Dunn '.online-experts.biz', // by Liberty Helmick '.onlinepoker-123.com', // by Andrea Feaster '.playpokeronline-123.com', // by Don Lenard '.poker-123.com', // by Mallory Patrick (Mallory_Patrick at marketing-support.info) '.texasholdem123.com', // by Savion Lasseter '.texasholdem-777.com', // by Savanna Lederman '.the-casino-directory-1715.us', // by Thora Oldenburg '.the-craps-100.us', // by Lorrine Ripley '.the-free-online-game-913.us', // by Kanesha Clem '.the-free-poker-1798.us', // by Elaina Witte '.the-las-vegas-gambling-939.us', // by Jesusita Hageman '.the-online-game-poker-1185.us', // by Merna Bey '.the-playing-black-jack.com', // by Kristine Brinker '.the-poker-1082.us', // by Kristofer Boldt '.the-rule-texas-hold-em-2496.us', // by Melvina Stamper '.the-texas-strategy-holdem-1124.us', // by Neda Frantz '.the-video-black-jack.com', // by Jagger Godin ), 'Something-Insurance' => array( // Car / Home / Life / Health / Travel insurance, Loan finance, Mortgage refinance // 0-9 '.0q.org', // by Shamika Curtin, "Online car insurance information" '.1-bookmark.com', // by Sonia Snyder, "Titan auto insurance information" '.1day-insurance.com', // by Kelsie Strouse, "Car insurance costs" '.1upinof.com', // by Diego Johnson, "Car insurance quote online uk resource" '.18wkcf.com', // by Lexy Bohannon '.2001werm.org', // by Raphael Rayburn '.2004heeparea1.org', // by Dinorah Andrews '.21nt.net', // by Jaida Estabrook '.3finfo.com', // by Damian Pearsall '.3somes.org', // by Mauro Tillett '.453531.com', // by Kurt Flannery '.4freesay.com', // by Eloy Jones '.5ssurvey.com', // by Annamarie Kowalski '.8-f22.com', // by Larraine Evers '.9q.org', // by Ami Boynton // A '.a40infobahn.com', // by Amit Nguyen '.a4h-squad.com', // by Ross Locklear '.aac2000.org', // by Randi Turner '.aaadvertisingjobs.com', // by Luciano Frisbie '.acahost.com', // by Milton Haberman '.aconspiracyofmountains.com', // by Lovell Gaines '.acornwebdesign.co.uk', // by Uriel Dorian '.activel-learning-site.com', // by Mateo Conn '.ad-makers.com', // by Shemeka Arsenault '.ada-information.org', // by Josef Osullivan '.adelawarerefinance.com', // by Particia Mcmillan, "Delaware refinance advisor" '.adult-personal-ads-e-site.info', // by Nery Ainsworth '.aequityrefinance.com', // by Jadwiga Duckworth '.aerovac-hotpress.com', // by Trey Marlow '.agfbiosensors.com', // by Lionel Dempsey '.ahomeloanrefinance.com', // by Leslie Kinser '.affordablerealestate.net', // by Season Otoole '.ahomerefinancingloans.com', // by Julie Buck, "Home refinancing loans guide" '.ahouserefinance.com', // by Young Alley '.akirasworld.com', // by Piper Sullivan '.alderik-production.com', // by Joan Stiles '.alltechdata.com', // by Dom Laporte '.amconllc.com', // by Syble Benjamin '.amobilehomerefinancing.com', // by Clyfland Buckley, "Mobile home refinancing" '.amortgagerefinancepennsylvania.com', // by Richard Battle, "Mortgage refinance pennsylvania articles" '.angelandcrown.net', // by Claretta Najera '.ankoralina.com', // by Eladia Demers '.antiquegoldmine.com', // by Keena Marlow '.aquinosotros.com', // by Nanci Prentice '.architectionale.com', // by Wilbur Cornett '.arcreditcards.com', // by Ecgbeorht Stokes, "Ameriquest credit cards articles" '.arefinancebadcredit.com', // by Isaac Mejia, "Refinance bad credit" '.arefinancehome.com', // by Duane Doran '.arefinancinghome.com', // by Ike Laney '.athletic-shoes-e-shop.info', // by Romelia Money '.auction-emall-site.info', // by Dayle Denman '.auctions-site.info', // by Cammie Chiu, "Online loan mortgage info" '.auto-buy-rite.com', // by Asuncion Buie '.axxinet.net', // by Roberta Gasper '.azimutservizi.com', // by Ethelene Brook '.azstudies.org', // by Bernardina Walden // B '.babtrek.com', // by Simonette Mcbrayer '.babycujo.com', // by Francisco Akers '.bakeddelights.com', // by Dave Evenson '.bbcart.com', // by Lucio Hamlin '.berlin-hotel-4u.com', // by Grisel Tillotson '.best-digital-phone.us', // by Meghann Crockett '.bjamusements.com', // by Lurlene Butz '.blursgsu.com', // by Weston Killian '.bookwide.net', // by Tequila Zacharias '.boreholes.org', // by Flora Reed '.breathingassociaiton.org', // by Alfred Crayton '.birdingnh.com', // by Donald Healy '.bisdragons.org', // by Lupe Cassity '.blcschools.net', // by Alycia Jolly '.bronte-foods.com', // by Kary Pfeiffer '.buckscountyneighbors.org', // by Maile Gaffney '.buffalofudge.com', // by Mable Whisenhunt '.burlisonforcongress.com', // by Luann King '.byairlinecreditcard.com', // by Cali Stevenson, "Airline credit card search" '.byplatinumcard.com', // by Pearl Cross, "Discover platinum card info" // C '.cabanes-web.com', // by Vaughn Latham '.cardko.com', // by Terris Cain, "Chase visa card search" '.cardpose.com', // by Deerward Gross, "Gm mastercard articles" '.checaloya.com', // by Susana Coburn '.calvarychapelrgvt.org', // by Karan Kittle '.cameras-esite.info', // by Karlee Frisch '.cancerkidsforum.org', // by Samson Constantino '.ccchoices.org', // by Kenia Cranford '.ccupca.org', // by Evonne Serrano '.celebratemehome.com', // by Soraya Tower '.centerfornourishingthefuture.org', // by Elisa Wilt '.chelseaartmmuseum.org', // by Kayla Vanhorn '.choose-shoes.net', // by Geoffrey Setser '.churla.com', // by Ollie Wolford '.circuithorns.co.uk', // by Nathanial Halle '.clanbov.com', // by Donell Hozier '.cnm-ok.org', // by Thalia Moye '.coalitioncoalition.org', // by Ned Macklin '.consoleaddicts.com', // by Dorla Hoy '.counterclockwise.net', // by Melynda Hartzell '.codypub.com', // by Mercedes Coffman '.comedystore.net', // by Floy Donald '.covsys.co.uk', // by Abby Jacey '.cpusa364-northsacramento.com', // by Dannette Lejeune '.craftybidders.com', // by Dannie Lazo '.credit-card-finder.net', // by Mellie Deherrera '.credit-cards-4u.info', // by Antonina Hil, "Credit cards info" '.creditcardstot.com', // by Bobby Alvarado, "Shell credit cards" '.ctwine.org', // by Hailey Knox // D '.dazyation.com', // by Louis Strasser '.deepfoam.org', // by Ethelyn Southard '.debt-fixing.com', // by Dagny Rickman '.dgmarketingwebdesign.com', // by Nubia Lea '.domainadoption.com', // by Breann Pappas '.diannbomkamp.com', // by Russel Croteau '.dictionary-spanish.us', // by Jacki Gilbreath '.dictionary-yahoo.us', // by Lili Mitchem '.digital-camera-review-esite.info', // by Milagros Jowers '.digital-cameras-esite.info', // by Milan Jolin '.dnstechnet.net', // by Tamera Oman '.drivenbydata.org', // by Katherine Noyes '.dtmf.net', // by Micki Slayton '.domainsfound.com', // by Blossom Lively // E '.ecstacyabuse.net', // by Alana Knight '.e-digital-camera-esite.info', // by Romaine Cress '.eda-aahperd.org', // by Kaliyah Hammonds '.eldorabusecenter.org', // by Annabella Oneal '.emicorporation.com', // by (Deangelo_Mikayla at marketing-support.info) '.encaponline.com', // by Patrick Keel '.ez-shopping-online.com', // by Gail Bartlett // F '.faithfulwordcf.com', // by Bart Weeks '.fammedassoc.com', // by Joshua Nelson '.federalministryoffinance.net', // by Jeffry Mcmillan '.f00k.org', // by Leslie Chapman '.foreignrealtions.org', // by Krystal Hawley '.fortwebsite.org', // by Kristina Motley '.fotofirstdigital.com', // by Tad Whitfield '.foundationcommons.org', // by Caryn Eskew '.fraisierest-alexandre.com', // by Dwayne Douglas '.freaky-cheats.com', // by Al Klein '.free--spyware.com', // by Nikki Contreras '.french-home-finance-consultant.info', // by Santana Melton '.fuel-tax-software-advisor.info', // by Derrick Snyder // G '.gaintrafficfast.com', // by Lila Meekins '.gaygain.org', // by Shell Davila '.gcaaa.com', // by Vallie Jaworski '.generalsysteme.com', // by Cale Vogel '.generation4games.co.uk', // by Sonya Graham '.german-dictionary.us', // by Rex Daniel '.gilmerrec.com', // by Leighann Guillory '.glenthuntly-athletics.com', // by Julee Hair '.glorybaskets.com', // by Lynette Lavelle '.goconstructionloan.com', // by Willis Monahan '.gohireit.com', // by Bertha Metzger '.godcenteredpeople.com', // by Jaycee Coble // H '.healthinsuranceem.com', // by Justin Munson '.hearthorizon.info', // by Kory Session '.hegerindustrial.com', // by Toni Wesley '.herzequip.com', // by Princess Dunkle '.hglcms.org', // by Gladwin Ng '.hipanoempresa.com', // by Shannon Staub '.hitempfurnaces.com', // by Rebbeca Jaeger '.horse-racing-result.com', // by Rodney Reynolds '.hueckerfamily.com', // by Hershel Sell // I '.ilove2win.com', // by Lamont Dickerson '.ilruralassistgrp.org', // by Moises Hauser '.imageonsolutions.com', // by Porsche Dubois '.infoanddatacenter.com', // by Eva Okelley '.islamfakta.org', // by Goldie Boykin '.ithomemortgage.com', // by Adelaide Towers '.iyoerg.com', // by Madyson Gagliano // J '.jeffaxelsen.com', // by Daphne William '.jeffreyf.net', // by Vito Platt '.johnmartinsreality.com', // by Pamela Larry '.johnsilvers.net', // by Silver Battaglia // K '.kcgerbil.org', // by Marisa Thayer '.kdc-phoenix.com', // by Salma Shoulders '.kingscreditcard.com', // by Sean Parsons, "Credit card info" '.kosove.org', // by Darwin Schneider // L '.leading-digital-camera-esite.info', // by Charles Moore, "Online home loan articles" '.letsgokayaking.net', // by Winnie Adair '.libertycabs.com', // by Adela Bonds '.liquor-store-cellar.info', // by Hugh Pearson '.locomojo.net', // by Marco Harmon '.lodatissimo.com', // by Adrian Greeson '.lsawc.org', // by Lara Han '.lycos-test.net', // by Rigoberto Oakley // M '.macro-society.com', // by Venessa Hodgson '.marthasflavorfest.com', // by Ahmad Lau '.martin-rank.com', // by Cathleen Crist '.maryandfrank.org', // by Theodore Apodaca '.masterkwonhapkido.com', // by Misty Graham '.maxrpm-demo.com', // by Cristal Cho '.mechanomorphic.com', // by Stanford Crow '.mepublishing.net', // by Karly Fleenor '.meyerlanguageservices.co.uk', // by Breana Kennedy '.metwahairports.com', // by Nan Kitchen '.middle-eastnews.com', // by Tybalt Altmann '.mikepelchy.com', // by Sherly Pearson '.milpa.org', // by Nelly Aguilera '.modayun.com', // by Camilla Velasco '.moonstoneerp.com', // by Garret Salmon '.morosozinho.com', // by Lenore Tovar '.morphadox.com', // by Hung Zielinski '.moscasenlared.com', // by Tera Gant '.sdjavasig.com', // by Gia Swisher '.mpeg-radio.com', // by Sincere Beebe '.mrg-now-yes.com', // by Sparkle Gallegos '.mtseniorcenter.org', // by Frederic Ortega '.mysteryclips.com', // by Edward Ashford // N '.naavs.org', // by Yuridia Gandy '.naval-aviation.org', // by Roselle Campo '.navigare-ischia.com', // by Arielle Coons '.ncredc.org', // by Brenda Nye '.neonmotorsports.com', // by Giovanna Vue '.nf-ny.com', // by Yadira Hibbard '.ngfdyqva.com', // by Emiliano Samples '.nicozone.com', // by Blaine Shell '.nmbusinessroundtable.org', // by Chantel Mccourt '.npawny.org', // by Willard Murphy '.nysdoed.org', // by Elric Delgadillo '.nyswasteless.org', // by Shaylee Moskowitz '.nytech-ir.com', // by Adrien Beals // O '.oadmidwest.com', // by Gavin Kaplan '.oarauto.com', // by Susann Merriman '.onairmilescard.com', // by Tomoko Hart, "Air miles card information" '.onbusinesscard.com', // by Farris Lane, "Gm business card" '.oncashbackcreditcard.com', // by Ida Willis, "Cash back credit card articles" '.onimagegoldcard.com', // by Roxanna Sims, "Imagine gold mastercard information" '.online-pills-24x7.biz', // by Aide Hallock '.online-shopping-site-24x7.info', // by Stacy Ricketts '.onlinehomeloanrefinance.com', // by Chaz Lynch '.onlinehomeloanfinancing.com', // by Humbert Eldridge '.onunicarehealthinsurance.com', // by Lawerence Paredes '.otterbayweb.com', // by Maxwell Irizarry // P '.painting-technique.us', // by Bryanna Tooley '.pakamrcongress.com', // by Bryce Summerville '.patabney.com', // by Kailyn Slone '.parde.org', // by Ellie Yates '.participatingprofiles.com', // by Jaelynn Meacham '.partnershipconference.org', // by Alla Floyd '.pet-stars.com', // by Carmon Luevano '.planning-law.org', // by Trista Holcombe '.ppawa.com', // by Evonne Scarlett '.precisionfilters.net', // by Faustina Fell // Q '.qacards.com', // by Perye Estrada, "Citi visa cards" '.quick-debt-consolidation.net', // by Lala Marte '.quicktvr.com', // by Vernell Crenshaw // R '.radicalsolutions.org', // by Reece Medlin '.randallburgos.com', // by Bradly Villa '.rcassel.com', // by Janiah Gallant '.rearchitect.org', // by Marcus Gaudet '.rent-an-mba.com', // by Valentina Mcdermott '.reprisenashville.com', // by Hester Khan '.reptilemedia.com', // by Alicia Patel '.resellers2000.com', // by Dedra Kennedy '.reverse-billing.com', // by Lazaro Gluck '.richcapaldi.com', // by Kya Haggard '.richformissouri.com', // by Alanna Elston '.robstraley.com', // by Leida Bartell '.rollingprairie-candlecompany.com', // by Leigha Aker '.rpgbbs.com', // by Leonel Peart '.ruralbusinessonline.org', // by Lynsey Watters '.ruwomenscenter.org', // by Vince Mclemore '.ryanjowens.com', // by Janine Smythe // S '.sagarmathatv.org', // by Liam Funke '.sakyathubtenling.org', // by Liane Falgout '.sandiegolawyer.net', // by Linnie Sommervill '.sandishaven.com', // by Lino Soloman '.scienkeen.com', // by Liza Navarra '.seimenswestinghouse.com', // by Teresa Benedetto '.severios.com', // by Isa Steffen '.sexual-hot-girls.com', // by Viviana Bolton '.shakespearelrc.com', // by Luciana Weaver '.shashran.org', // by Adriel Humphries '.shoes-shop.us', // by Austen Higginbotham '.skagitvalleybassanglers.com', // by Necole Thiele '.skinsciencesalon.com', // by Nena Rook '.smartalternative.net', // by Nicki Lariviere '.sml338.org', // by Nickole Krol '.smogfee.com', // by Sienna Kimble '.sneakers-e-shop.info', // by Nikki Fye '.spacewavemedia.com', // by Thanh Gast '.softkernel.com', // by Nicol Hummer '.stjoanmerrillville.com', // by Hunter Beckham '.strelinger.com', // by Arron Highsmith '.striking-viking.com', // by Kylie Endsley '.sunnydeception.org', // by Amaya Llora '.sunzmicro.com', // by Goddard Arreola '.sv-iabc.org', // by Braden Buck '.sykotick.com', // by Pierce Knecht // T '.tbody.net', // by Ormond Roman '.the-pizzaman.com', // by Mario Ramsey '.the-shoes.us', // by Alejandro Gaffney '.theborneocompany.com', // by Bryanna Tooley '.theflashchannel.com', // by Terrilyn Tam, "Loan financing info" '.thehomeschool.net', // by September Concepcio '.thenewlywed.com', // by Allegra Marra '.tigerspice.com', // by Denis Mosser '.tnaa.net', // by Jasmine Andress '.top-finance-sites.com', // by Maryann Doud '.tradereport.org', // by Bettie Sisk '.transmodeling.com', // by Martine Button '.travel-01.net', // by Jay Kim, "Refinance on line" '.tsaoc.com', // by Heriberto Mcfall '.tsunamidinner.com', // by Nannie Richey // U '.uhsaaa.com', // by Risa Herbert '.ultradeepfield.org', // by Bobby Ragland '.umkclaw.info', // by Cammy Kern '.unitedsafetycontainer.com', // by Shreya Heckendora '.usa-wolf.com', // by Jacklyn Morrill '.usjobfair.com', // by Lorina Burchette // V '.vacancesalouer.com', // by Loris Bergquist '.vagents.com', // by Lorna Beaudette, "Refinancing home loan info" '.valleylibertarians.org', // by Lena Massengale '.vanderbiltevents.com', // by Gannon Krueger '.vanwallree.com', // by Michelina Donahue '.vcertificates.com', // by Hyun Lamp '.vonormytexas.us', // by Suzette Waymire // W '.washingtondc-areahomes.net', // by Ailene Broome '.web-hosting-forum.net', // by Deedra Breen, "Mortgage information" '.wolsaoh.org', // by Daniela English '.worldpropertycatalog.com', // by Aray Baxter // Y '.yankee-merchants.com', // by Jackson Hinojosa '.yourbeachhouse.com', // by Dedrian Ryals '.yourdomainsource.com', // by Deems Weingarten // Z '.zkashan.com', // by Evan Light '.zockclock.com', // by Dorothea Guthrie ), 'Something-Drugs' => array( // Drugs / Pills / Diet '.adult-dvd-rental-top-shop.info', // by Gregoria Keating '.abdelghani-shady.com', // by Elly Alton '.bangbangfilm.com', // by Davin Chou '.centroantequera.com', // by Keon Kwiatkowski '.champagne-cellar.info', // by Kandis Rizzo '.chix0r.org', // by Christoper Baird '.discout-watches-deals.info', // by Taunya Limon, Insurance -> Drugs? '.fantasticbooks-shop.com', // by Kermit Ashley '.fast-cash-01.com', // by Edgar Oliver '.ficeb.info', // by Vaughn Jacobson, "Phentermine news" '.fn-nato.com', // by Donny Dunlap '.gqyinran.com', // by Alejandro Parks '.juris-net.com', // by Rachelle Bravo '.leftpencey.com', // by Aileen Ashby '.miamicaribbeancarnival.com', // by Herminia Barrios '.nike-shoes-e-shop.info', // by Machelle Groce, "Phentermine" '.palaceroyale.net', // by Brycen Stebbins '.pocket-watches-deals.info', // by Dorinda Stromberg '.regresiones.net', // by Lauralee Smtih, "Online phentermine updates" '.yukissushi.com', // by Donell Hozier ), 'Something-Others' => array( '.consulting-cu.com', // by Albina Rauch, 404 not found '.dvd-rentals-top-shop.info', // by Lashunda Pettway, 404 not found ), 'Something-NoApp' => array( '.auctioncarslisting.com', // "No application configured at this url." by John Davis '.buy-cheap-hardware.com', // "No application configured at this url." by Tim Morison (domains at sunex.ru) '.carsgarage.net', // "No application configured at this url." by Zonen Herms, and Jimmy Todessky (seomate at gmail.com) '.digitshopping.net', // "No application configured at this url." by Zonen Herms, and Jimmy Todessky (seomate at gmail.com) '.your-insurance.biz', // "No application configured at this url." by Jimmy Todessky (seomate at gmail.com) ), 'Cortez and family' => array( // by Cortez Shinn (info at goorkkjsaka.info), or Rico Laplant (info at nnjdksfornms.info) '.dronadaarsujf.info', // by Cortez '.fromnananaref.info', // by Cortez '.goorkkjsaka.info', // by Cortez '.jkdfjjkkdfe.info', // by Rico '.jkllloldkjsa.info', // by Cortez '.nnjdksfornms.info', // by Rico '.mcmdkkksaoka.info', // by Cortez '.srattaragfon.info', // by Cortez '.yreifnnonoom.info', // by Rico '.zjajjsvgeuds.info', // by Cortez ), 'admin at ematuranza.com' => array( '.ancorlontano.com', '.dentroallago.com', '.digiovinezza.com', '.ematuranza.com', '.ilfango.com', '.nullarimane.com', '.questaimmensa.com', '.tentailvolo.com', '.unatenerezza.com', '.volgondilettose.com', ), 'admin at edeuj84.info' => array( // by Cornelius Boyers '.bid99df.info', '.bj498uf.info', '.edeuj84.info', '.f4mfid.info', '.g4vf03a.info', '.j09j4r.info', '.jv4r8hv.info', '.k43sd3.info', '.k4r84d.info', '.k4rvda.info', '.k4v0df.info', '.k903os.info', '.k9df93d.info', '.kv94fd.info', '.ksjs93.info', '.l0ks03.info', '.l9u3jc.info', '.lv043a.info', '.nh94h9.info', '.m94r9d.info', '.s87fvd.info', '.v3k0d.info', '.v4r8j4.info', '.vf044s.info', '.vj49rs.info', '.vk498j.info', '.u03jow.info', ), 'Nikhil and Brian' => array( // by Brian Dieckman (info at iudndjsdhgas.info) // by Nikhil Swafford (info at jhcjdnbkrfo.info) // by Gerardo Figueiredo (info at jikpbtjiougje.info) '.ihfjeswouigf.info', // by Brian, / was not found '.iudndjsdhgas.info', // by Brian, / was not found '.iufbsehxrtcd.info', // by Brian, / was not found '.jiatdbdisut.info', // by Brian, / was not found '.jkfierwoundhw.info', // by Brian, / was not found '.kfjeoutweh.info', // by Brian, / was not found '.ncjsdhjahsjendl.info',// by Brian, / was not found '.oudjskdwibfm.info', // by Brian, / was not found '.cnewuhkqnfke.info', // by Nikhil, / was not found '.itxbsjacun.info', // by Nikhil, / was not found '.jahvjrijvv.info', // by Nikhil (info at jikpbtjiougje.info), / was not found '.jhcjdnbkrfo.info', // by Nikhil, / was not found '.najedncdcounrd.info', // by Nikhil, / was not found '.mcsjjaouvd.info', // by Nikhil, / was not found '.oujvjfdndl.info', // by Nikhil, / was not found '.uodncnewnncds.info', // by Nikhil, / was not found '.jikpbtjiougje.info', // by Julio Mccaughey (info at jikpbtjiougje.info), / was not found '.cijkalvcjirem.info', // by Gerardo, / was not found '.nkcjfkvnvpow.info', // by Gerardo, / was not found '.nmiiamfoujvnme.info', // by Gerardo, / was not found '.nxuwnkajgufvl.info', // by Gerardo, / was not found '.mkjajkfoejvnm.info', // by Gerardo, / was not found ), 'wealth777 at gmail.com' => array( // by Henry Ford '.brutal-forced.com', '.library-bdsm.com', '.rape-fantasy.us', ), 'Croesus International Inc.' => array( // by Croesus International Inc. (olex at okhei.net) '.purerotica.com', '.richsex.com', '.servik.net', '.withsex.com', ), 'dreamteammoney.com' => array( '.dreamteammoney.com', // dtmurl.com related '.dtmurl.com', // by dreamteammoney.com, redirection service ), 'KLIK VIP Search and family' => array( '.cheepmed.org', // "KLIK VIP Search" by petro (petrotsap1 at gmail.com) '.fastearning.net', // "KlikVIPsearch.com" by Matthew Parry (fastearning at mail.ru) '.klikvipsearch.com', // "KLIKVIPSEARCH.COM" by Adrian Monterra (support at searchservices.info) '.looked-for.info', // "MFeed Search" now, by johnson (edu2006alabama at hotmail.com) '.mnepoxuy.info', // "KlikVIPsearch.com" by DEREK MIYAMOTO (grosmeba at ukr.net) '.searchservices.info', // 403 Forbidden now, by Adrian Monterra (support at searchservices.info) '.visabiz.net', // "Visabiz-Katalog-Home" now, by Natalja Estrina (m.estrin at post.skynet.lt) ), 'vasyapupkin78 at bk.ru' => array( // by Andrey Kozlov '.antivirs.info', '.antivirus1.info', '.antivirus2.info', ), 'wasam at vangers.net and family' => array( // 69.31.82.51(colo-69-31-82-51.pilosoft.com) by Kadil Kasekwam (kadilk at vangers.net) '.bahatoca.org', '.digestlycos.org', '.educativaanale.info', '.guildstuscan.org', '.isaakrobbins.info', '.isfelons.org', '.lvwelevated.org', '.macphersonaca.org', '.markyaustrian.org', '.michelepug.org', '.opalbusy.info', '.quijotebachata.info', '.salthjc.info', '.shogunnerd.info', '.solarissean.org', '.sparkgsx.info', '.tarzanyearly.org', '.tulabnsf.org', '.vaccarinos.org', // 69.31.82.53(colo-69-31-82-53.pilosoft.com) by Bipik Joshu (bipik at vangers.net) '.e2007.info', '.cmoss.info', // 69.31.82.53(colo-69-31-82-53.pilosoft.com) by Kasturba Nagari (kasturba at vangers.net) '.finddesk.org', '.gsfind.org', // You mean: sfind.net by tvaals at vangers.net '.my-top.org', // You mean: my-top.net by tvaals at vangers.net '.rcatalog.org', '.sbitzone.org', // 69.31.82.53(colo-69-31-82-53.pilosoft.com) by Thomas Vaals (tvaals at vangers.net) '.cheapns.org', '.my-top.net', '.sfind.net', '.sspot.net', '.suvfind.info', // 69.31.82.53 by Mariano Ciaramolo (marion at vangers.net) '.trumber.com', // 69.31.82.53(colo-69-31-82-53.pilosoft.com) by Ashiksh Wasam (wasam at vangers.net) '.blogduet.org', '.carelf.info', '.cmagic.org', '.cspell.org', '.dspark.org', '.dtonic.org', '.mcharm.info', '.mslook.info', '.phpdinnerware.info', '.rnation.org', '.uzing.org', // 69.31.91.226(colo-69-31-91-226.pilosoft.com) by Kadil Kasekwam (kadilk at vangers.net) '.allbar.info', '.allersearch.org', '.allzoom.org', '.dynall.org', '.fastopia.org', '.offasfast.info', '.rblast.org', '.rchistes.info', '.rette.org', '.shufflequince.org', '.suvlook.org', // 69.31.91.226(colo-69-31-91-226.pilosoft.com) by Ashiksh Wasam (wasam at vangers.net) '.290cabeza.org', '.bossierpainted.org', '.connickkarel.info', // Admin: tvaals at vangers.net '.definekonica.info', // Admin: tvaals at vangers.net '.gradetelemundo.info', '.hydraulickin.info', '.indicadorestmj.info', '.keeleykincaid.org', '.kleenbowser.info', '.pipnickname.info', '.pacolily.org', '.redeemtrabalho.info', '.scanmakerchua.info', '.titanmessina.info', '.tragratuit.org', '.yeareola.info', ), 'SearchHealtAdvCorpGb.com' => array( // by Jonn Gardens (admin at SearchHealtAdvCorpGb.com -- no such domain) '.canadianmedsworld.info', // 84.252.133.112 '.tabsdrugstore.info', // 84.252.133.114 '.tabsstore.info', // 84.252.133.114 '.topcholesterol.info', // 84.252.133.132 ), 'be.cx' => array( '.be.cx', '.ca.cx', ), 'john780321 at yahoo.com' => array( // by John Brown '.bestdiscountpharmacy.biz', // 2007-01-27, 61.144.122.45 '.drugs4all.us', // 2007-03-09, 202.67.150.250 '.online-pharmacy-no-prescription.org', // 69.56.135.222(de.87.3845.static.theplanet.com) ), 'tremagl.freet at gmail.com' => array( // by Treman Eagles, redirect to searchadv.com '.bertela.info', '.forblis.info', '.frenallo.info', '.goyahoo.info', '.herbak.info', '.kiokast.info', '.nerenok.info', '.pestgets.info', '.snukker.info', '.thegetspons.info', ), '2xxc at 2xxc.net' => array( // by 2xxc, 404 not found '.bobop.info', '.kwwwe.info', '.piikz.info', '.moosm.info', '.vvvw.info', ), 'support at 51g.net' => array( // iframe www.lovetw.webnow.biz '.ftplin.com', // 125.65.112.15, by Yongchun Liao '.jplin.com', // 125.65.112.15, by Yongchun Liao '.jplineage.com', // 221.238.195.113, by Yongchun Liao '.jplingood.com', // 125.65.112.15 '.linenew.com', // 203.191.148.96 '.lyftp.com', // 218.5.77.17, by Yongchun Liao (weboy at 51g.net) '.yzlin.com', // 220.162.244.36 ), 'Betty.J.Pelletier at pookmail.com' => array( // by Betty J. Pelletier '.1111mb.com', '.2sex18.com', '.69porn1.com', ), 'ECTechnology' => array( '.atmouse.co.kr', // by EG gisul (kpgak at hanmail.net) '.auto-mouse.com', // "Copyright Ò$ 2007 www.automouse.jp" by ECTechnology (help at atmouse.co.kr) '.automouse.jp', ), 'lyqz at 21cn.com' => array( '.japangame1.com', '.lineinfo-jp.com', // www.lineinfo-jp.com is 61.139.126.10 '.livedoor1.com', '.ragnarokonline1.com', '.zhangweijp.com', // by qiu wang hao (qq.lilac at eyou.com), *.exe, hidden JavaScripts, the same IP of www.lineinfo-jp.com ), 'kingrou at hotmail.com' => array( // by yangjianhe '.youshini.com', // Two iframe to 453787.com's *.exe '.453787.com', ), 'anpaul541000 at 163.com' => array( // by su qiuqing '.cetname.com', // 222.77.185.87 '.jpgamer.net', // 220.247.157.106 '.jpplay.net', // 222.77.185.87, iframe www.lovetw.webnow.biz '.lovejptt.com', // 222.77.185.87 '.pangzigame.com', // 220.247.134.136, by qiuqingshan '.playncsoft.net', // 220.247.157.106 ), 'abc00613 at 163.com' => array( // by guo yong '.avtw1068.com', // 64.74.223.11 '.dj5566.org', // Seems IP not allocated now, by yongchao li '.djkkk66990.com', // 68.178.232.99 '.lingamesjp.com', // 219.153.13.23(8.myadmin.cn), by guo jinlong ), 'thomas.jsp at libertysurf.fr' => array( // by Perez Thomas '.cmonfofo.com', '.discutbb.com', ), 'Dorothy.D.Adams at mailinator.com' => array( // by Dorothy D. Adams '.preca.info', '.skiaggi.info', '.scrianal.info', '.tageom.info', ), 'Inpros.net' => array( // by Hayato Hikari (hikari at t-dm.co.jp) '.inpros.biz', // 38.99.91.137, redirect to inpros.net '.inpros.net', // 202.181.98.79 '.gametradeonline.jp', // 210.188.204.233, by Hayato Hikari, RMT ), 'szczffhh_sso at 21cn.net' => array( // by zhenfei chen '.ec51.com', '.ec51.net', ), 'abbevillelaties at yahoo.fr etc' => array( // by Mahat Ashat, JavaScript may mocks "ACCOUNT TERMINATE", or "Domain deleted Reason: ABUSE" but ... '.ringtones-rate.com', '.ringtones-dir.net', // by Alex Maklayt (maklayt at ringtones-dir.net), hidden JavaScript '.special-ringtones.net', ), 'gibson or gibs0n at skysquad.net' => array( // by Brzezinski Bartosz (gibson at skysquad.net), redirect to find.fm '.1sgsc.info', '.3h4r89h.info', '.3v44dd.info', '.6rfuh6.info', '.84hd8.info', '.94bui89.info', '.agysb3.info', '.asdjhs.info', '.bcvnrth.info', '.bheb4r.info', '.bhiuno.info', '.biug7g.info', '.bjb5f4.info', '.bob8g7g.info', '.br89bdd.info', '.bsa3h.info', '.bsieb8.info', '.basbiubf.info', '.bobwwfs2.info', '.ciuv9t.info', '.dbmdx4.info', '.dbrjms.info', '.dbtcm.info', '.dff9ghu.info', '.dfshbb.info', '.dgd4ffdh.info', '.dh3ge.info', '.duc86jh.info', '.ergth45.info', '.f78bf7ffb.info', '.gbdfbo4.info', '.ger45.info', '.gnvnrrg.info', '.h47he7.info', '.h488hbd4.info', '.hd72b94.info', '.he74b7.info', '.hfujfnr.info', '.husdhd42.info', '.hbwje.info', '.itg87gji.info', '.iugiougiuh.info', '.jhd4f4aa.info', '.jshd73.info', '.krhpgd.info', '.lyihjn.info', '.nfyjnfj.info', '.oihbv.info', '.os44fvs.info', '.sdfsd3.info', '.sdiug4.info', '.sdkufhh.info', '.sdugb4f.info', '.skdbf.info', '.sipiv78.info', '.sudbfb.info', '.tymbbmy.info', '.uilhjk.info', '.vi87vub.info', '.vfuyf87f.info', '.viyvvj877.info', '.w7fc8eu.info', '.wefg43g.info', '.xbrch78e.info', '.ywsfu.info', '.zxcbiv.info', ), 'info at infooracle.com' => array( // by Marek Luto Marek Luto '.abofios.info', '.amlekfn.info', '.amlkdoie.info', '.amkslewq.info', '.alemfu.info', '.aloweks1.info', '.alposd3.info', '.bamhpb.info', '.bhjkb.info', '.bjqnj.info', '.cvcxcbhpr.info', '.czoypaiat.info', '.dbpmgc.info', '.dgvogrxs.info', '.dldksf.info', '.dlor6za.com', '.dmkoiew.info', '.eewrefr.info', '.eladne.info', '.elksem.info', '.elwpod.info', '.emlwkdnr.info', '.esgmyqk.info', '.fauqv.info', '.fgxkgy.info', '.fhryns.info', '.fj38n4g.info', '.fjnesal.info', '.fmkfoe.info', '.fqkcfldtr.info', '.fwcigpdwz.info', '.fyhik.info', '.glrkje.info', '.gwkslfq.info', '.gwjracvh.info', '.hihopepe.info', '.hwlyggbkw.info', '.hmwbfw.info', '.hthyeb.info', '.iaofkyaw.info', '.uldkxuiw.info', '.is7c6w4.info', '.ivuddhdk.info', '.jgfndjem.info', '.jgmdlek.info', '.jkrnvmpad.info', '.jqujn.info', '.jvgmmba.info', '.kbaur.info', '.kgjindptv.info', '.kleo7s9.info', '.lezfgam.info', '.lfaasy.info', '.ljpdjki.info', '.lmnpis.info', '.lpzcu2f.info', '.lrptn.info', '.lursqt.info', '.mgkabviil.info', '.mhtknjyt.info', '.mksuuku.info', '.mkyky.info', '.mloaisn.com', '.mlsiknd.info', '.mthqz.info', '.nnooq.info', '.nohhylvc.info', '.nuprndsye.info', '.nsoelam.info', '.nykobczv.info', '.nzuhli.info', '.odyqzgylr.info', '.oidiau.info', '.oitzkw.info', '.okdmrpz.info', '.ooinziti.info', '.ortqr.info', '.osmkpnekv.info', '.ozkzfih.info', '.p3ix8wc.com', '.piwyt.info', '.pfkijrm.info', '.pjktcragi.info', '.pleoz.info', '.plvqm73.info', '.pqyrem.info', '.qipgqd.info', '.qlewixu.com', '.qmlskme.info', '.qtuff.info', '.quoga.info', '.quqz.info', '.qzxuw.info', '.rcaidegp.info', '.rlkmdi.info', '.rnsoiov.info', '.rnwlams.info', '.rprgkgqld.info', '.rubqvxrn.info', '.spqxstl.info', '.syckoqjql.info', '.tbirb.info', '.thalc34.info', '.tiabq.info', '.tszzpjr.info', '.tyjdyn.info', '.twgugpns.info', '.uaezrqp.info', '.udlkasu.info', '.uejncyf.info', '.ukvflb.info', '.ugsuv.info', '.ukhgpcp.info', '.urprzn.info', '.uuhememkw.info', '.yalc7en.info', '.ybuid.info', '.yhdkgfob.info', '.ymenq.info', '.ynlyb.info', '.vieatlubk.info', '.vltcaho.info', '.wlamsiek.info', '.wlerp.info', '.wlmtshzi.info', '.wmlkams.info', '.wprqd.info', '.wpyspszi.info', '.xdscc.info', '.xdvy.info', '.xeypku.info', '.xsrxh.info', '.xwjyrpfe.info', '.yxcqw.info', '.zhbktrh.info', '.zspepn.info', '.zsxtz.info', ), 'survi at poczta.fm and smiley' => array( '.pperd.info', // "main site :>" by Domagala Andrzej (survi at poczta.fm) '.ppert.info', '.pperta.info', '.pperts.info', '.pprtuis.info', '.13iuey.info', // ":>" '.13jkhs.info', '.13lksa.info', '.13rxtx.info', '.13slkd.info', '.13zaer.info', ), 'admin at esemeski.com' => array( // by Jan Kalka '.kxils.info', '.kuaph.info', '.lncdc.info', '.lsqpd.info', '.mczed.info', '.npous.info', '.obgju.info', ), 'LiquidNetLimited.com' => array( // liquidnetltd.net, // 216.65.1.131(duoservers.com) // FateBack.com related // 216.65.1.201(fateback.com) by LiquidNet Ltd. (president at fateback.com), redirect to www.japan.jp '.bebto.com', '.fateback.com', '.undonet.com', '.yoll.net', // 50webs.com // 64.72.112.10 // dns2.50webs.com // 64.72.112.11 '*.freehostia.com', // 64.72.112.12, many related hosts surrounded, http://freehostia.com/about_us.html says "... partnership with the UK-based LiquidNet Ltd., and ..." // dns2.freehostia.com // 64.72.112.13 // serv3.freehostia.com // 64.72.112.14 // hex12.freehostia.com // 64.72.112.19, 64.72.112.20 // mail.50webs.com // 64.72.112.26 // supremecenter41.com // 64.72.112.52 // 50webs2.50webs.com // 64.72.112.89 // supremecenter39.com // 64.72.112.103 // by LiquidNet Ltd. (support at propersupport.com) '*.50webs.com', // 64.72.112.10, redirect to mpage.jp, listed in http://www.liquidnetlimited.com/services.html // propersupport.com // 216.65.1.129(dns1.supremecenter.com) 'duoservers.com', // 216.65.1.130 // 100ws.com // No-ip by LiquidNet Ltd. (ceo at propersupport.com) ), 'domains at agava.com' => array( '.h18.ru', '.hut1.ru', ), 'wlmx009 at hotmail.com' => array( '.123lineage.com', '.ff11-info.com', '.lastlineage.com', '.lineage2-ol.com', '.lineage2006.com', '.lineagefirst.com', ), 'Zettahost.com' => array( '.atspace.biz', // sales at zettahost.com '.atspace.com', // abuse at zettahost.com '.atspace.name', // NS atspace.com '.awardspace.com', // by abuse at awardspace.com, no DirectoryIndex, 70.86.228.149 '.awardspace.us', // by Dimitar Dimitrov (sales at zettahost.com), 70.86.228.149 ), 'hlq9814 at 163.com' => array( '.kotonohax.com', // by ling bao '.ragnarox.mobi', // by lin bao, *.exe download '.rokonline-jp.com', // by hang long ), '77ch.jp' => array( '.77ch.jp', '.gamorimori.net', // by ryo takami (infomation at 77ch.jp) ), 'serchportal at mail.ru' => array( // by Namu Adin '.43fert.info', '.belis.info', '.bonu.info', '.chelsite.info', '.chparael.info', '.cool9f.info', '.dada2.info', '.dorplanete.info', '.dormonde.info', '.dorprojet.info', '.faciledor.info', '.fastsearchgroup.info', '.gerta0.info', '.getse.info', '.gopvl.info', '.knopki.info', '.propidor.info', '.quicksearchnet.info', '.ret5.info', '.slimfastsearch.info', '.virtualpvl.info', '.vpvla.info', '.xjdor.info', '.zhopki.info', ), 'SoniqHost.com' => array( // by Stanley Gutowski (support at soniqhost.com) '*.444mb.com', // Free hosting 'urlnip.com', // Redirection ), 'WWW.RU' => array( // by Angela (abuse at www.ru) '.1fasttimesatnau.info', '.1freecybersex.info', '.1freexxxcomics.info', '.1fuckingmywife.info', '.1pornpreview.info', 'www.ru', // by (service at demos.ru), redirection ), '65.90.250.10' => array( // IP seems the same (65.90.250.10) '.adultschat.info', '.livecamonline.info', '.webcam4u.info', '.younghot.info', ), 'hostorgadmin at googlemail.com' => array( // Byethost Internet Ltd. '.yoursupportgroup.com', // 72.36.219.162(*.static.reverse.ltdomains.com) // 209.51.196.242 '.22web.net', '.2kool4u.net', '.9skul.com', '.alojalo.info', '.byet.net', '.byethost2.com', '.byethost3.com', '.byethost4.com', '.byethost5.com', '.byethost6.com', '.byethost7.com', '.byethost8.com', '.byethost9.com', '.byethost10.com', '.byethost11.com', '.byethost12.com', '.byethost13.com', '.byethost14.com', '.byethost15.com', '.byethost16.com', '.byethost17.com', '.byethost18.com', '.headshothost.net', '.hostwq.net', '.mega-file.net', '.truefreehost.com', '.ifastnet.com', // 209.51.196.243 // 209.190.16.82(mx1.byet.org) '.1sthost.org', '.4sql.net', '.byet.org', '.hyperphp.com', '.kwikphp.com', '.my-php.net', '.my-place.us', '.my-webs.org', '.netfast.org', '.php0h.com', '.php1h.com', '.php2h.com', // by Andrew Millar (asmillar at sir-millar.com), ns also *.byet.org '.phpnet.us', '.prohosts.org', '.pro-php.org', '.prophp.org', '.sprinterweb.net', '.swiftphp.com', '.xlphp.net', // 209.190.16.83(mx2.byet.org) '.instant-wiki.net', // 209.190.16.84(mx3.byet.org) // 209.190.16.85(mx4.byet.org) '.instant-blog.net', '.instant-forum.net', '.byethost.com', // 209.190.18.138 ), 'webmaster at bestgirlssex.info' => array( // by lemnaru ionut, ns *.hostgator.com '.analmoviesite.info', '.bestgirlssex.info', '.boxvagina.info', '.cyberlivegirls.info', '.hotredgirls.info', '.forsexlove.info', '.hotnudezone.info', '.hotredpussy.info', '.lesbians-live.info', '.lesbians-on-cam.info', '.onlinegirlssite.info', '.sexloveonline.info', '.teensexcard.info', '.teensexdirect.info', '.topnudesite.info', '.vaginafree.info', '.webcam-show.info', '.webcamshow.info', '.youngsexchat.info', '.yourcumshot.info', ), 'stocking.club at gmail.com' => array( '.adulthotmodels.com', // by David Zajwzran '.aretheshit.info', // by David Theissen (zjwzra at mail.ru) '.cash-call.info', // by David Theissen '.cialis-compare-levitra-viagra.info', // by David Theissen '.cheap-online-viagra.info', // by David Theissen '.drugcleansing.net', // by David Zajwzran '.men-health-zone.com', // by David Theissen '.purchase-viagra.info', // by David Theissen '.realdrunkengirls.biz', // by David Theissen '.sextoyslife.com', // by David Zajwzran '.sexysubjects.info', // by David Zajwzran '.shithotsex.info', // by David Theissen (zjwzra at mail.ru) '.stocks-trader.info', // by David Theissen (zjwzra at mail.ru) '.travelcardsite.info', // by David Theissen ), 'lustiq at p5com.com' => array( '.wonkalook.com', // ns *.willywonka.co.in, 85.255.117.226 '.willywonka.co.in', // by Nick Priest (lustiq at p5com.com), 85.255.117.226 ), 'web at 6jy.com' => array( '.micro36.com', // by Teng Zhang, content from lineage.jp, post with 'lineage1bbs.com' '.movie1945.com', // by Zhang Teng, content from lineage.jp, hidden JavaScript ), 'mk_slowman at yahoo.com' => array( // by Mike Slowman (mk_slowman at yahoo.com) '.auto-fgen.info', '.fast-marketing.info', '.from-usa.info', '.generic-pharm.info', '.pharm-directory.info', '.popular-people.info', '.safe-health.info', '.star-celebrities.info', '.super-home-biz.info', '.top5-auto.info', '.top5-cars.info', '.vip-furniture.info', '.vip-pc.info', '.vip-pets.info', ), 'abuse at search-store.org' => array( '.travel-gen.info', // by Mike Slowman (abuse at search-store.org) ), 'Leading Edge Marketing Inc.' => array( // by Leading Edge Marketing Inc. (domains at leminternet.com), seems an advertiser '.abemedical.com', '.attractwomennow.com', '.bettersexmall.com', '.buymaxoderm.com', '.buyvprx.com', '.genf20.com', '.infinityhealthnews.com', '.istnewsletter.com', '.leadingedgecash.com', '.leadingedgeherbals.com', '.leadingedgevipsonly.com', '.lecash.com', '.leminfo.com', '.proextendersystem.com', '.provestra.com', '.semenax.com', '.shavenomore.com', '.theedgenewsletter.com', '.vigorelle.com', '.vigrx.com', '.vigrxplus.com', '.wbstnewsletter.com', ), 'clickx at bk.ru' => array( // by Alexey Enrertov '.coolget*.info' => '#^(?:.*\.)?' . 'coolget' . '(?:bus|find|news|php|place|post|srch)' . '\.info$#', '.coolgirl*.info' => '#^(?:.*\.)?' . 'coolgirl' . '(?:apple|fish|search)' . '\.info$#', '.coolmeet*.info' => '#^(?:.*\.)?' . 'coolmeet' . '(?:apple|click|find|fish|news|php|place|post|srch|search)' . '\.info$#', '.cool**.info' => '#^(?:.*\.)?' . 'cool' . '(?:strong|the)' . '(?:apple|bus|click|find|fish|news|php|place|post|srch|search)' . '\.info$#', '.freseasy*.info' => '#^(?:.*\.)?' . 'freseasy' . '(?:apple|click|find|fish|post|search)' . '\.info$#', '.fres**.info' => '#^(?:.*\.)?' . 'fres' . '(?:adult|boy|get|girl|meet|new|real|strong|the)' . '(?:apple|bus|click|find|fish|news|php|place|post|srch|search)' . '\.info$#', // These are not found yet: // fresgirlsrch.info // fresadultapple.info // fresadultclick.info // frestheplace.info // 66.232.113.44 '.nuhost.info', '.susearch.info', // 66.232.126.74(hv94.steephost.com) '.dilej.com', '.fyvij.com', '.howus.com', '.jisyn.com', '.kaxem.com', '.mihug.com', '.mobyb.com', '.qidat.com', '.qihek.com', '.ryzic.com', '.sasuv.com', '.tuquh.com', '.vehyq.com', '.wezid.com', '.wifuj.com', '.xijyt.com', '.zuqyn.com', ), 'jakaj ay hotmail.com' => array( // 66.232.113.46, the same approach and timing of clickx at bk.ru '.hitsearching.info', '.hugeamountdata.info', '.megafasthost.info', '.real-big-host.info', '.search4freez.info', '.yasech.info', // 66.232.97.246(host4.blazegalaxy.com => 71.6.196.202) '.bymire.com', // 66.232.120.98(host.radiantdomain.com => 71.6.196.202 => fc6196202.aspadmin.net) '.ligiwa.com', ), 'ice--man at mail.ru related' => array( // 74.50.97.198 by andrey, the same approach and timing of clickx at bk.ru '.bestcreola.com', '.crekatierra.com', '.creolafire.com', '.crolik.com', '.croller.cn', '.ecrmx.com', '.eflashpoint.com', '.exoticmed.com', '.feelview.com', '.greatexotic.com', '.icrtx.com', '.icyhip.com', '.icyiceman.com', '.icypopular.com', '.iflashpoint.com', '.justmdx.com', '.kiliusgroup.com', '.klickerr.com', '.klickerrworld.com', '.kreolic.com', '.margansitio.com', '.margantierra.com', '.mimargan.com', '.oilkeys.com', '.planetmdx.com', '.thekeyse.com', '.viewgreat.com', '.yourcreola.com', // 69.46.23.48 '.bestkilius.com', '.crekadirecto.com', '.getflashsite.com', '.sucreka.com', '.superkilius.com', // 69.46.23.48 by bing-16 at ftunez.org '.bovorup.cn', '.litotar.cn', '.nihydec.cn', // 66.232.112.175 by bing-32 at ftunez.org '.lasyxy.cn', // 69.46.23.48 by clarkson-34 at ftunez.org '.bumora.cn', '.byxite.cn', '.byxuqu.cn', '.jadama.cn', '.kybope.cn', '.mefeki.cn', '.mokiso.cn', '.niqeme.cn', '.pukafo.cn', '.qesaxa.cn', '.toxezi.cn', '.tujudy.cn', '.tutike.cn', // NEUTRAL but dark: with clarkson-34 at ftunez.org, non-existent domain '.cabino.cn', '.cuwace.cn', '.ferazi.cn', '.gigywy.cn', '.lapype.cn', '.mewabe.cn', '.pezegy.cn', '.pyzuza.cn', '.qypony.cn', '.ropesy.cn', '.wadyfe.cn', // 69.46.23.48 clarkson-58 at ftunez.org '.becabe.cn', '.biciqy.cn', '.bezymu.cn', '.cifori.cn', '.ciwyxi.cn', '.dobari.cn', '.dusofe.cn', '.dutyda.cn', '.dykanu.cn', '.fakexu.cn', '.fylema.cn', '.godymo.cn', '.hyhaxy.cn', '.ganosi.cn', '.kuxyju.cn', '.lacezy.cn', '.lonyru.cn', '.lycato.cn', '.nykyby.cn', '.qyhuko.cn', '.redere.cn', '.riwimu.cn', '.wopary.cn', '.xizity.cn', '.xuxusa.cn', // 69.46.23.48 by entretov-32 at ftunez.org '.cihuji.cn', '.deqyve.cn', '.genefa.cn', '.gujyju.cn', '.hasadu.cn', '.hedomi.cn', '.kecicy.cn', '.kipabo.cn', '.manunu.cn', '.musoru.cn', '.myvuna.cn', '.pikybe.cn', '.riqawo.cn', '.rufuxy.cn', '.vyfilu.cn', '.xadule.cn', '.zolaxe.cn', '.zerixu.cn', // 66.232.112.242(hv78.steephost.com) by entretov-43 at ftunez.org '.dozoda.cn', '.nemipu.cn', // 69.46.23.48 by jeremy-57 at ftunez.org '.duzele.cn', '.figede.cn', '.fiwany.cn', '.gyfalu.cn', '.jepylo.cn', '.nuqumy.cn', // NEUTRAL but dark: with jeremy-57 at ftunez.org, non-existent domain '.burahu.cn', '.jydijy.cn', '.komyby.cn', '.najepa.cn', '.pylobu.cn', '.qofoly.cn', '.sybuvi.cn', '.vycexu.cn', '.wotyqo.cn', '.xudoli.cn', // 66.232.112.175 by entretov-86 at ftunez.org '.faweji.cn', '.jypaci.cn', '.xozuso.cn', // 69.46.23.48 by miles-37 at ftunez.org '.beqymo.cn', '.ceqibi.cn', '.dyraqo.cn', '.qenedo.cn', '.qurypa.cn', '.siluvo.cn', '.tujala.cn', '.wukuwi.cn', '.xenibo.cn', '.xiculo.cn', '.zabemu.cn', // NEUTRAL but dark: with miles-37 at ftunez.org, non-existent domain '.bevaka.cn', '.fysyte.cn', '.guxixu.cn', '.hatoli.cn', '.jitobu.cn', '.juxeca.cn', '.kifuhy.cn', '.licila.cn', '.mecomy.cn', '.niryko.cn', '.noxoco.cn', '.qiwysu.cn', '.tutysy.cn', // 66.232.112.175 by sabrosky-49 at ftunez.org '.gywiqe.cn', '.jotapo.cn', '.jywixa.cn', // '69.46.23.48 by sabrosky-60 at ftunez.org '.bawegap.cn', '.buremyl.cn', '.cilybut.cn', '.cutufek.cn', '.defypyr.cn', '.femaxij.cn', '.gelejo.cn', '.gocylyv.cn', '.kehiqaq.cn', '.ninyjit.cn', '.ruroruw.cn', '.vetehow.cn', // 69.46.23.48 sabrosky-85 at ftunez.org '.banyla.cn', '.bubaqu.cn', '.bygage.cn', '.dafozy.cn', '.kaxyjo.cn', '.makyle.cn', '.naleto.cn', '.pidele.cn', '.poqexa.cn', '.pymaqo.cn', '.qupiqy.cn', '.reqefy.cn', '.sopocy.cn', '.vuhexo.cn', '.weryso.cn', '.wubula.cn', '.xufuxy.cn', '.zuhyxu.cn', // 69.46.23.48 by tribiani-97 at ftunez.org '.dyxorod.cn', '.firywoz.cn', '.jixezyx.cn', '.joveraw.cn', '.jowaxup.cn', '.nodarej.cn', '.pimijom.cn', '.tugupeg.cn', // 66.232.112.175 by abuse-here at inbox.ru '.catybe.cn', '.jytame.cn', '.wygete.cn', ), 'nijeoi at hotmai.com' => array( // 66.232.126.74 by Nicol Makerson, the same approach and timing _and IP_ of clickx at bk.ru '.bowij.com', '.bozib.com', '.cavux.com', '.dipov.com', '.gumoz.com', '.hakyb.com', '.hehyv.com', '.hepyt.com', '.howoj.com', '.jywaz.com', '.ka4search.info', // Found at faweji.cn/ and jytame.cn/, / forbidden '.kyheq.com', '.kyzad.com', '.qicad.com', '.qubyd.com', '.mocyq.com', '.muloq.com', '.myxim.com', '.nufyp.com', '.waqog.com', '.wyduc.com', '.xefyv.com', '.xomej.com', '.xomip.com', '.xykyl.com', '.zakuw.com', '.zeliw.com', '.zimev.com', '.zipif.com', // 66.232.97.244(host2.blazegalaxy.com => 71.6.196.202) '.tycoco.com', // 66.232.97.246(host4.blazegalaxy.com => 71.6.196.202) '.pufeqa.com', ), 'niichka at hotmail.com' => array( // 66.232.113.44, the same approach and IP of clickx at bk.ru '.aerosearch.info', '.freader.info', '.info4searchz.info', '.nice-host.info', '.realyfast.info', '.resuts.info', // 66.232.126.74, the same approach and IP of clickx at bk.ru '.bepoh.com', '.gufiq.com', '.kedyh.com', '.pofyb.com', '.rurid.com', '.vucaj.com', '.vuwir.com', // 66.232.97.244(host2.blazegalaxy.com => 71.6.196.202 => fc6196202.aspadmin.net) '.bejefe.com', // 66.232.97.245(host3.blazegalaxy.com => 71.6.196.202) '.tidawu.com', // 66.232.97.247(host5.blazegalaxy.com => 71.6.196.202) '.rofuqa.com', ), 'porychik at hot.ee' => array( // by Igor '.tedstate.info', // "Free Web Hosting" '.giftsee.com', ), 'aofa at vip.163.com' => array( '.bdjyw.net', // by gaoyun, infected images, iframe to 5944.net's VBScript '.5944.net', ), 'zerberster at gmail.com' => array( // by Curtis D. Pick, / not found '.maxrentcar.info', '.newsonyericsson.info', '.pornositeworld.biz', '.rentcarweb.info', '.xxxdomainsex.biz', ), 'kopper1970 at gmail.com' => array( '.cardealerall.info', // by Green '.donatecarsales.info', // by Sipil '.ringtonewilly.info', // by Sipil '.travelstraveling.info', // by Chinik '.viagrabuyonline.org', // by Sipil '.viagraorderbuy.com', // by Anatol '.worldcuptourism.info', // by Sipil ), 'lisaedwards at ledw.th' => array( // by Lisa Edwards '.globalinfoland.info', '.goodlifesearch.info', '.hotnetinfo.info', '.hotpornmovies.org', '.infopilot.info', ), 'iisuse at gmail.com' => array( // by vladislav morozov (iisuse at gmail.com). / is spam '.bang-bro.org', '.datinghost.info', '.hello-craulers.info', '.free-blog-host.info', '.sucking-boobs.info', ), 'chub at seznam.cz' => array( // "CamsGen 1.0" by Lee Chen Ho '.allcamsguide.info', '.camerascams.info', '.camerasera.info', '.girlcamsworld.info', '.hiddenlimocams.info', '.redlivecams.info', '.spycamsgear.info', '.spycamssite.info', '.supercamsusa.info', '.thecamsnow.info', ), '87.242.116.81' => array( '.axit.ru', // by Sergej L Ivanov (deeeport at yandex.ru) '.bilbidon.ru', // by Ilya S Vorobiyov (reginamedom at yandex.ru) '.flating.ru', // by Sergej L Ivanov (deeeport at yandex.ru) '.kalisto.ru', // by Vladimir I Sokolov (azimut at gmail.ru) '.sanartuk.ru', // by Vladimir I Noskov (hoskv2003 at gmail.ru) ), '208.70.75.153' => array( '.cerc-fi.info', // by Kon Bi (cerca-two at ya.ru) '.cerc-fo.info', // by Kon Bi (cerca-two at ya.ru) '.cerc-no.info', // by Ru Lee (cerca-tree at ya.ru) '.cerc-on.info', '.cerc-sv.info', // by Ru Lee (cerca-tree at ya.ru) '.cerc-sx.org', // by Kon Bi (cerca-two at ya.ru) '.cerc-te.info', // by Ru Lee (cerca-tree at ya.ru) '.cerc-tr.info', '.cerc-tw.info', '.cerc-fi.org', // by Kon Bi (cerca-two at ya.ru) '.cerc-fo.org', // by Kon Bi (cerca-two at ya.ru) '.cerc-no.org', // by Ru Lee (cerca-tree at ya.ru) '.cerc-on.org', // by cerca-one at ya.ru '.cerc-sv.org', // by Ru Lee (cerca-tree at ya.ru) '.cerc-sx.org', // by Kon Bi (cerca-two at ya.ru) '.cerc-te.org', // by Ru Lee (cerca-tree at ya.ru) '.cerc-tr.org', // by cerca-one at ya.ru '.cerc-tw.org', // by cerca-one at ya.ru '.cerca-fi.org', // by orgitaly1 at ya.ru '.cerca-fo.info', '.cerca-no.info', '.cerca-on.info', '.cerca-sv.info', '.cerca-sx.org', // by orgitaly2 at ya.ru '.cerca-te.info', '.cerca-tr.info', '.cerca-sx.org', '.cerca-tr.org', // orgitaly1 at ya.ru '.ricerca-fiv.org', // orgitaly1 at ya.ru '.ricerca-fo.info', '.ricerca-one.org', '.ricerca-sv.org', '.ricerca-sx.org', '.ricerca-te.org', '.ricerca-tw.org', // orgitaly1 at ya.ru '.subit01.org', '.subit02.org', '.subit03.org', '.subit04.org', '.subit05.org', '.subit06.org', '.subit01.info', '.subit02.info', '.subit03.info', '.subit04.info', '.subit05.info', '.subit06.info', ), 'ernestppc at yahoo.com' => array( // by Anrey Markov (ernestppc at yahoo.com) '.5-base.com', '.pharmacy-style.com', ), 'snmaster at yandex.ru' => array( // by Andrey M Somov (snmaster at yandex.ru) '.ista-2006.ru', '.wefas.ru', ), 'sidor2 at gmail.com' => array( // by Sipiki (sidor2 at gmail.com) '.tourismworldsite.info', '.yourtourismtravel.info', ), 'x-mail007 at mail.ru' => array( // by Boris britva (x-mail007 at mail.ru) '.easyfindcar.info', '.siteinfosystems.info', ), 'smesh1155 at gmail.com' => array( '.hospitalforyou.info', // by Gimmi '.thephentermineonline.info', // by Kipola ), 'supermaster at pisem.net' => array( // by Aleksandr Krasnik (supermaster at pisem.net), ns *.msn-dns.com '.kiski.net.in', '.pipki.org.in', '.popki.ind.in', '.siski.co.in', ), 'tiptronikmike at mail.com' => array( 'tiptronikmike at mail.com' => '#^(?:.*\.)?[irvyz][0-5]sex\.info$#', // by Michael Tronik (tiptronikmike at mail.com), e.g. // by Martin Brest (brestmartinjan at yahoo.com), e.g. 74.52.150.242 // by Adulterra Inkognita (inkognitaadulterra at yahoo.com), e.g. 74.52.150.244 //'.i0sex.info', // Michael //'.i1sex.info', // Michael //'.i2sex.info', // Martin //'.i3sex.info', // Martin //'.i4sex.info', // Adulterra //'.i5sex.info', // Adulterra //[irvyz]6sex.info not found '.i8sex.info', // by Martin ), 'skuarlytronald at mail.com' => array( '.girlsfreewild.info', // by Ronald Skuarlyt (skuarlytronald at mail.com), the same / with i4sex.info, post with z2sex.info, 64.27.13.120 '.girlsgoingmad.info', // 64.27.13.120 '.girlsgonewildside.info', // 64.27.13.120 ), '66.232.109.250' => array( '.1626pornporno.info', '.1851pornporno.info', '.1876pornporno.info', '.476pornporno.info', ), 'LiveAdultHost.com' => array( // by Daniel Simeonov (dsim at mbox.contact.bg) '.compactxxx.com', '.eadulthost.com', '.eadultview.com', '.eroticpool.net', '.ipornservice.com', '.liveadulthost.com', '.nudepal.com', '.sweetservers.com', ), 'support at orgija.org' => array( '.assfuckporn.org', '.dosugmos.org', '.fuckporn.org', '.girlsdosug.org', '.girlsporno.org', '.moscowintim.org', '.pornass.org', '.pornopussy.org', '.progirlsporn.org', '.pussypornogirls.org', ), '125.65.112.93' => array( '.gamanir.com', // by yangjianhe (upload888 at 126.com), malicious file '.twurbbs.com', // by mingzhong ni (ggyydiy at 163.com) ), 'm_koz at mail.ru' => array( // 217.11.233.76 by Kozlov Maxim '.beta-google.com', '.tv-reklama.info', '.ebooktradingpost.com', // Anonymous but 217.11.233.76, ns *.ruswm.com '.constitutionpartyofwa.org', // Anonymous but 217.11.233.76, ns *.ruswm.com, "UcoZ WEB-SERVICES" ), '81.0.195.148' => array( // Says: "GOOGLE LOVES ME!!!", I don't think so. the same post with m_koz found '.abobrinha.org', '.aneurysmic.com', // / not found '.physcomp.org', // / not found '.seriedelcaribe2006.org', '.refugeeyouthinamerica.com', ), 'skip_20022 at yahoo.com' => array( // 203.174.83.55 '.a28hosting.info', // by Bill Jones '.besthealth06.org', // by yakon, "Free Web Hosting Services" but "BestHealth" '.besthentai06.org', // by yakon ), 'USFINE.com' => array( '.usfine.com', // 74.52.201.108 by Tang zaiping (tzpsky at gmail.com) '.usfine.net', // 74.52.201.109 by zaiping tang (zppsky at gmail.com) ), '68.178.211.57' => array( '.igsstar.com', // 68.178.211.57 by igsstar at hotmail.com, PARK31.SECURESERVER.NET, pl '.powerleveling-wow.com', // 68.178.211.57 by zhang jun (zpq689 at 163.com) ), 'rambap at yandex.ru' => array( // by Equipe Tecnica Ajato (rambap at yandex.ru) '.google-yahoo-msn.org', '.expedia-travel.org', ), 'admin at newestsearch.com' => array( // by Gibrel Sitce '.emr5ce.org', '.wfe7nv.org', '.xyr99yx.org', ), '203.171.230.39' => array( // registrar bizcn.com, iframe + cursor '.playonlinenc.com', '.playboss-jp.com', ), 'Digi-Rock.com' => array( '.rom776.com', // owner-organization: DIGIROCK, INC. // owner-email: domain-contact at digi-rock.com // with an external ad-and-JavaScript, // says "This site introduces rom776."(Note: Actual rom776 is the another site, http://776.netgamers.jp/ro/ , says s/he don't own rom776.com) // "Actually, this site has been motivated by a desire to researching search-engine-rank of this site, and researching how the people place this site.". ), 'snap990 at yahoo.com' => array( // by John Glade (snap990 at yahoo.com) '.date-x.info', // 208.73.34.48(support-office.hostican.com -> 208.79.200.16) '.getrun.cn', // 208.73.34.48 '.ipod-application.info', // NO IP '.love-total.net', // 208.73.34.48, was 74.50.97.136(server.serveshare.com) '.stonesex.info', // NO IP, was 74.50.97.136 ), 'germerts at yandex.ru' => array( // 89.188.112.64(allworldteam.com by aakin at yandex.ru) by Sergey Marchenko (germerts at yandex.ru) '.andatra.info', '.banchitos.info', '.batareya.info', '.blevota.info', '.broneslon.info', '.gamadril.info', '.gipotenuza.info', '.govnosaklo.info', '.muflon.info', '.termitnik.info', ), '84.252.148.80' => array( // 84.252.148.80(heimdall.mchost.ru) '.acronis-true-image.info', '.calcio-xp.info', '.cosanova.info', '.cose-rx.info', '.dictip.info', '.findig.info', '.fotonow.info', '.lavoro-tip.info', '.loan-homes.info', '.mionovita.info', '.mustv.info', '.newsnaked.info', '.online-tod.info', '.opakit.info', '.opanow.info', '.opriton.info', '.porta-bl.info', '.refdif.info', '.xzmovie.info', ), '84.252.148.120 etc' => array( '.isurfind.ru', // 84.252.148.120 by Egor S Naumov (prpramer at narod.ru) '.planetavilton.info', // 84.252.148.120 '.softfind.info', // 84.252.148.80 by Dmitriy (dimamcd at yandex.ru) ), 'cxh at 99jk.com' => array( // by xinghao chen (cxh at 99jk.com), ns *.hichina.com, health care '.99jk.com', '.99jk.com.cn', '.99jk.cn', ), 'kiler81 at yandex.ru' => array( // by Vasiliy (kiler81 at yandex.ru) '.kliktop.biz', '.kliktop.org', '.pharmatop.us', '.supertop.us', '.supervaizer.info', ), 'infomed2004 at mail.ru' => array( // by Andrey Ushakov (infomed2004 at mail.ru) '.freeamateursexx.info', // 81.0.195.228 '.freeanalsexx.info', // 217.11.233.97 '.freegaysexx.info', // 81.0.195.228 ), 'support at dns4me.biz' => array( // 89.149.228.237 by John Black (support at dns4me.biz) '.abbhi.info', '.gayblogguide.biz', '.huope.info', '.thebdsmday.info', '.zioprt.info', // 89.149.228.237 ), 'dzheker at yandex.ru' => array( // by dzheker at yandex.ru '.boblisk.info', '.factyri.info', '.jorge1.info', ), 'lichincool at gmail.com' => array( // 72.232.229.115 by lichincool at gmail.com, / meanless '.bestmindstorm.org', '.redstoreonline.org', ), '59.106.24.2' => array( // 59.106.24.2, sakagutiryouta at yahoo.co.jp '.8e8ae.net', '.c-cock.com', '.fa59eaf.com', '.set-place.net', '.sex-beauty.net', ), '84.252.148.140' => array( // 84.252.148.140(kratos.mchost.ru) '.tomdir.info', '.tomdirdirect.info', '.tomdirworld.info', '.treton.info', '.trefas.info', '.tretonmondo.info', '.unefout.info', '.unefoutprojet.info', '.unitfree.info', '.vilret.info', '.vilttown.info', '.votrefout.info', '.warmfind.info', '.warptop.info', '.wildtram.info', '.xofind.info', '.xopdiscover.info', '.xopfind.info', '.xoplocate.info', '.xopseek.info', '.xpfirst.info', '.xphighest.info', '.xptop.info', ), 'info at thecanadianmeds.com' => array( // by Andrey Smirnov (info at thecanadianmeds.com) '.myviagrasite.com', // 80.74.153.2 '.thecanadianmeds.com', // 80.74.153.17 ), 'sania at zmail.ru' => array( // by Mark Williams (sania at zmail.ru) '.bigemot.com', // 217.11.233.34, / not found '.espharmacy.com', // 217.11.233.34 '.pharmacyonlinenet.com', // 216.195.51.59, hidden JavaScript '.ringtonecooler.com', // 217.11.233.34 ), 'dfym at dfym.cn' => array( // by chen jinian (dfym at dfym.cn) '.okwit.com', // 220.166.64.44 '.sakerver.com', // 220.166.64.194 '.motewiki.net', // 220.166.64.194 ), 'mkiyle at gmail.com' => array( // by Mihelich (mkiyle at gmail.com) '.findcraft.info', // 209.8.28.11(209-8-28-11.pccwglobal.net) '.lookmedicine.info', // 206.161.205.22 '.lookshop.info', // 209.8.40.52(goes.to.high.school.in.beverly-hills.ca.us) '.searchhealth.info', // 206.161.205.30(seg.fau.lt) '.worldsitesearch.info', // 209.8.40.59 ), 'lee.seery at gmail.com' => array( '.klikgoogle.com', // 64.21.34.55(klikgoogle.com), by KLIK Media GmbH (max at awmteam.com) '.lingvol.com', // 64.21.34.55 '.micevol.com', // 64.21.34.55 '.heyhey.info', // 64.21.34.55 by anonymous ), '69-64-64-71.dedicated.abac.net etc' => array( // ns *.trklink.com // 69-64-64-71.dedicated.abac.net '.520-ard.info', '.550bcards.info', '.559-cads.info', '.559caard.info', '.565-caaard.info', '.575cadr.info', '.577cadrs.info', '.590-acrds.info', '.596-cadrs.info', '.596caards.info', '.596caaard.info', '.asstablishingcads.info', '.astablish-ard.info', '.astablishcacrds.info', '.begginers-acards.info', '.begginersacrds.info', '.beggingcaaard.info', '.beginercacrds.info', '.cacrdscreating.info', '.caditbegging.info', '.cadr-buildup.info', '.cadr-establilsh.info', '.cadrs-buildercredit.info', '.cadrs570.info', '.cads-565.info', // 69-64-64-113.dedicated.abac.net '.interistacards.info', '.intrust-ards.info', '.intrustacrds.info', '.lfixed-ard.info', '.lowerate-ard.info', '.lowpercentage-ard.info', '.lowpercentageacrd.info', ), 'acua at mail.ru' => array( // 84.16.249.240(euro.lotgd.pl -> 88.198.6.42), / says 'noy found' '.dns4babka.info', // by acua at mail.ru // by webmaster at dns4babka.info '.credh.cn', '.fucfv.cn', '.gdxnk.cn', '.sqrrt.cn', '.ywtmd.cn', '.kncqy.cn', // by webmaster at allmyns.info // 84.16.251.222(alinoe.org -> 212.85.96.95 -> v00095.home.net.pl), / says 'noy found' '.dedka2ns.info', // by acua at mail.ru // by webmaster at dedka2ns.info '.ascpo.cn', '.jgycr.cn', '.nqdtt.cn', '.oswde.cn', '.qeyig.cn', '.soqsx.cn', '.ukncd.cn', '.zijgb.cn', // 84.16.255.253(*.internetserviceteam.com), / says 'noy found' '.dns4dedka.info', // by acua at mail.ru // by webmaster at dns4dedka.info '.bcpnb.cn', '.cfbpr.cn', '.dnndb.cn', '.ekwme.cn', '.iutps.cn', '.ryftj.cn', '.vxqcb.cn', '.zxvlr.cn', // by webmaster at allmyns.info // by dig at dns4dedka.info '.bdnge.cn', // 84.16.226.28(www.fs-tools.de -> 80.244.243.172 -> fs-tools.de) '.dcdsu.cn', // 217.20.112.102(*.internetserviceteam.com) '.fhgdp.cn', // 84.16.249.239(euro.lotgd.pl -> 88.198.6.42) '.frvdv.cn', // 84.16.226.28(*snip*) '.heulw.cn', // 84.16.226.217(mand.zapto.org -- Non-existent) '.hissw.cn', // 84.16.249.240(*snip*) '.lwqjr.cn', // 84.16.255.253(*snip*) '.obwew.cn', // 84.16.251.218(*.internetserviceteam.com) '.otkiu.cn', // 84.16.255.254(*.internetserviceteam.com) '.pztkq.cn', // 89.149.228.163(*.internetserviceteam.com) '.rgjcs.cn', // 84.16.251.219(*.internetserviceteam.com) '.rjskp.cn', // 84.16.249.241(ip2.frankfurt.mabako.net -> 84.16.234.167 -> frankfurt.mabako.net) '.sokrp.cn', // 84.16.226.217(*snip*) '.ubtnp.cn', // 84.16.226.29(www.billago.de -> 80.244.243.173 -> billago.de) '.vdecc.cn', // 84.16.226.29(*snip*) '.vgkkc.cn', // 89.149.196.72(mendoi.fansubs.omni-forums.net -> 72.9.144.200) '.vqsmy.cn', // 84.16.249.239(*snip*) '.xcmsp.cn', // 84.16.251.223(freebsd .. what) '.xiuky.cn', // 84.16.251.222(*snip*) '.xrqcd.cn', // 89.149.196.19(www.kosmetik-eshop.de -> 80.244.243.181 -> ip1.rumsoft-webhosting.de) // by la at dns4dedka.info '.aeyzf.cn', // 84.16.251.218(*snip*) '.blvqo.cn', // 84.16.249.241(*snip*), Expiration Date: 2008-08-16 '.bgslu.cn', // 89.149.228.163(*snip*) '.dxouw.cn', // 84.16.255.253(*snip*) '.ecsbe.cn', // 84.16.251.218(*snip*) '.eothy.cn', // 84.16.249.241(*snip*) '.epocy.cn', // 84.16.251.220(*.internetserviceteam.com) '.ewvjw.cn', // 89.149.196.72(*snip*) '.faacz.cn', // 84.16.251.222(*snip*) '.filun.cn', // 89.149.196.72(*snip*) '.fzdpk.cn', // 84.16.249.239(*snip*) '.hatyg.cn', // 84.16.251.223(*snip*) '.hmtqn.cn', // 84.16.249.240(*snip*) '.ibfte.cn', // 89.149.196.19(*snip*) '.jcaym.cn', // 84.16.249.240(*snip*) '.iqzaw.cn', // 84.16.255.254(*snip*) '.jclsf.cn', // 84.16.249.240(*snip*) '.jefdh.cn', // 84.16.249.240(*snip*) '.kchjh.cn', // 84.16.251.219(*snip*) '.krumo.cn', // 84.16.226.217(*snip*) '.lbava.cn', // 217.20.112.102(*snip*) '.mqrtw.cn', // 84.16.226.29(*snip*) '.njpgv.cn', // 84.16.251.219(*snip*) '.npovm.cn', // 84.16.226.28(*snip*) '.nyobt.cn', // 89.149.196.19(*snip*) '.ovxxt.cn', // 84.16.251.223(*snip*) '.owhwz.cn', // 89.149.228.163(*snip*) '.ozjyi.cn', // 84.16.249.241(*snip*) '.pfnzj.cn', // 84.16.226.217(*snip*) '.pixvf.cn', // 84.16.255.254(*snip*) '.qydph.cn', // 89.149.228.163(*snip*) '.rxens.cn', // 89.149.196.72(*snip*) '.sojbp.cn', // 84.16.249.239(*snip*) '.srths.cn', // 84.16.251.222(*snip*) '.tdytc.cn', // 84.16.255.254(*snip*) '.unquz.cn', // 84.16.251.223(*snip*) '.uwcns.cn', // 89.149.196.19(*snip*) '.vcbdm.cn', // 84.16.251.220(*snip*) '.wnmat.cn', // 84.16.255.253(*snip*) '.wttmr.cn', // 84.16.226.29(*snip*) '.xpwib.cn', // 84.16.251.220(*snip*) '.yrogt.cn', // 84.16.249.239(*snip*) // by le at dns4dedka.info '.goslw.cn', // 84.16.251.220(*snip*) '.hqbmh.cn', // 84.16.251.223(*snip*) '.iewik.cn', // 84.16.255.254(*snip*) '.jnkeh.cn', // 89.149.228.163(*snip*) '.pifyp.cn', // 89.149.228.163(*snip*) '.nohyl.cn', // 89.149.196.72(*snip*) '.nvzvx.cn', // 84.16.255.254(*snip*) '.uchoe.cn', // 84.16.249.239(*snip*) '.ujoyf.cn', // 84.16.251.218(*snip*) '.ulfqh.cn', // 89.149.196.19(*snip*) '.vxugv.cn', // 84.16.251.223(*snip*) '.dbgti.cn', // 84.16.249.240(*snip*) '.oelmv.cn', // 84.16.226.28(*snip*) '.qniww.cn', // 84.16.251.218(*snip*) '.vtvyq.cn', // 84.16.251.219(*snip*) '.zqonm.cn', // 84.16.249.241(*snip*) '.allmyns.info', // 84.16.226.29 by acua at mail.ru, / forbidden // by webmaster at allmyns.info '.degvc.cn', // 84.16.226.216(s3an.ath.cx -- DyDNS) '.ihpvy.cn', // 84.16.226.28(*snip*) '.lbtuo.cn', // 84.16.255.254(*snip*) '.liunc.cn', // 84.16.249.241(*snip*) '.rcyqr.cn', // 84.16.226.217(*snip*) '.rekth.cn', // 89.149.196.19(*snip*) '.riumh.cn', // 84.16.226.28(*snip*) '.zbtym.cn', // 84.16.251.219(*snip*) '.zjcgx.cn', // 217.20.112.102(*snip*) ), 'gilvcta sy jilbertsbram.com' => array( '.dsfljkeilm1.cn', // 206.53.51.126 '.dsfljkeilm2.cn', // 206.53.51.126 '.dsfljkeilm3.cn', // IP not allocated now '.dsfljkeilm4.cn', // IP not allocated now '.dsfljkeilm5.cn', // IP not allocated now '.dsfljkeilm6.cn', // IP not allocated now '.dsfljkeilm7.cn', // IP not allocated now '.dsfljkeilm8.cn', // IP not allocated now '.dsfljkeilm9.cn', // IP not allocated now '.dsfljkeilm10.cn', // IP not allocated now ), 'ganzer3 at gmail.com' => array( // by Roman Shteynshlyuger (ganzer3 at gmail.com) // 69.64.82.76(*.dedicated.abac.net) '.bruised-criedit.info', '.bruised-crtedit.info', '.bruised-czrd.info', '.bruisedcreditcars.info', '.bruisedcreitcard.info', '.bruisedcreitd.info', '.buliderscreadet.info', '.cleaningup-cdit.info', '.cleaningup-cedict.info', '.cleaningup-cerdic.info', '.cleanup-crrd.info', // 69.64.82.77(*.dedicated.abac.net) '.bruised-crediot.info', '.bruised-credtid.info', '.bruisedcriet.info', '.bruisedredit.info', '.buliders-crdt.info', '.buliders-cre4dit.info', '.buliders-creadt.info', '.buliders-credcards.info', '.buliders-credictcard.info', '.cleaningupccreditcards.info', '.cleaningupcdedit.info', '.cleaningupcedirt.info', '.cleaningupceidt.info', '.cleaningupcrasd.info', '.cleaningupcreait.info', // 69.64.82.78(*.dedicated.abac.net) '.bruised-cridet.info', '.bruised-drecit.info', '.bruised-reditcards.info', '.bruisedcredikt.info', '.bruisedcredith.info', '.bruisedcredtid.info', '.cleanup-criet.info', '.cleanup-csrds.info', '.cleanup-dards.info', // 69.64.82.79(*.dedicated.abac.net) '.bruised-crediotcards.info', '.bruised-creditcar.info', '.bruised-creid.info', '.bruised-creidtcard.info', '.buliders-crdit.info', '.buliders-creadet.info', '.cleaningup-ceridt.info', '.cleaningupcrecit.info', '.cleaningupccritcard.info', '.cleanupdredit.info', '.cleanupredit.info', ), '.malwarealarm.com', // (206.161.201.216 -> 206-161-201-216.pccwglobal.net) // by Eddie Sachs (hostmaster at isoftpay.com), scaring virus, spyware or something // NOTE: scanner.malwarealarm.com(206.161.201.212 -> 206-161-201-212.pccwglobal.net) '.viagraorder.org', // IP not allocated, ns *.heyhey.info(IP not allocated) => 89.248.99.110 'Inet-Traffic.com' => array( // "The Inet-Traffic network offers over 6 million unique visitors a month." //'.dcomm.com', // by D Communications Inc. S.A. '.freehomepages.com', // 205.237.204.51 by domains at inet-traffic.com, ns *.dcomm.com '.inet-traffic.com', // 205.237.204.106(reverse.dcomm.com) by domains at inet-traffic.com, ns *.dcomm.com // ... // 205.237.204.114(www.searchit.com -> 205.237.204.151) // ... '.homepagez.com', // 205.237.204.118 by domainadmin at navigationcatalyst.com, ns *.dnsnameserver.org // ... '.pagerealm.com', // 205.237.204.121 by domains at inet-traffic.com, ns *.dcomm.com '.koolpages.com', // 205.237.204.122 by domains at inet-traffic.com, ns *.dcomm.com '.oddworldz.com', // 205.237.204.123 by domains at inet-traffic.com, ns *.dcomm.com '.cybcity.com', // 205.237.204.124 by domains at inet-traffic.com, ns *.dcomm.com '.cybamall.com', // 205.237.204.125 by domains at inet-traffic.com, ns *.dcomm.com '.haywired.com', // 205.237.204.126 by domains at inet-traffic.com, ns *.dcomm.com '.cyberturf.com', // 205.237.204.127 by domains at inet-traffic.com, ns *.dcomm.com '.dazzled.com', // 205.237.204.128 by domains at inet-traffic.com, ns *.dcomm.com '.megaone.com', // 205.237.204.129 by domains at inet-traffic.com, ns *.dcomm.com // ... // 205.237.204.131(www.powow.com -> 205.237.204.136) // 205.237.204.132(www.pcpages.com -> 205.237.204.135) // ... '.pcpages.com', // 205.237.204.135(reverse.dcomm.com) by domains at inet-traffic.com, ns *.addplace.com '.powow.com', // 205.237.204.136 by domains at inet-traffic.com, ns *.dcomm.com // ... // 205.237.204.143(gameroom.com -> 72.32.22.210) // ... '.searchit.com', // 205.237.204.151(reverse.dcomm.com) by domains at inet-traffic.com, ns *.dcomm.com // http://www.trendmicro.com/vinfo/grayware/ve_GraywareDetails.asp?GNAME=ADW_SOFTOMATE.A // ... '.gameroom.com', // 72.32.22.210 by julieisbusy at yahoo.com, listed at inet-traffic.com and freehomepages.com ), 'andreyletov at yahoo.com related' => array( '.180haifa.com', // 82.103.128.177(e82-103-128-177s.easyspeedy.com) by Andrey Letov '.mens-medication.com', // 89.248.99.118 by Boris Rabinovich '.pills-supplier.com', // 89.248.99.118 by Boris Rabinovich // 89.248.99.118 by anonymous '.lpgpharmacy.com', '.onlybestgalleries.com', '.viagrabest.info', '.viagrabestprice.info', '.viagratop.info', '.canadians-medication.com', // 89.248.99.118 by beseo at bk.ru '.absulutepills.com', // 216.40.236.58(*.ev1servers.net) by bulka at skyhaifa.com, redirect to canadians-medication.com '.eyzempills.com', // 216.40.236.59(*.ev1servers.net) by bulka at skyhaifa.com, redirect to canadians-medication.com ), 'alrusnac at hotmail.com' => array( '.122mb.com', // 209.67.214.122 by Alexandru Rusnac (alrusnac at hotmail.com) //'.cigarettesportal.com', // 72.36.211.194(*.static.reverse.ltdomains.com) ), '203.116.63.123' => array( '.fast4me.info', // by Hakan Durov (poddubok at inbox.ru), / is blank '.fastmoms.info', // by Pavel Golyshev (pogol at walla.com), / is blank ), 'goodwin77 at bk.ru' => array( // ns *.petterhill.ru '.autotowncar.cn', // 69.73.146.184 '.badgirlhome.cn', // 69.73.146.186 ), 'Wmp.co.jp' => array( // 219.94.134.208, ns *.dns.ne.jp, adult '.celebe.net', // by nic-staff at sakura.ad.jp(using sakura.ne.jp), said: by "wmp.co.jp" '.kousyunyu.com', // Admin/Billing/Tech Email: * at wmp.co.jp // online-support.jp // 202.222.19.81(sv70.lolipop.jp), / blank ), 'Macherie.tv' => array( '.macherie.tv', // 124.32.230.31, pr to himehime.com '.himehime.com', // 124.32.230.94(recruit.macherie.tv) '.livechatladyjob.com', // 124.32.230.94 by Hajime Kawagoe (sawada at innetwork.jp), recruiting site for macherie.tv ), 'admin at fr4f3ds.info' => array( // 217.11.233.54, / forbidden '.yemine.info', '.fr4f3ds.info', ), '75.126.129.222' => array( // 75.126.129.222(greatpool.biz -> 72.232.198.234 -> brasilrok.com.br -> ...) '.viagrabuycheap.info', // ns *.advernsserver.com '.viagrageneric.org', // IP not allocated, ns *.heyhey.info(IP not allocated) => 75.126.129.222 ), 'sqr at bk.ru' => array( // 69.46.18.2(hv113.steephost.com -> 72.232.191.50 -> 72.232.191.50.steephost.com) '.masserch.info', // "Free Web Hosting", spam '.miserch.info', ), 'gangstadra at hotmail.com' => array( '.kenrucky.com', // 82.98.86.167(*.sedoparking.com) '.michigab.com', // 82.98.86.175(*.sedoparking.com) '.pimperos.com', // 82.98.86.163(*.sedoparking.com) '.pimpcupid.com', // 89.149.226.111(*.internetserviceteam.com) ), 'hosan by front.ru' => array( '.online-freesearch.com', // 206.53.51.155 '.carsprojects.com', // 206.53.51.159 '.sport-brands.com', // 206.53.51.167 '.choosefinest.com', // 206.53.51.157 '.online-pharmaceutics.com', // 206.53.51.168 ), // C-2: Lonely domains (buddies not found yet) '.0721-4404.com', '.0nline-porno.info', // by Timyr (timyr at narod.ru) '.1-click-clipart.com', // by Big Resources, Inc. (hostmaster at bigresources.com) '.19cellar.info', // by Eduardo Guro (boomouse at gmail.com) '.1gangmu.com', // by gangmutangyaoju (wlmx009 at hotmail.com), Seems physing site for ff11-jp.com '.1gb.cc', // by Hakan us (hakanus at mail.com) '.1gb.in', // by Sergius Mixman (lancelot.denis at gmail.com) '.0annie.info', '.6i6.de', '.advancediet.com', // by Shonta Mojica (hostadmin at advancediet.com) '.adult-master-club.com', // by Alehander (mazyrkevich at cosmostv.by) '.adultpersonalsclubs.com', // by Peter (vaspet34 at yahoo.com) '.akgame.com', // 72.32.79.100 by Howard Ke (gmtbank at gmail.com), rmt & pl '.alfanetwork.info', // by dante (dantequick at gmail.com) '.allworlddirect.info', // Forbidden '.amoreitsex.com', '.approved-medication.com', // 208.109.181.53(p3slh079.shr.phx3.secureserver.net) '.areahomeinfo.info', // by Andrus (ffastenergy at yahoo.com), republishing articlealley.com '.areaseo.com', // by Antony Carpito (xcentr at lycos.com) '.auto-car-cheap.org', '.banep.info', // by Mihailov Dmitriy (marokogadro at yahoo.com), iframe to this site '.baurish.info', '.bestop.name', '.betmmo.com', // 63.223.98.182 by Huang Qiang (liuxing-wushi at hotmail.com), pl '.bestrademark.info', // by victoria (niko16d at yahoo.com), redirect to majordomo.ru '.bestshopfinder.info', '.blogest.org', // 203.116.63.68 by Bobby.R.Kightlinger at pookmail.com, / seems blank '.bookblogsite.org', // 217.11.233.58 by Eugene.E.Mather at mailinator.com '.businessplace.biz', // by Grenchenko Ivan Petrovich (eurogogi at yandex.ru) '.capital2u.info', // by Delbert.A.Henry at dodgeit.com '.casa-olympus.com', // "UcoZ WEB-SERVICES" '.catkittenmagazines.org', // 87.118.97.117 '.covertarena.co.uk', // by Wayne Huxtable '.d999.info', // by Peter Vayner (peter.vayner at inbox.ru) '.dinmo.cn', // 218.30.96.149 by dinso at 163.com, seo etc. //'.wow-gold.dinmo.cn', // 125.65.76.59, pl '.dinmoseo.com', // 210.51.168.102(winp2-web-g02.xinnetdns.com) by jianmin911 at 126.com, NS *.xinnetdns.com, seo '.dlekei.info', // by Maxima Bucaro (webmaster at tts2f.info) '.dollar4u.info', // by Carla (Carla.J.Merritt at mytrashmail.com), / is blank '.drug-shop.us', // by Alexandr (matrixpro at mail.ru) '.drugs-usa.info', // by Edward SanFilippo (Edward.SanFilippo at gmail.com), redirect to activefreehost.com '.easyshopusa.com', // by riter (riter at nm.ru) '.edu.ph', // "philippine network foundation inc" '.ex-web.net', // RMT by ex co,ltd (rmt at ex-web.net) '.extracheapmeds.com', // "freexxxmovies" by John Smith (89 at bite.to) '.fantasy-handjob-ra.com', // by Hose Pedro (hosepedro at gmail.com) '.fastppc.info', // by peter conor (fastppc at msn.com) '.ffxiforums.net', // 204.16.199.105 by Zhang xiaolong (mail at 33986.com), hidden VBScript '*.filthserver.com', // sales at onlinemarketingservices.biz '.find-stuff.org', // by Alice Freedman (admin at ip-labs.ru), / 404 Not Found '.firstdrugstorezone.info', // by Goose (boris208 at yandex.ru) '.free-finding.com', // by Ny hom (nyhom at yahoo.com) '.free-rx.net', // by Neo-x (neo-xxl at yandex.ru), redirect to activefreehost.com '.free-sex-movie-net.info', // by vitas61 at yahoo.com '.freeblog.ru', // by Kondrashov Evgeniy Aleksandrovich (evkon at rol.ru), login form only, ns *.nthost.ru '.freehost5.com', // 75.126.32.184(kosmohost.net), words only '.freeliveringtones.com', // by Silan (lippe1988 at gmail.com) '.freemobilephonesworld.info', // by andresid (andresid1 at yandex.ru) '.game4enjoy.net', // by huang jinglong (fenlin231 at sina.com) '.game4egold.com', // by Filus Saifullin (ebay at soft-script.com) '.goldcoastonlinetutoring.com', // by Robert Tanenbaum (buildbt at lycos.com) '.gomeodc.com', // 125.65.112.49 by wang meili (gannipo at yahoo.com.cn), iframe to vviccd520.com '.ganecity.com', // by shao tian (huangjinqiang at sina.com) '.gm-exchange.jp', // 210.188.216.49 RMT '.goamoto.ru', // by Dmitry E Kotchnev (z2archive at gmail.com) '.good1688.com', // by Wen Chien Lunz (wzk1219 at yahoo.com.tw), one of them frame to , and whoop.to '.google-pharmacy.com', // by alex (mdisign1997 at yahoo.com), hiding with urlx.org etc '.greatbestwestern.org',// by gao.wungao at gmail.com '.greatsexdate.com', // by Andreas Crablo (crablo at hotmail.com) '.guesttext.info', // 81.0.195.134 by Grace.D.Kibby pookmail.com, / seems null '.guild-wars-online.com', // by Fuzhou Tianmeng Touzi Zixun Co.,Ltd (welkin at skyunion.com) '.happyhost.org', // by Paul Zamnov (paul at zamnov.be) '.hloris.com', // by Wilshi Jamil (ixisus at front.ru) '.honda168.net', // by tan tianfu (xueyihua at gmail.com), seems not used now '.hostuju.cz', // ns banan.cz, banan.it '.hot4buy.org', // by Hot Maker (jot at hot4buy.org) '.hotscriptonline.info',// by Psy Search (admin at psysearch.com) '.iinaa.net', // domain at ml.ninja.co.jp, ns *.shinobi.jp '.incbuy.info', // by Diego T. Murphy (Diego.T.Murphy at incbuy.info) '.infradoc.com', '.investorvillage.com', // by natalija puchkova (internet at internet.lv) '.ismarket.com', // Google-hiding. intercage.com related IP '.italialiveonline.info', // by Silvio Cataloni (segooglemsn at yahoo.com), redirect to activefreehost.com '.italy-search.org', // by Alex Yablin (zaharov-alex at yandex.ru) '.itsexosit.net', '.itxxxit.net', '.jimmys21.com', // by Klen Kudryavii (telvid at shaw.ca) '.jimka-mmsa.com', // by Alex Covax (c0vax at mail.ru), seems not used yet '.joynu.com', // by lei wang (93065 at qq.com), hidden JavaScript '.kingtools.de', '.kymon.org', // by Albert Poire (isupport at yahoo.com), / Forbidden, 70.87.62.252 '.leucainfo.com', '.library-blogs.net', // by Peter Scott (pscontent at gmail.com) '.lingage.com', // by huan bing (qbbs at xinoffice.com) '.link-keeper.net', // 210.172.108.236 (257.xrea.com) '.ls.la', // by Milton McLellan (McLellanMilton at yahoo.com) '.mamaha.info', // by Alex Klimovsky (paganec at gmail.com), seems now constructiong '.manseekingwomanx.com',// by Bill Peterson (coccooc at fastmail.fm) '.medicineonlinestore.com', // Alexander Korovin (domains at molddata.md) '.medpharmaworldguide.com', // by Nick Ivchenkov (signmark at gmail.com), / not found '.megvideochatlive.info', // Bad seo '.milfxxxpass.com', // by Morozov Pavlik (rulets at gmail.com) '.moremu.com', // 205.134.190.12(amateurlog.com) by Magaly Plumley (domains ay moremu.com) '.myfgj.info', // by Filus (softscript at gmail.com) '.mujiki.com', // by Mila Contora (ebumsn at ngs.ru) '.mxsupportmailer.com', '.next-moneylife.com', // RMT '.newalandirect.com', // by Alnoor Hirji, ns *.sablehost.com '.ngfu2.info', // by Tara Lagrant (webmaster at ngfu2.info) '.nucked-sex.com', // 203.223.150.222 by lis (noidlis2 at yahoo.com) '.ok10000.com', // by zipeng hu (ldcs350003 at hotmail.com) '.olimpmebel.info', // by pol (pauk_life at mail.ru), frame to bettersexmall.com '.onlinetert.info', // by Jarod Hyde (grigorysch at gmail.com) '.onlin-casino.com', // by Lomis Konstantinos (businessline3000 at gmx.de) '.onlineviagra.de', '.ornit.info', // by Victoria C. Frey (Victoria.C.Frey at pookmail.com) '.ozomw.info', '.pahuist.info', // by Yura (yuralg2005 at yandex.ru) '.pelican-bulletin.info', // by Elizabeth K. Perry (redmonk at mail.ru) '.perevozka777.ru', // by witalik at gmail.com '.pharmacy2online.com', // by Mike Hiliok (bbong80 at yahoo.com) '.pills-storage.com', // by '.plusintedia.com', // by g yk (abc00623 at 163.com), seems not used now '.porkyhost.com', // 79965 at whois.gkg.net '.porno-babe.info', // by Peter (asdas at mail.ru), redirect to Google '.pornesc.com', // by Xpeople (suppij atmail.ru) '.portaldiscount.com', // by Mark Tven (bestsaveup at gmail.com) '.powerlevelingweb.com', // 68.178.211.9 by jun zhang (huanbing at 126.com), pl '.prama.info', // by Juan.Kang at mytrashmail.com ',pulsar.net', // by TheBuzz Int. (theboss at tfcclion.com) '.qoclick.net', // by DMITRIY SOLDATENKO '.quality-teen-porn-photo.com', // by info at densa.info '.relurl.com', // tiny-like. by Grzes Tlalka (grzes1111 at interia.pl) '.replicaswatch.org', // by Replin (admin at furnitureblog.org) '.rigame.info', // by debra_jordan07 at yahoo.com '.rmt-trade.com', // by wang chun (dlxykj at 126.com), rmt '.roin.info', // by Evgenius (roinse at yandex.ru) '.save-darina.org', // 85.14.36.36 by Plamen Petrov (plamen5rov at yahoo.com) '.searchadv.com', // by Jaan Randolph (searchadv at gmail.com) '.seek-www.com', // by Adam Smit (pingpong at mail.md) '.sessocities.net', // 66.98.162.20(*.ev1servers.net: Non-existent domain) by info at secureserver3.com '.seven-pharmacy.com', // 83.138.176.247 by Justin Timberlake (preved at gmail.com) '.sexamoreit.com', '.sexforit.com', '.sexmaniacs.org', // by Yang Chong (chong at x-india.com) '.sexsmovies.info', // 203.174.83.22 by dima (vitas at vitas-k.com) '.sirlook.com', '.so-net.ws', // by Todaynic.com Inc, seems a physing site for so-net.jp '.sepcn.info', // / not found '.sslcp.com', // by shufang zhou (info at 6come.com), dns *.hichina.com '.sticy.info', // by Richard D. Mccall (richardmccall at yahoo.com) '.superrwm.info', // by Dark Dux (duxdark at yahoo.com) '.superverizonringtones.com', // by joshua at list.ru '.thehostcity.com', // Domains by Proxy '.thetinyurl.com', // by Beth J. Carter (Beth.J.Carter at thetinyurl.com), / is blank '.thetrendy.info', // by Harold (Harold.J.Craft at pookmail.com), / is blank '.theusapills.com', // by Dr. Zarman (contactus at theusapills.com) '.tingstock.info', // 209.160.73.65(delta.xocmep.info) "nice day, commander ;)" by Andrey Konkin (konkinnews55 at yahoo.com) '.topmeds10.com', '.truststorepills.com', // 89.188.113.64(allworldteam.com) by Alexey (admin at myweblogs.net) '.twabout.com', // by qiu wenbing (qiuwenbing at 126.com), content from l2mpt.net '.uaro.info', // by Neru Pioner (neru at smtp.ru) '.unctad.net', // by gfdogfd at lovespb.com '.vacant.org.uk', '.vip-get.info', // 203.223.150.222 by Jhon Craig (bartes1992 at mail.ru), / forbidden '.virtualsystem.de', '.vdxhost.com', '.vviccd520.com', // 202.75.219.217 by kuang zhang (oulingfeng66 at 163.com), encoded JavaScript '.homes.com.au', // 139.134.5.124 by wongcr at bigpond.net.au, / meanless, '.webnow.biz', // by Hsien I Fan (admin at servcomputing.com) '.webtools24.net', // by Michael Helminger (info at ishelminger.de) '.wer3.info', // by Martin Gundel (Martin at mail.com), 404 not found '.withsex.net', // by C.W.Jang (jangcw1204 at naver.com) '.whoop.to', // RMT '.womasia.info', // by Mark Fidele (markfidele at yahoo.com) '.worldinsurance.info', // by Alexander M. Brown (Alex_Brown at yahoo.com), fake-antivirus '.wow-powerleveling-wow.com', // 63.223.77.112 by dingmengxl at 126.com, pl '.wowgoldweb.com', // 64.202.189.111(winhostecn28.prod.mesa1.secureserver.net) by lei chen (dreamice at yeah.net), rmt & pl '.wwwna.info', // / 404 Not Found '.xpacificpoker.com', // by Hubert Hoffman (support at xpacificpoker.com) '.xamorexxx.net', '.xn--gmqt9gewhdnlyq9c.net', // 122.249.16.133(x016133.ppp.asahi-net.or.jp) by daizinazikanwo yahoo.co.jp '.xsessox.com', '.xxxmpegs.biz', // 217.11.233.65, redirect to *.malwarealarm.com, / null '.yoi4.net', // by Ryouhei Nakamura (888 at sympathys.com), tell me why so many blogs with popular issues and _diverted design from blog.livedoor.jp_ around here. '.zlocorp.com', // by tonibcrus at hotpop.com, spammed well with "http ://zlocorp.com/" '.zyguo.info', // ns globoxhost.net '.zhuyiw.com', // by zhou yuntao (whzyt0122 at sohu.com) '.101010.ru', // 72.232.246.178(spirit.intellovations.com -> 207.218.230.66) by gkrg94g at mail.ru, / forbidden '.alasex.info', // 'UcoZ web-services' 216.32.81.234(server.isndns.net) by yx0 at yx0.be '.golden-keys.net', // 89.149.205.146(unknown.vectoral.info) by aktitol at list.ru '.chatwalker.com', // 124.32.230.65 '.angel-live.com', // 61.211.231.181, ns *.netassist.ne.jp, pr to himehime.com '.angelkiss.jp', // 59.106.45.50, pr to himehime.com and chatwalker.com '.morfolojna.cn', // 206.53.51.126, by gilserta at jilbertsabram.com, Using web.archive.org '.mncxvsm.info', // 217.11.233.105, / blank '.super-discount.sakura.ne.jp', // 59.106.19.206(www756.sakura.ne.jp), sales '.privatedns.com', // 209.172.41.50(sebulba.privatedns.com), encoded JavaScript, root of various posts // C-3: Not classifiable (information wanted) // // Something incoming to pukiwiki related sites 'nana.co.il related' => array( '.planetnana.co.il', '.nana.co.il', ), ); // -------------------------------------------------- $blocklist['D'] = array( // D: Sample setting of // "Third party in good faith"s // // Hosts shown inside of the implanted contents, // not used via spam, but maybe useful to detect these contents // // 'RESERVED', ); // -------------------------------------------------- $blocklist['E'] = array( // E: Sample setting of // Promoters // (Affiliates, Hypes, Catalog retailers, Multi-level marketings, Resellers, // Ads, Business promotions) // // They often promotes near you using blog article, mail-magazines, tools(search engines, blogs, etc), etc. // Sometimes they may promote each other '15-Mail.com related' => array( '.15-mail.com', // 202.218.109.45(*.netassist.jp) by yukiyo yamamoto (sunkusu5268 at m4.ktplan.ne.jp) '.1bloglog.com', // 210.253.115.159 by Yukiyo Yamamoto (info at 15-mail.com) '.investment-school.com', // 210.253.115.159 by Yukiyo Yamamoto (info at 15-mail.com) '.breakjuku.com', // 210.253.115.159 (service provider bet.co.jp = xserver.jp) '.nambara.biz', // by Yukiyo Yamamoto (info at 15-mail.com) ), '.all-affiliater.com', // 202.222.30.18(sv125.lolipop.jp), ns *.lolipop.jp '.chachai.com', // 210.188.205.161(sv339.lolipop.jp) by tetsuo ihira (chachai at hida-kawai.jp) 'E-brainers.com related' => array( // 202.212.14.101 '.cyoto-morketing-club.com', // by Fujio Iwasaki (domain at sppd.co.jp) '.e-brainers.com', // by Fujio Iwasaki (domain at sppd.co.jp) '.my-tune.jp', // by brainers Inc. '.technical-support-center.com',// by Fujio Iwasaki (domain at sppd.co.jp) '.weekle.jp', // by brainers Inc. // 210.136.111.56 by Masatoshi Kobayashi (domain at e-brainers.com) // 210.136.111.56 by Fujio Iwasaki (domain at sppd.co.jp) '.3minutes-marketing-club.com', // by Fujio '.affiliate-vampire.com', // by Masatoshi '.article-site-power-package.com', // by Masatoshi '.audio-marketing-club.com', // by Fujio '.brainers-task-manager.com', // by Masatoshi '.brainers-troubleshooter-generator.com', // by Masatoshi '.brainersbuzz.com', // by Masatoshi '.den4renz-marketing-club.com', // by Fujio '.english-contents-club.com', // by Masatoshi '.fly-in-ads-japan.com', // by Fujio '.free-resalerights-giveaway.com', // by Fujio '.freegiveawaysecret.com', // by Masatoshi '.guaranteedvisitorpro.com', // by Masatoshi '.havads-japan.com', // by Masatoshi '.info-business123.com', // by Fujio '.instant-marketing-club.com', // by Fujio '.internetmarketinggorinjyu.com', // by Masatoshi '.marketing-force-japan.com', // by Fujio '.masatoshikobayashi.com', // by Fujio '.profitsinstigator.com', // by Masatoshi Kobayashi (akada at e-brainers.com) '.replytomatt.com', // by Fujio '.santa-deal.com', // by Fujio '.santa-deal-summer.com', // by Fujio '.scratch-card-factory.com', // by Masatoshi '.script4you-japan.com', // by Fujio '.sell1000000dollarinjapan.com',// by Fujio '.squeeze-page-secret.com', // by Masatoshi '.viral-blog-square.com', // by Fujio '.viralarticle.com', // by Fujio '.wowhoken.com', // by Fujio // 202.212.14.104 by Fujio Iwasaki (domain at sppd.co.jp) '.brainerstelevision.com', '.demosite4you.com', '.keywordcatcherpro.com', '.script-marketing-club.com', // 202.228.204.140(server.ultimate-marketing-weapon.com) by Masatoshi Kobayashi (akada at e-brainers.com) // 202.228.204.140 by Masatoshi Kobayashi (domain at e-brainers.com) // 202.228.204.140 by Naoki Kobayashi (info at bet.co.jp) '.1sap.com', // by Naoki, ns *.ultimate-marketing-weapon.com '.brainers.ws', // by info at key-systems.net, ns *.ultimate-marketing-weapon.com '.brainerscode.com', // by akada '.brainerslive.com', // by domain '.brainersreview.com', // by domain '.brainerstest.com', // by akada '.otosecret.com', // by domain '.ultimate-marketing-weapon.com', // by akada '.planet-club.net', // 202.228.204.141(server.ultimate-marketing-weapon.com) '.terk.jp', // by Tsuyoshi Tsukada, QHM '.samuraiautoresponder.com', // 211.125.179.75(bq1.mm22.jp) by Masatoshi Kobayashi (kobayashi at wowhoken.com) '.sppd.co.jp', // 210.136.106.122 by Studio Map Ltd., ns *.sppd.ne.jp, spam ), '.e2996.com', // 202.181.105.241(sv261.lolipop.jp) 'ezinearticles.com', // 216.235.79.13 by C Knight (opensrs at sparknet.net) '.fx4rich.com', // 219.94.128.161(www921.sakura.ne.jp) by Yuji Nakano (info at will76.com) 'gonz-style.com', // 210.251.253.242(s187.xrea.com) by arai at p-cafe.net, reseller 'Hokuken.com' => array( // Bisuness promotion, affiliate about QHM '.hokuken.com', // 210.188.216.191(sv399.lolipop.jp) by Takahiro Kameda (registrant email admin at muumuu-domain.com) '.1st-easy-hp.com', // 210.188.201.45(sv84.xserver.jp) by takahiro kameda (customer at hokuken.com) '.open-qhm.net', // 125.53.25.8(s297.xrea.com), was 202.222.31.223(sv183.lolipop.jp) "Open QHM by hokuken" // Redirects and affiliates: // (They all use "paperboy and co." related services, muumuu-domain.com and lolipop.jp) // yousense.info/fwd/mama1 redirects to www.infocart.jp/af.php?af=520517&url=www.1st-easy-hp.com/index.php?iInfoCart&item=XXXX redirects to www.1st-easy-hp.com/index.php?iInfoCart // info.mizo3.com/fwd/qhm redirects to (*snip*)af=moukaru88y(*snip*) // sanpei.vc/fwd/startkit redirects to (*snip*)af=katosanpe(*snip*) // ysa-techno.com/fwd/homepagesakusei redirects to (*snip*)af=yukko777(*snip*) // qhm.kikikan.com points several links to (*snip*)af=kikikan(*snip*) // www.writeonjp.com/puki points several links to (*snip*)af=notes(*snip*) // ... // Other suggestions: // info.mizo3.com says: "Owners who bought QHM from MY site..." // Blog posting at the same time // 2007/06/13 hidenonikki.seesaa.net/archives/20070613-1.html // 2007/06/13 e123.info/archives/76 // 2007/06/14 bobbin1950.seesaa.net/archives/20070614-1.html // 2007/06/25 ichibankantan.seesaa.net/article/52650651.html // 2007/06/26 www.neko01.com/pc/blog/2007/06/open_quick_homepage_maker_1.php ), 'info at kobeweb.jp' => array( '.soholife.jp', // 211.125.65.203 by Takashige Tabuchi (info at kobeweb.jp) '.kobeweb.jp', // 59.106.13.51(www421.sakura.ne.jp) '.sloters.tv', // 211.125.65.203 by Takashige Tabuchi (t-2 at white.interq.or.jp) ), '.info-affiliate.net', // 219.94.148.8(sv41.chicappa.jp) 'Infocart.jp' => array( // by wai at infocart.jp // Trying to earn money easily by selling 'earn-money-easiliy' tips //descr: INFOMAG (Shimooka,Yasuyoshi) '.infocart.jp', // 60.32.154.171, by Hawaiikigyo, affiliate //inetnum: 60.32.154.176 - 60.32.154.183 // descr: HAWAII KIGYO.COM (Shimooka,Yasuyoshi) '.infomag.jp', // 60.32.154.179, by Infocart, business promotion ), 'Info-sniper.com' => array( '.1koibana.com', // 59.106.12.162(sv265.lolipop.jp), says "Info-sniper presents" '.info-sniper.com', // 202.222.18.25(sv37.lolipop.jp) '.mailjoho.com', // 202.222.19.81(sv70.lolipop.jp), says "Info-sniper", link to info-sniper.com and 2muryoureport.com ), '.infostore.jp', // 216.255.235.45, ns *.estore.co.jp '.junquito55.com', // 59.106.12.213(sv281.lolipop.jp) 'JunSuzuki.com' => array( // e-brainers.com related '.junsuzuki.com', // 218.216.67.43(s92.xrea.com) by Jun Suzuki (jun_suzuki at compus.net) '.globalswing.biz', // 210.188.217.109(sv27.xserverzero.net) ), 'Natsukih.net' => array( '.natsukih.net', // 210.188.245.5(sv04.futurismworks.jp) by natsuki hayashi(ii at leo.bekkoame.ne.jp) '.1seikou.biz', // 221.186.251.73(s68.xrea.com), says "by natsuki hayashi", "Heisei natsuki project" '.oniblog.net', // 210.251.253.242(s187.xrea.com), says "Heisei natsuki project", see also blog.1seikou.biz '.muryoureport.com', // 210.188.205.58(sv311.lolipop.jp), redirect to 2muryoureport.com // by info at natsukih.net '.1muryoureport.com', // 222.227.75.40(s162.xrea.com), says "Heisei natsuki project" '.2muryoureport.com', // 59.139.29.227(s233.xrea.com), says "Heisei natsuki project" '.3muryoureport.com', // 222.227.75.45(s167.xrea.com) '.4muryoureport.com', // 202.222.31.77(sakura1.digi-rock.com) '.5muryoureport.com', // 210.251.253.230 '.6muryoureport.com', // 202.222.31.77(*snip*) '.7muryoureport.com', // 202.222.31.77(*snip*) '.muryouaff.com', // 210.251.253.238(s183.xrea.com) ), 'Point-park.com' => array( // Tadahiro Ogawa (domain at wide.ne.jp) '.11kanji.com', // 211.10.131.88 '.mlmsupport.jp', // 211.10.131.108 by info at point-park.com '.point-park.com', // 211.10.131.88 '.point-park.jp', // 43.244.140.160(160.140.244.43.ap.yournet.ne.jp) ), '.potitto.info', // 219.94.132.89(sv450.lolipop.jp) 'PRJAPAN.co.jp' => array( //'.prjapan.co.jp', // 211.10.20.143(sv.prjapan.co.jp) 'go.prjapan.co.jp', // 210.189.72.220(sv.webstars.jp) '.bestsale.jp', // 210.189.77.143 "Public Relations Inc." by info at prjapan.co.jp, kamita at prjapan.co.jp, nakade at prjapan.co.jp '.hyouka-navi.jp', // 202.218.52.63(sv.numberzoo.jp) by kamita at i-say.net '.sugowaza.jp', // 210.189.77.143(sv.bestsale.jp) by kamita at i-say.net, //'.webstars.jp', // 210.189.72.220 by info at prjapan.co.jp ), 'Rakuten.co.jp' => array( 'hb.afl.rakuten.co.jp', ///hsc/ 203.190.60.104 redirect to rakuten.co.jp 'hbb.afl.rakuten.co.jp', ///hsb/ 203.190.60.105 image server? ), '.sedori-data.com', // 210.188.205.7(sv03.lolipop.jp) '.tool4success.com', // 210.188.201.31(sv70.xserver.jp) by Yukihiro Akada (ml at original-ehon.com) 'tera at kirinn.com' => array( // 59.139.29.234(s240.xrea.com) by Naohsi Terada (tera at kirinn.com) '.e123.info', '.ialchemist.net', '.j012.net', '.xn--yckc2auxd4b6564dogvcf7g.biz', ), 'Viscose.jp' => array( '.web-navi21.com', // 202.222.30.12 by kazuhiro shikano(shikano at guitar.ocn.ne.jp) '.viscose.jp', ///link/ 210.188.205.205(sv370.lolipop.jp) by kazuhiro shikano ), '.zakkuzaku.com', // 210.188.201.44(sv83.xserver.jp) ); // -------------------------------------------------- $blocklist['Z'] = array( // Z: Yours // //'', //'', //'', ); ?>
gpl-2.0
s-papanastasiou/wireless-positioning
WifiPositioning/AndroidVisualiser/src/main/java/me/gregalbiston/androidvisualiser/display/SummaryListPreference.java
1043
package me.gregalbiston.androidvisualiser.display; import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; /** * Created with IntelliJ IDEA. * User: Greg Albiston * Date: 28/07/13 * Time: 18:39 * Based on Michael answer on Aug 10 '11: http://stackoverflow.com/questions/7017082/change-the-summary-of-a-listpreference-with-the-new-value-android - */ public class SummaryListPreference extends ListPreference { public SummaryListPreference(final Context context, final AttributeSet attrs) { super(context, attrs); } @Override public CharSequence getSummary() { final CharSequence entry = getEntry(); final CharSequence summary = super.getSummary(); if (summary == null || entry == null) { return null; } else { return String.format(summary.toString(), entry); } } @Override public void setValue(final String value) { super.setValue(value); notifyChanged(); } }
gpl-2.0
ciricihq/CakeOAuth2Client
tests/TestCase/Controller/AuthControllerTest.php
287
<?php namespace App\Test\TestCase\Controller; use Cake\TestSuite\IntegrationTestCase; use Cake\Routing\Router; class AuthControllerTest extends IntegrationTestCase { public function testLogin() { $this->get('/oauth2/login'); $this->assertResponseOk(); } }
gpl-2.0
fenexomega/MeheTutorials
7/main.cpp
5460
#include<iostream> #include<GL/glut.h> #include"SOIL/SOIL.h" #include<unistd.h> using namespace std; GLuint textures[3]; float rotx = 0; float roty = 0; float rotz = 0; bool fullscreen; bool active; bool keys[256]; bool light; bool lp; bool lf; GLfloat LightAmbient[] = { 0.5f, 0.5f,0.5f,0.5f}; GLfloat LightDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f}; GLfloat LightPosition[] = { 0.0f, 0.0f, 2.0f, 1.0f}; GLuint filter = 0; GLuint texture[3]; float xcof = 0; float ycof = 0; typedef struct GIMAGE { const char *filename; int width; int height; int *channels; unsigned char* DATA; int force_channels; }gImage; int as = 0; void DrawGL() { glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glLoadIdentity(); glTranslatef(0,0,-5.0f); glRotatef(rotx,1.0f,0,0); glRotatef(roty,0,1.0f,0); glBindTexture(GL_TEXTURE_2D,texture[filter]); glBegin(GL_QUADS); // Front Face glNormal3f(0.0f,0.0f,1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Back Face glNormal3f(0.0f,0.0f,-1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Top Face glNormal3f(0.0f,1.0f,0.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Bottom Face glNormal3f(0.0f,-1.0f,1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Right face glNormal3f(1.0f,0.0f,1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Left Face glNormal3f(-1.0f,0.0f,1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glEnd(); rotx += xcof; roty += ycof; glutSwapBuffers(); } bool LoadGLTextures() { gImage image; /*for(int i = 0 ; i < 3; ++i) { aux = texture[i] = SOIL_load_OGL_texture( "Crate.bmp", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y | SOIL_FLAG_MIPMAPS ); if(aux == 0) { cout << SOIL_last_result() << endl; } }*/ image.DATA = SOIL_load_image("Crate.bmp", &image.width,&image.height,0, SOIL_LOAD_RGB); cout << SOIL_last_result() << endl; glGenTextures(3,texture); glBindTexture(GL_TEXTURE_2D,texture[0]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D,0,3,image.width,image.height,0,GL_RGB,GL_UNSIGNED_BYTE,image.DATA); glBindTexture(GL_TEXTURE_2D,texture[1]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D,0,3,image.width,image.height,0,GL_RGB,GL_UNSIGNED_BYTE,image.DATA); glBindTexture(GL_TEXTURE_2D,texture[2]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D,3,image.width,image.height,GL_RGB,GL_UNSIGNED_BYTE,image.DATA); return true; } void InitGL() { LoadGLTextures(); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glClearDepth(1.0f); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); glLightfv(GL_LIGHT1, GL_POSITION, LightPosition); glEnable(GL_LIGHT1); } void ReshapeGL(int w, int h) { float ratio = (float) w/ (float) h; glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f,ratio,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void UpdateInput(unsigned char key, int x, int y) { switch(key) { case 'l': glIsEnabled(GL_LIGHTING) == 1 ? glDisable(GL_LIGHTING) : glEnable(GL_LIGHTING); break; case 'f': filter = (filter+1)%3; break; } } void UpdateSplInput(int key, int x, int y) { switch(key) { case GLUT_KEY_RIGHT: ycof -= 0.1f; break; case GLUT_KEY_LEFT: ycof += 0.1f; break; case GLUT_KEY_UP: xcof -= 0.1f; break; case GLUT_KEY_DOWN: xcof += 0.1f; break; } } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitWindowSize(800,600); glutInitDisplayMode(GLUT_DEPTH | GLUT_RGBA | GLUT_DOUBLE); glutCreateWindow("Nehe 7 - Lighinting"); InitGL(); glutDisplayFunc(DrawGL); glutIdleFunc(DrawGL); glutReshapeFunc(ReshapeGL); glutKeyboardFunc(UpdateInput); glutSpecialFunc(UpdateSplInput); glutMainLoop(); return 0; }
gpl-2.0
raedkleelsame/phpmyadmin
test/selenium/PmaSeleniumDbProceduresTest.php
5784
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Selenium TestCase for table related tests * * @package PhpMyAdmin-test * @subpackage Selenium */ require_once 'TestBase.php'; /** * PmaSeleniumDbProceduresTest class * * @package PhpMyAdmin-test * @subpackage Selenium */ class PMA_SeleniumDbProceduresTest extends PMA_SeleniumBase { /** * Setup the browser environment to run the selenium test case * * @return void */ public function setUp() { parent::setUp(); $this->dbQuery( "CREATE TABLE `test_table` (" . " `id` int(11) NOT NULL AUTO_INCREMENT," . " `name` varchar(20) NOT NULL," . " `datetimefield` datetime NOT NULL," . " PRIMARY KEY (`id`)" . ")" ); } /** * setUp function that can use the selenium session (called before each test) * * @return void */ public function setUpPage() { $this->login(); $this->waitForElement('byLinkText', $this->database_name)->click(); $this->waitForElement( "byXPath", "//a[contains(., 'test_table')]" ); $this->expandMore(); } /** * Creates procedure for tests * * @return void */ private function _procedureSQL() { $this->dbQuery( "CREATE PROCEDURE `test_procedure`(IN `inp` VARCHAR(10), OUT `outp` INT)" . " NOT DETERMINISTIC READS SQL DATA SQL SECURITY DEFINER SELECT char_" . "length(inp) + count(*) FROM test_table INTO outp" ); } /** * Create a procedure * * @return void * * @group large */ public function testAddProcedure() { $ele = $this->waitForElement("byPartialLinkText", "Routines"); $ele->click(); $ele = $this->waitForElement("byLinkText", "Add routine"); $ele->click(); $this->waitForElement("byClassName", "rte_form"); $this->byName("item_name")->value("test_procedure"); $this->byName("item_param_name[0]")->value("inp"); $this->select( $this->byName("item_param_type[0]") )->selectOptionByLabel("VARCHAR"); $this->byName("item_param_length[0]")->value("10"); $this->byCssSelector("input[value='Add parameter']")->click(); $this->select( $this->byName("item_param_dir[1]") )->selectOptionByLabel("OUT"); $ele = $this->waitForElement("byName", "item_param_name[1]"); $ele->value("outp"); $proc = "SELECT char_length(inp) + count(*) FROM test_table INTO outp"; $this->typeInTextArea($proc); $this->select( $this->byName("item_sqldataaccess") )->selectOptionByLabel("READS SQL DATA"); $this->byXPath("//button[contains(., 'Go')]")->click(); $ele = $this->waitForElement( "byXPath", "//div[@class='success' and contains(., " . "'Routine `test_procedure` has been created')]" ); $result = $this->dbQuery( "SHOW PROCEDURE STATUS WHERE Db='" . $this->database_name . "'" ); $this->assertEquals(1, $result->num_rows); $this->_executeProcedure("abcabcabcabcabcabcabc", 10); } /** * Test for editing procedure * * @return void * * @group large */ public function testEditProcedure() { $this->_procedureSQL(); $ele = $this->waitForElement("byPartialLinkText", "Routines"); $ele->click(); $this->waitForElement( "byXPath", "//legend[contains(., 'Routines')]" ); $this->byLinkText("Edit")->click(); $this->waitForElement("byClassName", "rte_form"); $this->byName("item_param_length[0]")->clear(); $this->byName("item_param_length[0]")->value("12"); $this->byXPath("//button[contains(., 'Go')]")->click(); $ele = $this->waitForElement( "byXPath", "//div[@class='success' and contains(., " . "'Routine `test_procedure` has been modified')]" ); $this->_executeProcedure("abcabcabcabcabcabcabc", 12); } /** * Test for dropping procedure * * @return void * * @group large */ public function testDropProcedure() { $this->_procedureSQL(); $ele = $this->waitForElement("byPartialLinkText", "Routines"); $ele->click(); $this->waitForElement( "byXPath", "//legend[contains(., 'Routines')]" ); $this->byLinkText("Drop")->click(); $this->waitForElement( "byXPath", "//button[contains(., 'OK')]" )->click(); $this->waitForElement("byId", "nothing2display"); usleep(1000000); $result = $this->dbQuery( "SHOW PROCEDURE STATUS WHERE Db='" . $this->database_name . "'" ); $this->assertEquals(0, $result->num_rows); } /** * Execute procedure * * @param string $text String to pass as inp param * @param int $length Expected output length * * @return void */ private function _executeProcedure($text, $length) { $this->waitForElement("byLinkText", "Execute")->click(); $this->waitForElement("byName", "params[inp]")->value($text); $this->byCssSelector("div.ui-dialog-buttonset button:nth-child(1)")->click(); $this->waitForElement( "byCssSelector", "span#PMA_slidingMessage table tbody" ); $head = $this->byCssSelector("span#PMA_slidingMessage table tbody")->text(); $this->assertEquals("outp\n$length", $head); } }
gpl-2.0
danieljabailey/inkscape_experiments
src/shortcuts.cpp
25316
/** \file * Keyboard shortcut processing. */ /* * Authors: * Lauris Kaplinski <[email protected]> * MenTaLguY <[email protected]> * bulia byak <[email protected]> * Peter Moulder <[email protected]> * * Copyright (C) 2005 Monash University * Copyright (C) 2005 MenTaLguY <[email protected]> * * You may redistribute and/or modify this file 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. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vector> #include <cstring> #include <string> #include <map> #include "shortcuts.h" #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <gtk/gtk.h> #include <glibmm/convert.h> #include <glibmm/i18n.h> #include <glibmm/miscutils.h> #include "helper/action.h" #include "helper/action-context.h" #include "io/sys.h" #include "io/resource.h" #include "verbs.h" #include "xml/node-iterators.h" #include "xml/repr.h" #include "document.h" #include "preferences.h" #include "ui/tools/tool-base.h" #include "inkscape.h" #include "desktop.h" #include "path-prefix.h" #include "ui/dialog/filedialog.h" using namespace Inkscape; using Inkscape::IO::Resource::get_path; using Inkscape::IO::Resource::SYSTEM; using Inkscape::IO::Resource::USER; using Inkscape::IO::Resource::KEYS; static void try_shortcuts_file(char const *filename); static void read_shortcuts_file(char const *filename, bool const is_user_set=false); unsigned int sp_shortcut_get_key(unsigned int const shortcut); GdkModifierType sp_shortcut_get_modifiers(unsigned int const shortcut); /* Returns true if action was performed */ bool sp_shortcut_invoke(unsigned int shortcut, Inkscape::UI::View::View *view) { Inkscape::Verb *verb = sp_shortcut_get_verb(shortcut); if (verb) { SPAction *action = verb->get_action(Inkscape::ActionContext(view)); if (action) { sp_action_perform(action, NULL); return true; } } return false; } static std::map<unsigned int, Inkscape::Verb * > *verbs = NULL; static std::map<Inkscape::Verb *, unsigned int> *primary_shortcuts = NULL; static std::map<Inkscape::Verb *, unsigned int> *user_shortcuts = NULL; void sp_shortcut_init() { verbs = new std::map<unsigned int, Inkscape::Verb * >(); primary_shortcuts = new std::map<Inkscape::Verb *, unsigned int>(); user_shortcuts = new std::map<Inkscape::Verb *, unsigned int>(); Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring shortcutfile = prefs->getString("/options/kbshortcuts/shortcutfile"); if (shortcutfile.empty()) { shortcutfile = Glib::ustring(get_path(SYSTEM, KEYS, "default.xml")); } read_shortcuts_file(shortcutfile.c_str()); try_shortcuts_file(get_path(USER, KEYS, "default.xml")); } static void try_shortcuts_file(char const *filename) { using Inkscape::IO::file_test; /* ah, if only we had an exception to catch... (permission, forgiveness) */ if (file_test(filename, G_FILE_TEST_EXISTS)) { read_shortcuts_file(filename, true); } } /* * Inkscape expects to add the Shift modifier to any accel_keys create with Shift * For exmaple on en_US keyboard <Shift>+6 = "&" - in this case return <Shift>+& * See get_group0_keyval() for explanation on why */ unsigned int sp_gdkmodifier_to_shortcut(guint accel_key, Gdk::ModifierType gdkmodifier, guint hardware_keycode) { unsigned int shortcut = 0; GdkEventKey event; event.state = gdkmodifier; event.keyval = accel_key; event.hardware_keycode = hardware_keycode; guint keyval = Inkscape::UI::Tools::get_group0_keyval (&event); shortcut = accel_key | ( (gdkmodifier & GDK_SHIFT_MASK) || ( accel_key != keyval) ? SP_SHORTCUT_SHIFT_MASK : 0 ) | ( gdkmodifier & GDK_CONTROL_MASK ? SP_SHORTCUT_CONTROL_MASK : 0 ) | ( gdkmodifier & GDK_MOD1_MASK ? SP_SHORTCUT_ALT_MASK : 0 ); return shortcut; } Glib::ustring sp_shortcut_to_label(unsigned int const shortcut) { Glib::ustring modifiers = ""; if (shortcut & SP_SHORTCUT_CONTROL_MASK) modifiers += "Ctrl,"; if (shortcut & SP_SHORTCUT_SHIFT_MASK) modifiers += "Shift,"; if (shortcut & SP_SHORTCUT_ALT_MASK) modifiers += "Alt,"; if(modifiers.length() > 0 && modifiers.find(',',modifiers.length()-1)!=modifiers.npos) { modifiers.erase(modifiers.length()-1, 1); } return modifiers; } /* * REmove all shortucts from the users file */ void sp_shortcuts_delete_all_from_file() { char const *filename = get_path(USER, KEYS, "default.xml"); XML::Document *doc=sp_repr_read_file(filename, NULL); if (!doc) { g_warning("Unable to read keys file %s", filename); return; } XML::Node *root=doc->root(); g_return_if_fail(!strcmp(root->name(), "keys")); XML::Node *iter=root->firstChild(); while (iter) { if (strcmp(iter->name(), "bind")) { // some unknown element, do not complain iter = iter->next(); continue; } // Delete node sp_repr_unparent(iter); iter=root->firstChild(); } sp_repr_save_file(doc, filename, NULL); GC::release(doc); } Inkscape::XML::Document *sp_shortcut_create_template_file(char const *filename) { gchar const *buffer = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> " "<keys name=\"My custom shortcuts\">" "</keys>"; Inkscape::XML::Document *doc = sp_repr_read_mem(buffer, strlen(buffer), NULL); sp_repr_save_file(doc, filename, NULL); return sp_repr_read_file(filename, NULL); } /* * Get a list of keyboard shortcut files names and paths from the system and users paths * Dont add the users custom keyboards file */ void sp_shortcut_get_file_names(std::vector<Glib::ustring> *names, std::vector<Glib::ustring> *paths) { std::list<gchar *> sources; sources.push_back( Inkscape::Application::profile_path("keys") ); sources.push_back( g_strdup(INKSCAPE_KEYSDIR) ); // loop through possible keyboard shortcut file locations. while (!sources.empty()) { gchar *dirname = sources.front(); if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS ) && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) { GError *err = 0; GDir *directory = g_dir_open(dirname, 0, &err); if (!directory) { gchar *safeDir = Inkscape::IO::sanitizeString(dirname); g_warning(_("Keyboard directory (%s) is unavailable."), safeDir); g_free(safeDir); } else { gchar *filename = 0; while ((filename = (gchar *) g_dir_read_name(directory)) != NULL) { gchar* lower = g_ascii_strdown(filename, -1); if (!strcmp(dirname, Inkscape::Application::profile_path("keys")) && !strcmp(lower, "default.xml")) { // Dont add the users custom keys file continue; } if (!strcmp(dirname, INKSCAPE_KEYSDIR) && !strcmp(lower, "inkscape.xml")) { // Dont add system inkscape.xml (since its a duplicate? of dfefault.xml) continue; } if (g_str_has_suffix(lower, ".xml")) { gchar* full = g_build_filename(dirname, filename, NULL); if (!Inkscape::IO::file_test(full, G_FILE_TEST_IS_DIR)) { // Get the "key name" from the root element of each file XML::Document *doc=sp_repr_read_file(full, NULL); if (!doc) { g_warning("Unable to read keyboard shortcut file %s", full); continue; } XML::Node *root=doc->root(); if (strcmp(root->name(), "keys")) { g_warning("Not a shortcut keys file %s", full); Inkscape::GC::release(doc); continue; } gchar const *name=root->attribute("name"); Glib::ustring label(filename); if (name) { label = Glib::ustring(name)+ " (" + filename + ")"; } if (!strcmp(filename, "default.xml")) { paths->insert(paths->begin(), full); names->insert(names->begin(), label.c_str()); } else { paths->push_back(full); names->push_back(label.c_str()); } Inkscape::GC::release(doc); } g_free(full); } g_free(lower); } g_dir_close(directory); } } g_free(dirname); sources.pop_front(); } } Glib::ustring sp_shortcut_get_file_path() { //# Get the current directory for finding files Glib::ustring open_path; Inkscape::Preferences *prefs = Inkscape::Preferences::get(); Glib::ustring attr = prefs->getString("/dialogs/save_export/path"); if (!attr.empty()) open_path = attr; //# Test if the open_path directory exists if (!Inkscape::IO::file_test(open_path.c_str(), (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) open_path = ""; if (open_path.empty()) { /* Grab document directory */ const gchar* docURI = SP_ACTIVE_DOCUMENT->getURI(); if (docURI) { open_path = Glib::path_get_dirname(docURI); open_path.append(G_DIR_SEPARATOR_S); } } //# If no open path, default to our home directory if (open_path.empty()) { open_path = g_get_home_dir(); open_path.append(G_DIR_SEPARATOR_S); } return open_path; } //static Inkscape::UI::Dialog::FileSaveDialog * saveDialog = NULL; void sp_shortcut_file_export() { Glib::ustring open_path = sp_shortcut_get_file_path(); open_path.append("shortcut_keys.xml"); SPDesktop *desktop = SP_ACTIVE_DESKTOP; Glib::ustring filename; Inkscape::UI::Dialog::FileSaveDialog *saveDialog = Inkscape::UI::Dialog::FileSaveDialog::create( *(desktop->getToplevel()), open_path, Inkscape::UI::Dialog::CUSTOM_TYPE, _("Select a filename for exporting"), "", "", Inkscape::Extension::FILE_SAVE_METHOD_SAVE_AS ); saveDialog->addFileType("All Files", "*"); bool success = saveDialog->show(); if (!success) { delete saveDialog; return; } Glib::ustring fileName = saveDialog->getFilename(); if (fileName.size() > 0) { Glib::ustring newFileName = Glib::filename_to_utf8(fileName); sp_shortcut_file_export_do(newFileName.c_str()); } delete saveDialog; } bool sp_shortcut_file_import() { Glib::ustring open_path = sp_shortcut_get_file_path(); SPDesktop *desktop = SP_ACTIVE_DESKTOP; Inkscape::UI::Dialog::FileOpenDialog *importFileDialog = Inkscape::UI::Dialog::FileOpenDialog::create( *desktop->getToplevel(), open_path, Inkscape::UI::Dialog::CUSTOM_TYPE, _("Select a file to import")); importFileDialog->addFilterMenu("All Files", "*"); //# Show the dialog bool const success = importFileDialog->show(); if (!success) { delete importFileDialog; return false; } Glib::ustring fileName = importFileDialog->getFilename(); sp_shortcut_file_import_do(fileName.c_str()); delete importFileDialog; return true; } void sp_shortcut_file_import_do(char const *importname) { XML::Document *doc=sp_repr_read_file(importname, NULL); if (!doc) { g_warning("Unable to read keyboard shortcut file %s", importname); return; } char const *filename = get_path(USER, KEYS, "default.xml"); sp_repr_save_file(doc, filename, NULL); GC::release(doc); sp_shortcut_init(); } void sp_shortcut_file_export_do(char const *exportname) { char const *filename = get_path(USER, KEYS, "default.xml"); XML::Document *doc=sp_repr_read_file(filename, NULL); if (!doc) { g_warning("Unable to read keyboard shortcut file %s", filename); return; } sp_repr_save_file(doc, exportname, NULL); GC::release(doc); } /* * Add or delete a shortcut to the users default.xml keys file * @param addremove - when true add/override a shortcut, when false remove shortcut * @param addshift - when true addthe Shifg modifier to the non-display element * * Shortcut file consists of pairs of bind elements : * Element (a) is used for shortcut display in menus (display="True") and contains the gdk_keyval_name of the shortcut key * Element (b) is used in shortcut lookup and contains an uppercase version of the gdk_keyval_name, * or a gdk_keyval_name name and the "Shift" modifier for Shift altered hardware code keys (see get_group0_keyval() for explanation) */ void sp_shortcut_delete_from_file(char const * /*action*/, unsigned int const shortcut) { char const *filename = get_path(USER, KEYS, "default.xml"); XML::Document *doc=sp_repr_read_file(filename, NULL); if (!doc) { g_warning("Unable to read keyboard shortcut file %s", filename); return; } gchar *key = gdk_keyval_name (sp_shortcut_get_key(shortcut)); std::string modifiers = sp_shortcut_to_label(shortcut & (SP_SHORTCUT_MODIFIER_MASK)); if (!key) { g_warning("Unknown key for shortcut %u", shortcut); return; } //g_message("Removing key %s, mods %s action %s", key, modifiers.c_str(), action); XML::Node *root=doc->root(); g_return_if_fail(!strcmp(root->name(), "keys")); XML::Node *iter=root->firstChild(); while (iter) { if (strcmp(iter->name(), "bind")) { // some unknown element, do not complain iter = iter->next(); continue; } gchar const *verb_name=iter->attribute("action"); if (!verb_name) { iter = iter->next(); continue; } gchar const *keyval_name = iter->attribute("key"); if (!keyval_name || !*keyval_name) { // that's ok, it's just listed for reference without assignment, skip it iter = iter->next(); continue; } if (Glib::ustring(key).lowercase() != Glib::ustring(keyval_name).lowercase()) { // If deleting, then delete both the upper and lower case versions iter = iter->next(); continue; } gchar const *modifiers_string = iter->attribute("modifiers"); if ((modifiers_string && !strcmp(modifiers.c_str(), modifiers_string)) || (!modifiers_string && modifiers.empty())) { //Looks like a match // Delete node sp_repr_unparent(iter); iter = root->firstChild(); continue; } iter = iter->next(); } sp_repr_save_file(doc, filename, NULL); GC::release(doc); } void sp_shortcut_add_to_file(char const *action, unsigned int const shortcut) { char const *filename = get_path(USER, KEYS, "default.xml"); XML::Document *doc=sp_repr_read_file(filename, NULL); if (!doc) { g_warning("Unable to read keyboard shortcut file %s, creating ....", filename); doc = sp_shortcut_create_template_file(filename); if (!doc) { g_warning("Unable to create keyboard shortcut file %s", filename); return; } } gchar *key = gdk_keyval_name (sp_shortcut_get_key(shortcut)); std::string modifiers = sp_shortcut_to_label(shortcut & (SP_SHORTCUT_MODIFIER_MASK)); if (!key) { g_warning("Unknown key for shortcut %u", shortcut); return; } //g_message("Adding key %s, mods %s action %s", key, modifiers.c_str(), action); // Add node Inkscape::XML::Node *newnode; newnode = doc->createElement("bind"); newnode->setAttribute("key", key); if (!modifiers.empty()) { newnode->setAttribute("modifiers", modifiers.c_str()); } newnode->setAttribute("action", action); newnode->setAttribute("display", "true"); doc->root()->appendChild(newnode); if (strlen(key) == 1) { // Add another uppercase version if a character Inkscape::XML::Node *newnode; newnode = doc->createElement("bind"); newnode->setAttribute("key", Glib::ustring(key).uppercase().c_str()); if (!modifiers.empty()) { newnode->setAttribute("modifiers", modifiers.c_str()); } newnode->setAttribute("action", action); doc->root()->appendChild(newnode); } sp_repr_save_file(doc, filename, NULL); GC::release(doc); } static void read_shortcuts_file(char const *filename, bool const is_user_set) { XML::Document *doc=sp_repr_read_file(filename, NULL); if (!doc) { g_warning("Unable to read keys file %s", filename); return; } XML::Node const *root=doc->root(); g_return_if_fail(!strcmp(root->name(), "keys")); XML::NodeConstSiblingIterator iter=root->firstChild(); for ( ; iter ; ++iter ) { bool is_primary; if (!strcmp(iter->name(), "bind")) { is_primary = iter->attribute("display") && strcmp(iter->attribute("display"), "false") && strcmp(iter->attribute("display"), "0"); } else { // some unknown element, do not complain continue; } gchar const *verb_name=iter->attribute("action"); if (!verb_name) { g_warning("Missing verb name (action= attribute) for shortcut"); continue; } Inkscape::Verb *verb=Inkscape::Verb::getbyid(verb_name); if (!verb #if !HAVE_POTRACE // Squash warning about disabled features && strcmp(verb_name, "ToolPaintBucket") != 0 && strcmp(verb_name, "SelectionTrace") != 0 && strcmp(verb_name, "PaintBucketPrefs") != 0 #endif ) { g_warning("Unknown verb name: %s", verb_name); continue; } gchar const *keyval_name=iter->attribute("key"); if (!keyval_name || !*keyval_name) { // that's ok, it's just listed for reference without assignment, skip it continue; } guint keyval=gdk_keyval_from_name(keyval_name); if (keyval == GDK_KEY_VoidSymbol || keyval == 0) { g_warning("Unknown keyval %s for %s", keyval_name, verb_name); continue; } guint modifiers=0; gchar const *modifiers_string=iter->attribute("modifiers"); if (modifiers_string) { gchar const *iter=modifiers_string; while (*iter) { size_t length=strcspn(iter, ","); gchar *mod=g_strndup(iter, length); if (!strcmp(mod, "Control") || !strcmp(mod, "Ctrl")) { modifiers |= SP_SHORTCUT_CONTROL_MASK; } else if (!strcmp(mod, "Shift")) { modifiers |= SP_SHORTCUT_SHIFT_MASK; } else if (!strcmp(mod, "Alt")) { modifiers |= SP_SHORTCUT_ALT_MASK; } else { g_warning("Unknown modifier %s for %s", mod, verb_name); } g_free(mod); iter += length; if (*iter) iter++; } } sp_shortcut_set(keyval | modifiers, verb, is_primary, is_user_set); } GC::release(doc); } /** * Removes a keyboard shortcut for the given verb. * (Removes any existing binding for the given shortcut, including appropriately * adjusting sp_shortcut_get_primary if necessary.)* */ void sp_shortcut_unset(unsigned int const shortcut) { if (!verbs) sp_shortcut_init(); Inkscape::Verb *verb = (*verbs)[shortcut]; /* Maintain the invariant that sp_shortcut_get_primary(v) returns either 0 or a valid shortcut for v. */ if (verb) { (*verbs)[shortcut] = 0; unsigned int const old_primary = (*primary_shortcuts)[verb]; if (old_primary == shortcut) { (*primary_shortcuts)[verb] = 0; } } } GtkAccelGroup * sp_shortcut_get_accel_group() { static GtkAccelGroup *accel_group = NULL; if (!accel_group) { accel_group = gtk_accel_group_new (); } return accel_group; } /** * Adds a gtk accelerator to a widget * Used to display the keyboard shortcuts in the main menu items */ void sp_shortcut_add_accelerator(GtkWidget *item, unsigned int const shortcut) { if (shortcut == GDK_KEY_VoidSymbol) { return; } unsigned int accel_key = sp_shortcut_get_key(shortcut); if (accel_key > 0) { gtk_widget_add_accelerator (item, "activate", sp_shortcut_get_accel_group(), accel_key, sp_shortcut_get_modifiers(shortcut), GTK_ACCEL_VISIBLE); } } unsigned int sp_shortcut_get_key(unsigned int const shortcut) { return (shortcut & (~SP_SHORTCUT_MODIFIER_MASK)); } GdkModifierType sp_shortcut_get_modifiers(unsigned int const shortcut) { return static_cast<GdkModifierType>( ((shortcut & SP_SHORTCUT_SHIFT_MASK) ? GDK_SHIFT_MASK : 0) | ((shortcut & SP_SHORTCUT_CONTROL_MASK) ? GDK_CONTROL_MASK : 0) | ((shortcut & SP_SHORTCUT_ALT_MASK) ? GDK_MOD1_MASK : 0) ); } /** * Adds a keyboard shortcut for the given verb. * (Removes any existing binding for the given shortcut, including appropriately * adjusting sp_shortcut_get_primary if necessary.) * * \param is_primary True iff this is the shortcut to be written in menu items or buttons. * * \post sp_shortcut_get_verb(shortcut) == verb. * \post !is_primary or sp_shortcut_get_primary(verb) == shortcut. */ void sp_shortcut_set(unsigned int const shortcut, Inkscape::Verb *const verb, bool const is_primary, bool const is_user_set) { if (!verbs) sp_shortcut_init(); Inkscape::Verb *old_verb = (*verbs)[shortcut]; (*verbs)[shortcut] = verb; /* Maintain the invariant that sp_shortcut_get_primary(v) returns either 0 or a valid shortcut for v. */ if (old_verb && old_verb != verb) { unsigned int const old_primary = (*primary_shortcuts)[old_verb]; if (old_primary == shortcut) { (*primary_shortcuts)[old_verb] = 0; (*user_shortcuts)[old_verb] = 0; } } if (is_primary) { (*primary_shortcuts)[verb] = shortcut; (*user_shortcuts)[verb] = is_user_set; } } Inkscape::Verb * sp_shortcut_get_verb(unsigned int shortcut) { if (!verbs) sp_shortcut_init(); return (*verbs)[shortcut]; } unsigned int sp_shortcut_get_primary(Inkscape::Verb *verb) { unsigned int result = GDK_KEY_VoidSymbol; if (!primary_shortcuts) { sp_shortcut_init(); } if (primary_shortcuts->count(verb)) { result = (*primary_shortcuts)[verb]; } return result; } bool sp_shortcut_is_user_set(Inkscape::Verb *verb) { unsigned int result = false; if (!primary_shortcuts) { sp_shortcut_init(); } if (primary_shortcuts->count(verb)) { result = (*user_shortcuts)[verb]; } return result; } gchar *sp_shortcut_get_label(unsigned int shortcut) { // The comment below was copied from the function sp_ui_shortcut_string in interface.cpp (which was subsequently removed) /* TODO: This function shouldn't exist. Our callers should use GtkAccelLabel instead of * a generic GtkLabel containing this string, and should call gtk_widget_add_accelerator. * Will probably need to change sp_shortcut_invoke callers. * * The existing gtk_label_new_with_mnemonic call can be replaced with * g_object_new(GTK_TYPE_ACCEL_LABEL, NULL) followed by * gtk_label_set_text_with_mnemonic(lbl, str). */ gchar *result = 0; if (shortcut != GDK_KEY_VoidSymbol) { result = gtk_accelerator_get_label( sp_shortcut_get_key(shortcut), sp_shortcut_get_modifiers(shortcut)); } return result; } /* Local Variables: mode:c++ c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) indent-tabs-mode:nil fill-column:99 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :
gpl-2.0
openbu/client
source/src/saveload/town_sl.cpp
13529
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD 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. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file town_sl.cpp Code handling saving and loading of towns and houses */ #include "../stdafx.h" #include "../newgrf_house.h" #include "../town.h" #include "../landscape.h" #include "../subsidy_func.h" #include "saveload.h" #include "newgrf_sl.h" #include "../safeguards.h" /** * Rebuild all the cached variables of towns. */ void RebuildTownCaches() { Town *town; InitializeBuildingCounts(); /* Reset town population and num_houses */ FOR_ALL_TOWNS(town) { town->cache.population = 0; town->cache.num_houses = 0; } for (TileIndex t = 0; t < MapSize(); t++) { if (!IsTileType(t, MP_HOUSE)) continue; HouseID house_id = GetHouseType(t); town = Town::GetByTile(t); IncreaseBuildingCount(town, house_id); if (IsHouseCompleted(t)) town->cache.population += HouseSpec::Get(house_id)->population; /* Increase the number of houses for every house, but only once. */ if (GetHouseNorthPart(house_id) == 0) town->cache.num_houses++; } /* Update the population and num_house dependent values */ FOR_ALL_TOWNS(town) { UpdateTownRadius(town); UpdateTownCargoes(town); } UpdateTownCargoBitmap(); } /** * Check and update town and house values. * * Checked are the HouseIDs. Updated are the * town population the number of houses per * town, the town radius and the max passengers * of the town. */ void UpdateHousesAndTowns() { for (TileIndex t = 0; t < MapSize(); t++) { if (!IsTileType(t, MP_HOUSE)) continue; HouseID house_id = GetCleanHouseType(t); if (!HouseSpec::Get(house_id)->enabled && house_id >= NEW_HOUSE_OFFSET) { /* The specs for this type of house are not available any more, so * replace it with the substitute original house type. */ house_id = _house_mngr.GetSubstituteID(house_id); SetHouseType(t, house_id); } } /* Check for cases when a NewGRF has set a wrong house substitute type. */ for (TileIndex t = 0; t < MapSize(); t++) { if (!IsTileType(t, MP_HOUSE)) continue; HouseID house_type = GetCleanHouseType(t); TileIndex north_tile = t + GetHouseNorthPart(house_type); // modifies 'house_type'! if (t == north_tile) { const HouseSpec *hs = HouseSpec::Get(house_type); bool valid_house = true; if (hs->building_flags & TILE_SIZE_2x1) { TileIndex tile = t + TileDiffXY(1, 0); if (!IsTileType(tile, MP_HOUSE) || GetCleanHouseType(tile) != house_type + 1) valid_house = false; } else if (hs->building_flags & TILE_SIZE_1x2) { TileIndex tile = t + TileDiffXY(0, 1); if (!IsTileType(tile, MP_HOUSE) || GetCleanHouseType(tile) != house_type + 1) valid_house = false; } else if (hs->building_flags & TILE_SIZE_2x2) { TileIndex tile = t + TileDiffXY(0, 1); if (!IsTileType(tile, MP_HOUSE) || GetCleanHouseType(tile) != house_type + 1) valid_house = false; tile = t + TileDiffXY(1, 0); if (!IsTileType(tile, MP_HOUSE) || GetCleanHouseType(tile) != house_type + 2) valid_house = false; tile = t + TileDiffXY(1, 1); if (!IsTileType(tile, MP_HOUSE) || GetCleanHouseType(tile) != house_type + 3) valid_house = false; } /* If not all tiles of this house are present remove the house. * The other tiles will get removed later in this loop because * their north tile is not the correct type anymore. */ if (!valid_house) DoClearSquare(t); } else if (!IsTileType(north_tile, MP_HOUSE) || GetCleanHouseType(north_tile) != house_type) { /* This tile should be part of a multi-tile building but the * north tile of this house isn't on the map. */ DoClearSquare(t); } } RebuildTownCaches(); } /** Save and load of towns. */ static const SaveLoad _town_desc[] = { SLE_CONDVAR(Town, xy, SLE_FILE_U16 | SLE_VAR_U32, 0, 5), SLE_CONDVAR(Town, xy, SLE_UINT32, 6, SL_MAX_VERSION), SLE_CONDNULL(2, 0, 2), ///< population, no longer in use SLE_CONDNULL(4, 3, 84), ///< population, no longer in use SLE_CONDNULL(2, 0, 91), ///< num_houses, no longer in use SLE_CONDVAR(Town, townnamegrfid, SLE_UINT32, 66, SL_MAX_VERSION), SLE_VAR(Town, townnametype, SLE_UINT16), SLE_VAR(Town, townnameparts, SLE_UINT32), SLE_CONDSTR(Town, name, SLE_STR | SLF_ALLOW_CONTROL, 0, 84, SL_MAX_VERSION), SLE_VAR(Town, flags, SLE_UINT8), SLE_CONDVAR(Town, statues, SLE_FILE_U8 | SLE_VAR_U16, 0, 103), SLE_CONDVAR(Town, statues, SLE_UINT16, 104, SL_MAX_VERSION), SLE_CONDNULL(1, 0, 1), ///< sort_index, no longer in use SLE_CONDVAR(Town, have_ratings, SLE_FILE_U8 | SLE_VAR_U16, 0, 103), SLE_CONDVAR(Town, have_ratings, SLE_UINT16, 104, SL_MAX_VERSION), SLE_CONDARR(Town, ratings, SLE_INT16, 8, 0, 103), SLE_CONDARR(Town, ratings, SLE_INT16, MAX_COMPANIES, 104, SL_MAX_VERSION), SLE_CONDNULL_X(MAX_COMPANIES, 0, SL_MAX_VERSION, SlXvFeatureTest(XSLFTO_AND, XSLFI_SPRINGPP)), /* failed bribe attempts are stored since savegame format 4 */ SLE_CONDARR(Town, unwanted, SLE_INT8, 8, 4, 103), SLE_CONDARR(Town, unwanted, SLE_INT8, MAX_COMPANIES, 104, SL_MAX_VERSION), SLE_CONDVAR(Town, supplied[CT_PASSENGERS].old_max, SLE_FILE_U16 | SLE_VAR_U32, 0, 8), SLE_CONDVAR(Town, supplied[CT_MAIL].old_max, SLE_FILE_U16 | SLE_VAR_U32, 0, 8), SLE_CONDVAR(Town, supplied[CT_PASSENGERS].new_max, SLE_FILE_U16 | SLE_VAR_U32, 0, 8), SLE_CONDVAR(Town, supplied[CT_MAIL].new_max, SLE_FILE_U16 | SLE_VAR_U32, 0, 8), SLE_CONDVAR(Town, supplied[CT_PASSENGERS].old_act, SLE_FILE_U16 | SLE_VAR_U32, 0, 8), SLE_CONDVAR(Town, supplied[CT_MAIL].old_act, SLE_FILE_U16 | SLE_VAR_U32, 0, 8), SLE_CONDVAR(Town, supplied[CT_PASSENGERS].new_act, SLE_FILE_U16 | SLE_VAR_U32, 0, 8), SLE_CONDVAR(Town, supplied[CT_MAIL].new_act, SLE_FILE_U16 | SLE_VAR_U32, 0, 8), SLE_CONDVAR(Town, supplied[CT_PASSENGERS].old_max, SLE_UINT32, 9, 164), SLE_CONDVAR(Town, supplied[CT_MAIL].old_max, SLE_UINT32, 9, 164), SLE_CONDVAR(Town, supplied[CT_PASSENGERS].new_max, SLE_UINT32, 9, 164), SLE_CONDVAR(Town, supplied[CT_MAIL].new_max, SLE_UINT32, 9, 164), SLE_CONDVAR(Town, supplied[CT_PASSENGERS].old_act, SLE_UINT32, 9, 164), SLE_CONDVAR(Town, supplied[CT_MAIL].old_act, SLE_UINT32, 9, 164), SLE_CONDVAR(Town, supplied[CT_PASSENGERS].new_act, SLE_UINT32, 9, 164), SLE_CONDVAR(Town, supplied[CT_MAIL].new_act, SLE_UINT32, 9, 164), SLE_CONDNULL(2, 0, 163), ///< pct_pass_transported / pct_mail_transported, now computed on the fly SLE_CONDVAR(Town, received[TE_FOOD].old_act, SLE_UINT16, 0, 164), SLE_CONDVAR(Town, received[TE_WATER].old_act, SLE_UINT16, 0, 164), SLE_CONDVAR(Town, received[TE_FOOD].new_act, SLE_UINT16, 0, 164), SLE_CONDVAR(Town, received[TE_WATER].new_act, SLE_UINT16, 0, 164), SLE_CONDARR(Town, goal, SLE_UINT32, NUM_TE, 165, SL_MAX_VERSION), SLE_CONDSTR(Town, text, SLE_STR | SLF_ALLOW_CONTROL, 0, 168, SL_MAX_VERSION), SLE_CONDVAR(Town, time_until_rebuild, SLE_FILE_U8 | SLE_VAR_U16, 0, 53), SLE_CONDVAR(Town, grow_counter, SLE_FILE_U8 | SLE_VAR_U16, 0, 53), SLE_CONDVAR(Town, growth_rate, SLE_FILE_U8 | SLE_VAR_I16, 0, 53), SLE_CONDVAR(Town, time_until_rebuild, SLE_UINT16, 54, SL_MAX_VERSION), SLE_CONDVAR(Town, grow_counter, SLE_UINT16, 54, SL_MAX_VERSION), SLE_CONDVAR(Town, growth_rate, SLE_FILE_I16 | SLE_VAR_U16, 54, 164), SLE_CONDVAR(Town, growth_rate, SLE_UINT16, 165, SL_MAX_VERSION), SLE_VAR(Town, fund_buildings_months, SLE_UINT8), SLE_VAR(Town, road_build_months, SLE_UINT8), SLE_CONDVAR(Town, exclusivity, SLE_UINT8, 2, SL_MAX_VERSION), SLE_CONDVAR(Town, exclusive_counter, SLE_UINT8, 2, SL_MAX_VERSION), SLE_CONDVAR(Town, larger_town, SLE_BOOL, 56, SL_MAX_VERSION), SLE_CONDVAR(Town, layout, SLE_UINT8, 113, SL_MAX_VERSION), SLE_CONDLST(Town, psa_list, REF_STORAGE, 161, SL_MAX_VERSION), SLE_CONDVAR(Town, cargo_produced, SLE_UINT32, 166, SL_MAX_VERSION), /* reserve extra space in savegame here. (currently 30 bytes) */ SLE_CONDNULL(30, 2, SL_MAX_VERSION), SLE_END() }; static const SaveLoad _town_supplied_desc[] = { SLE_CONDVAR(TransportedCargoStat<uint32>, old_max, SLE_UINT32, 165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat<uint32>, new_max, SLE_UINT32, 165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat<uint32>, old_act, SLE_UINT32, 165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat<uint32>, new_act, SLE_UINT32, 165, SL_MAX_VERSION), SLE_END() }; static const SaveLoad _town_received_desc[] = { SLE_CONDVAR(TransportedCargoStat<uint16>, old_max, SLE_UINT16, 165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat<uint16>, new_max, SLE_UINT16, 165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat<uint16>, old_act, SLE_UINT16, 165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat<uint16>, new_act, SLE_UINT16, 165, SL_MAX_VERSION), SLE_END() }; static const SaveLoad _town_received_desc_spp[] = { SLE_CONDVAR(TransportedCargoStat<uint16>, old_max, SLE_FILE_U32 | SLE_VAR_U16, 165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat<uint16>, new_max, SLE_FILE_U32 | SLE_VAR_U16, 165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat<uint16>, old_act, SLE_FILE_U32 | SLE_VAR_U16, 165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat<uint16>, new_act, SLE_FILE_U32 | SLE_VAR_U16, 165, SL_MAX_VERSION), SLE_END() }; static void Save_HIDS() { Save_NewGRFMapping(_house_mngr); } static void Load_HIDS() { Load_NewGRFMapping(_house_mngr); } const SaveLoad *GetTileMatrixDesc() { /* Here due to private member vars. */ static const SaveLoad _tilematrix_desc[] = { SLE_VAR(AcceptanceMatrix, area.tile, SLE_UINT32), SLE_VAR(AcceptanceMatrix, area.w, SLE_UINT16), SLE_VAR(AcceptanceMatrix, area.h, SLE_UINT16), SLE_END() }; return _tilematrix_desc; } static void RealSave_Town(Town *t) { SlObject(t, _town_desc); for (CargoID i = 0; i < NUM_CARGO; i++) { SlObject(&t->supplied[i], _town_supplied_desc); } if (SlXvIsFeaturePresent(XSLFI_SPRINGPP)) { for (int i = TE_BEGIN; i < NUM_TE; i++) { SlObject(&t->received[i], _town_received_desc_spp); } } else { for (int i = TE_BEGIN; i < NUM_TE; i++) { SlObject(&t->received[i], _town_received_desc); } } if (IsSavegameVersionBefore(166)) return; SlObject(&t->cargo_accepted, GetTileMatrixDesc()); if (t->cargo_accepted.area.w != 0) { uint arr_len = t->cargo_accepted.area.w / AcceptanceMatrix::GRID * t->cargo_accepted.area.h / AcceptanceMatrix::GRID; SlArray(t->cargo_accepted.data, arr_len, SLE_UINT32); } } static void Save_TOWN() { Town *t; FOR_ALL_TOWNS(t) { SlSetArrayIndex(t->index); SlAutolength((AutolengthProc*)RealSave_Town, t); } } static void Load_TOWN() { int index; while ((index = SlIterateArray()) != -1) { Town *t = new (index) Town(); SlObject(t, _town_desc); for (CargoID i = 0; i < NUM_CARGO; i++) { SlObject(&t->supplied[i], _town_supplied_desc); } if (SlXvIsFeaturePresent(XSLFI_SPRINGPP)) { for (int i = TE_BEGIN; i < NUM_TE; i++) { SlObject(&t->received[i], _town_received_desc_spp); } } else { for (int i = TE_BEGIN; i < NUM_TE; i++) { SlObject(&t->received[i], _town_received_desc); } } if (t->townnamegrfid == 0 && !IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1) && GB(t->townnametype, 11, 5) != 15) { SlErrorCorrupt("Invalid town name generator"); } if (IsSavegameVersionBefore(166)) continue; SlObject(&t->cargo_accepted, GetTileMatrixDesc()); if (t->cargo_accepted.area.w != 0) { uint arr_len = t->cargo_accepted.area.w / AcceptanceMatrix::GRID * t->cargo_accepted.area.h / AcceptanceMatrix::GRID; t->cargo_accepted.data = MallocT<uint32>(arr_len); SlArray(t->cargo_accepted.data, arr_len, SLE_UINT32); /* Rebuild total cargo acceptance. */ UpdateTownCargoTotal(t); } } } /** Fix pointers when loading town data. */ static void Ptrs_TOWN() { /* Don't run when savegame version lower than 161. */ if (IsSavegameVersionBefore(161)) return; Town *t; FOR_ALL_TOWNS(t) { SlObject(t, _town_desc); } } /** Chunk handler for towns. */ extern const ChunkHandler _town_chunk_handlers[] = { { 'HIDS', Save_HIDS, Load_HIDS, NULL, NULL, CH_ARRAY }, { 'CITY', Save_TOWN, Load_TOWN, Ptrs_TOWN, NULL, CH_ARRAY | CH_LAST}, };
gpl-2.0
ataxel/tp
ezpublish/cache/dev/twig/45/d4/2a3ec75db3a6e920adf61db104530c6dc3b5b5b0f58d55d47b13b2d57a17.php
4613
<?php /* WebProfilerBundle:Profiler:base_js.html.twig */ class __TwigTemplate_45d42a3ec75db3a6e920adf61db104530c6dc3b5b5b0f58d55d47b13b2d57a17 extends eZ\Bundle\EzPublishDebugBundle\Twig\DebugTemplate { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<script>/*<![CDATA[*/ Sfjs = (function() { \"use strict\"; var noop = function() {}, profilerStorageKey = 'sf2/profiler/', request = function(url, onSuccess, onError, payload, options) { var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); options = options || {}; options.maxTries = options.maxTries || 0; xhr.open(options.method || 'GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onreadystatechange = function(state) { if (4 !== xhr.readyState) { return null; } if (xhr.status == 404 && options.maxTries > 1) { setTimeout(function(){ options.maxTries--; request(url, onSuccess, onError, payload, options); }, 500); return null; } if (200 === xhr.status) { (onSuccess || noop)(xhr); } else { (onError || noop)(xhr); } }; xhr.send(payload || ''); }, hasClass = function(el, klass) { return el.className && el.className.match(new RegExp('\\\\b' + klass + '\\\\b')); }, removeClass = function(el, klass) { if (el.className) { el.className = el.className.replace(new RegExp('\\\\b' + klass + '\\\\b'), ' '); } }, addClass = function(el, klass) { if (!hasClass(el, klass)) { el.className += \" \" + klass; } }, getPreference = function(name) { if (!window.localStorage) { return null; } return localStorage.getItem(profilerStorageKey + name); }, setPreference = function(name, value) { if (!window.localStorage) { return null; } localStorage.setItem(profilerStorageKey + name, value); }; return { hasClass: hasClass, removeClass: removeClass, addClass: addClass, getPreference: getPreference, setPreference: setPreference, request: request, load: function(selector, url, onSuccess, onError, options) { var el = document.getElementById(selector); if (el && el.getAttribute('data-sfurl') !== url) { request( url, function(xhr) { el.innerHTML = xhr.responseText; el.setAttribute('data-sfurl', url); removeClass(el, 'loading'); (onSuccess || noop)(xhr, el); }, function(xhr) { (onError || noop)(xhr, el); }, '', options ); } return this; }, toggle: function(selector, elOn, elOff) { var i, style, tmp = elOn.style.display, el = document.getElementById(selector); elOn.style.display = elOff.style.display; elOff.style.display = tmp; if (el) { el.style.display = 'none' === tmp ? 'none' : 'block'; } return this; } } })(); /*]]>*/</script> "; } public function getTemplateName() { return "WebProfilerBundle:Profiler:base_js.html.twig"; } public function getDebugInfo() { return array ( 19 => 1,); } }
gpl-2.0
ojdkbuild/lookaside_java-1.8.0-openjdk
hotspot/test/gc/shenandoah/compiler/C1VectorizedMismatch.java
2108
/* * Copyright (c) 2016 Red Hat, Inc. and/or its affiliates. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ /* @test * @summary test C1 vectorized mismatch intrinsic * @run main/othervm -XX:TieredStopAtLevel=1 -XX:+UseShenandoahGC -XX:+UnlockDiagnosticVMOptions -XX:ShenandoahGCHeuristics=aggressive C1VectorizedMismatch */ import java.util.Arrays; public class C1VectorizedMismatch { private static final int NUM_RUNS = 10000; private static final int ARRAY_SIZE=10000; private static int[] a; private static int[] b; public static void main(String[] args) { a = new int[ARRAY_SIZE]; b = new int[ARRAY_SIZE]; for (int i = 0; i < NUM_RUNS; i++) { test(); } } private static void test() { int[] a1 = new int[ARRAY_SIZE]; int[] b1 = new int[ARRAY_SIZE]; fillArray(a); System.arraycopy(a, 0, b, 0, ARRAY_SIZE); if (! Arrays.equals(a, b)) { throw new RuntimeException("arrays not equal"); } } private static void fillArray(int[] array) { for (int i = 0; i < ARRAY_SIZE; i++) { int val = (int) (Math.random() * Integer.MAX_VALUE); array[i] = val; } } }
gpl-2.0
liumingkong/androidUI
app/src/main/java/org/android/black/viewpager/TestFragment.java
1766
package org.android.black.viewpager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; public final class TestFragment extends Fragment { private static final String KEY_CONTENT = "TestFragment:Content"; public static TestFragment newInstance(String content) { TestFragment fragment = new TestFragment(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 30; i++) { builder.append(content).append(" "); } builder.deleteCharAt(builder.length() - 1); fragment.mContent = builder.toString(); return fragment; } private String mContent = "???"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) { mContent = savedInstanceState.getString(KEY_CONTENT); } TextView text = new TextView(getActivity()); text.setText(mContent); text.setTextSize(20 * getResources().getDisplayMetrics().density); text.setPadding(20, 20, 20, 20); text.setGravity(Gravity.CENTER); LinearLayout layout = new LinearLayout(getActivity()); layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); layout.setGravity(Gravity.CENTER); layout.addView(text); return layout; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_CONTENT, mContent); } }
gpl-2.0
nedy13/AgilityContest
agility/console/frm_estadisticas.php
1228
<h1>Lorem Ipsum dolor sit amet</h1> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum. </p>
gpl-2.0
Esyst/PHP-Soap
src/Esyst/Soap/SoapException.php
71
<?php namespace Esyst\Soap; class SoapException extends \Exception{};
gpl-2.0
camptocamp/cartoweb3
scripts/stats/src/test/java/org/cartoweb/stats/report/DbTestCase.java
6092
/* * 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. * * @copyright 2008 Camptocamp SA */ package org.cartoweb.stats.report; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cartoweb.stats.BaseTestCase; import org.cartoweb.stats.Utils; import org.cartoweb.stats.imports.Import; import org.cartoweb.stats.imports.StatsRecord; import org.pvalsecc.jdbc.JdbcUtilities; import org.pvalsecc.opts.GetOptions; import org.pvalsecc.opts.Option; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public abstract class DbTestCase extends BaseTestCase { public static final Log LOGGER = LogFactory.getLog(DbTestCase.class); public static final String TABLE_NAME = "test"; public static final String RESULT_TABLE = TABLE_NAME + "_report"; protected static final int NB_X = 10; protected static final int NB_Y = 10; public static final TimeScaleDefinition[] TIME_SCALES = { new TimeScaleDefinition(TimeScaleDefinition.PeriodUnit.DAY, 1, 7, "daily"), new TimeScaleDefinition(TimeScaleDefinition.PeriodUnit.WEEK, 1, 10, "weekly"), new TimeScaleDefinition(TimeScaleDefinition.PeriodUnit.MONTH, 1, 12, "monthly"), new TimeScaleDefinition(TimeScaleDefinition.PeriodUnit.YEAR, 1, 5, "yearly"), }; /** * Taken from the environment variable "DB". */ @Option(desc = "A database connection string like \"jdbc:postgresql://localhost/db_stats?user=pvalsecc&password=c2c\"", environment = "STATS_DB") protected String db = "jdbc:postgresql://localhost/db_stats?user=pvalsecc&password=c2c"; protected Connection con; protected Import imports; public DbTestCase(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); try { GetOptions.parse(null, this); con = getConnection(); Utils.dropAllReportTables(con, TABLE_NAME); cleanDB(); String[] args = { "--db=" + db, "--tableName=" + TABLE_NAME, "--logDir=whatever", "--verbose=2", "--format=CartoWeb", }; imports = new Import(args); imports.dropStructure(con); imports.createStructure(con); Reports.checkDB(con, TABLE_NAME); } catch (Exception ex) { LOGGER.error(ex); throw ex; } } private void cleanDB() throws SQLException { Utils.dropTable(con, TABLE_NAME + "_reports", true); Utils.dropTable(con, TABLE_NAME + "_dimensions", true); } private Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("org.postgresql.Driver"); final Connection con = DriverManager.getConnection(db); con.setAutoCommit(false); //for using cursors in the select return con; } protected void tearDown() throws Exception { super.tearDown(); Report report = createReport(); report.dropStructure(con, TABLE_NAME); imports.dropStructure(con); cleanDB(); con.commit(); con.close(); con = null; } protected void addRecord(StatsRecord record) throws SQLException { final String query = "INSERT INTO " + TABLE_NAME + " (" + Import.MAPPER.getFieldNames() + ") VALUES (" + Import.MAPPER.getInsertPlaceHolders() + ")"; PreparedStatement stmt = con.prepareStatement(query); Import.MAPPER.saveToDb(stmt, record, 1); stmt.addBatch(); stmt.executeBatch(); stmt.close(); con.commit(); } protected void checkValue(final long expected, String where, String valueName) throws SQLException { for (int i = 0; i < TIME_SCALES.length; ++i) { TimeScaleDefinition timeScale = TIME_SCALES[i]; JdbcUtilities.runSelectQuery("checking report", "SELECT " + valueName + " FROM " + timeScale.getTableName(RESULT_TABLE) + " " + where, con, new JdbcUtilities.SelectTask() { public void setupStatement(PreparedStatement stmt) throws SQLException { } public void run(ResultSet rs) throws SQLException { if (!rs.next()) { fail("no record found"); } long val = rs.getLong(1); if (rs.wasNull()) { fail("null value"); } if (rs.next()) { fail("more than one record found"); } assertEquals(expected, val); } }); } } protected void checkGridValue(long expected, int x, int y, String fieldName) throws SQLException { checkValue(expected, "", fieldName + "[" + (x + y * NB_X + 1) + "]"); } protected void computeReport(boolean purgeOnConfigurationChange) throws SQLException, ClassNotFoundException { Report report = createReport(); report.init(con, TABLE_NAME, purgeOnConfigurationChange); report.compute(con, TABLE_NAME); } protected abstract Report createReport(); }
gpl-2.0
biblelamp/JavaExercises
JavaRushTasks/2.JavaCore/src/com/javarush/task/task17/task1711/Person.java
967
package com.javarush.task.task17.task1711; import java.util.Date; public class Person { private String name; private Sex sex; private Date birthDay; private Person(String name, Sex sex, Date birthDay) { this.name = name; this.sex = sex; this.birthDay = birthDay; } public static Person createMale(String name, Date birthDay) { return new Person(name, Sex.MALE, birthDay); } public static Person createFemale(String name, Date birthDay) { return new Person(name, Sex.FEMALE, birthDay); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } }
gpl-2.0
DavidRawling/ProtocolHelper
ProtocolHandler/DefinedProtocols.cs
1064
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace ProtocolHandler { public partial class DefinedProtocols : Form { BindingList<Handler> Handlers; public DefinedProtocols() { InitializeComponent(); } private void DefinedProtocols_Shown(object sender, EventArgs e) { HandlerSet HC = Configurator.GetAllHandlers(); Handlers = new BindingList<Handler>(); foreach (Handler H in HC) Handlers.Add(H); ProtocolDGV.DataSource = Handlers; for (int i = 3; i < ProtocolDGV.Columns.Count; i++) ProtocolDGV.Columns[i].Visible = false; } private void CloseButton_Click(object sender, EventArgs e) { Configurator.SetAllHandlers(Handlers); } } }
gpl-2.0
cuongnd/etravelservice
administrator/components/com_tsmart/helpers/tsmhoteladdon.php
18230
<?php /** * Class for getting with language keys translated text. The original code was written by joomla Platform 11.1 * * @package tsmart * @subpackage Helpers * @author Max Milbers * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @copyright Copyright (c) 2014 tsmart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * tsmart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See /administrator/components/com_tsmart/COPYRIGHT.php for copyright notices and details. * * http://tsmart.net */ /** * Text handling class. * * @package Joomla.Platform * @subpackage Language * @since 11.1 */ class tsmHotelAddon { /** * javascript strings * * @var array * @since 11.1 */ protected static $strings = array(); public static function get_list_tour_id_by_hotel_addon_id($tsmart_hotel_addon_id=0) { $db=JFactory::getDbo(); $query=$db->getQuery(true); $query->select('tsmart_product_id') ->from('#__tsmart_tour_id_hotel_addon_id') ->where('tsmart_hotel_addon_id='.(int)$tsmart_hotel_addon_id) ; return $db->setQuery($query)->loadColumn(); } public static function get_extra_night_addon($tsmart_product_id=0, $booking_date, $extra_night_type='pre_transfer') { $booking_date=JFactory::getDate($booking_date); $db=JFactory::getDbo(); $query=$db->getQuery(true); $query->select('*') ->from('#__tsmart_hotel_addon AS hotel_addon') ->leftJoin('#__tsmart_tour_id_hotel_addon_id AS tour_id_hotel_addon_id ON tour_id_hotel_addon_id.tsmart_hotel_addon_id=hotel_addon.tsmart_hotel_addon_id') ->where('hotel_addon.hotel_addon_type='.$query->q($extra_night_type)) ->where('tour_id_hotel_addon_id.tsmart_product_id='.(int)$tsmart_product_id) ->where('hotel_addon.vail_from<='.$query->q($booking_date->toSql())) ->where('hotel_addon.vail_to >='.$query->q($booking_date->toSql())) ; $hotel_addon=$db->setQuery($query)->loadObject(); $hotel_addon->data_price=base64_decode($hotel_addon->data_price); require_once JPATH_ROOT . '/libraries/upgradephp-19/upgrade.php'; $hotel_addon->data_price = up_json_decode($hotel_addon->data_price, false, 512, JSON_PARSE_JAVASCRIPT); return $hotel_addon; } public static function get_group_min_price($tsmart_product_id=0, $rule_date, $extra_night_type='pre_night') { $rule_date=JFactory::getDate($rule_date); $config=tsmConfig::get_config(); $params=$config->params; if($extra_night_type=='pre_night') { $hotel_night_booking_days_allow=$params->get('hotel_pre_night_booking_days_allow',1); $before_date=clone $rule_date; $before_date->modify("-$hotel_night_booking_days_allow day"); }else{ $hotel_night_booking_days_allow=$params->get('hotel_post_night_booking_days_allow',1); $after_date=clone $rule_date; $after_date->modify("+$hotel_night_booking_days_allow day"); } $db=JFactory::getDbo(); $query=$db->getQuery(true); $query->select('*') ->from('#__tsmart_hotel_addon AS hotel_addon') ->leftJoin('#__tsmart_tour_id_hotel_addon_id AS tour_id_hotel_addon_id ON tour_id_hotel_addon_id.tsmart_hotel_addon_id=hotel_addon.tsmart_hotel_addon_id') ->where('hotel_addon.hotel_addon_type='.$query->q($extra_night_type)) ->where('tour_id_hotel_addon_id.tsmart_product_id='.(int)$tsmart_product_id); if($extra_night_type=='pre_night'){ $query ->where($query->q($rule_date->toSql()).'<=hotel_addon.vail_to') //->where('hotel_addon.vail_from >='.$query->q($before_date->toSql())) ; }else{ $query ->where($query->q($rule_date->toSql()).'<=hotel_addon.vail_to') //->where('hotel_addon.vail_to >='.$query->q($after_date->toSql())) ; } ; require_once JPATH_ROOT . '/libraries/upgradephp-19/upgrade.php'; $list_hotel_addon=$db->setQuery($query)->loadObjectList(); if(count($list_hotel_addon)==0){ return null; } foreach($list_hotel_addon as &$hotel_addon){ $hotel_addon->data_price=base64_decode($hotel_addon->data_price); $hotel_addon->data_price = up_json_decode($hotel_addon->data_price, false, 512, JSON_PARSE_JAVASCRIPT); } $single_min_price=9999; $dbl_twin_min_price=9999; $tpl_min_price=9999; for($i=0;$i<count($list_hotel_addon);$i++) { $price_night_hotel = $list_hotel_addon[$i]; $data_price = $price_night_hotel->data_price; if ($data_price != null) { $item_mark_up_type =$data_price->item_mark_up_type; $items =$data_price->items; $double_twin_room =$items->double_twin_room; $single_room =$items->single_room; $triple_room =$items->triple_room; $double_twin_room_mark_up_amount =(float)$double_twin_room->mark_up_amount; $double_twin_room_mark_up_percent =(float)$double_twin_room->mark_up_percent; $double_twin_room_net_price =(float)$double_twin_room->net_price; $double_twin_room_tax =(float)$double_twin_room->tax; $single_room_mark_up_amount =(float)$single_room->mark_up_amount; $single_room_mark_up_percent =(float)$single_room->mark_up_percent; $single_room_net_price =(float)$single_room->net_price; $single_room_tax =(float)$single_room->tax; $triple_room_mark_up_amount =(float)$triple_room->mark_up_amount; $triple_room_mark_up_percent =(float)$triple_room->mark_up_percent; $triple_room_net_price =(float)$triple_room->net_price; $triple_room_tax =(float)$triple_room->tax; if ($item_mark_up_type =='percent') { $current_double_twin_room_sale_price =$double_twin_room_net_price + ($double_twin_room_net_price * $double_twin_room_mark_up_percent) / 100; $current_double_twin_room_sale_price =$current_double_twin_room_sale_price + ($current_double_twin_room_sale_price * $double_twin_room_tax) / 100; if ($current_double_twin_room_sale_price < $dbl_twin_min_price) { $dbl_twin_min_price =$current_double_twin_room_sale_price; } $single_room_sale_price =$single_room_net_price + ($single_room_net_price * $single_room_mark_up_percent) / 100; $single_room_sale_price =$single_room_sale_price + ($single_room_sale_price * $single_room_tax) / 100; if ($single_room_sale_price < $single_min_price) { $single_min_price =$single_room_sale_price; } $current_triple_room_sale_price =$triple_room_net_price + ($triple_room_net_price * $triple_room_mark_up_percent) / 100; $current_triple_room_sale_price =$current_triple_room_sale_price + ($current_triple_room_sale_price * $triple_room_tax) / 100; if ($current_triple_room_sale_price < $tpl_min_price) { $tpl_min_price =$current_triple_room_sale_price; } } else { $current_double_twin_room_sale_price =$double_twin_room_net_price + $double_twin_room_mark_up_amount; $current_double_twin_room_sale_price =$current_double_twin_room_sale_price + ($current_double_twin_room_sale_price * $double_twin_room_tax) / 100; if ($current_double_twin_room_sale_price < $dbl_twin_min_price) { $dbl_twin_min_price =$current_double_twin_room_sale_price; } $single_room_sale_price =$single_room_net_price + $single_room_mark_up_amount; $single_room_sale_price =$single_room_sale_price + ($single_room_sale_price * $single_room_tax) / 100; if ($single_room_sale_price < $single_min_price) { $single_min_price =$single_room_sale_price; } $current_triple_room_sale_price =$triple_room_net_price + $triple_room_mark_up_amount; $current_triple_room_sale_price =$current_triple_room_sale_price + ($current_triple_room_sale_price * $triple_room_tax) / 100; if ($current_triple_room_sale_price < $tpl_min_price) { $tpl_min_price =$current_triple_room_sale_price; } } } } $min_price=new stdClass(); $min_price->single_min_price=$single_min_price; $min_price->dbl_twin_min_price=$dbl_twin_min_price; $min_price->tpl_min_price=$tpl_min_price; return $min_price; } public static function get_data_price_by_hotel_add_on_id($tsmart_hotel_addon_id) { $db=JFactory::getDbo(); $query=$db->getQuery(true); $query->select('*') ->from('#__tsmart_hotel_addon AS hotel_addon') ->where('hotel_addon.tsmart_hotel_addon_id='.(int)$tsmart_hotel_addon_id); ; require_once JPATH_ROOT . '/libraries/upgradephp-19/upgrade.php'; $hotel_addon=$db->setQuery($query)->loadObject(); $hotel_addon->data_price=base64_decode($hotel_addon->data_price); $data_price = up_json_decode($hotel_addon->data_price, false, 512, JSON_PARSE_JAVASCRIPT); $data_price_for_room=new stdClass(); if ($data_price != null) { $item_mark_up_type =$data_price->item_mark_up_type; $items =$data_price->items; $double_twin_room =$items->double_twin_room; $single_room =$items->single_room; $triple_room =$items->triple_room; $double_twin_room_mark_up_amount =(float)$double_twin_room->mark_up_amount; $double_twin_room_mark_up_percent =(float)$double_twin_room->mark_up_percent; $double_twin_room_net_price =(float)$double_twin_room->net_price; $double_twin_room_tax =(float)$double_twin_room->tax; $single_room_mark_up_amount =(float)$single_room->mark_up_amount; $single_room_mark_up_percent =(float)$single_room->mark_up_percent; $single_room_net_price =(float)$single_room->net_price; $single_room_tax =(float)$single_room->tax; $triple_room_mark_up_amount =(float)$triple_room->mark_up_amount; $triple_room_mark_up_percent =(float)$triple_room->mark_up_percent; $triple_room_net_price =(float)$triple_room->net_price; $triple_room_tax =(float)$triple_room->tax; if ($item_mark_up_type =='percent') { $current_double_twin_room_sale_price =$double_twin_room_net_price + ($double_twin_room_net_price * $double_twin_room_mark_up_percent) / 100; $current_double_twin_room_sale_price =$current_double_twin_room_sale_price + ($current_double_twin_room_sale_price * $double_twin_room_tax) / 100; $double_twin_room=new stdClass(); $double_twin_room->net_price=$double_twin_room_net_price; $double_twin_room->mark_up_price=($double_twin_room_net_price * $double_twin_room_mark_up_percent) / 100; $double_twin_room->tax=$double_twin_room_tax; $double_twin_room->sale_price=$current_double_twin_room_sale_price; $data_price_for_room->double_twin_room=$double_twin_room; $single_room_sale_price =$single_room_net_price + ($single_room_net_price * $single_room_mark_up_percent) / 100; $single_room_sale_price =$single_room_sale_price + ($single_room_sale_price * $single_room_tax) / 100; $single_room=new stdClass(); $single_room->net_price=$single_room_net_price; $single_room->mark_up_price=($single_room_net_price * $single_room_mark_up_percent) / 100; $single_room->tax=$single_room_tax; $single_room->sale_price=$single_room_sale_price; $data_price_for_room->single_room=$single_room; $current_triple_room_sale_price =$triple_room_net_price + ($triple_room_net_price * $triple_room_mark_up_percent) / 100; $current_triple_room_sale_price =$current_triple_room_sale_price + ($current_triple_room_sale_price * $triple_room_tax) / 100; $triple_room=new stdClass(); $triple_room->net_price=$triple_room_net_price; $triple_room->mark_up_price=($triple_room_net_price * $triple_room_mark_up_percent) / 100; $triple_room->tax=$triple_room_tax; $triple_room->sale_price=$current_triple_room_sale_price; $data_price_for_room->triple_room=$triple_room; } else { $current_double_twin_room_sale_price =$double_twin_room_net_price + $double_twin_room_mark_up_amount; $current_double_twin_room_sale_price =$current_double_twin_room_sale_price + ($current_double_twin_room_sale_price * $double_twin_room_tax) / 100; $double_twin_room=new stdClass(); $double_twin_room->net_price=$double_twin_room_net_price; $double_twin_room->mark_up_price=$double_twin_room_mark_up_amount; $double_twin_room->tax=$double_twin_room_tax; $double_twin_room->sale_price=$current_double_twin_room_sale_price; $data_price_for_room->double_twin_room=$double_twin_room; $single_room_sale_price =$single_room_net_price + $single_room_mark_up_amount; $single_room_sale_price =$single_room_sale_price + ($single_room_sale_price * $single_room_tax) / 100; $single_room=new stdClass(); $single_room->net_price=$single_room_net_price; $single_room->mark_up_price=$single_room_mark_up_amount; $single_room->tax=$single_room_tax; $single_room->sale_price=$single_room_sale_price; $data_price_for_room->single_room=$single_room; $current_triple_room_sale_price =$triple_room_net_price + $triple_room_mark_up_amount; $current_triple_room_sale_price =$current_triple_room_sale_price + ($current_triple_room_sale_price * $triple_room_tax) / 100; $triple_room=new stdClass(); $triple_room->net_price=$triple_room_net_price; $triple_room->mark_up_price=$triple_room_mark_up_amount; $triple_room->tax=$triple_room_tax; $triple_room->sale_price=$current_triple_room_sale_price; $data_price_for_room->triple_room=$triple_room; } } $data_price_for_room->double_twin_room->room_type="double-twin room"; $data_price_for_room->single_room->room_type="Single room"; $data_price_for_room->triple_room->room_type="Triple room"; return $data_price_for_room; } public static function get_detail_hotel_by_hotel_id($vituemart_hotel_id=0){ $db=JFactory::getDbo(); $query=$db->getQuery(true); $query->select('hotel.*,cityarea.city_area_name') ->from('#__tsmart_hotel AS hotel') ->leftJoin('#__tsmart_cityarea AS cityarea USING(tsmart_cityarea_id)') ->where('hotel.tsmart_hotel_id='.(int)$vituemart_hotel_id) ; return $db->setQuery($query)->loadObject(); } public static function get_hoteladdon_by_hotel_addon_id($tsmart_hotel_addon_id=0){ $db=JFactory::getDbo(); $query=$db->getQuery(true); $query->select('hotel_addon.*') ->from('#__tsmart_hotel_addon AS hotel_addon') ->leftJoin('#__tsmart_cityarea AS cityarea USING(tsmart_cityarea_id)') ->where('hotel_addon.tsmart_hotel_addon_id='.(int)$tsmart_hotel_addon_id) ; return $db->setQuery($query)->loadObject(); } public static function get_list_hotel_payment_type() { $list_hotel_payment_type=array( 'instant_payment'=>'Instant payment', 'last_payment'=>'Last transfer' ); $a_list_hotel_payment_type=array(); foreach($list_hotel_payment_type as $key=>$text) { $a_item=new stdClass(); $a_item->value=$key; $a_item->text=$text; $a_list_hotel_payment_type[]=$a_item; } return $a_list_hotel_payment_type; } public static function get_list_hotel_addon_type() { $list_hotel_type=array( 'pre_night'=>'Pre night', 'post_night'=>'Post night' ); $a_list_hotel_type=array(); foreach($list_hotel_type as $key=>$text) { $a_item=new stdClass(); $a_item->value=$key; $a_item->text=$text; $a_list_hotel_type[]=$a_item; } return $a_list_hotel_type; } public static function get_list_hotel_addon_service_class() { $list_hotel_type=array( 'budget'=>'budget', 'standard'=>'standard', 'superior'=>'superior', 'deluxe'=>'deluxe', 'Luxury'=>'Luxury' ); $a_list_hotel_type=array(); foreach($list_hotel_type as $key=>$text) { $a_item=new stdClass(); $a_item->value=$key; $a_item->text=$text; $a_list_hotel_type[]=$a_item; } return $a_list_hotel_type; } }
gpl-2.0
DIPnet/popgenDB
sims_for_structure_paper/2PopDNAnorec_0.5_1000/2PopDNAnorec_1_278.res/2PopDNAnorec_1_278.js
922
USETEXTLINKS = 1 STARTALLOPEN = 0 WRAPTEXT = 1 PRESERVESTATE = 0 HIGHLIGHT = 1 ICONPATH = 'file:////Users/eric/github/popgenDB/sims_for_structure_paper/2PopDNAnorec_0.5_1000/' //change if the gif's folder is a subfolder, for example: 'images/' foldersTree = gFld("<i>ARLEQUIN RESULTS (2PopDNAnorec_1_278.arp)</i>", "") insDoc(foldersTree, gLnk("R", "Arlequin log file", "Arlequin_log.txt")) aux1 = insFld(foldersTree, gFld("Run of 31/07/18 at 17:01:43", "2PopDNAnorec_1_278.xml#31_07_18at17_01_43")) insDoc(aux1, gLnk("R", "Settings", "2PopDNAnorec_1_278.xml#31_07_18at17_01_43_run_information")) aux2 = insFld(aux1, gFld("Genetic structure (samp=pop)", "2PopDNAnorec_1_278.xml#31_07_18at17_01_43_pop_gen_struct")) insDoc(aux2, gLnk("R", "AMOVA", "2PopDNAnorec_1_278.xml#31_07_18at17_01_43_pop_amova")) insDoc(aux2, gLnk("R", "Pairwise distances", "2PopDNAnorec_1_278.xml#31_07_18at17_01_43_pop_pairw_diff"))
gpl-2.0
msimacek/koschei
alembic/versions/75d9e5d27ba5_create_partial_index_ix_builds_.py
471
""" Create partial index ix_builds_unprocessed Create Date: 2017-04-05 11:50:52.185886 """ # revision identifiers, used by Alembic. revision = '75d9e5d27ba5' down_revision = '2cc3e44a68de' from alembic import op def upgrade(): op.execute(""" CREATE INDEX ix_builds_unprocessed ON build (task_id) WHERE deps_resolved IS NULL AND repo_id IS NOT NULL """) def downgrade(): op.execute(""" DROP INDEX ix_builds_unprocessed """)
gpl-2.0
oceanscan/ros-imc-broker
workspace/src/ros_imc_broker/include/IMC/Spec/MagneticField.hpp
4667
//*************************************************************************** // Copyright 2017 OceanScan - Marine Systems & Technology, Lda. * //*************************************************************************** // 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. * //*************************************************************************** // Author: Ricardo Martins * //*************************************************************************** // Automatically generated. * //*************************************************************************** // IMC XML MD5: 74f41081eac3414e0a982ae6a8fe7347 * //*************************************************************************** #ifndef IMC_MAGNETICFIELD_HPP_INCLUDED_ #define IMC_MAGNETICFIELD_HPP_INCLUDED_ // ISO C++ 98 headers. #include <ostream> #include <string> #include <vector> // IMC headers. #include <IMC/Base/Config.hpp> #include <IMC/Base/Message.hpp> #include <IMC/Base/InlineMessage.hpp> #include <IMC/Base/MessageList.hpp> #include <IMC/Base/JSON.hpp> #include <IMC/Base/Serialization.hpp> #include <IMC/Spec/Enumerations.hpp> #include <IMC/Spec/Bitfields.hpp> namespace IMC { //! Magnetic Field. class MagneticField: public Message { public: //! Device Time. double time; //! X. double x; //! Y. double y; //! Z. double z; static uint16_t getIdStatic(void) { return 258; } static MagneticField* cast(Message* msg__) { return (MagneticField*)msg__; } MagneticField(void) { m_header.mgid = MagneticField::getIdStatic(); clear(); } MagneticField* clone(void) const { return new MagneticField(*this); } void clear(void) { time = 0; x = 0; y = 0; z = 0; } bool fieldsEqual(const Message& msg__) const { const IMC::MagneticField& other__ = static_cast<const MagneticField&>(msg__); if (time != other__.time) return false; if (x != other__.x) return false; if (y != other__.y) return false; if (z != other__.z) return false; return true; } uint8_t* serializeFields(uint8_t* bfr__) const { uint8_t* ptr__ = bfr__; ptr__ += IMC::serialize(time, ptr__); ptr__ += IMC::serialize(x, ptr__); ptr__ += IMC::serialize(y, ptr__); ptr__ += IMC::serialize(z, ptr__); return ptr__; } size_t deserializeFields(const uint8_t* bfr__, size_t size__) { const uint8_t* start__ = bfr__; bfr__ += IMC::deserialize(time, bfr__, size__); bfr__ += IMC::deserialize(x, bfr__, size__); bfr__ += IMC::deserialize(y, bfr__, size__); bfr__ += IMC::deserialize(z, bfr__, size__); return bfr__ - start__; } size_t reverseDeserializeFields(const uint8_t* bfr__, size_t size__) { const uint8_t* start__ = bfr__; bfr__ += IMC::reverseDeserialize(time, bfr__, size__); bfr__ += IMC::reverseDeserialize(x, bfr__, size__); bfr__ += IMC::reverseDeserialize(y, bfr__, size__); bfr__ += IMC::reverseDeserialize(z, bfr__, size__); return bfr__ - start__; } uint16_t getId(void) const { return MagneticField::getIdStatic(); } const char* getName(void) const { return "MagneticField"; } size_t getFixedSerializationSize(void) const { return 32; } void fieldsToJSON(std::ostream& os__, unsigned nindent__) const { IMC::toJSON(os__, "time", time, nindent__); IMC::toJSON(os__, "x", x, nindent__); IMC::toJSON(os__, "y", y, nindent__); IMC::toJSON(os__, "z", z, nindent__); } }; } #endif
gpl-2.0
leocockroach/JasperServer5.6
jasperserver-search/src/test/java/com/jaspersoft/jasperserver/search/service/impl/RepositorySearchServiceImplTest.java
14958
/* * Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com. * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program.&nbsp; If not, see <http://www.gnu.org/licenses/>. */ package com.jaspersoft.jasperserver.search.service.impl; import com.jaspersoft.jasperserver.api.common.domain.ExecutionContext; import com.jaspersoft.jasperserver.api.logging.diagnostic.domain.DiagnosticAttribute; import com.jaspersoft.jasperserver.api.logging.diagnostic.domain.DiagnosticAttributeImpl; import com.jaspersoft.jasperserver.api.logging.diagnostic.helper.DiagnosticAttributeBuilder; import com.jaspersoft.jasperserver.api.logging.diagnostic.service.DiagnosticCallback; import com.jaspersoft.jasperserver.api.metadata.common.domain.Folder; import com.jaspersoft.jasperserver.api.metadata.common.domain.Resource; import com.jaspersoft.jasperserver.api.metadata.common.domain.ResourceLookup; import com.jaspersoft.jasperserver.api.metadata.common.service.RepositoryService; import com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl; import com.jaspersoft.jasperserver.api.metadata.jasperreports.domain.ReportUnit; import com.jaspersoft.jasperserver.api.search.SearchCriteriaFactory; import com.jaspersoft.jasperserver.api.search.SearchFilter; import com.jaspersoft.jasperserver.api.search.SearchSorter; import com.jaspersoft.jasperserver.api.search.TransformerFactory; import com.jaspersoft.jasperserver.search.common.RepositorySearchConfiguration; import com.jaspersoft.jasperserver.search.filter.ResourceTypeSearchCriteriaFactory; import com.jaspersoft.jasperserver.search.mode.SearchMode; import com.jaspersoft.jasperserver.search.mode.SearchModeSettings; import com.jaspersoft.jasperserver.search.mode.SearchModeSettingsResolver; import com.jaspersoft.jasperserver.search.service.RepositorySearchCriteria; import org.junit.Test; import org.unitils.UnitilsJUnit4; import org.unitils.inject.annotation.TestedObject; import org.unitils.mock.Mock; import org.unitils.mock.MockUnitils; import org.unitils.mock.PartialMock; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Yaroslav.Kovalchyk * @version $Id: RepositorySearchServiceImplTest.java 47331 2014-07-18 09:13:06Z kklein $ */ public class RepositorySearchServiceImplTest extends UnitilsJUnit4 { @TestedObject private PartialMock<RepositorySearchServiceImpl> repositorySearchService; @Test public void getResultsFromSearchCriteriaWithFolders() { final String resourceTypeToCheck = Folder.class.getName(); RepositorySearchConfiguration configuration = MockUnitils.createMock(RepositorySearchConfiguration.class).getMock(); final Mock<SearchModeSettings> searchModeSettingsMock = MockUnitils.createMock(SearchModeSettings.class); searchModeSettingsMock.returns(configuration).getRepositorySearchConfiguration(); final SearchModeSettings searchModeSettings = searchModeSettingsMock.getMock(); final Mock<SearchModeSettingsResolver> resolverMock = MockUnitils.createMock(SearchModeSettingsResolver.class); resolverMock.returns(searchModeSettings).getSettings(SearchMode.SEARCH); final ResourceTypeSearchCriteriaFactory defaultSearchCriteriaFactory = new ResourceTypeSearchCriteriaFactory(); RepositoryService repositoryService = new HibernateRepositoryServiceImpl(){ @Override public List<ResourceLookup> getResources(ExecutionContext context, SearchCriteriaFactory searchCriteriaFactory, List<SearchFilter> filters, SearchSorter sorter, TransformerFactory transformerFactory, int current, int max) { assertEquals(ResourceLookup.class.getName(), ((ResourceTypeSearchCriteriaFactory)searchCriteriaFactory).getResourceType()); return new ArrayList<ResourceLookup>(); } }; RepositorySearchCriteria searchCritera = new RepositorySearchCriteriaImpl.Builder().setSearchMode(SearchMode.SEARCH).setResourceTypes(resourceTypeToCheck).getCriteria(); RepositorySearchServiceImpl service = new RepositorySearchServiceImpl(); service.setSearchModeSettingsResolver(resolverMock.getMock()); service.setDefaultSearchCriteriaFactory(defaultSearchCriteriaFactory); service.setRepositoryService(repositoryService); service.getResults(null, searchCritera); assertFalse(searchCritera.getResourceTypes() == null || searchCritera.getResourceTypes().isEmpty()); } @Test public void getResultsFromSearchCriteriaWithoutFolders() { final String resourceTypeToCheck = ReportUnit.class.getName(); RepositorySearchConfiguration configuration = MockUnitils.createMock(RepositorySearchConfiguration.class).getMock(); final Mock<SearchModeSettings> searchModeSettingsMock = MockUnitils.createMock(SearchModeSettings.class); searchModeSettingsMock.returns(configuration).getRepositorySearchConfiguration(); final SearchModeSettings searchModeSettings = searchModeSettingsMock.getMock(); final Mock<SearchModeSettingsResolver> resolverMock = MockUnitils.createMock(SearchModeSettingsResolver.class); resolverMock.returns(searchModeSettings).getSettings(SearchMode.SEARCH); final ResourceTypeSearchCriteriaFactory defaultSearchCriteriaFactory = new ResourceTypeSearchCriteriaFactory(); RepositoryService repositoryService = new HibernateRepositoryServiceImpl(){ @Override public List<ResourceLookup> getResources(ExecutionContext context, SearchCriteriaFactory searchCriteriaFactory, List<SearchFilter> filters, SearchSorter sorter, TransformerFactory transformerFactory, int current, int max) { assertEquals(Resource.class.getName(), ((ResourceTypeSearchCriteriaFactory)searchCriteriaFactory).getResourceType()); return new ArrayList<ResourceLookup>(); } }; RepositorySearchCriteria searchCritera = new RepositorySearchCriteriaImpl.Builder().setSearchMode(SearchMode.SEARCH).setResourceTypes(resourceTypeToCheck).setExcludeFolders(true).getCriteria(); RepositorySearchServiceImpl service = new RepositorySearchServiceImpl(); service.setSearchModeSettingsResolver(resolverMock.getMock()); service.setDefaultSearchCriteriaFactory(defaultSearchCriteriaFactory); service.setRepositoryService(repositoryService); service.getResults(null, searchCritera); assertFalse(searchCritera.getResourceTypes() == null || searchCritera.getResourceTypes().isEmpty()); } @Test public void getResultsFromSearchCriteriaWithoutFolders_folder() { final String resourceTypeToCheck = Folder.class.getName(); RepositorySearchConfiguration configuration = MockUnitils.createMock(RepositorySearchConfiguration.class).getMock(); final Mock<SearchModeSettings> searchModeSettingsMock = MockUnitils.createMock(SearchModeSettings.class); searchModeSettingsMock.returns(configuration).getRepositorySearchConfiguration(); final SearchModeSettings searchModeSettings = searchModeSettingsMock.getMock(); final Mock<SearchModeSettingsResolver> resolverMock = MockUnitils.createMock(SearchModeSettingsResolver.class); resolverMock.returns(searchModeSettings).getSettings(SearchMode.SEARCH); final ResourceTypeSearchCriteriaFactory defaultSearchCriteriaFactory = new ResourceTypeSearchCriteriaFactory(); RepositoryService repositoryService = new HibernateRepositoryServiceImpl(){ @Override public List<ResourceLookup> getResources(ExecutionContext context, SearchCriteriaFactory searchCriteriaFactory, List<SearchFilter> filters, SearchSorter sorter, TransformerFactory transformerFactory, int current, int max) { assertEquals(Resource.class.getName(), ((ResourceTypeSearchCriteriaFactory)searchCriteriaFactory).getResourceType()); return new ArrayList<ResourceLookup>(); } }; RepositorySearchCriteria searchCritera = new RepositorySearchCriteriaImpl.Builder().setSearchMode(SearchMode.SEARCH).setResourceTypes(resourceTypeToCheck).setExcludeFolders(true).getCriteria(); RepositorySearchServiceImpl service = new RepositorySearchServiceImpl(); service.setSearchModeSettingsResolver(resolverMock.getMock()); service.setDefaultSearchCriteriaFactory(defaultSearchCriteriaFactory); service.setRepositoryService(repositoryService); service.getResults(null, searchCritera); assertFalse(searchCritera.getResourceTypes() == null || searchCritera.getResourceTypes().isEmpty()); } @Test public void getDiagnosticDataTest() { //Setup mock behavior Mock<RepositoryService> repositoryServiceMock = MockUnitils.createMock(RepositoryService.class); Mock<Map> filterOptionToResourceTypesMock = MockUnitils.createMock(Map.class); Mock<SearchCriteriaFactory> defaultSearchCriteriaFactoryMock = MockUnitils.createMock(SearchCriteriaFactory.class); Mock<TransformerFactory> transformerFactoryMock = MockUnitils.createMock(TransformerFactory.class); repositorySearchService.getMock().setRepositoryService(repositoryServiceMock.getMock()); repositorySearchService.getMock().setFilterOptionToResourceTypes(filterOptionToResourceTypesMock.getMock()); repositorySearchService.getMock().setDefaultSearchCriteriaFactory(defaultSearchCriteriaFactoryMock.getMock()); repositorySearchService.getMock().setTransformerFactory(transformerFactoryMock.getMock()); Mock<RepositorySearchConfiguration> configuration = MockUnitils.createMock(RepositorySearchConfiguration.class); repositorySearchService.returns(configuration).getConfiguration(null); Mock<SearchCriteriaFactory> factory = MockUnitils.createMock(SearchCriteriaFactory.class); defaultSearchCriteriaFactoryMock.returns(factory).newFactory(null); Mock<SearchFilter> searchFilterMock1 = MockUnitils.createMock(SearchFilter.class); Mock<SearchFilter> searchFilterMock2 = MockUnitils.createMock(SearchFilter.class); Mock<SearchFilter> searchFilterMock3 = MockUnitils.createMock(SearchFilter.class); ArrayList<SearchFilter> allFiltersList = new ArrayList<SearchFilter>(); allFiltersList.add(searchFilterMock1.getMock()); allFiltersList.add(searchFilterMock2.getMock()); allFiltersList.add(searchFilterMock3.getMock()); Mock<ExecutionContext> executionContextMock = MockUnitils.createMock(ExecutionContext.class); repositorySearchService.returns(allFiltersList).createAllFiltersList(configuration.getMock(), null); repositorySearchService.returns(executionContextMock).putCriteriaToContext(null, null); Map<DiagnosticAttribute, DiagnosticCallback> resultDiagnosticData = repositorySearchService.getMock().getDiagnosticData(); //Testing total size of diagnostic attributes collected from SessionRegistryDiagnosticService assertEquals(5, resultDiagnosticData.size()); repositoryServiceMock.returns(30).getResourcesCount(executionContextMock.getMock(), factory.getMock(), allFiltersList, null, transformerFactoryMock.getMock()); //Test getting total report count int totalReportCount = (Integer)resultDiagnosticData. get(new DiagnosticAttributeImpl(DiagnosticAttributeBuilder.TOTAL_REPORTS_COUNT, null, null)).getDiagnosticAttributeValue(); filterOptionToResourceTypesMock.assertInvoked().get("resourceTypeFilter-reports"); assertEquals(30, totalReportCount); //Refresh getResourceCount for repository service mock repositoryServiceMock.resetBehavior(); repositoryServiceMock.returns(40).getResourcesCount(executionContextMock.getMock(), factory.getMock(), allFiltersList, null, transformerFactoryMock.getMock()); //Test getting total reports output count int totalReportsOutputCount = (Integer)resultDiagnosticData. get(new DiagnosticAttributeImpl(DiagnosticAttributeBuilder.TOTAL_REPORT_OUTPUTS_COUNT, null, null)).getDiagnosticAttributeValue(); filterOptionToResourceTypesMock.assertInvoked().get("resourceTypeFilter-reportOutput"); assertEquals(40, totalReportsOutputCount); //Refresh getResourceCount for repository service mock repositoryServiceMock.resetBehavior(); repositoryServiceMock.returns(50).getResourcesCount(executionContextMock.getMock(), factory.getMock(), allFiltersList, null, transformerFactoryMock.getMock()); //Test getting total olap views count int totalOlapViewCount = (Integer)resultDiagnosticData. get(new DiagnosticAttributeImpl(DiagnosticAttributeBuilder.TOTAL_OLAP_VIEWS_COUNT, null, null)).getDiagnosticAttributeValue(); filterOptionToResourceTypesMock.assertInvoked().get("resourceTypeFilter-view"); assertEquals(50, totalOlapViewCount); //Refresh getResourceCount for repository service mock repositoryServiceMock.resetBehavior(); repositoryServiceMock.returns(60).getResourcesCount(executionContextMock.getMock(), factory.getMock(), allFiltersList, null, transformerFactoryMock.getMock()); //Test getting total data sources count int totalDataSourcesCount = (Integer)resultDiagnosticData. get(new DiagnosticAttributeImpl(DiagnosticAttributeBuilder.TOTAL_DATA_SOURCES_COUNT, null, null)).getDiagnosticAttributeValue(); filterOptionToResourceTypesMock.assertInvoked().get("resourceTypeFilter-dataSources"); assertEquals(60, totalDataSourcesCount); repositoryServiceMock.returns(2).getFoldersCount(null); //Test getting total data sources count int totalFoldersCount = (Integer)resultDiagnosticData. get(new DiagnosticAttributeImpl(DiagnosticAttributeBuilder.TOTAL_FOLDERS_COUNT, null, null)).getDiagnosticAttributeValue(); assertEquals(2, totalFoldersCount); } }
gpl-2.0
GigaOM/go-code-scanner
components/external/CodeSniffer/Reports/Emacs.php
2323
<?php /** * Emacs report for PHP_CodeSniffer. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Gabriele Santini <[email protected]> * @author Greg Sherwood <[email protected]> * @copyright 2009 SQLI <www.sqli.com> * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * Emacs report for PHP_CodeSniffer. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Gabriele Santini <[email protected]> * @author Greg Sherwood <[email protected]> * @copyright 2009 SQLI <www.sqli.com> * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @version Release: 1.4.0 * @link http://pear.php.net/package/PHP_CodeSniffer */ class PHP_CodeSniffer_Reports_Emacs implements PHP_CodeSniffer_Report { /** * Generates an emacs report. * * @param array $report Prepared report. * @param boolean $showSources Show sources? * @param int $width Maximum allowed lne width. * @param boolean $toScreen Is the report being printed to screen? * * @return string */ public function generate( $report, $showSources=false, $width=80, $toScreen=true ) { $errorsShown = 0; foreach ($report['files'] as $filename => $file) { foreach ($file['messages'] as $line => $lineErrors) { foreach ($lineErrors as $column => $colErrors) { foreach ($colErrors as $error) { $message = $error['message']; if ($showSources === true) { $message .= ' ('.$error['source'].')'; } $type = strtolower($error['type']); echo $filename.':'.$line.':'.$column.': '.$type.' - '.$message.PHP_EOL; $errorsShown++; } } }//end foreach }//end foreach return $errorsShown; }//end generate() }//end class ?>
gpl-2.0
piaolinzhi/fight
dubbo/pay/pay-common-web/src/main/java/wusc/edu/pay/common/web/constant/PermissionConstant.java
2504
package wusc.edu.pay.common.web.constant; import java.io.InputStream; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @描述: 会话键常量类. * @作者: WuShuicheng. * @创建: 2014-8-19,上午9:26:46 * @版本: V1.0 * */ public class PermissionConstant { /** * logger. */ private static final Log LOG = LogFactory.getLog(PermissionConstant.class); /** * 登录操作员的session键名. */ public static final String OPERATOR_SESSION_KEY = "pmsOperator"; /** * 登录操作员拥有的权限集合的session键名. */ public static final String ACTIONS_SESSION_KEY = "actions"; // // /** // * 运营操作员会话键 // */ // public static String WEB_OPERATOR_KEY = "WebOperators"; /** * 操作员在线用户数限制(默认100). */ public static int WEB_ONLINE_LIMIT = 100; /** * 操作员密码连续输错次数限制(默认5). */ public static int WEB_PWD_INPUT_ERROR_LIMIT = 5; /** * 只加载一次. */ static { try { LOG.info("=== load session.properties and init"); InputStream proFile = Thread.currentThread().getContextClassLoader().getResourceAsStream("permission.properties"); Properties props = new Properties(); props.load(proFile); init(props); } catch (Exception e) { LOG.error("=== load and init session.properties exception:" + e); } } /** * 根据配置文件初始化静态变量值. * * @param props */ private static void init(Properties props) { // String web_operator_key_prefix = props.getProperty("web.operator.key.prefix"); // if (StringUtils.isNotBlank(web_operator_key_prefix)) { // WEB_OPERATOR_KEY = web_operator_key_prefix + WEB_OPERATOR_KEY; // LOG.info("===>WEB_OPERATOR_KEY:" + WEB_OPERATOR_KEY); // } String web_online_limit = props.getProperty("web.online.limit"); if (StringUtils.isNotBlank(web_online_limit)) { WEB_ONLINE_LIMIT = Integer.valueOf(web_online_limit); LOG.info("===>WEB_ONLINE_LIMIT:" + WEB_ONLINE_LIMIT); } String web_pwd_input_error_limit = props.getProperty("web.pwd.input.error.limit"); if (StringUtils.isNotBlank(web_pwd_input_error_limit)) { WEB_PWD_INPUT_ERROR_LIMIT = Integer.valueOf(web_pwd_input_error_limit); LOG.info("===>WEB_PWD_INPUT_ERROR_LIMIT:" + WEB_PWD_INPUT_ERROR_LIMIT); } } }
gpl-2.0
austinglaser/timeline
src/HelloWorld.java
259
/* * HelloWorld.java * Copyright (C) 2015 Austin Glaser <[email protected]> * * Distributed under terms of the MIT license. */ public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
gpl-2.0
a2flo/a2elight
src/gui/font.hpp
5950
/* * Albion 2 Engine "light" * Copyright (C) 2004 - 2014 Florian Ziesche * * 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 only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef __A2E_FONT_HPP__ #define __A2E_FONT_HPP__ #include "global.hpp" #include <floor/core/event.hpp> #include "gui/font_manager.hpp" #include "rendering/renderer/gl_shader_fwd.hpp" class shader; typedef struct FT_FaceRec_* FT_Face; //! stores a font and can be used for drawing class a2e_font { public: //! single font file or font collection a2e_font(font_manager* fm, const string& filename); //! multiple font files (note: only the first of each style will be used) a2e_font(font_manager* fm, vector<string>&& filenames); ~a2e_font(); // draw functions void draw(const string& text, const float2& position, const float4 color = float4(1.0f)); void draw_cached(const string& text, const float2& position, const float4 color = float4(1.0f)) const; void draw_cached(const GLuint& ubo, const size_t& character_count, const float2& position, const float4 color = float4(1.0f)) const; // style functions const vector<string> get_available_styles() const; const unsigned int& get_size() const; const unsigned int& get_display_size() const; float compute_advance(const string& str, const unsigned int component = 0) const; float compute_advance(const vector<unsigned int>& unicode_str, const unsigned int component = 0) const; vector<float2> compute_advance_map(const string& str, const unsigned int component = 0) const; vector<float2> compute_advance_map(const vector<unsigned int>& unicode_str, const unsigned int component = 0) const; //! http://en.wikipedia.org/wiki/Basic_Multilingual_Plane#Basic_Multilingual_Plane enum class BMP_BLOCK : unsigned int { BASIC_LATIN = 0x0000'007F, // NOTE: will be cached automatically (0000 - 007F) LATIN_1_SUPPLEMENT = 0x0080'00FF, // NOTE: will be cached automatically (0080 - 00FF) LATIN_EXTENDED_A = 0x0100'017F, // 0100 - 017F LATIN_EXTENDED_B = 0x0180'024F, // 0180 - 024F LATIN_IPA_EXTENSIONS = 0x0250'02AF, // 0250 - 02AF GREEK = 0x0370'03FF, // 0370 - 03FF CYRILLIC = 0x0400'04FF, // 0400 - 04FF CYRILLIC_SUPPLEMENT = 0x0500'052F, // 0500 - 052F ARMENIAN = 0x0530'058F, // 0530 - 058F HEBREW = 0x0590'05FF, // 0590 - 05FF ARABIC = 0x0600'06FF, // 0600 - 06FF ARABIC_SUPPLEMENT = 0x0750'077F, // 0750 - 077F HIRAGANA = 0x3040'309F, // 3040 - 309F KATAKANA = 0x30A0'30FF // 30A0 - 30FF }; //! shortcut for common blocks void cache(const BMP_BLOCK block); //! this must be utf-8 encoded void cache(const string& characters); //! should be within 0x0 - 0x10FFFF void cache(const unsigned int& start_code, const unsigned int& end_code); //! <<ubo, character_count>, extent>, note: ubo must be destroyed/managed manually! typedef pair<uint2, float2> text_cache; text_cache cache_text(const string& text, const GLuint existing_ubo = 0); static void destroy_text_cache(text_cache& cached_text); bool is_cached(const unsigned int& code) const; // TODO: clear cache //void clear_cache(); // texture cache info static constexpr unsigned int font_texture_size = 1024; // unicode -> texture index struct glyph_data { const unsigned int tex_index; const int4 layout; const int2 size; }; protected: shader* s = nullptr; font_manager* fm = nullptr; const vector<string> filenames; string font_name = "NONE"; // style -> ft face unordered_map<string, FT_Face> faces; bool add_face(const string& style, FT_Face face); // style -> (unicode -> glyph data) unordered_map<string, unordered_map<unsigned int, glyph_data>> glyph_map; unsigned int font_size = 10; unsigned int display_font_size = font_size; unsigned int glyphs_per_line = 0; unsigned int glyphs_per_layer = 0; void recreate_texture_array(const size_t& layers); GLuint tex_array = 0; size_t tex_array_layers = 0; GLuint glyph_vbo = 0; #if defined(FLOOR_IOS) unsigned char* tex_data { nullptr }; #endif pair<vector<uint2>, float2> create_text_ubo_data(const string& text, std::function<void(unsigned int)> cache_fnc = [](unsigned int){}) const; GLuint text_ubo = 0; gl_shader font_shd; void reload_shaders(); event::handler shader_reload_fnctr; bool shader_reload_handler(EVENT_TYPE type, shared_ptr<event_object> obj); // size functions (TODO: will be made public when dynamic size changes are supported) void set_size(const unsigned int& size); // float2 text_stepper(const string& str, std::function<void(unsigned int, const glyph_data&, const float2&, const float2&)> fnc = [](unsigned int, const glyph_data&, const float2&, const float2&){}, std::function<void(unsigned int, const float2&, const float&)> line_break_fnc = [](unsigned int, const float2&, const float&){}, std::function<void(unsigned int)> cache_fnc = [](unsigned int){}) const; float2 text_stepper(const vector<unsigned int>& unicode_str, std::function<void(unsigned int, const glyph_data&, const float2&, const float2&)> fnc = [](unsigned int, const glyph_data&, const float2&, const float2&){}, std::function<void(unsigned int, const float2&, const float&)> line_break_fnc = [](unsigned int, const float2&, const float&){}, std::function<void(unsigned int)> cache_fnc = [](unsigned int){}) const; }; #endif
gpl-2.0
pdonaire1/gisaga
tmp/install_544db754ed102/installer/adapters/plugin.php
4670
<?php /** * @package Installer Bundle Framework - RocketTheme * @version 2.0.7 November 5, 2013 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * * Installer uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system */ // Check to ensure this file is within the rest of the framework defined('JPATH_BASE') or die(); if (!class_exists("JInstallerPlugin")) { @include_once(JPATH_LIBRARIES . '/joomla/installer/adapters/plugin.php'); } /** * Component installer * * @package Joomla.Framework * @subpackage Installer * @since 1.5 */ class RokInstallerPlugin extends JInstallerPlugin { protected $access; protected $enabled; protected $client; protected $ordering = 0; protected $protected; protected $params; const DEFAULT_ACCESS = 1; const DEFAULT_ENABLED = 'true'; const DEFAULT_PROTECTED = 'false'; const DEFAULT_CLIENT = 'site'; const DEFAULT_ORDERING = 0; const DEFAULT_PARAMS = null; public function setAccess($access) { $this->access = $access; } public function getAccess() { return $this->access; } public function setClient($client) { switch ($client) { case 'site': $client = 0; break; case 'administrator': $client = 1; break; default: $client = (int)$client; break; } $this->client = $client; } public function getClient() { return $this->client; } public function setEnabled($enabled) { switch (strtolower($enabled)) { case 'true': $enabled = 1; break; case 'false': $enabled = 0; break; default: $enabled = (int)$enabled; break; } $this->enabled = $enabled; } public function getEnabled() { return $this->enabled; } public function setOrdering($ordering) { $this->ordering = $ordering; } public function getOrdering() { return $this->ordering; } public function setProtected($protected) { switch (strtolower($protected)) { case 'true': $protected = 1; break; case 'false': $protected = 0; break; default: $protected = (int)$protected; break; } $this->protected = $protected; } public function getProtected() { return $this->protected; } public function setParams($params) { $this->params = $params; } public function getParams() { return $this->params; } protected function updateExtension(&$extension) { if ($extension) { $extension->access = $this->access; $extension->enabled = $this->enabled; $extension->protected = $this->protected; $extension->client_id = $this->client; $extension->ordering = $this->ordering; $extension->params = $this->params; $extension->store(); } } public function postInstall($extensionId) { $coginfo = $this->parent->getCogInfo(); $this->setAccess(($coginfo['access']) ? (int)$coginfo['access'] : self::DEFAULT_ACCESS); $this->setEnabled(($coginfo['enabled']) ? (string)$coginfo['enabled'] : self::DEFAULT_ENABLED); $this->setProtected(($coginfo['protected']) ? (string)$coginfo['protected'] : self::DEFAULT_PROTECTED); $this->setClient(($coginfo['client']) ? (string)$coginfo['client'] : self::DEFAULT_CLIENT); $this->setParams(($coginfo->params) ? (string)$coginfo->params : self::DEFAULT_PARAMS); $this->setOrdering(($coginfo['ordering']) ? (int)$coginfo['ordering'] : self::DEFAULT_ORDERING); $params = null; if ($coginfo->params) $params = (string)$coginfo->params; $extention = $this->loadExtension($extensionId); // update the extension info $this->updateExtension($extention); } protected function &loadExtension($eid) { $row = JTable::getInstance('extension'); $row->load($eid); return $row; } public function getInstallType() { return $this->route; } }
gpl-2.0
xen2/mcs
tests/test-primary-ctor-01.cs
298
class Simple(int arg) { int Property { get; } = arg; public static int Main () { var c = new Simple (4); if (c.Property != 4) return 1; var s = new S (4.3m); if (s.Property != 4.3m) return 1; return 0; } } struct S(decimal arg) { internal decimal Property { get; } = arg; }
gpl-2.0
gwq5210/acm
zoj/3209.cpp
3540
#include <cstdio> #include <cstring> #include <cstdlib> using namespace std; #define MAXN 1010 //ÐÐÊý #define MAXM 1010 //ÁÐÊý #define MAXNODE 500010 //×î´óµÄ½áµãÊý int K; //ÖØ¸´¸²¸ÇÑ¡ÔñµÄ×î´óÐÐÊý struct DLX { int n, m, size; int U[MAXNODE], D[MAXNODE], R[MAXNODE], L[MAXNODE], Row[MAXNODE], Col[MAXNODE]; int H[MAXN], S[MAXM]; int ansd, ans[MAXN]; void init(int _n, int _m) { n = _n; m = _m; for (int i = 0; i <= m; ++i) { S[i] = 0; U[i] = D[i] = i; L[i] = i - 1; R[i] = i + 1; } R[m] = 0; L[0] = m; size = m; for (int i = 1; i <= n; ++i) { H[i] = -1; } } void link(int r, int c) { ++S[Col[++size] = c]; Row[size] = r; D[size] = D[c]; U[D[c]] = size; U[size] = c; D[c] = size; if (H[r] < 0) { H[r] = L[size] = R[size] = size; } else { R[size] = R[H[r]]; L[R[H[r]]] = size; L[size] = H[r]; R[H[r]] = size; } } void eremove(int c) { L[R[c]] = L[c]; R[L[c]] = R[c]; for (int i = D[c]; i != c; i = D[i]) { for (int j = R[i]; j != i; j = R[j]) { U[D[j]] = U[j]; D[U[j]] = D[j]; --S[Col[j]]; } } } void eresume(int c) { for (int i = U[c]; i != c; i = U[i]) { for (int j = L[i]; j != i; j = L[j]) { ++S[Col[U[D[j]]= D[U[j]] = j]]; } } L[R[c]] = R[L[c]] = c; } void remove(int c) { for (int i = D[c]; i != c; i = D[i]) { L[R[i]] = L[i]; R[L[i]] = R[i]; } } void resume(int c) { for (int i = U[c]; i != c; i = U[i]) { L[R[i]] = R[L[i]] = i; } } bool v[MAXM]; int f(void) { int ret = 0; for (int c = R[0]; c != 0; c = R[c]) { v[c] = true; } for (int c = R[0]; c != 0; c = R[c]) { if (v[c]) { ++ret; v[c] = false; for (int i = D[c]; i != c; i = D[i]) { for (int j = R[i]; j != i; j = R[j]) { v[Col[j]] = false; } } } } return ret; } bool dance(int d) { if (d + f() > K) { return false; } if (R[0] == 0) { return d <= K; } int c = R[0]; for (int i = R[0]; i != 0; i = R[i]) { if (S[i] < S[c]) { c = i; } } for (int i = D[c]; i != c; i = D[i]) { remove(i); for (int j = R[i]; j != i; j = R[j]) { remove(j); } if (dance(d + 1)) { return true; } for (int j = L[i]; j != i; j = L[j]) { resume(j); } resume(i); } return false; } bool edance(int d) { if (ansd != -1 && ansd <= d) { return true; } if (R[0] == 0) { if (ansd == -1) { ansd = d; } else if (d < ansd) { ansd = d; } return true; } int c = R[0]; for (int i = R[0]; i != 0; i = R[i]) { if (S[i] < S[c]) { c = i; } } eremove(c); for (int i = D[c]; i != c; i = D[i]) { ans[d] = Row[i]; for (int j = R[i]; j != i; j = R[j]) { eremove(Col[j]); } edance(d + 1); for (int j = L[i]; j != i; j = L[j]) { eresume(Col[j]); } } eresume(c); return false; } }; DLX g; int main(void) { int t; scanf("%d", &t); while (t--) { int n, m, p; scanf("%d%d%d", &n, &m, &p); g.init(p, n * m); for (int i = 1; i <= p; ++i) { int x1, x2, y1, y2; scanf("%d%d%d%d", &x1, &y1, &x2, &y2); for (int j = x1 + 1; j <= x2; ++j) { for (int k = y1 + 1; k <= y2; ++k) { g.link(i, (j - 1) * m + k); } } } g.ansd = -1; g.edance(0); printf("%d\n", g.ansd); } return 0; }
gpl-2.0
raphaelfeng/benerator
src/org/databene/model/data/ComponentAccessor.java
1945
/* * (c) Copyright 2007-2013 by Volker Bergmann. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, is permitted under the terms of the * GNU General Public License. * * For redistributing this software or a derivative work under a license other * than the GPL-compatible Free Software License as defined by the Free * Software Foundation or approved by OSI, you must first obtain a commercial * license to this software product from Volker Bergmann. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS, * REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE * HEREBY EXCLUDED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.databene.model.data; import org.databene.commons.Accessor; /** * Accesses a component of an entity specified by the component name.<br/> * <br/> * Created: 26.08.2007 07:22:33 */ public class ComponentAccessor implements Accessor<Entity, Object> { private String componentName; public ComponentAccessor(String componentName) { this.componentName = componentName; } @Override public Object getValue(Entity target) { return target.getComponent(componentName); } }
gpl-2.0
dalinhuang/kakayaga
img/includes/functions/html_output.php
13991
<?php // // +----------------------------------------------------------------------+ // |zen-cart Open Source E-commerce | // +----------------------------------------------------------------------+ // | Copyright (c) 2003 The zen-cart developers | // | | // | http://www.zen-cart.com/index.php | // | | // | Portions Copyright (c) 2003 osCommerce | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.0 of the GPL license, | // | that is bundled with this package in the file LICENSE, and is | // | available through the world-wide-web at the following url: | // | http://www.zen-cart.com/license/2_0.txt. | // | If you did not receive a copy of the zen-cart license and are unable | // | to obtain it through the world-wide-web, please send a note to | // | [email protected] so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // $Id: html_output.php 3089 2006-03-01 18:32:25Z ajeh $ // //// // The HTML href link wrapper function function zen_href_link($page = '', $parameters = '', $connection = 'NONSSL', $add_session_id = true) { global $request_type, $session_started, $http_domain, $https_domain; if ($page == '') { die('</td></tr></table></td></tr></table><br><br><font color="#ff0000"><b>Error!</b></font><br><br><b>Unable to determine the page link!<br><br>Function used:<br><br>zen_href_link(\'' . $page . '\', \'' . $parameters . '\', \'' . $connection . '\')</b>'); } if ($connection == 'NONSSL') { $link = HTTP_SERVER . DIR_WS_ADMIN; } elseif ($connection == 'SSL') { if (ENABLE_SSL_ADMIN == 'true') { $link = HTTPS_SERVER . DIR_WS_HTTPS_ADMIN; } else { $link = HTTP_SERVER . DIR_WS_ADMIN; } } else { die('</td></tr></table></td></tr></table><br><br><font color="#ff0000"><b>Error!</b></font><br><br><b>Unable to determine connection method on a link!<br><br>Known methods: NONSSL SSL<br><br>Function used:<br><br>zen_href_link(\'' . $page . '\', \'' . $parameters . '\', \'' . $connection . '\')</b>'); } if (!strstr($page, '.php')) $page .= '.php'; if ($parameters == '') { $link = $link . $page; $separator = '?'; } else { $link = $link . $page . '?' . $parameters; $separator = '&'; } while ( (substr($link, -1) == '&') || (substr($link, -1) == '?') ) $link = substr($link, 0, -1); // Add the session ID when moving from different HTTP and HTTPS servers, or when SID is defined if ( ($add_session_id == true) && ($session_started == true) ) { if (defined('SID') && zen_not_null(SID)) { $sid = SID; } elseif ( ( ($request_type == 'NONSSL') && ($connection == 'SSL') && (ENABLE_SSL_ADMIN == 'true') ) || ( ($request_type == 'SSL') && ($connection == 'NONSSL') ) ) { //die($connection); if ($http_domain != $https_domain) { $sid = zen_session_name() . '=' . zen_session_id(); } } } if (isset($sid)) { $link .= $separator . $sid; } return $link; } function zen_catalog_href_link($page = '', $parameters = '', $connection = 'NONSSL') { if ($connection == 'NONSSL') { $link = HTTP_CATALOG_SERVER . DIR_WS_CATALOG; } elseif ($connection == 'SSL') { if (ENABLE_SSL_CATALOG == 'true') { $link = HTTPS_CATALOG_SERVER . DIR_WS_HTTPS_CATALOG; } else { $link = HTTP_CATALOG_SERVER . DIR_WS_CATALOG; } } else { die('</td></tr></table></td></tr></table><br><br><font color="#ff0000"><b>Error!</b></font><br><br><b>Unable to determine connection method on a link!<br><br>Known methods: NONSSL SSL<br><br>Function used:<br><br>zen_href_link(\'' . $page . '\', \'' . $parameters . '\', \'' . $connection . '\')</b>'); } if ($parameters == '') { $link .= 'index.php?main_page='. $page; } else { $link .= 'index.php?main_page='. $page . "&" . zen_output_string($parameters); } while ( (substr($link, -1) == '&') || (substr($link, -1) == '?') ) $link = substr($link, 0, -1); return $link; } //// // The HTML image wrapper function function zen_image($src, $alt = '', $width = '', $height = '', $params = '') { $image = '<img src="' . $src . '" border="0" alt="' . $alt . '"'; if ($alt) { $image .= ' title=" ' . $alt . ' "'; } if ($width) { $image .= ' width="' . $width . '"'; } if ($height) { $image .= ' height="' . $height . '"'; } if ($params) { $image .= ' ' . $params; } $image .= '>'; return $image; } //// // The HTML form submit button wrapper function // Outputs a button in the selected language function zen_image_submit($image, $alt = '', $parameters = '') { global $language; $image_submit = '<input type="image" src="' . zen_output_string(DIR_WS_LANGUAGES . $_SESSION['language'] . '/images/buttons/' . $image) . '" border="0" alt="' . zen_output_string($alt) . '"'; if (zen_not_null($alt)) $image_submit .= ' title=" ' . zen_output_string($alt) . ' "'; if (zen_not_null($parameters)) $image_submit .= ' ' . $parameters; $image_submit .= '>'; return $image_submit; } //// // Draw a 1 pixel black line function zen_black_line() { return zen_image(DIR_WS_IMAGES . 'pixel_black.gif', '', '100%', '1'); } //// // Output a separator either through whitespace, or with an image function zen_draw_separator($image = 'pixel_black.gif', $width = '100%', $height = '1') { return zen_image(DIR_WS_IMAGES . $image, '', $width, $height); } //// // Output a function button in the selected language function zen_image_button($image, $alt = '', $params = '') { global $language; return zen_image(DIR_WS_LANGUAGES . $_SESSION['language'] . '/images/buttons/' . $image, $alt, '', '', $params); } //// // javascript to dynamically update the states/provinces list when the country is changed // TABLES: zones function zen_js_zone_list($country, $form, $field) { global $db; $countries = $db->Execute("select distinct zone_country_id from " . TABLE_ZONES . " order by zone_country_id"); $num_country = 1; $output_string = ''; while (!$countries->EOF) { if ($num_country == 1) { $output_string .= ' if (' . $country . ' == "' . $countries->fields['zone_country_id'] . '") {' . "\n"; } else { $output_string .= ' } else if (' . $country . ' == "' . $countries->fields['zone_country_id'] . '") {' . "\n"; } $states = $db->Execute("select zone_name, zone_id from " . TABLE_ZONES . " where zone_country_id = '" . $countries->fields['zone_country_id'] . "' order by zone_name"); $num_state = 1; while (!$states->EOF) { if ($num_state == '1') $output_string .= ' ' . $form . '.' . $field . '.options[0] = new Option("' . PLEASE_SELECT . '", "");' . "\n"; $output_string .= ' ' . $form . '.' . $field . '.options[' . $num_state . '] = new Option("' . $states->fields['zone_name'] . '", "' . $states->fields['zone_id'] . '");' . "\n"; $num_state++; $states->MoveNext(); } $num_country++; $countries->MoveNext(); } $output_string .= ' } else {' . "\n" . ' ' . $form . '.' . $field . '.options[0] = new Option("' . TYPE_BELOW . '", "");' . "\n" . ' }' . "\n"; return $output_string; } //// // Output a form function zen_draw_form($name, $action, $parameters = '', $method = 'post', $params = '', $usessl = 'false') { $form = '<form name="' . zen_output_string($name) . '" action="'; if (zen_not_null($parameters)) { if ($usessl) { $form .= zen_href_link($action, $parameters, 'NONSSL'); } else { $form .= zen_href_link($action, $parameters, 'NONSSL'); } } else { if ($usessl) { $form .= zen_href_link($action, '', 'NONSSL'); } else { $form .= zen_href_link($action, '', 'NONSSL'); } } $form .= '" method="' . zen_output_string($method) . '"'; if (zen_not_null($params)) { $form .= ' ' . $params; } $form .= '>'; return $form; } //// // Output a form input field function zen_draw_input_field($name, $value = '', $parameters = '', $required = false, $type = 'text', $reinsert_value = true) { $field = '<input type="' . zen_output_string($type) . '" name="' . zen_output_string($name) . '"'; if (isset($GLOBALS[$name]) && ($reinsert_value == true) && is_string($GLOBALS[$name])) { $field .= ' value="' . zen_output_string(stripslashes($GLOBALS[$name])) . '"'; } elseif (zen_not_null($value)) { $field .= ' value="' . zen_output_string($value) . '"'; } if (zen_not_null($parameters)) $field .= ' ' . $parameters; $field .= '>'; if ($required == true) $field .= TEXT_FIELD_REQUIRED; return $field; } //// // Output a form password field function zen_draw_password_field($name, $value = '', $required = false) { $field = zen_draw_input_field($name, $value, 'maxlength="40"', $required, 'password', false); return $field; } //// // Output a form filefield function zen_draw_file_field($name, $required = false) { $field = zen_draw_input_field($name, '', ' size="50" ', $required, 'file'); return $field; } //// // Output a selection field - alias function for zen_draw_checkbox_field() and zen_draw_radio_field() function zen_draw_selection_field($name, $type, $value = '', $checked = false, $compare = '', $parameters = '') { $selection = '<input type="' . zen_output_string($type) . '" name="' . zen_output_string($name) . '"'; if (zen_not_null($value)) $selection .= ' value="' . zen_output_string($value) . '"'; if ( ($checked == true) || (isset($GLOBALS[$name]) && is_string($GLOBALS[$name]) && ($GLOBALS[$name] == 'on')) || (isset($value) && isset($GLOBALS[$name]) && (stripslashes($GLOBALS[$name]) == $value)) || (zen_not_null($value) && zen_not_null($compare) && ($value == $compare)) ) { $selection .= ' CHECKED'; } if (zen_not_null($parameters)) $selection .= ' ' . $parameters; $selection .= '>'; return $selection; } //// // Output a form checkbox field function zen_draw_checkbox_field($name, $value = '', $checked = false, $compare = '', $parameters = '') { return zen_draw_selection_field($name, 'checkbox', $value, $checked, $compare, $parameters); } //// // Output a form radio field function zen_draw_radio_field($name, $value = '', $checked = false, $compare = '', $parameters = '') { return zen_draw_selection_field($name, 'radio', $value, $checked, $compare, $parameters); } //// // Output a form textarea field function zen_draw_textarea_field($name, $wrap, $width, $height, $text = '', $parameters = '', $reinsert_value = true) { $field = '<textarea name="' . zen_output_string($name) . '" wrap="' . zen_output_string($wrap) . '" cols="' . zen_output_string($width) . '" rows="' . zen_output_string($height) . '"'; if (zen_not_null($parameters)) $field .= ' ' . $parameters; $field .= '>'; if ( (isset($GLOBALS[$name])) && ($reinsert_value == true) ) { $field .= stripslashes($GLOBALS[$name]); } elseif (zen_not_null($text)) { $field .= $text; } $field .= '</textarea>'; return $field; } //// // Output a form hidden field function zen_draw_hidden_field($name, $value = '', $parameters = '') { $field = '<input type="hidden" name="' . zen_output_string($name) . '"'; if (zen_not_null($value)) { $field .= ' value="' . zen_output_string($value) . '"'; } elseif (isset($GLOBALS[$name]) && is_string($GLOBALS[$name])) { $field .= ' value="' . zen_output_string(stripslashes($GLOBALS[$name])) . '"'; } if (zen_not_null($parameters)) $field .= ' ' . $parameters; $field .= '>'; return $field; } //// // Output a form pull down menu function zen_draw_pull_down_menu($name, $values, $default = '', $parameters = '', $required = false) { // $field = '<select name="' . zen_output_string($name) . '"'; $field = '<select rel="dropdown" name="' . zen_output_string($name) . '"'; if (zen_not_null($parameters)) $field .= ' ' . $parameters; $field .= '>'; if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]); for ($i=0, $n=sizeof($values); $i<$n; $i++) { $field .= '<option value="' . zen_output_string($values[$i]['id']) . '"'; if ($default == $values[$i]['id']) { $field .= ' SELECTED'; } $field .= '>' . zen_output_string($values[$i]['text'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '</option>'; } $field .= '</select>'; if ($required == true) $field .= TEXT_FIELD_REQUIRED; return $field; } //// // Hide form elements function zen_hide_session_id() { global $session_started; if ( ($session_started == true) && defined('SID') && zen_not_null(SID) ) { return zen_draw_hidden_field(zen_session_name(), zen_session_id()); } } ?>
gpl-2.0
vogel/kadu
plugins/spellchecker/translations/spellchecker_el.ts
2390
<?xml version="1.0" ?><!DOCTYPE TS><TS language="el" version="2.1"> <context> <name>@default</name> <message> <source>Chat</source> <translation type="unfinished"/> </message> <message> <source>Misspelled Words Marking Options</source> <translation type="unfinished"/> </message> <message> <source>Color</source> <translation type="unfinished"/> </message> <message> <source>Bold</source> <translation type="unfinished"/> </message> <message> <source>Italic</source> <translation type="unfinished"/> </message> <message> <source>Underline</source> <translation type="unfinished"/> </message> <message> <source>Spell Checker Options</source> <translation type="unfinished"/> </message> <message> <source>Ignore case</source> <translation type="unfinished"/> </message> <message> <source>Spelling Suggestions Options</source> <translation type="unfinished"/> </message> <message> <source>Show suggestions</source> <translation type="unfinished"/> </message> <message> <source>Maximum number of suggested words</source> <translation type="unfinished"/> </message> <message> <source>Spelling</source> <translation type="unfinished"/> </message> </context> <context> <name>SpellChecker</name> <message> <source>Kadu</source> <translation type="unfinished"/> </message> <message> <source>Could not find dictionary for %1 language.</source> <translation type="unfinished"/> </message> <message> <source>Details</source> <translation type="unfinished"/> </message> </context> <context> <name>SpellcheckerConfigurationUiHandler</name> <message> <source>Move to &apos;Checked&apos;</source> <translation type="unfinished"/> </message> <message> <source>Available languages</source> <translation type="unfinished"/> </message> <message> <source>Move to &apos;Available languages&apos;</source> <translation type="unfinished"/> </message> <message> <source>Checked</source> <translation type="unfinished"/> </message> </context> </TS>
gpl-2.0
ericdum/niuble.com
other_sites/showcases/yuyan/control/admin_cooperate.php
825
<?php !defined('IN_HDWIKI') && exit('Access Denied'); class control extends base{ function control(& $get,& $post){ $this->base( & $get,& $post); $this->load('setting'); $this->view->setlang($this->setting['lang_name'],'back'); } /*set cooperate*/ function dodefault(){ if(!isset($this->post['submit'])){ $cooperatedoc=$this->setting['cooperatedoc']; $this->view->assign("cooperatedoc",$cooperatedoc); $this->view->display("admin_cooperate"); exit; } $setting=array(); $setting['cooperatedoc'] = trim($this->post['cooperate']); $_ENV['setting']->update_setting($setting); $this->cache->removecache('setting'); $this->cache->removecache('data_'.$GLOBALS['theme'].'_index'); $this->message($this->view->lang['cooperatesuccse'],'index.php?admin_cooperate'); } }
gpl-2.0
iGormilhit/plxminiGor
commentaires.php
2918
<?php if(!defined('PLX_ROOT')) exit; ?> <?php if($plxShow->plxMotor->plxRecord_coms): ?> <div id="comments"> <h2> <?php echo $plxShow->artNbCom() ?> </h2> <?php while($plxShow->plxMotor->plxRecord_coms->loop()): # On boucle sur les commentaires ?> <div id="<?php $plxShow->comId(); ?>" class="comment"> <blockquote> <p class="info_comment"><a class="num-com" href="<?php $plxShow->ComUrl(); ?>" title="#<?php echo $plxShow->plxMotor->plxRecord_coms->i+1 ?>">#<?php echo $plxShow->plxMotor->plxRecord_coms->i+1 ?> : <?php $plxShow->comDate('#num_year(4)-#num_month-#num_day &#64; #hour:#minute'); ?></a><br /> <?php $plxShow->comAuthor('link'); ?> <?php $plxShow->lang('SAID') ?> : </p> <p class="content_com type-<?php $plxShow->comType(); ?>"><?php $plxShow->comContent() ?></p> </blockquote> </div> <?php endwhile; # Fin de la boucle sur les commentaires ?> <div class="rss"> <?php $plxShow->comFeed('rss',$plxShow->artId()); ?> </div> </div> <?php endif; ?> <?php if($plxShow->plxMotor->plxRecord_arts->f('allow_com') AND $plxShow->plxMotor->aConf['allow_com']): ?> <div id="form"> <h2> <?php $plxShow->lang('WRITE_A_COMMENT') ?> </h2> <form action="<?php $plxShow->artUrl(); ?>#form" method="post"> <fieldset> <p> <label for="id_name"><?php $plxShow->lang('NAME') ?> :</label> </p> <p> <input id="id_name" name="name" type="text" size="20" value="<?php $plxShow->comGet('name',''); ?>" maxlength="30" /> </p> <p> <label for="id_site"><?php $plxShow->lang('WEBSITE') ?> :</label> </p> <p> <input id="id_site" name="site" type="text" size="20" value="<?php $plxShow->comGet('site',''); ?>" /> </p> <p> <label for="id_mail"><?php $plxShow->lang('EMAIL') ?> :</label> </p> <p> <input id="id_mail" name="mail" type="text" size="20" value="<?php $plxShow->comGet('mail',''); ?>" /> </p> <p> <label for="id_content" class="lab_com"><?php $plxShow->lang('COMMENT') ?> :</label> </p> <p> <textarea id="id_content" name="content" cols="35" rows="6"><?php $plxShow->comGet('content',''); ?></textarea> </p> <p class="com-alert"> <?php $plxShow->comMessage(); ?> </p> <?php if($plxShow->plxMotor->aConf['capcha']): ?> <p> <label for="id_rep"><strong><?php echo $plxShow->lang('ANTISPAM_WARNING') ?></strong> :</label> </p> <p> <?php $plxShow->capchaQ(); ?> : <input id="id_rep" name="rep" type="text" size="2" maxlength="1" /> </p> <?php endif; ?> <p> <input type="submit" value="<?php $plxShow->lang('SEND') ?>" /> </p> </fieldset> </form> </div> <?php else: ?> <p> <?php $plxShow->lang('COMMENTS_CLOSED') ?>. </p> <?php endif; # Fin du if sur l'autorisation des commentaires ?>
gpl-2.0
misur/FitEat
src/com/google/zxing/client/android/camera/CameraConfigurationManager.java
12176
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.client.android.camera; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Point; import android.hardware.Camera; import android.preference.PreferenceManager; import android.util.Log; import android.view.Display; import android.view.WindowManager; import com.google.zxing.client.android.PreferencesActivity; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * A class which deals with reading, parsing, and setting the camera parameters which are used to * configure the camera hardware. */ final class CameraConfigurationManager { private static final String TAG = "CameraConfiguration"; // This is bigger than the size of a small screen, which is still supported. The routine // below will still select the default (presumably 320x240) size for these. This prevents // accidental selection of very low resolution on some devices. private static final int MIN_PREVIEW_PIXELS = 480 * 320; // normal screen //private static final float MAX_EXPOSURE_COMPENSATION = 1.5f; //private static final float MIN_EXPOSURE_COMPENSATION = 0.0f; private static final double MAX_ASPECT_DISTORTION = 0.15; private final Context context; private Point screenResolution; private Point cameraResolution; CameraConfigurationManager(Context context) { this.context = context; } /** * Reads, one time, values from the camera that are needed by the app. */ void initFromCameraParameters(Camera camera) { Camera.Parameters parameters = camera.getParameters(); WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); Point theScreenResolution = new Point(); display.getSize(theScreenResolution); screenResolution = theScreenResolution; Log.i(TAG, "Screen resolution: " + screenResolution); cameraResolution = findBestPreviewSizeValue(parameters, screenResolution); Log.i(TAG, "Camera resolution: " + cameraResolution); } void setDesiredCameraParameters(Camera camera, boolean safeMode) { Camera.Parameters parameters = camera.getParameters(); if (parameters == null) { Log.w(TAG, "Device error: no camera parameters are available. Proceeding without configuration."); return; } Log.i(TAG, "Initial camera parameters: " + parameters.flatten()); if (safeMode) { Log.w(TAG, "In camera config safe mode -- most settings will not be honored"); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); initializeTorch(parameters, prefs, safeMode); String focusMode = null; if (prefs.getBoolean(PreferencesActivity.KEY_AUTO_FOCUS, true)) { if (safeMode || prefs.getBoolean(PreferencesActivity.KEY_DISABLE_CONTINUOUS_FOCUS, false)) { focusMode = findSettableValue(parameters.getSupportedFocusModes(), Camera.Parameters.FOCUS_MODE_AUTO); } else { focusMode = findSettableValue(parameters.getSupportedFocusModes(), Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE, Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, Camera.Parameters.FOCUS_MODE_AUTO); } } // Maybe selected auto-focus but not available, so fall through here: if (!safeMode && focusMode == null) { focusMode = findSettableValue(parameters.getSupportedFocusModes(), Camera.Parameters.FOCUS_MODE_MACRO, Camera.Parameters.FOCUS_MODE_EDOF); } if (focusMode != null) { parameters.setFocusMode(focusMode); } if (prefs.getBoolean(PreferencesActivity.KEY_INVERT_SCAN, false)) { String colorMode = findSettableValue(parameters.getSupportedColorEffects(), Camera.Parameters.EFFECT_NEGATIVE); if (colorMode != null) { parameters.setColorEffect(colorMode); } } parameters.setPreviewSize(cameraResolution.x, cameraResolution.y); camera.setParameters(parameters); Camera.Parameters afterParameters = camera.getParameters(); Camera.Size afterSize = afterParameters.getPreviewSize(); if (afterSize!= null && (cameraResolution.x != afterSize.width || cameraResolution.y != afterSize.height)) { Log.w(TAG, "Camera said it supported preview size " + cameraResolution.x + 'x' + cameraResolution.y + ", but after setting it, preview size is " + afterSize.width + 'x' + afterSize.height); cameraResolution.x = afterSize.width; cameraResolution.y = afterSize.height; } } Point getCameraResolution() { return cameraResolution; } Point getScreenResolution() { return screenResolution; } boolean getTorchState(Camera camera) { if (camera != null) { Camera.Parameters parameters = camera.getParameters(); if (parameters != null) { String flashMode = camera.getParameters().getFlashMode(); return flashMode != null && (Camera.Parameters.FLASH_MODE_ON.equals(flashMode) || Camera.Parameters.FLASH_MODE_TORCH.equals(flashMode)); } } return false; } void setTorch(Camera camera, boolean newSetting) { Camera.Parameters parameters = camera.getParameters(); doSetTorch(parameters, newSetting, false); camera.setParameters(parameters); } private void initializeTorch(Camera.Parameters parameters, SharedPreferences prefs, boolean safeMode) { boolean currentSetting = FrontLightMode.readPref(prefs) == FrontLightMode.ON; doSetTorch(parameters, currentSetting, safeMode); } private void doSetTorch(Camera.Parameters parameters, boolean newSetting, boolean safeMode) { String flashMode; if (newSetting) { flashMode = findSettableValue(parameters.getSupportedFlashModes(), Camera.Parameters.FLASH_MODE_TORCH, Camera.Parameters.FLASH_MODE_ON); } else { flashMode = findSettableValue(parameters.getSupportedFlashModes(), Camera.Parameters.FLASH_MODE_OFF); } if (flashMode != null) { parameters.setFlashMode(flashMode); } /* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (!prefs.getBoolean(PreferencesActivity.KEY_DISABLE_EXPOSURE, false)) { if (!safeMode) { int minExposure = parameters.getMinExposureCompensation(); int maxExposure = parameters.getMaxExposureCompensation(); if (minExposure != 0 || maxExposure != 0) { float step = parameters.getExposureCompensationStep(); int desiredCompensation; if (newSetting) { // Light on; set low exposue compensation desiredCompensation = Math.max((int) (MIN_EXPOSURE_COMPENSATION / step), minExposure); } else { // Light off; set high compensation desiredCompensation = Math.min((int) (MAX_EXPOSURE_COMPENSATION / step), maxExposure); } Log.i(TAG, "Setting exposure compensation to " + desiredCompensation + " / " + (step * desiredCompensation)); parameters.setExposureCompensation(desiredCompensation); } else { Log.i(TAG, "Camera does not support exposure compensation"); } } } */ } private Point findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution) { List<Camera.Size> rawSupportedSizes = parameters.getSupportedPreviewSizes(); if (rawSupportedSizes == null) { Log.w(TAG, "Device returned no supported preview sizes; using default"); Camera.Size defaultSize = parameters.getPreviewSize(); return new Point(defaultSize.width, defaultSize.height); } // Sort by size, descending List<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(rawSupportedSizes); Collections.sort(supportedPreviewSizes, new Comparator<Camera.Size>() { @Override public int compare(Camera.Size a, Camera.Size b) { int aPixels = a.height * a.width; int bPixels = b.height * b.width; if (bPixels < aPixels) { return -1; } if (bPixels > aPixels) { return 1; } return 0; } }); if (Log.isLoggable(TAG, Log.INFO)) { StringBuilder previewSizesString = new StringBuilder(); for (Camera.Size supportedPreviewSize : supportedPreviewSizes) { previewSizesString.append(supportedPreviewSize.width).append('x') .append(supportedPreviewSize.height).append(' '); } Log.i(TAG, "Supported preview sizes: " + previewSizesString); } double screenAspectRatio = (double) screenResolution.y / (double) screenResolution.x; // Remove sizes that are unsuitable Iterator<Camera.Size> it = supportedPreviewSizes.iterator(); while (it.hasNext()) { Camera.Size supportedPreviewSize = it.next(); int realWidth = supportedPreviewSize.width; int realHeight = supportedPreviewSize.height; if (realWidth * realHeight < MIN_PREVIEW_PIXELS) { it.remove(); continue; } boolean isCandidatePortrait = realWidth < realHeight; int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth; int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight; double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight; double distortion = Math.abs(aspectRatio - screenAspectRatio); if (distortion > MAX_ASPECT_DISTORTION) { it.remove(); continue; } if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) { Point exactPoint = new Point(realWidth, realHeight); Log.i(TAG, "Found preview size exactly matching screen size: " + exactPoint); return exactPoint; } } // If no exact match, use largest preview size. This was not a great idea on older devices because // of the additional computation needed. We're likely to get here on newer Android 4+ devices, where // the CPU is much more powerful. if (!supportedPreviewSizes.isEmpty()) { Camera.Size largestPreview = supportedPreviewSizes.get(0); Point largestSize = new Point(largestPreview.width, largestPreview.height); Log.i(TAG, "Using largest suitable preview size: " + largestSize); return largestSize; } // If there is nothing at all suitable, return current preview size Camera.Size defaultPreview = parameters.getPreviewSize(); Point defaultSize = new Point(defaultPreview.width, defaultPreview.height); Log.i(TAG, "No suitable preview sizes, using default: " + defaultSize); return defaultSize; } private static String findSettableValue(Collection<String> supportedValues, String... desiredValues) { Log.i(TAG, "Supported values: " + supportedValues); String result = null; if (supportedValues != null) { for (String desiredValue : desiredValues) { if (supportedValues.contains(desiredValue)) { result = desiredValue; break; } } } Log.i(TAG, "Settable value: " + result); return result; } }
gpl-2.0