code
stringlengths
4
1.01M
language
stringclasses
2 values
#pragma once #include <MellowPlayer/Presentation/Notifications/ISystemTrayIcon.hpp> #include <QMenu> #include <QSystemTrayIcon> namespace MellowPlayer::Domain { class ILogger; class IPlayer; class Setting; class Settings; } class SystemTrayIconStrings : public QObject { Q_OBJECT public: QString playPause() const; QString next() const; QString previous() const; QString restoreWindow() const; QString quit() const; }; namespace MellowPlayer::Infrastructure { class IApplication; } namespace MellowPlayer::Presentation { class IMainWindow; class SystemTrayIcon : public QObject, public ISystemTrayIcon { Q_OBJECT public: SystemTrayIcon(Domain::IPlayer& player, IMainWindow& mainWindow, Domain::Settings& settings); void show() override; void hide() override; void showMessage(const QString& title, const QString& message) override; public slots: void onActivated(QSystemTrayIcon::ActivationReason reason); void togglePlayPause(); void next(); void previous(); void restoreWindow(); void quit(); private slots: void onShowTrayIconSettingValueChanged(); private: void setUpMenu(); Domain::ILogger& logger_; Domain::IPlayer& player_; IMainWindow& mainWindow_; Domain::Settings& settings_; Domain::Setting& showTrayIconSetting_; QSystemTrayIcon qSystemTrayIcon_; QMenu menu_; QAction* playPauseAction_; QAction* previousSongAction_; QAction* nextSongAction_; QAction* restoreWindowAction_; QAction* quitApplicationAction_; }; }
Java
/* * ecgen, tool for generating Elliptic curve domain parameters * Copyright (C) 2017-2018 J08nY */ #include "hex.h" #include "exhaustive/arg.h" #include "field.h" #include "util/bits.h" #include "util/memory.h" #include "util/str.h" static char *hex_point(point_t *point) { GEN fx = field_elementi(gel(point->point, 1)); GEN fy = field_elementi(gel(point->point, 2)); char *fxs = pari_sprintf("%P0#*x", cfg->hex_digits, fx); char *fxy = pari_sprintf("%P0#*x", cfg->hex_digits, fy); char *result = str_joinv(",", fxs, fxy, NULL); pari_free(fxs); pari_free(fxy); return result; } static char *hex_points(point_t *points[], size_t len) { char *p[len]; for (size_t i = 0; i < len; ++i) { point_t *pt = points[i]; p[i] = hex_point(pt); } size_t total = 1; for (size_t i = 0; i < len; ++i) { total += strlen(p[i]); } char *result = try_calloc(total); for (size_t i = 0; i < len; ++i) { strcat(result, p[i]); try_free(p[i]); } return result; } CHECK(hex_check_param) { HAS_ARG(args); char *search_hex = try_strdup(args->args); char *p = search_hex; for (; *p; ++p) *p = (char)tolower(*p); char *params[OFFSET_END] = {NULL}; bool pari[OFFSET_END] = {false}; if (state >= OFFSET_SEED) { if (curve->seed && curve->seed->seed) { params[OFFSET_SEED] = bits_to_hex(curve->seed->seed); } } if (state >= OFFSET_FIELD) { if (cfg->field == FIELD_PRIME) { params[OFFSET_FIELD] = pari_sprintf("%P0#*x", cfg->hex_digits, curve->field); pari[OFFSET_FIELD] = true; } else if (cfg->field == FIELD_BINARY) { } } if (state >= OFFSET_A) { params[OFFSET_A] = pari_sprintf("%P0#*x", cfg->hex_digits, field_elementi(curve->a)); pari[OFFSET_A] = true; } if (state >= OFFSET_B) { params[OFFSET_B] = pari_sprintf("%P0#*x", cfg->hex_digits, field_elementi(curve->b)); pari[OFFSET_B] = true; } if (state >= OFFSET_ORDER) { params[OFFSET_ORDER] = pari_sprintf("%P0#*x", cfg->hex_digits, curve->order); pari[OFFSET_ORDER] = true; } if (state >= OFFSET_GENERATORS) { char *subgroups[curve->ngens]; for (size_t i = 0; i < curve->ngens; ++i) { subgroups[i] = hex_point(curve->generators[i]->generator); } params[OFFSET_GENERATORS] = str_join(",", subgroups, curve->ngens); for (size_t i = 0; i < curve->ngens; ++i) { try_free(subgroups[i]); } } if (state >= OFFSET_POINTS) { char *subgroups[curve->ngens]; for (size_t i = 0; i < curve->ngens; ++i) { subgroups[i] = hex_points(curve->generators[i]->points, curve->generators[i]->npoints); } params[OFFSET_POINTS] = str_join(",", subgroups, curve->ngens); for (size_t i = 0; i < curve->ngens; ++i) { try_free(subgroups[i]); } } int result = OFFSET_FIELD - state; for (offset_e i = OFFSET_SEED; i < OFFSET_END; ++i) { if (params[i]) { if (result != 1 && strstr(params[i], search_hex)) { result = 1; } if (pari[i]) { pari_free(params[i]); } else { try_free(params[i]); } } } try_free(search_hex); return result; }
Java
package irc.bot; import java.io.*; public class OutHandler implements Runnable { OutHandler(Connection connection) { this.connection = connection; } private Connection connection; public void run() {} }
Java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.ellcs.stack.android; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class string { public static final int app_name=0x7f030000; } public static final class style { public static final int GdxTheme=0x7f040000; } }
Java
PageProcessor::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 # config.middleware.insert 0, "Rack::WWWhisper" end
Java
This is a first attempt at constructing a Django wrapper around playing_god
Java
<?php function edd_rp_settings( $settings ) { $suggested_download_settings = array( array( 'id' => 'edd_rp_header', 'name' => '<strong>' . __('Recommended Products', 'edd-rp-txt') . '</strong>', 'desc' => '', 'type' => 'header', 'size' => 'regular' ), array( 'id' => 'edd_rp_display_single', 'name' => __('Show on Downloads', 'edd-rp-txt'), 'desc' => __('Display the recommended products on the download post type', 'edd-rp-txt'), 'type' => 'checkbox', 'size' => 'regular' ), array( 'id' => 'edd_rp_display_checkout', 'name' => __('Show on Checkout', 'edd-rp-txt'), 'desc' => __('Display the recommended products after the Checkout Cart, and before the Checkout Form', 'edd-rp-txt'), 'type' => 'checkbox', 'size' => 'regular' ), array( 'id' => 'edd_rp_suggestion_count', 'name' => __('Number of Recommendations', 'edd-rp-txt'), 'desc' => __('How many recommendations should be shown to users', 'edd-rp-txt'), 'type' => 'select', 'options' => edd_rp_suggestion_count() ), array( 'id' => 'edd_rp_show_free', 'name' => __('Show Free Products', 'edd-rp-txt'), 'desc' => __('Allows free products to be shown in the recommendations. (Requires Refresh of Recommendations after save)', 'edd-rp-txt'), 'type' => 'checkbox', 'size' => 'regular' ), array( 'id' => 'rp_settings_additional', 'name' => '', 'desc' => '', 'type' => 'hook' ) ); return array_merge( $settings, $suggested_download_settings ); } add_filter( 'edd_settings_extensions', 'edd_rp_settings' ); function edd_rp_suggestion_count() { for ( $i = 1; $i <= 5; $i++ ) { $count[$i] = $i; } $count[3] = __( '3 - Default', 'edd-rp-txt' ); return apply_filters( 'edd_rp_suggestion_counts', $count ); } function edd_rp_recalc_suggestions_button() { echo '<a href="' . wp_nonce_url( add_query_arg( array( 'edd_action' => 'refresh_edd_rp' ) ), 'edd-rp-recalculate' ) . '" class="button-secondary">' . __( 'Refresh Recommendations', 'edd-rp-txt' ) . '</a>'; } add_action( 'edd_rp_settings_additional', 'edd_rp_recalc_suggestions_button' ); function refresh_edd_rp( $data ) { if ( ! wp_verify_nonce( $data['_wpnonce'], 'edd-rp-recalculate' ) ) { return; } // Refresh Suggestions edd_rp_generate_stats(); add_action( 'admin_notices', 'edd_rp_recalc_notice' ); } add_action( 'edd_refresh_edd_rp', 'refresh_edd_rp' ); function edd_rp_recalc_notice() { printf( '<div class="updated settings-error"> <p> %s </p> </div>', esc_html__( 'Recommendations Updated.', 'edd-rp-txt' ) ); }
Java
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest06598") public class BenchmarkTest06598 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheValue("foo"); java.util.List<String> valuesList = new java.util.ArrayList<String>( ); valuesList.add("safe"); valuesList.add( param ); valuesList.add( "moresafe" ); valuesList.remove(0); // remove the 1st safe value String bar = valuesList.get(0); // get the param value try { java.util.Properties Benchmarkprops = new java.util.Properties(); Benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("Benchmark.properties")); String algorithm = Benchmarkprops.getProperty("cryptoAlg2", "AES/ECB/PKCS5Padding"); javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(algorithm); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case"); throw new ServletException(e); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case"); throw new ServletException(e); } response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed"); } }
Java
define(function(require) { var Model = require("web/common/model"); var SpsrModel = Model.extend({ idAttribute: "recordId", defaults: { name: "SDI1", kzck: 0, ydsd: 0, srjkxh: 0, ld: 123, dbd: 124, bhd: 125, sppy: 126, czpy: 127 }, urls: { "create": "spsr.psp", "update": "spsr.psp", "delete": "spsr.psp", "read": "spsr.psp" } }); return SpsrModel; });
Java
/** * Copyright (c) 2008-2012 Indivica Inc. * * This software is made available under the terms of the * GNU General Public License, Version 2, 1991 (GPLv2). * License details are available via "indivica.ca/gplv2" * and "gnu.org/licenses/gpl-2.0.html". */ package org.oscarehr.document.web; import java.io.File; import java.io.FileInputStream; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.pdfbox.pdfparser.PDFParser; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.oscarehr.common.dao.CtlDocumentDao; import org.oscarehr.common.dao.DocumentDao; import org.oscarehr.common.dao.PatientLabRoutingDao; import org.oscarehr.common.dao.ProviderInboxRoutingDao; import org.oscarehr.common.dao.ProviderLabRoutingDao; import org.oscarehr.common.dao.QueueDocumentLinkDao; import org.oscarehr.common.model.CtlDocument; import org.oscarehr.common.model.CtlDocumentPK; import org.oscarehr.common.model.Document; import org.oscarehr.common.model.PatientLabRouting; import org.oscarehr.common.model.ProviderInboxItem; import org.oscarehr.common.model.ProviderLabRoutingModel; import org.oscarehr.util.LoggedInInfo; import org.oscarehr.util.SpringUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import oscar.dms.EDoc; import oscar.dms.EDocUtil; import oscar.oscarLab.ca.all.upload.ProviderLabRouting; public class SplitDocumentAction extends DispatchAction { private DocumentDao documentDao = SpringUtils.getBean(DocumentDao.class); public ActionForward split(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String docNum = request.getParameter("document"); String[] commands = request.getParameterValues("page[]"); Document doc = documentDao.getDocument(docNum); String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); new File(docdownload); String newFilename = doc.getDocfilename(); FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); PDFParser parser = new PDFParser(input); parser.parse(); PDDocument pdf = parser.getPDDocument(); PDDocument newPdf = new PDDocument(); List pages = pdf.getDocumentCatalog().getAllPages(); if (commands != null) { for (String c : commands) { String[] command = c.split(","); int pageNum = Integer.parseInt(command[0]); int rotation = Integer.parseInt(command[1]); PDPage p = (PDPage)pages.get(pageNum-1); p.setRotation(rotation); newPdf.addPage(p); } } //newPdf.save(docdownload + newFilename); if (newPdf.getNumberOfPages() > 0) { LoggedInInfo loggedInInfo=LoggedInInfo.loggedInInfo.get(); EDoc newDoc = new EDoc("","", newFilename, "", loggedInInfo.loggedInProvider.getProviderNo(), doc.getDoccreator(), "", 'A', oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1",0); newDoc.setDocPublic("0"); newDoc.setContentType("application/pdf"); newDoc.setNumberOfPages(newPdf.getNumberOfPages()); String newDocNo = EDocUtil.addDocumentSQL(newDoc); newPdf.save(docdownload + newDoc.getFileName()); newPdf.close(); WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext()); ProviderInboxRoutingDao providerInboxRoutingDao = (ProviderInboxRoutingDao) ctx.getBean("providerInboxRoutingDAO"); providerInboxRoutingDao.addToProviderInbox("0", Integer.parseInt(newDocNo), "DOC"); List<ProviderInboxItem> routeList = providerInboxRoutingDao.getProvidersWithRoutingForDocument("DOC", Integer.parseInt(docNum)); for (ProviderInboxItem i : routeList) { providerInboxRoutingDao.addToProviderInbox(i.getProviderNo(), Integer.parseInt(newDocNo), "DOC"); } providerInboxRoutingDao.addToProviderInbox(loggedInInfo.loggedInProvider.getProviderNo(), Integer.parseInt(newDocNo), "DOC"); QueueDocumentLinkDao queueDocumentLinkDAO = (QueueDocumentLinkDao) ctx.getBean("queueDocumentLinkDAO"); Integer qid = 1; Integer did= Integer.parseInt(newDocNo.trim()); queueDocumentLinkDAO.addToQueueDocumentLink(qid,did); ProviderLabRoutingDao providerLabRoutingDao = (ProviderLabRoutingDao) SpringUtils.getBean("providerLabRoutingDao"); List<ProviderLabRoutingModel> result = providerLabRoutingDao.getProviderLabRoutingDocuments(Integer.parseInt(docNum)); if (!result.isEmpty()) { new ProviderLabRouting().route(newDocNo, result.get(0).getProviderNo(),"DOC"); } PatientLabRoutingDao patientLabRoutingDao = (PatientLabRoutingDao) SpringUtils.getBean("patientLabRoutingDao"); List<PatientLabRouting> result2 = patientLabRoutingDao.findDocByDemographic(Integer.parseInt(docNum)); if (!result2.isEmpty()) { PatientLabRouting newPatientRoute = new PatientLabRouting(); newPatientRoute.setDemographicNo(result2.get(0).getDemographicNo()); newPatientRoute.setLabNo(Integer.parseInt(newDocNo)); newPatientRoute.setLabType("DOC"); patientLabRoutingDao.persist(newPatientRoute); } CtlDocumentDao ctlDocumentDao = SpringUtils.getBean(CtlDocumentDao.class); CtlDocument result3 = ctlDocumentDao.getCtrlDocument(Integer.parseInt(docNum)); if (result3!=null) { CtlDocumentPK ctlDocumentPK = new CtlDocumentPK(Integer.parseInt(newDocNo), "demographic"); CtlDocument newCtlDocument = new CtlDocument(); newCtlDocument.setId(ctlDocumentPK); newCtlDocument.getId().setModuleId(result3.getId().getModuleId()); newCtlDocument.setStatus(result3.getStatus()); documentDao.persist(newCtlDocument); } } pdf.close(); input.close(); return mapping.findForward("success"); } public ActionForward rotate180(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document doc = documentDao.getDocument(request.getParameter("document")); String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); PDFParser parser = new PDFParser(input); parser.parse(); PDDocument pdf = parser.getPDDocument(); int x = 1; for (Object p : pdf.getDocumentCatalog().getAllPages()) { PDPage pg = (PDPage)p; Integer r = (pg.getRotation() != null ? pg.getRotation() : 0); pg.setRotation((r+180)%360); ManageDocumentAction.deleteCacheVersion(doc, x); x++; } pdf.save(docdownload + doc.getDocfilename()); pdf.close(); input.close(); return null; } public ActionForward rotate90(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document doc = documentDao.getDocument(request.getParameter("document")); String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); PDFParser parser = new PDFParser(input); parser.parse(); PDDocument pdf = parser.getPDDocument(); int x = 1; for (Object p : pdf.getDocumentCatalog().getAllPages()) { PDPage pg = (PDPage)p; Integer r = (pg.getRotation() != null ? pg.getRotation() : 0); pg.setRotation((r+90)%360); ManageDocumentAction.deleteCacheVersion(doc, x); x++; } pdf.save(docdownload + doc.getDocfilename()); pdf.close(); input.close(); return null; } public ActionForward removeFirstPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document doc = documentDao.getDocument(request.getParameter("document")); String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR"); FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename()); PDFParser parser = new PDFParser(input); parser.parse(); PDDocument pdf = parser.getPDDocument(); // Documents must have at least 2 pages, for the first page to be removed. if (pdf.getNumberOfPages() <= 1) { return null; } int x = 1; for (Object p : pdf.getDocumentCatalog().getAllPages()) { ManageDocumentAction.deleteCacheVersion(doc, x); x++; } pdf.removePage(0); EDocUtil.subtractOnePage(request.getParameter("document")); pdf.save(docdownload + doc.getDocfilename()); pdf.close(); input.close(); return null; } }
Java
<?php if (!defined('TFUSE')) exit('Direct access forbidden.'); /** * Class UPDATER. Check for new versions of the theme, framework, or modules. Installs if found. */ class TF_UPDATER extends TF_TFUSE { public $_the_class_name = 'UPDATER'; public $themefuse_update = false; public $check_url; #http://themefuse.com/update-themes/ public function __construct() { parent::__construct(); //$this->check_url = 'http://' . $_SERVER['HTTP_HOST'] . '/wp-updater/'; $this->check_url = 'http://themefuse.com/update-themes/'; } public function __init() { $this->themefuse_update = $this->themefuse_update_check(); if (get_option(TF_THEME_PREFIX . '_disable_updates') != 1) { add_action('admin_menu', array($this, 'updates_item_menu_page'), 20); if ($this->themefuse_update) { add_action('admin_notices', array($this, 'themefuse_update_nag')); } } } function updates_item_menu_page() { if (!empty($this->themefuse_update->response[TF_THEME_PREFIX])) $count = count($this->themefuse_update->response[TF_THEME_PREFIX]); $title = !empty($count) ? __('Updates', 'tfuse') . '<span class="update-plugins count-' . $count . '"><span class="update-count">' . number_format_i18n($count) . '</span></span>' : __('Updates', 'tfuse'); add_submenu_page('themefuse', __('Updates', 'tfuse'), $title, 'manage_options', 'tfupdates', array($this, 'themefuse_update_page')); } /** * This function pings an http://themefuse.com/ asking if a new * version of this theme is available. If not, it returns FALSE. * If so, the external server passes serialized data back to this * function, which gets unserialized and returned for use. * * @since 2.0 */ function themefuse_update_check() { if (!current_user_can('update_themes')) return false; if (!$this->request->empty_GET('action') && $this->request->GET('action') == 'checkagain') { delete_site_transient('themefuse-update'); wp_redirect(self_admin_url('admin.php?page=tfupdates')); } $themefuse_update = get_site_transient('themefuse-update'); if (!$themefuse_update) { $url = $this->check_url; $options = array( 'body' => $this->update_params() ); $request = wp_remote_post($url, $options); $response = wp_remote_retrieve_body($request); $themefuse_update = new stdClass(); $themefuse_update->last_checked = time(); // If an error occurred, return FALSE, store for 1 hour if ($response == 'error' || is_wp_error($response) || !is_serialized($response)) { $themefuse_update->response[TF_THEME_PREFIX]['Framework']['new_version'] = $this->theme->framework_version; $themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']['new_version'] = $this->theme->mods_version; $themefuse_update->response[TF_THEME_PREFIX]['Templates']['new_version'] = $this->theme->theme_version; set_site_transient('themefuse-update', $themefuse_update, 60 * 60); // store for 1 hour return false; } // Else, unserialize $themefuse_update->response[TF_THEME_PREFIX] = maybe_unserialize($response); // And store in transient set_site_transient('themefuse-update', $themefuse_update, 60 * 60 * 24); // store for 24 hours } if (!(@$themefuse_update->response[TF_THEME_PREFIX])) { // If response is empty return false; } else if (!empty($themefuse_update->response[TF_THEME_PREFIX]['suspended'])) { // Verify if updates for this theme are not suspended from themefuse return false; } else if ( version_compare( $this->theme->framework_version, (!empty($themefuse_update->response[TF_THEME_PREFIX]['Framework']) ? @$themefuse_update->response[TF_THEME_PREFIX]['Framework']['new_version'] : '0' ), '>=' ) && version_compare( $this->theme->mods_version, (!empty($themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']) ? @$themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']['new_version'] : '0' ), '>=' ) && version_compare( $this->theme->theme_version, (!empty($themefuse_update->response[TF_THEME_PREFIX]['Templates']) ? @$themefuse_update->response[TF_THEME_PREFIX]['Templates']['new_version'] : '0' ), '>=' ) ) { // If we're already using the latest version, return FALSE return false; } return $themefuse_update; } function update_params() { global $wp_version, $wpdb; $params = array( 'theme_name' => $this->theme->theme_name, 'prefix' => $this->theme->prefix, 'framework_version' => $this->theme->framework_version, 'mods_version' => $this->theme->mods_version, 'theme_version' => $this->theme->theme_version, 'wp_version' => $wp_version, 'php_version' => phpversion(), 'mysql_version' => $wpdb->db_version(), 'uri' => home_url(), 'locale' => get_locale(), 'is_multi' => is_multisite(), 'is_child' => is_child_theme() ); return apply_filters('tf_update_param', $params); } /** * This function displays the update nag at the top of the * dashboard if there is an ThemeFuse update available. * * @since 2.0 */ function themefuse_update_nag() { global $upgrading; if (!$this->request->empty_GET('page') && $this->request->GET('page') == 'tfupdates') return; echo apply_filters('tf_update_nag_notice', $this->load->view('updater/update_nag', NULL, true) ); } function themefuse_update_page() { if ('tf-do-upgrade' == $this->theme->action || 'tf-do-reinstall' == $this->theme->action || ($this->request->isset_POST('upgrade') && $this->request->POST('upgrade') == __('Proceed', 'tfuse'))) { check_admin_referer('themefuse-bulk-update'); $updates = !empty($this->themefuse_update->response[TF_THEME_PREFIX]) ? array_keys($this->themefuse_update->response[TF_THEME_PREFIX]) : array(); $updates = array_map('urldecode', $updates); $this->load->view('updater/update_page'); if ($this->request->isset_POST('connection_type') && $this->request->POST('connection_type') == 'ftp') { $filesystem = WP_Filesystem($this->request->POST()); } $this->do_core_upgrade($updates); } else { $this->themefuse_upgrade_preamble(); } } function themefuse_upgrade_preamble() { $updates = get_site_transient('themefuse-update'); $data = array( 'updates' => $updates ); if (isset($this->themefuse_update->response)) $data['response'] = $this->themefuse_update->response; $this->load->view('updater/upgrade_preamble', $data); } public function do_core_upgrade($updates) { $this->load->helper('UPGRADER'); $updates = array_map('urldecode', $updates); $url = 'admin.php?page=tfupdates&amp;updates=' . urlencode(implode(',', $updates)); $nonce = 'themefuse-bulk-update'; //wp_enqueue_script('jquery'); //iframe_header(); $upgrader = new TF_Theme_Upgrader(new TF_Bulk_Theme_Upgrader_Skin(compact('nonce', 'url'))); $upgrader->bulk_upgrade($updates); //iframe_footer(); } }
Java
from sys import argv script, input_file = argv def print_all(f): print f.read() def rewind(f): f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
Java
<?php session_start(); $_SESSION["Status"]=0; include("dbconn.php"); require ('../xajax.inc.php'); include("../dbinfo.inc.php"); $memid=$_SESSION['userId']; $_SESSION["userid"]=$memid; function viewuseralbums($userid,$jumpto) {//list all the albums owned by the user $objResponse = new xajaxResponse(); // how many rows to show per page $rowsPerPage = 5; // if $jumpto defined, use it as page number if($jumpto!="") $pageNum = $jumpto; else // by default show first page $pageNum = 1; $start = ($pageNum -1) * $rowsPerPage; // enter query and display stuff $query = "select * from album, ownalbum where album.AlbumId =ownalbum.AlbumId and ownalbum.OwnerId ='$userid' limit $start, $rowsPerPage"; $result=mysql_query($query)or die(mysql_error()); $count =mysql_numrows($result); $msg; if($count==0) {$msg= "No Records founds"; $objResponse->addAssign("mytable","innerHTML",$msg); } else{ //create a table to display album pictures now $msg.="<table class=\"table-wrapper\">";//echo $msg.="<tr>";//end of echo for($S=0;$S<$count;$S++) { $albumid =mysql_result($result,$S,"album.AlbumId"); $albumname= mysql_result($result,$S,"album.AlbumName"); //now display the album pic //1st get the image path of the pic // call a function Getpath2 $path = Getpath2($albumid); // now display the album //3 by 2 $msg.="<td>"; $msg.="<table class=\"table-shadows\" > <tr> <td class=\"td-shadows-main\"> <a href=\"javascript:void(null);\"onclick = \"xajax_createAlbumView($albumid,''); \" >";//end of echo //GetImage path $msg.="<IMG SRC=\"".$path."\"width=150 height=160> </a> </td > <td class=\"td-shadows-right\"></td> </tr> <tr> <td class=\"td-shadows-bottom\"></td> <td class=\"td-shadows-bottomright\"> </td> </tr> <tr><td width = 50 class =\"mytext_account\">$albumname</td></tr> </table><!--end of table shadows--> </td>";//end of echo //if no if col = 5 then new row if(($S %5 )==0 &&($S+1)!==1 ) $msg.="</tr><tr>"; }//for $msg.="</tr><table>"; //############## End of display stuff // how many rows we have in database $query="select COUNT(*) AS numrows from album, ownalbum where album.AlbumId =ownalbum.AlbumId and ownalbum.OwnerId ='$userid'"; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_array($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); //#################################### // creating 'previous' and 'next' link if ($pageNum > 1) { $page = $pageNum -1; $prev="<input type=\"button\" name=\"prev\" onclick =\"xajax_viewuseralbums($userid,$page);\" value=\"Prev\">"; $first = "<input type=\"button\" name=\"first\" onclick =\"xajax_viewuseralbums($userid,1);\" value=\"First\">"; } else { $prev = ' '; // we're on page one, don't enable 'previous' link $first = ' '; // nor 'first page' link } // print 'next' link only if we're not // on the last page if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = "<input type=\"button\" name=\"next\"onclick=\"xajax_viewuseralbums($userid,$page);\"value=\"Next\">"; $last = "<input type=\"button\" name=\"Last\"onclick=\"xajax_viewuseralbums($userid,$maxPage);\"value=\"Last\">"; } else { $next = ' '; // we're on the last page, don't enable 'next' link $last = ' '; // nor 'last page' link } // print the page navigation link $msg.="<div class =\"mytext_account\">"; $msg.=$first . $prev . " Page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last; $msg.="</div>"; $objResponse->addAssign("mytable","innerHTML",$msg); //$objResponse->addAssign("but","innerHTML",$but); }//else return $objResponse->getXML(); }//end of function function Getpath2($albumid) { $query="SELECT images.Url FROM images,albumcontainsimages where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=$albumid"; $result=mysql_query($query); $num=mysql_numrows($result); //check $msg; if($num==0) $msg= "No Records founds"; else { $Url=mysql_result($result,$num-1,"images.Url"); $msg="../Images/".$Url; }//else return $msg; }//end of function function createAlbumView($albumid,$jumpto) { $objResponse = new xajaxResponse(); // how many rows to show per page $rowsPerPage = 15; // if $jumpto defined, use it as page number if($jumpto!="") $pageNum = $jumpto; else // by default show first page $pageNum = 1; $start = ($pageNum -1) * $rowsPerPage; // enter query and display stuff $query="select * from images ,albumcontainsimages,album where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=album.AlbumId and album.AlbumId =$albumid limit $start, $rowsPerPage"; $result=mysql_query($query); $num=mysql_numrows($result); $msg; if($num==0) {$msg= "No Records founds"; $objResponse->addAssign("mytable","innerHTML",$msg); } else { //display Album Name $AlbumName= mysql_result($result,0,'album.AlbumName'); //display Creation Date $Date = mysql_result($result,0,'album.CreationDate'); //display description of album $des= mysql_result($result,0,'album.Description'); //display no of times viewed //call function GetViewed($albumid) //create a table to display album details first $msg="<table ><tr >";//end of echo $msg.= "<td class =\"td-thumbnails-navi\">Album Name :$AlbumName</td></tr>"; $msg.= "<tr><td class =\"td-thumbnails-navi\">Created on :$Date</td></tr>"; $msg.= "<tr><td class =\"td-thumbnails-navi\">Description :$des</td></tr>"; $msg.= "</table>"; //create a table to display album pictures now $msg.="<table class=\"table-wrapper\">";//echo $msg.="<tr>";//end of echo for($S=0;$S<$num;$S++) { //get path of image $path="../Images/"; $path .= mysql_result($result,$S,"images.Url"); //get des of image $imgdescription= mysql_result($result,$S,"images.Description"); //get dateuploaded of image $dateUploaded=mysql_result($result,$S,"images.DateUploaded"); //get name of image $ImgName=mysql_result($result,$S,"images.ImageName"); //get datecreated of image $imageId=mysql_result($result,$S,"images.ImageId"); $msg.="<td> "; $msg.="<table class=\"table-shadows\" > <tr> <td class=\"td-shadows-main\"> <a href=\"ImageZoom.php?ImgId=$imageId\" >";//end of echo //GetImage path $msg.="<IMG SRC=\"".$path."\"width=150 height=160 align=bottom alt=$ImgName> </a> </td> <td class=\"td-shadows-right\"></td> </tr> <tr> <td class=\"td-shadows-bottom\"></td> <td class=\"td-shadows-bottomright\"> </td> </tr> </table><!--end of table shadows--> </td>";//end of echo //if no if col = 5 then new row if(($S %4 )==0 &&($S+1)!==1 ) $msg.="</tr><tr>"; }//for $msg.="</tr><table>"; //############## End of display stuff // how many rows we have in database $query="select COUNT(*) AS numrows from images ,albumcontainsimages,album where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=album.AlbumId and album.AlbumId =$albumid "; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_array($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); //#################################### // creating 'previous' and 'next' link if ($pageNum > 1) { $page = $pageNum -1; $prev="<input type=\"button\" name=\"prev\" onclick =\"xajax_createAlbumView($albumid,$page);\" value=\"Prev\">"; $first = "<input type=\"button\" name=\"first\" onclick =\"xajax_createAlbumView($albumid,1);\" value=\"First\">"; } else { $prev = ' '; // we're on page one, don't enable 'previous' link $first = ' '; // nor 'first page' link } // print 'next' link only if we're not // on the last page if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = "<input type=\"button\" name=\"next\"onclick=\"xajax_createAlbumView($albumid,$page);\"value=\"Next\">"; $last = "<input type=\"button\" name=\"Last\"onclick=\"xajax_createAlbumView($albumid,$maxPage);\"value=\"Last\">"; } else { $next = ' '; // we're on the last page, don't enable 'next' link $last = ' '; // nor 'last page' link } // print the page navigation link $msg.=$first . $prev . " Page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last; $objResponse->addAssign("mytable","innerHTML",$msg); //$objResponse->addAssign("but","innerHTML",$but); }//else return $objResponse->getXML(); }//end of function //////////////////////////////// $xajax = new xajax(); $xajax->registerFunction("viewuseralbums"); $xajax->registerFunction("createAlbumView"); $xajax->processRequests(); ?> <html><head><?php $xajax->printJavascript("../"); ?><title>Select Album</title> <link href="../css/style.css" type="text/css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="../icons/spgm_style.css" /> </head><body onload = "xajax_viewuseralbums(<?php echo $memid ; ?>,'');"> <!--Start of footer table--> <table id="wapper" border=0> <tr> <td id="topleft">&nbsp;</td> <td id="top">&nbsp;</td> <td id="topright">&nbsp;</td> </tr> <tr><td id="left"></td> <td id="logocenter"> <p><span id="title">&nbsp;Select Album</span></p> <div id = "mytable"></div> </td> <td id="right">&nbsp;</td> </tr> <tr> <td id="bottomleft">&nbsp;</td> <td id="bottom">&nbsp;</td> <td id="bottomright">&nbsp;</td> </tr> </table> <!--End of footer table--> <br> <?php ?> </body> </html>
Java
all: 484.out %.out: %.R R --no-save < $< > $@ clean: -rm *.out *.pdf *.png *~ *swp view: -open *.png
Java
package edu.ucsd.ncmir.WIB.client.core.components; import com.google.gwt.user.client.ui.Widget; import edu.ucsd.ncmir.WIB.client.core.message.Message; import edu.ucsd.ncmir.WIB.client.core.message.MessageListener; import edu.ucsd.ncmir.WIB.client.core.message.MessageManager; import edu.ucsd.ncmir.WIB.client.core.messages.ResetMessage; /** * HorizontalSlider bar. * @author spl */ public class HorizontalSlider extends SliderHorizontal implements HorizontalSliderInterface, MessageListener, SliderValueUpdateHandler { private final Message _message; /** * Creates a <code>HorizontalSlider</code> object. */ public HorizontalSlider( Message message ) { super( "150px" ); this._message = message; super.addSliderValueUpdateHandler( this ); MessageManager.registerListener( ResetMessage.class, this ); } private int _min_value = 0; private int _max_value = 1; private int _default_value = 0; @Override public final void setSliderParameters( int min_value, int max_value, int default_value ) { this._min_value = min_value; this._max_value = max_value; this._default_value = default_value; this.setMaxValue( this._max_value - this._min_value ); this.setSliderValue( default_value ); super.setMinMarkStep( 1 ); } @Override public void setWidth( String size ) { this._transmit_value = false; double value = super.getValue(); super.setWidth( size ); super.setValue( value ); this._transmit_value = true; } private boolean _transmit_value = true; /** * Updates the value of the slider without firing the handler. * @param value The value to be set. */ @Override public void setSliderValueOnly( int value ) { // Turn off the handler. this._transmit_value = false; this.setSliderValue( value ); this._transmit_value = true; } @Override public void setSliderValue( double value ) { super.setValue( value - this._min_value ); } @Override public void action( Message m, Object o ) { this.setSliderValue( this._default_value ); } private boolean _initial = true; // To prevent premature Message firing. /** * Fired when the bar value changes. * @param event The <code>BarValueChangedEvent</code>. */ @Override public void onBarValueChanged( SliderValueUpdateEvent event ) { if ( this._transmit_value && !this._initial ) this.updateHandler( event.getValue() + this._min_value ); // Turn off the initial flag. The SliderBar object fires a // spurious BarValueChangedEvent when the object is loaded. // This prevents it being propagated. this._initial = false; } @Override public void updateHandler( double value ) { this._message.send( value ); } @Override public Widget widget() { return this; } @Override public double getSliderValue() { return this.getValue(); } }
Java
# datasciencecoursera This repository is created as a part of the data science class
Java
# The absolute path of the main script(p4_tools.rb) ROOT = File.expand_path('..', File.dirname(__FILE__)) # The absolute path of the folder which contains the command files COMMANDS_ROOT = ROOT + '/commands' # The absolute path of the folder which contains the custom command files CUSTOM_COMMANDS_ROOT = COMMANDS_ROOT + '/custom' # The absolute path of the folder which contains the configuration files CONFIG_ROOT = ROOT + '/config' # Array of command names, read from the COMMAND_ROOT folder SUB_COMMANDS = Dir[COMMANDS_ROOT + '/*.rb'].collect { |file| File.basename(file, '.rb') } $LOAD_PATH.unshift(CUSTOM_COMMANDS_ROOT, COMMANDS_ROOT)
Java
-- Thalorien Dawnseeker's Remains SET @ENTRY := 37552; UPDATE `creature_template` SET `faction`=1770 WHERE `entry`=@ENTRY; -- Phase DELETE FROM `spell_area` WHERE `spell`=70193; INSERT INTO `spell_area` (`spell`, `area`, `quest_start`, `quest_end`, `aura_spell`, `racemask`, `gender`, `autocast`, `quest_start_status`, `quest_end_status`) VALUES ('70193', '4075', '24535', '0', '0', '0', '2', '1', '8', '11'), ('70193', '4075', '24563', '0', '0', '0', '2', '1', '8', '11'); SET @CGUID := 600009; DELETE FROM `creature` WHERE `guid`=@CGUID;
Java
# Lesson-1---Review ### Create a song class #### Attributes: 1. Title 2. Band members: a dictionary with name as the key and instrument as the values. 3. (Highest) place on the charts. #### Methods: 1. __init__ Has a filepointer as an optional parameter. If filepointer is None have the user input the attributes. If the filepointer is not None input the song from the file. 2. __str__ Output the attributes in a nice way 3. save Save a song to a file, the filepointer should be a parameter. ### Create an album class #### Attributes: 1. Title 2. Year 3. Producer 4. Songs - a list of songs each of which are of type class song. #### Methods: 1. __init__ Has a filepointer as an optional parameter. If filepointer is None have the user input the attributes. If the filepointer is not None input the album from the file. In both cases, when you input a song make sure to use the songs method for input. The song attribute should be an optional parameter. If the value is None keep inputting songs until the user is done. 2. __str__ Output the attributes of the album in a nice way. 3. save saves the entire album to a file, makes use of the song.save attribute for the songs. The filepointer is a parameter. ### Create a menu #### Options: 1. Input a new album 2. Print albums 3. Quit When your program is opened it should read in the albums into a list of albums from the file, and when the user quits it should write the albums in the list to a file. Option 1 should add a new album to the album list.
Java
<?php include 'init.php'; $output = ''; $setup = new ON_Settings(); $setup->load(); $setup->registerForm('setup'); // fill form with elements $setup->fillForm(); // process forms if posted if ($setup->form->isSubmitted() && $setup->form->validate()) { $values =& $setup->form->exportValues(); $setup->setValues($values); if($setup->globalid > 0) { $res = $setup->update(); if ($res) { ON_Say::add(fmtSuccess(_('Settings updated successfuly'))); $defaults = $setup->defaults(); $setup->form->resetDefaults($defaults); } else { ON_Say::add(fmtError(_('Database error: settings update failed'))); } } else { $res = $setup->insert(); if ($res) { ON_Say::add(fmtSuccess(_('Settings inserted successfuly'))); } else { ON_Say::add(fmtError(_('Database error: settings insert failed'))); } } } $output .= $setup->form->toHtml(); include 'theme.php'; ?>
Java
# Find Python # ~~~~~~~~~~~ # Find the Python interpreter and related Python directories. # # This file defines the following variables: # # PYTHON_EXECUTABLE - The path and filename of the Python interpreter. # # PYTHON_SHORT_VERSION - The version of the Python interpreter found, # excluding the patch version number. (e.g. 2.5 and not 2.5.1)) # # PYTHON_LONG_VERSION - The version of the Python interpreter found as a human # readable string. # # PYTHON_SITE_PACKAGES_DIR - Location of the Python site-packages directory. # # PYTHON_INCLUDE_PATH - Directory holding the python.h include file. # # PYTHON_LIBRARY, PYTHON_LIBRARIES- Location of the Python library. # Copyright (c) 2007, Simon Edwards <simon@simonzone.com> # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. INCLUDE(CMakeFindFrameworks) if(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${PYTHON_SITE_PACKAGES_DIR}") # Already in cache, be silent set(PYTHONLIBRARY_FOUND TRUE) else(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${PYTHON_SITE_PACKAGES_DIR}") set(_custom_python_fw FALSE) if(APPLE AND PYTHON_CUSTOM_FRAMEWORK) if("${PYTHON_CUSTOM_FRAMEWORK}" MATCHES "Python\\.framework") STRING(REGEX REPLACE "(.*Python\\.framework).*$" "\\1" _python_fw "${PYTHON_CUSTOM_FRAMEWORK}") set(PYTHON_EXECUTABLE "${_python_fw}/Versions/Current/bin/python") set(PYTHON_INCLUDE_PATH "${_python_fw}/Versions/Current/Headers") set(PYTHON_LIBRARY "${_python_fw}/Versions/Current/Python") if(EXISTS "${PYTHON_EXECUTABLE}" AND EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}") set(_custom_python_fw TRUE) endif() endif("${PYTHON_CUSTOM_FRAMEWORK}" MATCHES "Python\\.framework") endif(APPLE AND PYTHON_CUSTOM_FRAMEWORK) IF (ENABLE_QT5) FIND_PACKAGE(PythonInterp 3) ADD_DEFINITIONS(-DPYTHON3) ELSE (ENABLE_QT5) FIND_PACKAGE(PythonInterp 2) ADD_DEFINITIONS(-DPYTHON2) ENDIF (ENABLE_QT5) if(PYTHONINTERP_FOUND) FIND_FILE(_find_lib_python_py FindLibPython.py PATHS ${CMAKE_MODULE_PATH}) EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${_find_lib_python_py} OUTPUT_VARIABLE python_config) if(python_config) STRING(REGEX REPLACE ".*exec_prefix:([^\n]+).*$" "\\1" PYTHON_PREFIX ${python_config}) STRING(REGEX REPLACE ".*\nshort_version:([^\n]+).*$" "\\1" PYTHON_SHORT_VERSION ${python_config}) STRING(REGEX REPLACE ".*\nlong_version:([^\n]+).*$" "\\1" PYTHON_LONG_VERSION ${python_config}) STRING(REGEX REPLACE ".*\npy_inc_dir:([^\n]+).*$" "\\1" PYTHON_INCLUDE_PATH ${python_config}) if(NOT PYTHON_SITE_PACKAGES_DIR) if(NOT PYTHON_LIBS_WITH_KDE_LIBS) STRING(REGEX REPLACE ".*\nsite_packages_dir:([^\n]+).*$" "\\1" PYTHON_SITE_PACKAGES_DIR ${python_config}) else(NOT PYTHON_LIBS_WITH_KDE_LIBS) set(PYTHON_SITE_PACKAGES_DIR ${KDE4_LIB_INSTALL_DIR}/python${PYTHON_SHORT_VERSION}/site-packages) endif(NOT PYTHON_LIBS_WITH_KDE_LIBS) endif(NOT PYTHON_SITE_PACKAGES_DIR) STRING(REGEX REPLACE "([0-9]+).([0-9]+)" "\\1\\2" PYTHON_SHORT_VERSION_NO_DOT ${PYTHON_SHORT_VERSION}) set(PYTHON_LIBRARY_NAMES python${PYTHON_SHORT_VERSION} python${PYTHON_SHORT_VERSION_NO_DOT} python${PYTHON_SHORT_VERSION}m python${PYTHON_SHORT_VERSION_NO_DOT}m) if(WIN32) STRING(REPLACE "\\" "/" PYTHON_SITE_PACKAGES_DIR ${PYTHON_SITE_PACKAGES_DIR}) endif(WIN32) FIND_LIBRARY(PYTHON_LIBRARY NAMES ${PYTHON_LIBRARY_NAMES}) set(PYTHON_INCLUDE_PATH ${PYTHON_INCLUDE_PATH} CACHE FILEPATH "Directory holding the python.h include file" FORCE) set(PYTHONLIBRARY_FOUND TRUE) endif(python_config) # adapted from cmake's builtin FindPythonLibs if(APPLE AND NOT _custom_python_fw) CMAKE_FIND_FRAMEWORKS(Python) set(PYTHON_FRAMEWORK_INCLUDES) if(Python_FRAMEWORKS) # If a framework has been selected for the include path, # make sure "-framework" is used to link it. if("${PYTHON_INCLUDE_PATH}" MATCHES "Python\\.framework") set(PYTHON_LIBRARY "") set(PYTHON_DEBUG_LIBRARY "") endif("${PYTHON_INCLUDE_PATH}" MATCHES "Python\\.framework") if(NOT PYTHON_LIBRARY) set (PYTHON_LIBRARY "-framework Python" CACHE FILEPATH "Python Framework" FORCE) endif(NOT PYTHON_LIBRARY) set(PYTHONLIBRARY_FOUND TRUE) endif(Python_FRAMEWORKS) endif(APPLE AND NOT _custom_python_fw) endif(PYTHONINTERP_FOUND) if(PYTHONLIBRARY_FOUND) if(APPLE) # keep reference to system or custom python site-packages # useful during app-bundling operations set(PYTHON_SITE_PACKAGES_SYS ${PYTHON_SITE_PACKAGES_DIR}) endif(APPLE) set(PYTHON_LIBRARIES ${PYTHON_LIBRARY}) if(NOT PYTHONLIBRARY_FIND_QUIETLY) message(STATUS "Found Python executable: ${PYTHON_EXECUTABLE}") message(STATUS "Found Python version: ${PYTHON_LONG_VERSION}") message(STATUS "Found Python library: ${PYTHON_LIBRARY}") endif(NOT PYTHONLIBRARY_FIND_QUIETLY) else(PYTHONLIBRARY_FOUND) if(PYTHONLIBRARY_FIND_REQUIRED) message(FATAL_ERROR "Could not find Python") endif(PYTHONLIBRARY_FIND_REQUIRED) endif(PYTHONLIBRARY_FOUND) endif (EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${PYTHON_SITE_PACKAGES_DIR}")
Java
/* linux/drivers/mmc/host/sdhci-s3c.c * * Copyright 2008 Openmoko Inc. * Copyright 2008 Simtec Electronics * Ben Dooks <ben@simtec.co.uk> * http://armlinux.simtec.co.uk/ * * SDHCI (HSMMC) support for Samsung SoC * * 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 <mach/regs-clock.h> #include <linux/delay.h> #include <linux/dma-mapping.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/mmc/host.h> #include <plat/sdhci.h> #include <plat/regs-sdhci.h> #include <plat/clock.h> #include <plat/clock-clksrc.h> #include <linux/kernel.h> #include "sdhci.h" #define MAX_BUS_CLK (1) void mmc_valid(u16 valid, struct mmc_host *host); /* add by cym 20130328 */ #if CONFIG_MTK_COMBO_MT66XX /* skip do suspend for mmc2 host. But it would fail because clock is stopped * but NOT restored automatically after resume. */ #define MMC2_SKIP_SUSPEND (0) /* Enable the following pm capabilities for mmc2 host for wlan suspend/resume: * MMC_PM_KEEP_POWER * MMC_PM_WAKE_SDIO_IRQ * MMC_PM_IGNORE_PM_NOTIFY * It works on mldk4x12. */ #define MMC2_DO_SUSPEND_KEEP_PWR (1) #endif /* end add */ /** * struct sdhci_s3c - S3C SDHCI instance * @host: The SDHCI host created * @pdev: The platform device we where created from. * @ioarea: The resource created when we claimed the IO area. * @pdata: The platform data for this controller. * @cur_clk: The index of the current bus clock. * @clk_io: The clock for the internal bus interface. * @clk_bus: The clocks that are available for the SD/MMC bus clock. */ struct sdhci_s3c { struct sdhci_host *host; struct platform_device *pdev; struct resource *ioarea; struct s3c_sdhci_platdata *pdata; unsigned int cur_clk; int ext_cd_irq; int ext_cd_gpio; struct clk *clk_io; struct clk *clk_bus[MAX_BUS_CLK]; }; static inline struct sdhci_s3c *to_s3c(struct sdhci_host *host) { return sdhci_priv(host); } /** * get_curclk - convert ctrl2 register to clock source number * @ctrl2: Control2 register value. */ static u32 get_curclk(u32 ctrl2) { ctrl2 &= S3C_SDHCI_CTRL2_SELBASECLK_MASK; ctrl2 >>= S3C_SDHCI_CTRL2_SELBASECLK_SHIFT; return ctrl2; } static void sdhci_s3c_check_sclk(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); u32 tmp = readl(host->ioaddr + S3C_SDHCI_CONTROL2); if (get_curclk(tmp) != ourhost->cur_clk) { dev_dbg(&ourhost->pdev->dev, "restored ctrl2 clock setting\n"); tmp &= ~S3C_SDHCI_CTRL2_SELBASECLK_MASK; tmp |= ourhost->cur_clk << S3C_SDHCI_CTRL2_SELBASECLK_SHIFT; writel(tmp, host->ioaddr + 0x80); } } /** * sdhci_s3c_get_max_clk - callback to get maximum clock frequency. * @host: The SDHCI host instance. * * Callback to return the maximum clock rate acheivable by the controller. */ static unsigned int sdhci_s3c_get_max_clk(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); struct clk *busclk; unsigned int rate, max; int clk; /* note, a reset will reset the clock source */ sdhci_s3c_check_sclk(host); for (max = 0, clk = 0; clk < MAX_BUS_CLK; clk++) { busclk = ourhost->clk_bus[clk]; if (!busclk) continue; rate = clk_get_rate(busclk); if (rate > max) max = rate; } return max; } static inline struct clksrc_clk *to_clksrc(struct clk *clk)//lisw sd { return container_of(clk, struct clksrc_clk, clk); } /** * sdhci_s3c_consider_clock - consider one the bus clocks for current setting * @ourhost: Our SDHCI instance. * @src: The source clock index. * @wanted: The clock frequency wanted. */ static unsigned int sdhci_s3c_consider_clock(struct sdhci_s3c *ourhost, unsigned int src, unsigned int wanted) { unsigned long rate; struct clk *clk_sclk_mmc = ourhost->clk_bus[0];//lisw sd : for different clk source structure struct clksrc_clk *clksrc_parent = to_clksrc(clk_sclk_mmc->parent); struct clk *clksrc = clksrc_parent->sources->sources[src]; int div; if (!clksrc) return UINT_MAX; /* * Clock divider's step is different as 1 from that of host controller * when 'clk_type' is S3C_SDHCI_CLK_DIV_EXTERNAL. */ // if (ourhost->pdata->clk_type) { // rate = clk_round_rate(clksrc, wanted); // return wanted - rate; // } rate = clk_get_rate(clksrc); for (div = 1; div < 256; div++) { if ((rate / div) <= wanted) break; } dev_dbg(&ourhost->pdev->dev, "clk %d: rate %ld, want %d, got %ld\n", src, rate, wanted, rate / div); return (wanted - (rate / div)); } /** * sdhci_s3c_set_clock_src - callback on clock change * @host: The SDHCI host being changed * @clock: The clock rate being requested. * * When the card's clock is going to be changed, look at the new frequency * and find the best clock source to go with it. */ int s3c_setrate_clksrc_two_div(struct clk *clk, unsigned long rate);//lisw sd int clk_set_parent(struct clk *clk, struct clk *parent);//lisw sd static void sdhci_s3c_set_clock_src(struct sdhci_host *host, unsigned int clock) { struct sdhci_s3c *ourhost = to_s3c(host); struct clk *clk_sclk_mmc = ourhost->clk_bus[0];//lisw sd : for different clk source structure struct clksrc_clk *clksrc_parent = to_clksrc(clk_sclk_mmc->parent); unsigned int best = UINT_MAX; unsigned int delta; int best_src = 0; int src; u32 ctrl; /* don't bother if the clock is going off. */ if (clock == 0) return; if(MAX_BUS_CLK==1){ for (src = 6; src < clksrc_parent->sources->nr_sources; src++) {//lisw ms : set 6 as firsrt selection because XXTI 24Mhz is not stable delta = sdhci_s3c_consider_clock(ourhost, src, clock); if (delta < best) { best = delta; best_src = src; } } } else return; //printk("selected source %d, clock %d, delta %d\n", // best_src, clock, best); /* select the new clock source */ if (ourhost->cur_clk != best_src) { struct clk *clk = clksrc_parent->sources->sources[best_src]; /* turn clock off to card before changing clock source */ writew(0, host->ioaddr + SDHCI_CLOCK_CONTROL); ourhost->cur_clk = best_src; host->max_clk = clk_get_rate(clk); // ctrl = readl(host->ioaddr + S3C_SDHCI_CONTROL2); // ctrl &= ~S3C_SDHCI_CTRL2_SELBASECLK_MASK; // ctrl |= best_src << S3C_SDHCI_CTRL2_SELBASECLK_SHIFT; // writel(ctrl, host->ioaddr + S3C_SDHCI_CONTROL2); //***use base clock select funtion in CMU instread in SD host controller***// if (clk_set_parent(clk_sclk_mmc->parent, clk)) printk("Unable to set parent %s of clock %s.\n", clk->name, clksrc_parent->clk.name); clk_sclk_mmc->parent->parent = clk; } // s3c_setrate_clksrc_two_div(clk_sclk_mmc,clock); /* reconfigure the hardware for new clock rate */ { struct mmc_ios ios; ios.clock = clock; if (ourhost->pdata->cfg_card) (ourhost->pdata->cfg_card)(ourhost->pdev, host->ioaddr, &ios, NULL); } } /** * sdhci_s3c_set_clock - callback on clock change * @host: The SDHCI host being changed * @clock: The clock rate being requested. * * When the card's clock is going to be changed, look at the new frequency * and find the best clock source to go with it. */ static void sdhci_s3c_set_clock(struct sdhci_host *host, unsigned int clock) { struct sdhci_s3c *ourhost = to_s3c(host); unsigned int best = UINT_MAX; unsigned int delta; int best_src = 0; int src; u32 ctrl; /* don't bother if the clock is going off. */ if (clock == 0) return; for (src = 0; src < MAX_BUS_CLK; src++) { delta = sdhci_s3c_consider_clock(ourhost, src, clock); if (delta < best) { best = delta; best_src = src; } } dev_dbg(&ourhost->pdev->dev, "selected source %d, clock %d, delta %d\n", best_src, clock, best); /* select the new clock source */ if (ourhost->cur_clk != best_src) { struct clk *clk = ourhost->clk_bus[best_src]; /* turn clock off to card before changing clock source */ writew(0, host->ioaddr + SDHCI_CLOCK_CONTROL); ourhost->cur_clk = best_src; host->max_clk = clk_get_rate(clk); ctrl = readl(host->ioaddr + S3C_SDHCI_CONTROL2); ctrl &= ~S3C_SDHCI_CTRL2_SELBASECLK_MASK; ctrl |= best_src << S3C_SDHCI_CTRL2_SELBASECLK_SHIFT; writel(ctrl, host->ioaddr + S3C_SDHCI_CONTROL2); } /* reconfigure the hardware for new clock rate */ { struct mmc_ios ios; ios.clock = clock; if (ourhost->pdata->cfg_card) (ourhost->pdata->cfg_card)(ourhost->pdev, host->ioaddr, &ios, NULL); } } /** * sdhci_s3c_get_min_clock - callback to get minimal supported clock value * @host: The SDHCI host being queried * * To init mmc host properly a minimal clock value is needed. For high system * bus clock's values the standard formula gives values out of allowed range. * The clock still can be set to lower values, if clock source other then * system bus is selected. */ static unsigned int sdhci_s3c_get_min_clock(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); unsigned int delta, min = UINT_MAX; int src; for (src = 0; src < MAX_BUS_CLK; src++) { delta = sdhci_s3c_consider_clock(ourhost, src, 0); if (delta == UINT_MAX) continue; /* delta is a negative value in this case */ if (-delta < min) min = -delta; } return min; } /* sdhci_cmu_get_max_clk - callback to get maximum clock frequency.*/ static unsigned int sdhci_cmu_get_max_clock(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); host->max_clk = clk_get_rate(to_clksrc(ourhost->clk_bus[0]->parent)->sources->sources[ourhost->cur_clk]); return host->max_clk;//clk_round_rate(ourhost->clk_bus[ourhost->cur_clk], UINT_MAX); } /* sdhci_cmu_get_min_clock - callback to get minimal supported clock value. */ static unsigned int sdhci_cmu_get_min_clock(struct sdhci_host *host) { struct sdhci_s3c *ourhost = to_s3c(host); /* * initial clock can be in the frequency range of * 100KHz-400KHz, so we set it as max value. */ return sdhci_cmu_get_max_clock(host)/((1 << to_clksrc(ourhost->clk_bus[0]->parent)->reg_div.size)*(1 << to_clksrc(ourhost->clk_bus[0])->reg_div.size)); } /* sdhci_cmu_set_clock - callback on clock change.*/ static void sdhci_cmu_set_clock(struct sdhci_host *host, unsigned int clock) { struct sdhci_s3c *ourhost = to_s3c(host); /* don't bother if the clock is going off */ if (clock == 0) return; // sdhci_s3c_set_clock(host, clock); sdhci_s3c_set_clock_src(host, clock); // clk_set_rate(ourhost->clk_bus[ourhost->cur_clk], clock); s3c_setrate_clksrc_two_div(ourhost->clk_bus[0],clock); host->clock = clock; } /** * sdhci_s3c_platform_8bit_width - support 8bit buswidth * @host: The SDHCI host being queried * @width: MMC_BUS_WIDTH_ macro for the bus width being requested * * We have 8-bit width support but is not a v3 controller. * So we add platform_8bit_width() and support 8bit width. */ static int sdhci_s3c_platform_8bit_width(struct sdhci_host *host, int width) { u8 ctrl; ctrl = sdhci_readb(host, SDHCI_HOST_CONTROL); switch (width) { case MMC_BUS_WIDTH_8: ctrl |= SDHCI_CTRL_8BITBUS; ctrl &= ~SDHCI_CTRL_4BITBUS; break; case MMC_BUS_WIDTH_4: ctrl |= SDHCI_CTRL_4BITBUS; ctrl &= ~SDHCI_CTRL_8BITBUS; break; default: break; } sdhci_writeb(host, ctrl, SDHCI_HOST_CONTROL); return 0; } //ly 20111123 int sdhci_s3c_get_cd(struct sdhci_host *mmc)//lisw sd hotplug { int detect; struct sdhci_s3c* sc = sdhci_priv(mmc); if(mmc->mmc->index== 1){ //ch0+1 is emmc ch2 is TF int status = gpio_get_value(sc->pdata->ext_cd_gpio); if (sc->pdata->ext_cd_gpio_invert) status = !status; if (status){ detect = true; }else{ detect = false; } }else{ detect = true; } return detect; } static struct sdhci_ops sdhci_s3c_ops = { .get_max_clock = sdhci_s3c_get_max_clk, .set_clock = sdhci_s3c_set_clock, .get_min_clock = sdhci_s3c_get_min_clock, .platform_8bit_width = sdhci_s3c_platform_8bit_width, .get_cd = sdhci_s3c_get_cd,//ly }; void sdhci_init(struct sdhci_host *host, int soft); static void sdhci_s3c_notify_change(struct platform_device *dev, int state) { struct sdhci_host *host = platform_get_drvdata(dev); unsigned long flags; if (host) { spin_lock_irqsave(&host->lock, flags); if (state) { dev_dbg(&dev->dev, "card inserted.\n"); host->flags &= ~SDHCI_DEVICE_DEAD; host->quirks |= SDHCI_QUIRK_BROKEN_CARD_DETECTION; sdhci_init(host,0);//lisw sd hotplug : for reinitialize host controller each time plugin } else { dev_dbg(&dev->dev, "card removed.\n"); host->flags |= SDHCI_DEVICE_DEAD; host->quirks &= ~SDHCI_QUIRK_BROKEN_CARD_DETECTION; } tasklet_schedule(&host->card_tasklet); spin_unlock_irqrestore(&host->lock, flags); } } static irqreturn_t sdhci_s3c_gpio_card_detect_thread(int irq, void *dev_id) { struct sdhci_s3c *sc = dev_id; int status = gpio_get_value(sc->pdata->ext_cd_gpio); if (sc->pdata->ext_cd_gpio_invert) status = !status; if(status){//card present mmc_valid(1,sc->host->mmc);//lisw sd hotplug } else{//card absent mmc_valid(0,sc->host->mmc); } sdhci_s3c_notify_change(sc->pdev, status); return IRQ_HANDLED; } void sdhci_s3c_sdio_card_detect(struct platform_device *pdev) { struct sdhci_host *host = platform_get_drvdata(pdev); //printk(KERN_DEBUG "+%s", __FUNCTION__); printk("+%s\n", __FUNCTION__); // mmc_detect_change(host->mmc, msecs_to_jiffies(60)); mmc_detect_change(host->mmc, msecs_to_jiffies(500)); //printk(KERN_DEBUG "-%s", __FUNCTION__); printk("-%s\n", __FUNCTION__); } EXPORT_SYMBOL(sdhci_s3c_sdio_card_detect); static void sdhci_s3c_setup_card_detect_gpio(struct sdhci_s3c *sc) { struct s3c_sdhci_platdata *pdata = sc->pdata; struct device *dev = &sc->pdev->dev; if (gpio_request(pdata->ext_cd_gpio, "SDHCI EXT CD") == 0) { sc->ext_cd_gpio = pdata->ext_cd_gpio; sc->ext_cd_irq = gpio_to_irq(pdata->ext_cd_gpio); enable_irq_wake(sc->ext_cd_irq);//lisw hotplug during suspend if (sc->ext_cd_irq && request_threaded_irq(sc->ext_cd_irq, NULL, sdhci_s3c_gpio_card_detect_thread, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, dev_name(dev), sc) == 0) { int status = gpio_get_value(sc->ext_cd_gpio); if (pdata->ext_cd_gpio_invert) status = !status; sdhci_s3c_notify_change(sc->pdev, status); } else { dev_warn(dev, "cannot request irq for card detect\n"); sc->ext_cd_irq = 0; } } else { dev_err(dev, "cannot request gpio for card detect\n"); } } static int __devinit sdhci_s3c_probe(struct platform_device *pdev) { struct s3c_sdhci_platdata *pdata = pdev->dev.platform_data; struct device *dev = &pdev->dev; struct sdhci_host *host; struct sdhci_s3c *sc; struct resource *res; int ret, irq, ptr, clks; if (!pdata) { dev_err(dev, "no device data specified\n"); return -ENOENT; } irq = platform_get_irq(pdev, 0); if (irq < 0) { dev_err(dev, "no irq specified\n"); return irq; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(dev, "no memory specified\n"); return -ENOENT; } host = sdhci_alloc_host(dev, sizeof(struct sdhci_s3c)); if (IS_ERR(host)) { dev_err(dev, "sdhci_alloc_host() failed\n"); return PTR_ERR(host); } sc = sdhci_priv(host); sc->host = host; sc->pdev = pdev; sc->pdata = pdata; sc->ext_cd_gpio = -1; /* invalid gpio number */ platform_set_drvdata(pdev, host); sc->clk_io = clk_get(dev, "hsmmc"); if (IS_ERR(sc->clk_io)) { dev_err(dev, "failed to get io clock\n"); ret = PTR_ERR(sc->clk_io); goto err_io_clk; } /* enable the local io clock and keep it running for the moment. */ clk_enable(sc->clk_io); for (clks = 0, ptr = 0; ptr < MAX_BUS_CLK; ptr++) { struct clk *clk; char *name = pdata->clocks[ptr]; if (name == NULL) continue; clk = clk_get(dev, name); if (IS_ERR(clk)) { dev_err(dev, "failed to get clock %s\n", name); continue; } clks++; sc->clk_bus[ptr] = clk; /* * save current clock index to know which clock bus * is used later in overriding functions. */ sc->cur_clk = 7;// clock sources select number clk_set_parent(clk->parent,to_clksrc(clk->parent)->sources->sources[7]); clk_enable(clk); dev_info(dev, "clock source %d: %s (%ld Hz)\n", ptr, name, clk_get_rate(clk)); } if (clks == 0) { dev_err(dev, "failed to find any bus clocks\n"); ret = -ENOENT; goto err_no_busclks; } sc->ioarea = request_mem_region(res->start, resource_size(res), mmc_hostname(host->mmc)); if (!sc->ioarea) { dev_err(dev, "failed to reserve register area\n"); ret = -ENXIO; goto err_req_regs; } host->ioaddr = ioremap_nocache(res->start, resource_size(res)); if (!host->ioaddr) { dev_err(dev, "failed to map registers\n"); ret = -ENXIO; goto err_req_regs; } /* Ensure we have minimal gpio selected CMD/CLK/Detect */ if (pdata->cfg_gpio) pdata->cfg_gpio(pdev, pdata->max_width); host->hw_name = "samsung-hsmmc"; host->ops = &sdhci_s3c_ops; host->quirks = 0; host->irq = irq; /* Setup quirks for the controller */ host->quirks |= SDHCI_QUIRK_NO_ENDATTR_IN_NOPDESC; host->quirks |= SDHCI_QUIRK_NO_HISPD_BIT; #ifndef CONFIG_MMC_SDHCI_S3C_DMA /* we currently see overruns on errors, so disable the SDMA * support as well. */ host->quirks |= SDHCI_QUIRK_BROKEN_DMA; #endif /* CONFIG_MMC_SDHCI_S3C_DMA */ /* It seems we do not get an DATA transfer complete on non-busy * transfers, not sure if this is a problem with this specific * SDHCI block, or a missing configuration that needs to be set. */ host->quirks |= SDHCI_QUIRK_NO_BUSY_IRQ; /* This host supports the Auto CMD12 */ host->quirks |= SDHCI_QUIRK_MULTIBLOCK_READ_ACMD12; if (pdata->cd_type == S3C_SDHCI_CD_NONE || pdata->cd_type == S3C_SDHCI_CD_PERMANENT) host->quirks |= SDHCI_QUIRK_BROKEN_CARD_DETECTION; if (pdata->cd_type == S3C_SDHCI_CD_PERMANENT) host->mmc->caps = MMC_CAP_NONREMOVABLE; if (pdata->host_caps) host->mmc->caps |= pdata->host_caps; host->quirks |= (SDHCI_QUIRK_32BIT_DMA_ADDR | SDHCI_QUIRK_32BIT_DMA_SIZE); /* HSMMC on Samsung SoCs uses SDCLK as timeout clock */ host->quirks |= SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK; /* * If controller does not have internal clock divider, * we can use overriding functions instead of default. */ if (pdata->clk_type) { sdhci_s3c_ops.set_clock = sdhci_cmu_set_clock; sdhci_s3c_ops.get_min_clock = sdhci_cmu_get_min_clock; sdhci_s3c_ops.get_max_clock = sdhci_cmu_get_max_clock; } /* It supports additional host capabilities if needed */ if (pdata->host_caps) host->mmc->caps |= pdata->host_caps; /* add by cym 20130328 */ #if MMC2_SKIP_SUSPEND if (2 == host->mmc->index) { /* to avoid redundant mmc_detect_change() called by mmc_pm_notify() */ printk(KERN_INFO "%s: set MMC_PM_IGNORE_PM_NOTIFY for %s pm_flags\n", __func__, mmc_hostname(host->mmc)); host->mmc->pm_flags |= MMC_PM_IGNORE_PM_NOTIFY; } #elif MMC2_DO_SUSPEND_KEEP_PWR if (2 == host->mmc->index) { /* to avoid redundant mmc_detect_change() called by mmc_pm_notify() */ printk(KERN_INFO "%s: set MMC_PM_IGNORE_PM_NOTIFY for %s pm_flags\n", __func__, mmc_hostname(host->mmc)); host->mmc->pm_flags |= MMC_PM_IGNORE_PM_NOTIFY; printk(KERN_INFO "%s: set MMC_PM_KEEP_POWER | MMC_PM_WAKE_SDIO_IRQ for %s pm_caps\n", __func__, mmc_hostname(host->mmc)); host->mmc->pm_caps |= MMC_PM_KEEP_POWER | MMC_PM_WAKE_SDIO_IRQ; } #endif /* end add */ ret = sdhci_add_host(host); if (ret) { dev_err(dev, "sdhci_add_host() failed\n"); goto err_add_host; } /* The following two methods of card detection might call sdhci_s3c_notify_change() immediately, so they can be called only after sdhci_add_host(). Setup errors are ignored. */ if (pdata->cd_type == S3C_SDHCI_CD_EXTERNAL && pdata->ext_cd_init) pdata->ext_cd_init(&sdhci_s3c_notify_change); if (pdata->cd_type == S3C_SDHCI_CD_GPIO && gpio_is_valid(pdata->ext_cd_gpio)) sdhci_s3c_setup_card_detect_gpio(sc); return 0; err_add_host: release_resource(sc->ioarea); kfree(sc->ioarea); err_req_regs: for (ptr = 0; ptr < MAX_BUS_CLK; ptr++) { clk_disable(sc->clk_bus[ptr]); clk_put(sc->clk_bus[ptr]); } err_no_busclks: clk_disable(sc->clk_io); clk_put(sc->clk_io); err_io_clk: sdhci_free_host(host); return ret; } static int __devexit sdhci_s3c_remove(struct platform_device *pdev) { struct s3c_sdhci_platdata *pdata = pdev->dev.platform_data; struct sdhci_host *host = platform_get_drvdata(pdev); struct sdhci_s3c *sc = sdhci_priv(host); int ptr; if (pdata->cd_type == S3C_SDHCI_CD_EXTERNAL && pdata->ext_cd_cleanup) pdata->ext_cd_cleanup(&sdhci_s3c_notify_change); if (sc->ext_cd_irq) free_irq(sc->ext_cd_irq, sc); if (gpio_is_valid(sc->ext_cd_gpio)) gpio_free(sc->ext_cd_gpio); sdhci_remove_host(host, 1); for (ptr = 0; ptr < 3; ptr++) { if (sc->clk_bus[ptr]) { clk_disable(sc->clk_bus[ptr]); clk_put(sc->clk_bus[ptr]); } } clk_disable(sc->clk_io); clk_put(sc->clk_io); iounmap(host->ioaddr); release_resource(sc->ioarea); kfree(sc->ioarea); sdhci_free_host(host); platform_set_drvdata(pdev, NULL); return 0; } #ifdef CONFIG_PM static int sdhci_s3c_suspend(struct platform_device *dev, pm_message_t pm) { struct sdhci_host *host = platform_get_drvdata(dev); /* add by cym 20130328 */ #if MMC2_SKIP_SUSPEND /* mmc2 is s3c_device_hsmmc3 */ if (2 == host->mmc->index) { printk(KERN_INFO "skip %s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); return 0; } else { printk(KERN_INFO "%s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); } #endif /* end add */ sdhci_suspend_host(host, pm); return 0; } static int sdhci_s3c_resume(struct platform_device *dev) { struct sdhci_host *host = platform_get_drvdata(dev); struct sdhci_s3c *sc = sdhci_priv(host); /* add by cym 20130328 */ #if MMC2_SKIP_SUSPEND /* mmc2 is s3c_device_hsmmc3 */ if (2 == host->mmc->index) { printk(KERN_INFO "skip %s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); return 0; } else { printk(KERN_INFO "%s for %s dev->id(%d)\n", __func__, mmc_hostname(host->mmc), dev->id); } #endif /* end add */ sdhci_resume_host(host); /* add by cym 20130328 */ #ifndef MMC2_SKIP_SUSPEND /* end add */ if(!(host->mmc->caps & MMC_CAP_NONREMOVABLE)){//lisw hotplug during suspend int status = gpio_get_value(sc->ext_cd_gpio); if (sc->pdata->ext_cd_gpio_invert) status = !status; sdhci_s3c_notify_change(sc->pdev, status); } /* add by cym 20130328 */ #endif /* end add */ return 0; } #else #define sdhci_s3c_suspend NULL #define sdhci_s3c_resume NULL #endif static struct platform_driver sdhci_s3c_driver = { .probe = sdhci_s3c_probe, .remove = __devexit_p(sdhci_s3c_remove), .suspend = sdhci_s3c_suspend, .resume = sdhci_s3c_resume, .driver = { .owner = THIS_MODULE, .name = "s3c-sdhci", }, }; static int __init sdhci_s3c_init(void) { return platform_driver_register(&sdhci_s3c_driver); } static void __exit sdhci_s3c_exit(void) { platform_driver_unregister(&sdhci_s3c_driver); } module_init(sdhci_s3c_init); module_exit(sdhci_s3c_exit); MODULE_DESCRIPTION("Samsung SDHCI (HSMMC) glue"); MODULE_AUTHOR("Ben Dooks, <ben@simtec.co.uk>"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:s3c-sdhci");
Java
/* Copyright (c) 2009-2011, Code Aurora Forum. 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 version 2 and * only 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. * */ /*----------------------------------------------------------------------------*/ // COPYRIGHT(C) FUJITSU LIMITED 2011-2012 /*----------------------------------------------------------------------------*/ #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/hrtimer.h> #include <linux/delay.h> #include <mach/hardware.h> #include <linux/io.h> #include <asm/system.h> #include <asm/mach-types.h> #include <linux/semaphore.h> #include <linux/spinlock.h> #include <linux/fb.h> #include "mdp.h" #include "msm_fb.h" #include "mdp4.h" /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption start */ extern struct mutex msm_fb_ioctl_lut_sem; /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption end */ static struct mdp4_overlay_pipe *mddi_pipe; static struct msm_fb_data_type *mddi_mfd; static int busy_wait_cnt; static int vsync_start_y_adjust = 4; static int dmap_vsync_enable; /* FUJITSU:2011-12-22 add sandstorm blocker --> */ #if defined(CONFIG_FB_MSM_MDDI) extern void mddi_panel_fullscrn_update_notify(void); #endif /* FUJITSU:2011-12-22 add sandstorm blocker <-- */ void mdp_dmap_vsync_set(int enable) { dmap_vsync_enable = enable; } int mdp_dmap_vsync_get(void) { return dmap_vsync_enable; } void mdp4_mddi_vsync_enable(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe, int which) { uint32 start_y, data, tear_en; tear_en = (1 << which); if ((mfd->use_mdp_vsync) && (mfd->ibuf.vsync_enable) && (mfd->panel_info.lcd.vsync_enable)) { if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* need dmas dmap switch */ if (which == 0 && dmap_vsync_enable == 0 && mfd->panel_info.lcd.rev < 2) /* dma_p */ return; } if (vsync_start_y_adjust <= pipe->dst_y) start_y = pipe->dst_y - vsync_start_y_adjust; else start_y = (mfd->total_lcd_lines - 1) - (vsync_start_y_adjust - pipe->dst_y); if (which == 0) MDP_OUTP(MDP_BASE + 0x210, start_y); /* primary */ else MDP_OUTP(MDP_BASE + 0x214, start_y); /* secondary */ data = inpdw(MDP_BASE + 0x20c); data |= tear_en; MDP_OUTP(MDP_BASE + 0x20c, data); } else { data = inpdw(MDP_BASE + 0x20c); data &= ~tear_en; MDP_OUTP(MDP_BASE + 0x20c, data); } } #define WHOLESCREEN void mdp4_overlay_update_lcd(struct msm_fb_data_type *mfd) { MDPIBUF *iBuf = &mfd->ibuf; uint8 *src; int ptype; uint32 mddi_ld_param; uint16 mddi_vdo_packet_reg; struct mdp4_overlay_pipe *pipe; int ret; if (mfd->key != MFD_KEY) return; /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption start */ mutex_lock(&msm_fb_ioctl_lut_sem); /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption end */ mddi_mfd = mfd; /* keep it */ /* FUJITSU:2011-12-22 add sandstorm blocker --> */ #if defined(CONFIG_FB_MSM_MDDI) /* if update RAM image size is full screen size */ if (iBuf->dma_h == mfd->panel_info.yres) { mddi_panel_fullscrn_update_notify(); } #endif /* FUJITSU:2011-12-22 add sandstorm blocker <-- */ /* MDP cmd block enable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); if (mddi_pipe == NULL) { ptype = mdp4_overlay_format2type(mfd->fb_imgType); if (ptype < 0) printk(KERN_INFO "%s: format2type failed\n", __func__); pipe = mdp4_overlay_pipe_alloc(ptype, MDP4_MIXER0); if (pipe == NULL) printk(KERN_INFO "%s: pipe_alloc failed\n", __func__); pipe->pipe_used++; pipe->mixer_num = MDP4_MIXER0; pipe->src_format = mfd->fb_imgType; mdp4_overlay_panel_mode(pipe->mixer_num, MDP4_PANEL_MDDI); ret = mdp4_overlay_format2pipe(pipe); if (ret < 0) printk(KERN_INFO "%s: format2type failed\n", __func__); mddi_pipe = pipe; /* keep it */ mddi_pipe->blt_end = 1; /* mark as end */ mddi_ld_param = 0; mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt; if (mdp_hw_revision == MDP4_REVISION_V2_1) { uint32 data; data = inpdw(MDP_BASE + 0x0028); data &= ~0x0300; /* bit 8, 9, MASTER4 */ if (mfd->fbi->var.xres == 540) /* qHD, 540x960 */ data |= 0x0200; else data |= 0x0100; MDP_OUTP(MDP_BASE + 0x00028, data); } if (mfd->panel_info.type == MDDI_PANEL) { if (mfd->panel_info.pdest == DISPLAY_1) mddi_ld_param = 0; else mddi_ld_param = 1; } else { mddi_ld_param = 2; } MDP_OUTP(MDP_BASE + 0x00090, mddi_ld_param); if (mfd->panel_info.bpp == 24) MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC_24 << 16) | mddi_vdo_packet_reg); else if (mfd->panel_info.bpp == 16) MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC_16 << 16) | mddi_vdo_packet_reg); else MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC << 16) | mddi_vdo_packet_reg); MDP_OUTP(MDP_BASE + 0x00098, 0x01); } else { pipe = mddi_pipe; } /* 0 for dma_p, client_id = 0 */ MDP_OUTP(MDP_BASE + 0x00090, 0); src = (uint8 *) iBuf->buf; #ifdef WHOLESCREEN { struct fb_info *fbi; fbi = mfd->fbi; pipe->src_height = fbi->var.yres; pipe->src_width = fbi->var.xres; pipe->src_h = fbi->var.yres; pipe->src_w = fbi->var.xres; pipe->src_y = 0; pipe->src_x = 0; pipe->dst_h = fbi->var.yres; pipe->dst_w = fbi->var.xres; pipe->dst_y = 0; pipe->dst_x = 0; pipe->srcp0_addr = (uint32)src; pipe->srcp0_ystride = fbi->fix.line_length; } #else if (mdp4_overlay_active(MDP4_MIXER0)) { struct fb_info *fbi; fbi = mfd->fbi; pipe->src_height = fbi->var.yres; pipe->src_width = fbi->var.xres; pipe->src_h = fbi->var.yres; pipe->src_w = fbi->var.xres; pipe->src_y = 0; pipe->src_x = 0; pipe->dst_h = fbi->var.yres; pipe->dst_w = fbi->var.xres; pipe->dst_y = 0; pipe->dst_x = 0; pipe->srcp0_addr = (uint32) src; pipe->srcp0_ystride = fbi->fix.line_length; } else { /* starting input address */ src += (iBuf->dma_x + iBuf->dma_y * iBuf->ibuf_width) * iBuf->bpp; pipe->src_height = iBuf->dma_h; pipe->src_width = iBuf->dma_w; pipe->src_h = iBuf->dma_h; pipe->src_w = iBuf->dma_w; pipe->src_y = 0; pipe->src_x = 0; pipe->dst_h = iBuf->dma_h; pipe->dst_w = iBuf->dma_w; pipe->dst_y = iBuf->dma_y; pipe->dst_x = iBuf->dma_x; pipe->srcp0_addr = (uint32) src; pipe->srcp0_ystride = iBuf->ibuf_width * iBuf->bpp; } #endif pipe->mixer_stage = MDP4_MIXER_STAGE_BASE; mdp4_overlay_rgb_setup(pipe); mdp4_mixer_stage_up(pipe); mdp4_overlayproc_cfg(pipe); mdp4_overlay_dmap_xy(pipe); mdp4_overlay_dmap_cfg(mfd, 0); mdp4_mddi_vsync_enable(mfd, pipe, 0); /* MDP cmd block disable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } int mdp4_mddi_overlay_blt_offset(int *off) { if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* need dmas dmap switch */ if (mddi_pipe->blt_end || (mdp4_overlay_mixer_play(mddi_pipe->mixer_num) == 0)) { *off = -1; return -EINVAL; } } else { /* no dmas dmap switch */ if (mddi_pipe->blt_end) { *off = -1; return -EINVAL; } } if (mddi_pipe->blt_cnt & 0x01) *off = mddi_pipe->src_height * mddi_pipe->src_width * 3; else *off = 0; return 0; } void mdp4_mddi_overlay_blt(ulong addr) { unsigned long flag; spin_lock_irqsave(&mdp_spin_lock, flag); if (addr) { mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp_intr_mask |= INTR_DMA_P_DONE; outp32(MDP_INTR_ENABLE, mdp_intr_mask); mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mddi_pipe->blt_cnt = 0; mddi_pipe->blt_end = 0; mddi_pipe->blt_addr = addr; } else { mddi_pipe->blt_end = 1; /* mark as end */ } spin_unlock_irqrestore(&mdp_spin_lock, flag); } void mdp4_blt_xy_update(struct mdp4_overlay_pipe *pipe) { uint32 off, addr; int bpp; char *overlay_base; if (pipe->blt_addr == 0) return; #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif off = 0; if (pipe->dmap_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; addr = pipe->blt_addr + off; /* dmap */ MDP_OUTP(MDP_BASE + 0x90008, addr); /* overlay 0 */ overlay_base = MDP_BASE + MDP4_OVERLAYPROC0_BASE;/* 0x10000 */ outpdw(overlay_base + 0x000c, addr); outpdw(overlay_base + 0x001c, addr); } /* * mdp4_dmap_done_mddi: called from isr */ void mdp4_dma_p_done_mddi(void) { if (mddi_pipe->blt_end) { mddi_pipe->blt_addr = 0; mdp_intr_mask &= ~INTR_DMA_P_DONE; outp32(MDP_INTR_ENABLE, mdp_intr_mask); mdp4_overlayproc_cfg(mddi_pipe); mdp4_overlay_dmap_xy(mddi_pipe); } /* * single buffer, no need to increase * mdd_pipe->dmap_cnt here */ } /* * mdp4_overlay0_done_mddi: called from isr */ void mdp4_overlay0_done_mddi(struct mdp_dma_data *dma) { mdp_disable_irq_nosync(MDP_OVERLAY0_TERM); dma->busy = FALSE; /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption start */ mutex_unlock(&msm_fb_ioctl_lut_sem); /* FUJITSU:2012-05-29 DISP add prevent set_lut interruption end */ complete(&dma->comp); mdp_pipe_ctrl(MDP_OVERLAY0_BLOCK, MDP_BLOCK_POWER_OFF, TRUE); if (busy_wait_cnt) busy_wait_cnt--; pr_debug("%s: ISR-done\n", __func__); if (mddi_pipe->blt_addr) { if (mddi_pipe->blt_cnt == 0) { mdp4_overlayproc_cfg(mddi_pipe); mdp4_overlay_dmap_xy(mddi_pipe); mddi_pipe->ov_cnt = 0; mddi_pipe->dmap_cnt = 0; /* BLT start from next frame */ } else { mdp_pipe_ctrl(MDP_DMA2_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp4_blt_xy_update(mddi_pipe); outpdw(MDP_BASE + 0x000c, 0x0); /* start DMAP */ } mddi_pipe->blt_cnt++; mddi_pipe->ov_cnt++; } } void mdp4_mddi_overlay_restore(void) { if (mddi_mfd == NULL) return; pr_debug("%s: resotre, pid=%d\n", __func__, current->pid); if (mddi_mfd->panel_power_on == 0) return; if (mddi_mfd && mddi_pipe) { mdp4_mddi_dma_busy_wait(mddi_mfd); mdp4_overlay_update_lcd(mddi_mfd); mdp4_mddi_overlay_kickoff(mddi_mfd, mddi_pipe); mddi_mfd->dma_update_flag = 1; } if (mdp_hw_revision < MDP4_REVISION_V2_1) /* need dmas dmap switch */ mdp4_mddi_overlay_dmas_restore(); } /* * mdp4_mddi_cmd_dma_busy_wait: check mddi link activity * dsi link is a shared resource and it can only be used * while it is in idle state. * ov_mutex need to be acquired before call this function. */ void mdp4_mddi_dma_busy_wait(struct msm_fb_data_type *mfd) { unsigned long flag; int need_wait = 0; pr_debug("%s: START, pid=%d\n", __func__, current->pid); spin_lock_irqsave(&mdp_spin_lock, flag); if (mfd->dma->busy == TRUE) { if (busy_wait_cnt == 0) INIT_COMPLETION(mfd->dma->comp); busy_wait_cnt++; need_wait++; } spin_unlock_irqrestore(&mdp_spin_lock, flag); if (need_wait) { /* wait until DMA finishes the current job */ pr_debug("%s: PENDING, pid=%d\n", __func__, current->pid); wait_for_completion(&mfd->dma->comp); } pr_debug("%s: DONE, pid=%d\n", __func__, current->pid); } void mdp4_mddi_kickoff_video(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { pr_debug("%s: pid=%d\n", __func__, current->pid); mdp4_mddi_overlay_kickoff(mfd, pipe); } void mdp4_mddi_kickoff_ui(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { pr_debug("%s: pid=%d\n", __func__, current->pid); mdp4_mddi_overlay_kickoff(mfd, pipe); } void mdp4_mddi_overlay_kickoff(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { /* change mdp clk while mdp is idle` */ mdp4_set_perf_level(); if (mdp_hw_revision == MDP4_REVISION_V2_1) { if (mdp4_overlay_status_read(MDP4_OVERLAY_TYPE_UNSET)) { uint32 data; data = inpdw(MDP_BASE + 0x0028); data &= ~0x0300; /* bit 8, 9, MASTER4 */ if (mfd->fbi->var.xres == 540) /* qHD, 540x960 */ data |= 0x0200; else data |= 0x0100; MDP_OUTP(MDP_BASE + 0x00028, data); mdp4_overlay_status_write(MDP4_OVERLAY_TYPE_UNSET, false); } if (mdp4_overlay_status_read(MDP4_OVERLAY_TYPE_SET)) { uint32 data; data = inpdw(MDP_BASE + 0x0028); data &= ~0x0300; /* bit 8, 9, MASTER4 */ MDP_OUTP(MDP_BASE + 0x00028, data); mdp4_overlay_status_write(MDP4_OVERLAY_TYPE_SET, false); } } mdp_enable_irq(MDP_OVERLAY0_TERM); mfd->dma->busy = TRUE; /* start OVERLAY pipe */ mdp_pipe_kickoff(MDP_OVERLAY0_TERM, mfd); mdp4_stat.kickoff_ov0++; } void mdp4_dma_s_update_lcd(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { MDPIBUF *iBuf = &mfd->ibuf; uint32 outBpp = iBuf->bpp; uint16 mddi_vdo_packet_reg; uint32 dma_s_cfg_reg; dma_s_cfg_reg = 0; if (mfd->fb_imgType == MDP_RGBA_8888) dma_s_cfg_reg |= DMA_PACK_PATTERN_BGR; /* on purpose */ else if (mfd->fb_imgType == MDP_BGR_565) dma_s_cfg_reg |= DMA_PACK_PATTERN_BGR; else dma_s_cfg_reg |= DMA_PACK_PATTERN_RGB; if (outBpp == 4) dma_s_cfg_reg |= (1 << 26); /* xRGB8888 */ else if (outBpp == 2) dma_s_cfg_reg |= DMA_IBUF_FORMAT_RGB565; dma_s_cfg_reg |= DMA_DITHER_EN; /* MDP cmd block enable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* PIXELSIZE */ MDP_OUTP(MDP_BASE + 0xa0004, (pipe->dst_h << 16 | pipe->dst_w)); MDP_OUTP(MDP_BASE + 0xa0008, pipe->srcp0_addr); /* ibuf address */ MDP_OUTP(MDP_BASE + 0xa000c, pipe->srcp0_ystride);/* ystride */ if (mfd->panel_info.bpp == 24) { dma_s_cfg_reg |= DMA_DSTC0G_8BITS | /* 666 18BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } else if (mfd->panel_info.bpp == 18) { dma_s_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else { dma_s_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } MDP_OUTP(MDP_BASE + 0xa0010, (pipe->dst_y << 16) | pipe->dst_x); /* 1 for dma_s, client_id = 0 */ MDP_OUTP(MDP_BASE + 0x00090, 1); mddi_vdo_packet_reg = mfd->panel_info.mddi.vdopkt; if (mfd->panel_info.bpp == 24) MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC_24 << 16) | mddi_vdo_packet_reg); else if (mfd->panel_info.bpp == 16) MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC_16 << 16) | mddi_vdo_packet_reg); else MDP_OUTP(MDP_BASE + 0x00094, (MDDI_VDO_PACKET_DESC << 16) | mddi_vdo_packet_reg); MDP_OUTP(MDP_BASE + 0x00098, 0x01); MDP_OUTP(MDP_BASE + 0xa0000, dma_s_cfg_reg); mdp4_mddi_vsync_enable(mfd, pipe, 1); /* MDP cmd block disable */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } void mdp4_mddi_dma_s_kickoff(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { /* change mdp clk while mdp is idle` */ mdp4_set_perf_level(); mdp_enable_irq(MDP_DMA_S_TERM); mfd->dma->busy = TRUE; mfd->ibuf_flushed = TRUE; /* start dma_s pipe */ mdp_pipe_kickoff(MDP_DMA_S_TERM, mfd); mdp4_stat.kickoff_dmas++; /* wait until DMA finishes the current job */ wait_for_completion(&mfd->dma->comp); mdp_disable_irq(MDP_DMA_S_TERM); } void mdp4_mddi_overlay_dmas_restore(void) { /* mutex held by caller */ if (mddi_mfd && mddi_pipe) { mdp4_mddi_dma_busy_wait(mddi_mfd); mdp4_dma_s_update_lcd(mddi_mfd, mddi_pipe); mdp4_mddi_dma_s_kickoff(mddi_mfd, mddi_pipe); mddi_mfd->dma_update_flag = 1; } } void mdp4_mddi_overlay(struct msm_fb_data_type *mfd) { mutex_lock(&mfd->dma->ov_mutex); if (mfd && mfd->panel_power_on) { mdp4_mddi_dma_busy_wait(mfd); mdp4_overlay_update_lcd(mfd); if (mdp_hw_revision < MDP4_REVISION_V2_1) { /* dmas dmap switch */ if (mdp4_overlay_mixer_play(mddi_pipe->mixer_num) == 0) { mdp4_dma_s_update_lcd(mfd, mddi_pipe); mdp4_mddi_dma_s_kickoff(mfd, mddi_pipe); } else mdp4_mddi_kickoff_ui(mfd, mddi_pipe); } else /* no dams dmap switch */ mdp4_mddi_kickoff_ui(mfd, mddi_pipe); /* signal if pan function is waiting for the update completion */ if (mfd->pan_waiting) { mfd->pan_waiting = FALSE; complete(&mfd->pan_comp); } } mutex_unlock(&mfd->dma->ov_mutex); } int mdp4_mddi_overlay_cursor(struct fb_info *info, struct fb_cursor *cursor) { struct msm_fb_data_type *mfd = info->par; mutex_lock(&mfd->dma->ov_mutex); if (mfd && mfd->panel_power_on) { mdp4_mddi_dma_busy_wait(mfd); mdp_hw_cursor_update(info, cursor); } mutex_unlock(&mfd->dma->ov_mutex); return 0; }
Java
<?php /** * Template Name: Two Column, Right-Sidebar * * This is the most generic template file in a WordPress theme * and one of the two required files for a theme (the other being style.css). * It is used to display a page when nothing more specific matches a query. * E.g., it puts together the home page when no home.php file exists. * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package joe_neat */ get_header(); ?> <div id="primary" class="content-area"> <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /* Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'page-templates/partials/content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; ?> <?php else : ?> <?php get_template_part( 'partials/content', 'none' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endif; ?> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
Java
package org.nla.tarotdroid.lib.helpers; import static com.google.common.base.Preconditions.checkArgument; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * Network and internet connexion helper class. */ public class ConnexionHelper { /** * Checking for all possible internet providers * **/ public static boolean isConnectedToInternet(Context context) { checkArgument(context != null, "context is null"); boolean toReturn = false; ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { toReturn = true; break; } } return toReturn; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_18) on Tue Nov 02 13:16:53 CET 2010 --> <TITLE> com.redhat.rhn.common.filediff Class Hierarchy </TITLE> <META NAME="date" CONTENT="2010-11-02"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.redhat.rhn.common.filediff Class Hierarchy"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../com/redhat/rhn/common/errors/test/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../com/redhat/rhn/common/filediff/test/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/redhat/rhn/common/filediff/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package com.redhat.rhn.common.filediff </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.Object<UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Diff.html" title="class in com.redhat.rhn.common.filediff"><B>Diff</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Differ.html" title="class in com.redhat.rhn.common.filediff"><B>Differ</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Edit.html" title="class in com.redhat.rhn.common.filediff"><B>Edit</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/FileLines.html" title="class in com.redhat.rhn.common.filediff"><B>FileLines</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Hunk.html" title="class in com.redhat.rhn.common.filediff"><B>Hunk</B></A><UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/ChangeHunk.html" title="class in com.redhat.rhn.common.filediff"><B>ChangeHunk</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DeleteHunk.html" title="class in com.redhat.rhn.common.filediff"><B>DeleteHunk</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/InsertHunk.html" title="class in com.redhat.rhn.common.filediff"><B>InsertHunk</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/MatchHunk.html" title="class in com.redhat.rhn.common.filediff"><B>MatchHunk</B></A></UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/RhnHtmlDiffWriter.html" title="class in com.redhat.rhn.common.filediff"><B>RhnHtmlDiffWriter</B></A> (implements com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffVisitor.html" title="interface in com.redhat.rhn.common.filediff">DiffVisitor</A>, com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffWriter.html" title="interface in com.redhat.rhn.common.filediff">DiffWriter</A>) <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/RhnPatchDiffWriter.html" title="class in com.redhat.rhn.common.filediff"><B>RhnPatchDiffWriter</B></A> (implements com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffVisitor.html" title="interface in com.redhat.rhn.common.filediff">DiffVisitor</A>, com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffWriter.html" title="interface in com.redhat.rhn.common.filediff">DiffWriter</A>) <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/Trace.html" title="class in com.redhat.rhn.common.filediff"><B>Trace</B></A></UL> </UL> <H2> Interface Hierarchy </H2> <UL> <LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffVisitor.html" title="interface in com.redhat.rhn.common.filediff"><B>DiffVisitor</B></A><LI TYPE="circle">com.redhat.rhn.common.filediff.<A HREF="../../../../../com/redhat/rhn/common/filediff/DiffWriter.html" title="interface in com.redhat.rhn.common.filediff"><B>DiffWriter</B></A></UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../com/redhat/rhn/common/errors/test/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../com/redhat/rhn/common/filediff/test/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/redhat/rhn/common/filediff/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
<?php class SatellitePlugin { var $plugin_name; var $plugin_base; var $pre = 'Satellite'; var $debugging = false; var $menus = array(); var $latestorbit = 'jquery.orbit-1.3.1.js'; //var $latestorbit = 'orbit-min.js'; var $cssfile = 'orbit-css.php'; var $cssadmin = 'admin-styles.css'; var $sections = array( 'satellite' => 'satellite-slides', 'settings' => 'satellite', 'newgallery' => 'satellite-galleries', ); var $helpers = array('Ajax', 'Config', 'Db', 'Html', 'Form', 'Metabox', 'Version'); var $models = array('Slide','Gallery'); function register_plugin($name, $base) { $this->plugin_base = rtrim(dirname($base), DS); $this->initialize_classes(); $this->initialize_options(); if (function_exists('load_plugin_textdomain')) { $currentlocale = get_locale(); if (!empty($currentlocale)) { $moFile = dirname(__FILE__) . DS . "languages" . DS . SATL_PLUGIN_NAME . "-" . $currentlocale . ".mo"; if (@file_exists($moFile) && is_readable($moFile)) { load_textdomain(SATL_PLUGIN_NAME, $moFile); } } } if ($this->debugging == true) { global $wpdb; $wpdb->show_errors(); error_reporting(E_ALL); @ini_set('display_errors', 1); } $this->add_action('wp_head', 'enqueue_scripts', 1); $this->add_action('admin_head', 'add_admin_styles'); $this->add_action("admin_head", 'plupload_admin_head'); $this->add_action('admin_init', 'admin_scripts'); $this->add_filter('the_posts', 'conditionally_add_scripts_and_styles'); // the_posts gets triggered before wp_head $this->add_action('wp_ajax_plupload_action', "g_plupload_action"); return true; } function add_admin_styles() { $adminStyleUrl = SATL_PLUGIN_URL . '/css/' . $this -> cssadmin . '?v=' . SATL_VERSION; wp_register_style(SATL_PLUGIN_NAME . "_adstyle", $adminStyleUrl); wp_enqueue_style(SATL_PLUGIN_NAME . "_adstyle"); } function conditionally_add_scripts_and_styles($posts){ if (empty($posts)) return $posts; $shortcode_found = false; // use this flag to see if styles and scripts need to be enqueued if ($this->get_option('shortreq') == 'N') { $shortcode_found = true; } else { foreach ($posts as $post) { if ( ( stripos($post->post_content, '[gpslideshow') !== false ) || ( stripos($post->post_content, '[satellite') !== false) || ( stripos($post->post_content, '[slideshow') !== false && $this->get_option('embedss') == "Y" ) ) { $shortcode_found = true; // bingo! $pID = $post->ID; break; } } } if ($shortcode_found) { $satlStyleFile = SATL_PLUGIN_DIR . '/css/' . $this -> cssfile; $satlStyleUrl = SATL_PLUGIN_URL . '/css/' . $this -> cssfile . '?v=' . SATL_VERSION . '&amp;pID=' . $pID; if ($_SERVER['HTTPS']) { $satlStyleUrl = str_replace("http:", "https:", $satlStyleUrl); } //$infogal = $this; if (file_exists($satlStyleFile)) { if ($styles = $this->get_option('styles')) { foreach ($styles as $skey => $sval) { $satlStyleUrl .= "&amp;" . $skey . "=" . urlencode($sval); } } $width_temp = $this->get_option('width_temp'); $height_temp = $this->get_option('height_temp'); $align_temp = $this->get_option('align_temp'); $nav_temp = $this->get_option('nav_temp'); //print_r($wp_query->current_post); if (is_array($width_temp)) { foreach ($width_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;width_temp=" . urlencode($sval); } } if (is_array($height_temp)) { foreach ($height_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;height_temp=" . urlencode($sval); } } if (is_array($align_temp)) { foreach ($align_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;align=" . urlencode($sval); } } if (is_array($nav_temp)) { foreach ($nav_temp as $skey => $sval) { if ($skey == $pID) $satlStyleUrl .= "&amp;nav=" . urlencode($sval); } } wp_register_style(SATL_PLUGIN_NAME . "_style", $satlStyleUrl); } // enqueue here wp_enqueue_style(SATL_PLUGIN_NAME . "_style"); wp_enqueue_script(SATL_PLUGIN_NAME . "_script", '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/' . $this->latestorbit, array('jquery'), SATL_VERSION); //wp_enqueue_script(SATL_PLUGIN_NAME . "_script"); } return $posts; } function init_class($name = null, $params = array()) { if (!empty($name)) { $name = $this->pre . $name; if (class_exists($name)) { if ($class = new $name($params)) { return $class; } } } $this->init_class('Country'); return false; } function initialize_classes() { if (!empty($this->helpers)) { foreach ($this->helpers as $helper) { $hfile = dirname(__FILE__) . DS . 'helpers' . DS . strtolower($helper) . '.php'; if (file_exists($hfile)) { require_once($hfile); if (empty($this->{$helper}) || !is_object($this->{$helper})) { $classname = $this->pre . $helper . 'Helper'; if (class_exists($classname)) { $this->{$helper} = new $classname; } } } } } if (!empty($this->models)) { foreach ($this->models as $model) { $mfile = dirname(__FILE__) . DS . 'models' . DS . strtolower($model) . '.php'; if (file_exists($mfile)) { require_once($mfile); if (empty($this->{$model}) || !is_object($this->{$model})) { $classname = $this->pre . $model; if (class_exists($classname)) { $this->{$model} = new $classname; } } } } } } function initialize_options() { $styles = array( 'width' => "450", 'height' => "300", 'thumbheight' => "75", 'thumbarea' => "275", 'thumbareamargin' => "30", 'thumbmargin' => "2", 'thumbspacing' => "5", 'thumbactive' => "#FFFFFF", 'thumbopacity' => "70", 'align' => "none", 'border' => "1px solid #CCCCCC", 'background' => "#000000", 'infotitle' => "2", 'infobackground' => "#000000", 'infocolor' => "#FFFFFF", 'playshow' => "A", 'navpush' => "0", 'infomin' => "Y" ); $this->add_option('styles', $styles); //General Settings $this->add_option('fadespeed', 10); $this->add_option('nav_opacity', 30); $this->add_option('navhover', 70); $this->add_option('nolinker', "N"); $this->add_option('nolinkpage', 0); $this->add_option('pagelink', "S"); $this->add_option('wpattach', "N"); $this->add_option('captionlink', "N"); $this->add_option('transition', "FB"); $this->add_option('information', "Y"); $this->add_option('infospeed', 10); $this->add_option('showhover', "P"); $this->add_option('thumbnails', "N"); $this->add_option('thumbposition', "bottom"); $this->add_option('thumbscrollspeed', 5); $this->add_option('autoslide', "Y"); $this->add_option('autoslide_temp', "Y"); $this->add_option('imagesbox', "T"); $this->add_option('autospeed', 10); $this->add_option('abscenter', "Y"); $this->add_option('embedss', "Y"); $this->add_option('satwiz', "Y"); $this->add_option('shortreq', "Y"); $this->add_option('ggljquery', "Y"); $this->add_option('splash', "N"); $this->add_option('stldb_version', "1.0"); // Orbit Only $this->add_option('autospeed2', 5000); $this->add_option('duration', 700); $this->add_option('othumbs', "B"); $this->add_option('bullcenter', "true"); //Multi-ImageSlide $this->add_option('multicols', 3); $this->add_option('dropshadow', 'N'); //Full Right / Left $this->add_option('thumbarea', 250); //Premium $this->add_option('custslide', 10); $this->add_option('preload', 'N'); $this->add_option('keyboard', 'N'); $this->add_option('manager', 'manage_options'); $this->add_option('nav', "on"); //$this->add_option('orbitinfo', 'Y'); //$this->add_option('orbitinfo_temp', 'Y'); } function render_msg($message = '') { $this->render('msg-top', array('message' => $message), true, 'admin'); } function render_err($message = '') { $this->render('err-top', array('message' => $message), true, 'admin'); } function redirect($location = '', $msgtype = '', $message = '') { $url = $location; if ($msgtype == "message") { $url .= '&' . $this->pre . 'updated=true'; } elseif ($msgtype == "error") { $url .= '&' . $this->pre . 'error=true'; } if (!empty($message)) { $url .= '&' . $this->pre . 'message=' . urlencode($message); } ?> <script type="text/javascript"> window.location = '<?php echo (empty($url)) ? get_option('home') : $url; ?>'; </script> <?php flush(); } function paginate($model = null, $fields = '*', $sub = null, $conditions = null, $searchterm = null, $per_page = 10, $order = array('modified', "DESC")) { global $wpdb; if (!empty($model)) { global $paginate; $paginate = $this->vendor('Paginate'); $paginate->table = $this->{$model}->table; $paginate->sub = (empty($sub)) ? $this->{$model}->controller : $sub; $paginate->fields = (empty($fields)) ? '*' : $fields; $paginate->where = (empty($conditions)) ? false : $conditions; $paginate->searchterm = (empty($searchterm)) ? false : $searchterm; $paginate->per_page = $per_page; $paginate->order = $order; $data = $paginate->start_paging($_GET[$this->pre . 'page']); if (!empty($data)) { $newdata = array(); foreach ($data as $record) { $newdata[] = $this->init_class($model, $record); } $data = array(); $data[$model] = $newdata; $data['Paginate'] = $paginate; } return $data; } return false; } function vendor($name = '', $folder = '') { if (!empty($name)) { $filename = 'class.' . strtolower($name) . '.php'; $filepath = rtrim(dirname(__FILE__), DS) . DS . 'vendors' . DS . $folder . ''; $filefull = $filepath . $filename; if (file_exists($filefull)) { require_once($filefull); $class = 'Satellite' . $name; if (${$name} = new $class) { return ${$name}; } } } return false; } function check_uploaddir() { if (!file_exists(SATL_UPLOAD_DIR)) { if (@mkdir(SATL_UPLOAD_DIR, 0777)) { @chmod(SATL_UPLOAD_DIR, 0755); return true; } else { $message = __('Uploads folder named "' . SATL_PLUGIN_NAME . '" cannot be created inside "' . SATL_UPLOAD_DIR, SATL_PLUGIN_NAME); $this->render_msg($message); } } return false; } function check_sgprodir() { $sgprodir = SATL_UPLOAD_DIR.'/../slideshow-gallery-pro/'; if (file_exists($sgprodir) && $this->is_empty_folder(SATL_UPLOAD_DIR)) { if ($this->is_empty_folder($sgprodir)) { return false; } $message = __('Transitioning from <strong>Slideshow Gallery Pro</strong>? <a href="admin.php?page=satellite-slides&method=copysgpro">Copy Files</a> from your previous custom galleries', SATL_PLUGIN_NAME); $this->render_msg($message); } return false; } function is_empty_folder($folder){ $c=0; if(is_dir($folder) ){ $files = opendir($folder); while ($file=readdir($files)){$c++;} if ($c>2){ return false; }else{ return true; } } } function add_action($action, $function = null, $priority = 10, $params = 1) { if (add_action($action, array($this, (empty($function)) ? $action : $function), $priority, $params)) { return true; } return false; } function add_filter($filter, $function = null, $priority = 10, $params = 1) { if (add_filter($filter, array($this, (empty($function)) ? $filter : $function), $priority, $params)) { return true; } return false; } function admin_scripts() { if (!empty($_GET['page']) && in_array($_GET['page'], (array) $this->sections)) { wp_enqueue_script('autosave'); if ($_GET['page'] == 'satellite') { wp_enqueue_script('common'); wp_enqueue_script('wp-lists'); wp_enqueue_script('postbox'); wp_enqueue_script('settings-editor', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/settings-editor.js', array('jquery'), SATL_VERSION); wp_enqueue_script('admin', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/admin.js', array('jquery'), SATL_VERSION); } if ($_GET['page'] == "satellite-slides" && $_GET['method'] == "order") { wp_enqueue_script('jquery-ui-sortable'); } if ($_GET['page'] == "satellite-galleries") { wp_enqueue_script('plupload-all'); wp_enqueue_script('jquery-ui-sortable'); wp_enqueue_script('admin', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/admin.js', array('jquery'), SATL_VERSION); } wp_enqueue_scripts(); //wp_enqueue_script('jquery-ui-sortable'); add_thickbox(); } } function enqueue_scripts() { if ($this->get_option('ggljquery') == "Y") { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'); } wp_enqueue_script('jquery'); if (SATL_PRO && ($this->get_option('preload') == 'Y')) { wp_register_script('satellite_preloader', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/pro/preloader.js'); wp_enqueue_script('satellite_preloader'); } if ($this->get_option('imagesbox') == "T") add_thickbox(); return true; } function plupload_admin_head() { //Thank you Krishna!! http://www.krishnakantsharma.com/ // place js config array for plupload $plupload_init = array( 'runtimes' => 'html5,silverlight,flash,html4', 'browse_button' => 'plupload-browse-button', // will be adjusted per uploader 'container' => 'plupload-upload-ui', // will be adjusted per uploader 'drop_element' => 'drag-drop-area', // will be adjusted per uploader 'file_data_name' => 'async-upload', // will be adjusted per uploader 'multiple_queues' => true, 'max_file_size' => wp_max_upload_size() . 'b', 'url' => admin_url('admin-ajax.php'), 'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'), 'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'), 'filters' => array(array('title' => __('Allowed Files'), 'extensions' => '*')), 'multipart' => true, 'urlstream_upload' => true, 'multi_selection' => false, // will be added per uploader // additional post data to send to our ajax hook 'multipart_params' => array( '_ajax_nonce' => "", // will be added per uploader 'action' => 'plupload_action', // the ajax action name 'imgid' => 0 // will be added per uploader ) ); ?> <script type="text/javascript"> var base_plupload_config=<?php echo json_encode($plupload_init); ?>; </script> <?php } function g_plupload_action() { // check ajax noonce $imgid = $_POST["imgid"]; check_ajax_referer($imgid . 'pluploadan'); // handle file upload $status = wp_handle_upload($_FILES[$imgid . 'async-upload'], array('test_form' => true, 'action' => 'plupload_action')); // send the uploaded file url in response echo $status['url']; exit; } function plugin_base() { return rtrim(dirname(__FILE__), '/'); } function url() { return rtrim(WP_PLUGIN_URL, '/') . '/' . substr(preg_replace("/\\" . DS . "/si", "/", $this->plugin_base()), strlen(ABSPATH)); } function add_option($name = '', $value = '') { if (add_option($this->pre . $name, $value)) { return true; } return false; } function update_option($name = '', $value = '') { if (update_option($this->pre . $name, $value)) { return true; } return false; } function get_option($name = '', $stripslashes = true) { if ($option = get_option($this->pre . $name)) { if (@unserialize($option) !== false) { return unserialize($option); } if ($stripslashes == true) { $option = stripslashes_deep($option); } return $option; } return false; } function debug($var = array()) { if ($this->debugging) { echo '<pre>' . print_r($var, true) . '</pre>'; return true; } return false; } function check_table( $model = null ) { global $wpdb; if ( !empty($model) ) { if ( !empty($this->fields) && is_array($this->fields ) ) { if ( /* !$wpdb->get_var("SHOW TABLES LIKE '" . $this->table . "'") ||*/ $this->get_option($model.'db_version') != SATL_VERSION ) { $query = "CREATE TABLE " . $this->table . " (\n"; $c = 1; foreach ( $this->fields as $field => $attributes ) { if ( $field != "key" ) { $query .= "`" . $field . "` " . $attributes . ""; //$query .= "`".$field . "` " . $attributes ; } else { $query .= "" . $attributes . ""; } if ($c < count($this->fields)) { $query .= ",\n"; } $c++; } $query .= ");"; if (!empty($query)) { $this->table_query[] = $query; } if (SATL_PRO) { if ( class_exists( 'SatellitePremium' ) ) { $satlprem = new SatellitePremium; $satlprem->check_pro_dirs(); } } if (!empty($this->table_query)) { require_once(ABSPATH . 'wp-admin'.DS.'includes'.DS.'upgrade.php'); dbDelta($this->table_query, true); $this -> update_option($model.'db_version', SATL_VERSION); $this -> update_option('stldb_version', SATL_VERSION); error_log("Updated slideshow satellite databases"); } } else { //echo "this model db version: ".$this->get_option($model.'db_version'); $field_array = $this->get_fields($this->table); foreach ($this->fields as $field => $attributes) { if ($field != "key") { $this->add_field($this->table, $field, $attributes); } } } } } return false; } function get_fields($table = null) { global $wpdb; if (!empty($table)) { $fullname = $table; if (($tablefields = mysql_list_fields(DB_NAME, $fullname, $wpdb->dbh)) !== false) { $columns = mysql_num_fields($tablefields); $field_array = array(); for ($i = 0; $i < $columns; $i++) { $fieldname = mysql_field_name($tablefields, $i); $field_array[] = $fieldname; } return $field_array; } } return false; } function delete_field($table = '', $field = '') { global $wpdb; if (!empty($table)) { if (!empty($field)) { $query = "ALTER TABLE `" . $wpdb->prefix . "" . $table . "` DROP `" . $field . "`"; if ($wpdb->query($query)) { return false; } } } return false; } function change_field($table = '', $field = '', $newfield = '', $attributes = "TEXT NOT NULL") { global $wpdb; if (!empty($table)) { if (!empty($field)) { if (!empty($newfield)) { $field_array = $this->get_fields($table); if (!in_array($field, $field_array)) { if ($this->add_field($table, $newfield)) { return true; } } else { $query = "ALTER TABLE `" . $table . "` CHANGE `" . $field . "` `" . $newfield . "` " . $attributes . ";"; if ($wpdb->query($query)) { return true; } } } } } return false; } function add_field($table = '', $field = '', $attributes = "TEXT NOT NULL") { global $wpdb; if (!empty($table)) { if (!empty($field)) { $field_array = $this->get_fields($table); if (!empty($field_array)) { if (!in_array($field, $field_array)) { $query = "ALTER TABLE `" . $table . "` ADD `" . $field . "` " . $attributes . ";"; if ($wpdb->query($query)) { return true; } } } } } return false; } function render($file = '', $params = array(), $output = true, $folder = 'admin') { if (!empty($file)) { $filename = $file . '.php'; $filepath = $this->plugin_base() . DS . 'views' . DS . $folder . DS; $filefull = $filepath . $filename; if (file_exists($filefull)) { if (!empty($params)) { foreach ($params as $pkey => $pval) { ${$pkey} = $pval; } } if ($output == false) { ob_start(); } include($filefull); if ($output == false) { $data = ob_get_clean(); return $data; } else { flush(); return true; } } } return false; } /** * Add Settings link to plugins - code from GD Star Ratings */ function add_satl_settings_link($links, $file) { static $this_plugin; if (!$this_plugin) $this_plugin = plugin_basename(__FILE__); if ($file == $this_plugin) { $settings_link = '<a href="admin.php?page=satellite">' . __("Settings", SATL_PLUGIN_NAME) . '</a>'; array_unshift($links, $settings_link); } return $links; } } ?>
Java
# -*- coding: UTF-8 -*- #/* # * Copyright (C) 2011 Ivo Brhel # * # * # * This Program is free software; you can redistribute it and/or modify # * it under the terms of the GNU General Public License as published by # * the Free Software Foundation; either version 2, or (at your option) # * any later version. # * # * This Program is distributed in the hope that it will be useful, # * but WITHOUT ANY WARRANTY; without even the implied warranty of # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # * GNU General Public License for more details. # * # * You should have received a copy of the GNU General Public License # * along with this program; see the file COPYING. If not, write to # * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # * http://www.gnu.org/copyleft/gpl.html # * # */ import re,os,urllib,urllib2,cookielib import util,resolver from provider import ContentProvider class HejbejseContentProvider(ContentProvider): def __init__(self,username=None,password=None,filter=None): ContentProvider.__init__(self,'hejbejse.tv','http://www.kynychova-tv.cz/',username,password,filter) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.LWPCookieJar())) urllib2.install_opener(opener) def capabilities(self): return ['resolve','categories','list'] def categories(self): page = util.parse_html('http://www.kynychova-tv.cz/index.php?id=5') result = [] for title,uri in [(x.h3.text,x.h3.a['href']) for x in page.select('div.entry5') if x.h3]: item = self.dir_item() item['title'] = title item['url'] = uri result.append(item) return result def list(self, url): url = self._url(url) page = util.parse_html(url) result = [] for title,uri in [(x.img['title'],x['href']) for x in page.select('div.entry3')[0].findAll('a')]: item = self.video_item() item['title'] = title item['url'] = uri result.append(item) return result def resolve(self,item,captcha_cb=None,select_cb=None): item = item.copy() url = self._url(item['url']) page = util.parse_html(url) result = [] data=str(page.select('div.entry3 > center')[0]) resolved = resolver.findstreams(data,['<iframe(.+?)src=[\"\'](?P<url>.+?)[\'\"]']) try: for i in resolved: item = self.video_item() item['title'] = i['name'] item['url'] = i['url'] item['quality'] = i['quality'] item['surl'] = i['surl'] result.append(item) except: print '===Unknown resolver===' if len(result)==1: return result[0] elif len(result) > 1 and select_cb: return select_cb(result)
Java
# Wider Gravity Forms Stop Entries ## Download the latest release of this plugin from: https://wordpress.org/plugins/wider-gravity-forms-stop-entries/ or install from your WordPress Dashboard by searching for 'Wider Gravity Forms Stop Entires'. ### Selectively stop Gravity Forms entries being stored on your web server to comply with privacy and the GDPR. Gravity Forms is a wonderful plugin and each form submission is stored on your web server and is accessible through the admin area - which can be great if you have problems with the email address you have setup to receive form submissions. However, there is no easy way in the admin area to selectively stop entries being stored on your web server, it has to be done in code and is a bit of hassle - this plugin makes it easy to stop this potentially sensitive data being stored. Improve the privacy of your visitors form submissions and make your website comply with the GDPR - this plugin allows you to select individual Gravity Forms you have setup and stop these entries being stored through easy to use admin options. You will find the options under `Settings > Gravity Forms Stop Entries`. NOTE: Requires Gravity Forms v1.8 or newer!
Java
<?php /** * Template Name: Full Width Blog * * The template for displaying content in full width with no sidebars. * * * @package blogBox WordPress Theme * @copyright Copyright (c) 2012, Kevin Archibald * @license http://www.gnu.org/licenses/quick-guide-gplv3.html GNU Public License * @author Kevin Archibald <www.kevinsspace.ca/contact/> */ ?> <?php get_header(); ?> <div id="fullwidth"> <h2 class="fullwidth_blog_title"><?php the_title(); ?></h2> <div id="home1post"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post"> <div class="entry"> <?php the_content('Read more'); ?> </div> </div> <?php endwhile; else : endif; ?> </div> <div id="fullwidth_blog"> <?php $exclude_categories = blogBox_exclude_categories(); $temp = $wp_query; $wp_query = null; $wp_query = new WP_Query(); $wp_query->query('cat='.$exclude_categories.'&paged='.$paged); if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php global $more; $more = 0; blogBox_post_format(); ?> </div> <?php endwhile; ?> <?php if(function_exists('wp_pagenavi')) { echo '<div class="postpagenav">'; wp_pagenavi(); echo '</div>'; } else { ?> <div class="postpagenav"> <div class="left"><?php next_posts_link(__('&lt;&lt; older entries','blogBox') ); ?></div> <div class="right"><?php previous_posts_link(__(' newer entries &gt;&gt;','blogBox') ); ?></div> <br/> </div> <?php } ?> <?php $wp_query = null; $wp_query = $temp;?> <?php else : ?> <?php endif; ?> <br/> </div> </div> <?php get_footer(); ?>
Java
<?php /** * The template for displaying 404 pages (not found) * * @link https://codex.wordpress.org/Creating_an_Error_404_Page * * @package wapp */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <section class="error-404 not-found"> <header class="page-header"> <h1 class="page-title"><?php esc_html_e( 'Oops! That page can&rsquo;t be found.', 'wapp' ); ?></h1> </header><!-- .page-header --> <div class="page-content"> <p><?php esc_html_e( 'It looks like nothing was found at this location. Maybe try one of the links below or a search?', 'wapp' ); ?></p> <?php get_search_form(); the_widget( 'WP_Widget_Recent_Posts' ); // Only show the widget if site has multiple categories. if ( wapp_categorized_blog() ) : ?> <div class="widget widget_categories"> <h2 class="widget-title"><?php esc_html_e( 'Most Used Categories', 'wapp' ); ?></h2> <ul> <?php wp_list_categories( array( 'orderby' => 'count', 'order' => 'DESC', 'show_count' => 1, 'title_li' => '', 'number' => 10, ) ); ?> </ul> </div><!-- .widget --> <?php endif; /* translators: %1$s: smiley */ $archive_content = '<p>' . sprintf( esc_html__( 'Try looking in the monthly archives. %1$s', 'wapp' ), convert_smilies( ':)' ) ) . '</p>'; the_widget( 'WP_Widget_Archives', 'dropdown=1', "after_title=</h2>$archive_content" ); the_widget( 'WP_Widget_Tag_Cloud' ); ?> </div><!-- .page-content --> </section><!-- .error-404 --> </main><!-- #main --> </div><!-- #primary --> <?php get_footer();
Java
-- phpMyAdmin SQL Dump -- version 3.3.9 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 16, 2011 at 10:05 AM -- Server version: 5.5.8 -- PHP Version: 5.3.5 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `sqlparser` -- -- -------------------------------------------------------- -- -- Table structure for table `articles` -- CREATE TABLE IF NOT EXISTS `articles` ( `article_id` int(10) NOT NULL AUTO_INCREMENT, `article_format_id` int(10) NOT NULL, `article_title` varchar(150) NOT NULL, `article_body` text NOT NULL, `article_date` date NOT NULL, `article_cat_id` int(10) NOT NULL, `article_active` tinyint(1) NOT NULL, `article_user_id` int(10) NOT NULL, PRIMARY KEY (`article_id`), KEY `article_format_id` (`article_format_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ; -- -- Dumping data for table `articles` -- INSERT INTO `articles` (`article_id`, `article_format_id`, `article_title`, `article_body`, `article_date`, `article_cat_id`, `article_active`, `article_user_id`) VALUES (1, 2, 'Tinie Tempah, Arcade Fire score Brits doubles', 'Tinie Tempah and Arcade Fire were the major winners at tonight''s Brit Awards, taking home two trophies apiece.', '2011-02-15', 3, 1, 1), (2, 1, 'Kelly Osbourne ''defends Leona Lewis''', 'Kelly Osbourne has revealed that she doesn''t understand why Leona Lewis is being judged because of her new style.', '2011-02-16', 2, 1, 0), (3, 2, 'Adele Storms download chart', 'Adele has stormed the singles chart following her performance at the Brit Awards. The singer, who sang a moving rendition of ''Someone Like You'', saw the track rocket up the download chart immediately after the gig.', '2011-01-16', 2, 1, 2); -- -------------------------------------------------------- -- -- Table structure for table `article_categories` -- CREATE TABLE IF NOT EXISTS `article_categories` ( `article_id` int(10) NOT NULL, `category_id` int(10) NOT NULL, KEY `article_id` (`article_id`,`category_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `article_categories` -- INSERT INTO `article_categories` (`article_id`, `category_id`) VALUES (1, 2), (2, 1), (2, 2), (3, 2); -- -------------------------------------------------------- -- -- Table structure for table `categories` -- CREATE TABLE IF NOT EXISTS `categories` ( `category_id` int(10) NOT NULL AUTO_INCREMENT, `category_title` varchar(150) NOT NULL, PRIMARY KEY (`category_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ; -- -- Dumping data for table `categories` -- INSERT INTO `categories` (`category_id`, `category_title`) VALUES (1, 'Showbiz'), (2, 'Music'), (3, 'Hotels'); -- -------------------------------------------------------- -- -- Table structure for table `formats` -- CREATE TABLE IF NOT EXISTS `formats` ( `format_id` int(10) NOT NULL AUTO_INCREMENT, `format_title` varchar(150) NOT NULL, PRIMARY KEY (`format_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; -- -- Dumping data for table `formats` -- INSERT INTO `formats` (`format_id`, `format_title`) VALUES (1, 'Video'), (2, 'TV Show'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(10) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) NOT NULL, KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `user_name`) VALUES (1, 'Jason'), (2, 'Paul');
Java
# # bzr support for dpkg-source # # Copyright © 2007 Colin Watson <cjwatson@debian.org>. # Based on Dpkg::Source::Package::V3_0::git, which is: # Copyright © 2007 Joey Hess <joeyh@debian.org>. # Copyright © 2008 Frank Lichtenheld <djpig@debian.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. package Dpkg::Source::Package::V3::Bzr; use strict; use warnings; our $VERSION = '0.01'; use Cwd; use File::Basename; use File::Find; use File::Temp qw(tempdir); use Dpkg::Gettext; use Dpkg::Compression; use Dpkg::ErrorHandling; use Dpkg::Source::Archive; use Dpkg::Exit qw(push_exit_handler pop_exit_handler); use Dpkg::Source::Functions qw(erasedir); use parent qw(Dpkg::Source::Package); our $CURRENT_MINOR_VERSION = '0'; sub import { foreach my $dir (split(/:/, $ENV{PATH})) { if (-x "$dir/bzr") { return 1; } } error(g_('cannot unpack bzr-format source package because ' . 'bzr is not in the PATH')); } sub sanity_check { my $srcdir = shift; if (! -d "$srcdir/.bzr") { error(g_('source directory is not the top directory of a bzr repository (%s/.bzr not present), but Format bzr was specified'), $srcdir); } # Symlinks from .bzr to outside could cause unpack failures, or # point to files they shouldn't, so check for and don't allow. if (-l "$srcdir/.bzr") { error(g_('%s is a symlink'), "$srcdir/.bzr"); } my $abs_srcdir = Cwd::abs_path($srcdir); find(sub { if (-l) { if (Cwd::abs_path(readlink) !~ /^\Q$abs_srcdir\E(?:\/|$)/) { error(g_('%s is a symlink to outside %s'), $File::Find::name, $srcdir); } } }, "$srcdir/.bzr"); return 1; } sub can_build { my ($self, $dir) = @_; return (0, g_("doesn't contain a bzr repository")) unless -d "$dir/.bzr"; return 1; } sub do_build { my ($self, $dir) = @_; my @argv = @{$self->{options}{ARGV}}; # TODO: warn here? #my @tar_ignore = map { "--exclude=$_" } @{$self->{options}{tar_ignore}}; my $diff_ignore_regex = $self->{options}{diff_ignore_regex}; $dir =~ s{/+$}{}; # Strip trailing / my ($dirname, $updir) = fileparse($dir); if (scalar(@argv)) { usageerr(g_("-b takes only one parameter with format '%s'"), $self->{fields}{'Format'}); } my $sourcepackage = $self->{fields}{'Source'}; my $basenamerev = $self->get_basename(1); my $basename = $self->get_basename(); my $basedirname = $basename; $basedirname =~ s/_/-/; sanity_check($dir); my $old_cwd = getcwd(); chdir $dir or syserr(g_("unable to chdir to '%s'"), $dir); local $_; # Check for uncommitted files. # To support dpkg-source -i, remove any ignored files from the # output of bzr status. open(my $bzr_status_fh, '-|', 'bzr', 'status') or subprocerr('bzr status'); my @files; while (<$bzr_status_fh>) { chomp; next unless s/^ +//; if (! length $diff_ignore_regex || ! m/$diff_ignore_regex/o) { push @files, $_; } } close($bzr_status_fh) or syserr(g_('bzr status exited nonzero')); if (@files) { error(g_('uncommitted, not-ignored changes in working directory: %s'), join(' ', @files)); } chdir $old_cwd or syserr(g_("unable to chdir to '%s'"), $old_cwd); my $tmp = tempdir("$dirname.bzr.XXXXXX", DIR => $updir); push_exit_handler(sub { erasedir($tmp) }); my $tardir = "$tmp/$dirname"; system('bzr', 'branch', $dir, $tardir); subprocerr("bzr branch $dir $tardir") if $?; # Remove the working tree. system('bzr', 'remove-tree', $tardir); subprocerr("bzr remove-tree $tardir") if $?; # Some branch metadata files are unhelpful. unlink("$tardir/.bzr/branch/branch-name", "$tardir/.bzr/branch/parent"); # Create the tar file my $debianfile = "$basenamerev.bzr.tar." . $self->{options}{comp_ext}; info(g_('building %s in %s'), $sourcepackage, $debianfile); my $tar = Dpkg::Source::Archive->new(filename => $debianfile, compression => $self->{options}{compression}, compression_level => $self->{options}{comp_level}); $tar->create(chdir => $tmp); $tar->add_directory($dirname); $tar->finish(); erasedir($tmp); pop_exit_handler(); $self->add_file($debianfile); } # Called after a tarball is unpacked, to check out the working copy. sub do_extract { my ($self, $newdirectory) = @_; my $fields = $self->{fields}; my $dscdir = $self->{basedir}; my $basename = $self->get_basename(); my $basenamerev = $self->get_basename(1); my @files = $self->get_files(); if (@files > 1) { error(g_('format v3.0 uses only one source file')); } my $tarfile = $files[0]; my $comp_ext_regex = compression_get_file_extension_regex(); if ($tarfile !~ /^\Q$basenamerev\E\.bzr\.tar\.$comp_ext_regex$/) { error(g_('expected %s, got %s'), "$basenamerev.bzr.tar.$comp_ext_regex", $tarfile); } if ($self->{options}{no_overwrite_dir} and -e $newdirectory) { error(g_('unpack target exists: %s'), $newdirectory); } else { erasedir($newdirectory); } # Extract main tarball info(g_('unpacking %s'), $tarfile); my $tar = Dpkg::Source::Archive->new(filename => "$dscdir$tarfile"); $tar->extract($newdirectory); sanity_check($newdirectory); my $old_cwd = getcwd(); chdir($newdirectory) or syserr(g_("unable to chdir to '%s'"), $newdirectory); # Reconstitute the working tree. system('bzr', 'checkout'); subprocerr('bzr checkout') if $?; chdir $old_cwd or syserr(g_("unable to chdir to '%s'"), $old_cwd); } 1;
Java
/**************************************************************************** * * $Id: vpHinkley.cpp 4056 2013-01-05 13:04:42Z fspindle $ * * This file is part of the ViSP software. * Copyright (C) 2005 - 2013 by INRIA. All rights reserved. * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ViSP with software that can not be combined with the GNU * GPL, please contact INRIA about acquiring a ViSP Professional * Edition License. * * See http://www.irisa.fr/lagadic/visp/visp.html for more information. * * This software was developed at: * INRIA Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * http://www.irisa.fr/lagadic * * If you have questions regarding the use of this file, please contact * INRIA at visp@inria.fr * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * * Description: * Hinkley's cumulative sum test implementation. * * Authors: * Fabien Spindler * *****************************************************************************/ /*! \file vpHinkley.cpp \brief Definition of the vpHinkley class corresponding to the Hinkley's cumulative sum test. */ #include <visp/vpHinkley.h> #include <visp/vpDebug.h> #include <visp/vpIoTools.h> #include <visp/vpMath.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <cmath> // std::fabs #include <limits> // numeric_limits /* VP_DEBUG_MODE fixed by configure: 1: 2: 3: Print data */ /*! Constructor. Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ to default values. By default \f$ \delta = 0.2 \f$ and \f$ \alpha = 0.2\f$. Use setDelta() and setAlpha() to modify these values. */ vpHinkley::vpHinkley() { init(); setAlpha(0.2); setDelta(0.2); } /*! Constructor. Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ thresholds. \param alpha : \f$\alpha\f$ is a predefined threshold. \param delta : \f$\delta\f$ denotes the jump minimal magnitude that we want to detect. \sa setAlpha(), setDelta() */ vpHinkley::vpHinkley(double alpha, double delta) { init(); setAlpha(alpha); setDelta(delta); } /*! Call init() to initialise the Hinkley's test and set \f$\alpha\f$ and \f$\delta\f$ thresholds. \param alpha : \f$\alpha\f$ is a predefined threshold. \param delta : \f$\delta\f$ denotes the jump minimal magnitude that we want to detect. \sa setAlpha(), setDelta() */ void vpHinkley::init(double alpha, double delta) { init(); setAlpha(alpha); setDelta(delta); } /*! Destructor. */ vpHinkley::~vpHinkley() { } /*! Initialise the Hinkley's test by setting the mean signal value \f$m_0\f$ to zero as well as \f$S_k, M_k, T_k, N_k\f$. */ void vpHinkley::init() { nsignal = 0; mean = 0.0; Sk = 0; Mk = 0; Tk = 0; Nk = 0; } /*! Set the value of \f$\delta\f$, the jump minimal magnetude that we want to detect. \sa setAlpha() */ void vpHinkley::setDelta(double delta) { dmin2 = delta / 2; } /*! Set the value of \f$\alpha\f$, a predefined threshold. \sa setDelta() */ void vpHinkley::setAlpha(double alpha) { this->alpha = alpha; } /*! Perform the Hinkley test. A downward jump is detected if \f$ M_k - S_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testUpwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testDownwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; // Calcul des variables cumulées computeSk(signal); computeMk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Sk: " << Sk << " Mk: " << Mk; // teste si les variables cumulées excèdent le seuil if ((Mk - Sk) > alpha) jump = downwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >=2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upwardJump " << std::endl; break; } } #endif computeMean(signal); if (jump == downwardJump) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Sk = 0; Mk = 0; nsignal = 0; } return (jump); } /*! Perform the Hinkley test. An upward jump is detected if \f$ T_k - N_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testDownwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testUpwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; // Calcul des variables cumulées computeTk(signal); computeNk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Tk: " << Tk << " Nk: " << Nk; // teste si les variables cumulées excèdent le seuil if ((Tk - Nk) > alpha) jump = upwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >= 2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upWardJump " << std::endl; break; } } #endif computeMean(signal); if (jump == upwardJump) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Tk = 0; Nk = 0; nsignal = 0; } return (jump); } /*! Perform the Hinkley test. A downward jump is detected if \f$ M_k - S_k > \alpha \f$. An upward jump is detected if \f$ T_k - N_k > \alpha \f$. \param signal : Observed signal \f$ s(t) \f$. \sa setDelta(), setAlpha(), testDownwardJump(), testUpwardJump() */ vpHinkley::vpHinkleyJumpType vpHinkley::testDownUpwardJump(double signal) { vpHinkleyJumpType jump = noJump; nsignal ++; // Signal length if (nsignal == 1) mean = signal; // Calcul des variables cumulées computeSk(signal); computeTk(signal); computeMk(); computeNk(); vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2 << " signal: " << signal << " Sk: " << Sk << " Mk: " << Mk << " Tk: " << Tk << " Nk: " << Nk << std::endl; // teste si les variables cumulées excèdent le seuil if ((Mk - Sk) > alpha) jump = downwardJump; else if ((Tk - Nk) > alpha) jump = upwardJump; #ifdef VP_DEBUG if (VP_DEBUG_MODE >= 2) { switch(jump) { case noJump: std::cout << "noJump " << std::endl; break; case downwardJump: std::cout << "downWardJump " << std::endl; break; case upwardJump: std::cout << "upwardJump " << std::endl; break; } } #endif computeMean(signal); if ((jump == upwardJump) || (jump == downwardJump)) { vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n"; Sk = 0; Mk = 0; Tk = 0; Nk = 0; nsignal = 0; // Debut modif FS le 03/09/2003 mean = signal; // Fin modif FS le 03/09/2003 } return (jump); } /*! Compute the mean value \f$m_0\f$ of the signal. The mean value must be computed before the jump is estimated on-line. \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeMean(double signal) { // Debut modif FS le 03/09/2003 // Lors d'une chute ou d'une remontée lente du signal, pariculièrement // après un saut, la moyenne a tendance à "dériver". Pour réduire ces // dérives de la moyenne, elle n'est remise à jour avec la valeur // courante du signal que si un début de saut potentiel n'est pas détecté. //if ( ((Mk-Sk) == 0) && ((Tk-Nk) == 0) ) if ( ( std::fabs(Mk-Sk) <= std::fabs(vpMath::maximum(Mk,Sk))*std::numeric_limits<double>::epsilon() ) && ( std::fabs(Tk-Nk) <= std::fabs(vpMath::maximum(Tk,Nk))*std::numeric_limits<double>::epsilon() ) ) // Fin modif FS le 03/09/2003 // Mise a jour de la moyenne. mean = (mean * (nsignal - 1) + signal) / (nsignal); } /*! Compute \f$S_k = \sum_{t=0}^{k} (s(t) - m_0 + \frac{\delta}{2})\f$ \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeSk(double signal) { // Calcul des variables cumulées Sk += signal - mean + dmin2; } /*! Compute \f$M_k\f$, the maximum value of \f$S_k\f$. */ void vpHinkley::computeMk() { if (Sk > Mk) Mk = Sk; } /*! Compute \f$T_k = \sum_{t=0}^{k} (s(t) - m_0 - \frac{\delta}{2})\f$ \param signal : Observed signal \f$ s(t) \f$. */ void vpHinkley::computeTk(double signal) { // Calcul des variables cumulées Tk += signal - mean - dmin2; } /*! Compute \f$N_k\f$, the minimum value of \f$T_k\f$. */ void vpHinkley::computeNk() { if (Tk < Nk) Nk = Tk; } void vpHinkley::print(vpHinkley::vpHinkleyJumpType jump) { switch(jump) { case noJump : std::cout << " No jump detected " << std::endl ; break ; case downwardJump : std::cout << " Jump downward detected " << std::endl ; break ; case upwardJump : std::cout << " Jump upward detected " << std::endl ; break ; default: std::cout << " Jump detected " << std::endl ; break ; } }
Java
<?php /** * The template for displaying all single posts. * * @package srh_framework */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'single' ); ?> <?php the_post_navigation(); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
Java
//: containers/MapDataTest.java package course.containers; /* Added by Eclipse.py */ import java.util.*; import net.mindview.util.*; import static net.mindview.util.Print.*; class Letters implements Generator<Pair<Integer,String>>, Iterable<Integer> { private int size = 9; private int number = 1; private char letter = 'A'; public Pair<Integer,String> next() { return new Pair<Integer,String>( number++, "" + letter++); } public Iterator<Integer> iterator() { return new Iterator<Integer>() { public Integer next() { return number++; } public boolean hasNext() { return number < size; } public void remove() { throw new UnsupportedOperationException(); } }; } } public class MapDataTest { public static void main(String[] args) { // Pair Generator: print(MapData.map(new Letters(), 11)); // Two separate generators: print(MapData.map(new CountingGenerator.Character(), new RandomGenerator.String(3), 8)); // A key Generator and a single value: print(MapData.map(new CountingGenerator.Character(), "Value", 6)); // An Iterable and a value Generator: print(MapData.map(new Letters(), new RandomGenerator.String(3))); // An Iterable and a single value: print(MapData.map(new Letters(), "Pop")); } } /* Output: {1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I, 10=J, 11=K} {a=YNz, b=brn, c=yGc, d=FOW, e=ZnT, f=cQr, g=Gse, h=GZM} {a=Value, b=Value, c=Value, d=Value, e=Value, f=Value} {1=mJM, 2=RoE, 3=suE, 4=cUO, 5=neO, 6=EdL, 7=smw, 8=HLG} {1=Pop, 2=Pop, 3=Pop, 4=Pop, 5=Pop, 6=Pop, 7=Pop, 8=Pop} *///:~
Java
/**************************************************************************** * * Copyright (c) 2006 Dave Hylands <dhylands@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Alternatively, this software may be distributed under the terms of BSD * license. * * See README and COPYING for more details. * ****************************************************************************/ /** * * @file Hardware.h * * @brief Defines all of the hardware definitions for the chip. * ****************************************************************************/ #if !defined( HARDWARE_H ) #define HARDWARE_H /**< Include Guard */ /* ---- Include Files ---------------------------------------------------- */ #include "Config.h" #include <avr/io.h> //-------------------------------------------------------------------------- // LED Constants #define RED_LED_PIN 4 #define RED_LED_MASK ( 1 << RED_LED_PIN ) #define RED_LED_DDR DDRG #define RED_LED_PORT PORTG #define BLUE_LED_PIN 3 #define BLUE_LED_MASK ( 1 << BLUE_LED_PIN ) #define BLUE_LED_DDR DDRG #define BLUE_LED_PORT PORTG #define YELLOW_LED_PIN 4 #define YELLOW_LED_MASK ( 1 << YELLOW_LED_PIN ) #define YELLOW_LED_DDR DDRB #define YELLOW_LED_PORT PORTB //-------------------------------------------------------------------------- // Some convenience macros to turn the LEDs on/off. // // Usage: LED_ON( BLUE ); // // to turn on the blue LED. // // Note: Setting the pin to 0 turns the LED on. #define LED_ON( color ) do { color ## _LED_PORT &= ~color ## _LED_MASK; } while (0) #define LED_OFF( color ) do { color ## _LED_PORT |= color ## _LED_MASK; } while (0) //-------------------------------------------------------------------------- // Port registers. // // Note: For input ports, writing a 1 to the PORT register casues an internal // pullup resistor to be activated. This feature also requires the // PUD bit to be set in the SFIOR register. // // For the DDR pins, 0 = input, 1 = output // Port A if the one that's just pads on the bottom of the board #define PORTA_INIT 0xFF #define DDRA_INIT 0x00 // Port B has 3 PWM lines, and SPI. Pin 4 is connected to the Yellow LED // // 7 - OC2 ATM_PWM1C // 6 - OC1B ATM_PWM1B // 5 - OC1A ATM_PWM1A // 4 - OC0 PB4 (Yellow LED) // 3 - MISO ATM_MISO // 2 - MOSI ATM_MOSI // 1 - SCK ATM_SCK // 0 - SS ATM_SS #define PORTB_INIT 0xFF // Enable pullups for inputs, Yellow LED off #define DDRB_INIT YELLOW_LED_MASK // Port C is available on the headers as 8 I/O lines. We'll assume all inputs // for now. #define PORTC_INIT 0xFF // enable pullups for all inputs #define DDRC_INIT 0x00 // Port D // // 7 - T2 ATM_T2 // 6 - T1 ATM_T1 // 5 - PD5 ATM_PD5 // 4 - IC1 ATM_IC1 // 3 - INT3 ATM_TX1 // 2 - INT2 ATM_RX1 // 1 - INT1 ATM_SDA // 0 - INT0 ATM_SCL #define PORTD_INIT 0xFF // enable pullups for all inputs #define DDRD_INIT 0x00 // Port E // // 7 - INT7 ATM_INT7 // 6 - INT6 ATM_INT6 // 5 - OC3C ATM_PWM3C // 4 - OC3B ATM_PWM3B // 3 - OC3A ATM_PWM3A // 2 - PE2 ATM_IRQ Used to interrupt gumstix // 1 - TXD ATM_TX0 // 0 - RXD ATM_RX0 #define PORTE_INIT 0xFF // enable pullups for all inputs #define DDRE_INIT 0x00 // Port F - A/D lines - could be used as GPIO // // We disable all pullups by default so they don't mess with the A/D #define PORTF_INIT 0x00 // disable pullups for A/D channels #define DDRF_INIT 0x00 // Port G // // 7 - N/A // 6 - N/A // 5 - N/A // 4 - TOSC1 ATM_PG4 - Red LED // 3 - TOSC2 ATM_PG3 - Blue LED // 2 - ALE ATM_PG2 // 1 - /RD ATM_PG1 // 0 - /WR ATM_PG0 #define PORTG_INIT 0xFF // Enable pullups for inputs, LEDs off #define DDRG_INIT ( RED_LED_MASK | BLUE_LED_MASK ) // Make LEDs outputs //-------------------------------------------------------------------------- // ASSR - Asynchronous Status Register // // TOSC1 & TOSC2 are connected to the Red/Blue LEDs so we need to set // AS0 to 0. AS0 is the only writable bit. #define ASSR_INIT 0x00 //-------------------------------------------------------------------------- // ADC Settings #define ADC_PRESCALAR_2 (( 0 << ADPS2 ) | ( 0 << ADPS1 ) | ( 1 << ADPS0 )) #define ADC_PRESCALAR_4 (( 0 << ADPS2 ) | ( 1 << ADPS1 ) | ( 0 << ADPS0 )) #define ADC_PRESCALAR_8 (( 0 << ADPS2 ) | ( 1 << ADPS1 ) | ( 1 << ADPS0 )) #define ADC_PRESCALAR_16 (( 1 << ADPS2 ) | ( 0 << ADPS1 ) | ( 0 << ADPS0 )) #define ADC_PRESCALAR_32 (( 1 << ADPS2 ) | ( 0 << ADPS1 ) | ( 1 << ADPS0 )) #define ADC_PRESCALAR_64 (( 1 << ADPS2 ) | ( 1 << ADPS1 ) | ( 0 << ADPS0 )) #define ADC_PRESCALAR_128 (( 1 << ADPS2 ) | ( 1 << ADPS1 ) | ( 1 << ADPS0 )) #define ADCSR_INIT (( 1 << ADEN ) | ( 1 << ADSC ) | ADC_PRESCALAR_128 ) #define ADMUX_REF_AREF (( 0 << REFS1 ) | ( 0 << REFS0 )) #define ADMUX_REF_AVCC (( 0 << REFS1 ) | ( 1 << REFS0 )) #define ADMUX_REF_INTERNAL (( 1 << REFS1 ) | ( 1 << REFS0 )) #define ADMUX_INIT ADMUX_REF_AVCC //-------------------------------------------------------------------------- // UART settings #define UART0_BAUD_RATE 38400 #define UART1_BAUD_RATE 38400 #define UART_DATA_BIT_8 (( 1 << UCSZ1 ) | ( 1 << UCSZ0 )) #define UART_PARITY_NONE (( 0 << UPM1 ) | ( 0 << UPM0 )) #define UART_STOP_BIT_1 ( 0 << USBS ) #define UBRR0_INIT (( CFG_CPU_CLOCK / 16 / UART0_BAUD_RATE ) - 1 ) #define UBRR1_INIT (( CFG_CPU_CLOCK / 16 / UART1_BAUD_RATE ) - 1 ) #define UCSR0A_INIT 0 #define UCSR0B_INIT (( 1 << RXCIE ) | ( 1 << RXEN ) | ( 1 << TXEN )) #define UCSR0C_INIT ( UART_DATA_BIT_8 | UART_PARITY_NONE | UART_STOP_BIT_1 ) #define UCSR1A_INIT 0 #define UCSR1B_INIT (( 1 << RXCIE ) | ( 1 << RXEN ) | ( 1 << TXEN )) #define UCSR1C_INIT ( UART_DATA_BIT_8 | UART_PARITY_NONE | UART_STOP_BIT_1 ) /* ---- Variable Externs ------------------------------------------------- */ /** * Description of variable. */ /* ---- Function Prototypes ---------------------------------------------- */ void InitHardware( void ); /** @} */ #endif // HARDWARE_H
Java
<?php class Listify_Template_Page_Templates { public function __construct() { add_filter( 'theme_page_templates', array( $this, 'visual_composer' ) ); } public function visual_composer( $page_templates ) { if ( listify_has_integration( 'visual-composer' ) ) { return $page_templates; } unset( $page_templates[ 'page-templates/template-home-vc.php' ] ); return $page_templates; } }
Java
import socket import threading import time def tcplink(sock, addr): print 'Accept new connection from %s:%s...' % addr sock.send('Welcome!') while True: data = sock.recv(1024) time.sleep(1) if data == 'exit' or not data: break sock.send('Hello, %s!' % data) sock.close() print 'Connection from %s:%s closed.' % addr s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8888)) s.listen(5) print 'Waiting for connection...' while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start()
Java
import os import sys import shutil import binascii import traceback import subprocess from win32com.client import Dispatch LAUNCHER_PATH = "C:\\Program Files\\Augur" DATA_PATH = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', "Augur") PASSFILE = os.path.join(DATA_PATH, "password.txt") if getattr(sys, 'frozen', False): # we are running in a |PyInstaller| bundle BASEDIR = sys._MEIPASS else: # we are running in a normal Python environment BASEDIR = os.path.dirname(os.path.abspath(__file__)) GETH_EXE = os.path.join(BASEDIR, 'geth.exe') LAUNCHER_EXE = os.path.join(BASEDIR, 'augurlauncher.exe') def main(): # first make all the appropriate directories print("Making directories...") for d in LAUNCHER_PATH, DATA_PATH: print("Creating", d, end=" ", flush=True) os.mkdir(d) print("Success!") print("Generating random password file...", end=" ", flush=True) # then generate the password password = binascii.b2a_hex(os.urandom(32)) passfile = open(PASSFILE, "w") passfile.write(password.decode('ascii')) passfile.close() print("Success!") # Then copy ".exe"s to the launcher path exes = GETH_EXE, LAUNCHER_EXE results = [] for exe in exes: print("Copying", os.path.basename(exe), "to", LAUNCHER_PATH, "...", end=" ", flush=True) results.append(shutil.copy(exe, LAUNCHER_PATH)) print("Sucess!") print("Creating node account...", end=" ", flush=True) # create account on node p = subprocess.Popen([results[0], "--password", PASSFILE, "account", "new"]) p.wait() print("Success!") print("Creating shortcut...", end=" ", flush=True) desktop = os.path.join(os.path.expanduser('~'), 'Desktop') shortcut_path = os.path.join(desktop, "Augur Launcher.lnk") wDir = LAUNCHER_PATH shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(shortcut_path) shortcut.Targetpath = results[1] shortcut.WorkingDirectory = wDir shortcut.IconLocation = results[1] shortcut.save() print("Success!") def uninstall(): paths = LAUNCHER_PATH, DATA_PATH for p in paths: print("Deleting", p, "...", end=" ", flush=True) shutil.rmtree(p) print("Success!") print("Removing desktop shortcut...", end=" ", flush=True) desktop = os.path.join(os.path.expanduser('~'), 'Desktop') shortcut_path = os.path.join(desktop, "Augur Launcher.lnk") os.remove(shortcut_path) print("Success!") if __name__ == '__main__': try: if len(sys.argv) == 2 and sys.argv[1] == 'uninstall': uninstall() elif len(sys.argv) == 1: main() else: assert len(sys.argv) <= 2, "wrong number of arguements!" except Exception as exc: traceback.print_exc() finally: os.system("pause") sys.exit(0)
Java
import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def test_recordInheritance(self): recf, recd = getRecordInheritance("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def test_recordsInfo(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "DepartmentOfficePayModeRow" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def test_classInfo(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
Java
<div class="twelve columns alpha"> <h3 class="headline">Descripción del Proyecto</h3><span class="line"></span><div class="clearfix"></div> <p>O Parque Tecnológico Itaipu (conocido como PTI) tiene un sitio web que proporciona mucha información sobre las actividades y los proyectos de PTI. <p>PTI ha identificado algunos problemas en su sitio, y presentado estas demandas a Celtab, para resolver estos problemas, así como mejorar el sitio en general, completamente en Drupal. <p>Por lo tanto, al ser necesario el desarrollo de algunas mejoras en Drupal y crear "plugins" para ayudar a la publicación de noticias y edición.</p> <p><strong>Investigadores:</strong> Cristhian Urunaga; Mario Villagra</p> </div> <!-- Job Description --> <div class="four columns omega"> <h3 class="headline">Detalles del Proyecto</h3><span class="line"></span><div class="clearfix"></div> <ul style="margin: 2px 0 18px 0;" class="list-3"> <li>PHP</li> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> <li>CMS Drupal 7.x</li> </ul> <div class="clearfix"></div> </div>
Java
var express = require('express'), formidable = require('formidable'), imgur = require('imgur'), fs = require('fs'), url = require('url'), bodyParser = require('body-parser'), router = express.Router(), uuid = require('node-uuid'), db = require('../lib/database'), tools = require('../lib/functions'); var connection = db.connectdb(); router.post('/upload', function(req, res) { res.writeHead(200, { 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked' }); var id = tools.makeid(); var owner = uuid.v1(); var form = new formidable.IncomingForm(), files = [], fields = []; form.uploadDir = 'tmp/'; form.on('field', function(field, value) { fields.push(value); }); form.on('file', function(field, file) { files.push(file); }); form.on('end', function() { res.end('http://' + req.headers.host + '/' + id); if (fields[0]) { owner = fields[0]; } files.forEach(function(file) { imgur.uploadFile(file.path) .then(function(json) { fs.unlink(file.path); connection.query("INSERT INTO `imgsnap`.`images` (`id`, `direct`, `timestamp`, `delete`, `owner`) VALUES ('" + connection.escape(id).replace(/'/g, '') + "', '" + connection.escape(json.data.link).replace(/'/g, '') + "', '" + connection.escape(json.data.datetime) + "', '" + connection.escape(json.data.deletehash).replace(/'/g, '') + "', '" + connection.escape(owner).replace(/'/g, '') + "')"); }) .catch(function(err) { fs.unlink(file.path); console.log(err); }); }); }); form.parse(req); }); router.get('/image/:id', function(req, res) { var id = req.params.id; connection.query('SELECT * FROM images WHERE id = ' + connection.escape(id), function(err, row, fields) { if (!row[0]) { res.json({ status: false }); } else { res.json({ status: true, direct: row[0].direct, timestamp: row[0].timestamp }); } }); }); router.get('/check', function(req, res) { res.writeHead(200, { 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked' }); res.end('Server Online'); }); module.exports = router;
Java
# -*- coding: utf-8 -*- def outfit(): collection = [] for _ in range(0, 5): collection.append("Item{}".format(_)) return { "data": collection, } api = [ ('/outfit', 'outfit', outfit), ]
Java
var UniteNivoPro = new function() { var t = this; var containerID = "slider_container"; var container, arrow_left, arrow_right, bullets_container; var caption_back, caption_text; var bulletsRelativeY = ""; /** * show slider view error, hide all the elements */ t.showSliderViewError = function(errorMessage) { jQuery("#config-document").hide(); UniteAdmin.showErrorMessage(errorMessage); } /** * main init of the object */ var init = function() { container = jQuery("#" + containerID); arrow_left = jQuery("#arrow_left"); arrow_right = jQuery("#arrow_right"); bullets_container = jQuery("#bullets_wrapper"); caption_back = jQuery("#caption_back"); caption_text = jQuery("#caption_text"); UniteAdmin.hideSystemMessageDelay(); } /** * init visual form width */ t.initSliderView = function() { init(); //init the object - must call //update menu event jQuery("#visual").click(function() { setTimeout("UniteNivoPro.initAfterDelay()", 300); }); //update visual from fields updateFromFields(); initSliderEvents(); initVisualTabs(); //update arrows fields ) if not set setTimeout("UniteNivoPro.initAfterDelay()", 1000); } /* ===================== Item View Section =================== */ /** * init item view */ t.initItemView = function() { //operate on slide image change var obj = document.getElementById("jform_params_image"); obj.addEvent('change', function() { var urlImage = g_urlRoot + this.value; //trace(urlImage); jQuery("#image_preview_wrapper").show().css("background-image", "url(\"" + urlImage + "\")"); }); } /* ===================== Item View End =================== */ /** * on visual tab display event. update some fields */ t.onVisualDisplay = function() { updateArrowPosFields(); bulletsAlignCenter(); } /** * init elements after delay */ t.initAfterDelay = function() { updateArrowPosFields(); initBullets(); } /** * align the bullets to center */ var bulletsAlignCenter = function() { var align = jQuery("#jform_visual_bullets_align").val(); if (align != "center") return(true); var data = getElementsData(); var bulletsX = Math.round((data.sliderWidth - data.bulletsWidth) / 2); bullets_container.css("left", bulletsX + "px"); updateBulletFields("center"); } /** * set bullets position by relative. */ var bulletsSetRelativeYPos = function() { var data = getElementsData(); if (data.bulletsWidth == 0) return(true); if (bulletsRelativeY == "") return(true); var bulletsPosY = data.sliderHeight + bulletsRelativeY; bullets_container.css("top", bulletsPosY + "px"); updateBulletFields("relative"); } /** * do some actions on bullets align change */ var onBulletsAlignChange = function(align) { switch (align) { case "center": bullets_container.draggable("option", "axis", "y"); bulletsAlignCenter(); UniteAdmin.hideFormField("jform_visual_bullets_xleft"); UniteAdmin.hideFormField("jform_visual_bullets_xright"); break; case "left": bullets_container.draggable("option", "axis", ""); UniteAdmin.showFormField("jform_visual_bullets_xleft"); UniteAdmin.hideFormField("jform_visual_bullets_xright"); jQuery("#jform_visual_bullets_xleft-lbl").css('display', 'inline'); break; case "right": bullets_container.draggable("option", "axis", ""); UniteAdmin.hideFormField("jform_visual_bullets_xleft"); UniteAdmin.showFormField("jform_visual_bullets_xright"); jQuery("#jform_visual_bullets_xright-lbl").css('display', 'inline'); break; } } /** * on bullets drag event, update fields. */ var onBulletsDrag = function() { updateBulletFields("drag"); } /** * update relative y */ var updateBulletsRelativeY = function() { var data = getElementsData(); bulletsRelativeY = data.bulletsY - data.sliderHeight; } /** * init the bullets position */ var initBullets = function() { var selectorBulletsAlign = "#jform_visual_bullets_align"; var selectorBulletReverse = "#jform_visual_reverse_bullets"; var align = jQuery(selectorBulletsAlign).val(); //set bullets draggable var drag_options = {drag: onBulletsDrag}; if (align == "center") { bulletsAlignCenter(); //set draggable only y axis drag_options.axis = "y"; } jQuery(selectorBulletReverse).change(function() { reverse_bullets(); }) //set select event jQuery(selectorBulletsAlign).change(function() { onBulletsAlignChange(this.value); }); //set draggable event bullets_container.draggable(drag_options); //show the bullets (if hidden) bullets_container.removeClass("invisible"); updateBulletsRelativeY(); } /** * show some tab, set it selecetd class, and hide the others. */ var showVisualTab = function(linkID) { var link = jQuery("#" + linkID); if (!link.length) return(false); var tabID = link.data("tab"); //set togler selected jQuery("#tabs_visual li a").removeClass("selected"); link.addClass("selected"); //show panel jQuery(".visual_panel").removeClass("hidden").hide(); jQuery(tabID).show(); } /** * init visual tabs functionality */ var initVisualTabs = function() { var hash = location.hash; if (hash) { var linkID = hash.replace("#tab-", ""); showVisualTab(linkID); } //set event jQuery("#tabs_visual li a").click(function() { showVisualTab(this.id); }); } /** * on slider resize event. update all elements and fields accordingly */ var onSliderResize = function(event, ui) { //update fields widht / height if (event) { //only if came from event jQuery("#jform_visual_width").val(container.width()); jQuery("#jform_visual_height").val(container.height()); } checkArrowsConnection("arrow_left"); bulletsSetRelativeYPos(); bulletsAlignCenter(); } /** * init slider view onchange events */ var initSliderEvents = function() { //set fields onchange events var fields = "#visual_wrapper input"; jQuery(fields).blur(updateFromFields).click(updateFromFields); jQuery(fields).keypress(function(event) { if (event.keyCode == 13) updateFromFields(this); }); jQuery("#visual_wrapper select").change(updateFromFields); //set resizible event: container.resizable({resize: onSliderResize}); //set on color picker move event: UniteAdmin.onColorPickerMove(function() { updateFromFields(); }); //set arrows draggable jQuery("#arrow_left,#arrow_right").draggable({ drag: onArrowsDrag }); jQuery("#arrows_gocenter").click(arrowsToCenter); } /** * get all element sizes and positions. */ var getElementsData = function() { var data = {}; //slider data data.sliderWidth = Number(jQuery("#jform_visual_width").val()); data.sliderHeight = Number(jQuery("#jform_visual_height").val()); //arrows data var arrowLeftPos = arrow_left.position(); var arrowRightPos = arrow_right.position(); data.arrowLeftX = Math.round(arrowLeftPos.left); data.arrowLeftY = Math.round(arrowLeftPos.top); data.arrowRightX = Math.round(arrowRightPos.left); data.arrowRightY = Math.round(arrowRightPos.top); data.arrowLeftWidth = arrow_left.width(); data.arrowLeftHeight = arrow_left.height(); data.arrowRightWidth = arrow_right.width(); data.arrowRightHeight = arrow_right.height(); //bullets data: var bulletsPos = bullets_container.position(); data.bulletsWidth = bullets_container.width(); data.bulletsHeight = bullets_container.height(); data.bulletsX = Math.round(bulletsPos.left); data.bulletsY = Math.round(bulletsPos.top); return(data); } /** * get the arrows to center of the banner (y axes) */ var arrowsToCenter = function() { var data = getElementsData(); var arrowsNewY = Math.round(data.sliderHeight - data.arrowLeftHeight) / 2; arrow_right.css("top", arrowsNewY + "px"); arrow_left.css("top", arrowsNewY + "px"); //update position fields on the panel updateArrowPosFields(); } /** * check arrows connection, and */ var checkArrowsConnection = function(arrowID) { var freeDrag = jQuery("#jform_visual_arrows_free_drag").is(":checked"); if (freeDrag == true) { updateArrowPosFields(); return(false); } var data = getElementsData(); if (arrowID == "arrow_left") { //left arrow is main. var arrowRightNewX = data.sliderWidth - data.arrowLeftX - data.arrowRightWidth; //set right arrow position arrow_right.css({"top": data.arrowLeftY + "px", "left": arrowRightNewX + "px"}); } else if (arrowID == "arrow_right") { //right arrow is main var arrowLeftNewX = data.sliderWidth - data.arrowRightX - data.arrowRightWidth; //set left arrow position arrow_left.css({"top": data.arrowRightY + "px", "left": arrowLeftNewX + "px"}); } updateArrowPosFields(); } /** * on arrows drag event. update form fields, and operate arrow connections. */ var onArrowsDrag = function() { var arrowID = this.id; checkArrowsConnection(arrowID); } /** * * update bullets position from the bullets */ var updateBulletFields = function(fromWhere) { //trace("update fields "+fromWhere);return(false); if (bullets_container.is(":visible") == false) return(true); var data = getElementsData(); //update fields: var bulletsRightX = data.sliderWidth - data.bulletsX - data.bulletsWidth; jQuery("#jform_visual_bullets_y").val(data.bulletsY); jQuery("#jform_visual_bullets_xleft").val(data.bulletsX); jQuery("#jform_visual_bullets_xright").val(bulletsRightX); //update relative option updateBulletsRelativeY(); } /** * update arrows positions from the arrows */ var updateArrowPosFields = function() { //don't update if the container not visible if (container.is(':visible') == false) return(true); if (arrow_left.is(':visible') == false) return(true); var data = getElementsData(); //set values jQuery("#jform_visual_arrow_left_x").val(data.arrowLeftX); jQuery("#jform_visual_arrow_left_y").val(data.arrowLeftY); jQuery("#jform_visual_arrow_right_x").val(data.arrowRightX); jQuery("#jform_visual_arrow_right_y").val(data.arrowRightY); } /** * hide arrows and disable panel elements */ var hideArrows = function() { if (arrow_left.is(':visible') == false) return(true); arrow_left.hide(); arrow_right.hide(); //hide arrow fields jQuery("#section_arrows").hide(); } /** * show arrows and enable panel elements */ var showArrows = function() { if (arrow_left.is(':visible') == true) return(true); arrow_left.show(); arrow_right.show(); //show arrow fields jQuery("#section_arrows").show(); } /** * update the container from fields. */ var updateFromFields = function(element) { if (element == undefined || element.id == undefined) element = this; var elemID = null; if (element.id != undefined) elemID = element.id; //---- update width / height var width = jQuery("#jform_visual_width").val(); var height = jQuery("#jform_visual_height").val(); container.width(width).height(height); //width / heigth event switch (elemID) { case "jform_visual_width": case "jform_visual_height": onSliderResize(); break; } //update border updateFromFields_border(); //update shadow updateFromFields_shadow(); //update arrows updateFromFields_arrows(elemID); //update bullets updateFromFields_bullets(elemID); //set the bullets according the resize bulletsSetRelativeYPos(); //update captions updateFromFields_caption(elemID); //update caption text updateFromFields_captionText(); } /** * update caption text */ var updateFromFields_captionText = function() { var css = {}; if (caption_back.is(":visible") == false) return(true); //set color var textColor = jQuery("#jform_visual_text_color").val(); css["color"] = textColor; //set text align var textAlign = jQuery("#jform_visual_text_align").val(); css["text-align"] = textAlign; //set padding var textPadding = jQuery("#jform_visual_text_padding").val(); css["padding"] = textPadding + "px"; var fontSize = jQuery("#jform_visual_font_size").val(); css["font-size"] = fontSize + "px"; //set the css caption_text.css(css); } /** * show the caption */ var showCaption = function() { if (caption_back.is(":visible") == true) return(false); caption_back.show(); } /** * hide the caption */ var hideCaption = function() { if (caption_back.is(":visible") == false) return(false); caption_back.hide(); } /** * update captions fields */ var updateFromFields_caption = function(elemID) { var css = {}; if (elemID == "jform_visual_has_caption") { var hasCaption = jQuery("#jform_visual_has_caption").is(":checked"); if (hasCaption == true) showCaption(); else hideCaption(); } if (caption_back.is(":visible") == false) return(true); //set back color var backColor = jQuery("#jform_visual_caption_back_color").val(); css["background-color"] = backColor; //set alpha var alpha = jQuery("#jform_visual_caption_back_alpha").val(); var alpha = Number(alpha) / 100; caption_back.fadeTo(0, alpha); //set position: var position = jQuery("#jform_visual_caption_position").val(); if (position == "top") { css["bottom"] = ""; //set to top css["top"] = "0px"; } else { css["bottom"] = "0px"; //set to bottom css["top"] = ""; } //set the css caption_back.css(css); } /** * hide the bullets */ var hideBullets = function() { if (bullets_container.is(":visible") == false) return(true); //hide fields jQuery("#section_bullets").hide(); //hide bullets bullets_container.hide(); } /** * show the bullets */ var showBullets = function() { if (bullets_container.is(":visible") == true) return(true); //show fields jQuery("#section_bullets").show(); //show bullets bullets_container.removeClass("invisible").show(); } /** * update bullets fields */ var reverse_bullets = function() { var reverseChecked = jQuery("#jform_visual_reverse_bullets").is(":checked"); var normal = 'normal'; var active = 'active'; if (reverseChecked) { normal = 'active'; active = 'normal'; } jQuery("#bullets_wrapper img").each(function(index, value) { if (index == 1) { jQuery(this).attr('src', jQuery(this).attr('src').replace(normal, active)); } else { jQuery(this).attr('src', jQuery(this).attr('src').replace(active, normal)); } }); } /** * update bullets fields */ var updateFromFields_bullets = function(elemID) { //trace("update bullets");return(false); switch (elemID) { case "jform_visual_has_bullets": var showBulletsCheck = jQuery("#jform_visual_has_bullets").is(":checked"); if (showBulletsCheck) showBullets(); else hideBullets(); break; } //skip invisible container if (bullets_container.is(':visible') == false) return(true); var bulletsY = jQuery("#jform_visual_bullets_y").val(); switch (elemID) { default: case "jform_visual_bullets_xleft": var bulletsX = jQuery("#jform_visual_bullets_xleft").val(); break; case "jform_visual_bullets_xright": var data = getElementsData(); var bulletsRightX = jQuery("#jform_visual_bullets_xright").val(); var bulletsX = data.sliderWidth - data.bulletsWidth - bulletsRightX; break; case "jform_visual_bullets_spacing": //set spacing var spacing = jQuery("#jform_visual_bullets_spacing").val(); bullets_container.find("ul li:not(:first-child)").css("margin-left", spacing + "px"); bulletsAlignCenter(); break; } bullets_container.css({"top": bulletsY + "px", "left": bulletsX + "px"}); updateBulletFields("fields"); } /** * update border */ var updateFromFields_border = function() { var has_border = jQuery("#jform_visual_has_border").is(':checked'); if (has_border == true) { var border_color = jQuery("#jform_visual_border_color").val(); var border_size = jQuery("#jform_visual_border_size").val(); container.css({"border-style": "solid", "border-width": border_size + "px", "border-color": border_color }); } else container.css({"border-style": "none"}); } /** * update shadow from fields */ var updateFromFields_shadow = function() { //----update shadow: var has_shadow = jQuery("#jform_visual_has_shadow").is(':checked'); if (has_shadow == true) { var shadow_color = jQuery("#jform_visual_shadow_color").val(); var shadowProps = "0px 1px 5px 0px " + shadow_color; container.css({"box-shadow": shadowProps, "-moz-box-shadow": shadowProps, "-webkit-box-shadow": shadowProps}); } else container.css({"box-shadow": "none", "-moz-box-shadow": "none", "-webkit-box-shadow": "none"}); } /** * set arrows in the place of the fields */ var updateFromFields_arrows = function(elemID) { var showArrows_check = jQuery("#jform_visual_has_arrows").is(":checked"); //check arrows hide / show if (elemID == "jform_visual_has_arrows") { if (showArrows_check == false) hideArrows(); else showArrows(); } //position arrows if (arrow_left.is(':visible') == false) return(true); var arrowLeftX = jQuery("#jform_visual_arrow_left_x").val(); var arrowLeftY = jQuery("#jform_visual_arrow_left_y").val(); var arrowRightX = jQuery("#jform_visual_arrow_right_x").val(); var arrowRightY = jQuery("#jform_visual_arrow_right_y").val(); arrow_left.css({"top": arrowLeftY + "px", "left": arrowLeftX + "px"}); arrow_right.css({"top": arrowRightY + "px", "left": arrowRightX + "px"}); //operate errors connection: switch (elemID) { case "jform_visual_has_arrows": case "jform_visual_arrow_left_y": case "jform_visual_arrow_left_x": checkArrowsConnection("arrow_left"); break; case "jform_visual_arrow_right_y": case "jform_visual_arrow_right_x": checkArrowsConnection("arrow_right"); break; } } /** * on arrows select event - update arrow pictures and change arrows set */ t.onArrowsSelect = function(data) { jQuery("#arrow_left").attr("src", data.url_left); jQuery("#arrow_right").attr("src", data.url_right); jQuery("#jform_visual_arrows_set").val(data.arrowName); //align arrows setTimeout("UniteNivoPro.operationDelay('checkArrowsConnection')", 500); } /** * on bullets select - take bullets html by ajax, and change the bullets. */ t.onBulletsSelect = function(setName) { var data = {setName: setName}; UniteAdmin.ajaxRequest("get_bullets_html", data, function(response) { jQuery("#bullets_wrapper").html(response.bullets_html); jQuery("#jform_visual_bullets_set").val(setName); //align center after delay setTimeout("UniteNivoPro.operationDelay('bulletsAlignCenter')", 500); bulletsAlignCenter(); reverse_bullets(); }); } /** * align center after delay function */ t.operationDelay = function(operation) { switch (operation) { case "bulletsAlignCenter": bulletsAlignCenter(); break; case "checkArrowsConnection": checkArrowsConnection("arrow_left"); break; } } }
Java
#ifndef _UMLNCRELATION_H #define _UMLNCRELATION_H #include "UmlBaseNcRelation.h" #include <qcstring.h> //This class manages 'relations' between non class objects // // You can modify it as you want (except the constructor) class UmlNcRelation : public UmlBaseNcRelation { public: UmlNcRelation(void * id, const QCString & n) : UmlBaseNcRelation(id, n) {}; virtual int orderWeight(); }; #endif
Java
/* * Copyright (C) 2013-2019 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public License * version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package org.n52.series.spi.geo; import org.locationtech.jts.geom.Geometry; import org.n52.io.crs.CRSUtils; import org.n52.io.request.IoParameters; import org.n52.io.response.dataset.StationOutput; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TransformationService { private static final Logger LOGGER = LoggerFactory.getLogger(TransformationService.class); /** * @param station * the station to transform * @param parameters * the query containing CRS and how to handle axes order */ protected void transformInline(StationOutput station, IoParameters parameters) { String crs = parameters.getCrs(); if (CRSUtils.DEFAULT_CRS.equals(crs)) { // no need to transform return; } Geometry geometry = transform(station.getGeometry(), parameters); station.setValue(StationOutput.GEOMETRY, geometry, parameters, station::setGeometry); } public Geometry transform(Geometry geometry, IoParameters query) { String crs = query.getCrs(); if (CRSUtils.DEFAULT_CRS.equals(crs)) { // no need to transform return geometry; } return transformGeometry(query, geometry, crs); } private Geometry transformGeometry(IoParameters query, Geometry geometry, String crs) throws RuntimeException { try { CRSUtils crsUtils = query.isForceXY() ? CRSUtils.createEpsgForcedXYAxisOrder() : CRSUtils.createEpsgStrictAxisOrder(); return geometry != null ? crsUtils.transformInnerToOuter(geometry, crs) : geometry; } catch (TransformException e) { throwRuntimeException(crs, e); } catch (FactoryException e) { LOGGER.debug("Couldn't create geometry factory", e); } return geometry; } private void throwRuntimeException(String crs, TransformException e) throws RuntimeException { throw new RuntimeException("Could not transform to requested CRS: " + crs, e); } }
Java
// This file is part of fityk program. Copyright 2001-2013 Marcin Wojdyr // Licence: GNU General Public License ver. 2+ /// wrapper around MPFIT (cmpfit) library, /// http://www.physics.wisc.edu/~craigm/idl/cmpfit.html /// which is Levenberg-Marquardt implementation based on MINPACK-1 #ifndef FITYK_MPFIT_H_ #define FITYK_MPFIT_H_ #include "fit.h" #include "cmpfit/mpfit.h" namespace fityk { /// Wrapper around CMPFIT class MPfit : public Fit { public: MPfit(Full* F, const char* fname) : Fit(F, fname) {} virtual double run_method(std::vector<realt>* best_a); // implementation (must be public to be called inside callback function) int calculate(int m, int npar, double *par, double *deviates, double **derivs); int on_iteration(); virtual std::vector<double> get_covariance_matrix(const std::vector<Data*>& datas); virtual std::vector<double> get_standard_errors(const std::vector<Data*>& datas); private: mp_config_struct mp_conf_; mp_result result_; int run_mpfit(const std::vector<Data*>& datas, const std::vector<realt>& parameters, const std::vector<bool>& param_usage, double *final_a=NULL); }; } // namespace fityk #endif
Java
#include <stdio.h> #include <string.h> #include <stdlib.h> // prototypes declarations char** split(char *str, char *delimitators); int main(void) { char** result; char str[] = "1-0:0.0.1(132412515)\n1-0:0.2.3.4(654236517)\n"; result = split(str, "()\n"); for(size_t index = 0; *(result + index); index++) { printf("%s\n",*(result + index)); } free(result); return 0; } char** split(char *str, char* delimitators) { int count = 0; size_t index = 0; char **parse; char *tmp = str; char *token; char *last_delimitator; while(*tmp) { /****************************************** si *tmp contiene uno de los deliitadores strchr devolvera la direcccion de este sino devolvera una direccion nula *******************************************/ if(strchr(delimitators, *tmp) != NULL) { count++; last_delimitator = tmp; } tmp++; } //Espacio para datos ubicados luego del ultimo delimitador count += last_delimitator < (str + strlen(str) - 1); //Espacio para el caracter nulo del arreglo de punteros count++; parse = malloc(sizeof(char*) * count); token = strtok(str, delimitators); while(token != NULL) { *(parse + index++) = token; token = strtok(NULL, delimitators); } *(parse + index) = 0; return parse; }
Java
<?php /** * ECSHOP 控制台首頁 * ============================================================================ * 版權所有 2005-2010 上海商派網絡科技有限公司,並保留所有權利。 * 網站地址: http://www.ecshop.com; * ---------------------------------------------------------------------------- * 這不是一個自由軟件!您只能在不用於商業目的的前提下對程序代碼進行修改和 * 使用;不允許對程序代碼以任何形式任何目的的再發布。 * ============================================================================ * $Author: liuhui $ * $Id: index.php 17163 2010-05-20 10:13:23Z liuhui $ */ define('IN_ECS', true); require(dirname(__FILE__) . '/includes/init.php'); require_once(ROOT_PATH . '/includes/lib_order.php'); /*------------------------------------------------------ */ //-- 框架 /*------------------------------------------------------ */ if ($_REQUEST['act'] == '') { $smarty->assign('shop_url', urlencode($ecs->url())); $smarty->display('index.htm'); } /*------------------------------------------------------ */ //-- 頂部框架的內容 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'top') { // 獲得管理員設置的菜單 $lst = array(); $nav = $db->GetOne('SELECT nav_list FROM ' . $ecs->table('admin_user') . " WHERE user_id = '" . $_SESSION['admin_id'] . "'"); if (!empty($nav)) { $arr = explode(',', $nav); foreach ($arr AS $val) { $tmp = explode('|', $val); $lst[$tmp[1]] = $tmp[0]; } } // 獲得管理員設置的菜單 // 獲得管理員ID $smarty->assign('send_mail_on',$_CFG['send_mail_on']); $smarty->assign('nav_list', $lst); $smarty->assign('admin_id', $_SESSION['admin_id']); $smarty->assign('certi', $_CFG['certi']); $smarty->display('top.htm'); } /*------------------------------------------------------ */ //-- 計算器 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'calculator') { $smarty->display('calculator.htm'); } /*------------------------------------------------------ */ //-- 左邊的框架 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'menu') { include_once('includes/inc_menu.php'); // 權限對照表 include_once('includes/inc_priv.php'); foreach ($modules AS $key => $value) { ksort($modules[$key]); } ksort($modules); foreach ($modules AS $key => $val) { $menus[$key]['label'] = $_LANG[$key]; if (is_array($val)) { foreach ($val AS $k => $v) { if ( isset($purview[$k])) { if (is_array($purview[$k])) { $boole = false; foreach ($purview[$k] as $action) { $boole = $boole || admin_priv($action, '', false); } if (!$boole) { continue; } } else { if (! admin_priv($purview[$k], '', false)) { continue; } } } if ($k == 'ucenter_setup' && $_CFG['integrate_code'] != 'ucenter') { continue; } $menus[$key]['children'][$k]['label'] = $_LANG[$k]; $menus[$key]['children'][$k]['action'] = $v; } } else { $menus[$key]['action'] = $val; } // 如果children的子元素長度為0則刪除該組 if(empty($menus[$key]['children'])) { unset($menus[$key]); } } $smarty->assign('menus', $menus); $smarty->assign('no_help', $_LANG['no_help']); $smarty->assign('help_lang', $_CFG['lang']); $smarty->assign('charset', EC_CHARSET); $smarty->assign('admin_id', $_SESSION['admin_id']); $smarty->display('menu.htm'); } /*------------------------------------------------------ */ //-- 清除緩存 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'clear_cache') { clear_all_files(); sys_msg($_LANG['caches_cleared']); } /*------------------------------------------------------ */ //-- 主窗口,起始頁 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'main') { //開店嚮導第一步 if(isset($_SESSION['shop_guide']) && $_SESSION['shop_guide'] === true) { unset($_SESSION['shop_guide']);//銷毀session ecs_header("Location: ./index.php?act=first\n"); exit(); } $gd = gd_version(); /* 檢查文件目錄屬性 */ $warning = array(); if ($_CFG['shop_closed']) { $warning[] = $_LANG['shop_closed_tips']; } if (file_exists('../install')) { $warning[] = $_LANG['remove_install']; } if (file_exists('../upgrade')) { $warning[] = $_LANG['remove_upgrade']; } if (file_exists('../demo')) { $warning[] = $_LANG['remove_demo']; } $open_basedir = ini_get('open_basedir'); if (!empty($open_basedir)) { /* 如果 open_basedir 不為空,則檢查是否包含了 upload_tmp_dir */ $open_basedir = str_replace(array("\\", "\\\\"), array("/", "/"), $open_basedir); $upload_tmp_dir = ini_get('upload_tmp_dir'); if (empty($upload_tmp_dir)) { if (stristr(PHP_OS, 'win')) { $upload_tmp_dir = getenv('TEMP') ? getenv('TEMP') : getenv('TMP'); $upload_tmp_dir = str_replace(array("\\", "\\\\"), array("/", "/"), $upload_tmp_dir); } else { $upload_tmp_dir = getenv('TMPDIR') === false ? '/tmp' : getenv('TMPDIR'); } } if (!stristr($open_basedir, $upload_tmp_dir)) { $warning[] = sprintf($_LANG['temp_dir_cannt_read'], $upload_tmp_dir); } } $result = file_mode_info('../cert'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'cert', $_LANG['cert_cannt_write']); } $result = file_mode_info('../' . DATA_DIR); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'data', $_LANG['data_cannt_write']); } else { $result = file_mode_info('../' . DATA_DIR . '/afficheimg'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/afficheimg', $_LANG['afficheimg_cannt_write']); } $result = file_mode_info('../' . DATA_DIR . '/brandlogo'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/brandlogo', $_LANG['brandlogo_cannt_write']); } $result = file_mode_info('../' . DATA_DIR . '/cardimg'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/cardimg', $_LANG['cardimg_cannt_write']); } $result = file_mode_info('../' . DATA_DIR . '/feedbackimg'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/feedbackimg', $_LANG['feedbackimg_cannt_write']); } $result = file_mode_info('../' . DATA_DIR . '/packimg'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/packimg', $_LANG['packimg_cannt_write']); } } $result = file_mode_info('../images'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['images_cannt_write']); } else { $result = file_mode_info('../' . IMAGE_DIR . '/upload'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], IMAGE_DIR . '/upload', $_LANG['imagesupload_cannt_write']); } } $result = file_mode_info('../temp'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['tpl_cannt_write']); } $result = file_mode_info('../temp/backup'); if ($result < 2) { $warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['tpl_backup_cannt_write']); } if (!is_writeable('../' . DATA_DIR . '/order_print.html')) { $warning[] = $_LANG['order_print_canntwrite']; } clearstatcache(); $smarty->assign('warning_arr', $warning); /* 管理員留言信息 */ $sql = 'SELECT message_id, sender_id, receiver_id, sent_time, readed, deleted, title, message, user_name ' . 'FROM ' . $ecs->table('admin_message') . ' AS a, ' . $ecs->table('admin_user') . ' AS b ' . "WHERE a.sender_id = b.user_id AND a.receiver_id = '$_SESSION[admin_id]' AND ". "a.readed = 0 AND deleted = 0 ORDER BY a.sent_time DESC"; $admin_msg = $db->GetAll($sql); $smarty->assign('admin_msg', $admin_msg); /* 取得支持貨到付款和不支持貨到付款的支付方式 */ $ids = get_pay_ids(); /* 已完成的訂單 */ $order['finished'] = $db->GetOne('SELECT COUNT(*) FROM ' . $ecs->table('order_info'). " WHERE 1 " . order_query_sql('finished')); $status['finished'] = CS_FINISHED; /* 待發貨的訂單: */ $order['await_ship'] = $db->GetOne('SELECT COUNT(*)'. ' FROM ' .$ecs->table('order_info') . " WHERE 1 " . order_query_sql('await_ship')); $status['await_ship'] = CS_AWAIT_SHIP; /* 待付款的訂單: */ $order['await_pay'] = $db->GetOne('SELECT COUNT(*)'. ' FROM ' .$ecs->table('order_info') . " WHERE 1 " . order_query_sql('await_pay')); $status['await_pay'] = CS_AWAIT_PAY; /* “未確認”的訂單 */ $order['unconfirmed'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('order_info'). " WHERE 1 " . order_query_sql('unconfirmed')); $status['unconfirmed'] = OS_UNCONFIRMED; // $today_start = mktime(0,0,0,date('m'),date('d'),date('Y')); $order['stats'] = $db->getRow('SELECT COUNT(*) AS oCount, IFNULL(SUM(order_amount), 0) AS oAmount' . ' FROM ' .$ecs->table('order_info')); $smarty->assign('order', $order); $smarty->assign('status', $status); /* 商品信息 */ $goods['total'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_alone_sale = 1 AND is_real = 1'); $virtual_card['total'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_alone_sale = 1 AND is_real=0 AND extension_code=\'virtual_card\''); $goods['new'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_new = 1 AND is_real = 1'); $virtual_card['new'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_new = 1 AND is_real=0 AND extension_code=\'virtual_card\''); $goods['best'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_best = 1 AND is_real = 1'); $virtual_card['best'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_best = 1 AND is_real=0 AND extension_code=\'virtual_card\''); $goods['hot'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_hot = 1 AND is_real = 1'); $virtual_card['hot'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_hot = 1 AND is_real=0 AND extension_code=\'virtual_card\''); $time = gmtime(); $goods['promote'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND promote_price>0' . " AND promote_start_date <= '$time' AND promote_end_date >= '$time' AND is_real = 1"); $virtual_card['promote'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND promote_price>0' . " AND promote_start_date <= '$time' AND promote_end_date >= '$time' AND is_real=0 AND extension_code='virtual_card'"); /* 缺貨商品 */ if ($_CFG['use_storage']) { $sql = 'SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND goods_number <= warn_number AND is_real = 1'; $goods['warn'] = $db->GetOne($sql); $sql = 'SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND goods_number <= warn_number AND is_real=0 AND extension_code=\'virtual_card\''; $virtual_card['warn'] = $db->GetOne($sql); } else { $goods['warn'] = 0; $virtual_card['warn'] = 0; } $smarty->assign('goods', $goods); $smarty->assign('virtual_card', $virtual_card); /* 訪問統計信息 */ $today = local_getdate(); $sql = 'SELECT COUNT(*) FROM ' .$ecs->table('stats'). ' WHERE access_time > ' . (mktime(0, 0, 0, $today['mon'], $today['mday'], $today['year']) - date('Z')); $today_visit = $db->GetOne($sql); $smarty->assign('today_visit', $today_visit); $online_users = $sess->get_users_count(); $smarty->assign('online_users', $online_users); /* 最近反饋 */ $sql = "SELECT COUNT(f.msg_id) ". "FROM " . $ecs->table('feedback') . " AS f ". "LEFT JOIN " . $ecs->table('feedback') . " AS r ON r.parent_id=f.msg_id " . 'WHERE f.parent_id=0 AND ISNULL(r.msg_id) ' ; $smarty->assign('feedback_number', $db->GetOne($sql)); /* 未審核評論 */ $smarty->assign('comment_number', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('comment') . ' WHERE status = 0 AND parent_id = 0')); $mysql_ver = $db->version(); // 獲得 MySQL 版本 /* 系統信息 */ $sys_info['os'] = PHP_OS; $sys_info['ip'] = $_SERVER['SERVER_ADDR']; $sys_info['web_server'] = $_SERVER['SERVER_SOFTWARE']; $sys_info['php_ver'] = PHP_VERSION; $sys_info['mysql_ver'] = $mysql_ver; $sys_info['zlib'] = function_exists('gzclose') ? $_LANG['yes']:$_LANG['no']; $sys_info['safe_mode'] = (boolean) ini_get('safe_mode') ? $_LANG['yes']:$_LANG['no']; $sys_info['safe_mode_gid'] = (boolean) ini_get('safe_mode_gid') ? $_LANG['yes'] : $_LANG['no']; $sys_info['timezone'] = function_exists("date_default_timezone_get") ? date_default_timezone_get() : $_LANG['no_timezone']; $sys_info['socket'] = function_exists('fsockopen') ? $_LANG['yes'] : $_LANG['no']; if ($gd == 0) { $sys_info['gd'] = 'N/A'; } else { if ($gd == 1) { $sys_info['gd'] = 'GD1'; } else { $sys_info['gd'] = 'GD2'; } $sys_info['gd'] .= ' ('; /* 檢查系統支持的圖片類型 */ if ($gd && (imagetypes() & IMG_JPG) > 0) { $sys_info['gd'] .= ' JPEG'; } if ($gd && (imagetypes() & IMG_GIF) > 0) { $sys_info['gd'] .= ' GIF'; } if ($gd && (imagetypes() & IMG_PNG) > 0) { $sys_info['gd'] .= ' PNG'; } $sys_info['gd'] .= ')'; } /* IP庫版本 */ $sys_info['ip_version'] = ecs_geoip('255.255.255.0'); /* 允許上傳的最大文件大小 */ $sys_info['max_filesize'] = ini_get('upload_max_filesize'); $smarty->assign('sys_info', $sys_info); /* 缺貨登記 */ $smarty->assign('booking_goods', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('booking_goods') . ' WHERE is_dispose = 0')); /* 退款申請 */ $smarty->assign('new_repay', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('user_account') . ' WHERE process_type = ' . SURPLUS_RETURN . ' AND is_paid = 0 ')); assign_query_info(); $smarty->assign('ecs_version', VERSION); $smarty->assign('ecs_release', RELEASE); $smarty->assign('ecs_lang', $_CFG['lang']); $smarty->assign('ecs_charset', strtoupper(EC_CHARSET)); $smarty->assign('install_date', local_date($_CFG['date_format'], $_CFG['install_date'])); $smarty->display('start.htm'); } elseif ($_REQUEST['act'] == 'main_api') { require_once(ROOT_PATH . '/includes/lib_base.php'); $data = read_static_cache('api_str'); if($data === false || API_TIME < date('Y-m-d H:i:s',time()-43200)) { include_once(ROOT_PATH . 'includes/cls_transport.php'); $ecs_version = VERSION; $ecs_lang = $_CFG['lang']; $ecs_release = RELEASE; $php_ver = PHP_VERSION; $mysql_ver = $db->version(); $order['stats'] = $db->getRow('SELECT COUNT(*) AS oCount, IFNULL(SUM(order_amount), 0) AS oAmount' . ' FROM ' .$ecs->table('order_info')); $ocount = $order['stats']['oCount']; $oamount = $order['stats']['oAmount']; $goods['total'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND is_alone_sale = 1 AND is_real = 1'); $gcount = $goods['total']; $ecs_charset = strtoupper(EC_CHARSET); $ecs_user = $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('users')); $ecs_template = $db->getOne('SELECT value FROM ' . $ecs->table('shop_config') . ' WHERE code = \'template\''); $style = $db->getOne('SELECT value FROM ' . $ecs->table('shop_config') . ' WHERE code = \'stylename\''); if($style == '') { $style = '0'; } $ecs_style = $style; $shop_url = urlencode($ecs->url()); $patch_file = file_get_contents(ROOT_PATH.ADMIN_PATH."/patch_num"); $apiget = "ver= $ecs_version &lang= $ecs_lang &release= $ecs_release &php_ver= $php_ver &mysql_ver= $mysql_ver &ocount= $ocount &oamount= $oamount &gcount= $gcount &charset= $ecs_charset &usecount= $ecs_user &template= $ecs_template &style= $ecs_style &url= $shop_url &patch= $patch_file "; $t = new transport; $api_comment = $t->request('http://api.ecshop.com/checkver.php', $apiget); $api_str = $api_comment["body"]; echo $api_str; $f=ROOT_PATH . 'data/config.php'; file_put_contents($f,str_replace("'API_TIME', '".API_TIME."'","'API_TIME', '".date('Y-m-d H:i:s',time())."'",file_get_contents($f))); write_static_cache('api_str', $api_str); } else { echo $data; } } /*------------------------------------------------------ */ //-- 開店嚮導第一步 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'first') { $smarty->assign('countries', get_regions()); $smarty->assign('provinces', get_regions(1, 1)); $smarty->assign('cities', get_regions(2, 2)); $sql = 'SELECT value from ' . $ecs->table('shop_config') . " WHERE code='shop_name'"; $shop_name = $db->getOne($sql); $smarty->assign('shop_name', $shop_name); $sql = 'SELECT value from ' . $ecs->table('shop_config') . " WHERE code='shop_title'"; $shop_title = $db->getOne($sql); $smarty->assign('shop_title', $shop_title); //獲取配送方式 // $modules = read_modules('../includes/modules/shipping'); $directory = ROOT_PATH . 'includes/modules/shipping'; $dir = @opendir($directory); $set_modules = true; $modules = array(); while (false !== ($file = @readdir($dir))) { if (preg_match("/^.*?\.php$/", $file)) { if ($file != 'express.php') { include_once($directory. '/' .$file); } } } @closedir($dir); unset($set_modules); foreach ($modules AS $key => $value) { ksort($modules[$key]); } ksort($modules); for ($i = 0; $i < count($modules); $i++) { $lang_file = ROOT_PATH.'languages/' .$_CFG['lang']. '/shipping/' .$modules[$i]['code']. '.php'; if (file_exists($lang_file)) { include_once($lang_file); } $modules[$i]['name'] = $_LANG[$modules[$i]['code']]; $modules[$i]['desc'] = $_LANG[$modules[$i]['desc']]; $modules[$i]['insure_fee'] = empty($modules[$i]['insure'])? 0 : $modules[$i]['insure']; $modules[$i]['cod'] = $modules[$i]['cod']; $modules[$i]['install'] = 0; } $smarty->assign('modules', $modules); unset($modules); //獲取支付方式 $modules = read_modules('../includes/modules/payment'); for ($i = 0; $i < count($modules); $i++) { $code = $modules[$i]['code']; $modules[$i]['name'] = $_LANG[$modules[$i]['code']]; if (!isset($modules[$i]['pay_fee'])) { $modules[$i]['pay_fee'] = 0; } $modules[$i]['desc'] = $_LANG[$modules[$i]['desc']]; } // $modules[$i]['install'] = '0'; $smarty->assign('modules_payment', $modules); assign_query_info(); $smarty->assign('ur_here', $_LANG['ur_config']); $smarty->display('setting_first.htm'); } /*------------------------------------------------------ */ //-- 開店嚮導第二步 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'second') { admin_priv('shop_config'); $shop_name = empty($_POST['shop_name']) ? '' : $_POST['shop_name'] ; $shop_title = empty($_POST['shop_title']) ? '' : $_POST['shop_title'] ; $shop_country = empty($_POST['shop_country']) ? '' : intval($_POST['shop_country']); $shop_province = empty($_POST['shop_province']) ? '' : intval($_POST['shop_province']); $shop_city = empty($_POST['shop_city']) ? '' : intval($_POST['shop_city']); $shop_address = empty($_POST['shop_address']) ? '' : $_POST['shop_address'] ; $shipping = empty($_POST['shipping']) ? '' : $_POST['shipping']; $payment = empty($_POST['payment']) ? '' : $_POST['payment']; if(!empty($shop_name)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . " SET value = '$shop_name' WHERE code = 'shop_name'"; $db->query($sql); } if(!empty($shop_title)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . " SET value = '$shop_title' WHERE code = 'shop_title'"; $db->query($sql); } if(!empty($shop_address)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . " SET value = '$shop_address' WHERE code = 'shop_address'"; $db->query($sql); } if(!empty($shop_country)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . "SET value = '$shop_country' WHERE code='shop_country'"; $db->query($sql); } if(!empty($shop_province)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . "SET value = '$shop_province' WHERE code='shop_province'"; $db->query($sql); } if(!empty($shop_city)) { $sql = 'UPDATE ' . $ecs->table('shop_config') . "SET value = '$shop_city' WHERE code='shop_city'"; $db->query($sql); } //設置配送方式 if(!empty($shipping)) { $shop_add = read_modules('../includes/modules/shipping'); foreach ($shop_add as $val) { $mod_shop[] = $val['code']; } $mod_shop = implode(',',$mod_shop); $set_modules = true; if(strpos($mod_shop,$shipping) === false) { exit; } else { include_once(ROOT_PATH . 'includes/modules/shipping/' . $shipping . '.php'); } $sql = "SELECT shipping_id FROM " .$ecs->table('shipping'). " WHERE shipping_code = '$shipping'"; $shipping_id = $db->GetOne($sql); if($shipping_id <= 0) { $insure = empty($modules[0]['insure']) ? 0 : $modules[0]['insure']; $sql = "INSERT INTO " . $ecs->table('shipping') . " (" . "shipping_code, shipping_name, shipping_desc, insure, support_cod, enabled" . ") VALUES (" . "'" . addslashes($modules[0]['code']). "', '" . addslashes($_LANG[$modules[0]['code']]) . "', '" . addslashes($_LANG[$modules[0]['desc']]) . "', '$insure', '" . intval($modules[0]['cod']) . "', 1)"; $db->query($sql); $shipping_id = $db->insert_Id(); } //設置配送區域 $area_name = empty($_POST['area_name']) ? '' : $_POST['area_name']; if(!empty($area_name)) { $sql = "SELECT shipping_area_id FROM " .$ecs->table("shipping_area"). " WHERE shipping_id='$shipping_id' AND shipping_area_name='$area_name'"; $area_id = $db->getOne($sql); if($area_id <= 0) { $config = array(); foreach ($modules[0]['configure'] AS $key => $val) { $config[$key]['name'] = $val['name']; $config[$key]['value'] = $val['value']; } $count = count($config); $config[$count]['name'] = 'free_money'; $config[$count]['value'] = 0; /* 如果支持貨到付款,則允許設置貨到付款支付費用 */ if ($modules[0]['cod']) { $count++; $config[$count]['name'] = 'pay_fee'; $config[$count]['value'] = make_semiangle(0); } $sql = "INSERT INTO " .$ecs->table('shipping_area'). " (shipping_area_name, shipping_id, configure) ". "VALUES" . " ('$area_name', '$shipping_id', '" .serialize($config). "')"; $db->query($sql); $area_id = $db->insert_Id(); } $region_id = empty($_POST['shipping_country']) ? 1 : intval($_POST['shipping_country']); $region_id = empty($_POST['shipping_province']) ? $region_id : intval($_POST['shipping_province']); $region_id = empty($_POST['shipping_city']) ? $region_id : intval($_POST['shipping_city']); $region_id = empty($_POST['shipping_district']) ? $region_id : intval($_POST['shipping_district']); /* 添加選定的城市和地區 */ $sql = "REPLACE INTO ".$ecs->table('area_region')." (shipping_area_id, region_id) VALUES ('$area_id', '$region_id')"; $db->query($sql); } } unset($modules); if(!empty($payment)) { /* 取相應插件信息 */ $set_modules = true; include_once(ROOT_PATH.'includes/modules/payment/' . $payment . '.php'); $pay_config = array(); if (isset($_REQUEST['cfg_value']) && is_array($_REQUEST['cfg_value'])) { for ($i = 0; $i < count($_POST['cfg_value']); $i++) { $pay_config[] = array('name' => trim($_POST['cfg_name'][$i]), 'type' => trim($_POST['cfg_type'][$i]), 'value' => trim($_POST['cfg_value'][$i]) ); } } $pay_config = serialize($pay_config); /* 安裝,檢查該支付方式是否曾經安裝過 */ $sql = "SELECT COUNT(*) FROM " . $ecs->table('payment') . " WHERE pay_code = '$payment'"; if ($db->GetOne($sql) > 0) { $sql = "UPDATE " . $ecs->table('payment') . " SET pay_config = '$pay_config'," . " enabled = '1' " . "WHERE pay_code = '$payment' LIMIT 1"; $db->query($sql); } else { // $modules = read_modules('../includes/modules/payment'); $payment_info = array(); $payment_info['name'] = $_LANG[$modules[0]['code']]; $payment_info['pay_fee'] = empty($modules[0]['pay_fee']) ? 0 : $modules[0]['pay_fee']; $payment_info['desc'] = $_LANG[$modules[0]['desc']]; $sql = "INSERT INTO " . $ecs->table('payment') . " (pay_code, pay_name, pay_desc, pay_config, is_cod, pay_fee, enabled, is_online)" . "VALUES ('$payment', '$payment_info[name]', '$payment_info[desc]', '$pay_config', '0', '$payment_info[pay_fee]', '1', '1')"; $db->query($sql); } } clear_all_files(); assign_query_info(); $smarty->assign('ur_here', $_LANG['ur_add']); $smarty->display('setting_second.htm'); } /*------------------------------------------------------ */ //-- 開店嚮導第三步 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'third') { admin_priv('goods_manage'); $good_name = empty($_POST['good_name']) ? '' : $_POST['good_name']; $good_number = empty($_POST['good_number']) ? '' : $_POST['good_number']; $good_category = empty($_POST['good_category']) ? '' : $_POST['good_category']; $good_brand = empty($_POST['good_brand']) ? '' : $_POST['good_brand']; $good_price = empty($_POST['good_price']) ? 0 : $_POST['good_price']; $good_name = empty($_POST['good_name']) ? '' : $_POST['good_name']; $is_best = empty($_POST['is_best']) ? 0 : 1; $is_new = empty($_POST['is_new']) ? 0 : 1; $is_hot = empty($_POST['is_hot']) ? 0 :1; $good_brief = empty($_POST['good_brief']) ? '' : $_POST['good_brief']; $market_price = $good_price * 1.2; if(!empty($good_category)) { if (cat_exists($good_category, 0)) { /* 同級別下不能有重複的分類名稱 */ $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)'); sys_msg($_LANG['catname_exist'], 0, $link); } } if(!empty($good_brand)) { if (brand_exists($good_brand)) { /* 同級別下不能有重複的品牌名稱 */ $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)'); sys_msg($_LANG['brand_name_exist'], 0, $link); } } $brand_id = 0; if(!empty($good_brand)) { $sql = 'INSERT INTO ' . $ecs->table('brand') . " (brand_name, is_show)" . " values('" . $good_brand . "', '1')"; $db->query($sql); $brand_id = $db->insert_Id(); } if(!empty($good_category)) { $sql = 'INSERT INTO ' . $ecs->table('category') . " (cat_name, parent_id, is_show)" . " values('" . $good_category . "', '0', '1')"; $db->query($sql); $cat_id = $db->insert_Id(); //貨號 require_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_goods.php'); $max_id = $db->getOne("SELECT MAX(goods_id) + 1 FROM ".$ecs->table('goods')); $goods_sn = generate_goods_sn($max_id); include_once(ROOT_PATH . 'includes/cls_image.php'); $image = new cls_image($_CFG['bgcolor']); if(!empty($good_name)) { /* 檢查圖片:如果有錯誤,檢查尺寸是否超過最大值;否則,檢查文件類型 */ if (isset($_FILES['goods_img']['error'])) // php 4.2 版本才支持 error { // 最大上傳文件大小 $php_maxsize = ini_get('upload_max_filesize'); $htm_maxsize = '2M'; // 商品圖片 if ($_FILES['goods_img']['error'] == 0) { if (!$image->check_img_type($_FILES['goods_img']['type'])) { sys_msg($_LANG['invalid_goods_img'], 1, array(), false); } } elseif ($_FILES['goods_img']['error'] == 1) { sys_msg(sprintf($_LANG['goods_img_too_big'], $php_maxsize), 1, array(), false); } elseif ($_FILES['goods_img']['error'] == 2) { sys_msg(sprintf($_LANG['goods_img_too_big'], $htm_maxsize), 1, array(), false); } } /* 4。1版本 */ else { // 商品圖片 if ($_FILES['goods_img']['tmp_name'] != 'none') { if (!$image->check_img_type($_FILES['goods_img']['type'])) { sys_msg($_LANG['invalid_goods_img'], 1, array(), false); } } } $goods_img = ''; // 初始化商品圖片 $goods_thumb = ''; // 初始化商品縮略圖 $original_img = ''; // 初始化原始圖片 $old_original_img = ''; // 初始化原始圖片舊圖 // 如果上傳了商品圖片,相應處理 if ($_FILES['goods_img']['tmp_name'] != '' && $_FILES['goods_img']['tmp_name'] != 'none') { $original_img = $image->upload_image($_FILES['goods_img']); // 原始圖片 if ($original_img === false) { sys_msg($image->error_msg(), 1, array(), false); } $goods_img = $original_img; // 商品圖片 /* 複製一份相冊圖片 */ $img = $original_img; // 相冊圖片 $pos = strpos(basename($img), '.'); $newname = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos); if (!copy('../' . $img, '../' . $newname)) { sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false); } $img = $newname; $gallery_img = $img; $gallery_thumb = $img; // 如果系統支持GD,縮放商品圖片,且給商品圖片和相冊圖片加水印 if ($image->gd_version() > 0 && $image->check_img_function($_FILES['goods_img']['type'])) { // 如果設置大小不為0,縮放圖片 if ($_CFG['image_width'] != 0 || $_CFG['image_height'] != 0) { $goods_img = $image->make_thumb('../'. $goods_img , $GLOBALS['_CFG']['image_width'], $GLOBALS['_CFG']['image_height']); if ($goods_img === false) { sys_msg($image->error_msg(), 1, array(), false); } } $newname = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos); if (!copy('../' . $img, '../' . $newname)) { sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false); } $gallery_img = $newname; // 加水印 if (intval($_CFG['watermark_place']) > 0 && !empty($GLOBALS['_CFG']['watermark'])) { if ($image->add_watermark('../'.$goods_img,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false) { sys_msg($image->error_msg(), 1, array(), false); } if ($image->add_watermark('../'. $gallery_img,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false) { sys_msg($image->error_msg(), 1, array(), false); } } // 相冊縮略圖 if ($_CFG['thumb_width'] != 0 || $_CFG['thumb_height'] != 0) { $gallery_thumb = $image->make_thumb('../' . $img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']); if ($gallery_thumb === false) { sys_msg($image->error_msg(), 1, array(), false); } } } else { /* 複製一份原圖 */ $pos = strpos(basename($img), '.'); $gallery_img = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos); if (!copy('../' . $img, '../' . $gallery_img)) { sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false); } $gallery_thumb = ''; } } // 未上傳,如果自動選擇生成,且上傳了商品圖片,生成所略圖 if (!empty($original_img)) { // 如果設置縮略圖大小不為0,生成縮略圖 if ($_CFG['thumb_width'] != 0 || $_CFG['thumb_height'] != 0) { $goods_thumb = $image->make_thumb('../' . $original_img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']); if ($goods_thumb === false) { sys_msg($image->error_msg(), 1, array(), false); } } else { $goods_thumb = $original_img; } } $sql = 'INSERT INTO ' . $ecs->table('goods') . "(goods_name, goods_sn, goods_number, cat_id, brand_id, goods_brief, shop_price, market_price, goods_img, goods_thumb, original_img,add_time, last_update, is_best, is_new, is_hot)" . "VALUES('$good_name', '$goods_sn', '$good_number', '$cat_id', '$brand_id', '$good_brief', '$good_price'," . " '$market_price', '$goods_img', '$goods_thumb', '$original_img','" . gmtime() . "', '". gmtime() . "', '$is_best', '$is_new', '$is_hot')"; $db->query($sql); $good_id = $db->insert_id(); /* 如果有圖片,把商品圖片加入圖片相冊 */ if (isset($img)) { $sql = "INSERT INTO " . $ecs->table('goods_gallery') . " (goods_id, img_url, img_desc, thumb_url, img_original) " . "VALUES ('$good_id', '$gallery_img', '', '$gallery_thumb', '$img')"; $db->query($sql); } } } assign_query_info(); // $smarty->assign('ur_here', '開店嚮導-添加商品'); $smarty->display('setting_third.htm'); } /*------------------------------------------------------ */ //-- 關於 ECSHOP /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'about_us') { assign_query_info(); $smarty->display('about_us.htm'); } /*------------------------------------------------------ */ //-- 拖動的幀 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'drag') { $smarty->display('drag.htm');; } /*------------------------------------------------------ */ //-- 檢查訂單 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'check_order') { if (empty($_SESSION['last_check'])) { $_SESSION['last_check'] = gmtime(); make_json_result('', '', array('new_orders' => 0, 'new_paid' => 0)); } /* 新訂單 */ $sql = 'SELECT COUNT(*) FROM ' . $ecs->table('order_info'). " WHERE add_time >= '$_SESSION[last_check]'"; $arr['new_orders'] = $db->getOne($sql); /* 新付款的訂單 */ $sql = 'SELECT COUNT(*) FROM '.$ecs->table('order_info'). ' WHERE pay_time >= ' . $_SESSION['last_check']; $arr['new_paid'] = $db->getOne($sql); $_SESSION['last_check'] = gmtime(); if (!(is_numeric($arr['new_orders']) && is_numeric($arr['new_paid']))) { make_json_error($db->error()); } else { make_json_result('', '', $arr); } } /*------------------------------------------------------ */ //-- Totolist操作 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'save_todolist') { $content = json_str_iconv($_POST["content"]); $sql = "UPDATE" .$GLOBALS['ecs']->table('admin_user'). " SET todolist='" . $content . "' WHERE user_id = " . $_SESSION['admin_id']; $GLOBALS['db']->query($sql); } elseif ($_REQUEST['act'] == 'get_todolist') { $sql = "SELECT todolist FROM " .$GLOBALS['ecs']->table('admin_user'). " WHERE user_id = " . $_SESSION['admin_id']; $content = $GLOBALS['db']->getOne($sql); echo $content; } // 郵件群發處理 elseif ($_REQUEST['act'] == 'send_mail') { if ($_CFG['send_mail_on'] == 'off') { make_json_result('', $_LANG['send_mail_off'], 0); exit(); } $sql = "SELECT * FROM " . $ecs->table('email_sendlist') . " ORDER BY pri DESC, last_send ASC LIMIT 1"; $row = $db->getRow($sql); //發送列表為空 if (empty($row['id'])) { make_json_result('', $_LANG['mailsend_null'], 0); } //發送列表不為空,郵件地址為空 if (!empty($row['id']) && empty($row['email'])) { $sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'"; $db->query($sql); $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist')); make_json_result('', $_LANG['mailsend_skip'], array('count' => $count, 'goon' => 1)); } //查詢相關模板 $sql = "SELECT * FROM " . $ecs->table('mail_templates') . " WHERE template_id = '$row[template_id]'"; $rt = $db->getRow($sql); //如果是模板,則將已存入email_sendlist的內容作為郵件內容 //否則即是雜質,將mail_templates調出的內容作為郵件內容 if ($rt['type'] == 'template') { $rt['template_content'] = $row['email_content']; } if ($rt['template_id'] && $rt['template_content']) { if (send_mail('', $row['email'], $rt['template_subject'], $rt['template_content'], $rt['is_html'])) { //發送成功 //從列表中刪除 $sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'"; $db->query($sql); //剩餘列表數 $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist')); if($count > 0) { $msg = sprintf($_LANG['mailsend_ok'],$row['email'],$count); } else { $msg = sprintf($_LANG['mailsend_finished'],$row['email']); } make_json_result('', $msg, array('count' => $count)); } else { //發送出錯 if ($row['error'] < 3) { $time = time(); $sql = "UPDATE " . $ecs->table('email_sendlist') . " SET error = error + 1, pri = 0, last_send = '$time' WHERE id = '$row[id]'"; } else { //將出錯超次的紀錄刪除 $sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'"; } $db->query($sql); $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist')); make_json_result('', sprintf($_LANG['mailsend_fail'],$row['email']), array('count' => $count)); } } else { //無效的郵件隊列 $sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'"; $db->query($sql); $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist')); make_json_result('', sprintf($_LANG['mailsend_fail'],$row['email']), array('count' => $count)); } } /*------------------------------------------------------ */ //-- license操作 /*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'license') { $is_ajax = $_GET['is_ajax']; if (isset($is_ajax) && $is_ajax) { // license 檢查 include_once(ROOT_PATH . 'includes/cls_transport.php'); include_once(ROOT_PATH . 'includes/cls_json.php'); include_once(ROOT_PATH . 'includes/lib_main.php'); include_once(ROOT_PATH . 'includes/lib_license.php'); $license = license_check(); switch ($license['flag']) { case 'login_succ': if (isset($license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str']) && $license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str'] != '') { make_json_result(process_login_license($license['request']['info']['service']['ecshop_b2c']['cert_auth'])); } else { make_json_error(0); } break; case 'login_fail': case 'login_ping_fail': make_json_error(0); break; case 'reg_succ': $_license = license_check(); switch ($_license['flag']) { case 'login_succ': if (isset($_license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str']) && $_license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str'] != '') { make_json_result(process_login_license($license['request']['info']['service']['ecshop_b2c']['cert_auth'])); } else { make_json_error(0); } break; case 'login_fail': case 'login_ping_fail': make_json_error(0); break; } break; case 'reg_fail': case 'reg_ping_fail': make_json_error(0); break; } } else { make_json_error(0); } } /** * license check * @return bool */ function license_check() { // return 返回數組 $return_array = array(); // 取出網店 license $license = get_shop_license(); // 檢測網店 license if (!empty($license['certificate_id']) && !empty($license['token']) && !empty($license['certi'])) { // license(登錄) $return_array = license_login(); } else { // license(註冊) $return_array = license_reg(); } return $return_array; } ?>
Java
/* Copyright (C) 2022, Specify Collections Consortium * * Specify Collections Consortium, Biodiversity Institute, University of Kansas, * 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, support@specifysoftware.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package edu.ku.brc.af.ui.forms.persist; import static edu.ku.brc.helpers.XMLHelper.getAttr; import static edu.ku.brc.ui.UIHelper.createDuplicateJGoodiesDef; import static edu.ku.brc.ui.UIRegistry.getResourceString; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Vector; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ScrollPaneConstants; import javax.swing.table.DefaultTableModel; import org.apache.commons.betwixt.XMLIntrospector; import org.apache.commons.betwixt.io.BeanWriter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.dom4j.Element; import org.dom4j.Node; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import edu.ku.brc.af.core.db.DBFieldInfo; import edu.ku.brc.af.core.db.DBRelationshipInfo; import edu.ku.brc.af.core.db.DBTableChildIFace; import edu.ku.brc.af.core.db.DBTableIdMgr; import edu.ku.brc.af.core.db.DBTableInfo; import edu.ku.brc.af.prefs.AppPreferences; import edu.ku.brc.af.ui.forms.FormDataObjIFace; import edu.ku.brc.af.ui.forms.FormHelper; import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterIFace; import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterMgr; import edu.ku.brc.af.ui.forms.validation.TypeSearchForQueryFactory; import edu.ku.brc.ui.CustomFrame; import edu.ku.brc.ui.UIHelper; import edu.ku.brc.ui.UIRegistry; import edu.ku.brc.helpers.XMLHelper; /** * Factory that creates Views from ViewSet files. This class uses the singleton ViewSetMgr to verify the View Set Name is unique. * If it is not unique than it throws an exception.<br> In this case a "form" is really the definition of a form. The form's object hierarchy * is used to creates the forms using Swing UI objects. The classes will also be used by the forms editor. * @code_status Beta ** * @author rods */ public class ViewLoader { public static final int DEFAULT_ROWS = 4; public static final int DEFAULT_COLS = 10; public static final int DEFAULT_SUBVIEW_ROWS = 5; // Statics private static final Logger log = Logger.getLogger(ViewLoader.class); private static final ViewLoader instance = new ViewLoader(); private static final String ID = "id"; private static final String NAME = "name"; private static final String TYPE = "type"; private static final String LABEL = "label"; private static final String DESC = "desc"; private static final String TITLE = "title"; private static final String CLASSNAME = "class"; private static final String GETTABLE = "gettable"; private static final String SETTABLE = "settable"; private static final String INITIALIZE = "initialize"; private static final String DSPUITYPE = "dspuitype"; private static final String VALIDATION = "validation"; private static final String ISREQUIRED = "isrequired"; private static final String RESOURCELABELS = "useresourcelabels"; // Data Members protected boolean doingResourceLabels = false; protected String viewSetName = null; // Members needed for verification protected static boolean doFieldVerification = true; protected static boolean isTreeClass = false; protected static DBTableInfo fldVerTableInfo = null; protected static FormViewDef fldVerFormViewDef = null; protected static String colDefType = null; protected static CustomFrame verifyDlg = null; protected FieldVerifyTableModel fldVerTableModel = null; // Debug //protected static ViewDef gViewDef = null; static { doFieldVerification = AppPreferences.getLocalPrefs().getBoolean("verify_field_names", false); } /** * Default Constructor * */ protected ViewLoader() { // do nothing } /** * Creates the view. * @param element the element to build the View from * @param altViewsViewDefName the hashtable to track the AltView's ViewDefName * @return the View * @throws Exception */ protected static ViewIFace createView(final Element element, final Hashtable<AltViewIFace, String> altViewsViewDefName) throws Exception { String name = element.attributeValue(NAME); String objTitle = getAttr(element, "objtitle", null); String className = element.attributeValue(CLASSNAME); String desc = getDesc(element); String businessRules = getAttr(element, "busrules", null); boolean isInternal = getAttr(element, "isinternal", true); DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(className); if (ti != null && StringUtils.isEmpty(objTitle)) { objTitle = ti.getTitle(); } View view = new View(instance.viewSetName, name, objTitle, className, businessRules != null ? businessRules.trim() : null, getAttr(element, "usedefbusrule", true), isInternal, desc); // Later we should get this from a properties file. if (ti != null) { view.setTitle(ti.getTitle()); } /*if (!isInternal) { System.err.println(StringUtils.replace(name, " ", "_")+"="+UIHelper.makeNamePretty(name)); }*/ Element altviews = (Element)element.selectSingleNode("altviews"); if (altviews != null) { AltViewIFace defaultAltView = null; AltView.CreationMode defaultMode = AltView.parseMode(getAttr(altviews, "mode", ""), AltViewIFace.CreationMode.VIEW); String selectorName = altviews.attributeValue("selector"); view.setDefaultMode(defaultMode); view.setSelectorName(selectorName); Hashtable<String, Boolean> nameCheckHash = new Hashtable<String, Boolean>(); // iterate through child elements for ( Iterator<?> i = altviews.elementIterator( "altview" ); i.hasNext(); ) { Element altElement = (Element) i.next(); AltView.CreationMode mode = AltView.parseMode(getAttr(altElement, "mode", ""), AltViewIFace.CreationMode.VIEW); String altName = altElement.attributeValue(NAME); String viewDefName = altElement.attributeValue("viewdef"); String title = altElement.attributeValue(TITLE); boolean isValidated = getAttr(altElement, "validated", mode == AltViewIFace.CreationMode.EDIT); boolean isDefault = getAttr(altElement, "default", false); // Make sure we only have one default view if (defaultAltView != null && isDefault) { isDefault = false; } // Check to make sure all the AlViews have different names. Boolean nameExists = nameCheckHash.get(altName); if (nameExists == null) // no need to check the boolean { AltView altView = new AltView(view, altName, title, mode, isValidated, isDefault, null); // setting a null viewdef altViewsViewDefName.put(altView, viewDefName); if (StringUtils.isNotEmpty(selectorName)) { altView.setSelectorName(selectorName); String selectorValue = altElement.attributeValue("selector_value"); if (StringUtils.isNotEmpty(selectorValue)) { altView.setSelectorValue(selectorValue); } else { FormDevHelper.appendFormDevError("Selector Value is missing for viewDefName["+viewDefName+"] altName["+altName+"]"); } } if (defaultAltView == null && isDefault) { defaultAltView = altView; } view.addAltView(altView); nameCheckHash.put(altName, true); } else { log.error("The altView name["+altName+"] already exists!"); } nameCheckHash.clear(); // why not? } // No default Alt View was indicated, so choose the first one (if there is one) if (defaultAltView == null && view.getAltViews() != null && view.getAltViews().size() > 0) { view.getAltViews().get(0).setDefault(true); } } return view; } /** * Creates a ViewDef * @param element the element to build the ViewDef from * @return a viewdef * @throws Exception */ private static ViewDef createViewDef(final Element element) throws Exception { String name = element.attributeValue(NAME); String className = element.attributeValue(CLASSNAME); String gettableClassName = element.attributeValue(GETTABLE); String settableClassName = element.attributeValue(SETTABLE); String desc = getDesc(element); String resLabels = getAttr(element, RESOURCELABELS, "false"); boolean useResourceLabels = resLabels.equals("true"); if (isEmpty(name)) { FormDevHelper.appendFormDevError("Name is null for element["+element.asXML()+"]"); return null; } if (isEmpty(className)) { FormDevHelper.appendFormDevError("className is null. name["+name+"] for element["+element.asXML()+"]"); return null; } if (isEmpty(gettableClassName)) { FormDevHelper.appendFormDevError("gettableClassName Name is null.name["+name+"] classname["+className+"]"); return null; } DBTableInfo tableinfo = DBTableIdMgr.getInstance().getByClassName(className); ViewDef.ViewType type = null; try { type = ViewDefIFace.ViewType.valueOf(element.attributeValue(TYPE)); } catch (Exception ex) { String msg = "view["+name+"] has illegal type["+element.attributeValue(TYPE)+"]"; log.error(msg, ex); FormDevHelper.appendFormDevError(msg, ex); return null; } ViewDef viewDef = null;//new ViewDef(type, name, className, gettableClassName, settableClassName, desc); switch (type) { case rstable: case formtable : case form : viewDef = createFormViewDef(element, type, name, className, gettableClassName, settableClassName, desc, useResourceLabels, tableinfo); break; case table : //view = createTableView(element, id, name, className, gettableClassName, settableClassName, // desc, instance.doingResourceLabels, isValidated); break; case field : //view = createFormView(FormView.ViewType.field, element, id, name, gettableClassName, settableClassName, // className, desc, instance.doingResourceLabels, isValidated); break; case iconview: viewDef = createIconViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels); break; } return viewDef; } /** * Gets the optional description text * @param element the parent element of the desc node * @return the string of the text or null */ protected static String getDesc(final Element element) { String desc = null; Element descElement = (Element)element.selectSingleNode(DESC); if (descElement != null) { desc = descElement.getTextTrim(); } return desc; } /** * Fill the Vector with all the views from the DOM document * @param doc the DOM document conforming to form.xsd * @param views the list to be filled * @throws Exception for duplicate view set names or if a Form ID is not unique */ public static String getViews(final Element doc, final Hashtable<String, ViewIFace> views, final Hashtable<AltViewIFace, String> altViewsViewDefName) throws Exception { instance.viewSetName = doc.attributeValue(NAME); /* System.err.println("#################################################"); System.err.println("# "+instance.viewSetName); System.err.println("#################################################"); */ Element viewsElement = (Element)doc.selectSingleNode("views"); if (viewsElement != null) { for ( Iterator<?> i = viewsElement.elementIterator( "view" ); i.hasNext(); ) { Element element = (Element) i.next(); // assume element is NOT null, if it is null it will cause an exception ViewIFace view = createView(element, altViewsViewDefName); if (view != null) { if (views.get(view.getName()) == null) { views.put(view.getName(), view); } else { String msg = "View Set ["+instance.viewSetName+"] ["+view.getName()+"] is not unique."; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } return instance.viewSetName; } /** * Fill the Vector with all the views from the DOM document * @param doc the DOM document conforming to form.xsd * @param viewDefs the list to be filled * @param doMapDefinitions tells it to map and clone the definitions for formtables (use false for the FormEditor) * @return the viewset name * @throws Exception for duplicate view set names or if a ViewDef name is not unique */ public static String getViewDefs(final Element doc, final Hashtable<String, ViewDefIFace> viewDefs, @SuppressWarnings("unused") final Hashtable<String, ViewIFace> views, final boolean doMapDefinitions) throws Exception { colDefType = AppPreferences.getLocalPrefs().get("ui.formatting.formtype", UIHelper.getOSTypeAsStr()); instance.viewSetName = doc.attributeValue(NAME); Element viewDefsElement = (Element)doc.selectSingleNode("viewdefs"); if (viewDefsElement != null) { for ( Iterator<?> i = viewDefsElement.elementIterator( "viewdef" ); i.hasNext(); ) { Element element = (Element) i.next(); // assume element is NOT null, if it is null it will cause an exception ViewDef viewDef = createViewDef(element); if (viewDef != null) { if (viewDefs.get(viewDef.getName()) == null) { viewDefs.put(viewDef.getName(), viewDef); } else { String msg = "View Set ["+instance.viewSetName+"] the View Def Name ["+viewDef.getName()+"] is not unique."; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } if (doMapDefinitions) { mapDefinitionViewDefs(viewDefs); } } return instance.viewSetName; } /** * Re-maps and clones the definitions. * @param viewDefs the hash table to be mapped * @throws Exception */ public static void mapDefinitionViewDefs(final Hashtable<String, ViewDefIFace> viewDefs) throws Exception { // Now that all the definitions have been read in // cycle thru and have all the tableform objects clone there definitions for (ViewDefIFace viewDef : new Vector<ViewDefIFace>(viewDefs.values())) { if (viewDef.getType() == ViewDefIFace.ViewType.formtable) { String viewDefName = ((FormViewDefIFace)viewDef).getDefinitionName(); if (viewDefName != null) { //log.debug(viewDefName); ViewDefIFace actualDef = viewDefs.get(viewDefName); if (actualDef != null) { viewDefs.remove(viewDef.getName()); actualDef = (ViewDef)actualDef.clone(); actualDef.setType(ViewDefIFace.ViewType.formtable); actualDef.setName(viewDef.getName()); viewDefs.put(actualDef.getName(), actualDef); } else { String msg = "Couldn't find the ViewDef for formtable definition name["+((FormViewDefIFace)viewDef).getDefinitionName()+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } } /** * Processes all the AltViews * @param aFormView the form they should be associated with * @param aElement the element to process */ public static Hashtable<String, String> getEnableRules(final Element element) { Hashtable<String, String> rulesList = new Hashtable<String, String>(); if (element != null) { Element enableRules = (Element)element.selectSingleNode("enableRules"); if (enableRules != null) { // iterate through child elements of root with element name "foo" for ( Iterator<?> i = enableRules.elementIterator( "rule" ); i.hasNext(); ) { Element ruleElement = (Element) i.next(); String id = getAttr(ruleElement, ID, ""); if (isNotEmpty(id)) { rulesList.put(id, ruleElement.getTextTrim()); } else { String msg = "The name is missing for rule["+ruleElement.getTextTrim()+"] is missing."; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } else { log.error("View Set ["+instance.viewSetName+"] element ["+element+"] is null."); } return rulesList; } /** * Gets the string (or creates one) from a columnDef * @param element the DOM element to process * @param attrName the name of the element to go get all the elements (strings) from * @param numRows the number of rows * @param item * @return the String representing the column definition for JGoodies */ protected static String createDef(final Element element, final String attrName, final int numRows, final FormViewDef.JGDefItem item) { Element cellDef = null; if (attrName.equals("columnDef")) { // For columnDef(s) we can mark one or more as being platform specific // but if we can't find a default one (no 'os' defined) // then we ultimately pick the first one. List<?> list = element.selectNodes(attrName); if (list.size() == 1) { cellDef = (Element)list.get(0); // pick the first one if there is only one. } else { String osTypeStr = UIHelper.getOSTypeAsStr(); Element defCD = null; Element defOSCD = null; Element ovrOSCD = null; for (Object obj : list) { Element ce = (Element)obj; String osType = getAttr(ce, "os", null); if (osType == null) { defCD = ce; // ok we found the default one } else { if (osType.equals(osTypeStr)) { defOSCD = ce; // we found the matching our OS } if (colDefType != null && osType.equals(colDefType)) { ovrOSCD = ce; // we found the one matching prefs } } } if (ovrOSCD != null) { cellDef = ovrOSCD; } else if (defOSCD != null) { cellDef = defOSCD; } else if (defCD != null) { cellDef = defCD; } else { // ok, we couldn't find one for our platform, so use the default // or pick the first one. cellDef = (Element)list.get(0); } } } else { // this is for rowDef cellDef = (Element)element.selectSingleNode(attrName); } if (cellDef != null) { String cellText = cellDef.getText(); String cellStr = getAttr(cellDef, "cell", null); String sepStr = getAttr(cellDef, "sep", null); item.setDefStr(cellText); item.setCellDefStr(cellStr); item.setSepDefStr(sepStr); if (StringUtils.isNotEmpty(cellStr) && StringUtils.isNotEmpty(sepStr)) { boolean auto = getAttr(cellDef, "auto", false); item.setAuto(auto); if (auto) { String autoStr = createDuplicateJGoodiesDef(cellStr, sepStr, numRows) + (StringUtils.isNotEmpty(cellText) ? ("," + cellText) : ""); item.setDefStr(autoStr); return autoStr; } // else FormDevHelper.appendFormDevError("Element ["+element.getName()+"] Cell or Sep is null for 'dup' or 'auto 'on column def."); return ""; } // else item.setAuto(false); return cellText; } // else String msg = "Element ["+element.getName()+"] must have a columnDef"; log.error(msg); FormDevHelper.appendFormDevError(msg); return ""; } /** * Returns a resource string if it is suppose to * @param label the label or the label key * @return Returns a resource string if it is suppose to */ protected static String getResourceLabel(final String label) { if (isNotEmpty(label) && StringUtils.deleteWhitespace(label).length() > 0) { return instance.doingResourceLabels ? getResourceString(label) : label; } // else return ""; } /** * Returns a Label from the cell and gets the resource string for it if necessary * @param cellElement the cell * @param labelId the Id of the resource or the string * @return the localized string (if necessary) */ protected static String getLabel(final Element cellElement) { String lbl = getAttr(cellElement, LABEL, null); if (lbl == null || lbl.equals("##")) { return "##"; } return getResourceLabel(lbl); } /** * Processes all the rows * @param element the parent DOM element of the rows * @param cellRows the list the rows are to be added to */ protected static void processRows(final Element element, final List<FormRowIFace> cellRows, final DBTableInfo tableinfo) { Element rowsElement = (Element)element.selectSingleNode("rows"); if (rowsElement != null) { byte rowNumber = 0; for ( Iterator<?> i = rowsElement.elementIterator( "row" ); i.hasNext(); ) { Element rowElement = (Element) i.next(); FormRow formRow = new FormRow(); formRow.setRowNumber(rowNumber); for ( Iterator<?> cellIter = rowElement.elementIterator( "cell" ); cellIter.hasNext(); ) { Element cellElement = (Element)cellIter.next(); String cellId = getAttr(cellElement, ID, ""); String cellName = getAttr(cellElement, NAME, cellId); // let the name default to the id if it doesn't have a name int colspan = getAttr(cellElement, "colspan", 1); int rowspan = getAttr(cellElement, "rowspan", 1); /*boolean isReq = getAttr(cellElement, ISREQUIRED, false); if (isReq) { System.err.println(String.format("%s\t%s\t%s\t%s", gViewDef.getName(), cellId, cellName, tableinfo != null ? tableinfo.getTitle() : "N/A")); }*/ FormCell.CellType cellType = null; FormCellIFace cell = null; try { cellType = FormCellIFace.CellType.valueOf(cellElement.attributeValue(TYPE)); } catch (java.lang.IllegalArgumentException ex) { FormDevHelper.appendFormDevError(ex.toString()); FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] Type[%s]", cellName, cellId, cellElement.attributeValue(TYPE))); return; } if (doFieldVerification && fldVerTableInfo != null && cellType == FormCellIFace.CellType.field && StringUtils.isNotEmpty(cellId) && !cellName.equals("this")) { processFieldVerify(cellName, cellId, rowNumber); } switch (cellType) { case label: { cell = formRow.addCell(new FormCellLabel(cellId, cellName, getLabel(cellElement), getAttr(cellElement, "labelfor", ""), getAttr(cellElement, "icon", null), getAttr(cellElement, "recordobj", false), colspan)); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cell.setProperties(UIHelper.parseProperties(initialize)); } break; } case separator: { cell = formRow.addCell(new FormCellSeparator(cellId, cellName, getLabel(cellElement), getAttr(cellElement, "collapse", ""), colspan)); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cell.setProperties(UIHelper.parseProperties(initialize)); } break; } case field: { String uitypeStr = getAttr(cellElement, "uitype", ""); String format = getAttr(cellElement, "format", ""); String formatName = getAttr(cellElement, "formatname", ""); String uiFieldFormatterName = getAttr(cellElement, "uifieldformatter", ""); int cols = getAttr(cellElement, "cols", DEFAULT_COLS); // XXX PREF for default width of text field int rows = getAttr(cellElement, "rows", DEFAULT_ROWS); // XXX PREF for default heightof text area String validationType = getAttr(cellElement, "valtype", "Changed"); String validationRule = getAttr(cellElement, VALIDATION, ""); String initialize = getAttr(cellElement, INITIALIZE, ""); boolean isRequired = getAttr(cellElement, ISREQUIRED, false); String pickListName = getAttr(cellElement, "picklist", ""); if (isNotEmpty(format) && isNotEmpty(formatName)) { String msg = "Both format and formatname cannot both be set! ["+cellName+"] ignoring format"; log.error(msg); FormDevHelper.appendFormDevError(msg); format = ""; } Properties properties = UIHelper.parseProperties(initialize); if (isEmpty(uitypeStr)) { // XXX DEBUG ONLY PLease REMOVE LATER //log.debug("***************************************************************************"); //log.debug("***** Cell Id["+cellId+"] Name["+cellName+"] uitype is empty and should be 'text'. (Please Fix!)"); //log.debug("***************************************************************************"); uitypeStr = "text"; } // THis switch is used to get the "display type" and // set up other vars needed for creating the controls FormCellFieldIFace.FieldType uitype = null; try { uitype = FormCellFieldIFace.FieldType.valueOf(uitypeStr); } catch (java.lang.IllegalArgumentException ex) { FormDevHelper.appendFormDevError(ex.toString()); FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] uitype[%s] is in error", cellName, cellId, uitypeStr)); uitype = FormCellFieldIFace.FieldType.text; // default to text } String dspUITypeStr = null; switch (uitype) { case textarea: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextarea"); break; case textareabrief: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textareabrief"); break; case querycbx: { dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textfieldinfo"); String fmtName = TypeSearchForQueryFactory.getInstance().getDataObjFormatterName(properties.getProperty("name")); if (isEmpty(formatName) && isNotEmpty(fmtName)) { formatName = fmtName; } break; } case formattedtext: { validationRule = getAttr(cellElement, VALIDATION, "formatted"); // XXX Is this OK? dspUITypeStr = getAttr(cellElement, DSPUITYPE, "formattedtext"); //------------------------------------------------------- // This part should be moved to the ViewFactory // because it is the only part that need the Schema Information //------------------------------------------------------- if (isNotEmpty(uiFieldFormatterName)) { UIFieldFormatterIFace uiFormatter = UIFieldFormatterMgr.getInstance().getFormatter(uiFieldFormatterName); if (uiFormatter == null) { String msg = "Couldn't find formatter["+uiFieldFormatterName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); uiFieldFormatterName = ""; uitype = FormCellFieldIFace.FieldType.text; } } else // ok now check the schema for the UI formatter { if (tableinfo != null) { DBFieldInfo fieldInfo = tableinfo.getFieldByName(cellName); if (fieldInfo != null) { if (fieldInfo.getFormatter() != null) { uiFieldFormatterName = fieldInfo.getFormatter().getName(); } else if (fieldInfo.getDataClass().isAssignableFrom(Date.class) || fieldInfo.getDataClass().isAssignableFrom(Calendar.class)) { String msg = "Missing Date Formatter for ["+cellName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); uiFieldFormatterName = "Date"; UIFieldFormatterIFace uiFormatter = UIFieldFormatterMgr.getInstance().getFormatter(uiFieldFormatterName); if (uiFormatter == null) { uiFieldFormatterName = ""; uitype = FormCellFieldIFace.FieldType.text; } } else { uiFieldFormatterName = ""; uitype = FormCellFieldIFace.FieldType.text; } } } } break; } case url: dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr); properties = UIHelper.parseProperties(initialize); break; case list: case image: case tristate: case checkbox: case password: dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr); break; case plugin: case button: dspUITypeStr = getAttr(cellElement, DSPUITYPE, uitypeStr); properties = UIHelper.parseProperties(initialize); String ttl = properties.getProperty(TITLE); if (ttl != null) { properties.put(TITLE, getResourceLabel(ttl)); } break; case spinner: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextfield"); properties = UIHelper.parseProperties(initialize); break; case combobox: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "textpl"); if (tableinfo != null) { DBFieldInfo fieldInfo = tableinfo.getFieldByName(cellName); if (fieldInfo != null) { if (StringUtils.isNotEmpty(pickListName)) { fieldInfo.setPickListName(pickListName); } else { pickListName = fieldInfo.getPickListName(); } } } break; default: dspUITypeStr = getAttr(cellElement, DSPUITYPE, "dsptextfield"); break; } //switch FormCellFieldIFace.FieldType dspUIType = FormCellFieldIFace.FieldType.valueOf(dspUITypeStr); try { dspUIType = FormCellFieldIFace.FieldType.valueOf(dspUITypeStr); } catch (java.lang.IllegalArgumentException ex) { FormDevHelper.appendFormDevError(ex.toString()); FormDevHelper.appendFormDevError(String.format("Cell Name[%s] Id[%s] dspuitype[%s] is in error", cellName, cellId, dspUIType)); uitype = FormCellFieldIFace.FieldType.label; // default to text } // check to see see if the validation is a node in the cell if (isEmpty(validationRule)) { Element valNode = (Element)cellElement.selectSingleNode(VALIDATION); if (valNode != null) { String str = valNode.getTextTrim(); if (isNotEmpty(str)) { validationRule = str; } } } boolean isEncrypted = getAttr(cellElement, "isencrypted", false); boolean isReadOnly = uitype == FormCellFieldIFace.FieldType.dsptextfield || uitype == FormCellFieldIFace.FieldType.dsptextarea || uitype == FormCellFieldIFace.FieldType.label; FormCellField field = new FormCellField(FormCellIFace.CellType.field, cellId, cellName, uitype, dspUIType, format, formatName, uiFieldFormatterName, isRequired, cols, rows, colspan, rowspan, validationType, validationRule, isEncrypted); String labelStr = uitype == FormCellFieldIFace.FieldType.checkbox ? getLabel(cellElement) : getAttr(cellElement, "label", ""); field.setLabel(labelStr); field.setReadOnly(getAttr(cellElement, "readonly", isReadOnly)); field.setDefaultValue(getAttr(cellElement, "default", "")); field.setPickListName(pickListName); field.setChangeListenerOnly(getAttr(cellElement, "changesonly", true) && !isRequired); field.setProperties(properties); cell = formRow.addCell(field); break; } case command: { cell = formRow.addCell(new FormCellCommand(cellId, cellName, getLabel(cellElement), getAttr(cellElement, "commandtype", ""), getAttr(cellElement, "action", ""))); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cell.setProperties(UIHelper.parseProperties(initialize)); } break; } case panel: { FormCellPanel cellPanel = new FormCellPanel(cellId, cellName, getAttr(cellElement, "paneltype", ""), getAttr(cellElement, "coldef", "p"), getAttr(cellElement, "rowdef", "p"), colspan, rowspan); String initialize = getAttr(cellElement, INITIALIZE, null); if (StringUtils.isNotEmpty(initialize)) { cellPanel.setProperties(UIHelper.parseProperties(initialize)); } processRows(cellElement, cellPanel.getRows(), tableinfo); fixLabels(cellPanel.getName(), cellPanel.getRows(), tableinfo); cell = formRow.addCell(cellPanel); break; } case subview: { Properties properties = UIHelper.parseProperties(getAttr(cellElement, INITIALIZE, null)); String svViewSetName = cellElement.attributeValue("viewsetname"); if (isEmpty(svViewSetName)) { svViewSetName = null; } if (instance.doingResourceLabels && properties != null) { String title = properties.getProperty(TITLE); if (title != null) { properties.setProperty(TITLE, UIRegistry.getResourceString(title)); } } String viewName = getAttr(cellElement, "viewname", null); cell = formRow.addCell(new FormCellSubView(cellId, cellName, svViewSetName, viewName, cellElement.attributeValue("class"), getAttr(cellElement, "desc", ""), getAttr(cellElement, "defaulttype", null), getAttr(cellElement, "rows", DEFAULT_SUBVIEW_ROWS), colspan, rowspan, getAttr(cellElement, "single", false))); cell.setProperties(properties); break; } case iconview: { String vsName = cellElement.attributeValue("viewsetname"); if (isEmpty(vsName)) { vsName = instance.viewSetName; } String viewName = getAttr(cellElement, "viewname", null); cell = formRow.addCell(new FormCellSubView(cellId, cellName, vsName, viewName, cellElement.attributeValue("class"), getAttr(cellElement, "desc", ""), colspan, rowspan)); break; } case statusbar: { cell = formRow.addCell(new FormCell(FormCellIFace.CellType.statusbar, cellId, cellName, colspan, rowspan)); break; } default: { // what is this? log.error("Encountered unknown cell type"); continue; } } // switch cell.setIgnoreSetGet(getAttr(cellElement, "ignore", false)); } cellRows.add(formRow); rowNumber++; } } } /** * @param cellName * @param cellId * @param rowNumber */ private static void processFieldVerify(final String cellName, final String cellId, final int rowNumber) { try { boolean isOK = false; if (StringUtils.contains(cellName, '.')) { DBTableInfo tblInfo = fldVerTableInfo; String[] fieldNames = StringUtils.split(cellName, "."); for (int i=0;i<fieldNames.length-1;i++) { String type = null; DBTableChildIFace child = tblInfo.getItemByName(fieldNames[i]); if (child instanceof DBFieldInfo) { DBFieldInfo fldInfo = (DBFieldInfo)child; type = fldInfo.getType(); if (type != null) { DBTableInfo tInfo = DBTableIdMgr.getInstance().getByClassName(type); tblInfo = tInfo != null ? tInfo : tblInfo; } isOK = tblInfo.getItemByName(fieldNames[fieldNames.length-1]) != null; } else if (child instanceof DBRelationshipInfo) { DBRelationshipInfo relInfo = (DBRelationshipInfo)child; type = relInfo.getDataClass().getName(); if (type != null) { tblInfo = DBTableIdMgr.getInstance().getByClassName(type); } } //System.out.println(type); } if (tblInfo != null) { isOK = tblInfo.getItemByName(fieldNames[fieldNames.length-1]) != null; } } else { isOK = fldVerTableInfo.getItemByName(cellName) != null; } if (!isOK) { String msg = " ViewSet["+instance.viewSetName+"]\n ViewDef["+fldVerFormViewDef.getName()+"]\n The cell name ["+cellName+"] for cell with Id ["+cellId+"] is not a field\n in Data Object["+fldVerTableInfo.getName()+"]\n on Row ["+rowNumber+"]"; if (!isTreeClass) { instance.fldVerTableModel.addRow(instance.viewSetName, fldVerFormViewDef.getName(), cellId, cellName, Integer.toString(rowNumber)); } log.error(msg); } } catch (Exception ex) { log.error(ex); } } /** * @param element the DOM element for building the form * @param type the type of form to be built * @param id the id of the form * @param name the name of the form * @param className the class name of the data object * @param gettableClassName the class name of the getter * @param settableClassName the class name of the setter * @param desc the description * @param useResourceLabels whether to use resource labels * @param tableinfo table info * @return a form view of type "form" */ protected static FormViewDef createFormViewDef(final Element element, final ViewDef.ViewType type, final String name, final String className, final String gettableClassName, final String settableClassName, final String desc, final boolean useResourceLabels, final DBTableInfo tableinfo) { FormViewDef formViewDef = new FormViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels, XMLHelper.getAttr(element, "editableDlg", true)); fldVerTableInfo = null; if (type != ViewDefIFace.ViewType.formtable) { if (doFieldVerification) { if (instance.fldVerTableModel == null) { instance.createFieldVerTableModel(); } try { //log.debug(className); Class<?> classObj = Class.forName(className); if (FormDataObjIFace.class.isAssignableFrom(classObj)) { fldVerTableInfo = DBTableIdMgr.getInstance().getByClassName(className); isTreeClass = fldVerTableInfo != null && fldVerTableInfo.getFieldByName("highestChildNodeNumber") != null; fldVerFormViewDef = formViewDef; } } catch (ClassNotFoundException ex) { String msg = "ClassNotFoundException["+className+"] Name["+name+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ViewLoader.class, comments, ex); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ViewLoader.class, ex); } } List<FormRowIFace> rows = formViewDef.getRows(); instance.doingResourceLabels = useResourceLabels; //gViewDef = formViewDef; processRows(element, rows, tableinfo); instance.doingResourceLabels = false; createDef(element, "columnDef", rows.size(), formViewDef.getColumnDefItem()); createDef(element, "rowDef", rows.size(), formViewDef.getRowDefItem()); formViewDef.setEnableRules(getEnableRules(element)); fixLabels(formViewDef.getName(), rows, tableinfo); } else { Node defNode = element.selectSingleNode("definition"); if (defNode != null) { String defName = defNode.getText(); if (StringUtils.isNotEmpty(defName)) { formViewDef.setDefinitionName(defName); return formViewDef; } } String msg = "formtable is missing or has empty <defintion> node"; log.error(msg); FormDevHelper.appendFormDevError(msg); return null; } return formViewDef; } /** * @param fieldName * @param tableInfo * @return */ protected static String getTitleFromFieldName(final String fieldName, final DBTableInfo tableInfo) { DBTableChildIFace derivedCI = null; if (fieldName.indexOf(".") > -1) { derivedCI = FormHelper.getChildInfoFromPath(fieldName, tableInfo); if (derivedCI == null) { String msg = "The name 'path' ["+fieldName+"] was not valid in ViewSet ["+instance.viewSetName+"]"; FormDevHelper.appendFormDevError(msg); log.error(msg); return ""; } } DBTableChildIFace tblChild = derivedCI != null ? derivedCI : tableInfo.getItemByName(fieldName); if (tblChild == null) { String msg = "The Field Name ["+fieldName+"] was not in the Table ["+tableInfo.getTitle()+"] in ViewSet ["+instance.viewSetName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); return ""; } return tblChild.getTitle(); } /** * @param rows * @param tableInfo */ protected static void fixLabels(final String name, final List<FormRowIFace> rows, final DBTableInfo tableInfo) { if (tableInfo == null) { return; } Hashtable<String, String> fldIdMap = new Hashtable<String, String>(); for (FormRowIFace row : rows) { for (FormCellIFace cell : row.getCells()) { if (cell.getType() == FormCellIFace.CellType.field || cell.getType() == FormCellIFace.CellType.subview) { fldIdMap.put(cell.getIdent(), cell.getName()); }/* else { System.err.println("Skipping ["+cell.getIdent()+"] " + cell.getType()); }*/ } } for (FormRowIFace row : rows) { for (FormCellIFace cell : row.getCells()) { if (cell.getType() == FormCellIFace.CellType.label) { FormCellLabelIFace lblCell = (FormCellLabelIFace)cell; String label = lblCell.getLabel(); if (label.length() == 0 || label.equals("##")) { String idFor = lblCell.getLabelFor(); if (StringUtils.isNotEmpty(idFor)) { String fieldName = fldIdMap.get(idFor); if (StringUtils.isNotEmpty(fieldName)) { if (!fieldName.equals("this")) { //FormCellFieldIFace fcf = get lblCell.setLabel(getTitleFromFieldName(fieldName, tableInfo)); } } else { String msg = "Setting Label - Form control with id["+idFor+"] is not in ViewDef or Panel ["+name+"] in ViewSet ["+instance.viewSetName+"]"; log.error(msg); FormDevHelper.appendFormDevError(msg); } } } } else if (cell.getType() == FormCellIFace.CellType.field && cell instanceof FormCellFieldIFace && ((((FormCellFieldIFace)cell).getUiType() == FormCellFieldIFace.FieldType.checkbox) || (((FormCellFieldIFace)cell).getUiType() == FormCellFieldIFace.FieldType.tristate))) { FormCellFieldIFace fcf = (FormCellFieldIFace)cell; if (fcf.getLabel().equals("##")) { fcf.setLabel(getTitleFromFieldName(cell.getName(), tableInfo)); } } } } } /** * @param type the type of form to be built * @param name the name of the form * @param className the class name of the data object * @param gettableClassName the class name of the getter * @param settableClassName the class name of the setter * @param desc the description * @param useResourceLabels whether to use resource labels * @return a form view of type "form" */ protected static ViewDef createIconViewDef(final ViewDef.ViewType type, final String name, final String className, final String gettableClassName, final String settableClassName, final String desc, final boolean useResourceLabels) { ViewDef formView = new ViewDef(type, name, className, gettableClassName, settableClassName, desc, useResourceLabels); //formView.setEnableRules(getEnableRules(element)); return formView; } /** * Creates a Table Form View * @param typeName the type of form to be built * @param element the DOM element for building the form * @param name the name of the form * @param className the class name of the data object * @param gettableClassName the class name of the getter * @param settableClassName the class name of the setter * @param desc the description * @param useResourceLabels whether to use resource labels * @return a form view of type "table" */ protected static TableViewDefIFace createTableView(final Element element, final String name, final String className, final String gettableClassName, final String settableClassName, final String desc, final boolean useResourceLabels) { TableViewDefIFace tableView = new TableViewDef( name, className, gettableClassName, settableClassName, desc, useResourceLabels); //tableView.setResourceLabels(resLabels); Element columns = (Element)element.selectSingleNode("columns"); if (columns != null) { for ( Iterator<?> i = columns.elementIterator( "column" ); i.hasNext(); ) { Element colElement = (Element) i.next(); FormColumn column = new FormColumn(colElement.attributeValue(NAME), colElement.attributeValue(LABEL), getAttr(colElement, "dataobjformatter", null), getAttr(colElement, "format", null) ); tableView.addColumn(column); } } return tableView; } /** * Save out a viewSet to a file * @param viewSet the viewSet to save * @param filename the filename (full path) as to where to save it */ public static void save(final ViewSet viewSet, final String filename) { try { Vector<ViewSet> viewsets = new Vector<ViewSet>(); viewsets.add(viewSet); File file = new File(filename); FileWriter fw = new FileWriter(file); fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); BeanWriter beanWriter = new BeanWriter(fw); XMLIntrospector introspector = beanWriter.getXMLIntrospector(); introspector.getConfiguration().setWrapCollectionsInElement(false); beanWriter.getBindingConfiguration().setMapIDs(false); beanWriter.setWriteEmptyElements(false); beanWriter.enablePrettyPrint(); beanWriter.write(viewSet); fw.close(); } catch(Exception ex) { log.error("error writing views", ex); } } //-------------------------------------------------------------------------------------------- //-- Field Verify Methods, Classes, Helpers //-------------------------------------------------------------------------------------------- public void createFieldVerTableModel() { fldVerTableModel = new FieldVerifyTableModel(); } /** * @return the doFieldVerification */ public static boolean isDoFieldVerification() { return doFieldVerification; } /** * @param doFieldVerification the doFieldVerification to set */ public static void setDoFieldVerification(boolean doFieldVerification) { ViewLoader.doFieldVerification = doFieldVerification; } public static void clearFieldVerInfo() { if (instance.fldVerTableModel != null) { instance.fldVerTableModel.clear(); } } /** * Di */ public static void displayFieldVerInfo() { if (verifyDlg != null) { verifyDlg.setVisible(false); verifyDlg.dispose(); verifyDlg = null; } System.err.println("------------- "+(instance.fldVerTableModel != null ? instance.fldVerTableModel.getRowCount() : "null")); if (instance.fldVerTableModel != null && instance.fldVerTableModel.getRowCount() > 0) { JLabel lbl = UIHelper.createLabel("<html><i>(Some of fields are special buttons or labal names. Review them to make sure you have not <br>mis-named any of the fields you are working with.)"); final JTable table = new JTable(instance.fldVerTableModel); UIHelper.calcColumnWidths(table); CellConstraints cc = new CellConstraints(); JScrollPane sp = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g,4px,p")); pb.add(sp, cc.xy(1, 1)); pb.add(lbl, cc.xy(1, 3)); pb.setDefaultDialogBorder(); verifyDlg = new CustomFrame("Field Names on Form, but not in Database : "+instance.fldVerTableModel.getRowCount(), CustomFrame.OK_BTN, pb.getPanel()) { @Override protected void okButtonPressed() { super.okButtonPressed(); table.setModel(new DefaultTableModel()); dispose(); verifyDlg = null; } }; verifyDlg.setOkLabel(getResourceString("CLOSE")); verifyDlg.createUI(); verifyDlg.setVisible(true); } } class FieldVerifyTableModel extends DefaultTableModel { protected Vector<List<String>> rowData = new Vector<List<String>>(); protected String[] colNames = {"ViewSet", "View Def", "Cell Id", "Cell Name", "Row"}; protected Hashtable<String, Boolean> nameHash = new Hashtable<String, Boolean>(); public FieldVerifyTableModel() { super(); } public void clear() { for (List<String> list : rowData) { list.clear(); } rowData.clear(); nameHash.clear(); } public void addRow(final String viewSet, final String viewDef, final String cellId, final String cellName, final String rowInx) { String key = viewSet + viewDef + cellId; if (nameHash.get(key) == null) { List<String> row = new ArrayList<String>(5); row.add(viewSet); row.add(viewDef); row.add(cellId); row.add(cellName); row.add(rowInx); rowData.add(row); nameHash.put(key, true); } } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getColumnCount() */ @Override public int getColumnCount() { return colNames.length; } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getColumnName(int) */ @Override public String getColumnName(int column) { return colNames[column]; } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getRowCount() */ @Override public int getRowCount() { return rowData == null ? 0 : rowData.size(); } /* (non-Javadoc) * @see javax.swing.table.DefaultTableModel#getValueAt(int, int) */ @Override public Object getValueAt(int row, int column) { List<String> rowList = rowData.get(row); return rowList.get(column); } } }
Java
#!/bin/bash RRD=/data/mirror/rrd PNG=/data/mirror/www/size for file in $RRD/*; do tree=`basename $file` tree=${tree/.rrd/} rrdtool graph $PNG/$tree-week.png --imgformat PNG \ --end now --start end-1w \ "DEF:raw=$file:size:AVERAGE" "CDEF:size=raw,1048576,*" \ "AREA:size#507AAA" -l 0 -M >/dev/null rrdtool graph $PNG/$tree-month.png --imgformat PNG \ --end now --start end-1m \ "DEF:raw=$file:size:AVERAGE" "CDEF:size=raw,1048576,*" \ "AREA:size#507AAA" -l 0 -M >/dev/null rrdtool graph $PNG/$tree-year.png --imgformat PNG \ --end now --start end-1y \ "DEF:raw=$file:size:AVERAGE" "CDEF:size=raw,1048576,*" \ "AREA:size#507AAA" -l 0 -M >/dev/null done
Java
/* Copyright: © 2011 Thomas Stein, CodeLounge.de <mailto:info@codelounge.de> <http://www.codelounge.de/> Released under the terms of the GNU General Public License. You should have received a copy of the GNU General Public License, along with this software. In the main directory, see: licence.txt If not, see: <http://www.gnu.org/licenses/>. */ /* * MBP - Mobile boilerplate helper functions */ (function(document){ window.MBP = window.MBP || {}; // Fix for iPhone viewport scale bug // http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/ MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]'); MBP.ua = navigator.userAgent; MBP.scaleFix = function () { if (MBP.viewportmeta && /iPhone|iPad/.test(MBP.ua) && !/Opera Mini/.test(MBP.ua)) { MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0"; document.addEventListener("gesturestart", MBP.gestureStart, false); } }; MBP.gestureStart = function () { MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6"; }; // Hide URL Bar for iOS // http://remysharp.com/2010/08/05/doing-it-right-skipping-the-iphone-url-bar/ MBP.hideUrlBar = function () { /iPhone/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () { window.scrollTo(0, 1); }, 1000), /iPad/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () { window.scrollTo(0, 1); }, 1000); }; }); jQuery( function() { $("a.facebox").fancybox(); //$("a.fancybox").prettyPhoto({ // social_tools: false //}); jQuery('.entenlogo').click(function() { $('.entenlogo').hide(); }); var current_url = $(location).attr('href'); //console.log($(location).attr('href')); jQuery('body').bind( 'taphold', function( e ) { //$('#next_post_link').attr('refresh'); //$('#previous_post_link').attr('refresh'); $('#page').page('refresh'); var next_url = $('#next_post_link').attr('href'); var previous_url = $('#previous_post_link').attr('href'); console.log(next_url + ' --- ' + previous_url); e.stopImmediatePropagation(); return false; } ); jQuery('body').bind( 'swipeleft', function( e ) { var next_url = $('.ui-page-active #next_post_link').attr('href'); var previous_url = $('.ui-page-active #previous_post_link').attr('href'); console.log("Swiped Left: " + next_url + ' --- ' + previous_url); if (undefined != previous_url) { //$.mobile.changePage( previous_url,"slide", true); $.mobile.changePage( previous_url, { transition: "slide", reverse: false, changeHash: true }); e.stopImmediatePropagation(); return false; } } ); jQuery('body').bind( 'swiperight', function( e ) { var next_url = $('.ui-page-active #next_post_link').attr('href'); var previous_url = $('.ui-page-active #previous_post_link').attr('href'); console.log("Swiped Right: " + next_url + ' --- ' + previous_url); if (undefined != next_url) { //$.mobile.changePage( next_url, "slide", true); $.mobile.changePage( next_url, { transition: "slide", reverse: true, changeHash: true }); e.stopImmediatePropagation(); return false; } } ); } );
Java
#include "tacticattacker.h" TacticAttacker::TacticAttacker(WorldModel *worldmodel, QObject *parent) : Tactic("TacticAttacker", worldmodel, parent) { everyOneInTheirPos = false; maxDistance = sqrt(pow(Field::MaxX*2,2)+pow(Field::MaxY*2,2)); } RobotCommand TacticAttacker::getCommand() { RobotCommand rc; if(!wm->ourRobot[id].isValid) return rc; if(wm->ourRobot[id].Status == AgentStatus::FollowingBall) { rc.maxSpeed = 2; tANDp target = findTarget(); // OperatingPosition p = BallControl(target.pos, target.prob, this->id, rc.maxSpeed); OperatingPosition p = BallControl(target.pos, target.prob, this->id, rc.maxSpeed,3); if( p.readyToShoot ) // rc.kickspeedx = detectKickSpeed(kickType::Shoot, p.shootSensor); { rc.kickspeedz = detectChipSpeed(/*kickType::Shoot, */p.shootSensor); } rc.fin_pos = p.pos; rc.useNav = p.useNav; rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::Kicking) { // if(wm->gs == STATE_Indirect_Free_kick_Our) // { // rc = KickTheBallIndirect(); // } // else if(wm->gs == STATE_Free_kick_Our) // { // rc = KickTheBallDirect(); // } // else if(wm->gs == STATE_Start) // { // rc = StartTheGame(); // } if(wm->gs == STATE_Start) { rc = StartTheGame(); } else { rc = KickTheBallIndirect(); } rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::Chiping) { rc = ChipTheBallIndirect(); rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::RecievingPass) { rc.fin_pos = idlePosition; rc.maxSpeed = 2.5; rc.useNav = true; rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::BlockingRobot) { AngleDeg desiredDeg = (wm->oppRobot[playerToKeep].pos.loc-Field::ourGoalCenter).dir(); Position final; final.loc.x = wm->oppRobot[playerToKeep].pos.loc.x - (300*cos(desiredDeg.radian())); final.loc.y = wm->oppRobot[playerToKeep].pos.loc.y - (300*sin(desiredDeg.radian())); final.dir = desiredDeg.radian(); if( wm->gs == GameStateType::STATE_Free_kick_Opp || wm->gs == GameStateType::STATE_Indirect_Free_kick_Opp) { if( wm->kn->IsInsideSecureArea(final.loc,wm->ball.pos.loc) ) { Vector2D fstInt,secInt; Circle2D secArea(wm->ball.pos.loc,ALLOW_NEAR_BALL_RANGE); Line2D connectedLine(wm->ball.pos.loc,Field::ourGoalCenter); int numberOfIntersections = secArea.intersection(connectedLine,&fstInt,&secInt); rc.fin_pos.dir = (wm->oppRobot[playerToKeep].pos.loc - Field::ourGoalCenter).dir().radian(); if( numberOfIntersections == 2 ) { if( (fstInt-final.loc).length() > (secInt-final.loc).length() ) rc.fin_pos.loc = secInt; else rc.fin_pos.loc = fstInt; } else if( numberOfIntersections == 1 ) { rc.fin_pos.loc = fstInt; } else rc.fin_pos = wm->ourRobot[this->id].pos; } else { rc.fin_pos = final; } } else { rc.fin_pos = final; } if( wm->opp_vel > 3 ) rc.maxSpeed = 3; else rc.maxSpeed = wm->opp_vel; rc.useNav = true; rc.isBallObs = true; rc.isKickObs = true; } else if(wm->ourRobot[id].Status == AgentStatus::Idle) { rc.fin_pos = idlePosition; rc.maxSpeed = 2; rc.useNav = true; rc.isBallObs = true; rc.isKickObs = true; if( wm->gs == STATE_Stop ) return rc; } if( wm->kn->IsInsideGolieArea(rc.fin_pos.loc) ) { Circle2D attackerCircles(Field::ourGoalCenter , Field::goalCircle_R+300); Line2D robotRay(rc.fin_pos.loc,wm->ourRobot[this->id].pos.loc); Vector2D firstPoint,secondPoint; attackerCircles.intersection(robotRay,&firstPoint,&secondPoint); if( (wm->ourRobot[this->id].pos.loc-firstPoint).length() < (wm->ourRobot[this->id].pos.loc-secondPoint).length() ) rc.fin_pos.loc = firstPoint; else rc.fin_pos.loc = secondPoint; } if( wm->kn->IsInsideOppGolieArea(rc.fin_pos.loc) && !wm->cmgs.ourPenaltyKick() /*&& wm->defenceMode*/) { Circle2D attackerCircles(Field::oppGoalCenter , Field::goalCircle_R+300); Line2D robotRay(rc.fin_pos.loc, wm->ourRobot[this->id].pos.loc); Vector2D firstPoint,secondPoint; attackerCircles.intersection(robotRay,&firstPoint,&secondPoint); if( (wm->ourRobot[this->id].pos.loc-firstPoint).length() < (wm->ourRobot[this->id].pos.loc-secondPoint).length() ) rc.fin_pos.loc = firstPoint; else rc.fin_pos.loc = secondPoint; } return rc; } RobotCommand TacticAttacker::goBehindBall() { RobotCommand rc; canKick=false; rc.maxSpeed = 1; float deg=atan((0-wm->ball.pos.loc.y)/(3025-wm->ball.pos.loc.x)); if(!wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 30, 180)) { rc.fin_pos.loc= {wm->ball.pos.loc.x-110*cos(deg),wm->ball.pos.loc.y-110*sin(deg)}; rc.fin_pos.dir=atan((0-wm->ball.pos.loc.y)/(3025-wm->ball.pos.loc.x)); } if(!wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 20, 2)) { //double test=findBestPoint(); //rc.fin_pos.dir=test; } rc.fin_pos.loc= {wm->ball.pos.loc.x-100*cos(deg),wm->ball.pos.loc.y-100*sin(deg)}; if(wm->kn->ReachedToPos(wm->ourRobot[id].pos, rc.fin_pos, 10, 4)) { canKick=true; } return rc; } RobotCommand TacticAttacker::KickTheBallIndirect() { RobotCommand rc; rc.maxSpeed = 0.5; Vector2D target = receiverPos; Line2D b2g(target,Field::oppGoalCenter); Circle2D cir(target,300); Vector2D goal,first,second; int numOfPoints = cir.intersection(b2g,&first,&second); // if( numOfPoints == 2) // { // if( first.x > target.x ) // goal = first; // else if( second.x > target.x ) // goal = second; // else // goal = target; // } // else if( numOfPoints == 1) // goal = first; // else goal = target; wm->passPoints.clear(); wm->passPoints.push_back(goal); OperatingPosition kickPoint = BallControl(goal,100,this->id,rc.maxSpeed); rc.fin_pos = kickPoint.pos; rc.useNav = kickPoint.useNav; qDebug()<<"readyToShoot : "<<kickPoint.readyToShoot<<" , everyOneInTheirPos : "<<everyOneInTheirPos; if( kickPoint.readyToShoot && everyOneInTheirPos) { rc.kickspeedx = detectKickSpeed(freeKickType, kickPoint.shootSensor); // Line2D ball2Target(wm->ball.pos.loc,goal); // QList<int> activeOpp = wm->kn->ActiveOppAgents(); // bool wayIsClear = true; // for(int i=0;i<activeOpp.size();i++) // { // double distance = ball2Target.dist(wm->oppRobot[activeOpp.at(i)].pos.loc); // if( distance < ROBOT_RADIUS+BALL_RADIUS ) // { // wayIsClear = false; // break; // } // } // if( wayIsClear ) // { // rc.kickspeedx = 255;// detectKickSpeed(goal); // qDebug()<<"Kickk..."; // } // else // { // rc.kickspeedx = 3;//255;// detectKickSpeed(goal); // rc.kickspeedz = 3; // qDebug()<<"CHIP..."; // } } return rc; } RobotCommand TacticAttacker::KickTheBallDirect() { RobotCommand rc; rc.maxSpeed = 0.5; tANDp target = findTarget(); OperatingPosition kickPoint = BallControl(target.pos, target.prob, this->id, rc.maxSpeed); rc.fin_pos = kickPoint.pos; if( kickPoint.readyToShoot ) { rc.kickspeedx = detectKickSpeed(kickType::Shoot, kickPoint.shootSensor); qDebug()<<"Kickk..."; } rc.useNav = kickPoint.useNav; return rc; } RobotCommand TacticAttacker::StartTheGame() { RobotCommand rc; rc.maxSpeed = 0.5; Vector2D target(Field::oppGoalCenter.x,Field::oppGoalCenter.y); OperatingPosition kickPoint = BallControl(target, 100, this->id, rc.maxSpeed); rc.fin_pos = kickPoint.pos; rc.useNav = kickPoint.useNav; if( kickPoint.readyToShoot ) { //rc.kickspeedz = 2.5;//50; rc.kickspeedx = detectKickSpeed(kickType::Shoot, kickPoint.shootSensor); qDebug()<<"Kickk..."; } return rc; } RobotCommand TacticAttacker::ChipTheBallIndirect() { RobotCommand rc; rc.maxSpeed = 0.5; Vector2D target = receiverPos; Vector2D goal(target.x,target.y); OperatingPosition kickPoint = BallControl(goal, 100, this->id, rc.maxSpeed); rc.fin_pos = kickPoint.pos; rc.useNav = kickPoint.useNav; if( kickPoint.readyToShoot && everyOneInTheirPos) { rc.kickspeedz = detectChipSpeed(kickPoint.shootSensor); qDebug()<<"Chip..."; } return rc; } int TacticAttacker::findBestPlayerForPass() { QList<int> ourAgents = wm->kn->findAttackers(); ourAgents.removeOne(this->id); QList<int> freeAgents , busyAgents; while( !ourAgents.isEmpty() ) { int index = ourAgents.takeFirst(); if(isFree(index)) freeAgents.append(index); else busyAgents.append(index); } QList<double> weights; for(int i=0;i<freeAgents.size();i++) { double weight = -1000000; if( wm->ourRobot[freeAgents.at(i)].isValid ) { double dist = 1 - ((wm->ball.pos.loc - wm->ourRobot[freeAgents.at(i)].pos.loc).length()/maxDistance); double prob = wm->kn->scoringChance(wm->ourRobot[freeAgents.at(i)].pos.loc) / 100; weight = (20 * prob) + (10*dist); } weights.append(weight); } int index = -1; double max = -10000; for(int i=0;i<weights.size();i++) { if( max < weights.at(i) ) { max = weights.at(i); index = freeAgents.at(i); } } return index; } void TacticAttacker::isKicker() { wm->ourRobot[this->id].Status = AgentStatus::Kicking; findReciever = true; } void TacticAttacker::isChiper() { wm->ourRobot[this->id].Status = AgentStatus::Chiping; findReciever = true; } void TacticAttacker::isKicker(int recieverID) { wm->ourRobot[this->id].Status = AgentStatus::Kicking; findReciever = false; this->receiverPos = wm->ourRobot[recieverID].pos.loc; } void TacticAttacker::isKicker(Vector2D pos) { wm->ourRobot[this->id].Status = AgentStatus::Kicking; findReciever = false; this->receiverPos = pos; } void TacticAttacker::isChiper(Vector2D pos) { wm->ourRobot[this->id].Status = AgentStatus::Chiping; findReciever = false; this->receiverPos = pos; } void TacticAttacker::setGameOnPositions(Position pos) { setIdlePosition(pos); } void TacticAttacker::setGameOnPositions(Vector2D pos) { Position position = wm->kn->AdjustKickPoint(pos,Field::oppGoalCenter); setIdlePosition(position); } void TacticAttacker::setIdlePosition(Position pos) { this->idlePosition = pos; } void TacticAttacker::setIdlePosition(Vector2D pos) { this->idlePosition.loc = pos; this->idlePosition.dir = ( wm->ball.pos.loc - pos).dir().radian(); } void TacticAttacker::youHavePermissionForKick() { everyOneInTheirPos = true; if( findReciever ) { int indexOfReciever = findBestPlayerForPass(); if( indexOfReciever != -1 ) receiverPos = wm->ourRobot[indexOfReciever].pos.loc; } } void TacticAttacker::setFreeKickType(kickType type) { this->freeKickType = type; } bool TacticAttacker::isFree(int index) { QList<int> oppAgents = wm->kn->ActiveOppAgents(); while( !oppAgents.isEmpty() ) { int indexOPP = oppAgents.takeFirst(); if( (wm->ourRobot[index].pos.loc-wm->oppRobot[indexOPP].pos.loc).length() < DangerDist && fabs((wm->ourRobot[index].vel.loc - wm->oppRobot[indexOPP].vel.loc).length())<0.3 ) { return false; } } return true; }
Java
simple drupal module to display user profile information in balloon #how to install 1.extract the module and in sites/all/module dir and enable the module 2. config the module as need
Java
/******************************************************************************\ CAMotics is an Open-Source simulation and CAM software. Copyright (C) 2011-2019 Joseph Coffland <joseph@cauldrondevelopment.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/>. \******************************************************************************/ #pragma once #include <cbang/SmartPointer.h> #include <QDialog> namespace Ui {class DonateDialog;} namespace CAMotics { class DonateDialog : public QDialog { Q_OBJECT; cb::SmartPointer<Ui::DonateDialog> ui; public: DonateDialog(QWidget *parent); QString getVersion() const; void onStartup(); // From QDialog int exec(); // From QWidget void showEvent(QShowEvent *event); }; }
Java
#include<stdio.h> int main() { double r,pi=3.14159; scanf("%lf",&r); printf("A=%.4lf\n",pi*r*r); return 0; }
Java
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest04982") public class BenchmarkTest04982 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheParameter("foo"); String bar; String guess = "ABC"; char switchTarget = guess.charAt(1); // condition 'B', which is safe // Simple case statement that assigns param to bar on conditions 'A' or 'C' switch (switchTarget) { case 'A': bar = param; break; case 'B': bar = "bob"; break; case 'C': case 'D': bar = param; break; default: bar = "bob's your uncle"; break; } Object[] obj = { bar, "b"}; response.getWriter().printf("notfoo",obj); } }
Java
<?php /* Copyright (c) 2007 BeVolunteer This file is part of BW Rox. BW Rox 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. BW Rox 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/> or write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ $words = new MOD_words(); ?> <div id="teaser" class="clearfix"> <div class="subcolumns"> <div class="c62l"> <div class="subcl"> <h1 class="slogan"><span id="something" ><?php echo $words->get('IndexPageTeaserReal1a');?></span> <span id="real" ><?php echo $words->get('IndexPageTeaserReal1b');?></span>&nbsp;</h1> <h2><?php echo $words->get('IndexPageTeaserReal2');?></h2> <a class="bigbutton float_left" href="signup" onclick="this.blur();"><span><?php echo $words->get('signup_now');?></span></a> <a class="bigbutton float_left" href="tour" onclick="this.blur();"><span><?php echo $words->get('tour_take');?></span></a> </div> <!-- subcl --> </div> <!-- c50l --> <div class="c38r"> <div class="subcr"> <div id="slideshow-content"> <div class="slide" id="slide1"> <img src="images/tour/share4_small.jpg" alt="share" /> </div> <div class="slide" id="slide2" style="display: none;"> <img src="images/tour/syrien.jpg" alt="syria" /> </div> <div class="slide" id="slide3" style="display: none;"> <img src="images/tour/mountain1.jpg" alt="mountain" /> </div> <div class="slide" id="slide4" style="display: none;"> <img src="images/tour/river.jpg" alt="river" /> </div> <div class="slide" id="slide5" style="display: none;"> <img src="images/tour/dancing2.jpg" alt="dancing" /> </div> <div class="slide" id="slide6" style="display: none;"> <img src="images/tour/mountain2.jpg" alt="river" /> </div> <div class="slide" id="slide7" style="display: none;"> <img src="images/tour/people.jpg" alt="river" /> </div> <div class="slide" id="slide8" style="display: none;"> <img src="images/tour/people2.jpg" alt="river" /> </div> <p class="small photodesc"> (cc) <?=$words->get('StartPageListofPhotographers');?> </p> </div> </div> <!-- subcr --> </div> <!-- c50r --> </div> <!-- subcolumns --> <script type="text/javascript"> <!-- function realeffect() { new Effect.toggle('real', 'appear', {duration: 2}) } $('real').hide(); $('something').hide(); window.onload = function () { new Effect.toggle('something', 'appear', {duration: 2}); setTimeout('realeffect()',2000); start_slideshow(1, 8, 10000); }; // --> </script> <script type="text/javascript"> function start_slideshow(start_frame, end_frame, delay) { setTimeout(switch_slides(start_frame,start_frame,end_frame, delay), delay); } function switch_slides(frame, start_frame, end_frame, delay) { return (function() { Effect.Fade('slide' + frame); if (frame == end_frame) { frame = start_frame; } else { frame = frame + 1; } setTimeout("Effect.Appear('slide" + frame + "');", 950); setTimeout(switch_slides(frame, start_frame, end_frame, delay), delay + 950); }) } </script> </div>
Java
using UnityEngine; using System.Collections; public class MapCollisionsDetector : MonoBehaviour { // Use this for initialization void Start () { } void FixedUpdate() { } /*void OnCollisionEnter(Collision collision) { foreach(var contact in collision.contacts) print (contact.otherCollider.gameObject.name); }*/ }
Java
/* Copyright (C) 2015 Panagiotis Roubatsis 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. */ /* Created by Panagiotis Roubatsis Description: Load and apply GLSL shaders to irrlicht nodes. */ #ifndef GLSL_SHADER_H #define GLSL_SHADER_H #include "Shader.h" #include <iostream> #include <irrlicht.h> class GlslShader : public Shader { private: irr::video::E_MATERIAL_TYPE _materialType; bool _isLoaded; public: GlslShader(); GlslShader(std::string fileName, irr::video::IGPUProgrammingServices* gpu, int type); void load(std::string fileName, irr::video::IGPUProgrammingServices* gpu, int type); void apply(irr::scene::ISceneNode* node); }; #endif
Java
/************************************************************************************** * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * **************************************************************************************/ package com.espertech.esper.epl.join.pollindex; import com.espertech.esper.epl.join.table.EventTable; import com.espertech.esper.epl.join.table.UnindexedEventTableList; import com.espertech.esper.epl.join.table.PropertyIndexedEventTable; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.EventType; import java.util.Arrays; import java.util.List; /** * Strategy for building an index out of poll-results knowing the properties to base the index on. */ public class PollResultIndexingStrategyIndex implements PollResultIndexingStrategy { private final int streamNum; private final EventType eventType; private final String[] propertyNames; /** * Ctor. * @param streamNum is the stream number of the indexed stream * @param eventType is the event type of the indexed stream * @param propertyNames is the property names to be indexed */ public PollResultIndexingStrategyIndex(int streamNum, EventType eventType, String[] propertyNames) { this.streamNum = streamNum; this.eventType = eventType; this.propertyNames = propertyNames; } public EventTable index(List<EventBean> pollResult, boolean isActiveCache) { if (!isActiveCache) { return new UnindexedEventTableList(pollResult); } PropertyIndexedEventTable table = new PropertyIndexedEventTable(streamNum, eventType, propertyNames); table.add(pollResult.toArray(new EventBean[pollResult.size()])); return table; } public String toQueryPlan() { return this.getClass().getSimpleName() + " properties " + Arrays.toString(propertyNames); } }
Java
variable_name =============
Java
/* * ALSA SoC Voice Codec Interface for TI DAVINCI processor * * Copyright (C) 2010 Texas Instruments. * * Author: Miguel Aguilar <miguel.aguilar@ridgerun.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/mfd/davinci_voicecodec.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/initval.h> #include <sound/soc.h> #include "davinci-pcm.h" #include "davinci-i2s.h" #include "davinci-vcif.h" #define MOD_REG_BIT(val, mask, set) do { \ if (set) { \ val |= mask; \ } else { \ val &= ~mask; \ } \ } while (0) struct davinci_vcif_dev { struct davinci_vc *davinci_vc; struct davinci_pcm_dma_params dma_params[2]; }; static void davinci_vcif_start(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct davinci_vcif_dev *davinci_vcif_dev = rtd->dai->cpu_dai->private_data; struct davinci_vc *davinci_vc = davinci_vcif_dev->davinci_vc; u32 w; /* Start the sample generator and enable transmitter/receiver */ w = readl(davinci_vc->base + DAVINCI_VC_CTRL); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) MOD_REG_BIT(w, DAVINCI_VC_CTRL_RSTDAC, 0); else MOD_REG_BIT(w, DAVINCI_VC_CTRL_RSTADC, 0); writel(w, davinci_vc->base + DAVINCI_VC_CTRL); } static void davinci_vcif_stop(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct davinci_vcif_dev *davinci_vcif_dev = rtd->dai->cpu_dai->private_data; struct davinci_vc *davinci_vc = davinci_vcif_dev->davinci_vc; u32 w; /* Reset transmitter/receiver and sample rate/frame sync generators */ w = readl(davinci_vc->base + DAVINCI_VC_CTRL); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) MOD_REG_BIT(w, DAVINCI_VC_CTRL_RSTDAC, 1); else MOD_REG_BIT(w, DAVINCI_VC_CTRL_RSTADC, 1); writel(w, davinci_vc->base + DAVINCI_VC_CTRL); } static int davinci_vcif_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct davinci_vcif_dev *davinci_vcif_dev = dai->private_data; struct davinci_vc *davinci_vc = davinci_vcif_dev->davinci_vc; struct davinci_pcm_dma_params *dma_params = &davinci_vcif_dev->dma_params[substream->stream]; u32 w; /* Restart the codec before setup */ davinci_vcif_stop(substream); davinci_vcif_start(substream); /* General line settings */ writel(DAVINCI_VC_CTRL_MASK, davinci_vc->base + DAVINCI_VC_CTRL); writel(DAVINCI_VC_INT_MASK, davinci_vc->base + DAVINCI_VC_INTCLR); writel(DAVINCI_VC_INT_MASK, davinci_vc->base + DAVINCI_VC_INTEN); w = readl(davinci_vc->base + DAVINCI_VC_CTRL); /* Determine xfer data type */ switch (params_format(params)) { case SNDRV_PCM_FORMAT_U8: dma_params->data_type = 0; MOD_REG_BIT(w, DAVINCI_VC_CTRL_RD_BITS_8 | DAVINCI_VC_CTRL_RD_UNSIGNED | DAVINCI_VC_CTRL_WD_BITS_8 | DAVINCI_VC_CTRL_WD_UNSIGNED, 1); break; case SNDRV_PCM_FORMAT_S8: dma_params->data_type = 1; MOD_REG_BIT(w, DAVINCI_VC_CTRL_RD_BITS_8 | DAVINCI_VC_CTRL_WD_BITS_8, 1); MOD_REG_BIT(w, DAVINCI_VC_CTRL_RD_UNSIGNED | DAVINCI_VC_CTRL_WD_UNSIGNED, 0); break; case SNDRV_PCM_FORMAT_S16_LE: dma_params->data_type = 2; MOD_REG_BIT(w, DAVINCI_VC_CTRL_RD_BITS_8 | DAVINCI_VC_CTRL_RD_UNSIGNED | DAVINCI_VC_CTRL_WD_BITS_8 | DAVINCI_VC_CTRL_WD_UNSIGNED, 0); break; default: printk(KERN_WARNING "davinci-vcif: unsupported PCM format"); return -EINVAL; } dma_params->acnt = dma_params->data_type; writel(w, davinci_vc->base + DAVINCI_VC_CTRL); return 0; } static int davinci_vcif_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { int ret = 0; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: davinci_vcif_start(substream); break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: davinci_vcif_stop(substream); break; default: ret = -EINVAL; } return ret; } #define DAVINCI_VCIF_RATES SNDRV_PCM_RATE_8000_48000 static struct snd_soc_dai_ops davinci_vcif_dai_ops = { .trigger = davinci_vcif_trigger, .hw_params = davinci_vcif_hw_params, }; struct snd_soc_dai davinci_vcif_dai = { .name = "davinci-vcif", .playback = { .channels_min = 1, .channels_max = 2, .rates = DAVINCI_VCIF_RATES, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .capture = { .channels_min = 1, .channels_max = 2, .rates = DAVINCI_VCIF_RATES, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .ops = &davinci_vcif_dai_ops, }; EXPORT_SYMBOL_GPL(davinci_vcif_dai); static int davinci_vcif_probe(struct platform_device *pdev) { struct davinci_vc *davinci_vc = platform_get_drvdata(pdev); struct davinci_vcif_dev *davinci_vcif_dev; int ret; davinci_vcif_dev = kzalloc(sizeof(struct davinci_vcif_dev), GFP_KERNEL); if (!davinci_vc) { dev_dbg(&pdev->dev, "could not allocate memory for private data\n"); return -ENOMEM; } /* DMA tx params */ davinci_vcif_dev->davinci_vc = davinci_vc; davinci_vcif_dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].channel = davinci_vc->davinci_vcif.dma_tx_channel; davinci_vcif_dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].dma_addr = davinci_vc->davinci_vcif.dma_tx_addr; /* DMA rx params */ davinci_vcif_dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].channel = davinci_vc->davinci_vcif.dma_rx_channel; davinci_vcif_dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].dma_addr = davinci_vc->davinci_vcif.dma_rx_addr; davinci_vcif_dai.dev = &pdev->dev; davinci_vcif_dai.capture.dma_data = davinci_vcif_dev->dma_params; davinci_vcif_dai.playback.dma_data = davinci_vcif_dev->dma_params; davinci_vcif_dai.private_data = davinci_vcif_dev; ret = snd_soc_register_dai(&davinci_vcif_dai); if (ret != 0) { dev_err(&pdev->dev, "could not register dai\n"); goto fail; } return 0; fail: kfree(davinci_vcif_dev); return ret; } static int davinci_vcif_remove(struct platform_device *pdev) { snd_soc_unregister_dai(&davinci_vcif_dai); return 0; } static struct platform_driver davinci_vcif_driver = { .probe = davinci_vcif_probe, .remove = davinci_vcif_remove, .driver = { .name = "davinci_vcif", .owner = THIS_MODULE, }, }; static int __init davinci_vcif_init(void) { return platform_driver_probe(&davinci_vcif_driver, davinci_vcif_probe); } module_init(davinci_vcif_init); static void __exit davinci_vcif_exit(void) { platform_driver_unregister(&davinci_vcif_driver); } module_exit(davinci_vcif_exit); MODULE_AUTHOR("Miguel Aguilar"); MODULE_DESCRIPTION("Texas Instruments DaVinci ASoC Voice Codec Interface"); MODULE_LICENSE("GPL");
Java
package com.ht.halo.hibernate3.base; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map.Entry; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.ht.halo.hibernate3.HaloDao; import com.ht.halo.map.HaloMap; public class MyEntityUtils { private static final Log logger = LogFactory.getLog(MyEntityUtils.class); /** * @Title: setEntity * @Description: TODO Action层 设置实体某字段值 map转entity * @param entity * @param parameters */ public static Object setEntity(Object entity,HaloMap parameter){ if(null!=parameter){ for (Entry<String, ?> entry : parameter.entrySet()) { try { BeanUtils.setProperty(entity, entry.getKey(), entry.getValue()); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } // MyBeanUtils.setFieldValue(entity, entry.getKey(), entry.getValue()); } } return entity; } public static <T> T toEntity(Class<T> clazz, HaloMap map) { T obj = null; try { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); obj = clazz.newInstance(); // 创建 JavaBean 对象 // 给 JavaBean 对象的属性赋值 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (map.containsKey(propertyName)) { // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。 Object value = map.get(propertyName); if ("".equals(value)) { value = null; } Object[] args = new Object[1]; args[0] = value; try { descriptor.getWriteMethod().invoke(obj, args); } catch (InvocationTargetException e) { logger.warn("字段映射失败"); } } } } catch (IllegalAccessException e) { logger.error("实例化 JavaBean 失败"); } catch (IntrospectionException e) { logger.error("分析类属性失败"); } catch (IllegalArgumentException e) { logger.error("映射错误"); } catch (InstantiationException e) { logger.error("实例化 JavaBean 失败"); } return (T) obj; } public static HaloMap toHaloMap(Object bean) { Class<? extends Object> clazz = bean.getClass(); HaloMap returnMap = new HaloMap(); BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (null != propertyName) { propertyName = propertyName.toString(); } if(null==result){ continue; } if (null != result) { result = result.toString(); } returnMap.put(propertyName, result); } } } catch (IntrospectionException e) { logger.error("分析类属性失败"); } catch (IllegalAccessException e) { logger.error("实例化 JavaBean 失败"); } catch (IllegalArgumentException e) { logger.error("映射错误"); } catch (InvocationTargetException e) { logger.error("调用属性的 setter 方法失败"); } return returnMap; } public static HaloMap toFindHaloMap(Object bean) { Class<? extends Object> clazz = bean.getClass(); HaloMap returnMap = new HaloMap(); BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (null != propertyName) { propertyName = propertyName.toString(); } if(null==result){ continue; } if (null != result) { result = result.toString(); } if(propertyName.equals("json")){ continue; } returnMap.put(propertyName+HaloDao.MYSPACE+HaloDao.PRM, result); } } } catch (IntrospectionException e) { logger.error("分析类属性失败"); } catch (IllegalAccessException e) { logger.error("实例化 JavaBean 失败"); } catch (IllegalArgumentException e) { logger.error("映射错误"); } catch (InvocationTargetException e) { logger.error("调用属性的 setter 方法失败"); } return returnMap; } }
Java
import os import unittest import tempfile from git import Repo from oeqa.utils.commands import get_bb_var from oe.buildhistory_analysis import blob_to_dict, compare_dict_blobs class TestBlobParsing(unittest.TestCase): def setUp(self): import time self.repo_path = tempfile.mkdtemp(prefix='selftest-buildhistory', dir=get_bb_var('TOPDIR')) self.repo = Repo.init(self.repo_path) self.test_file = "test" self.var_map = {} def tearDown(self): import shutil shutil.rmtree(self.repo_path) def commit_vars(self, to_add={}, to_remove = [], msg="A commit message"): if len(to_add) == 0 and len(to_remove) == 0: return for k in to_remove: self.var_map.pop(x,None) for k in to_add: self.var_map[k] = to_add[k] with open(os.path.join(self.repo_path, self.test_file), 'w') as repo_file: for k in self.var_map: repo_file.write("%s = %s\n" % (k, self.var_map[k])) self.repo.git.add("--all") self.repo.git.commit(message=msg) def test_blob_to_dict(self): """ Test convertion of git blobs to dictionary """ valuesmap = { "foo" : "1", "bar" : "2" } self.commit_vars(to_add = valuesmap) blob = self.repo.head.commit.tree.blobs[0] self.assertEqual(valuesmap, blob_to_dict(blob), "commit was not translated correctly to dictionary") def test_compare_dict_blobs(self): """ Test comparisson of dictionaries extracted from git blobs """ changesmap = { "foo-2" : ("2", "8"), "bar" : ("","4"), "bar-2" : ("","5")} self.commit_vars(to_add = { "foo" : "1", "foo-2" : "2", "foo-3" : "3" }) blob1 = self.repo.heads.master.commit.tree.blobs[0] self.commit_vars(to_add = { "foo-2" : "8", "bar" : "4", "bar-2" : "5" }) blob2 = self.repo.heads.master.commit.tree.blobs[0] change_records = compare_dict_blobs(os.path.join(self.repo_path, self.test_file), blob1, blob2, False, False) var_changes = { x.fieldname : (x.oldvalue, x.newvalue) for x in change_records} self.assertEqual(changesmap, var_changes, "Changes not reported correctly") def test_compare_dict_blobs_default(self): """ Test default values for comparisson of git blob dictionaries """ defaultmap = { x : ("default", "1") for x in ["PKG", "PKGE", "PKGV", "PKGR"]} self.commit_vars(to_add = { "foo" : "1" }) blob1 = self.repo.heads.master.commit.tree.blobs[0] self.commit_vars(to_add = { "PKG" : "1", "PKGE" : "1", "PKGV" : "1", "PKGR" : "1" }) blob2 = self.repo.heads.master.commit.tree.blobs[0] change_records = compare_dict_blobs(os.path.join(self.repo_path, self.test_file), blob1, blob2, False, False) var_changes = {} for x in change_records: oldvalue = "default" if ("default" in x.oldvalue) else x.oldvalue var_changes[x.fieldname] = (oldvalue, x.newvalue) self.assertEqual(defaultmap, var_changes, "Defaults not set properly")
Java
/* * Copyright (c) 2001-2002 by David Brownell * * 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. */ #ifdef __KERNEL__ #include <linux/rwsem.h> /* This file contains declarations of usbcore internals that are mostly * used or exposed by Host Controller Drivers. */ /* * USB Packet IDs (PIDs) */ #define USB_PID_UNDEF_0 0xf0 #define USB_PID_OUT 0xe1 #define USB_PID_ACK 0xd2 #define USB_PID_DATA0 0xc3 #define USB_PID_PING 0xb4 /* USB 2.0 */ #define USB_PID_SOF 0xa5 #define USB_PID_NYET 0x96 /* USB 2.0 */ #define USB_PID_DATA2 0x87 /* USB 2.0 */ #define USB_PID_SPLIT 0x78 /* USB 2.0 */ #define USB_PID_IN 0x69 #define USB_PID_NAK 0x5a #define USB_PID_DATA1 0x4b #define USB_PID_PREAMBLE 0x3c /* Token mode */ #define USB_PID_ERR 0x3c /* USB 2.0: handshake mode */ #define USB_PID_SETUP 0x2d #define USB_PID_STALL 0x1e #define USB_PID_MDATA 0x0f /* USB 2.0 */ /*-------------------------------------------------------------------------*/ /* * USB Host Controller Driver (usb_hcd) framework * * Since "struct usb_bus" is so thin, you can't share much code in it. * This framework is a layer over that, and should be more sharable. * * @authorized_default: Specifies if new devices are authorized to * connect by default or they require explicit * user space authorization; this bit is settable * through /sys/class/usb_host/X/authorized_default. * For the rest is RO, so we don't lock to r/w it. */ /*-------------------------------------------------------------------------*/ struct usb_hcd { /* * housekeeping */ struct usb_bus self; /* hcd is-a bus */ struct kref kref; /* reference counter */ const char *product_desc; /* product/vendor string */ char irq_descr[24]; /* driver + bus # */ struct timer_list rh_timer; /* drives root-hub polling */ struct urb *status_urb; /* the current status urb */ #ifdef CONFIG_PM struct work_struct wakeup_work; /* for remote wakeup */ #endif /* * hardware info/state */ const struct hc_driver *driver; /* hw-specific hooks */ /* Flags that need to be manipulated atomically */ unsigned long flags; #define HCD_FLAG_HW_ACCESSIBLE 0x00000001 #define HCD_FLAG_SAW_IRQ 0x00000002 unsigned rh_registered:1;/* is root hub registered? */ /* The next flag is a stopgap, to be removed when all the HCDs * support the new root-hub polling mechanism. */ unsigned uses_new_polling:1; unsigned poll_rh:1; /* poll for rh status? */ unsigned poll_pending:1; /* status has changed? */ unsigned wireless:1; /* Wireless USB HCD */ unsigned authorized_default:1; int irq; /* irq allocated */ void __iomem *regs; /* device memory/io */ u64 rsrc_start; /* memory/io resource start */ u64 rsrc_len; /* memory/io resource length */ unsigned power_budget; /* in mA, 0 = no limit */ #define HCD_BUFFER_POOLS 4 struct dma_pool *pool [HCD_BUFFER_POOLS]; int state; # define __ACTIVE 0x01 # define __SUSPEND 0x04 # define __TRANSIENT 0x80 # define HC_STATE_HALT 0 # define HC_STATE_RUNNING (__ACTIVE) # define HC_STATE_QUIESCING (__SUSPEND|__TRANSIENT|__ACTIVE) # define HC_STATE_RESUMING (__SUSPEND|__TRANSIENT) # define HC_STATE_SUSPENDED (__SUSPEND) #define HC_IS_RUNNING(state) ((state) & __ACTIVE) #define HC_IS_SUSPENDED(state) ((state) & __SUSPEND) /* more shared queuing code would be good; it should support * smarter scheduling, handle transaction translators, etc; * input size of periodic table to an interrupt scheduler. * (ohci 32, uhci 1024, ehci 256/512/1024). */ /* The HC driver's private data is stored at the end of * this structure. */ unsigned long hcd_priv[0] __attribute__ ((aligned (sizeof(unsigned long)))); }; /* 2.4 does this a bit differently ... */ static inline struct usb_bus *hcd_to_bus (struct usb_hcd *hcd) { return &hcd->self; } static inline struct usb_hcd *bus_to_hcd (struct usb_bus *bus) { return container_of(bus, struct usb_hcd, self); } struct hcd_timeout { /* timeouts we allocate */ struct list_head timeout_list; struct timer_list timer; }; /*-------------------------------------------------------------------------*/ struct hc_driver { const char *description; /* "ehci-hcd" etc */ const char *product_desc; /* product/vendor string */ size_t hcd_priv_size; /* size of private data */ /* irq handler */ irqreturn_t (*irq) (struct usb_hcd *hcd); int flags; #define HCD_MEMORY 0x0001 /* HC regs use memory (else I/O) */ #define HCD_USB11 0x0010 /* USB 1.1 */ #define HCD_USB2 0x0020 /* USB 2.0 */ /* called to init HCD and root hub */ int (*reset) (struct usb_hcd *hcd); int (*start) (struct usb_hcd *hcd); /* NOTE: these suspend/resume calls relate to the HC as * a whole, not just the root hub; they're for PCI bus glue. */ /* called after suspending the hub, before entering D3 etc */ int (*suspend) (struct usb_hcd *hcd, pm_message_t message); /* called after entering D0 (etc), before resuming the hub */ int (*resume) (struct usb_hcd *hcd); /* cleanly make HCD stop writing memory and doing I/O */ void (*stop) (struct usb_hcd *hcd); /* shutdown HCD */ void (*shutdown) (struct usb_hcd *hcd); /* return current frame number */ int (*get_frame_number) (struct usb_hcd *hcd); /* manage i/o requests, device state */ int (*urb_enqueue)(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags); int (*urb_dequeue)(struct usb_hcd *hcd, struct urb *urb, int status); /* hw synch, freeing endpoint resources that urb_dequeue can't */ void (*endpoint_disable)(struct usb_hcd *hcd, struct usb_host_endpoint *ep); /* root hub support */ int (*hub_status_data) (struct usb_hcd *hcd, char *buf); int (*hub_control) (struct usb_hcd *hcd, u16 typeReq, u16 wValue, u16 wIndex, char *buf, u16 wLength); int (*bus_suspend)(struct usb_hcd *); int (*bus_resume)(struct usb_hcd *); int (*start_port_reset)(struct usb_hcd *, unsigned port_num); void (*hub_irq_enable)(struct usb_hcd *); /* Needed only if port-change IRQs are level-triggered */ #ifdef CONFIG_KDB_USB /* KDB poll function for this HC */ int (*kdb_poll_char)(struct urb *urb); #endif /* CONFIG_KDB_USB */ }; extern int usb_hcd_link_urb_to_ep(struct usb_hcd *hcd, struct urb *urb); extern int usb_hcd_check_unlink_urb(struct usb_hcd *hcd, struct urb *urb, int status); extern void usb_hcd_unlink_urb_from_ep(struct usb_hcd *hcd, struct urb *urb); extern int usb_hcd_submit_urb (struct urb *urb, gfp_t mem_flags); extern int usb_hcd_unlink_urb (struct urb *urb, int status); extern void usb_hcd_giveback_urb(struct usb_hcd *hcd, struct urb *urb, int status); extern void usb_hcd_flush_endpoint(struct usb_device *udev, struct usb_host_endpoint *ep); extern void usb_hcd_disable_endpoint(struct usb_device *udev, struct usb_host_endpoint *ep); extern int usb_hcd_get_frame_number (struct usb_device *udev); extern struct usb_hcd *usb_create_hcd (const struct hc_driver *driver, struct device *dev, char *bus_name); extern struct usb_hcd *usb_get_hcd (struct usb_hcd *hcd); extern void usb_put_hcd (struct usb_hcd *hcd); extern int usb_add_hcd(struct usb_hcd *hcd, unsigned int irqnum, unsigned long irqflags); extern void usb_remove_hcd(struct usb_hcd *hcd); struct platform_device; extern void usb_hcd_platform_shutdown(struct platform_device* dev); #ifdef CONFIG_PCI struct pci_dev; struct pci_device_id; extern int usb_hcd_pci_probe (struct pci_dev *dev, const struct pci_device_id *id); extern void usb_hcd_pci_remove (struct pci_dev *dev); #ifdef CONFIG_PM extern int usb_hcd_pci_suspend (struct pci_dev *dev, pm_message_t state); extern int usb_hcd_pci_resume (struct pci_dev *dev); #endif /* CONFIG_PM */ extern void usb_hcd_pci_shutdown (struct pci_dev *dev); #endif /* CONFIG_PCI */ /* pci-ish (pdev null is ok) buffer alloc/mapping support */ int hcd_buffer_create (struct usb_hcd *hcd); void hcd_buffer_destroy (struct usb_hcd *hcd); void *hcd_buffer_alloc (struct usb_bus *bus, size_t size, gfp_t mem_flags, dma_addr_t *dma); void hcd_buffer_free (struct usb_bus *bus, size_t size, void *addr, dma_addr_t dma); /* generic bus glue, needed for host controllers that don't use PCI */ extern irqreturn_t usb_hcd_irq (int irq, void *__hcd); extern void usb_hc_died (struct usb_hcd *hcd); extern void usb_hcd_poll_rh_status(struct usb_hcd *hcd); /* -------------------------------------------------------------------------- */ /* Enumeration is only for the hub driver, or HCD virtual root hubs */ extern struct usb_device *usb_alloc_dev(struct usb_device *parent, struct usb_bus *, unsigned port); extern int usb_new_device(struct usb_device *dev); extern void usb_disconnect(struct usb_device **); extern int usb_get_configuration(struct usb_device *dev); extern void usb_destroy_configuration(struct usb_device *dev); /*-------------------------------------------------------------------------*/ /* * HCD Root Hub support */ #include "hub.h" /* (shifted) direction/type/recipient from the USB 2.0 spec, table 9.2 */ #define DeviceRequest \ ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8) #define DeviceOutRequest \ ((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8) #define InterfaceRequest \ ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8) #define EndpointRequest \ ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8) #define EndpointOutRequest \ ((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8) /* class requests from the USB 2.0 hub spec, table 11-15 */ /* GetBusState and SetHubDescriptor are optional, omitted */ #define ClearHubFeature (0x2000 | USB_REQ_CLEAR_FEATURE) #define ClearPortFeature (0x2300 | USB_REQ_CLEAR_FEATURE) #define GetHubDescriptor (0xa000 | USB_REQ_GET_DESCRIPTOR) #define GetHubStatus (0xa000 | USB_REQ_GET_STATUS) #define GetPortStatus (0xa300 | USB_REQ_GET_STATUS) #define SetHubFeature (0x2000 | USB_REQ_SET_FEATURE) #define SetPortFeature (0x2300 | USB_REQ_SET_FEATURE) /*-------------------------------------------------------------------------*/ /* * Generic bandwidth allocation constants/support */ #define FRAME_TIME_USECS 1000L #define BitTime(bytecount) (7 * 8 * bytecount / 6) /* with integer truncation */ /* Trying not to use worst-case bit-stuffing of (7/6 * 8 * bytecount) = 9.33 * bytecount */ /* bytecount = data payload byte count */ #define NS_TO_US(ns) ((ns + 500L) / 1000L) /* convert & round nanoseconds to microseconds */ /* * Full/low speed bandwidth allocation constants/support. */ #define BW_HOST_DELAY 1000L /* nanoseconds */ #define BW_HUB_LS_SETUP 333L /* nanoseconds */ /* 4 full-speed bit times (est.) */ #define FRAME_TIME_BITS 12000L /* frame = 1 millisecond */ #define FRAME_TIME_MAX_BITS_ALLOC (90L * FRAME_TIME_BITS / 100L) #define FRAME_TIME_MAX_USECS_ALLOC (90L * FRAME_TIME_USECS / 100L) /* * Ceiling [nano/micro]seconds (typical) for that many bytes at high speed * ISO is a bit less, no ACK ... from USB 2.0 spec, 5.11.3 (and needed * to preallocate bandwidth) */ #define USB2_HOST_DELAY 5 /* nsec, guess */ #define HS_NSECS(bytes) ( ((55 * 8 * 2083) \ + (2083UL * (3 + BitTime(bytes))))/1000 \ + USB2_HOST_DELAY) #define HS_NSECS_ISO(bytes) ( ((38 * 8 * 2083) \ + (2083UL * (3 + BitTime(bytes))))/1000 \ + USB2_HOST_DELAY) #define HS_USECS(bytes) NS_TO_US (HS_NSECS(bytes)) #define HS_USECS_ISO(bytes) NS_TO_US (HS_NSECS_ISO(bytes)) extern long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount); /*-------------------------------------------------------------------------*/ extern void usb_set_device_state(struct usb_device *udev, enum usb_device_state new_state); /*-------------------------------------------------------------------------*/ /* exported only within usbcore */ extern struct list_head usb_bus_list; extern struct mutex usb_bus_list_lock; extern wait_queue_head_t usb_kill_urb_queue; extern void usb_enable_root_hub_irq (struct usb_bus *bus); extern int usb_find_interface_driver (struct usb_device *dev, struct usb_interface *interface); #define usb_endpoint_out(ep_dir) (!((ep_dir) & USB_DIR_IN)) #ifdef CONFIG_PM extern void usb_hcd_resume_root_hub (struct usb_hcd *hcd); extern void usb_root_hub_lost_power (struct usb_device *rhdev); extern int hcd_bus_suspend(struct usb_device *rhdev); extern int hcd_bus_resume(struct usb_device *rhdev); #else static inline void usb_hcd_resume_root_hub(struct usb_hcd *hcd) { return; } #endif /* CONFIG_PM */ /* * USB device fs stuff */ #ifdef CONFIG_USB_DEVICEFS /* * these are expected to be called from the USB core/hub thread * with the kernel lock held */ extern void usbfs_update_special (void); extern int usbfs_init(void); extern void usbfs_cleanup(void); #else /* CONFIG_USB_DEVICEFS */ static inline void usbfs_update_special (void) {} static inline int usbfs_init(void) { return 0; } static inline void usbfs_cleanup(void) { } #endif /* CONFIG_USB_DEVICEFS */ /*-------------------------------------------------------------------------*/ #if defined(CONFIG_USB_MON) struct usb_mon_operations { void (*urb_submit)(struct usb_bus *bus, struct urb *urb); void (*urb_submit_error)(struct usb_bus *bus, struct urb *urb, int err); void (*urb_complete)(struct usb_bus *bus, struct urb *urb, int status); /* void (*urb_unlink)(struct usb_bus *bus, struct urb *urb); */ }; extern struct usb_mon_operations *mon_ops; static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb) { if (bus->monitored) (*mon_ops->urb_submit)(bus, urb); } static inline void usbmon_urb_submit_error(struct usb_bus *bus, struct urb *urb, int error) { if (bus->monitored) (*mon_ops->urb_submit_error)(bus, urb, error); } static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb, int status) { if (bus->monitored) (*mon_ops->urb_complete)(bus, urb, status); } int usb_mon_register(struct usb_mon_operations *ops); void usb_mon_deregister(void); #else static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb) {} static inline void usbmon_urb_submit_error(struct usb_bus *bus, struct urb *urb, int error) {} static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb, int status) {} #endif /* CONFIG_USB_MON */ /*-------------------------------------------------------------------------*/ /* hub.h ... DeviceRemovable in 2.4.2-ac11, gone in 2.4.10 */ // bleech -- resurfaced in 2.4.11 or 2.4.12 #define bitmap DeviceRemovable /*-------------------------------------------------------------------------*/ /* random stuff */ #define RUN_CONTEXT (in_irq () ? "in_irq" \ : (in_interrupt () ? "in_interrupt" : "can sleep")) /* This rwsem is for use only by the hub driver and ehci-hcd. * Nobody else should touch it. */ extern struct rw_semaphore ehci_cf_port_reset_rwsem; #endif /* __KERNEL__ */
Java
# -*- 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 re from PyQt5 import QtWidgets from picard import config from picard.plugin import ExtensionPoint class OptionsCheckError(Exception): def __init__(self, title, info): self.title = title self.info = info class OptionsPage(QtWidgets.QWidget): PARENT = None SORT_ORDER = 1000 ACTIVE = True STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }" STYLESHEET = "QLabel { qproperty-wordWrap: true; }" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setStyleSheet(self.STYLESHEET) def info(self): raise NotImplementedError def check(self): pass def load(self): pass def save(self): pass def restore_defaults(self): try: options = self.options except AttributeError: return old_options = {} for option in options: if option.section == 'setting': old_options[option.name] = config.setting[option.name] config.setting[option.name] = option.default self.load() # Restore the config values incase the user doesn't save after restoring defaults for key in old_options: config.setting[key] = old_options[key] def display_error(self, error): dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self) dialog.exec_() def init_regex_checker(self, regex_edit, regex_error): """ regex_edit : a widget supporting text() and textChanged() methods, ie QLineEdit regex_error : a widget supporting setStyleSheet() and setText() methods, ie. QLabel """ def check(): try: re.compile(regex_edit.text()) except re.error as e: raise OptionsCheckError(_("Regex Error"), string_(e)) def live_checker(text): regex_error.setStyleSheet("") regex_error.setText("") try: check() except OptionsCheckError as e: regex_error.setStyleSheet(self.STYLESHEET_ERROR) regex_error.setText(e.info) regex_edit.textChanged.connect(live_checker) _pages = ExtensionPoint() def register_options_page(page_class): _pages.register(page_class.__module__, page_class)
Java
/* MI Command Set - disassemble commands. Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. Contributed by Cygnus Solutions (a Red Hat company). This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "defs.h" #include "target.h" #include "value.h" #include "mi-cmds.h" #include "mi-getopt.h" #include "gdb_string.h" #include "ui-out.h" #include "disasm.h" /* The arguments to be passed on the command line and parsed here are: either: START-ADDRESS: address to start the disassembly at. END-ADDRESS: address to end the disassembly at. or: FILENAME: The name of the file where we want disassemble from. LINE: The line around which we want to disassemble. It will disassemble the function that contins that line. HOW_MANY: Number of disassembly lines to display. In mixed mode, it is the number of disassembly lines only, not counting the source lines. always required: MODE: 0 or 1 for disassembly only, or mixed source and disassembly, respectively. */ void mi_cmd_disassemble (char *command, char **argv, int argc) { CORE_ADDR start; int mixed_source_and_assembly; struct symtab *s; /* Which options have we processed ... */ int file_seen = 0; int line_seen = 0; int num_seen = 0; int start_seen = 0; int end_seen = 0; /* ... and their corresponding value. */ char *file_string = NULL; int line_num = -1; int how_many = -1; CORE_ADDR low = 0; CORE_ADDR high = 0; /* Options processing stuff. */ int optind = 0; char *optarg; enum opt { FILE_OPT, LINE_OPT, NUM_OPT, START_OPT, END_OPT }; static struct mi_opt opts[] = { {"f", FILE_OPT, 1}, {"l", LINE_OPT, 1}, {"n", NUM_OPT, 1}, {"s", START_OPT, 1}, {"e", END_OPT, 1}, { 0, 0, 0 } }; /* Get the options with their arguments. Keep track of what we encountered. */ while (1) { int opt = mi_getopt ("mi_cmd_disassemble", argc, argv, opts, &optind, &optarg); if (opt < 0) break; switch ((enum opt) opt) { case FILE_OPT: file_string = xstrdup (optarg); file_seen = 1; break; case LINE_OPT: line_num = atoi (optarg); line_seen = 1; break; case NUM_OPT: how_many = atoi (optarg); num_seen = 1; break; case START_OPT: low = parse_and_eval_address (optarg); start_seen = 1; break; case END_OPT: high = parse_and_eval_address (optarg); end_seen = 1; break; } } argv += optind; argc -= optind; /* Allow only filename + linenum (with how_many which is not required) OR start_addr + and_addr */ if (!((line_seen && file_seen && num_seen && !start_seen && !end_seen) || (line_seen && file_seen && !num_seen && !start_seen && !end_seen) || (!line_seen && !file_seen && !num_seen && start_seen && end_seen))) error ("mi_cmd_disassemble: Usage: ( [-f filename -l linenum [-n howmany]] | [-s startaddr -e endaddr]) [--] mixed_mode."); if (argc != 1) error ("mi_cmd_disassemble: Usage: [-f filename -l linenum [-n howmany]] [-s startaddr -e endaddr] [--] mixed_mode."); mixed_source_and_assembly = atoi (argv[0]); if ((mixed_source_and_assembly != 0) && (mixed_source_and_assembly != 1)) error (_("mi_cmd_disassemble: Mixed_mode argument must be 0 or 1.")); /* We must get the function beginning and end where line_num is contained. */ if (line_seen && file_seen) { s = lookup_symtab (file_string); if (s == NULL) error (_("mi_cmd_disassemble: Invalid filename.")); if (!find_line_pc (s, line_num, &start)) error (_("mi_cmd_disassemble: Invalid line number")); if (find_pc_partial_function (start, NULL, &low, &high) == 0) error (_("mi_cmd_disassemble: No function contains specified address")); } gdb_disassembly (uiout, file_string, line_num, mixed_source_and_assembly, how_many, low, high); }
Java
/** ****************************************************************************** * @file TIM/TIM_TimeBase/Src/main.c * @author MCD Application Team * @version V1.2.3 * @date 09-October-2015 * @brief This sample code shows how to use STM32F4xx TIM HAL API to generate * a time base. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2015 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /** @addtogroup STM32F4xx_HAL_Examples * @{ */ /** @addtogroup TIM_TimeBase * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Timer handler declaration */ TIM_HandleTypeDef TimHandle; uint32_t uwPrescalerValue = 0; /* Private function prototypes -----------------------------------------------*/ static void SystemClock_Config(void); static void Error_Handler(void); /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main(void) { /* STM32F4xx HAL library initialization: - Configure the Flash prefetch, instruction and Data caches - Configure the Systick to generate an interrupt each 1 msec - Set NVIC Group Priority to 4 - Global MSP (MCU Support Package) initialization */ HAL_Init(); /* Configure the system clock to 168 MHz */ SystemClock_Config(); /* Configure LED1 and LED3 */ BSP_LED_Init(LED1); BSP_LED_Init(LED3); /*##-1- Configure the TIM peripheral #######################################*/ /* ----------------------------------------------------------------------- In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1), since APB1 prescaler is different from 1. TIM3CLK = 2 * PCLK1 PCLK1 = HCLK / 4 => TIM3CLK = HCLK / 2 = SystemCoreClock /2 To get TIM3 counter clock at 10 KHz, the Prescaler is computed as following: Prescaler = (TIM3CLK / TIM3 counter clock) - 1 Prescaler = ((SystemCoreClock /2) /10 KHz) - 1 Note: SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file. Each time the core clock (HCLK) changes, user had to update SystemCoreClock variable value. Otherwise, any configuration based on this variable will be incorrect. This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetSysClockFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency ----------------------------------------------------------------------- */ /* Compute the prescaler value to have TIM3 counter clock equal to 10 KHz */ uwPrescalerValue = (uint32_t) ((SystemCoreClock /2) / 10000) - 1; /* Set TIMx instance */ TimHandle.Instance = TIMx; /* Initialize TIM3 peripheral as follow: + Period = 10000 - 1 + Prescaler = ((SystemCoreClock/2)/10000) - 1 + ClockDivision = 0 + Counter direction = Up */ TimHandle.Init.Period = 10000 - 1; TimHandle.Init.Prescaler = uwPrescalerValue; TimHandle.Init.ClockDivision = 0; TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; if(HAL_TIM_Base_Init(&TimHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*##-2- Start the TIM Base generation in interrupt mode ####################*/ /* Start Channel1 */ if(HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK) { /* Starting Error */ Error_Handler(); } /* Infinite loop */ while (1) { } } /** * @brief Period elapsed callback in non blocking mode * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { BSP_LED_Toggle(LED1); } /** * @brief This function is executed in case of error occurrence. * @param None * @retval None */ static void Error_Handler(void) { /* Turn LED3 on */ BSP_LED_On(LED3); while(1) { } } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSE) * SYSCLK(Hz) = 168000000 * HCLK(Hz) = 168000000 * AHB Prescaler = 1 * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = 25000000 * PLL_M = 25 * PLL_N = 336 * PLL_P = 2 * PLL_Q = 7 * VDD(V) = 3.3 * Main regulator output voltage = Scale1 mode * Flash Latency(WS) = 5 * @param None * @retval None */ static void SystemClock_Config(void) { RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_OscInitTypeDef RCC_OscInitStruct; /* Enable Power Control clock */ __HAL_RCC_PWR_CLK_ENABLE(); /* The voltage scaling allows optimizing the power consumption when the device is clocked below the maximum system frequency, to update the voltage scaling value regarding system frequency refer to product datasheet. */ __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /* Enable HSE Oscillator and activate PLL with HSE as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = 25; RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 7; HAL_RCC_OscConfig(&RCC_OscInitStruct); /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); /* STM32F405x/407x/415x/417x Revision Z devices: prefetch is supported */ if (HAL_GetREVID() == 0x1001) { /* Enable the Flash prefetch */ __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); } } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Java
<?php /* * DynamicHub * * Copyright (C) 2015-2016 LegendsOfMCPE * * 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, either version 3 of the License, or * (at your option) any later version. * * @author LegendsOfMCPE */ namespace DynamicHub\Module\Match; class MatchBaseConfig{ // players public $maxPlayers; public $semiMaxPlayers; public $minPlayers; // time, in seconds public $minWaitTime; public $maxWaitTime; public $maxMatchTime; public $maxPrepTime; // positions public $playerJoinPositions = []; public $spectatorJoinPositions = []; public function getNextPlayerJoinPosition(){ if(next($this->playerJoinPositions) === false){ reset($this->playerJoinPositions); } return current($this->playerJoinPositions); } public function getNextSpectatorJoinPosition(){ if(next($this->spectatorJoinPositions) === false){ reset($this->spectatorJoinPositions); } return current($this->spectatorJoinPositions); } }
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LogicaDeNegocios")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Intel Corporation")] [assembly: AssemblyProduct("LogicaDeNegocios")] [assembly: AssemblyCopyright("Copyright © Intel Corporation 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("979b681f-8f57-479b-a119-c830ef08f826")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>schrodinger.application.desmond.replica_sid_generator.ProteinReport</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="schrodinger-module.html">Package&nbsp;schrodinger</a> :: <a href="schrodinger.application-module.html">Package&nbsp;application</a> :: <a href="schrodinger.application.desmond-module.html">Package&nbsp;desmond</a> :: <a href="schrodinger.application.desmond.replica_sid_generator-module.html">Module&nbsp;replica_sid_generator</a> :: Class&nbsp;ProteinReport </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="schrodinger.application.desmond.replica_sid_generator.ProteinReport-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class ProteinReport</h1><p class="nomargin-top"></p> <pre class="base-tree"> <a href="object-class.html">object</a> --+ | <strong class="uidshort">ProteinReport</strong> </pre> <hr /> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.application.desmond.replica_sid_generator.ProteinReport-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">cms_st</span>)</span><br /> x.__init__(...) initializes x; see help(type(x)) for signature</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="export"></a><span class="summary-sig-name">export</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_hot_atoms"></a><span class="summary-sig-name">get_hot_atoms</span>(<span class="summary-sig-arg">self</span>)</span><br /> Returns number of atoms in the hot region</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_residues"></a><span class="summary-sig-name">get_residues</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_number_atoms"></a><span class="summary-sig-name">get_number_atoms</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_protein"></a><span class="summary-sig-name">get_protein</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__delattr__">__delattr__</a></code>, <code><a href="object-class.html#__format__">__format__</a></code>, <code><a href="object-class.html#__getattribute__">__getattribute__</a></code>, <code><a href="object-class.html#__hash__">__hash__</a></code>, <code><a href="object-class.html#__new__">__new__</a></code>, <code><a href="object-class.html#__reduce__">__reduce__</a></code>, <code><a href="object-class.html#__reduce_ex__">__reduce_ex__</a></code>, <code><a href="object-class.html#__repr__">__repr__</a></code>, <code><a href="object-class.html#__setattr__">__setattr__</a></code>, <code><a href="object-class.html#__sizeof__">__sizeof__</a></code>, <code><a href="object-class.html#__str__">__str__</a></code>, <code><a href="object-class.html#__subclasshook__">__subclasshook__</a></code> </p> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__class__">__class__</a></code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="__init__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">cms_st</span>)</span> <br /><em class="fname">(Constructor)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>x.__init__(...) initializes x; see help(type(x)) for signature</p> <dl class="fields"> <dt>Overrides: object.__init__ <dd><em class="note">(inherited documentation)</em></dd> </dt> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Sat May 9 06:31:10 2015 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
Java
<?php /* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * Service definition for Pagespeedonline (v1). * * <p> * Lets you analyze the performance of a web page and get tailored suggestions to make that page faster. * </p> * * <p> * For more information about this service, see the API * <a href="https://developers.google.com/speed/docs/insights/v1/getting_started" target="_blank">Documentation</a> * </p> * * @author Google, Inc. */ class GoogleGAL_Service_Pagespeedonline extends GoogleGAL_Service { public $pagespeedapi; /** * Constructs the internal representation of the Pagespeedonline service. * * @param GoogleGAL_Client $client */ public function __construct(GoogleGAL_Client $client) { parent::__construct($client); $this->servicePath = 'pagespeedonline/v1/'; $this->version = 'v1'; $this->serviceName = 'pagespeedonline'; $this->pagespeedapi = new GoogleGAL_Service_Pagespeedonline_Pagespeedapi_Resource( $this, $this->serviceName, 'pagespeedapi', array( 'methods' => array( 'runpagespeed' => array( 'path' => 'runPagespeed', 'httpMethod' => 'GET', 'parameters' => array( 'url' => array( 'location' => 'query', 'type' => 'string', 'required' => true, ), 'screenshot' => array( 'location' => 'query', 'type' => 'boolean', ), 'locale' => array( 'location' => 'query', 'type' => 'string', ), 'snapshots' => array( 'location' => 'query', 'type' => 'boolean', ), 'strategy' => array( 'location' => 'query', 'type' => 'string', ), 'rule' => array( 'location' => 'query', 'type' => 'string', 'repeated' => true, ), 'filter_third_party_resources' => array( 'location' => 'query', 'type' => 'boolean', ), ), ), ) ) ); } } /** * The "pagespeedapi" collection of methods. * Typical usage is: * <code> * $pagespeedonlineService = new GoogleGAL_Service_Pagespeedonline(...); * $pagespeedapi = $pagespeedonlineService->pagespeedapi; * </code> */ class GoogleGAL_Service_Pagespeedonline_Pagespeedapi_Resource extends GoogleGAL_Service_Resource { /** * Runs Page Speed analysis on the page at the specified URL, and returns a Page * Speed score, a list of suggestions to make that page faster, and other * information. (pagespeedapi.runpagespeed) * * @param string $url * The URL to fetch and analyze * @param array $optParams Optional parameters. * * @opt_param bool screenshot * Indicates if binary data containing a screenshot should be included * @opt_param string locale * The locale used to localize formatted results * @opt_param bool snapshots * Indicates if binary data containing snapshot images should be included * @opt_param string strategy * The analysis strategy to use * @opt_param string rule * A Page Speed rule to run; if none are given, all rules are run * @opt_param bool filter_third_party_resources * Indicates if third party resources should be filtered out before PageSpeed analysis. * @return GoogleGAL_Service_Pagespeedonline_Result */ public function runpagespeed($url, $optParams = array()) { $params = array('url' => $url); $params = array_merge($params, $optParams); return $this->call('runpagespeed', array($params), "GoogleGAL_Service_Pagespeedonline_Result"); } } class GoogleGAL_Service_Pagespeedonline_Result extends GoogleGAL_Collection { protected $formattedResultsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResults'; protected $formattedResultsDataType = ''; public $id; public $invalidRules; public $kind; protected $pageStatsType = 'GoogleGAL_Service_Pagespeedonline_ResultPageStats'; protected $pageStatsDataType = ''; public $responseCode; public $score; protected $screenshotType = 'GoogleGAL_Service_Pagespeedonline_ResultScreenshot'; protected $screenshotDataType = ''; public $title; protected $versionType = 'GoogleGAL_Service_Pagespeedonline_ResultVersion'; protected $versionDataType = ''; public function setFormattedResults(GoogleGAL_Service_Pagespeedonline_ResultFormattedResults $formattedResults) { $this->formattedResults = $formattedResults; } public function getFormattedResults() { return $this->formattedResults; } public function setId($id) { $this->id = $id; } public function getId() { return $this->id; } public function setInvalidRules($invalidRules) { $this->invalidRules = $invalidRules; } public function getInvalidRules() { return $this->invalidRules; } public function setKind($kind) { $this->kind = $kind; } public function getKind() { return $this->kind; } public function setPageStats(GoogleGAL_Service_Pagespeedonline_ResultPageStats $pageStats) { $this->pageStats = $pageStats; } public function getPageStats() { return $this->pageStats; } public function setResponseCode($responseCode) { $this->responseCode = $responseCode; } public function getResponseCode() { return $this->responseCode; } public function setScore($score) { $this->score = $score; } public function getScore() { return $this->score; } public function setScreenshot(GoogleGAL_Service_Pagespeedonline_ResultScreenshot $screenshot) { $this->screenshot = $screenshot; } public function getScreenshot() { return $this->screenshot; } public function setTitle($title) { $this->title = $title; } public function getTitle() { return $this->title; } public function setVersion(GoogleGAL_Service_Pagespeedonline_ResultVersion $version) { $this->version = $version; } public function getVersion() { return $this->version; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResults extends GoogleGAL_Model { public $locale; protected $ruleResultsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElement'; protected $ruleResultsDataType = 'map'; public function setLocale($locale) { $this->locale = $locale; } public function getLocale() { return $this->locale; } public function setRuleResults($ruleResults) { $this->ruleResults = $ruleResults; } public function getRuleResults() { return $this->ruleResults; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElement extends GoogleGAL_Collection { public $localizedRuleName; public $ruleImpact; protected $urlBlocksType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocks'; protected $urlBlocksDataType = 'array'; public function setLocalizedRuleName($localizedRuleName) { $this->localizedRuleName = $localizedRuleName; } public function getLocalizedRuleName() { return $this->localizedRuleName; } public function setRuleImpact($ruleImpact) { $this->ruleImpact = $ruleImpact; } public function getRuleImpact() { return $this->ruleImpact; } public function setUrlBlocks($urlBlocks) { $this->urlBlocks = $urlBlocks; } public function getUrlBlocks() { return $this->urlBlocks; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocks extends GoogleGAL_Collection { protected $headerType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeader'; protected $headerDataType = ''; protected $urlsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrls'; protected $urlsDataType = 'array'; public function setHeader(GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeader $header) { $this->header = $header; } public function getHeader() { return $this->header; } public function setUrls($urls) { $this->urls = $urls; } public function getUrls() { return $this->urls; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeader extends GoogleGAL_Collection { protected $argsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeaderArgs'; protected $argsDataType = 'array'; public $format; public function setArgs($args) { $this->args = $args; } public function getArgs() { return $this->args; } public function setFormat($format) { $this->format = $format; } public function getFormat() { return $this->format; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeaderArgs extends GoogleGAL_Model { public $type; public $value; public function setType($type) { $this->type = $type; } public function getType() { return $this->type; } public function setValue($value) { $this->value = $value; } public function getValue() { return $this->value; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrls extends GoogleGAL_Collection { protected $detailsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetails'; protected $detailsDataType = 'array'; protected $resultType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResult'; protected $resultDataType = ''; public function setDetails($details) { $this->details = $details; } public function getDetails() { return $this->details; } public function setResult(GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResult $result) { $this->result = $result; } public function getResult() { return $this->result; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetails extends GoogleGAL_Collection { protected $argsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetailsArgs'; protected $argsDataType = 'array'; public $format; public function setArgs($args) { $this->args = $args; } public function getArgs() { return $this->args; } public function setFormat($format) { $this->format = $format; } public function getFormat() { return $this->format; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetailsArgs extends GoogleGAL_Model { public $type; public $value; public function setType($type) { $this->type = $type; } public function getType() { return $this->type; } public function setValue($value) { $this->value = $value; } public function getValue() { return $this->value; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResult extends GoogleGAL_Collection { protected $argsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResultArgs'; protected $argsDataType = 'array'; public $format; public function setArgs($args) { $this->args = $args; } public function getArgs() { return $this->args; } public function setFormat($format) { $this->format = $format; } public function getFormat() { return $this->format; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResultArgs extends GoogleGAL_Model { public $type; public $value; public function setType($type) { $this->type = $type; } public function getType() { return $this->type; } public function setValue($value) { $this->value = $value; } public function getValue() { return $this->value; } } class GoogleGAL_Service_Pagespeedonline_ResultPageStats extends GoogleGAL_Model { public $cssResponseBytes; public $flashResponseBytes; public $htmlResponseBytes; public $imageResponseBytes; public $javascriptResponseBytes; public $numberCssResources; public $numberHosts; public $numberJsResources; public $numberResources; public $numberStaticResources; public $otherResponseBytes; public $textResponseBytes; public $totalRequestBytes; public function setCssResponseBytes($cssResponseBytes) { $this->cssResponseBytes = $cssResponseBytes; } public function getCssResponseBytes() { return $this->cssResponseBytes; } public function setFlashResponseBytes($flashResponseBytes) { $this->flashResponseBytes = $flashResponseBytes; } public function getFlashResponseBytes() { return $this->flashResponseBytes; } public function setHtmlResponseBytes($htmlResponseBytes) { $this->htmlResponseBytes = $htmlResponseBytes; } public function getHtmlResponseBytes() { return $this->htmlResponseBytes; } public function setImageResponseBytes($imageResponseBytes) { $this->imageResponseBytes = $imageResponseBytes; } public function getImageResponseBytes() { return $this->imageResponseBytes; } public function setJavascriptResponseBytes($javascriptResponseBytes) { $this->javascriptResponseBytes = $javascriptResponseBytes; } public function getJavascriptResponseBytes() { return $this->javascriptResponseBytes; } public function setNumberCssResources($numberCssResources) { $this->numberCssResources = $numberCssResources; } public function getNumberCssResources() { return $this->numberCssResources; } public function setNumberHosts($numberHosts) { $this->numberHosts = $numberHosts; } public function getNumberHosts() { return $this->numberHosts; } public function setNumberJsResources($numberJsResources) { $this->numberJsResources = $numberJsResources; } public function getNumberJsResources() { return $this->numberJsResources; } public function setNumberResources($numberResources) { $this->numberResources = $numberResources; } public function getNumberResources() { return $this->numberResources; } public function setNumberStaticResources($numberStaticResources) { $this->numberStaticResources = $numberStaticResources; } public function getNumberStaticResources() { return $this->numberStaticResources; } public function setOtherResponseBytes($otherResponseBytes) { $this->otherResponseBytes = $otherResponseBytes; } public function getOtherResponseBytes() { return $this->otherResponseBytes; } public function setTextResponseBytes($textResponseBytes) { $this->textResponseBytes = $textResponseBytes; } public function getTextResponseBytes() { return $this->textResponseBytes; } public function setTotalRequestBytes($totalRequestBytes) { $this->totalRequestBytes = $totalRequestBytes; } public function getTotalRequestBytes() { return $this->totalRequestBytes; } } class GoogleGAL_Service_Pagespeedonline_ResultScreenshot extends GoogleGAL_Model { public $data; public $height; public $mimeType; public $width; public function setData($data) { $this->data = $data; } public function getData() { return $this->data; } public function setHeight($height) { $this->height = $height; } public function getHeight() { return $this->height; } public function setMimeType($mimeType) { $this->mimeType = $mimeType; } public function getMimeType() { return $this->mimeType; } public function setWidth($width) { $this->width = $width; } public function getWidth() { return $this->width; } } class GoogleGAL_Service_Pagespeedonline_ResultVersion extends GoogleGAL_Model { public $major; public $minor; public function setMajor($major) { $this->major = $major; } public function getMajor() { return $this->major; } public function setMinor($minor) { $this->minor = $minor; } public function getMinor() { return $this->minor; } }
Java
/* SPDX-License-Identifier: LGPL-2.1+ */ /*** This file is part of systemd. Copyright 2010 Lennart Poettering systemd 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; either version 2.1 of the License, or (at your option) any later version. systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>. ***/ #include <errno.h> #include <sys/epoll.h> #include <sys/stat.h> #include <unistd.h> #include "libudev.h" #include "alloc-util.h" #include "dbus-swap.h" #include "escape.h" #include "exit-status.h" #include "fd-util.h" #include "format-util.h" #include "fstab-util.h" #include "parse-util.h" #include "path-util.h" #include "process-util.h" #include "special.h" #include "string-table.h" #include "string-util.h" #include "swap.h" #include "udev-util.h" #include "unit-name.h" #include "unit.h" #include "virt.h" static const UnitActiveState state_translation_table[_SWAP_STATE_MAX] = { [SWAP_DEAD] = UNIT_INACTIVE, [SWAP_ACTIVATING] = UNIT_ACTIVATING, [SWAP_ACTIVATING_DONE] = UNIT_ACTIVE, [SWAP_ACTIVE] = UNIT_ACTIVE, [SWAP_DEACTIVATING] = UNIT_DEACTIVATING, [SWAP_DEACTIVATING_SIGTERM] = UNIT_DEACTIVATING, [SWAP_DEACTIVATING_SIGKILL] = UNIT_DEACTIVATING, [SWAP_FAILED] = UNIT_FAILED }; static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata); static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata); static bool SWAP_STATE_WITH_PROCESS(SwapState state) { return IN_SET(state, SWAP_ACTIVATING, SWAP_ACTIVATING_DONE, SWAP_DEACTIVATING, SWAP_DEACTIVATING_SIGTERM, SWAP_DEACTIVATING_SIGKILL); } static void swap_unset_proc_swaps(Swap *s) { assert(s); if (!s->from_proc_swaps) return; s->parameters_proc_swaps.what = mfree(s->parameters_proc_swaps.what); s->from_proc_swaps = false; } static int swap_set_devnode(Swap *s, const char *devnode) { Hashmap *swaps; Swap *first; int r; assert(s); r = hashmap_ensure_allocated(&UNIT(s)->manager->swaps_by_devnode, &path_hash_ops); if (r < 0) return r; swaps = UNIT(s)->manager->swaps_by_devnode; if (s->devnode) { first = hashmap_get(swaps, s->devnode); LIST_REMOVE(same_devnode, first, s); if (first) hashmap_replace(swaps, first->devnode, first); else hashmap_remove(swaps, s->devnode); s->devnode = mfree(s->devnode); } if (devnode) { s->devnode = strdup(devnode); if (!s->devnode) return -ENOMEM; first = hashmap_get(swaps, s->devnode); LIST_PREPEND(same_devnode, first, s); return hashmap_replace(swaps, first->devnode, first); } return 0; } static void swap_init(Unit *u) { Swap *s = SWAP(u); assert(s); assert(UNIT(s)->load_state == UNIT_STUB); s->timeout_usec = u->manager->default_timeout_start_usec; s->exec_context.std_output = u->manager->default_std_output; s->exec_context.std_error = u->manager->default_std_error; s->parameters_proc_swaps.priority = s->parameters_fragment.priority = -1; s->control_command_id = _SWAP_EXEC_COMMAND_INVALID; u->ignore_on_isolate = true; } static void swap_unwatch_control_pid(Swap *s) { assert(s); if (s->control_pid <= 0) return; unit_unwatch_pid(UNIT(s), s->control_pid); s->control_pid = 0; } static void swap_done(Unit *u) { Swap *s = SWAP(u); assert(s); swap_unset_proc_swaps(s); swap_set_devnode(s, NULL); s->what = mfree(s->what); s->parameters_fragment.what = mfree(s->parameters_fragment.what); s->parameters_fragment.options = mfree(s->parameters_fragment.options); s->exec_runtime = exec_runtime_unref(s->exec_runtime, false); exec_command_done_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX); s->control_command = NULL; dynamic_creds_unref(&s->dynamic_creds); swap_unwatch_control_pid(s); s->timer_event_source = sd_event_source_unref(s->timer_event_source); } static int swap_arm_timer(Swap *s, usec_t usec) { int r; assert(s); if (s->timer_event_source) { r = sd_event_source_set_time(s->timer_event_source, usec); if (r < 0) return r; return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT); } if (usec == USEC_INFINITY) return 0; r = sd_event_add_time( UNIT(s)->manager->event, &s->timer_event_source, CLOCK_MONOTONIC, usec, 0, swap_dispatch_timer, s); if (r < 0) return r; (void) sd_event_source_set_description(s->timer_event_source, "swap-timer"); return 0; } static int swap_add_device_dependencies(Swap *s) { assert(s); if (!s->what) return 0; if (!s->from_fragment) return 0; if (is_device_path(s->what)) return unit_add_node_dependency(UNIT(s), s->what, MANAGER_IS_SYSTEM(UNIT(s)->manager), UNIT_BINDS_TO, UNIT_DEPENDENCY_FILE); else /* File based swap devices need to be ordered after * systemd-remount-fs.service, since they might need a * writable file system. */ return unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_REMOUNT_FS_SERVICE, NULL, true, UNIT_DEPENDENCY_FILE); } static int swap_add_default_dependencies(Swap *s) { int r; assert(s); if (!UNIT(s)->default_dependencies) return 0; if (!MANAGER_IS_SYSTEM(UNIT(s)->manager)) return 0; if (detect_container() > 0) return 0; /* swap units generated for the swap dev links are missing the * ordering dep against the swap target. */ r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SWAP_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT); if (r < 0) return r; return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT); } static int swap_verify(Swap *s) { _cleanup_free_ char *e = NULL; int r; if (UNIT(s)->load_state != UNIT_LOADED) return 0; r = unit_name_from_path(s->what, ".swap", &e); if (r < 0) return log_unit_error_errno(UNIT(s), r, "Failed to generate unit name from path: %m"); if (!unit_has_name(UNIT(s), e)) { log_unit_error(UNIT(s), "Value of What= and unit name do not match, not loading."); return -EINVAL; } if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) { log_unit_error(UNIT(s), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load."); return -EINVAL; } return 0; } static int swap_load_devnode(Swap *s) { _cleanup_udev_device_unref_ struct udev_device *d = NULL; struct stat st; const char *p; assert(s); if (stat(s->what, &st) < 0 || !S_ISBLK(st.st_mode)) return 0; d = udev_device_new_from_devnum(UNIT(s)->manager->udev, 'b', st.st_rdev); if (!d) return 0; p = udev_device_get_devnode(d); if (!p) return 0; return swap_set_devnode(s, p); } static int swap_load(Unit *u) { int r; Swap *s = SWAP(u); assert(s); assert(u->load_state == UNIT_STUB); /* Load a .swap file */ if (SWAP(u)->from_proc_swaps) r = unit_load_fragment_and_dropin_optional(u); else r = unit_load_fragment_and_dropin(u); if (r < 0) return r; if (u->load_state == UNIT_LOADED) { if (UNIT(s)->fragment_path) s->from_fragment = true; if (!s->what) { if (s->parameters_fragment.what) s->what = strdup(s->parameters_fragment.what); else if (s->parameters_proc_swaps.what) s->what = strdup(s->parameters_proc_swaps.what); else { r = unit_name_to_path(u->id, &s->what); if (r < 0) return r; } if (!s->what) return -ENOMEM; } path_kill_slashes(s->what); if (!UNIT(s)->description) { r = unit_set_description(u, s->what); if (r < 0) return r; } r = unit_require_mounts_for(UNIT(s), s->what, UNIT_DEPENDENCY_IMPLICIT); if (r < 0) return r; r = swap_add_device_dependencies(s); if (r < 0) return r; r = swap_load_devnode(s); if (r < 0) return r; r = unit_patch_contexts(u); if (r < 0) return r; r = unit_add_exec_dependencies(u, &s->exec_context); if (r < 0) return r; r = unit_set_default_slice(u); if (r < 0) return r; r = swap_add_default_dependencies(s); if (r < 0) return r; } return swap_verify(s); } static int swap_setup_unit( Manager *m, const char *what, const char *what_proc_swaps, int priority, bool set_flags) { _cleanup_free_ char *e = NULL; bool delete = false; Unit *u = NULL; int r; SwapParameters *p; assert(m); assert(what); assert(what_proc_swaps); r = unit_name_from_path(what, ".swap", &e); if (r < 0) return log_unit_error_errno(u, r, "Failed to generate unit name from path: %m"); u = manager_get_unit(m, e); if (u && SWAP(u)->from_proc_swaps && !path_equal(SWAP(u)->parameters_proc_swaps.what, what_proc_swaps)) { log_error("Swap %s appeared twice with different device paths %s and %s", e, SWAP(u)->parameters_proc_swaps.what, what_proc_swaps); return -EEXIST; } if (!u) { delete = true; r = unit_new_for_name(m, sizeof(Swap), e, &u); if (r < 0) goto fail; SWAP(u)->what = strdup(what); if (!SWAP(u)->what) { r = -ENOMEM; goto fail; } unit_add_to_load_queue(u); } else delete = false; p = &SWAP(u)->parameters_proc_swaps; if (!p->what) { p->what = strdup(what_proc_swaps); if (!p->what) { r = -ENOMEM; goto fail; } } if (set_flags) { SWAP(u)->is_active = true; SWAP(u)->just_activated = !SWAP(u)->from_proc_swaps; } SWAP(u)->from_proc_swaps = true; p->priority = priority; unit_add_to_dbus_queue(u); return 0; fail: log_unit_warning_errno(u, r, "Failed to load swap unit: %m"); if (delete) unit_free(u); return r; } static int swap_process_new(Manager *m, const char *device, int prio, bool set_flags) { _cleanup_udev_device_unref_ struct udev_device *d = NULL; struct udev_list_entry *item = NULL, *first = NULL; const char *dn; struct stat st; int r; assert(m); r = swap_setup_unit(m, device, device, prio, set_flags); if (r < 0) return r; /* If this is a block device, then let's add duplicates for * all other names of this block device */ if (stat(device, &st) < 0 || !S_ISBLK(st.st_mode)) return 0; d = udev_device_new_from_devnum(m->udev, 'b', st.st_rdev); if (!d) return 0; /* Add the main device node */ dn = udev_device_get_devnode(d); if (dn && !streq(dn, device)) swap_setup_unit(m, dn, device, prio, set_flags); /* Add additional units for all symlinks */ first = udev_device_get_devlinks_list_entry(d); udev_list_entry_foreach(item, first) { const char *p; /* Don't bother with the /dev/block links */ p = udev_list_entry_get_name(item); if (streq(p, device)) continue; if (path_startswith(p, "/dev/block/")) continue; if (stat(p, &st) >= 0) if (!S_ISBLK(st.st_mode) || st.st_rdev != udev_device_get_devnum(d)) continue; swap_setup_unit(m, p, device, prio, set_flags); } return r; } static void swap_set_state(Swap *s, SwapState state) { SwapState old_state; Swap *other; assert(s); old_state = s->state; s->state = state; if (!SWAP_STATE_WITH_PROCESS(state)) { s->timer_event_source = sd_event_source_unref(s->timer_event_source); swap_unwatch_control_pid(s); s->control_command = NULL; s->control_command_id = _SWAP_EXEC_COMMAND_INVALID; } if (state != old_state) log_unit_debug(UNIT(s), "Changed %s -> %s", swap_state_to_string(old_state), swap_state_to_string(state)); unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true); /* If there other units for the same device node have a job queued it might be worth checking again if it is runnable now. This is necessary, since swap_start() refuses operation with EAGAIN if there's already another job for the same device node queued. */ LIST_FOREACH_OTHERS(same_devnode, other, s) if (UNIT(other)->job) job_add_to_run_queue(UNIT(other)->job); } static int swap_coldplug(Unit *u) { Swap *s = SWAP(u); SwapState new_state = SWAP_DEAD; int r; assert(s); assert(s->state == SWAP_DEAD); if (s->deserialized_state != s->state) new_state = s->deserialized_state; else if (s->from_proc_swaps) new_state = SWAP_ACTIVE; if (new_state == s->state) return 0; if (s->control_pid > 0 && pid_is_unwaited(s->control_pid) && SWAP_STATE_WITH_PROCESS(new_state)) { r = unit_watch_pid(UNIT(s), s->control_pid); if (r < 0) return r; r = swap_arm_timer(s, usec_add(u->state_change_timestamp.monotonic, s->timeout_usec)); if (r < 0) return r; } if (!IN_SET(new_state, SWAP_DEAD, SWAP_FAILED)) { (void) unit_setup_dynamic_creds(u); (void) unit_setup_exec_runtime(u); } swap_set_state(s, new_state); return 0; } static void swap_dump(Unit *u, FILE *f, const char *prefix) { char buf[FORMAT_TIMESPAN_MAX]; Swap *s = SWAP(u); SwapParameters *p; assert(s); assert(f); if (s->from_proc_swaps) p = &s->parameters_proc_swaps; else if (s->from_fragment) p = &s->parameters_fragment; else p = NULL; fprintf(f, "%sSwap State: %s\n" "%sResult: %s\n" "%sWhat: %s\n" "%sFrom /proc/swaps: %s\n" "%sFrom fragment: %s\n", prefix, swap_state_to_string(s->state), prefix, swap_result_to_string(s->result), prefix, s->what, prefix, yes_no(s->from_proc_swaps), prefix, yes_no(s->from_fragment)); if (s->devnode) fprintf(f, "%sDevice Node: %s\n", prefix, s->devnode); if (p) fprintf(f, "%sPriority: %i\n" "%sOptions: %s\n", prefix, p->priority, prefix, strempty(p->options)); fprintf(f, "%sTimeoutSec: %s\n", prefix, format_timespan(buf, sizeof(buf), s->timeout_usec, USEC_PER_SEC)); if (s->control_pid > 0) fprintf(f, "%sControl PID: "PID_FMT"\n", prefix, s->control_pid); exec_context_dump(&s->exec_context, f, prefix); kill_context_dump(&s->kill_context, f, prefix); cgroup_context_dump(&s->cgroup_context, f, prefix); } static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) { ExecParameters exec_params = { .flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN, .stdin_fd = -1, .stdout_fd = -1, .stderr_fd = -1, }; pid_t pid; int r; assert(s); assert(c); assert(_pid); r = unit_prepare_exec(UNIT(s)); if (r < 0) return r; r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec)); if (r < 0) goto fail; manager_set_exec_params(UNIT(s)->manager, &exec_params); unit_set_exec_params(UNIT(s), &exec_params); r = exec_spawn(UNIT(s), c, &s->exec_context, &exec_params, s->exec_runtime, &s->dynamic_creds, &pid); if (r < 0) goto fail; r = unit_watch_pid(UNIT(s), pid); if (r < 0) /* FIXME: we need to do something here */ goto fail; *_pid = pid; return 0; fail: s->timer_event_source = sd_event_source_unref(s->timer_event_source); return r; } static void swap_enter_dead(Swap *s, SwapResult f) { assert(s); if (s->result == SWAP_SUCCESS) s->result = f; if (s->result != SWAP_SUCCESS) log_unit_warning(UNIT(s), "Failed with result '%s'.", swap_result_to_string(s->result)); swap_set_state(s, s->result != SWAP_SUCCESS ? SWAP_FAILED : SWAP_DEAD); s->exec_runtime = exec_runtime_unref(s->exec_runtime, true); exec_context_destroy_runtime_directory(&s->exec_context, UNIT(s)->manager->prefix[EXEC_DIRECTORY_RUNTIME]); unit_unref_uid_gid(UNIT(s), true); dynamic_creds_destroy(&s->dynamic_creds); } static void swap_enter_active(Swap *s, SwapResult f) { assert(s); if (s->result == SWAP_SUCCESS) s->result = f; swap_set_state(s, SWAP_ACTIVE); } static void swap_enter_dead_or_active(Swap *s, SwapResult f) { assert(s); if (s->from_proc_swaps) swap_enter_active(s, f); else swap_enter_dead(s, f); } static void swap_enter_signal(Swap *s, SwapState state, SwapResult f) { int r; KillOperation kop; assert(s); if (s->result == SWAP_SUCCESS) s->result = f; if (state == SWAP_DEACTIVATING_SIGTERM) kop = KILL_TERMINATE; else kop = KILL_KILL; r = unit_kill_context(UNIT(s), &s->kill_context, kop, -1, s->control_pid, false); if (r < 0) goto fail; if (r > 0) { r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec)); if (r < 0) goto fail; swap_set_state(s, state); } else if (state == SWAP_DEACTIVATING_SIGTERM && s->kill_context.send_sigkill) swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_SUCCESS); else swap_enter_dead_or_active(s, SWAP_SUCCESS); return; fail: log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m"); swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES); } static void swap_enter_activating(Swap *s) { _cleanup_free_ char *opts = NULL; int r; assert(s); unit_warn_leftover_processes(UNIT(s)); s->control_command_id = SWAP_EXEC_ACTIVATE; s->control_command = s->exec_command + SWAP_EXEC_ACTIVATE; if (s->from_fragment) { int priority = -1; r = fstab_find_pri(s->parameters_fragment.options, &priority); if (r < 0) log_warning_errno(r, "Failed to parse swap priority \"%s\", ignoring: %m", s->parameters_fragment.options); else if (r == 1 && s->parameters_fragment.priority >= 0) log_warning("Duplicate swap priority configuration by Priority and Options fields."); if (r <= 0 && s->parameters_fragment.priority >= 0) { if (s->parameters_fragment.options) r = asprintf(&opts, "%s,pri=%i", s->parameters_fragment.options, s->parameters_fragment.priority); else r = asprintf(&opts, "pri=%i", s->parameters_fragment.priority); if (r < 0) goto fail; } } r = exec_command_set(s->control_command, "/sbin/swapon", NULL); if (r < 0) goto fail; if (s->parameters_fragment.options || opts) { r = exec_command_append(s->control_command, "-o", opts ? : s->parameters_fragment.options, NULL); if (r < 0) goto fail; } r = exec_command_append(s->control_command, s->what, NULL); if (r < 0) goto fail; swap_unwatch_control_pid(s); r = swap_spawn(s, s->control_command, &s->control_pid); if (r < 0) goto fail; swap_set_state(s, SWAP_ACTIVATING); return; fail: log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapon' task: %m"); swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES); } static void swap_enter_deactivating(Swap *s) { int r; assert(s); s->control_command_id = SWAP_EXEC_DEACTIVATE; s->control_command = s->exec_command + SWAP_EXEC_DEACTIVATE; r = exec_command_set(s->control_command, "/sbin/swapoff", s->what, NULL); if (r < 0) goto fail; swap_unwatch_control_pid(s); r = swap_spawn(s, s->control_command, &s->control_pid); if (r < 0) goto fail; swap_set_state(s, SWAP_DEACTIVATING); return; fail: log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapoff' task: %m"); swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES); } static int swap_start(Unit *u) { Swap *s = SWAP(u), *other; int r; assert(s); /* We cannot fulfill this request right now, try again later please! */ if (IN_SET(s->state, SWAP_DEACTIVATING, SWAP_DEACTIVATING_SIGTERM, SWAP_DEACTIVATING_SIGKILL)) return -EAGAIN; /* Already on it! */ if (s->state == SWAP_ACTIVATING) return 0; assert(IN_SET(s->state, SWAP_DEAD, SWAP_FAILED)); if (detect_container() > 0) return -EPERM; /* If there's a job for another swap unit for the same node * running, then let's not dispatch this one for now, and wait * until that other job has finished. */ LIST_FOREACH_OTHERS(same_devnode, other, s) if (UNIT(other)->job && UNIT(other)->job->state == JOB_RUNNING) return -EAGAIN; r = unit_start_limit_test(u); if (r < 0) { swap_enter_dead(s, SWAP_FAILURE_START_LIMIT_HIT); return r; } r = unit_acquire_invocation_id(u); if (r < 0) return r; s->result = SWAP_SUCCESS; u->reset_accounting = true; swap_enter_activating(s); return 1; } static int swap_stop(Unit *u) { Swap *s = SWAP(u); assert(s); switch (s->state) { case SWAP_DEACTIVATING: case SWAP_DEACTIVATING_SIGTERM: case SWAP_DEACTIVATING_SIGKILL: /* Already on it */ return 0; case SWAP_ACTIVATING: case SWAP_ACTIVATING_DONE: /* There's a control process pending, directly enter kill mode */ swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_SUCCESS); return 0; case SWAP_ACTIVE: if (detect_container() > 0) return -EPERM; swap_enter_deactivating(s); return 1; default: assert_not_reached("Unexpected state."); } } static int swap_serialize(Unit *u, FILE *f, FDSet *fds) { Swap *s = SWAP(u); assert(s); assert(f); assert(fds); unit_serialize_item(u, f, "state", swap_state_to_string(s->state)); unit_serialize_item(u, f, "result", swap_result_to_string(s->result)); if (s->control_pid > 0) unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid); if (s->control_command_id >= 0) unit_serialize_item(u, f, "control-command", swap_exec_command_to_string(s->control_command_id)); return 0; } static int swap_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) { Swap *s = SWAP(u); assert(s); assert(fds); if (streq(key, "state")) { SwapState state; state = swap_state_from_string(value); if (state < 0) log_unit_debug(u, "Failed to parse state value: %s", value); else s->deserialized_state = state; } else if (streq(key, "result")) { SwapResult f; f = swap_result_from_string(value); if (f < 0) log_unit_debug(u, "Failed to parse result value: %s", value); else if (f != SWAP_SUCCESS) s->result = f; } else if (streq(key, "control-pid")) { pid_t pid; if (parse_pid(value, &pid) < 0) log_unit_debug(u, "Failed to parse control-pid value: %s", value); else s->control_pid = pid; } else if (streq(key, "control-command")) { SwapExecCommand id; id = swap_exec_command_from_string(value); if (id < 0) log_unit_debug(u, "Failed to parse exec-command value: %s", value); else { s->control_command_id = id; s->control_command = s->exec_command + id; } } else log_unit_debug(u, "Unknown serialization key: %s", key); return 0; } _pure_ static UnitActiveState swap_active_state(Unit *u) { assert(u); return state_translation_table[SWAP(u)->state]; } _pure_ static const char *swap_sub_state_to_string(Unit *u) { assert(u); return swap_state_to_string(SWAP(u)->state); } _pure_ static bool swap_check_gc(Unit *u) { Swap *s = SWAP(u); assert(s); return s->from_proc_swaps; } static void swap_sigchld_event(Unit *u, pid_t pid, int code, int status) { Swap *s = SWAP(u); SwapResult f; assert(s); assert(pid >= 0); if (pid != s->control_pid) return; s->control_pid = 0; if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL)) f = SWAP_SUCCESS; else if (code == CLD_EXITED) f = SWAP_FAILURE_EXIT_CODE; else if (code == CLD_KILLED) f = SWAP_FAILURE_SIGNAL; else if (code == CLD_DUMPED) f = SWAP_FAILURE_CORE_DUMP; else assert_not_reached("Unknown code"); if (s->result == SWAP_SUCCESS) s->result = f; if (s->control_command) { exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status); s->control_command = NULL; s->control_command_id = _SWAP_EXEC_COMMAND_INVALID; } log_unit_full(u, f == SWAP_SUCCESS ? LOG_DEBUG : LOG_NOTICE, 0, "Swap process exited, code=%s status=%i", sigchld_code_to_string(code), status); switch (s->state) { case SWAP_ACTIVATING: case SWAP_ACTIVATING_DONE: if (f == SWAP_SUCCESS || s->from_proc_swaps) swap_enter_active(s, f); else swap_enter_dead(s, f); break; case SWAP_DEACTIVATING: case SWAP_DEACTIVATING_SIGKILL: case SWAP_DEACTIVATING_SIGTERM: swap_enter_dead_or_active(s, f); break; default: assert_not_reached("Uh, control process died at wrong time."); } /* Notify clients about changed exit status */ unit_add_to_dbus_queue(u); } static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) { Swap *s = SWAP(userdata); assert(s); assert(s->timer_event_source == source); switch (s->state) { case SWAP_ACTIVATING: case SWAP_ACTIVATING_DONE: log_unit_warning(UNIT(s), "Activation timed out. Stopping."); swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT); break; case SWAP_DEACTIVATING: log_unit_warning(UNIT(s), "Deactivation timed out. Stopping."); swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT); break; case SWAP_DEACTIVATING_SIGTERM: if (s->kill_context.send_sigkill) { log_unit_warning(UNIT(s), "Swap process timed out. Killing."); swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_FAILURE_TIMEOUT); } else { log_unit_warning(UNIT(s), "Swap process timed out. Skipping SIGKILL. Ignoring."); swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT); } break; case SWAP_DEACTIVATING_SIGKILL: log_unit_warning(UNIT(s), "Swap process still around after SIGKILL. Ignoring."); swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT); break; default: assert_not_reached("Timeout at wrong time."); } return 0; } static int swap_load_proc_swaps(Manager *m, bool set_flags) { unsigned i; int r = 0; assert(m); rewind(m->proc_swaps); (void) fscanf(m->proc_swaps, "%*s %*s %*s %*s %*s\n"); for (i = 1;; i++) { _cleanup_free_ char *dev = NULL, *d = NULL; int prio = 0, k; k = fscanf(m->proc_swaps, "%ms " /* device/file */ "%*s " /* type of swap */ "%*s " /* swap size */ "%*s " /* used */ "%i\n", /* priority */ &dev, &prio); if (k != 2) { if (k == EOF) break; log_warning("Failed to parse /proc/swaps:%u.", i); continue; } if (cunescape(dev, UNESCAPE_RELAX, &d) < 0) return log_oom(); device_found_node(m, d, true, DEVICE_FOUND_SWAP, set_flags); k = swap_process_new(m, d, prio, set_flags); if (k < 0) r = k; } return r; } static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) { Manager *m = userdata; Unit *u; int r; assert(m); assert(revents & EPOLLPRI); r = swap_load_proc_swaps(m, true); if (r < 0) { log_error_errno(r, "Failed to reread /proc/swaps: %m"); /* Reset flags, just in case, for late calls */ LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) { Swap *swap = SWAP(u); swap->is_active = swap->just_activated = false; } return 0; } manager_dispatch_load_queue(m); LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) { Swap *swap = SWAP(u); if (!swap->is_active) { /* This has just been deactivated */ swap_unset_proc_swaps(swap); switch (swap->state) { case SWAP_ACTIVE: swap_enter_dead(swap, SWAP_SUCCESS); break; default: /* Fire again */ swap_set_state(swap, swap->state); break; } if (swap->what) device_found_node(m, swap->what, false, DEVICE_FOUND_SWAP, true); } else if (swap->just_activated) { /* New swap entry */ switch (swap->state) { case SWAP_DEAD: case SWAP_FAILED: (void) unit_acquire_invocation_id(UNIT(swap)); swap_enter_active(swap, SWAP_SUCCESS); break; case SWAP_ACTIVATING: swap_set_state(swap, SWAP_ACTIVATING_DONE); break; default: /* Nothing really changed, but let's * issue an notification call * nonetheless, in case somebody is * waiting for this. */ swap_set_state(swap, swap->state); break; } } /* Reset the flags for later calls */ swap->is_active = swap->just_activated = false; } return 1; } static Unit *swap_following(Unit *u) { Swap *s = SWAP(u); Swap *other, *first = NULL; assert(s); /* If the user configured the swap through /etc/fstab or * a device unit, follow that. */ if (s->from_fragment) return NULL; LIST_FOREACH_OTHERS(same_devnode, other, s) if (other->from_fragment) return UNIT(other); /* Otherwise, make everybody follow the unit that's named after * the swap device in the kernel */ if (streq_ptr(s->what, s->devnode)) return NULL; LIST_FOREACH_AFTER(same_devnode, other, s) if (streq_ptr(other->what, other->devnode)) return UNIT(other); LIST_FOREACH_BEFORE(same_devnode, other, s) { if (streq_ptr(other->what, other->devnode)) return UNIT(other); first = other; } /* Fall back to the first on the list */ return UNIT(first); } static int swap_following_set(Unit *u, Set **_set) { Swap *s = SWAP(u), *other; Set *set; int r; assert(s); assert(_set); if (LIST_JUST_US(same_devnode, s)) { *_set = NULL; return 0; } set = set_new(NULL); if (!set) return -ENOMEM; LIST_FOREACH_OTHERS(same_devnode, other, s) { r = set_put(set, other); if (r < 0) goto fail; } *_set = set; return 1; fail: set_free(set); return r; } static void swap_shutdown(Manager *m) { assert(m); m->swap_event_source = sd_event_source_unref(m->swap_event_source); m->proc_swaps = safe_fclose(m->proc_swaps); m->swaps_by_devnode = hashmap_free(m->swaps_by_devnode); } static void swap_enumerate(Manager *m) { int r; assert(m); if (!m->proc_swaps) { m->proc_swaps = fopen("/proc/swaps", "re"); if (!m->proc_swaps) { if (errno == ENOENT) log_debug("Not swap enabled, skipping enumeration"); else log_error_errno(errno, "Failed to open /proc/swaps: %m"); return; } r = sd_event_add_io(m->event, &m->swap_event_source, fileno(m->proc_swaps), EPOLLPRI, swap_dispatch_io, m); if (r < 0) { log_error_errno(r, "Failed to watch /proc/swaps: %m"); goto fail; } /* Dispatch this before we dispatch SIGCHLD, so that * we always get the events from /proc/swaps before * the SIGCHLD of /sbin/swapon. */ r = sd_event_source_set_priority(m->swap_event_source, SD_EVENT_PRIORITY_NORMAL-10); if (r < 0) { log_error_errno(r, "Failed to change /proc/swaps priority: %m"); goto fail; } (void) sd_event_source_set_description(m->swap_event_source, "swap-proc"); } r = swap_load_proc_swaps(m, false); if (r < 0) goto fail; return; fail: swap_shutdown(m); } int swap_process_device_new(Manager *m, struct udev_device *dev) { struct udev_list_entry *item = NULL, *first = NULL; _cleanup_free_ char *e = NULL; const char *dn; Unit *u; int r = 0; assert(m); assert(dev); dn = udev_device_get_devnode(dev); if (!dn) return 0; r = unit_name_from_path(dn, ".swap", &e); if (r < 0) return r; u = manager_get_unit(m, e); if (u) r = swap_set_devnode(SWAP(u), dn); first = udev_device_get_devlinks_list_entry(dev); udev_list_entry_foreach(item, first) { _cleanup_free_ char *n = NULL; int q; q = unit_name_from_path(udev_list_entry_get_name(item), ".swap", &n); if (q < 0) return q; u = manager_get_unit(m, n); if (u) { q = swap_set_devnode(SWAP(u), dn); if (q < 0) r = q; } } return r; } int swap_process_device_remove(Manager *m, struct udev_device *dev) { const char *dn; int r = 0; Swap *s; dn = udev_device_get_devnode(dev); if (!dn) return 0; while ((s = hashmap_get(m->swaps_by_devnode, dn))) { int q; q = swap_set_devnode(s, NULL); if (q < 0) r = q; } return r; } static void swap_reset_failed(Unit *u) { Swap *s = SWAP(u); assert(s); if (s->state == SWAP_FAILED) swap_set_state(s, SWAP_DEAD); s->result = SWAP_SUCCESS; } static int swap_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) { return unit_kill_common(u, who, signo, -1, SWAP(u)->control_pid, error); } static int swap_get_timeout(Unit *u, usec_t *timeout) { Swap *s = SWAP(u); usec_t t; int r; if (!s->timer_event_source) return 0; r = sd_event_source_get_time(s->timer_event_source, &t); if (r < 0) return r; if (t == USEC_INFINITY) return 0; *timeout = t; return 1; } static bool swap_supported(void) { static int supported = -1; /* If swap support is not available in the kernel, or we are * running in a container we don't support swap units, and any * attempts to starting one should fail immediately. */ if (supported < 0) supported = access("/proc/swaps", F_OK) >= 0 && detect_container() <= 0; return supported; } static int swap_control_pid(Unit *u) { Swap *s = SWAP(u); assert(s); return s->control_pid; } static const char* const swap_exec_command_table[_SWAP_EXEC_COMMAND_MAX] = { [SWAP_EXEC_ACTIVATE] = "ExecActivate", [SWAP_EXEC_DEACTIVATE] = "ExecDeactivate", }; DEFINE_STRING_TABLE_LOOKUP(swap_exec_command, SwapExecCommand); static const char* const swap_result_table[_SWAP_RESULT_MAX] = { [SWAP_SUCCESS] = "success", [SWAP_FAILURE_RESOURCES] = "resources", [SWAP_FAILURE_TIMEOUT] = "timeout", [SWAP_FAILURE_EXIT_CODE] = "exit-code", [SWAP_FAILURE_SIGNAL] = "signal", [SWAP_FAILURE_CORE_DUMP] = "core-dump", [SWAP_FAILURE_START_LIMIT_HIT] = "start-limit-hit", }; DEFINE_STRING_TABLE_LOOKUP(swap_result, SwapResult); const UnitVTable swap_vtable = { .object_size = sizeof(Swap), .exec_context_offset = offsetof(Swap, exec_context), .cgroup_context_offset = offsetof(Swap, cgroup_context), .kill_context_offset = offsetof(Swap, kill_context), .exec_runtime_offset = offsetof(Swap, exec_runtime), .dynamic_creds_offset = offsetof(Swap, dynamic_creds), .sections = "Unit\0" "Swap\0" "Install\0", .private_section = "Swap", .init = swap_init, .load = swap_load, .done = swap_done, .coldplug = swap_coldplug, .dump = swap_dump, .start = swap_start, .stop = swap_stop, .kill = swap_kill, .get_timeout = swap_get_timeout, .serialize = swap_serialize, .deserialize_item = swap_deserialize_item, .active_state = swap_active_state, .sub_state_to_string = swap_sub_state_to_string, .check_gc = swap_check_gc, .sigchld_event = swap_sigchld_event, .reset_failed = swap_reset_failed, .control_pid = swap_control_pid, .bus_vtable = bus_swap_vtable, .bus_set_property = bus_swap_set_property, .bus_commit_properties = bus_swap_commit_properties, .following = swap_following, .following_set = swap_following_set, .enumerate = swap_enumerate, .shutdown = swap_shutdown, .supported = swap_supported, .status_message_formats = { .starting_stopping = { [0] = "Activating swap %s...", [1] = "Deactivating swap %s...", }, .finished_start_job = { [JOB_DONE] = "Activated swap %s.", [JOB_FAILED] = "Failed to activate swap %s.", [JOB_TIMEOUT] = "Timed out activating swap %s.", }, .finished_stop_job = { [JOB_DONE] = "Deactivated swap %s.", [JOB_FAILED] = "Failed deactivating swap %s.", [JOB_TIMEOUT] = "Timed out deactivating swap %s.", }, }, };
Java
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="<?php gp_keywords(); ?>"> <meta name="keywords" content="<?php gp_keywords(); ?>" /> <meta name="description" itemprop="description" content="<?php gp_description(); ?>" /> <link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/dist/css/main.css"/> <title><?php wp_title( '_', true, 'right' ); bloginfo( 'name' ); ?></title> </head> <body> <header class="head-s"> <div class="r"> <a href="/book_tag" class="l" title="搜索"><i class="icon-search"></i></a> <a href="/" class="l" title="首页"><i class="icon-home"></i></a> </div> <a href="/" class="l"><i class="icon-pre"></i></a> <h3>帮助文档</h3> </header> <div class="content"> <div class="help-box"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php the_content( __( '<p class="serif">Read the rest of this page &rarr;</p>', 'gampress' ) ); ?> <?php endwhile; endif; ?> </div> </div> <?php get_footer();?>
Java
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8"> <title>8v18.GitHub.io by 8v18</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen"> <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen"> </head> <body> <section class="page-header"> <h1 class="project-name">8v18.GitHub.io</h1> <h2 class="project-tagline"></h2> </section> <section class="main-content"> <h3> <a id="welcome-to-github-pages" class="anchor" href="#welcome-to-github-pages" aria-hidden="true"><span class="octicon octicon-link"></span></a>Welcome to GitHub Pages.</h3> <p>This automatic page generator is the easiest way to create beautiful pages for all of your projects. Author your page content here <a href="https://guides.github.com/features/mastering-markdown/">using GitHub Flavored Markdown</a>, select a template crafted by a designer, and publish. After your page is generated, you can check out the new <code>gh-pages</code> branch locally. If you’re using GitHub Desktop, simply sync your repository and you’ll see the new branch.</p> <h3> <a id="designer-templates" class="anchor" href="#designer-templates" aria-hidden="true"><span class="octicon octicon-link"></span></a>Designer Templates</h3> <p>We’ve crafted some handsome templates for you to use. Go ahead and click 'Continue to layouts' to browse through them. You can easily go back to edit your page before publishing. After publishing your page, you can revisit the page generator and switch to another theme. Your Page content will be preserved.</p> <h3> <a id="creating-pages-manually" class="anchor" href="#creating-pages-manually" aria-hidden="true"><span class="octicon octicon-link"></span></a>Creating pages manually</h3> <p>If you prefer to not use the automatic generator, push a branch named <code>gh-pages</code> to your repository to create a page manually. In addition to supporting regular HTML content, GitHub Pages support Jekyll, a simple, blog aware static site generator. Jekyll makes it easy to create site-wide headers and footers without having to copy them across every page. It also offers intelligent blog support and other advanced templating features.</p> <h3> <a id="authors-and-contributors" class="anchor" href="#authors-and-contributors" aria-hidden="true"><span class="octicon octicon-link"></span></a>Authors and Contributors</h3> <p>You can <a href="https://github.com/blog/821" class="user-mention">@mention</a> a GitHub username to generate a link to their profile. The resulting <code>&lt;a&gt;</code> element will link to the contributor’s GitHub Profile. For example: In 2007, Chris Wanstrath (<a href="https://github.com/defunkt" class="user-mention">@defunkt</a>), PJ Hyett (<a href="https://github.com/pjhyett" class="user-mention">@pjhyett</a>), and Tom Preston-Werner (<a href="https://github.com/mojombo" class="user-mention">@mojombo</a>) founded GitHub.</p> <h3> <a id="support-or-contact" class="anchor" href="#support-or-contact" aria-hidden="true"><span class="octicon octicon-link"></span></a>Support or Contact</h3> <p>Having trouble with Pages? Check out our <a href="https://help.github.com/pages">documentation</a> or <a href="https://github.com/contact">contact support</a> and we’ll help you sort it out.</p> <footer class="site-footer"> <span class="site-footer-credits">This page was generated by <a href="https://pages.github.com">GitHub Pages</a> using the <a href="https://github.com/jasonlong/cayman-theme">Cayman theme</a> by <a href="https://twitter.com/jasonlong">Jason Long</a>.</span> </footer> </section> </body> </html>
Java
<<<<<<< HEAD <p>The <strong>view type</strong> describes how this view is stored; Views is capable of having Views entirely in code that are not in the database. This allows modules to easily ship with Views built in, and it allows you to create a module to store your views for easy deployment between development and production servers.</p> <dl> <dt><strong>Normal</strong></dt> <dd>Normal views are stored in your database and are completely local to your system.</dd> <dt><strong>Default</strong></dt> <dd>Default views are stored only in code and are not anywhere in your database. They may be <strong>enabled</strong> or <strong>disabled</strong> but you may not completely remove them from your system. You can <strong>override</strong> the view which will create a local copy of your view. If you do this, future updates to the version in code will not affect your view.</dd> <dt><strong>Overridden</strong></dt> <dd>Overridden views are stored both in code and in the database; while overridden, the version that is in code is completely dormant. If you <strong>revert</strong> the view, the version in the database will be deleted, and the version that is in code will once again be used.</dd> </dl> You may store your views in code with the following procedure: <ol> <li> Create a module to store the views. </li> <li> Add the function <em>MODULENAME_views_default_views()</em> to this module. </li> <li> Export the view you wish to store in your module in code. Cut and paste that into the abovenamed function. Make sure the last line of the view is: <em>$views[$view-&gt;name] = $view;</em></li> <li> Make sure the last line of the function is <em>return $views;</em></li> <li> After you make any changes, be sure to <strong>clear the Views' cache</strong>. You may do this from the <strong>Tools</strong> menu.</li> </ol> ======= <p>The <strong>view type</strong> describes how this view is stored; Views is capable of having Views entirely in code that are not in the database. This allows modules to easily ship with Views built in, and it allows you to create a module to store your views for easy deployment between development and production servers.</p> <dl> <dt><strong>Normal</strong></dt> <dd>Normal views are stored in your database and are completely local to your system.</dd> <dt><strong>Default</strong></dt> <dd>Default views are stored only in code and are not anywhere in your database. They may be <strong>enabled</strong> or <strong>disabled</strong> but you may not completely remove them from your system. You can <strong>override</strong> the view which will create a local copy of your view. If you do this, future updates to the version in code will not affect your view.</dd> <dt><strong>Overridden</strong></dt> <dd>Overridden views are stored both in code and in the database; while overridden, the version that is in code is completely dormant. If you <strong>revert</strong> the view, the version in the database will be deleted, and the version that is in code will once again be used.</dd> </dl> You may store your views in code with the following procedure: <ol> <li> Create a module to store the views. </li> <li> Add the function <em>MODULENAME_views_default_views()</em> to this module. </li> <li> Export the view you wish to store in your module in code. Cut and paste that into the abovenamed function. Make sure the last line of the view is: <em>$views[$view-&gt;name] = $view;</em></li> <li> Make sure the last line of the function is <em>return $views;</em></li> <li> After you make any changes, be sure to <strong>clear the Views' cache</strong>. You may do this from the <strong>Tools</strong> menu.</li> </ol> >>>>>>> 6d2bfc44ff0188b46711530fc6441339db8d58cc
Java
/* * File: prg.c * Implements: parsing javascript program aggregate * * Copyright: Jens Låås, 2015 * Copyright license: According to GPL, see file COPYING in this directory. * */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include "duktape.h" #include "prg.h" static struct prg *prg_call; static struct native_mod *prg_native_modules; int prg_register(struct prg *prg, struct native_mod *native_modules) { prg_call = prg; prg_native_modules = native_modules; return 0; } struct mod *prg_storage_byname(const char *name) { struct mod *mod; for(mod = prg_call->modules; mod; mod=mod->next) { if(!strcmp(mod->fullname, name)) return mod; } return (void*)0; } struct mod *prg_storage_byid(int id) { struct mod *mod; for(mod = prg_call->modules; mod; mod=mod->next) { if(mod->id == id) return mod; } return (void*)0; } static struct mod *mod_new() { struct mod *m; m = malloc(sizeof(struct mod)); if(m) memset(m, 0, sizeof(struct mod)); return m; } int prg_wrapped_compile_execute(duk_context *ctx) { int ret; struct prg *prg = prg_call; duk_compile(ctx, 0); close(prg->fd); munmap(prg->buf, prg->size); duk_push_global_object(ctx); /* 'this' binding */ duk_call_method(ctx, 0); prg->status = duk_to_int(ctx, -1); duk_pop(ctx); // pop return value // Check if global property 'main' exists duk_push_global_object(ctx); ret = duk_get_prop_string(ctx, -1, "main"); duk_remove(ctx, -2); // remove global object // If main exists we call it if(ret && duk_get_type(ctx, -1) != DUK_TYPE_UNDEFINED) { int i; duk_push_global_object(ctx); /* 'this' binding */ for(i=1;i<prg->argc;i++) { duk_push_string(ctx, prg->argv[i]); } duk_call_method(ctx, prg->argc-1); prg->status = duk_to_int(ctx, -1); } duk_pop(ctx); return 0; // no values returned (0) } static int x(duk_context *ctx) { duk_push_string(ctx, "hello from x"); return 1; } static const duk_function_list_entry x_funcs[] = { { "x", x, 0 /* fd */ }, { NULL, NULL, 0 } }; /* Duktape.modSearch = function (id, require, exports, module) */ static int modSearch(duk_context *ctx) { struct mod *mod; struct prg *prg; int i; prg = prg_call; const char *id = duk_to_string(ctx, 0); /* * To support the native module case, the module search function can also return undefined * (or any non-string value), in which case Duktape will assume that the module was found * but has no Ecmascript source to execute. Symbols written to exports in the module search * function are the only symbols provided by the module. */ for(i=0;;i++) { if(!prg_native_modules[i].name) break; if(!strcmp(id, prg_native_modules[i].name)) { prg_native_modules[i].fn(ctx, 2, prg); duk_push_undefined(ctx); return 1; } } if(!strcmp(id, "x")) { duk_put_function_list(ctx, 2, x_funcs); duk_push_undefined(ctx); return 1; } /* * If a module is found, the module search function can return a string providing the source * code for the module. Duktape will then take care of compiling and executing the module code * so that module symbols get registered into the exports object. */ for(mod=prg->modules;mod;mod=mod->next) { if(!strcmp(mod->name, id)) { duk_push_lstring(ctx, mod->buf, mod->size); return 1; } } duk_error(ctx, DUK_ERR_ERROR, "failed to find module '%s'", id); return DUK_RET_ERROR; } int prg_push_modsearch(duk_context *ctx) { duk_get_prop_string(ctx, -1, "Duktape"); duk_push_c_function(ctx, modSearch, 4); duk_put_prop_string(ctx, -2, "modSearch"); duk_pop(ctx); // pop Duktape return 0; } int prg_parse_appfile(struct prg *prg) { char *p, *endp, *start, *m, *mainstart; off_t offset, pa_offset; struct mod *mod; int id = 1000; // read file prg->name prg->fd = open(prg->name, O_RDONLY); if(prg->fd == -1) { exit(1); } prg->size = lseek(prg->fd, 0, SEEK_END); prg->buf = mmap((void*)0, prg->size, PROT_READ, MAP_PRIVATE, prg->fd, 0); /* parse file header */ p = prg->buf; endp = prg->buf + prg->size; if(*p == '#') { while((p < endp) && (*p != '\n')) p++; if(p >= endp) { fprintf(stderr, "EOF\n"); exit(1); } p++; } mainstart = p; mod = mod_new(); mod->id = id++; for(start=p;p < endp;p++) { if(*p == '\n') { /* is this a module specification? */ for(m = start; *m == ' '; m++); if((*m >= '0') && (*m <= '9')) { mod->size = strtoul(m, &m, 10); if(!m) break; if(*m != ' ') break; m++; mod->name = strndup(m, p-m); mod->fullname = strdup(mod->name); if(!strcmp(mod->name, "total")) break; mod->next = prg->modules; prg->modules = mod; mod = mod_new(); mod->id = id++; } else break; start = p+1; } } offset = prg->size; for(mod = prg->modules; mod; mod=mod->next) { offset -= mod->size; pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1); mod->buf = mmap((void*)0, mod->size + offset - pa_offset, PROT_READ, MAP_PRIVATE, prg->fd, pa_offset); if(mod->buf == MAP_FAILED) { fprintf(stderr, "mmap failed\n"); exit(1); } mod->buf += (offset - pa_offset); } for(mod = prg->modules; mod; mod=mod->next) { char *p; if((p=strrchr(mod->name, '.'))) { if(!strcmp(p, ".js")) *p=0; } } for(mod = prg->modules; mod; mod=mod->next) { if(!strcmp(mod->name, "main")) { prg->main = mod; } else { char *p; if((p=strrchr(mod->name, '/'))) { if(!strcmp(p+1, "main")) { prg->main = mod; } } } } if(!prg->modules) { prg->main = mod_new(); prg->main->id = id++; prg->main->buf = mainstart; prg->main->size = prg->size - (mainstart - prg->buf); prg->main->name = "main"; prg->main->fullname = "main"; } if(!prg->main) { fprintf(stderr, "no main module\n"); exit(1); } return 0; } static int prg1_storage(duk_context *ctx) { const char *name = duk_to_string(ctx, 0); struct mod *mod; mod = prg_storage_byname(name); if(mod) { duk_push_object(ctx); duk_push_int(ctx, mod->id); duk_put_prop_string(ctx, -2, "id"); duk_push_int(ctx, mod->size); duk_put_prop_string(ctx, -2, "size"); duk_push_string(ctx, mod->name); duk_put_prop_string(ctx, -2, "name"); duk_push_string(ctx, mod->fullname); duk_put_prop_string(ctx, -2, "fullname"); } else { duk_push_undefined(ctx); } return 1; } static int prg1_storage_write(duk_context *ctx) { struct mod *mod; int rc = -1; int id, fd; size_t offset, len; fd = duk_to_int(ctx, 0); id = duk_to_int(ctx, 1); offset = duk_to_int(ctx, 2); len = duk_to_int(ctx, 3); mod = prg_storage_byid(id); if(mod) { rc = write(fd, mod->buf + offset, len); } duk_push_int(ctx, rc); return 1; } static int prg1_storage_buffer(duk_context *ctx) { struct mod *mod; int id; size_t offset, len; char *buf; id = duk_to_int(ctx, 0); offset = duk_to_int(ctx, 1); len = duk_to_int(ctx, 2); mod = prg_storage_byid(id); if(mod) { buf = duk_push_fixed_buffer(ctx, len); memcpy(buf, mod->buf + offset, len); } else { duk_push_undefined(ctx); } return 1; } static const duk_function_list_entry prg1_funcs[] = { { "storage", prg1_storage, 1 /* name */ }, { "storage_write", prg1_storage_write, 4 /* fd, id, offset, len */ }, { "storage_buffer", prg1_storage_buffer, 4 /* id, offset, len */ }, { NULL, NULL, 0 } }; static const duk_number_list_entry prg1_consts[] = { { NULL, 0.0 } }; int prg1_load(duk_context *ctx, int n, struct prg *prg) { duk_put_function_list(ctx, n, prg1_funcs); duk_put_number_list(ctx, n, prg1_consts); return 0; }
Java
/* * Intel XScale PXA Programmable Interrupt Controller. * * Copyright (c) 2006 Openedhand Ltd. * Copyright (c) 2006 Thorsten Zitterell * Written by Andrzej Zaborowski <balrog@zabor.org> * * This code is licenced under the GPL. */ #include "hw.h" #include "pxa.h" #define ICIP 0x00 /* Interrupt Controller IRQ Pending register */ #define ICMR 0x04 /* Interrupt Controller Mask register */ #define ICLR 0x08 /* Interrupt Controller Level register */ #define ICFP 0x0c /* Interrupt Controller FIQ Pending register */ #define ICPR 0x10 /* Interrupt Controller Pending register */ #define ICCR 0x14 /* Interrupt Controller Control register */ #define ICHP 0x18 /* Interrupt Controller Highest Priority register */ #define IPR0 0x1c /* Interrupt Controller Priority register 0 */ #define IPR31 0x98 /* Interrupt Controller Priority register 31 */ #define ICIP2 0x9c /* Interrupt Controller IRQ Pending register 2 */ #define ICMR2 0xa0 /* Interrupt Controller Mask register 2 */ #define ICLR2 0xa4 /* Interrupt Controller Level register 2 */ #define ICFP2 0xa8 /* Interrupt Controller FIQ Pending register 2 */ #define ICPR2 0xac /* Interrupt Controller Pending register 2 */ #define IPR32 0xb0 /* Interrupt Controller Priority register 32 */ #define IPR39 0xcc /* Interrupt Controller Priority register 39 */ #define PXA2XX_PIC_SRCS 40 typedef struct { CPUState *cpu_env; uint32_t int_enabled[2]; uint32_t int_pending[2]; uint32_t is_fiq[2]; uint32_t int_idle; uint32_t priority[PXA2XX_PIC_SRCS]; } PXA2xxPICState; static void pxa2xx_pic_update(void *opaque) { uint32_t mask[2]; PXA2xxPICState *s = (PXA2xxPICState *) opaque; if (s->cpu_env->halted) { mask[0] = s->int_pending[0] & (s->int_enabled[0] | s->int_idle); mask[1] = s->int_pending[1] & (s->int_enabled[1] | s->int_idle); if (mask[0] || mask[1]) cpu_interrupt(s->cpu_env, CPU_INTERRUPT_EXITTB); } mask[0] = s->int_pending[0] & s->int_enabled[0]; mask[1] = s->int_pending[1] & s->int_enabled[1]; if ((mask[0] & s->is_fiq[0]) || (mask[1] & s->is_fiq[1])) cpu_interrupt(s->cpu_env, CPU_INTERRUPT_FIQ); else cpu_reset_interrupt(s->cpu_env, CPU_INTERRUPT_FIQ); if ((mask[0] & ~s->is_fiq[0]) || (mask[1] & ~s->is_fiq[1])) cpu_interrupt(s->cpu_env, CPU_INTERRUPT_HARD); else cpu_reset_interrupt(s->cpu_env, CPU_INTERRUPT_HARD); } /* Note: Here level means state of the signal on a pin, not * IRQ/FIQ distinction as in PXA Developer Manual. */ static void pxa2xx_pic_set_irq(void *opaque, int irq, int level) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; int int_set = (irq >= 32); irq &= 31; if (level) s->int_pending[int_set] |= 1 << irq; else s->int_pending[int_set] &= ~(1 << irq); pxa2xx_pic_update(opaque); } static inline uint32_t pxa2xx_pic_highest(PXA2xxPICState *s) { int i, int_set, irq; uint32_t bit, mask[2]; uint32_t ichp = 0x003f003f; /* Both IDs invalid */ mask[0] = s->int_pending[0] & s->int_enabled[0]; mask[1] = s->int_pending[1] & s->int_enabled[1]; for (i = PXA2XX_PIC_SRCS - 1; i >= 0; i --) { irq = s->priority[i] & 0x3f; if ((s->priority[i] & (1 << 31)) && irq < PXA2XX_PIC_SRCS) { /* Source peripheral ID is valid. */ bit = 1 << (irq & 31); int_set = (irq >= 32); if (mask[int_set] & bit & s->is_fiq[int_set]) { /* FIQ asserted */ ichp &= 0xffff0000; ichp |= (1 << 15) | irq; } if (mask[int_set] & bit & ~s->is_fiq[int_set]) { /* IRQ asserted */ ichp &= 0x0000ffff; ichp |= (1 << 31) | (irq << 16); } } } return ichp; } static uint32_t pxa2xx_pic_mem_read(void *opaque, target_phys_addr_t offset) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; switch (offset) { case ICIP: /* IRQ Pending register */ return s->int_pending[0] & ~s->is_fiq[0] & s->int_enabled[0]; case ICIP2: /* IRQ Pending register 2 */ return s->int_pending[1] & ~s->is_fiq[1] & s->int_enabled[1]; case ICMR: /* Mask register */ return s->int_enabled[0]; case ICMR2: /* Mask register 2 */ return s->int_enabled[1]; case ICLR: /* Level register */ return s->is_fiq[0]; case ICLR2: /* Level register 2 */ return s->is_fiq[1]; case ICCR: /* Idle mask */ return (s->int_idle == 0); case ICFP: /* FIQ Pending register */ return s->int_pending[0] & s->is_fiq[0] & s->int_enabled[0]; case ICFP2: /* FIQ Pending register 2 */ return s->int_pending[1] & s->is_fiq[1] & s->int_enabled[1]; case ICPR: /* Pending register */ return s->int_pending[0]; case ICPR2: /* Pending register 2 */ return s->int_pending[1]; case IPR0 ... IPR31: return s->priority[0 + ((offset - IPR0 ) >> 2)]; case IPR32 ... IPR39: return s->priority[32 + ((offset - IPR32) >> 2)]; case ICHP: /* Highest Priority register */ return pxa2xx_pic_highest(s); default: printf("%s: Bad register offset " REG_FMT "\n", __FUNCTION__, offset); return 0; } } static void pxa2xx_pic_mem_write(void *opaque, target_phys_addr_t offset, uint32_t value) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; switch (offset) { case ICMR: /* Mask register */ s->int_enabled[0] = value; break; case ICMR2: /* Mask register 2 */ s->int_enabled[1] = value; break; case ICLR: /* Level register */ s->is_fiq[0] = value; break; case ICLR2: /* Level register 2 */ s->is_fiq[1] = value; break; case ICCR: /* Idle mask */ s->int_idle = (value & 1) ? 0 : ~0; break; case IPR0 ... IPR31: s->priority[0 + ((offset - IPR0 ) >> 2)] = value & 0x8000003f; break; case IPR32 ... IPR39: s->priority[32 + ((offset - IPR32) >> 2)] = value & 0x8000003f; break; default: printf("%s: Bad register offset " REG_FMT "\n", __FUNCTION__, offset); return; } pxa2xx_pic_update(opaque); } /* Interrupt Controller Coprocessor Space Register Mapping */ static const int pxa2xx_cp_reg_map[0x10] = { [0x0 ... 0xf] = -1, [0x0] = ICIP, [0x1] = ICMR, [0x2] = ICLR, [0x3] = ICFP, [0x4] = ICPR, [0x5] = ICHP, [0x6] = ICIP2, [0x7] = ICMR2, [0x8] = ICLR2, [0x9] = ICFP2, [0xa] = ICPR2, }; static uint32_t pxa2xx_pic_cp_read(void *opaque, int op2, int reg, int crm, void *retaddr) { target_phys_addr_t offset; if (pxa2xx_cp_reg_map[reg] == -1) { printf("%s: Bad register 0x%x\n", __FUNCTION__, reg); return 0; } offset = pxa2xx_cp_reg_map[reg]; return pxa2xx_pic_mem_read(opaque, offset); } static void pxa2xx_pic_cp_write(void *opaque, int op2, int reg, int crm, uint32_t value, void *retaddr) { target_phys_addr_t offset; if (pxa2xx_cp_reg_map[reg] == -1) { printf("%s: Bad register 0x%x\n", __FUNCTION__, reg); return; } offset = pxa2xx_cp_reg_map[reg]; pxa2xx_pic_mem_write(opaque, offset, value); } static CPUReadMemoryFunc * const pxa2xx_pic_readfn[] = { pxa2xx_pic_mem_read, pxa2xx_pic_mem_read, pxa2xx_pic_mem_read, }; static CPUWriteMemoryFunc * const pxa2xx_pic_writefn[] = { pxa2xx_pic_mem_write, pxa2xx_pic_mem_write, pxa2xx_pic_mem_write, }; static void pxa2xx_pic_save(QEMUFile *f, void *opaque) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; int i; for (i = 0; i < 2; i ++) qemu_put_be32s(f, &s->int_enabled[i]); for (i = 0; i < 2; i ++) qemu_put_be32s(f, &s->int_pending[i]); for (i = 0; i < 2; i ++) qemu_put_be32s(f, &s->is_fiq[i]); qemu_put_be32s(f, &s->int_idle); for (i = 0; i < PXA2XX_PIC_SRCS; i ++) qemu_put_be32s(f, &s->priority[i]); } static int pxa2xx_pic_load(QEMUFile *f, void *opaque, int version_id) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; int i; for (i = 0; i < 2; i ++) qemu_get_be32s(f, &s->int_enabled[i]); for (i = 0; i < 2; i ++) qemu_get_be32s(f, &s->int_pending[i]); for (i = 0; i < 2; i ++) qemu_get_be32s(f, &s->is_fiq[i]); qemu_get_be32s(f, &s->int_idle); for (i = 0; i < PXA2XX_PIC_SRCS; i ++) qemu_get_be32s(f, &s->priority[i]); pxa2xx_pic_update(opaque); return 0; } qemu_irq *pxa2xx_pic_init(target_phys_addr_t base, CPUState *env) { PXA2xxPICState *s; int iomemtype; qemu_irq *qi; s = (PXA2xxPICState *) qemu_mallocz(sizeof(PXA2xxPICState)); if (!s) return NULL; s->cpu_env = env; s->int_pending[0] = 0; s->int_pending[1] = 0; s->int_enabled[0] = 0; s->int_enabled[1] = 0; s->is_fiq[0] = 0; s->is_fiq[1] = 0; qi = qemu_allocate_irqs(pxa2xx_pic_set_irq, s, PXA2XX_PIC_SRCS); /* Enable IC memory-mapped registers access. */ iomemtype = cpu_register_io_memory(pxa2xx_pic_readfn, pxa2xx_pic_writefn, s, DEVICE_NATIVE_ENDIAN); cpu_register_physical_memory(base, 0x00100000, iomemtype); /* Enable IC coprocessor access. */ cpu_arm_set_cp_io(env, 6, pxa2xx_pic_cp_read, pxa2xx_pic_cp_write, s); register_savevm(NULL, "pxa2xx_pic", 0, 0, pxa2xx_pic_save, pxa2xx_pic_load, s); return qi; }
Java
#include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/jiffies.h> #include <asm/system.h> #include <asm/io.h> #include <asm/setup.h> #include <asm/amigaints.h> #include <asm/amigahw.h> #include <asm/amigayle.h> #include <asm/amipcmcia.h> #include "8390.h" #define DRV_NAME "apne" #define NE_BASE (dev->base_addr) #define NE_CMD 0x00 #define NE_DATAPORT 0x10 #define NE_RESET 0x1f #define NE_IO_EXTENT 0x20 #define NE_EN0_ISR 0x07 #define NE_EN0_DCFG 0x0e #define NE_EN0_RSARLO 0x08 #define NE_EN0_RSARHI 0x09 #define NE_EN0_RCNTLO 0x0a #define NE_EN0_RXCR 0x0c #define NE_EN0_TXCR 0x0d #define NE_EN0_RCNTHI 0x0b #define NE_EN0_IMR 0x0f #define NE1SM_START_PG 0x20 #define NE1SM_STOP_PG 0x40 #define NESM_START_PG 0x40 #define NESM_STOP_PG 0x80 struct net_device * __init apne_probe(int unit); static int apne_probe1(struct net_device *dev, int ioaddr); static void apne_reset_8390(struct net_device *dev); static void apne_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page); static void apne_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset); static void apne_block_output(struct net_device *dev, const int count, const unsigned char *buf, const int start_page); static irqreturn_t apne_interrupt(int irq, void *dev_id); static int init_pcmcia(void); #define IOBASE 0x300 static const char version[] = "apne.c:v1.1 7/10/98 Alain Malek (Alain.Malek@cryogen.ch)\n"; static int apne_owned; struct net_device * __init apne_probe(int unit) { struct net_device *dev; #ifndef MANUAL_CONFIG char tuple[8]; #endif int err; if (!MACH_IS_AMIGA) return ERR_PTR(-ENODEV); if (apne_owned) return ERR_PTR(-ENODEV); if ( !(AMIGAHW_PRESENT(PCMCIA)) ) return ERR_PTR(-ENODEV); printk("Looking for PCMCIA ethernet card : "); if (!(PCMCIA_INSERTED)) { printk("NO PCMCIA card inserted\n"); return ERR_PTR(-ENODEV); } dev = alloc_ei_netdev(); if (!dev) return ERR_PTR(-ENOMEM); if (unit >= 0) { sprintf(dev->name, "eth%d", unit); netdev_boot_setup_check(dev); } pcmcia_disable_irq(); #ifndef MANUAL_CONFIG if ((pcmcia_copy_tuple(CISTPL_FUNCID, tuple, 8) < 3) || (tuple[2] != CISTPL_FUNCID_NETWORK)) { printk("not an ethernet card\n"); free_netdev(dev); return ERR_PTR(-ENODEV); } #endif printk("ethernet PCMCIA card inserted\n"); if (!init_pcmcia()) { free_netdev(dev); return ERR_PTR(-ENODEV); } if (!request_region(IOBASE, 0x20, DRV_NAME)) { free_netdev(dev); return ERR_PTR(-EBUSY); } err = apne_probe1(dev, IOBASE); if (err) { release_region(IOBASE, 0x20); free_netdev(dev); return ERR_PTR(err); } err = register_netdev(dev); if (!err) return dev; pcmcia_disable_irq(); free_irq(IRQ_AMIGA_PORTS, dev); pcmcia_reset(); release_region(IOBASE, 0x20); free_netdev(dev); return ERR_PTR(err); } static int __init apne_probe1(struct net_device *dev, int ioaddr) { int i; unsigned char SA_prom[32]; int wordlength = 2; const char *name = NULL; int start_page, stop_page; #ifndef MANUAL_HWADDR0 int neX000, ctron; #endif static unsigned version_printed; if (ei_debug && version_printed++ == 0) printk(version); printk("PCMCIA NE*000 ethercard probe"); { unsigned long reset_start_time = jiffies; outb(inb(ioaddr + NE_RESET), ioaddr + NE_RESET); while ((inb(ioaddr + NE_EN0_ISR) & ENISR_RESET) == 0) if (time_after(jiffies, reset_start_time + 2*HZ/100)) { printk(" not found (no reset ack).\n"); return -ENODEV; } outb(0xff, ioaddr + NE_EN0_ISR); } #ifndef MANUAL_HWADDR0 { struct {unsigned long value, offset; } program_seq[] = { {E8390_NODMA+E8390_PAGE0+E8390_STOP, NE_CMD}, {0x48, NE_EN0_DCFG}, {0x00, NE_EN0_RCNTLO}, {0x00, NE_EN0_RCNTHI}, {0x00, NE_EN0_IMR}, {0xFF, NE_EN0_ISR}, {E8390_RXOFF, NE_EN0_RXCR}, {E8390_TXOFF, NE_EN0_TXCR}, {32, NE_EN0_RCNTLO}, {0x00, NE_EN0_RCNTHI}, {0x00, NE_EN0_RSARLO}, {0x00, NE_EN0_RSARHI}, {E8390_RREAD+E8390_START, NE_CMD}, }; for (i = 0; i < ARRAY_SIZE(program_seq); i++) { outb(program_seq[i].value, ioaddr + program_seq[i].offset); } } for(i = 0; i < 32 ; i+=2) { SA_prom[i] = inb(ioaddr + NE_DATAPORT); SA_prom[i+1] = inb(ioaddr + NE_DATAPORT); if (SA_prom[i] != SA_prom[i+1]) wordlength = 1; } if (wordlength == 2) for (i = 0; i < 16; i++) SA_prom[i] = SA_prom[i+i]; if (wordlength == 2) { outb(0x49, ioaddr + NE_EN0_DCFG); start_page = NESM_START_PG; stop_page = NESM_STOP_PG; } else { start_page = NE1SM_START_PG; stop_page = NE1SM_STOP_PG; } neX000 = (SA_prom[14] == 0x57 && SA_prom[15] == 0x57); ctron = (SA_prom[0] == 0x00 && SA_prom[1] == 0x00 && SA_prom[2] == 0x1d); if (neX000) { name = (wordlength == 2) ? "NE2000" : "NE1000"; } else if (ctron) { name = (wordlength == 2) ? "Ctron-8" : "Ctron-16"; start_page = 0x01; stop_page = (wordlength == 2) ? 0x40 : 0x20; } else { printk(" not found.\n"); return -ENXIO; } #else wordlength = 2; outb(0x49, ioaddr + NE_EN0_DCFG); start_page = NESM_START_PG; stop_page = NESM_STOP_PG; SA_prom[0] = MANUAL_HWADDR0; SA_prom[1] = MANUAL_HWADDR1; SA_prom[2] = MANUAL_HWADDR2; SA_prom[3] = MANUAL_HWADDR3; SA_prom[4] = MANUAL_HWADDR4; SA_prom[5] = MANUAL_HWADDR5; name = "NE2000"; #endif dev->base_addr = ioaddr; dev->irq = IRQ_AMIGA_PORTS; dev->netdev_ops = &ei_netdev_ops; i = request_irq(dev->irq, apne_interrupt, IRQF_SHARED, DRV_NAME, dev); if (i) return i; for(i = 0; i < ETHER_ADDR_LEN; i++) dev->dev_addr[i] = SA_prom[i]; printk(" %pM\n", dev->dev_addr); printk("%s: %s found.\n", dev->name, name); ei_status.name = name; ei_status.tx_start_page = start_page; ei_status.stop_page = stop_page; ei_status.word16 = (wordlength == 2); ei_status.rx_start_page = start_page + TX_PAGES; ei_status.reset_8390 = &apne_reset_8390; ei_status.block_input = &apne_block_input; ei_status.block_output = &apne_block_output; ei_status.get_8390_hdr = &apne_get_8390_hdr; NS8390_init(dev, 0); pcmcia_ack_int(pcmcia_get_intreq()); pcmcia_enable_irq(); apne_owned = 1; return 0; } static void apne_reset_8390(struct net_device *dev) { unsigned long reset_start_time = jiffies; init_pcmcia(); if (ei_debug > 1) printk("resetting the 8390 t=%ld...", jiffies); outb(inb(NE_BASE + NE_RESET), NE_BASE + NE_RESET); ei_status.txing = 0; ei_status.dmaing = 0; while ((inb(NE_BASE+NE_EN0_ISR) & ENISR_RESET) == 0) if (time_after(jiffies, reset_start_time + 2*HZ/100)) { printk("%s: ne_reset_8390() did not complete.\n", dev->name); break; } outb(ENISR_RESET, NE_BASE + NE_EN0_ISR); } static void apne_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page) { int nic_base = dev->base_addr; int cnt; char *ptrc; short *ptrs; if (ei_status.dmaing) { printk("%s: DMAing conflict in ne_get_8390_hdr " "[DMAstat:%d][irqlock:%d][intr:%d].\n", dev->name, ei_status.dmaing, ei_status.irqlock, dev->irq); return; } ei_status.dmaing |= 0x01; outb(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base+ NE_CMD); outb(ENISR_RDC, nic_base + NE_EN0_ISR); outb(sizeof(struct e8390_pkt_hdr), nic_base + NE_EN0_RCNTLO); outb(0, nic_base + NE_EN0_RCNTHI); outb(0, nic_base + NE_EN0_RSARLO); outb(ring_page, nic_base + NE_EN0_RSARHI); outb(E8390_RREAD+E8390_START, nic_base + NE_CMD); if (ei_status.word16) { ptrs = (short*)hdr; for(cnt = 0; cnt < (sizeof(struct e8390_pkt_hdr)>>1); cnt++) *ptrs++ = inw(NE_BASE + NE_DATAPORT); } else { ptrc = (char*)hdr; for(cnt = 0; cnt < sizeof(struct e8390_pkt_hdr); cnt++) *ptrc++ = inb(NE_BASE + NE_DATAPORT); } outb(ENISR_RDC, nic_base + NE_EN0_ISR); ei_status.dmaing &= ~0x01; le16_to_cpus(&hdr->count); } static void apne_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset) { int nic_base = dev->base_addr; char *buf = skb->data; char *ptrc; short *ptrs; int cnt; if (ei_status.dmaing) { printk("%s: DMAing conflict in ne_block_input " "[DMAstat:%d][irqlock:%d][intr:%d].\n", dev->name, ei_status.dmaing, ei_status.irqlock, dev->irq); return; } ei_status.dmaing |= 0x01; outb(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base+ NE_CMD); outb(ENISR_RDC, nic_base + NE_EN0_ISR); outb(count & 0xff, nic_base + NE_EN0_RCNTLO); outb(count >> 8, nic_base + NE_EN0_RCNTHI); outb(ring_offset & 0xff, nic_base + NE_EN0_RSARLO); outb(ring_offset >> 8, nic_base + NE_EN0_RSARHI); outb(E8390_RREAD+E8390_START, nic_base + NE_CMD); if (ei_status.word16) { ptrs = (short*)buf; for (cnt = 0; cnt < (count>>1); cnt++) *ptrs++ = inw(NE_BASE + NE_DATAPORT); if (count & 0x01) { buf[count-1] = inb(NE_BASE + NE_DATAPORT); } } else { ptrc = (char*)buf; for (cnt = 0; cnt < count; cnt++) *ptrc++ = inb(NE_BASE + NE_DATAPORT); } outb(ENISR_RDC, nic_base + NE_EN0_ISR); ei_status.dmaing &= ~0x01; } static void apne_block_output(struct net_device *dev, int count, const unsigned char *buf, const int start_page) { int nic_base = NE_BASE; unsigned long dma_start; char *ptrc; short *ptrs; int cnt; if (ei_status.word16 && (count & 0x01)) count++; if (ei_status.dmaing) { printk("%s: DMAing conflict in ne_block_output." "[DMAstat:%d][irqlock:%d][intr:%d]\n", dev->name, ei_status.dmaing, ei_status.irqlock, dev->irq); return; } ei_status.dmaing |= 0x01; outb(E8390_PAGE0+E8390_START+E8390_NODMA, nic_base + NE_CMD); outb(ENISR_RDC, nic_base + NE_EN0_ISR); outb(count & 0xff, nic_base + NE_EN0_RCNTLO); outb(count >> 8, nic_base + NE_EN0_RCNTHI); outb(0x00, nic_base + NE_EN0_RSARLO); outb(start_page, nic_base + NE_EN0_RSARHI); outb(E8390_RWRITE+E8390_START, nic_base + NE_CMD); if (ei_status.word16) { ptrs = (short*)buf; for (cnt = 0; cnt < count>>1; cnt++) outw(*ptrs++, NE_BASE+NE_DATAPORT); } else { ptrc = (char*)buf; for (cnt = 0; cnt < count; cnt++) outb(*ptrc++, NE_BASE + NE_DATAPORT); } dma_start = jiffies; while ((inb(NE_BASE + NE_EN0_ISR) & ENISR_RDC) == 0) if (time_after(jiffies, dma_start + 2*HZ/100)) { printk("%s: timeout waiting for Tx RDC.\n", dev->name); apne_reset_8390(dev); NS8390_init(dev,1); break; } outb(ENISR_RDC, nic_base + NE_EN0_ISR); ei_status.dmaing &= ~0x01; return; } static irqreturn_t apne_interrupt(int irq, void *dev_id) { unsigned char pcmcia_intreq; if (!(gayle.inten & GAYLE_IRQ_IRQ)) return IRQ_NONE; pcmcia_intreq = pcmcia_get_intreq(); if (!(pcmcia_intreq & GAYLE_IRQ_IRQ)) { pcmcia_ack_int(pcmcia_intreq); return IRQ_NONE; } if (ei_debug > 3) printk("pcmcia intreq = %x\n", pcmcia_intreq); pcmcia_disable_irq(); ei_interrupt(irq, dev_id); pcmcia_ack_int(pcmcia_get_intreq()); pcmcia_enable_irq(); return IRQ_HANDLED; } #ifdef MODULE static struct net_device *apne_dev; static int __init apne_module_init(void) { apne_dev = apne_probe(-1); if (IS_ERR(apne_dev)) return PTR_ERR(apne_dev); return 0; } static void __exit apne_module_exit(void) { unregister_netdev(apne_dev); pcmcia_disable_irq(); free_irq(IRQ_AMIGA_PORTS, apne_dev); pcmcia_reset(); release_region(IOBASE, 0x20); free_netdev(apne_dev); } module_init(apne_module_init); module_exit(apne_module_exit); #endif static int init_pcmcia(void) { u_char config; #ifndef MANUAL_CONFIG u_char tuple[32]; int offset_len; #endif u_long offset; pcmcia_reset(); pcmcia_program_voltage(PCMCIA_0V); pcmcia_access_speed(PCMCIA_SPEED_250NS); pcmcia_write_enable(); #ifdef MANUAL_CONFIG config = MANUAL_CONFIG; #else if (pcmcia_copy_tuple(CISTPL_CFTABLE_ENTRY, tuple, 32) < 3) return 0; config = tuple[2] & 0x3f; #endif #ifdef MANUAL_OFFSET offset = MANUAL_OFFSET; #else if (pcmcia_copy_tuple(CISTPL_CONFIG, tuple, 32) < 6) return 0; offset_len = (tuple[2] & 0x3) + 1; offset = 0; while(offset_len--) { offset = (offset << 8) | tuple[4+offset_len]; } #endif out_8(GAYLE_ATTRIBUTE+offset, config); return 1; } MODULE_LICENSE("GPL");
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>Curate ♫ | Prototype</title> <link rel="stylesheet" href="curate.css"> <script src="script.js"></script> </head> <body> <!-- First Page --> <div> <h1>Canvas 1 - Intro Animations <br> Hit Refresh for Animation Replay.</h1> <section> <header> <img src="http://lorinsteel.com/blog/wp-content/uploads/2014/11/iOS-8-Status-Bar-01.png" alt="iOS 8 Status Bar"> </header> <main> <img src="assets/logo.png" alt=""> <img src="assets/bg1.png" alt=""> <div> <img src="assets/albums1.png" alt=""> <img src="assets/albums2.png" alt=""> </div> <aside> <p>Feel like savoring <br> these dishes, fam? &UpperRightArrow; </p> <br> <hr> <div></div> <br> <br> <img src="assets/icon.png" alt=""> <p>"you got flavor, boi"</p> </aside> </main> </section> </div> <!-- Second Page --> <div> <h1>Canvas 2 - Bot Function <br> Hit Refresh for Animation Replay.</h1> <section> <header> <img src="http://lorinsteel.com/blog/wp-content/uploads/2014/11/iOS-8-Status-Bar-01.png" alt="iOS 8 Status Bar"> </header> <main> <img src="assets/logo.png" alt=""> <aside> <p>Forget Kansas yet?<br> Here's Portugal in an <br> acoustic nutshell &LowerRightArrow; </p> <img src="assets/icon.png" alt=""> <br> <hr> <div></div> <p>start speaking or type</p> <p>"I miss home, toto."</p> <p>Alright, here's what's <br> lit back in Topeka. &LowerRightArrow;</p> </aside> <img src="assets/suggestion.png" alt=""> <img src="assets/new_suggestion_albums.png" alt=""> <img src="assets/new_suggestion_bg.png" alt=""> </main> <img src="assets/keyboard.png" alt=""> </section> </div> <!-- Third Page --> <div> <h1>Canvas 3 - Navigation <br> Hit Refresh for Animation Replay.</h1> <section> <header> <img src="http://lorinsteel.com/blog/wp-content/uploads/2014/11/iOS-8-Status-Bar-01.png" alt="iOS 8 Status Bar"> </header> <main> <aside> <p>“ You might fall in love with pop duo Nuremburg’s silky synths -- a velvety vocal debut. ”</p> <p>- Variety, 2016</p> <img src="assets/icon.png" alt=""> </aside> <img src="assets/logo.png" alt=""> <img src="assets/album_bg.png" alt=""> <img src="assets/album_nav.png" alt=""> </main> <main> <img src="assets/player.png" alt=""> <img src="assets/waveform.png" alt=""> <img src="assets/player_bg.png" alt=""> <img src="assets/player_suggest.png" alt=""> </main> <main> <img src="assets/suggestion_bot.png" alt=""> <img src="assets/suggestion_album.png" alt=""> </main> </section> </div> </body> </html>
Java
<?php class departamento extends controller { public function __construct() { parent::__construct(); include 'controllers/loginController.php'; $valida = new login(); $valida->sessao_valida(); } public function index_action($pagina = 1) { //list all records $_SESSION['pagina'] = $pagina; $this->smarty->assign('paginador', $this->mostraGrid()); $this->smarty->assign('title', 'Departamento'); //call the smarty $this->smarty->display('departamento/index.tpl'); } public function add() { $this->smarty->assign('title', 'Novo Departamento'); $this->smarty->display('departamento/new.tpl'); } public function save() { $modeldepartamento = new departamentoModel(); $dados['departamento'] = $_POST['name']; //$dados['created'] = date("Y-m-d H:i:s"); //$dados['active'] = 1; $modeldepartamento->setDepartamento($dados); header('Location: /departamento'); } public function update() { $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $dados['codigo'] = $id; $dados['departamento'] = $_POST['name']; $modeldepartamento->updDepartamento($dados); header('Location: /departamento'); } public function detalhes() { $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $resdepartamento = $modeldepartamento->getDepartamento('codigo=' . $id); $this->smarty->assign('registro', $resdepartamento[0]); $this->smarty->assign('title', 'Detalhes do Departamento'); //call the smarty $this->smarty->display('departamento/detail.tpl'); } public function edit() { //die(); $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $resdepartamento = $modeldepartamento->getDepartamento('codigo=' . $id); $this->smarty->assign('registro', $resdepartamento[0]); $this->smarty->assign('title', 'Editar Departamento'); //call the smarty $this->smarty->display('departamento/edit.tpl'); } public function delete() { $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $dados['codigo'] = $id; $modeldepartamento->delDepartamento($dados); header('Location: /departamento'); } public function mostraGrid(){ $total_reg = "10"; // número de registros por página $pagina = $_SESSION['pagina']; if (!$pagina) { $pc = "1"; } else { $pc = $pagina; } $inicio = $pc - 1; $inicio = $inicio * $total_reg; //list all records $model_departamentos = new departamentoModel(); $departamentos_res = $model_departamentos->getDepartamentoLimit(null,$inicio,$total_reg); //Full table Scan :( or :) //send the records to template sytem $this->smarty->assign('listdepartamento', $departamentos_res); $query_total = $model_departamentos->getCountDepartamento(); $total_registros = $query_total[0]['total']; //pega o valor $html = $this->paginador($pc, $total_registros, 'departamento'); return $html; } public function paginacao() { $this->index_action($this->getParam('pagina')); } } ?>
Java
Webspark FeaturesCustom ============ A collection of features compiled specifically for the Webspark distro of Panopoly. This includes: ASU GSA - Google Search Appliance ASU Maps Enhanced ASU Security Scan Fixes Various Fieldable Panel Pane Elements: ASU Spotlight Webspark Banner Webspark Hero Webspark Jumbohero Webspark Content Callout Webspark Extras Webspark feeds content: Webspark News & Events Webspark Page Elements: Webspark Breadcrumbs Mega Footer Mega Footer Menu Webspark Megamenu Webspark Panels Styles Webspark WYSIWYG settings
Java
<?php // $Id: oci8po.class.php 68 2009-07-31 18:23:01Z dlandau $ /////////////////////////////////////////////////////////////////////////// // // // NOTICE OF COPYRIGHT // // // // Moodle - Modular Object-Oriented Dynamic Learning Environment // // http://moodle.com // // // // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // // (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.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: // // // // http://www.gnu.org/copyleft/gpl.html // // // /////////////////////////////////////////////////////////////////////////// /// This class generate SQL code to be used against Oracle /// It extends XMLDBgenerator so everything can be /// overriden as needed to generate correct SQL. class XMLDBoci8po extends XMLDBgenerator { /// Only set values that are different from the defaults present in XMLDBgenerator var $statement_end = "\n/"; // String to be automatically added at the end of each statement // Using "/" because the standard ";" isn't good for stored procedures (triggers) var $number_type = 'NUMBER'; // Proper type for NUMBER(x) in this DB var $unsigned_allowed = false; // To define in the generator must handle unsigned information var $default_for_char = ' '; // To define the default to set for NOT NULLs CHARs without default (null=do nothing) // Using this whitespace here because Oracle doesn't distinguish empty and null! :-( var $drop_default_clause_required = true; //To specify if the generator must use some DEFAULT clause to drop defaults var $drop_default_clause = 'NULL'; //The DEFAULT clause required to drop defaults var $default_after_null = false; //To decide if the default clause of each field must go after the null clause var $sequence_extra_code = true; //Does the generator need to add extra code to generate the sequence fields var $sequence_name = ''; //Particular name for inline sequences in this generator var $drop_table_extra_code = true; //Does the generator need to add code after table drop var $rename_table_extra_code = true; //Does the generator need to add code after table rename var $rename_column_extra_code = true; //Does the generator need to add code after field rename var $enum_inline_code = false; //Does the generator need to add inline code in the column definition var $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY (COLUMNSPECS)'; //The SQL template to alter columns /** * Creates one new XMLDBoci8po */ function XMLDBoci8po() { parent::XMLDBgenerator(); $this->prefix = ''; $this->reserved_words = $this->getReservedWords(); } /** * Given one XMLDB Type, lenght and decimals, returns the DB proper SQL type */ function getTypeSQL ($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) { switch ($xmldb_type) { case XMLDB_TYPE_INTEGER: // From http://www.postgresql.org/docs/7.4/interactive/datatype.html if (empty($xmldb_length)) { $xmldb_length = 10; } $dbtype = 'NUMBER(' . $xmldb_length . ')'; break; case XMLDB_TYPE_NUMBER: $dbtype = $this->number_type; /// 38 is the max allowed if ($xmldb_length > 38) { $xmldb_length = 38; } if (!empty($xmldb_length)) { $dbtype .= '(' . $xmldb_length; if (!empty($xmldb_decimals)) { $dbtype .= ',' . $xmldb_decimals; } $dbtype .= ')'; } break; case XMLDB_TYPE_FLOAT: $dbtype = 'NUMBER'; break; case XMLDB_TYPE_CHAR: $dbtype = 'VARCHAR2'; if (empty($xmldb_length)) { $xmldb_length='255'; } $dbtype .= '(' . $xmldb_length . ')'; break; case XMLDB_TYPE_TEXT: $dbtype = 'CLOB'; break; case XMLDB_TYPE_BINARY: $dbtype = 'BLOB'; break; case XMLDB_TYPE_DATETIME: $dbtype = 'DATE'; break; } return $dbtype; } /** * Returns the code needed to create one enum for the xmldb_table and xmldb_field passes */ function getEnumExtraSQL ($xmldb_table, $xmldb_field) { $sql = 'CONSTRAINT ' . $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'ck'); $sql.= ' CHECK (' . $this->getEncQuoted($xmldb_field->getName()) . ' IN (' . implode(', ', $xmldb_field->getEnumValues()) . '))'; return $sql; } /** * Returns the code needed to create one sequence for the xmldb_table and xmldb_field passes */ function getCreateSequenceSQL ($xmldb_table, $xmldb_field) { $results = array(); $sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq'); $sequence = "CREATE SEQUENCE " . $sequence_name; $sequence.= "\n START WITH 1"; $sequence.= "\n INCREMENT BY 1"; $sequence.= "\n NOMAXVALUE"; $results[] = $sequence; $results = array_merge($results, $this->getCreateTriggerSQL ($xmldb_table, $xmldb_field)); return $results; } /** * Returns the code needed to create one trigger for the xmldb_table and xmldb_field passed */ function getCreateTriggerSQL ($xmldb_table, $xmldb_field) { $trigger_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'trg'); $sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq'); $trigger = "CREATE TRIGGER " . $trigger_name; $trigger.= "\n BEFORE INSERT"; $trigger.= "\nON " . $this->getTableName($xmldb_table); $trigger.= "\n FOR EACH ROW"; $trigger.= "\nBEGIN"; $trigger.= "\n IF :new." . $this->getEncQuoted($xmldb_field->getName()) . ' IS NULL THEN'; $trigger.= "\n SELECT " . $sequence_name . '.nextval INTO :new.' . $this->getEncQuoted($xmldb_field->getName()) . " FROM dual;"; $trigger.= "\n END IF;"; $trigger.= "\nEND;"; return array($trigger); } /** * Returns the code needed to drop one sequence for the xmldb_table and xmldb_field passed * Can, optionally, specify if the underlying trigger will be also dropped */ function getDropSequenceSQL ($xmldb_table, $xmldb_field, $include_trigger=false) { $sequence_name = $this->getSequenceFromDB($xmldb_table); $sequence = "DROP SEQUENCE " . $sequence_name; $trigger_name = $this->getTriggerFromDB($xmldb_table); $trigger = "DROP TRIGGER " . $trigger_name; if ($include_trigger) { $result = array($sequence, $trigger); } else { $result = array($sequence); } return $result; } /** * Returns the code (in array) needed to add one comment to the table */ function getCommentSQL ($xmldb_table) { $comment = "COMMENT ON TABLE " . $this->getTableName($xmldb_table); $comment.= " IS '" . addslashes(substr($xmldb_table->getComment(), 0, 250)) . "'"; return array($comment); } /** * Returns the code (array of statements) needed to execute extra statements on field rename */ function getRenameFieldExtraSQL ($xmldb_table, $xmldb_field, $newname) { $results = array(); /// If the field is enum, drop and re-create the check constraint if ($xmldb_field->getEnum()) { /// Drop the current enum $results = array_merge($results, $this->getDropEnumSQL($xmldb_table, $xmldb_field)); /// Change field name (over a clone to avoid some potential problems later) $new_xmldb_field = clone($xmldb_field); $new_xmldb_field->setName($newname); /// Recreate the enum $results = array_merge($results, $this->getCreateEnumSQL($xmldb_table, $new_xmldb_field)); } return $results; } /** * Returns the code (array of statements) needed to execute extra statements on table drop */ function getDropTableExtraSQL ($xmldb_table) { $xmldb_field = new XMLDBField('id'); // Fields having sequences should be exclusively, id. return $this->getDropSequenceSQL($xmldb_table, $xmldb_field, false); } /** * Returns the code (array of statements) needed to execute extra statements on table rename */ function getRenameTableExtraSQL ($xmldb_table, $newname) { $results = array(); $xmldb_field = new XMLDBField('id'); // Fields having sequences should be exclusively, id. $oldseqname = $this->getSequenceFromDB($xmldb_table); $newseqname = $this->getNameForObject($newname, $xmldb_field->getName(), 'seq'); /// Rename de sequence $results[] = 'RENAME ' . $oldseqname . ' TO ' . $newseqname; $oldtriggername = $this->getTriggerFromDB($xmldb_table); $newtriggername = $this->getNameForObject($newname, $xmldb_field->getName(), 'trg'); /// Drop old trigger $results[] = "DROP TRIGGER " . $oldtriggername; $newt = new XMLDBTable($newname); /// Temp table for trigger code generation /// Create new trigger $results = array_merge($results, $this->getCreateTriggerSQL($newt, $xmldb_field)); /// Rename all the check constraints in the table $oldtablename = $this->getTableName($xmldb_table); $newtablename = $this->getTableName($newt); $oldconstraintprefix = $this->getNameForObject($xmldb_table->getName(), ''); $newconstraintprefix = $this->getNameForObject($newt->getName(), '', ''); if ($constraints = $this->getCheckConstraintsFromDB($xmldb_table)) { foreach ($constraints as $constraint) { /// Drop the old constraint $results[] = 'ALTER TABLE ' . $newtablename . ' DROP CONSTRAINT ' . $constraint->name; /// Calculate the new constraint name $newconstraintname = str_replace($oldconstraintprefix, $newconstraintprefix, $constraint->name); /// Add the new constraint $results[] = 'ALTER TABLE ' . $newtablename . ' ADD CONSTRAINT ' . $newconstraintname . ' CHECK (' . $constraint->description . ')'; } } return $results; } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to alter the field in the table * Oracle has some severe limits: * - clob and blob fields doesn't allow type to be specified * - error is dropped if the null/not null clause is specified and hasn't changed * - changes in precision/decimals of numeric fields drop an ORA-1440 error */ function getAlterFieldSQL($xmldb_table, $xmldb_field) { global $db; $results = array(); /// To store all the needed SQL commands /// Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); /// Take a look to field metadata $meta = array_change_key_case($db->MetaColumns($tablename)); $metac = $meta[$fieldname]; $oldtype = strtolower($metac->type); $oldmetatype = column_type($xmldb_table->getName(), $fieldname); $oldlength = $metac->max_length; /// To calculate the oldlength if the field is numeric, we need to perform one extra query /// because ADOdb has one bug here. http://phplens.com/lens/lensforum/msgs.php?id=15883 if ($oldmetatype == 'N') { $uppertablename = strtoupper($tablename); $upperfieldname = strtoupper($fieldname); if ($col = get_record_sql("SELECT cname, precision FROM col WHERE tname = '$uppertablename' AND cname = '$upperfieldname'")) { $oldlength = $col->precision; } } $olddecimals = empty($metac->scale) ? null : $metac->scale; $oldnotnull = empty($metac->not_null) ? false : $metac->not_null; $olddefault = empty($metac->default_value) || strtoupper($metac->default_value) == 'NULL' ? null : $metac->default_value; $typechanged = true; //By default, assume that the column type has changed $precisionchanged = true; //By default, assume that the column precision has changed $decimalchanged = true; //By default, assume that the column decimal has changed $defaultchanged = true; //By default, assume that the column default has changed $notnullchanged = true; //By default, assume that the column notnull has changed $from_temp_fields = false; //By default don't assume we are going to use temporal fields /// Detect if we are changing the type of the column if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && substr($oldmetatype, 0, 1) == 'I') || ($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') || ($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') || ($xmldb_field->getType() == XMLDB_TYPE_CHAR && substr($oldmetatype, 0, 1) == 'C') || ($xmldb_field->getType() == XMLDB_TYPE_TEXT && substr($oldmetatype, 0, 1) == 'X') || ($xmldb_field->getType() == XMLDB_TYPE_BINARY && $oldmetatype == 'B')) { $typechanged = false; } /// Detect if precision has changed if (($xmldb_field->getType() == XMLDB_TYPE_TEXT) || ($xmldb_field->getType() == XMLDB_TYPE_BINARY) || ($oldlength == -1) || ($xmldb_field->getLength() == $oldlength)) { $precisionchanged = false; } /// Detect if decimal has changed if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER) || ($xmldb_field->getType() == XMLDB_TYPE_CHAR) || ($xmldb_field->getType() == XMLDB_TYPE_TEXT) || ($xmldb_field->getType() == XMLDB_TYPE_BINARY) || (!$xmldb_field->getDecimals()) || (!$olddecimals) || ($xmldb_field->getDecimals() == $olddecimals)) { $decimalchanged = false; } /// Detect if we are changing the default if (($xmldb_field->getDefault() === null && $olddefault === null) || ($xmldb_field->getDefault() === $olddefault) || //Check both equality and ("'" . $xmldb_field->getDefault() . "'" === $olddefault)) { //Equality with quotes because ADOdb returns the default with quotes $defaultchanged = false; } /// Detect if we are changing the nullability if (($xmldb_field->getNotnull() === $oldnotnull)) { $notnullchanged = false; } /// If type has changed or precision or decimal has changed and we are in one numeric field /// - create one temp column with the new specs /// - fill the new column with the values from the old one /// - drop the old column /// - rename the temp column to the original name if (($typechanged) || (($oldmetatype == 'N' || $oldmetatype == 'I') && ($precisionchanged || $decimalchanged))) { $tempcolname = $xmldb_field->getName() . '_alter_column_tmp'; /// Prevent temp field to have both NULL/NOT NULL and DEFAULT constraints $this->alter_column_skip_notnull = true; $this->alter_column_skip_default = true; $xmldb_field->setName($tempcolname); /// Create the temporal column $results = array_merge($results, $this->getAddFieldSQL($xmldb_table, $xmldb_field)); /// Copy contents from original col to the temporal one $results[] = 'UPDATE ' . $tablename . ' SET ' . $tempcolname . ' = ' . $fieldname; /// Drop the old column $xmldb_field->setName($fieldname); //Set back the original field name $results = array_merge($results, $this->getDropFieldSQL($xmldb_table, $xmldb_field)); /// Rename the temp column to the original one $results[] = 'ALTER TABLE ' . $tablename . ' RENAME COLUMN ' . $tempcolname . ' TO ' . $fieldname; /// Mark we have performed one change based in temp fields $from_temp_fields = true; /// Re-enable the notnull and default sections so the general AlterFieldSQL can use it $this->alter_column_skip_notnull = false; $this->alter_column_skip_default = false; /// Dissable the type section because we have done it with the temp field $this->alter_column_skip_type = true; /// If new field is nullable, nullability hasn't changed if (!$xmldb_field->getNotnull()) { $notnullchanged = false; } /// If new field hasn't default, default hasn't changed if ($xmldb_field->getDefault() === null) { $defaultchanged = false; } } /// If type and precision and decimals hasn't changed, prevent the type clause if (!$typechanged && !$precisionchanged && !$decimalchanged) { $this->alter_column_skip_type = true; } /// If NULL/NOT NULL hasn't changed /// prevent null clause to be specified if (!$notnullchanged) { $this->alter_column_skip_notnull = true; /// Initially, prevent the notnull clause /// But, if we have used the temp field and the new field is not null, then enforce the not null clause if ($from_temp_fields && $xmldb_field->getNotnull()) { $this->alter_column_skip_notnull = false; } } /// If default hasn't changed /// prevent default clause to be specified if (!$defaultchanged) { $this->alter_column_skip_default = true; /// Initially, prevent the default clause /// But, if we have used the temp field and the new field has default clause, then enforce the default clause if ($from_temp_fields && $default_clause = $this->getDefaultClause($xmldb_field)) { $this->alter_column_skip_default = false; } } /// If arriving here, something is not being skiped (type, notnull, default), calculate the standar AlterFieldSQL if (!$this->alter_column_skip_type || !$this->alter_column_skip_notnull || !$this->alter_column_skip_default) { $results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field)); return $results; } /// Finally return results return $results; } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to create its enum * (usually invoked from getModifyEnumSQL() */ function getCreateEnumSQL($xmldb_table, $xmldb_field) { /// All we have to do is to create the check constraint return array('ALTER TABLE ' . $this->getTableName($xmldb_table) . ' ADD ' . $this->getEnumExtraSQL($xmldb_table, $xmldb_field)); } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to drop its enum * (usually invoked from getModifyEnumSQL() */ function getDropEnumSQL($xmldb_table, $xmldb_field) { /// Let's introspect to know the real name of the check constraint if ($check_constraints = $this->getCheckConstraintsFromDB($xmldb_table, $xmldb_field)) { $check_constraint = array_shift($check_constraints); /// Get the 1st (should be only one) $constraint_name = strtolower($check_constraint->name); /// Extract the REAL name /// All we have to do is to drop the check constraint return array('ALTER TABLE ' . $this->getTableName($xmldb_table) . ' DROP CONSTRAINT ' . $constraint_name); } else { /// Constraint not found. Nothing to do return array(); } } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to create its default * (usually invoked from getModifyDefaultSQL() */ function getCreateDefaultSQL($xmldb_table, $xmldb_field) { /// Just a wrapper over the getAlterFieldSQL() function for Oracle that /// is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to drop its default * (usually invoked from getModifyDefaultSQL() */ function getDropDefaultSQL($xmldb_table, $xmldb_field) { /// Just a wrapper over the getAlterFieldSQL() function for Oracle that /// is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** * Given one XMLDBTable returns one array with all the check constrainsts * in the table (fetched from DB) * Optionally the function allows one xmldb_field to be specified in * order to return only the check constraints belonging to one field. * Each element contains the name of the constraint and its description * If no check constraints are found, returns an empty array */ function getCheckConstraintsFromDB($xmldb_table, $xmldb_field = null) { $results = array(); $tablename = strtoupper($this->getTableName($xmldb_table)); if ($constraints = get_records_sql("SELECT lower(c.constraint_name) AS name, c.search_condition AS description FROM user_constraints c WHERE c.table_name = '{$tablename}' AND c.constraint_type = 'C' AND c.constraint_name not like 'SYS%'")) { foreach ($constraints as $constraint) { $results[$constraint->name] = $constraint; } } /// Filter by the required field if specified if ($xmldb_field) { $filtered_results = array(); $filter = $xmldb_field->getName(); /// Lets clean a bit each constraint description, looking for the filtered field foreach ($results as $key => $result) { /// description starts by "$filter IN" assume it's a constraint beloging to the field if (preg_match("/^{$filter} IN/i", $result->description)) { $filtered_results[$key] = $result; } } /// Assign filtered results to the final results array $results = $filtered_results; } return $results; } /** * Given one XMLDBTable returns one string with the sequence of the table * in the table (fetched from DB) * The sequence name for oracle is calculated by looking the corresponding * trigger and retrieving the sequence name from it (because sequences are * independent elements) * If no sequence is found, returns false */ function getSequenceFromDB($xmldb_table) { $tablename = strtoupper($this->getTableName($xmldb_table)); $prefixupper = strtoupper($this->prefix); $sequencename = false; if ($trigger = get_record_sql("SELECT trigger_name, trigger_body FROM user_triggers WHERE table_name = '{$tablename}' AND trigger_name LIKE '{$prefixupper}%_ID%_TRG'")) { /// If trigger found, regexp it looking for the sequence name preg_match('/.*SELECT (.*)\.nextval/i', $trigger->trigger_body, $matches); if (isset($matches[1])) { $sequencename = $matches[1]; } } return $sequencename; } /** * Given one XMLDBTable returns one string with the trigger * in the table (fetched from DB) * If no trigger is found, returns false */ function getTriggerFromDB($xmldb_table) { $tablename = strtoupper($this->getTableName($xmldb_table)); $prefixupper = strtoupper($this->prefix); $triggername = false; if ($trigger = get_record_sql("SELECT trigger_name, trigger_body FROM user_triggers WHERE table_name = '{$tablename}' AND trigger_name LIKE '{$prefixupper}%_ID%_TRG'")) { $triggername = $trigger->trigger_name; } return $triggername; } /** * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg) * return if such name is currently in use (true) or no (false) * (invoked from getNameForObject() */ function isNameInUse($object_name, $type, $table_name) { switch($type) { case 'ix': case 'uix': case 'seq': case 'trg': if ($check = get_records_sql("SELECT object_name FROM user_objects WHERE lower(object_name) = '" . strtolower($object_name) . "'")) { return true; } break; case 'pk': case 'uk': case 'fk': case 'ck': if ($check = get_records_sql("SELECT constraint_name FROM user_constraints WHERE lower(constraint_name) = '" . strtolower($object_name) . "'")) { return true; } break; } return false; //No name in use found } /** * Returns an array of reserved words (lowercase) for this DB */ function getReservedWords() { /// This file contains the reserved words for Oracle databases /// from http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/ap_keywd.htm $reserved_words = array ( 'access', 'add', 'all', 'alter', 'and', 'any', 'as', 'asc', 'audit', 'between', 'by', 'char', 'check', 'cluster', 'column', 'comment', 'compress', 'connect', 'create', 'current', 'date', 'decimal', 'default', 'delete', 'desc', 'distinct', 'drop', 'else', 'exclusive', 'exists', 'file', 'float', 'for', 'from', 'grant', 'group', 'having', 'identified', 'immediate', 'in', 'increment', 'index', 'initial', 'insert', 'integer', 'intersect', 'into', 'is', 'level', 'like', 'lock', 'long', 'maxextents', 'minus', 'mlslabel', 'mode', 'modify', 'noaudit', 'nocompress', 'not', 'nowait', 'null', 'number', 'of', 'offline', 'on', 'online', 'option', 'or', 'order', 'pctfree', 'prior', 'privileges', 'public', 'raw', 'rename', 'resource', 'revoke', 'row', 'rowid', 'rownum', 'rows', 'select', 'session', 'set', 'share', 'size', 'smallint', 'start', 'successful', 'synonym', 'sysdate', 'table', 'then', 'to', 'trigger', 'uid', 'union', 'unique', 'update', 'user', 'validate', 'values', 'varchar', 'varchar2', 'view', 'whenever', 'where', 'with' ); return $reserved_words; } } ?>
Java
<!DOCTYPE html> <html> <head> <title>SceneJS / cannon.js example</title> <meta charset="utf-8"> <style> * {margin:0;padding:0} </style> </head> <body> <script src="../libs/scenejs.js"></script> <script src="../build/cannon.js"></script> <canvas id="theCanvas" width="600" height="400"/> <script> var scene, quaternionNode, translationNode, world, body, shape, timeStep=1/60; initCannon(); initSceneJS(); animate(); function initCannon() { world = new CANNON.World(); world.gravity.set(0,0,0); shape = new CANNON.Box(new CANNON.Vec3(1,1,1)); body = new CANNON.Body({ mass: 1 }); body.addShape(shape); body.angularVelocity.set(0,10,0); body.angularDamping = 0.01; world.add(body); } function initSceneJS() { SceneJS.createScene({ id: "theScene", canvasId: "theCanvas", nodes: [ { type: "lookAt", eye : { x: 0.0, y: 10.0, z: 15 }, look : { y:1.0 }, up : { y: 1.0 }, nodes: [ { type: "camera", optics: { type: "perspective", fovy : 25.0, aspect : 1.47, near : 0.10, far : 300.0 }, nodes: [ { type: "renderer", clearColor: { r: 1.0, g: 1.0, b: 1.0 }, clear: { depth : true, color : true }, nodes: [ { type: "light", mode: "dir", color: { r: 1.0, g: 1.0, b: 1.0 }, diffuse: true, specular: true, dir: { x: 1.0, y: -0.5, z: -1.0 } }, { type: "light", mode: "dir", color: { r: 1.0, g: 1.0, b: 0.8 }, diffuse: true, specular: false, dir: { x: 0.0, y: -0.5, z: -1.0 } }, { type: "translate", id: "translate", x : 0.0, y : 0.0, z : 0.0, nodes: [ { type: "quaternion", id: "quaternion", x : 1.0, y : 0.0, z : 0.0, angle : 0.0, nodes: [ { type: "material", emit: 0, baseColor: { r: 0.5, g: 0.5, b: 0.6 }, specularColor: { r: 0.9, g: 0.9, b: 0.9 }, specular: 1.0, shine: 70.0, nodes: [ { type : "cube", xSize: shape.halfExtents.x, ySize: shape.halfExtents.y, zSize: shape.halfExtents.z, } ] } ] } ] } ] } ] } ] } ] }); // Get handles to some nodes scene = SceneJS.scene("theScene"); quaternionNode = scene.findNode("quaternion"); translationNode = scene.findNode("translate"); } function animate() { // Start the scene rendering scene.start({ idleFunc: updatePhysics }); } function updatePhysics() { var axisAndAngle, axis, angle; // Step the physics world world.step(timeStep); // Copy position from cannon to SceneJS translation node translationNode.set("xyz",body.position); // Get orientation of the body from cannon.js axisAndAngle = body.quaternion.toAxisAngle(); axis = axisAndAngle[0]; angle = axisAndAngle[1]; // Copy orientation to the SceneJS quaternion node quaternionNode.set("rotation",{ x: axis.x, y: axis.y, z: axis.z, angle: angle*180 / Math.PI }); } </script> </body> </html>
Java
<?php class BWGViewGalleries_bwg { //////////////////////////////////////////////////////////////////////////////////////// // Events // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Constants // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Variables // //////////////////////////////////////////////////////////////////////////////////////// private $model; //////////////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor // //////////////////////////////////////////////////////////////////////////////////////// public function __construct($model) { $this->model = $model; } //////////////////////////////////////////////////////////////////////////////////////// // Public Methods // //////////////////////////////////////////////////////////////////////////////////////// public function display() { global $WD_BWG_UPLOAD_DIR; $rows_data = $this->model->get_rows_data(); $page_nav = $this->model->page_nav(); $search_value = ((isset($_POST['search_value'])) ? esc_html(stripslashes($_POST['search_value'])) : ''); $search_select_value = ((isset($_POST['search_select_value'])) ? (int) $_POST['search_select_value'] : 0); $asc_or_desc = ((isset($_POST['asc_or_desc'])) ? esc_html(stripslashes($_POST['asc_or_desc'])) : 'asc'); $order_by = (isset($_POST['order_by']) ? esc_html(stripslashes($_POST['order_by'])) : 'order'); $order_class = 'manage-column column-title sorted ' . $asc_or_desc; $ids_string = ''; ?> <div style="clear: both; float: left; width: 95%;"> <div style="float:left; font-size: 14px; font-weight: bold;"> This section allows you to create, edit and delete galleries. <a style="color: blue; text-decoration: none;" target="_blank" href="http://web-dorado.com/wordpress-gallery-guide-step-2.html">Read More in User Manual</a> </div> <div style="float: right; text-align: right;"> <a style="text-decoration: none;" target="_blank" href="http://web-dorado.com/products/wordpress-photo-gallery-plugin.html"> <img width="215" border="0" alt="web-dorado.com" src="<?php echo WD_BWG_URL . '/images/logo.png'; ?>" /> </a> </div> </div> <form class="wrap" id="galleries_form" method="post" action="admin.php?page=galleries_bwg" style="float: left; width: 95%;"> <span class="gallery-icon"></span> <h2> Galleries <a href="" class="add-new-h2" onclick="spider_set_input_value('task', 'add'); spider_form_submit(event, 'galleries_form')">Add new</a> </h2> <div id="draganddrop" class="updated" style="display:none;"><strong><p>Changes made in this table should be saved.</p></strong></div> <div class="buttons_div"> <span class="button-secondary non_selectable" onclick="spider_check_all_items()"> <input type="checkbox" id="check_all_items" name="check_all_items" onclick="spider_check_all_items_checkbox()" style="margin: 0; vertical-align: middle;" /> <span style="vertical-align: middle;">Select All</span> </span> <input id="show_hide_weights" class="button-secondary" type="button" onclick="spider_show_hide_weights();return false;" value="Hide order column" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('task', 'save_order')" value="Save Order" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('task', 'publish_all')" value="Publish" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('task', 'unpublish_all')" value="Unpublish" /> <input class="button-secondary" type="submit" onclick="if (confirm('Do you want to delete selected items?')) { spider_set_input_value('task', 'delete_all'); } else { return false; }" value="Delete" /> </div> <div class="tablenav top"> <?php WDWLibrary::search('Name', $search_value, 'galleries_form'); WDWLibrary::html_page_nav($page_nav['total'], $page_nav['limit'], 'galleries_form'); ?> </div> <table class="wp-list-table widefat fixed pages"> <thead> <th class="table_small_col"></th> <th class="manage-column column-cb check-column table_small_col"><input id="check_all" type="checkbox" onclick="spider_check_all(this)" style="margin:0;" /></th> <th class="table_small_col <?php if ($order_by == 'id') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'id'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'id') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>ID</span><span class="sorting-indicator"></span> </a> </th> <th class="table_extra_large_col">Thumbnail</th> <th class="<?php if ($order_by == 'name') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'name'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'name') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Name</span><span class="sorting-indicator"></span> </a> </th> <th class="<?php if ($order_by == 'slug') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'slug'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'slug') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Slug</span><span class="sorting-indicator"></span> </a> </th> <th class="<?php if ($order_by == 'display_name') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'display_name'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'display_name') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Author</span><span class="sorting-indicator"></span> </a> </th> <th id="th_order" class="table_medium_col <?php if ($order_by == 'order') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'order'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'order') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Order</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col <?php if ($order_by == 'published') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'published'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'published') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Published</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col">Edit</th> <th class="table_big_col">Delete</th> </thead> <tbody id="tbody_arr"> <?php if ($rows_data) { foreach ($rows_data as $row_data) { $alternate = (!isset($alternate) || $alternate == 'class="alternate"') ? '' : 'class="alternate"'; $published_image = (($row_data->published) ? 'publish' : 'unpublish'); $published = (($row_data->published) ? 'unpublish' : 'publish'); if ($row_data->preview_image == '') { $preview_image = WD_BWG_URL . '/images/no-image.png'; } else { $preview_image = site_url() . '/' . $WD_BWG_UPLOAD_DIR . $row_data->preview_image; } ?> <tr id="tr_<?php echo $row_data->id; ?>" <?php echo $alternate; ?>> <td class="connectedSortable table_small_col"><div title="Drag to re-order"class="handle" style="margin:5px auto 0 auto;"></div></td> <td class="table_small_col check-column"><input id="check_<?php echo $row_data->id; ?>" name="check_<?php echo $row_data->id; ?>" onclick="spider_check_all(this)" type="checkbox" /></td> <td class="table_small_col"><?php echo $row_data->id; ?></td> <td class="table_extra_large_col"> <img title="<?php echo $row_data->name; ?>" style="border: 1px solid #CCCCCC; max-width:60px; max-height:60px;" src="<?php echo $preview_image . '?date=' . date('Y-m-y H:i:s'); ?>"> </td> <td><a onclick="spider_set_input_value('task', 'edit'); spider_set_input_value('page_number', '1'); spider_set_input_value('search_value', ''); spider_set_input_value('search_or_not', ''); spider_set_input_value('asc_or_desc', 'asc'); spider_set_input_value('order_by', 'order'); spider_set_input_value('current_id', '<?php echo $row_data->id; ?>'); spider_form_submit(event, 'galleries_form')" href="" title="Edit"><?php echo $row_data->name; ?></a></td> <td><?php echo $row_data->slug; ?></td> <td><?php echo get_userdata($row_data->author)->display_name; ?></td> <td class="spider_order table_medium_col"><input id="order_input_<?php echo $row_data->id; ?>" name="order_input_<?php echo $row_data->id; ?>" type="text" size="1" value="<?php echo $row_data->order; ?>" /></td> <td class="table_big_col"><a onclick="spider_set_input_value('task', '<?php echo $published; ?>');spider_set_input_value('current_id', '<?php echo $row_data->id; ?>');spider_form_submit(event, 'galleries_form')" href=""><img src="<?php echo WD_BWG_URL . '/images/' . $published_image . '.png'; ?>"></img></a></td> <td class="table_big_col"><a onclick="spider_set_input_value('task', 'edit'); spider_set_input_value('page_number', '1'); spider_set_input_value('search_value', ''); spider_set_input_value('search_or_not', ''); spider_set_input_value('asc_or_desc', 'asc'); spider_set_input_value('order_by', 'order'); spider_set_input_value('current_id', '<?php echo $row_data->id; ?>'); spider_form_submit(event, 'galleries_form')" href="">Edit</a></td> <td class="table_big_col"><a onclick="spider_set_input_value('task', 'delete'); spider_set_input_value('current_id', '<?php echo $row_data->id; ?>'); spider_form_submit(event, 'galleries_form')" href="">Delete</a></td> </tr> <?php $ids_string .= $row_data->id . ','; } } ?> </tbody> </table> <input id="task" name="task" type="hidden" value="" /> <input id="current_id" name="current_id" type="hidden" value="" /> <input id="ids_string" name="ids_string" type="hidden" value="<?php echo $ids_string; ?>" /> <input id="asc_or_desc" name="asc_or_desc" type="hidden" value="asc" /> <input id="order_by" name="order_by" type="hidden" value="<?php echo $order_by; ?>" /> <script> window.onload = spider_show_hide_weights; </script> </form> <?php } public function edit($id) { global $WD_BWG_UPLOAD_DIR; $row = $this->model->get_row_data($id); $option_row = $this->model->get_option_row_data(); $page_title = (($id != 0) ? 'Edit gallery ' . $row->name : 'Create new gallery'); ?> <div style="clear: both; float: left; width: 95%;"> <div id="message_div" class="updated" style="display: none;"></div> <div style="float:left; font-size: 14px; font-weight: bold;"> This section allows you to add/edit gallery. <a style="color: blue; text-decoration: none;" target="_blank" href="http://web-dorado.com/wordpress-gallery-guide-step-2.html">Read More in User Manual</a> </div> <div style="float: right; text-align: right;"> <a style="text-decoration: none;" target="_blank" href="http://web-dorado.com/products/wordpress-photo-gallery-plugin.html"> <img width="215" border="0" alt="web-dorado.com" src="<?php echo WD_BWG_URL . '/images/logo.png'; ?>" /> </a> </div> </div> <script> function spider_set_href(a, number, type) { var image_url = document.getElementById("image_url_" + number).value; var thumb_url = document.getElementById("thumb_url_" + number).value; a.href='<?php echo add_query_arg(array('action' => 'editThumb', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>&type=' + type + '&image_id=' + number + '&image_url=' + image_url + '&thumb_url=' + thumb_url + '&TB_iframe=1'; } function bwg_add_preview_image(files) { document.getElementById("preview_image").value = files[0]['thumb_url']; document.getElementById("button_preview_image").style.display = "none"; document.getElementById("delete_preview_image").style.display = "inline-block"; if (document.getElementById("img_preview_image")) { document.getElementById("img_preview_image").src = files[0]['reliative_url']; document.getElementById("img_preview_image").style.display = "inline-block"; } } var j_int = 0; var bwg_j = 'pr_' + j_int; function bwg_add_image(files) { var tbody = document.getElementById('tbody_arr'); for (var i in files) { var is_video = files[i]['filetype'] == 'YOUTUBE' || files[i]['filetype'] == 'VIMEO'; var tr = document.createElement('tr'); tr.setAttribute('id', "tr_" + bwg_j); if (tbody.firstChild) { tbody.insertBefore(tr, tbody.firstChild); } else { tbody.appendChild(tr); } // Handle TD. var td_handle = document.createElement('td'); td_handle.setAttribute('class', "connectedSortable table_small_col"); td_handle.setAttribute('title', "Drag to re-order"); tr.appendChild(td_handle); var div_handle = document.createElement('div'); div_handle.setAttribute('class', "handle connectedSortable"); div_handle.setAttribute('style', "margin: 5px auto 0px;"); td_handle.appendChild(div_handle); // Checkbox TD. var td_checkbox = document.createElement('td'); td_checkbox.setAttribute('class', "table_small_col check-column"); td_checkbox.setAttribute('onclick', "spider_check_all(this)"); tr.appendChild(td_checkbox); var input_checkbox = document.createElement('input'); input_checkbox.setAttribute('id', "check_" + bwg_j); input_checkbox.setAttribute('name', "check_" + bwg_j); input_checkbox.setAttribute('type', "checkbox"); td_checkbox.appendChild(input_checkbox); // Numbering TD. var td_numbering = document.createElement('td'); td_numbering.setAttribute('class', "table_small_col"); td_numbering.innerHTML = ""; tr.appendChild(td_numbering); // Thumb TD. var td_thumb = document.createElement('td'); td_thumb.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_thumb); var a_thumb = document.createElement('a'); a_thumb.setAttribute('class', "thickbox thickbox-preview"); a_thumb.setAttribute('href', "<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display'/*thumb_display*/, 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1"); a_thumb.setAttribute('title', files[i]['name']); td_thumb.appendChild(a_thumb); var img_thumb = document.createElement('img'); img_thumb.setAttribute('id', "image_thumb_" + bwg_j); img_thumb.setAttribute('class', "thumb"); img_thumb.setAttribute('src', files[i]['thumb']); a_thumb.appendChild(img_thumb); // Filename TD. var td_filename = document.createElement('td'); td_filename.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_filename); var div_filename = document.createElement('div'); div_filename.setAttribute('class', "filename"); div_filename.setAttribute('id', "filename_" + bwg_j); td_filename.appendChild(div_filename); var strong_filename = document.createElement('strong'); div_filename.appendChild(strong_filename); var a_filename = document.createElement('a'); a_filename.setAttribute('href', "<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1"); a_filename.setAttribute('class', "spider_word_wrap thickbox thickbox-preview"); a_filename.setAttribute('title', files[i]['filename']); a_filename.innerHTML = files[i]['filename']; strong_filename.appendChild(a_filename); var div_date_modified = document.createElement('div'); div_date_modified.setAttribute('class', "fileDescription"); div_date_modified.setAttribute('title', "Date modified"); div_date_modified.setAttribute('id', "date_modified_" + bwg_j); div_date_modified.innerHTML = files[i]['date_modified']; td_filename.appendChild(div_date_modified); var div_fileresolution = document.createElement('div'); div_fileresolution.setAttribute('class', "fileDescription"); div_fileresolution.setAttribute('title', "Image Resolution"); div_fileresolution.setAttribute('id', "fileresolution" + bwg_j); div_fileresolution.innerHTML = files[i]['resolution']; td_filename.appendChild(div_fileresolution); var div_filesize = document.createElement('div'); div_filesize.setAttribute('class', "fileDescription"); div_filesize.setAttribute('title', (!is_video) ? "Image size" : "Duration"); div_filesize.setAttribute('id', "filesize" + bwg_j); div_filesize.innerHTML = files[i]['size']; td_filename.appendChild(div_filesize); var div_filetype = document.createElement('div'); div_filetype.setAttribute('class', "fileDescription"); div_filetype.setAttribute('title', "Type"); div_filetype.setAttribute('id', "filetype" + bwg_j); div_filetype.innerHTML = files[i]['filetype']; td_filename.appendChild(div_filetype); if (!is_video) { var div_edit = document.createElement('div'); td_filename.appendChild(div_edit); var span_edit_crop = document.createElement('span'); span_edit_crop.setAttribute('class', "edit_thumb"); div_edit.appendChild(span_edit_crop); var a_crop = document.createElement('a'); a_crop.setAttribute('class', "thickbox thickbox-preview"); a_crop.setAttribute('onclick', "spider_set_href(this, '" + bwg_j + "', 'crop');"); a_crop.innerHTML = "Crop"; span_edit_crop.appendChild(a_crop); div_edit.innerHTML += " | "; var span_edit_rotate = document.createElement('span'); span_edit_rotate.setAttribute('class', "edit_thumb"); div_edit.appendChild(span_edit_rotate); var a_rotate = document.createElement('a'); a_rotate.setAttribute('class', "thickbox thickbox-preview"); a_rotate.setAttribute('onclick', "spider_set_href(this, '" + bwg_j + "', 'rotate');"); a_rotate.innerHTML = "Rotate"; span_edit_rotate.appendChild(a_rotate); div_edit.innerHTML += " | " var span_edit_recover = document.createElement('span'); span_edit_recover.setAttribute('class', "edit_thumb"); div_edit.appendChild(span_edit_recover); var a_recover = document.createElement('a'); a_recover.setAttribute('onclick', 'if (confirm("Do you want to reset the image?")) { spider_set_input_value("ajax_task", "recover"); spider_set_input_value("image_current_id", "' + bwg_j + '"); spider_ajax_save("galleries_form");} return false;'); a_recover.innerHTML = "Reset"; span_edit_recover.appendChild(a_recover); } var input_image_url = document.createElement('input'); input_image_url.setAttribute('id', "image_url_" + bwg_j); input_image_url.setAttribute('name', "image_url_" + bwg_j); input_image_url.setAttribute('type', "hidden"); input_image_url.setAttribute('value', files[i]['url']); td_filename.appendChild(input_image_url); var input_thumb_url = document.createElement('input'); input_thumb_url.setAttribute('id', "thumb_url_" + bwg_j); input_thumb_url.setAttribute('name', "thumb_url_" + bwg_j); input_thumb_url.setAttribute('type', "hidden"); input_thumb_url.setAttribute('value', files[i]['thumb_url']); td_filename.appendChild(input_thumb_url); var input_filename = document.createElement('input'); input_filename.setAttribute('id', "input_filename_" + bwg_j); input_filename.setAttribute('name', "input_filename_" + bwg_j); input_filename.setAttribute('type', "hidden"); input_filename.setAttribute('value', files[i]['filename']); td_filename.appendChild(input_filename); var input_date_modified = document.createElement('input'); input_date_modified.setAttribute('id', "input_date_modified_" + bwg_j); input_date_modified.setAttribute('name', "input_date_modified_" + bwg_j); input_date_modified.setAttribute('type', "hidden"); input_date_modified.setAttribute('value', files[i]['date_modified']); td_filename.appendChild(input_date_modified); var input_resolution = document.createElement('input'); input_resolution.setAttribute('id', "input_resolution_" + bwg_j); input_resolution.setAttribute('name', "input_resolution_" + bwg_j); input_resolution.setAttribute('type', "hidden"); input_resolution.setAttribute('value', files[i]['resolution']); td_filename.appendChild(input_resolution); var input_size = document.createElement('input'); input_size.setAttribute('id', "input_size_" + bwg_j); input_size.setAttribute('name', "input_size_" + bwg_j); input_size.setAttribute('type', "hidden"); input_size.setAttribute('value', files[i]['size']); td_filename.appendChild(input_size); var input_filetype = document.createElement('input'); input_filetype.setAttribute('id', "input_filetype_" + bwg_j); input_filetype.setAttribute('name', "input_filetype_" + bwg_j); input_filetype.setAttribute('type', "hidden"); input_filetype.setAttribute('value', files[i]['filetype']); td_filename.appendChild(input_filetype); // Alt/Title TD. var td_alt = document.createElement('td'); td_alt.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_alt); var input_alt = document.createElement('input'); input_alt.setAttribute('id', "image_alt_text_" + bwg_j); input_alt.setAttribute('name', "image_alt_text_" + bwg_j); input_alt.setAttribute('type', "text"); input_alt.setAttribute('size', "24"); if (is_video) { input_alt.setAttribute('value', files[i]['name']); } else { input_alt.setAttribute('value', files[i]['filename']); } td_alt.appendChild(input_alt); <?php if ($option_row->thumb_click_action != 'open_lightbox') { ?> //Redirect url input_alt = document.createElement('input'); input_alt.setAttribute('id', "redirect_url_" + bwg_j); input_alt.setAttribute('name', "redirect_url_" + bwg_j); input_alt.setAttribute('type', "text"); input_alt.setAttribute('size', "24"); td_alt.appendChild(input_alt); <?php } ?> // Description TD. var td_desc = document.createElement('td'); td_desc.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_desc); var textarea_desc = document.createElement('textarea'); textarea_desc.setAttribute('id', "image_description_" + bwg_j); textarea_desc.setAttribute('name', "image_description_" + bwg_j); textarea_desc.setAttribute('rows', "2"); textarea_desc.setAttribute('cols', "20"); textarea_desc.setAttribute('style', "resize:vertical;"); if (is_video) { textarea_desc.innerHTML = files[i]['description']; } td_desc.appendChild(textarea_desc); // Tag TD. var td_tag = document.createElement('td'); td_tag.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_tag); var a_tag = document.createElement('a'); a_tag.setAttribute('class', "button button-small button-primary thickbox thickbox-preview"); a_tag.setAttribute('href', "<?php echo add_query_arg(array('action' => 'addTags', 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1"); a_tag.innerHTML = 'Add tag'; td_tag.appendChild(a_tag); var div_tag = document.createElement('div'); div_tag.setAttribute('class', "tags_div"); div_tag.setAttribute('id', "tags_div_" + bwg_j); td_tag.appendChild(div_tag); var hidden_tag = document.createElement('input'); hidden_tag.setAttribute('type', "hidden"); hidden_tag.setAttribute('id', "tags_" + bwg_j); hidden_tag.setAttribute('name', "tags_" + bwg_j); hidden_tag.setAttribute('value', ""); td_tag.appendChild(hidden_tag); // Order TD. var td_order = document.createElement('td'); td_order.setAttribute('class', "spider_order table_medium_col"); td_order.setAttribute('style', "display: none;"); tr.appendChild(td_order); var input_order = document.createElement('input'); input_order.setAttribute('id', "order_input_" + bwg_j); input_order.setAttribute('name', "order_input_" + bwg_j); input_order.setAttribute('type', "text"); input_order.setAttribute('value', 0 - j_int); input_order.setAttribute('size', "1"); td_order.appendChild(input_order); // Publish TD. var td_publish = document.createElement('td'); td_publish.setAttribute('class', "table_big_col"); tr.appendChild(td_publish); var a_publish = document.createElement('a'); a_publish.setAttribute('onclick', "spider_set_input_value('ajax_task', 'image_unpublish');spider_set_input_value('image_current_id', '" + bwg_j + "');spider_ajax_save('galleries_form');"); td_publish.appendChild(a_publish); var img_publish = document.createElement('img'); img_publish.setAttribute('src', "<?php echo WD_BWG_URL . '/images/publish.png'; ?>"); a_publish.appendChild(img_publish); // Delete TD. var td_delete = document.createElement('td'); td_delete.setAttribute('class', "table_big_col"); tr.appendChild(td_delete); var a_delete = document.createElement('a'); a_delete.setAttribute('onclick', "spider_set_input_value('ajax_task', 'image_delete');spider_set_input_value('image_current_id', '" + bwg_j + "');spider_ajax_save('galleries_form');"); a_delete.innerHTML = 'Delete'; td_delete.appendChild(a_delete); document.getElementById("ids_string").value += bwg_j + ','; j_int++; bwg_j = 'pr_' + j_int; } jQuery("#show_hide_weights").val("Hide order column"); spider_show_hide_weights(); } </script> <form class="wrap" method="post" id="galleries_form" action="admin.php?page=galleries_bwg" style="float: left; width: 95%;"> <span class="gallery-icon"></span> <h2><?php echo $page_title; ?></h2> <div style="float:right;"> <input class="button-secondary" type="button" onclick="if (spider_check_required('name', 'Name')) {return false;}; spider_set_input_value('page_number', '1'); spider_set_input_value('ajax_task', 'ajax_save'); spider_ajax_save('galleries_form'); spider_set_input_value('task', 'save')" value="Save" /> <input class="button-secondary" type="button" onclick="if (spider_check_required('name', 'Name')) {return false;}; spider_set_input_value('ajax_task', 'ajax_apply'); spider_ajax_save('galleries_form')" value="Apply" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('page_number', '1'); spider_set_input_value('task', 'cancel')" value="Cancel" /> </div> <table style="clear:both;"> <tbody> <tr> <td class="spider_label"><label for="name">Name: <span style="color:#FF0000;">*</span> </label></td> <td><input type="text" id="name" name="name" value="<?php echo $row->name; ?>" size="39" /></td> </tr> <tr> <td class="spider_label"><label for="slug">Slug: </label></td> <td><input type="text" id="slug" name="slug" value="<?php echo $row->slug; ?>" size="39" /></td> </tr> <tr> <td class="spider_label"><label for="description">Description: </label></td> <td> <div style="width:500px;"> <?php if (user_can_richedit()) { wp_editor($row->description, 'description', array('teeny' => FALSE, 'textarea_name' => 'description', 'media_buttons' => FALSE, 'textarea_rows' => 5)); } else { ?> <textarea cols="36" rows="5" id="description" name="description" style="resize:vertical"> <?php echo $row->description; ?> </textarea> <?php } ?> </div> </td> </tr> <tr> <td class="spider_label"><label>Author: </label></td> <td><?php echo get_userdata($row->author)->display_name; ?></td> </tr> <tr> <td class="spider_label"><label for="published1">Published: </label></td> <td> <input type="radio" class="inputbox" id="published0" name="published" <?php echo (($row->published) ? '' : 'checked="checked"'); ?> value="0" > <label for="published0">No</label> <input type="radio" class="inputbox" id="published1" name="published" <?php echo (($row->published) ? 'checked="checked"' : ''); ?> value="1" > <label for="published1">Yes</label> </td> </tr> <tr> <td class="spider_label"><label for="url">Preview image: </label></td> <td> <a href="<?php echo add_query_arg(array('action' => 'addImages', 'width' => '700', 'height' => '550', 'extensions' => 'jpg,jpeg,png,gif', 'callback' => 'bwg_add_preview_image', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" id="button_preview_image" class="button-primary thickbox thickbox-preview" title="Add Preview Image" onclick="return false;" style="margin-bottom:5px; display:none;"> Add Preview Image </a> <input type="hidden" id="preview_image" name="preview_image" value="<?php echo $row->preview_image; ?>" style="display:inline-block;"/> <img id="img_preview_image" style="max-height:90px; max-width:120px; vertical-align:middle;" src="<?php echo site_url() . '/' . $WD_BWG_UPLOAD_DIR . $row->preview_image; ?>"> <span id="delete_preview_image" class="spider_delete_img" onclick="spider_remove_url('button_preview_image', 'preview_image', 'delete_preview_image', 'img_preview_image')"></span> </td> </tr> <tr> <td colspan=2> <?php echo $this->image_display($id); ?> </td> </tr> </tbody> </table> <input id="task" name="task" type="hidden" value="" /> <input id="current_id" name="current_id" type="hidden" value="<?php echo $row->id; ?>" /> <script> <?php if ($row->preview_image == '') { ?> spider_remove_url('button_preview_image', 'preview_image', 'delete_preview_image', 'img_preview_image'); <?php } ?> </script> <div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div> <div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;"> <img src="<?php echo WD_BWG_URL . '/images/ajax_loader.png'; ?>" class="spider_ajax_loading" style="margin-top: 200px; width:50px;"> </div> </form> <?php } public function image_display($id) { global $WD_BWG_UPLOAD_DIR; $rows_data = $this->model->get_image_rows_data($id); $page_nav = $this->model->image_page_nav($id); $option_row = $this->model->get_option_row_data(); $search_value = ((isset($_POST['search_value'])) ? esc_html(stripslashes($_POST['search_value'])) : ''); $asc_or_desc = ((isset($_POST['asc_or_desc'])) ? esc_html(stripslashes($_POST['asc_or_desc'])) : 'asc'); $image_order_by = (isset($_POST['image_order_by']) ? esc_html(stripslashes($_POST['image_order_by'])) : 'order'); $order_class = 'manage-column column-title sorted ' . $asc_or_desc; $page_number = (isset($_POST['page_number']) ? esc_html(stripslashes($_POST['page_number'])) : 1); $ids_string = ''; ?> <div id="draganddrop" class="updated" style="display:none;"><strong><p>Changes made in this table should be saved.</p></strong></div> <div class="buttons_div_left"> <a href="<?php echo add_query_arg(array('action' => 'addImages', 'width' => '700', 'height' => '550', 'extensions' => 'jpg,jpeg,png,gif', 'callback' => 'bwg_add_image', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" class="button-primary thickbox thickbox-preview" id="content-add_media" title="Add Images" onclick="return false;" style="margin-bottom:5px;"> Add Images </a> <input id="show_add_video" class="button-primary" type="button" onclick="jQuery('.opacity_add_video').show(); return false;" value="Add Video" /> </div> <div class="buttons_div_right"> <span class="button-secondary non_selectable" onclick="spider_check_all_items()"> <input type="checkbox" id="check_all_items" name="check_all_items" onclick="spider_check_all_items_checkbox()" style="margin: 0; vertical-align: middle;" /> <span style="vertical-align: middle;">Select All</span> </span> <input id="show_hide_weights" class="button-secondary" type="button" onclick="spider_show_hide_weights();return false;" value="Hide order column" /> <input class="button-primary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_set_watermark'); spider_ajax_save('galleries_form'); return false;" value="Set Watermark" /> <input class="button-secondary" type="submit" onclick="jQuery('.opacity_resize_image').show(); return false;" value="Resize" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_recover_all'); spider_ajax_save('galleries_form'); return false;" value="Reset" /> <a onclick="return bwg_check_checkboxes();" href="<?php echo add_query_arg(array('action' => 'addTags', 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&TB_iframe=1" class="button-primary thickbox thickbox-preview">Add tag</a> <input class="button-secondary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_publish_all'); spider_ajax_save('galleries_form'); return false;" value="Publish" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_unpublish_all'); spider_ajax_save('galleries_form'); return false;" value="Unpublish" /> <input class="button-secondary" type="submit" onclick="if (confirm('Do you want to delete selected items?')) { spider_set_input_value('ajax_task', 'image_delete_all'); spider_ajax_save('galleries_form'); return false; } else { return false; }" value="Delete" /> </div> <div id="opacity_add_video" class="opacity_resize_image opacity_add_video bwg_opacity_video" onclick="jQuery('.opacity_add_video').hide();jQuery('.opacity_resize_image').hide();"></div> <div id="add_video" class="opacity_add_video bwg_add_video"> <input type="text" id="video_url" name="video_url" value="" /> <input class="button-primary" type="button" onclick="if (bwg_get_video_info('video_url')) {jQuery('.opacity_add_video').hide();} return false;" value="Add to gallery" /> <input class="button-secondary" type="button" onclick="jQuery('.opacity_add_video').hide(); return false;" value="Cancel" /> <div class="spider_description">Enter YouTube or Vimeo link here.</div> </div> <div id="" class="opacity_resize_image bwg_resize_image"> Resize images to: <input type="text" name="image_width" id="image_width" value="1600" /> x <input type="text" name="image_height" id="image_height" value="1200" /> px <input class="button-primary" type="button" onclick="spider_set_input_value('ajax_task', 'image_resize'); spider_ajax_save('galleries_form'); jQuery('.opacity_resize_image').hide(); return false;" value="Resize" /> <input class="button-secondary" type="button" onclick="jQuery('.opacity_resize_image').hide(); return false;" value="Cancel" /> <div class="spider_description">The maximum size of resized image.</div> </div> <div class="tablenav top"> <?php WDWLibrary::ajax_search('Filename', $search_value, 'galleries_form'); WDWLibrary::ajax_html_page_nav($page_nav['total'], $page_nav['limit'], 'galleries_form'); ?> </div> <table id="images_table" class="wp-list-table widefat fixed pages"> <thead> <th class="check-column table_small_col"></th> <th class="manage-column column-cb check-column table_small_col"><input id="check_all" type="checkbox" onclick="spider_check_all(this)" style="margin:0;" /></th> <th class="table_small_col">#</th> <th class="table_extra_large_col">Thumbnail</th> <th class="table_extra_large_col <?php if ($image_order_by == 'filename') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'filename'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'filename') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Filename</span><span class="sorting-indicator"></span> </a> </th> <th class="table_extra_large_col <?php if ($image_order_by == 'alt') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'alt'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'alt') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Alt/Title<?php if ($option_row->thumb_click_action != 'open_lightbox') { ?><br />Redirect URL<?php } ?></span><span class="sorting-indicator"></span> </a> </th> <th class="table_extra_large_col <?php if ($image_order_by == 'description') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'description'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'description') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Description</span><span class="sorting-indicator"></span> </a> </th> <th class="table_extra_large_col">Tags</th> <th id="th_order" class="table_medium_col <?php if ($image_order_by == 'order') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'order'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'order') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Order</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col <?php if ($image_order_by == 'published') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'published'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'published') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Published</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col">Delete</th> </thead> <tbody id="tbody_arr"> <?php $i = ($page_number - 1) * 20; if ($rows_data) { foreach ($rows_data as $row_data) { $is_video = $row_data->filetype == 'YOUTUBE' || $row_data->filetype == 'VIMEO'; $alternate = (!isset($alternate) || $alternate == 'class="alternate"') ? '' : 'class="alternate"'; $rows_tag_data = $this->model->get_tag_rows_data($row_data->id); $published_image = (($row_data->published) ? 'publish' : 'unpublish'); $published = (($row_data->published) ? 'unpublish' : 'publish'); ?> <tr id="tr_<?php echo $row_data->id; ?>" <?php echo $alternate; ?>> <td class="connectedSortable table_small_col"><div title="Drag to re-order" class="handle" style="margin:5px auto 0 auto;"></div></td> <td class="table_small_col check-column"><input id="check_<?php echo $row_data->id; ?>" name="check_<?php echo $row_data->id; ?>" onclick="spider_check_all(this)" type="checkbox" /></td> <td class="table_small_col"><?php echo ++$i; ?></td> <td class="table_extra_large_col"> <a class="thickbox thickbox-preview" title="<?php echo $row_data->alt; ?>" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display'/*thumb_display*/, 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>"> <img id="image_thumb_<?php echo $row_data->id; ?>" class="thumb" src="<?php echo (!$is_video ? site_url() . '/' . $WD_BWG_UPLOAD_DIR : "") . $row_data->thumb_url . '?date=' . date('Y-m-y H:i:s'); ?>"> </a> </td> <td class="table_extra_large_col"> <div class="filename" id="filename_<?php echo $row_data->id; ?>"> <strong><a title="<?php echo $row_data->alt; ?>" class="spider_word_wrap thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display', 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>"><?php echo $row_data->filename; ?></a></strong> </div> <div class="fileDescription" title="Date modified" id="date_modified_<?php echo $row_data->id; ?>"><?php echo date("d F Y, H:i", strtotime($row_data->date)); ?></div> <div class="fileDescription" title="Image Resolution" id="fileresolution_<?php echo $row_data->id; ?>"><?php echo $row_data->resolution; ?></div> <div class="fileDescription" title="<?php echo (!$is_video ? "Image size" : "Duration")?>" id="filesize_<?php echo $row_data->id; ?>"><?php echo $row_data->size; ?></div> <div class="fileDescription" title="Type" id="filetype_<?php echo $row_data->id; ?>"><?php echo $row_data->filetype; ?></div> <?php if(!$is_video) {?> <div> <span class="edit_thumb"><a class="thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'crop', 'image_id' => $row_data->id, 'TB_iframe' => '1', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>">Crop</a></span> | <span class="edit_thumb"><a class="thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'rotate', 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>">Rotate</a></span> | <span class="edit_thumb"><a onclick="if (confirm('Do you want to reset the image?')) { spider_set_input_value('ajax_task', 'recover'); spider_set_input_value('image_current_id', '<?php echo $row_data->id; ?>'); spider_ajax_save('galleries_form'); } return false;">Reset</a></span> </div> <?php } ?> <input type="hidden" id="image_url_<?php echo $row_data->id; ?>" name="image_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->image_url; ?>" /> <input type="hidden" id="thumb_url_<?php echo $row_data->id; ?>" name="thumb_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->thumb_url; ?>" /> <input type="hidden" id="input_filename_<?php echo $row_data->id; ?>" name="input_filename_<?php echo $row_data->id; ?>" value="<?php echo $row_data->filename; ?>" /> <input type="hidden" id="input_date_modified_<?php echo $row_data->id; ?>" name="input_date_modified_<?php echo $row_data->id; ?>" value="<?php echo $row_data->date; ?>" /> <input type="hidden" id="input_resolution_<?php echo $row_data->id; ?>" name="input_resolution_<?php echo $row_data->id; ?>" value="<?php echo $row_data->resolution; ?>" /> <input type="hidden" id="input_size_<?php echo $row_data->id; ?>" name="input_size_<?php echo $row_data->id; ?>" value="<?php echo $row_data->size; ?>" /> <input type="hidden" id="input_filetype_<?php echo $row_data->id; ?>" name="input_filetype_<?php echo $row_data->id; ?>" value="<?php echo $row_data->filetype; ?>" /> </td> <td class="table_extra_large_col"> <input size="24" type="text" id="image_alt_text_<?php echo $row_data->id; ?>" name="image_alt_text_<?php echo $row_data->id; ?>" value="<?php echo $row_data->alt; ?>" /> <?php if ($option_row->thumb_click_action != 'open_lightbox') { ?> <input size="24" type="text" id="redirect_url_<?php echo $row_data->id; ?>" name="redirect_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->redirect_url; ?>" /> <?php } ?> </td> <td class="table_extra_large_col"> <textarea cols="20" rows="2" id="image_description_<?php echo $row_data->id; ?>" name="image_description_<?php echo $row_data->id; ?>" style="resize:vertical;"><?php echo $row_data->description; ?></textarea> </td> <td class="table_extra_large_col"> <a href="<?php echo add_query_arg(array('action' => 'addTags', 'image_id' => $row_data->id, 'width' => '650', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" class="button button-small button-primary thickbox thickbox-preview">Add tag</a> <div class="tags_div" id="tags_div_<?php echo $row_data->id; ?>"> <?php $tags_id_string = ''; if ($rows_tag_data) { foreach($rows_tag_data as $row_tag_data) { ?> <div class="tag_div" id="<?php echo $row_data->id; ?>_tag_<?php echo $row_tag_data->term_id; ?>"> <span class="tag_name"><?php echo $row_tag_data->name; ?></span> <span style="float:right;" class="spider_delete_img_small" onclick="bwg_remove_tag('<?php echo $row_tag_data->term_id; ?>', '<?php echo $row_data->id; ?>')" /> </div> <?php $tags_id_string .= $row_tag_data->term_id . ','; } } ?> </div> <input type="hidden" value="<?php echo $tags_id_string; ?>" id="tags_<?php echo $row_data->id; ?>" name="tags_<?php echo $row_data->id; ?>"/> </td> <td class="spider_order table_medium_col"><input id="order_input_<?php echo $row_data->id; ?>" name="order_input_<?php echo $row_data->id; ?>" type="text" size="1" value="<?php echo $row_data->order; ?>" /></td> <td class="table_big_col"><a onclick="spider_set_input_value('ajax_task', 'image_<?php echo $published; ?>'); spider_set_input_value('image_current_id', '<?php echo $row_data->id; ?>'); spider_ajax_save('galleries_form');"><img src="<?php echo WD_BWG_URL . '/images/' . $published_image . '.png'; ?>"></img></a></td> <td class="table_big_col"><a onclick="spider_set_input_value('ajax_task', 'image_delete'); spider_set_input_value('image_current_id', '<?php echo $row_data->id; ?>'); spider_ajax_save('galleries_form');">Delete</a></td> </tr> <?php $ids_string .= $row_data->id . ','; } } ?> <input id="ids_string" name="ids_string" type="hidden" value="<?php echo $ids_string; ?>" /> <input id="asc_or_desc" name="asc_or_desc" type="hidden" value="asc" /> <input id="image_order_by" name="image_order_by" type="hidden" value="<?php echo $image_order_by; ?>" /> <input id="ajax_task" name="ajax_task" type="hidden" value="" /> <input id="image_current_id" name="image_current_id" type="hidden" value="" /> <input id="added_tags_select_all" name="added_tags_select_all" type="hidden" value="" /> </tbody> </table> <script> window.onload = spider_show_hide_weights; </script> <?php } //////////////////////////////////////////////////////////////////////////////////////// // Getters & Setters // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Private Methods // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Listeners // //////////////////////////////////////////////////////////////////////////////////////// }
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>read_at</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../reference.html" title="Reference"> <link rel="prev" href="read/overload8.html" title="read (8 of 8 overloads)"> <link rel="next" href="read_at/overload1.html" title="read_at (1 of 8 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="read/overload8.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="read_at/overload1.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h3 class="title"> <a name="boost_asio.reference.read_at"></a><a class="link" href="read_at.html" title="read_at">read_at</a> </h3></div></div></div> <p> <a class="indexterm" name="id1486748"></a> Attempt to read a certain amount of data at the specified offset before returning. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload1.html" title="read_at (1 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload1.html" title="read_at (1 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload2.html" title="read_at (2 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload2.html" title="read_at (2 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">CompletionCondition</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload3.html" title="read_at (3 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">,</span> <span class="identifier">CompletionCondition</span> <span class="identifier">completion_condition</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload3.html" title="read_at (3 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">CompletionCondition</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload4.html" title="read_at (4 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">,</span> <span class="identifier">CompletionCondition</span> <span class="identifier">completion_condition</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload4.html" title="read_at (4 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Allocator</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload5.html" title="read_at (5 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="identifier">basic_streambuf</span><span class="special">&lt;</span> <span class="identifier">Allocator</span> <span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">b</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload5.html" title="read_at (5 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Allocator</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload6.html" title="read_at (6 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="identifier">basic_streambuf</span><span class="special">&lt;</span> <span class="identifier">Allocator</span> <span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">b</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload6.html" title="read_at (6 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Allocator</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">CompletionCondition</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload7.html" title="read_at (7 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="identifier">basic_streambuf</span><span class="special">&lt;</span> <span class="identifier">Allocator</span> <span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">b</span><span class="special">,</span> <span class="identifier">CompletionCondition</span> <span class="identifier">completion_condition</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload7.html" title="read_at (7 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Allocator</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">CompletionCondition</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload8.html" title="read_at (8 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="identifier">basic_streambuf</span><span class="special">&lt;</span> <span class="identifier">Allocator</span> <span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">b</span><span class="special">,</span> <span class="identifier">CompletionCondition</span> <span class="identifier">completion_condition</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload8.html" title="read_at (8 of 8 overloads)">more...</a></em></span> </pre> <h5> <a name="boost_asio.reference.read_at.h0"></a> <span><a name="boost_asio.reference.read_at.requirements"></a></span><a class="link" href="read_at.html#boost_asio.reference.read_at.requirements">Requirements</a> </h5> <p> <span class="bold"><strong>Header: </strong></span><code class="literal">boost/asio/read_at.hpp</code> </p> <p> <span class="bold"><strong>Convenience header: </strong></span><code class="literal">boost/asio.hpp</code> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2011 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="read/overload8.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="read_at/overload1.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>strategy::transform::rotate_transformer</title> <link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../index.html" title="Chapter&#160;1.&#160;Geometry 1.0"> <link rel="up" href="../strategies.html" title="Strategies"> <link rel="prev" href="strategy_transform_map_transformer.html" title="strategy::transform::map_transformer"> <link rel="next" href="strategy_transform_scale_transformer.html" title="strategy::transform::scale_transformer"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="strategy_transform_map_transformer.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../strategies.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="strategy_transform_scale_transformer.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer"></a><a class="link" href="strategy_transform_rotate_transformer.html" title="strategy::transform::rotate_transformer">strategy::transform::rotate_transformer</a> </h4></div></div></div> <p> <a class="indexterm" name="id954360"></a><a class="indexterm" name="id954366"></a><a class="indexterm" name="id954371"></a> Strategy of rotate transformation in Cartesian system. </p> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h0"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.description"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.description">Description</a> </h6> <p> Rotate rotates a geometry of specified angle about a fixed point (e.g. origin). </p> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h1"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.synopsis"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.synopsis">Synopsis</a> </h6> <p> </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> <span class="identifier">P1</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">P2</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">DegreeOrRadian</span><span class="special">&gt;</span> <span class="keyword">class</span> <span class="identifier">strategy</span><span class="special">::</span><span class="identifier">transform</span><span class="special">::</span><span class="identifier">rotate_transformer</span> <span class="special">{</span> <span class="comment">// ...</span> <span class="special">};</span> </pre> <p> </p> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h2"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.template_parameter_s_"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.template_parameter_s_">Template parameter(s)</a> </h6> <div class="informaltable"><table class="table"> <colgroup> <col> <col> </colgroup> <thead><tr> <th> <p> Parameter </p> </th> <th> <p> Description </p> </th> </tr></thead> <tbody> <tr> <td> <p> typename P1 </p> </td> <td> <p> first point type </p> </td> </tr> <tr> <td> <p> typename P2 </p> </td> <td> <p> second point type </p> </td> </tr> <tr> <td> <p> typename DegreeOrRadian </p> </td> <td> <p> degree/or/radian, type of rotation angle specification </p> </td> </tr> </tbody> </table></div> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h3"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.constructor_s_"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.constructor_s_">Constructor(s)</a> </h6> <div class="informaltable"><table class="table"> <colgroup> <col> <col> <col> </colgroup> <thead><tr> <th> <p> Function </p> </th> <th> <p> Description </p> </th> <th> <p> Parameters </p> </th> </tr></thead> <tbody><tr> <td> <p> </p> <pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="identifier">rotate_transformer</span><span class="special">(</span><span class="identifier">angle_type</span> <span class="keyword">const</span> <span class="special">&amp;</span> <span class="identifier">angle</span><span class="special">)</span></pre> <p> </p> </td> <td> </td> <td> <p> <span class="bold"><strong>angle_type const &amp;</strong></span>: <span class="emphasis"><em>angle</em></span>: </p> </td> </tr></tbody> </table></div> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h4"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.header"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.header">Header</a> </h6> <p> <code class="computeroutput"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">geometry</span><span class="special">/</span><span class="identifier">strategies</span><span class="special">/</span><span class="identifier">transform</span><span class="special">/</span><span class="identifier">matrix_transformers</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span></code> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2011 Barend Gehrels, Bruno Lalande, Mateusz Loskot<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="strategy_transform_map_transformer.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../strategies.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="strategy_transform_scale_transformer.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
Java
package visitors; /** * Created by stratosphr on 20/11/15. */ public interface IVisitedSort extends IVisited { Object accept(ISortVisitor visitor); }
Java
/* * aTunes * Copyright (C) Alex Aranda, Sylvain Gaudard and contributors * * See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors * * http://www.atunes.org * http://sourceforge.net/projects/atunes * * 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. */ package net.sourceforge.atunes.kernel.modules.navigator; import java.awt.Component; import java.util.List; import javax.swing.Action; import javax.swing.JMenu; import javax.swing.JMenuItem; import net.sourceforge.atunes.kernel.actions.CustomAbstractAction; import net.sourceforge.atunes.model.IAudioObject; import net.sourceforge.atunes.model.IPlayListHandler; import net.sourceforge.atunes.model.ITreeNode; /** * Enables or disables navigator actions given selection * * @author alex * */ public class NavigatorActionsStateController { private IPlayListHandler playListHandler; /** * @param playListHandler */ public void setPlayListHandler(final IPlayListHandler playListHandler) { this.playListHandler = playListHandler; } /** * Enables or disables tree popup actions * * @param rootSelected * @param components * @param nodes */ void updateTreePopupMenuWithTreeSelection(final boolean rootSelected, final Component[] components, final List<ITreeNode> nodes) { for (Component c : components) { updateMenuComponent(rootSelected, nodes, c); } } /** * Enables or disables table popup actions * * @param rootSelected * @param components * @param selection */ void updateTablePopupMenuWithTableSelection(final boolean rootSelected, final Component[] components, final List<IAudioObject> selection) { for (Component c : components) { updateTableMenuComponent(rootSelected, selection, c); } } /** * @param rootSelected * @param selection * @param c */ private void updateMenuComponent(final boolean rootSelected, final List<ITreeNode> selection, final Component c) { if (c != null) { if (c instanceof JMenu) { for (int i = 0; i < ((JMenu) c).getItemCount(); i++) { updateMenuComponent(rootSelected, selection, ((JMenu) c).getItem(i)); } } else if (c instanceof JMenuItem) { updateMenuItem(rootSelected, selection, (JMenuItem) c); } } } /** * @param rootSelected * @param selection * @param c */ private void updateTableMenuComponent(final boolean rootSelected, final List<IAudioObject> selection, final Component c) { if (c != null) { if (c instanceof JMenu) { for (int i = 0; i < ((JMenu) c).getItemCount(); i++) { updateTableMenuComponent(rootSelected, selection, ((JMenu) c).getItem(i)); } } else if (c instanceof JMenuItem) { updateTableMenuItem(rootSelected, selection, (JMenuItem) c); } } } /** * @param rootSelected * @param selection * @param menuItem */ private void updateMenuItem(final boolean rootSelected, final List<ITreeNode> selection, final JMenuItem menuItem) { Action a = menuItem.getAction(); if (a instanceof CustomAbstractAction) { CustomAbstractAction customAction = (CustomAbstractAction) a; if (!customAction.isEnabledForPlayList(this.playListHandler .getVisiblePlayList())) { customAction.setEnabled(false); } else { customAction.setEnabled(customAction .isEnabledForNavigationTreeSelection(rootSelected, selection)); } } } /** * @param rootSelected * @param selection * @param menuItem */ private void updateTableMenuItem(final boolean rootSelected, final List<IAudioObject> selection, final JMenuItem menuItem) { Action a = menuItem.getAction(); if (a instanceof CustomAbstractAction) { CustomAbstractAction customAction = (CustomAbstractAction) a; if (!customAction.isEnabledForPlayList(this.playListHandler .getVisiblePlayList())) { customAction.setEnabled(false); } else { customAction.setEnabled(customAction .isEnabledForNavigationTableSelection(selection)); } } } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.mum.ea.mb; import edu.mum.ea.ejb.ProjectEJB; import edu.mum.ea.ejb.ReleaseBacklogEJB; import edu.mum.ea.ejb.SprintEJB; import edu.mum.ea.ejb.TaskEJB; import edu.mum.ea.entity.Project; import edu.mum.ea.entity.ReleaseBacklog; import edu.mum.ea.entity.Sprint; import edu.mum.ea.entity.Task; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; /** * * @author Syed */ @ManagedBean @RequestScoped public class SprintMB { private Sprint sprint; @EJB private SprintEJB sprintEJB; @EJB private ProjectEJB projectEJB; @EJB private ReleaseBacklogEJB releaseBacklogEJB; @EJB private TaskEJB taskEJB; @ManagedProperty(value = "#{sessionMB}") private SessionMB sessionMB; private List<Task> taskList = new ArrayList<Task>(); private List<ReleaseBacklog> releaseBacklogList = new ArrayList<ReleaseBacklog>(); private long relBacklogId; private List<String> selectedTasks = new ArrayList<String>(); private List<Sprint> sprintList; /** * Creates a new instance of ProjectMB */ public SprintMB() { sprint = new Sprint(); sprintList = new ArrayList<Sprint>(); } @PostConstruct public void init() { //Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); //Project project = projectEJB.find(sessionMB.getUserSelectedProject().getId()); releaseBacklogList = releaseBacklogEJB.findAllRelBakByProject(sessionMB.getUserSelectedProject().getId());//project.getReleaseBacklogList(); } public SessionMB getSessionMB() { return sessionMB; } public void setSessionMB(SessionMB sessionMB) { this.sessionMB = sessionMB; } public Sprint getSprint() { return sprint; } public void setSprint(Sprint sprint) { this.sprint = sprint; } public List<Sprint> getSprintList() { sprintList = sprintEJB.findAllSprintByProject(sessionMB.getUserSelectedProject().getId());//sprintEJB.findAll(); return sprintList; } public void setSprintList(List<Sprint> sprintList) { this.sprintList = sprintList; } public List<ReleaseBacklog> getReleaseBacklogList() { return releaseBacklogList; } public void setReleaseBacklogList(List<ReleaseBacklog> releaseBacklogList) { this.releaseBacklogList = releaseBacklogList; } public long getRelBacklogId() { return relBacklogId; } public void setRelBacklogId(long relBacklogId) { this.relBacklogId = relBacklogId; } public List<Task> getTaskList() { return taskList; } public void setTaskList(List<Task> taskList) { this.taskList = taskList; } public List<String> getSelectedTasks() { return selectedTasks; } public void setSelectedTasks(List<String> selectedTasks) { this.selectedTasks = selectedTasks; } public String createSprint() { sprint.setReleaseBacklog(releaseBacklogEJB.find(getRelBacklogId())); sprintEJB.save(sprint); return "sprint-list"; } public String gotoUpdatePage(Long id){ sprint = sprintEJB.find(id); try { setRelBacklogId(sprint.getReleaseBacklog().getId()); } catch(Exception e) { //System.out.println("-----" + e.getMessage()); } return "sprint-update"; } public String updateSprint(){ try { sprint.setReleaseBacklog(releaseBacklogEJB.find(getRelBacklogId())); } catch (Exception e) { //System.out.println("-----" + e.getMessage()); } sprintEJB.edit(sprint); return "sprint-list"; } public String deleteSprint(Long sprintId){ sprintEJB.delete(sprintId); return "sprint-list"; } public String sprintDetail(Long id) { sprint = sprintEJB.find(id); taskList = taskEJB.findAll(); for (Task t : sprint.getTasks()) { selectedTasks.add(t.getId().toString()); } return "sprint-view"; } public String addTaskToSprint() { long sprintId = sprint.getId(); sprint = sprintEJB.find(sprintId); taskList = sprint.getTasks(); int size = taskList.size(); for (int i = 0; i < size; i++) { taskList.remove(taskList.get(i)); size--; --i; } for (String taskId : selectedTasks) { if (!taskList.contains(taskEJB.find(Long.parseLong(taskId)))) { sprint.getTasks().add(taskEJB.find(Long.parseLong(taskId))); } } sprintEJB.edit(sprint); return "/sprint/sprint-list"; } }
Java
/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjsua2/account.hpp> #include <pjsua2/endpoint.hpp> #include <pjsua2/presence.hpp> #include <pj/ctype.h> #include "util.hpp" using namespace pj; using namespace std; #define THIS_FILE "account.cpp" /////////////////////////////////////////////////////////////////////////////// void RtcpFbCap::fromPj(const pjmedia_rtcp_fb_cap &prm) { this->codecId = pj2Str(prm.codec_id); this->type = prm.type; this->typeName = pj2Str(prm.type_name); this->param = pj2Str(prm.param); } pjmedia_rtcp_fb_cap RtcpFbCap::toPj() const { pjmedia_rtcp_fb_cap cap; pj_bzero(&cap, sizeof(cap)); cap.codec_id = str2Pj(this->codecId); cap.type = this->type; cap.type_name = str2Pj(this->typeName); cap.param = str2Pj(this->param); return cap; } /////////////////////////////////////////////////////////////////////////////// RtcpFbConfig::RtcpFbConfig() { pjmedia_rtcp_fb_setting setting; pjmedia_rtcp_fb_setting_default(&setting); fromPj(setting); } void RtcpFbConfig::fromPj(const pjmedia_rtcp_fb_setting &prm) { this->dontUseAvpf = PJ2BOOL(prm.dont_use_avpf); this->caps.clear(); for (unsigned i = 0; i < prm.cap_count; ++i) { RtcpFbCap cap; cap.fromPj(prm.caps[i]); this->caps.push_back(cap); } } pjmedia_rtcp_fb_setting RtcpFbConfig::toPj() const { pjmedia_rtcp_fb_setting setting; pj_bzero(&setting, sizeof(setting)); setting.dont_use_avpf = this->dontUseAvpf; setting.cap_count = this->caps.size(); for (unsigned i = 0; i < setting.cap_count; ++i) { setting.caps[i] = this->caps[i].toPj(); } return setting; } void RtcpFbConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("RtcpFbConfig"); NODE_READ_BOOL (this_node, dontUseAvpf); ContainerNode cap_node = this_node.readArray("caps"); this->caps.clear(); while (cap_node.hasUnread()) { RtcpFbCap cap; NODE_READ_STRING (cap_node, cap.codecId); NODE_READ_NUM_T (cap_node, pjmedia_rtcp_fb_type, cap.type); NODE_READ_STRING (cap_node, cap.typeName); NODE_READ_STRING (cap_node, cap.param); this->caps.push_back(cap); } } void RtcpFbConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("RtcpFbConfig"); NODE_WRITE_BOOL (this_node, dontUseAvpf); ContainerNode cap_node = this_node.writeNewArray("caps"); for (unsigned i=0; i<this->caps.size(); ++i) { NODE_WRITE_STRING (cap_node, this->caps[i].codecId); NODE_WRITE_NUM_T (cap_node, pjmedia_rtcp_fb_type, this->caps[i].type); NODE_WRITE_STRING (cap_node, this->caps[i].typeName); NODE_WRITE_STRING (cap_node, this->caps[i].param); } } /////////////////////////////////////////////////////////////////////////////// void SrtpCrypto::fromPj(const pjmedia_srtp_crypto &prm) { this->key = pj2Str(prm.key); this->name = pj2Str(prm.name); this->flags = prm.flags; } pjmedia_srtp_crypto SrtpCrypto::toPj() const { pjmedia_srtp_crypto crypto; crypto.key = str2Pj(this->key); crypto.name = str2Pj(this->name); crypto.flags = this->flags; return crypto; } /////////////////////////////////////////////////////////////////////////////// SrtpOpt::SrtpOpt() { pjsua_srtp_opt opt; pjsua_srtp_opt_default(&opt); fromPj(opt); } void SrtpOpt::fromPj(const pjsua_srtp_opt &prm) { this->cryptos.clear(); for (unsigned i = 0; i < prm.crypto_count; ++i) { SrtpCrypto crypto; crypto.fromPj(prm.crypto[i]); this->cryptos.push_back(crypto); } this->keyings.clear(); for (unsigned i = 0; i < prm.keying_count; ++i) { this->keyings.push_back(prm.keying[i]); } } pjsua_srtp_opt SrtpOpt::toPj() const { pjsua_srtp_opt opt; pj_bzero(&opt, sizeof(opt)); opt.crypto_count = this->cryptos.size(); for (unsigned i = 0; i < opt.crypto_count; ++i) { opt.crypto[i] = this->cryptos[i].toPj(); } opt.keying_count = this->keyings.size(); for (unsigned i = 0; i < opt.keying_count; ++i) { opt.keying[i] = (pjmedia_srtp_keying_method)this->keyings[i]; } return opt; } void SrtpOpt::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("SrtpOpt"); ContainerNode crypto_node = this_node.readArray("cryptos"); this->cryptos.clear(); while (crypto_node.hasUnread()) { SrtpCrypto crypto; NODE_READ_STRING (crypto_node, crypto.key); NODE_READ_STRING (crypto_node, crypto.name); NODE_READ_UNSIGNED (crypto_node, crypto.flags); this->cryptos.push_back(crypto); } ContainerNode keying_node = this_node.readArray("keyings"); this->keyings.clear(); while (keying_node.hasUnread()) { unsigned keying; NODE_READ_UNSIGNED (keying_node, keying); this->keyings.push_back(keying); } } void SrtpOpt::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("SrtpOpt"); ContainerNode crypto_node = this_node.writeNewArray("cryptos"); for (unsigned i=0; i<this->cryptos.size(); ++i) { NODE_WRITE_STRING (crypto_node, this->cryptos[i].key); NODE_WRITE_STRING (crypto_node, this->cryptos[i].name); NODE_WRITE_UNSIGNED (crypto_node, this->cryptos[i].flags); } ContainerNode keying_node = this_node.writeNewArray("keyings"); for (unsigned i=0; i<this->keyings.size(); ++i) { NODE_WRITE_UNSIGNED (keying_node, this->keyings[i]); } } /////////////////////////////////////////////////////////////////////////////// void AccountRegConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountRegConfig"); NODE_READ_STRING (this_node, registrarUri); NODE_READ_BOOL (this_node, registerOnAdd); NODE_READ_UNSIGNED (this_node, timeoutSec); NODE_READ_UNSIGNED (this_node, retryIntervalSec); NODE_READ_UNSIGNED (this_node, firstRetryIntervalSec); NODE_READ_UNSIGNED (this_node, randomRetryIntervalSec); NODE_READ_UNSIGNED (this_node, delayBeforeRefreshSec); NODE_READ_BOOL (this_node, dropCallsOnFail); NODE_READ_UNSIGNED (this_node, unregWaitMsec); NODE_READ_UNSIGNED (this_node, proxyUse); NODE_READ_STRING (this_node, contactParams); readSipHeaders(this_node, "headers", headers); } void AccountRegConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountRegConfig"); NODE_WRITE_STRING (this_node, registrarUri); NODE_WRITE_BOOL (this_node, registerOnAdd); NODE_WRITE_UNSIGNED (this_node, timeoutSec); NODE_WRITE_UNSIGNED (this_node, retryIntervalSec); NODE_WRITE_UNSIGNED (this_node, firstRetryIntervalSec); NODE_WRITE_UNSIGNED (this_node, randomRetryIntervalSec); NODE_WRITE_UNSIGNED (this_node, delayBeforeRefreshSec); NODE_WRITE_BOOL (this_node, dropCallsOnFail); NODE_WRITE_UNSIGNED (this_node, unregWaitMsec); NODE_WRITE_UNSIGNED (this_node, proxyUse); NODE_WRITE_STRING (this_node, contactParams); writeSipHeaders(this_node, "headers", headers); } /////////////////////////////////////////////////////////////////////////////// void AccountSipConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountSipConfig"); NODE_READ_STRINGV (this_node, proxies); NODE_READ_STRING (this_node, contactForced); NODE_READ_STRING (this_node, contactParams); NODE_READ_STRING (this_node, contactUriParams); NODE_READ_BOOL (this_node, authInitialEmpty); NODE_READ_STRING (this_node, authInitialAlgorithm); NODE_READ_INT (this_node, transportId); ContainerNode creds_node = this_node.readArray("authCreds"); authCreds.resize(0); while (creds_node.hasUnread()) { AuthCredInfo cred; cred.readObject(creds_node); authCreds.push_back(cred); } } void AccountSipConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountSipConfig"); NODE_WRITE_STRINGV (this_node, proxies); NODE_WRITE_STRING (this_node, contactForced); NODE_WRITE_STRING (this_node, contactParams); NODE_WRITE_STRING (this_node, contactUriParams); NODE_WRITE_BOOL (this_node, authInitialEmpty); NODE_WRITE_STRING (this_node, authInitialAlgorithm); NODE_WRITE_INT (this_node, transportId); ContainerNode creds_node = this_node.writeNewArray("authCreds"); for (unsigned i=0; i<authCreds.size(); ++i) { authCreds[i].writeObject(creds_node); } } /////////////////////////////////////////////////////////////////////////////// void AccountCallConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountCallConfig"); NODE_READ_NUM_T ( this_node, pjsua_call_hold_type, holdType); NODE_READ_NUM_T ( this_node, pjsua_100rel_use, prackUse); NODE_READ_NUM_T ( this_node, pjsua_sip_timer_use, timerUse); NODE_READ_UNSIGNED( this_node, timerMinSESec); NODE_READ_UNSIGNED( this_node, timerSessExpiresSec); } void AccountCallConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountCallConfig"); NODE_WRITE_NUM_T ( this_node, pjsua_call_hold_type, holdType); NODE_WRITE_NUM_T ( this_node, pjsua_100rel_use, prackUse); NODE_WRITE_NUM_T ( this_node, pjsua_sip_timer_use, timerUse); NODE_WRITE_UNSIGNED( this_node, timerMinSESec); NODE_WRITE_UNSIGNED( this_node, timerSessExpiresSec); } /////////////////////////////////////////////////////////////////////////////// void AccountPresConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountPresConfig"); NODE_READ_BOOL ( this_node, publishEnabled); NODE_READ_BOOL ( this_node, publishQueue); NODE_READ_UNSIGNED( this_node, publishShutdownWaitMsec); NODE_READ_STRING ( this_node, pidfTupleId); readSipHeaders(this_node, "headers", headers); } void AccountPresConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountPresConfig"); NODE_WRITE_BOOL ( this_node, publishEnabled); NODE_WRITE_BOOL ( this_node, publishQueue); NODE_WRITE_UNSIGNED( this_node, publishShutdownWaitMsec); NODE_WRITE_STRING ( this_node, pidfTupleId); writeSipHeaders(this_node, "headers", headers); } /////////////////////////////////////////////////////////////////////////////// void AccountMwiConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountMwiConfig"); NODE_READ_BOOL ( this_node, enabled); NODE_READ_UNSIGNED( this_node, expirationSec); } void AccountMwiConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountMwiConfig"); NODE_WRITE_BOOL ( this_node, enabled); NODE_WRITE_UNSIGNED( this_node, expirationSec); } /////////////////////////////////////////////////////////////////////////////// void AccountNatConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountNatConfig"); NODE_READ_NUM_T ( this_node, pjsua_stun_use, sipStunUse); NODE_READ_NUM_T ( this_node, pjsua_stun_use, mediaStunUse); NODE_READ_NUM_T ( this_node, pjsua_nat64_opt, nat64Opt); NODE_READ_BOOL ( this_node, iceEnabled); NODE_READ_INT ( this_node, iceMaxHostCands); NODE_READ_BOOL ( this_node, iceAggressiveNomination); NODE_READ_UNSIGNED( this_node, iceNominatedCheckDelayMsec); NODE_READ_INT ( this_node, iceWaitNominationTimeoutMsec); NODE_READ_BOOL ( this_node, iceNoRtcp); NODE_READ_BOOL ( this_node, iceAlwaysUpdate); NODE_READ_BOOL ( this_node, turnEnabled); NODE_READ_STRING ( this_node, turnServer); NODE_READ_NUM_T ( this_node, pj_turn_tp_type, turnConnType); NODE_READ_STRING ( this_node, turnUserName); NODE_READ_INT ( this_node, turnPasswordType); NODE_READ_STRING ( this_node, turnPassword); NODE_READ_INT ( this_node, contactRewriteUse); NODE_READ_INT ( this_node, contactRewriteMethod); NODE_READ_INT ( this_node, viaRewriteUse); NODE_READ_INT ( this_node, sdpNatRewriteUse); NODE_READ_INT ( this_node, sipOutboundUse); NODE_READ_STRING ( this_node, sipOutboundInstanceId); NODE_READ_STRING ( this_node, sipOutboundRegId); NODE_READ_UNSIGNED( this_node, udpKaIntervalSec); NODE_READ_STRING ( this_node, udpKaData); NODE_READ_INT ( this_node, contactUseSrcPort); } void AccountNatConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountNatConfig"); NODE_WRITE_NUM_T ( this_node, pjsua_stun_use, sipStunUse); NODE_WRITE_NUM_T ( this_node, pjsua_stun_use, mediaStunUse); NODE_WRITE_NUM_T ( this_node, pjsua_nat64_opt, nat64Opt); NODE_WRITE_BOOL ( this_node, iceEnabled); NODE_WRITE_INT ( this_node, iceMaxHostCands); NODE_WRITE_BOOL ( this_node, iceAggressiveNomination); NODE_WRITE_UNSIGNED( this_node, iceNominatedCheckDelayMsec); NODE_WRITE_INT ( this_node, iceWaitNominationTimeoutMsec); NODE_WRITE_BOOL ( this_node, iceNoRtcp); NODE_WRITE_BOOL ( this_node, iceAlwaysUpdate); NODE_WRITE_BOOL ( this_node, turnEnabled); NODE_WRITE_STRING ( this_node, turnServer); NODE_WRITE_NUM_T ( this_node, pj_turn_tp_type, turnConnType); NODE_WRITE_STRING ( this_node, turnUserName); NODE_WRITE_INT ( this_node, turnPasswordType); NODE_WRITE_STRING ( this_node, turnPassword); NODE_WRITE_INT ( this_node, contactRewriteUse); NODE_WRITE_INT ( this_node, contactRewriteMethod); NODE_WRITE_INT ( this_node, viaRewriteUse); NODE_WRITE_INT ( this_node, sdpNatRewriteUse); NODE_WRITE_INT ( this_node, sipOutboundUse); NODE_WRITE_STRING ( this_node, sipOutboundInstanceId); NODE_WRITE_STRING ( this_node, sipOutboundRegId); NODE_WRITE_UNSIGNED( this_node, udpKaIntervalSec); NODE_WRITE_STRING ( this_node, udpKaData); NODE_WRITE_INT ( this_node, contactUseSrcPort); } /////////////////////////////////////////////////////////////////////////////// void AccountMediaConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountMediaConfig"); NODE_READ_BOOL ( this_node, lockCodecEnabled); NODE_READ_BOOL ( this_node, streamKaEnabled); NODE_READ_NUM_T ( this_node, pjmedia_srtp_use, srtpUse); NODE_READ_INT ( this_node, srtpSecureSignaling); NODE_READ_OBJ ( this_node, srtpOpt); NODE_READ_NUM_T ( this_node, pjsua_ipv6_use, ipv6Use); NODE_READ_OBJ ( this_node, transportConfig); NODE_READ_BOOL ( this_node, rtcpMuxEnabled); } void AccountMediaConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountMediaConfig"); NODE_WRITE_BOOL ( this_node, lockCodecEnabled); NODE_WRITE_BOOL ( this_node, streamKaEnabled); NODE_WRITE_NUM_T ( this_node, pjmedia_srtp_use, srtpUse); NODE_WRITE_INT ( this_node, srtpSecureSignaling); NODE_WRITE_OBJ ( this_node, srtpOpt); NODE_WRITE_NUM_T ( this_node, pjsua_ipv6_use, ipv6Use); NODE_WRITE_OBJ ( this_node, transportConfig); NODE_WRITE_BOOL ( this_node, rtcpMuxEnabled); } /////////////////////////////////////////////////////////////////////////////// void AccountVideoConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountVideoConfig"); NODE_READ_BOOL ( this_node, autoShowIncoming); NODE_READ_BOOL ( this_node, autoTransmitOutgoing); NODE_READ_UNSIGNED( this_node, windowFlags); NODE_READ_NUM_T ( this_node, pjmedia_vid_dev_index, defaultCaptureDevice); NODE_READ_NUM_T ( this_node, pjmedia_vid_dev_index, defaultRenderDevice); NODE_READ_NUM_T ( this_node, pjmedia_vid_stream_rc_method, rateControlMethod); NODE_READ_UNSIGNED( this_node, rateControlBandwidth); NODE_READ_UNSIGNED( this_node, startKeyframeCount); NODE_READ_UNSIGNED( this_node, startKeyframeInterval); } void AccountVideoConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountVideoConfig"); NODE_WRITE_BOOL ( this_node, autoShowIncoming); NODE_WRITE_BOOL ( this_node, autoTransmitOutgoing); NODE_WRITE_UNSIGNED( this_node, windowFlags); NODE_WRITE_NUM_T ( this_node, pjmedia_vid_dev_index, defaultCaptureDevice); NODE_WRITE_NUM_T ( this_node, pjmedia_vid_dev_index, defaultRenderDevice); NODE_WRITE_NUM_T ( this_node, pjmedia_vid_stream_rc_method, rateControlMethod); NODE_WRITE_UNSIGNED( this_node, rateControlBandwidth); NODE_WRITE_UNSIGNED( this_node, startKeyframeCount); NODE_WRITE_UNSIGNED( this_node, startKeyframeInterval); } /////////////////////////////////////////////////////////////////////////////// void AccountIpChangeConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountIpChangeConfig"); NODE_READ_BOOL ( this_node, shutdownTp); NODE_READ_BOOL ( this_node, hangupCalls); NODE_READ_UNSIGNED( this_node, reinviteFlags); } void AccountIpChangeConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountIpChangeConfig"); NODE_WRITE_BOOL ( this_node, shutdownTp); NODE_WRITE_BOOL ( this_node, hangupCalls); NODE_WRITE_UNSIGNED( this_node, reinviteFlags); } /////////////////////////////////////////////////////////////////////////////// AccountConfig::AccountConfig() { pjsua_acc_config acc_cfg; pjsua_acc_config_default(&acc_cfg); pjsua_media_config med_cfg; pjsua_media_config_default(&med_cfg); fromPj(acc_cfg, &med_cfg); } /* Convert to pjsip. */ void AccountConfig::toPj(pjsua_acc_config &ret) const { unsigned i; pjsua_acc_config_default(&ret); // Global ret.priority = priority; ret.id = str2Pj(idUri); // AccountRegConfig ret.reg_uri = str2Pj(regConfig.registrarUri); ret.register_on_acc_add = regConfig.registerOnAdd; ret.reg_timeout = regConfig.timeoutSec; ret.reg_retry_interval = regConfig.retryIntervalSec; ret.reg_first_retry_interval= regConfig.firstRetryIntervalSec; ret.reg_retry_random_interval= regConfig.randomRetryIntervalSec; ret.reg_delay_before_refresh= regConfig.delayBeforeRefreshSec; ret.drop_calls_on_reg_fail = regConfig.dropCallsOnFail; ret.unreg_timeout = regConfig.unregWaitMsec; ret.reg_use_proxy = regConfig.proxyUse; ret.reg_contact_params = str2Pj(regConfig.contactParams); for (i=0; i<regConfig.headers.size(); ++i) { pj_list_push_back(&ret.reg_hdr_list, &regConfig.headers[i].toPj()); } // AccountSipConfig ret.cred_count = 0; if (sipConfig.authCreds.size() > PJ_ARRAY_SIZE(ret.cred_info)) PJSUA2_RAISE_ERROR(PJ_ETOOMANY); for (i=0; i<sipConfig.authCreds.size(); ++i) { const AuthCredInfo &src = sipConfig.authCreds[i]; pjsip_cred_info *dst = &ret.cred_info[i]; dst->realm = str2Pj(src.realm); dst->scheme = str2Pj(src.scheme); dst->username = str2Pj(src.username); dst->data_type = src.dataType; dst->data = str2Pj(src.data); dst->ext.aka.k = str2Pj(src.akaK); dst->ext.aka.op = str2Pj(src.akaOp); dst->ext.aka.amf= str2Pj(src.akaAmf); ret.cred_count++; } ret.proxy_cnt = 0; if (sipConfig.proxies.size() > PJ_ARRAY_SIZE(ret.proxy)) PJSUA2_RAISE_ERROR(PJ_ETOOMANY); for (i=0; i<sipConfig.proxies.size(); ++i) { ret.proxy[ret.proxy_cnt++] = str2Pj(sipConfig.proxies[i]); } ret.force_contact = str2Pj(sipConfig.contactForced); ret.contact_params = str2Pj(sipConfig.contactParams); ret.contact_uri_params = str2Pj(sipConfig.contactUriParams); ret.auth_pref.initial_auth = sipConfig.authInitialEmpty; ret.auth_pref.algorithm = str2Pj(sipConfig.authInitialAlgorithm); ret.transport_id = sipConfig.transportId; // AccountCallConfig ret.call_hold_type = callConfig.holdType; ret.require_100rel = callConfig.prackUse; ret.use_timer = callConfig.timerUse; ret.timer_setting.min_se = callConfig.timerMinSESec; ret.timer_setting.sess_expires = callConfig.timerSessExpiresSec; // AccountPresConfig for (i=0; i<presConfig.headers.size(); ++i) { pj_list_push_back(&ret.sub_hdr_list, &presConfig.headers[i].toPj()); } ret.publish_enabled = presConfig.publishEnabled; ret.publish_opt.queue_request= presConfig.publishQueue; ret.unpublish_max_wait_time_msec = presConfig.publishShutdownWaitMsec; ret.pidf_tuple_id = str2Pj(presConfig.pidfTupleId); // AccountMwiConfig ret.mwi_enabled = mwiConfig.enabled; ret.mwi_expires = mwiConfig.expirationSec; // AccountNatConfig ret.sip_stun_use = natConfig.sipStunUse; ret.media_stun_use = natConfig.mediaStunUse; ret.nat64_opt = natConfig.nat64Opt; ret.ice_cfg_use = PJSUA_ICE_CONFIG_USE_CUSTOM; ret.ice_cfg.enable_ice = natConfig.iceEnabled; ret.ice_cfg.ice_max_host_cands = natConfig.iceMaxHostCands; ret.ice_cfg.ice_opt.aggressive = natConfig.iceAggressiveNomination; ret.ice_cfg.ice_opt.nominated_check_delay = natConfig.iceNominatedCheckDelayMsec; ret.ice_cfg.ice_opt.controlled_agent_want_nom_timeout = natConfig.iceWaitNominationTimeoutMsec; ret.ice_cfg.ice_no_rtcp = natConfig.iceNoRtcp; ret.ice_cfg.ice_always_update = natConfig.iceAlwaysUpdate; ret.turn_cfg_use = PJSUA_TURN_CONFIG_USE_CUSTOM; ret.turn_cfg.enable_turn = natConfig.turnEnabled; ret.turn_cfg.turn_server = str2Pj(natConfig.turnServer); ret.turn_cfg.turn_conn_type = natConfig.turnConnType; ret.turn_cfg.turn_auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; ret.turn_cfg.turn_auth_cred.data.static_cred.username = str2Pj(natConfig.turnUserName); ret.turn_cfg.turn_auth_cred.data.static_cred.data_type = (pj_stun_passwd_type)natConfig.turnPasswordType; ret.turn_cfg.turn_auth_cred.data.static_cred.data = str2Pj(natConfig.turnPassword); ret.turn_cfg.turn_auth_cred.data.static_cred.realm = pj_str((char*)""); ret.turn_cfg.turn_auth_cred.data.static_cred.nonce = pj_str((char*)""); ret.allow_contact_rewrite = natConfig.contactRewriteUse; ret.contact_rewrite_method = natConfig.contactRewriteMethod; ret.contact_use_src_port = natConfig.contactUseSrcPort; ret.allow_via_rewrite = natConfig.viaRewriteUse; ret.allow_sdp_nat_rewrite = natConfig.sdpNatRewriteUse; ret.use_rfc5626 = natConfig.sipOutboundUse; ret.rfc5626_instance_id = str2Pj(natConfig.sipOutboundInstanceId); ret.rfc5626_reg_id = str2Pj(natConfig.sipOutboundRegId); ret.ka_interval = natConfig.udpKaIntervalSec; ret.ka_data = str2Pj(natConfig.udpKaData); // AccountMediaConfig ret.rtp_cfg = mediaConfig.transportConfig.toPj(); ret.lock_codec = mediaConfig.lockCodecEnabled; #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0) ret.use_stream_ka = mediaConfig.streamKaEnabled; #endif ret.use_srtp = mediaConfig.srtpUse; ret.srtp_secure_signaling = mediaConfig.srtpSecureSignaling; ret.srtp_opt = mediaConfig.srtpOpt.toPj(); ret.ipv6_media_use = mediaConfig.ipv6Use; ret.enable_rtcp_mux = mediaConfig.rtcpMuxEnabled; ret.rtcp_fb_cfg = mediaConfig.rtcpFbConfig.toPj(); // AccountVideoConfig ret.vid_in_auto_show = videoConfig.autoShowIncoming; ret.vid_out_auto_transmit = videoConfig.autoTransmitOutgoing; ret.vid_wnd_flags = videoConfig.windowFlags; ret.vid_cap_dev = videoConfig.defaultCaptureDevice; ret.vid_rend_dev = videoConfig.defaultRenderDevice; ret.vid_stream_rc_cfg.method= videoConfig.rateControlMethod; ret.vid_stream_rc_cfg.bandwidth = videoConfig.rateControlBandwidth; ret.vid_stream_sk_cfg.count = videoConfig.startKeyframeCount; ret.vid_stream_sk_cfg.interval = videoConfig.startKeyframeInterval; // AccountIpChangeConfig ret.ip_change_cfg.shutdown_tp = ipChangeConfig.shutdownTp; ret.ip_change_cfg.hangup_calls = ipChangeConfig.hangupCalls; ret.ip_change_cfg.reinvite_flags = ipChangeConfig.reinviteFlags; } /* Initialize from pjsip. */ void AccountConfig::fromPj(const pjsua_acc_config &prm, const pjsua_media_config *mcfg) { const pjsip_hdr *hdr; unsigned i; // Global priority = prm.priority; idUri = pj2Str(prm.id); // AccountRegConfig regConfig.registrarUri = pj2Str(prm.reg_uri); regConfig.registerOnAdd = (prm.register_on_acc_add != 0); regConfig.timeoutSec = prm.reg_timeout; regConfig.retryIntervalSec = prm.reg_retry_interval; regConfig.firstRetryIntervalSec = prm.reg_first_retry_interval; regConfig.randomRetryIntervalSec = prm.reg_retry_random_interval; regConfig.delayBeforeRefreshSec = prm.reg_delay_before_refresh; regConfig.dropCallsOnFail = PJ2BOOL(prm.drop_calls_on_reg_fail); regConfig.unregWaitMsec = prm.unreg_timeout; regConfig.proxyUse = prm.reg_use_proxy; regConfig.contactParams = pj2Str(prm.reg_contact_params); regConfig.headers.clear(); hdr = prm.reg_hdr_list.next; while (hdr != &prm.reg_hdr_list) { SipHeader new_hdr; new_hdr.fromPj(hdr); regConfig.headers.push_back(new_hdr); hdr = hdr->next; } // AccountSipConfig sipConfig.authCreds.clear(); for (i=0; i<prm.cred_count; ++i) { AuthCredInfo cred; const pjsip_cred_info &src = prm.cred_info[i]; cred.realm = pj2Str(src.realm); cred.scheme = pj2Str(src.scheme); cred.username = pj2Str(src.username); cred.dataType = src.data_type; cred.data = pj2Str(src.data); cred.akaK = pj2Str(src.ext.aka.k); cred.akaOp = pj2Str(src.ext.aka.op); cred.akaAmf = pj2Str(src.ext.aka.amf); sipConfig.authCreds.push_back(cred); } sipConfig.proxies.clear(); for (i=0; i<prm.proxy_cnt; ++i) { sipConfig.proxies.push_back(pj2Str(prm.proxy[i])); } sipConfig.contactForced = pj2Str(prm.force_contact); sipConfig.contactParams = pj2Str(prm.contact_params); sipConfig.contactUriParams = pj2Str(prm.contact_uri_params); sipConfig.authInitialEmpty = PJ2BOOL(prm.auth_pref.initial_auth); sipConfig.authInitialAlgorithm = pj2Str(prm.auth_pref.algorithm); sipConfig.transportId = prm.transport_id; // AccountCallConfig callConfig.holdType = prm.call_hold_type; callConfig.prackUse = prm.require_100rel; callConfig.timerUse = prm.use_timer; callConfig.timerMinSESec = prm.timer_setting.min_se; callConfig.timerSessExpiresSec = prm.timer_setting.sess_expires; // AccountPresConfig presConfig.headers.clear(); hdr = prm.sub_hdr_list.next; while (hdr != &prm.sub_hdr_list) { SipHeader new_hdr; new_hdr.fromPj(hdr); presConfig.headers.push_back(new_hdr); hdr = hdr->next; } presConfig.publishEnabled = PJ2BOOL(prm.publish_enabled); presConfig.publishQueue = PJ2BOOL(prm.publish_opt.queue_request); presConfig.publishShutdownWaitMsec = prm.unpublish_max_wait_time_msec; presConfig.pidfTupleId = pj2Str(prm.pidf_tuple_id); // AccountMwiConfig mwiConfig.enabled = PJ2BOOL(prm.mwi_enabled); mwiConfig.expirationSec = prm.mwi_expires; // AccountNatConfig natConfig.sipStunUse = prm.sip_stun_use; natConfig.mediaStunUse = prm.media_stun_use; natConfig.nat64Opt = prm.nat64_opt; if (prm.ice_cfg_use == PJSUA_ICE_CONFIG_USE_CUSTOM) { natConfig.iceEnabled = PJ2BOOL(prm.ice_cfg.enable_ice); natConfig.iceMaxHostCands = prm.ice_cfg.ice_max_host_cands; natConfig.iceAggressiveNomination = PJ2BOOL(prm.ice_cfg.ice_opt.aggressive); natConfig.iceNominatedCheckDelayMsec = prm.ice_cfg.ice_opt.nominated_check_delay; natConfig.iceWaitNominationTimeoutMsec = prm.ice_cfg.ice_opt.controlled_agent_want_nom_timeout; natConfig.iceNoRtcp = PJ2BOOL(prm.ice_cfg.ice_no_rtcp); natConfig.iceAlwaysUpdate = PJ2BOOL(prm.ice_cfg.ice_always_update); } else { pjsua_media_config default_mcfg; if (!mcfg) { pjsua_media_config_default(&default_mcfg); mcfg = &default_mcfg; } natConfig.iceEnabled = PJ2BOOL(mcfg->enable_ice); natConfig.iceMaxHostCands= mcfg->ice_max_host_cands; natConfig.iceAggressiveNomination = PJ2BOOL(mcfg->ice_opt.aggressive); natConfig.iceNominatedCheckDelayMsec = mcfg->ice_opt.nominated_check_delay; natConfig.iceWaitNominationTimeoutMsec = mcfg->ice_opt.controlled_agent_want_nom_timeout; natConfig.iceNoRtcp = PJ2BOOL(mcfg->ice_no_rtcp); natConfig.iceAlwaysUpdate = PJ2BOOL(mcfg->ice_always_update); } if (prm.turn_cfg_use == PJSUA_TURN_CONFIG_USE_CUSTOM) { natConfig.turnEnabled = PJ2BOOL(prm.turn_cfg.enable_turn); natConfig.turnServer = pj2Str(prm.turn_cfg.turn_server); natConfig.turnConnType = prm.turn_cfg.turn_conn_type; natConfig.turnUserName = pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.username); natConfig.turnPasswordType = prm.turn_cfg.turn_auth_cred.data.static_cred.data_type; natConfig.turnPassword = pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.data); } else { pjsua_media_config default_mcfg; if (!mcfg) { pjsua_media_config_default(&default_mcfg); mcfg = &default_mcfg; } natConfig.turnEnabled = PJ2BOOL(mcfg->enable_turn); natConfig.turnServer = pj2Str(mcfg->turn_server); natConfig.turnConnType = mcfg->turn_conn_type; natConfig.turnUserName = pj2Str(mcfg->turn_auth_cred.data.static_cred.username); natConfig.turnPasswordType = mcfg->turn_auth_cred.data.static_cred.data_type; natConfig.turnPassword = pj2Str(mcfg->turn_auth_cred.data.static_cred.data); } natConfig.contactRewriteUse = prm.allow_contact_rewrite; natConfig.contactRewriteMethod = prm.contact_rewrite_method; natConfig.contactUseSrcPort = prm.contact_use_src_port; natConfig.viaRewriteUse = prm.allow_via_rewrite; natConfig.sdpNatRewriteUse = prm.allow_sdp_nat_rewrite; natConfig.sipOutboundUse = prm.use_rfc5626; natConfig.sipOutboundInstanceId = pj2Str(prm.rfc5626_instance_id); natConfig.sipOutboundRegId = pj2Str(prm.rfc5626_reg_id); natConfig.udpKaIntervalSec = prm.ka_interval; natConfig.udpKaData = pj2Str(prm.ka_data); // AccountMediaConfig mediaConfig.transportConfig.fromPj(prm.rtp_cfg); mediaConfig.lockCodecEnabled= PJ2BOOL(prm.lock_codec); #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0) mediaConfig.streamKaEnabled = PJ2BOOL(prm.use_stream_ka); #else mediaConfig.streamKaEnabled = false; #endif mediaConfig.srtpUse = prm.use_srtp; mediaConfig.srtpSecureSignaling = prm.srtp_secure_signaling; mediaConfig.srtpOpt.fromPj(prm.srtp_opt); mediaConfig.ipv6Use = prm.ipv6_media_use; mediaConfig.rtcpMuxEnabled = PJ2BOOL(prm.enable_rtcp_mux); mediaConfig.rtcpFbConfig.fromPj(prm.rtcp_fb_cfg); // AccountVideoConfig videoConfig.autoShowIncoming = PJ2BOOL(prm.vid_in_auto_show); videoConfig.autoTransmitOutgoing = PJ2BOOL(prm.vid_out_auto_transmit); videoConfig.windowFlags = prm.vid_wnd_flags; videoConfig.defaultCaptureDevice = prm.vid_cap_dev; videoConfig.defaultRenderDevice = prm.vid_rend_dev; videoConfig.rateControlMethod = prm.vid_stream_rc_cfg.method; videoConfig.rateControlBandwidth = prm.vid_stream_rc_cfg.bandwidth; videoConfig.startKeyframeCount = prm.vid_stream_sk_cfg.count; videoConfig.startKeyframeInterval = prm.vid_stream_sk_cfg.interval; // AccountIpChangeConfig ipChangeConfig.shutdownTp = PJ2BOOL(prm.ip_change_cfg.shutdown_tp); ipChangeConfig.hangupCalls = PJ2BOOL(prm.ip_change_cfg.hangup_calls); ipChangeConfig.reinviteFlags = prm.ip_change_cfg.reinvite_flags; } void AccountConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountConfig"); NODE_READ_INT ( this_node, priority); NODE_READ_STRING ( this_node, idUri); NODE_READ_OBJ ( this_node, regConfig); NODE_READ_OBJ ( this_node, sipConfig); NODE_READ_OBJ ( this_node, callConfig); NODE_READ_OBJ ( this_node, presConfig); NODE_READ_OBJ ( this_node, mwiConfig); NODE_READ_OBJ ( this_node, natConfig); NODE_READ_OBJ ( this_node, mediaConfig); NODE_READ_OBJ ( this_node, videoConfig); } void AccountConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountConfig"); NODE_WRITE_INT ( this_node, priority); NODE_WRITE_STRING ( this_node, idUri); NODE_WRITE_OBJ ( this_node, regConfig); NODE_WRITE_OBJ ( this_node, sipConfig); NODE_WRITE_OBJ ( this_node, callConfig); NODE_WRITE_OBJ ( this_node, presConfig); NODE_WRITE_OBJ ( this_node, mwiConfig); NODE_WRITE_OBJ ( this_node, natConfig); NODE_WRITE_OBJ ( this_node, mediaConfig); NODE_WRITE_OBJ ( this_node, videoConfig); } /////////////////////////////////////////////////////////////////////////////// void AccountInfo::fromPj(const pjsua_acc_info &pai) { id = pai.id; isDefault = pai.is_default != 0; uri = pj2Str(pai.acc_uri); regIsConfigured = pai.has_registration != 0; regIsActive = pai.has_registration && pai.expires > 0 && (pai.status / 100 == 2); regExpiresSec = pai.expires; regStatus = pai.status; regStatusText = pj2Str(pai.status_text); regLastErr = pai.reg_last_err; onlineStatus = pai.online_status != 0; onlineStatusText = pj2Str(pai.online_status_text); } /////////////////////////////////////////////////////////////////////////////// Account::Account() : id(PJSUA_INVALID_ID) { } Account::~Account() { /* If this instance is deleted, also delete the corresponding account in * PJSUA library. */ shutdown(); } void Account::create(const AccountConfig &acc_cfg, bool make_default) PJSUA2_THROW(Error) { pjsua_acc_config pj_acc_cfg; acc_cfg.toPj(pj_acc_cfg); pj_acc_cfg.user_data = (void*)this; PJSUA2_CHECK_EXPR( pjsua_acc_add(&pj_acc_cfg, make_default, &id) ); } void Account::shutdown() { if (isValid() && pjsua_get_state() < PJSUA_STATE_CLOSING) { // Cleanup buddies in the buddy list while(buddyList.size() > 0) { Buddy *b = buddyList[0]; delete b; /* this will remove itself from the list */ } // This caused error message of "Error: cannot find Account.." // when Endpoint::on_reg_started() is called for unregistration. //pjsua_acc_set_user_data(id, NULL); pjsua_acc_del(id); } } void Account::modify(const AccountConfig &acc_cfg) PJSUA2_THROW(Error) { pjsua_acc_config pj_acc_cfg; acc_cfg.toPj(pj_acc_cfg); pj_acc_cfg.user_data = (void*)this; PJSUA2_CHECK_EXPR( pjsua_acc_modify(id, &pj_acc_cfg) ); } bool Account::isValid() const { return pjsua_acc_is_valid(id) != 0; } void Account::setDefault() PJSUA2_THROW(Error) { PJSUA2_CHECK_EXPR( pjsua_acc_set_default(id) ); } bool Account::isDefault() const { return pjsua_acc_get_default() == id; } int Account::getId() const { return id; } Account *Account::lookup(int acc_id) { return (Account*)pjsua_acc_get_user_data(acc_id); } AccountInfo Account::getInfo() const PJSUA2_THROW(Error) { pjsua_acc_info pj_ai; AccountInfo ai; PJSUA2_CHECK_EXPR( pjsua_acc_get_info(id, &pj_ai) ); ai.fromPj(pj_ai); return ai; } void Account::setRegistration(bool renew) PJSUA2_THROW(Error) { PJSUA2_CHECK_EXPR( pjsua_acc_set_registration(id, renew) ); } void Account::setOnlineStatus(const PresenceStatus &pres_st) PJSUA2_THROW(Error) { pjrpid_element pj_rpid; pj_bzero(&pj_rpid, sizeof(pj_rpid)); pj_rpid.type = PJRPID_ELEMENT_TYPE_PERSON; pj_rpid.activity = pres_st.activity; pj_rpid.id = str2Pj(pres_st.rpidId); pj_rpid.note = str2Pj(pres_st.note); PJSUA2_CHECK_EXPR( pjsua_acc_set_online_status2( id, pres_st.status == PJSUA_BUDDY_STATUS_ONLINE, &pj_rpid) ); } void Account::setTransport(TransportId tp_id) PJSUA2_THROW(Error) { PJSUA2_CHECK_EXPR( pjsua_acc_set_transport(id, tp_id) ); } void Account::presNotify(const PresNotifyParam &prm) PJSUA2_THROW(Error) { pj_str_t pj_state_str = str2Pj(prm.stateStr); pj_str_t pj_reason = str2Pj(prm.reason); pjsua_msg_data msg_data; prm.txOption.toPj(msg_data); PJSUA2_CHECK_EXPR( pjsua_pres_notify(id, (pjsua_srv_pres*)prm.srvPres, prm.state, &pj_state_str, &pj_reason, prm.withBody, &msg_data) ); } const BuddyVector& Account::enumBuddies() const PJSUA2_THROW(Error) { return buddyList; } BuddyVector2 Account::enumBuddies2() const PJSUA2_THROW(Error) { BuddyVector2 bv2; pjsua_buddy_id ids[PJSUA_MAX_BUDDIES]; unsigned i, count = PJSUA_MAX_BUDDIES; PJSUA2_CHECK_EXPR( pjsua_enum_buddies(ids, &count) ); for (i = 0; i < count; ++i) { bv2.push_back(Buddy(ids[i])); } return bv2; } Buddy* Account::findBuddy(string uri, FindBuddyMatch *buddy_match) const PJSUA2_THROW(Error) { if (!buddy_match) { static FindBuddyMatch def_bm; buddy_match = &def_bm; } for (unsigned i = 0; i < buddyList.size(); i++) { if (buddy_match->match(uri, *buddyList[i])) return buddyList[i]; } PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); } Buddy Account::findBuddy2(string uri) const PJSUA2_THROW(Error) { pj_str_t pj_uri; pjsua_buddy_id bud_id; pj_strset2(&pj_uri, (char*)uri.c_str()); bud_id = pjsua_buddy_find(&pj_uri); if (id == PJSUA_INVALID_ID) { PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); } Buddy buddy(bud_id); return buddy; } void Account::addBuddy(Buddy *buddy) { pj_assert(buddy); buddyList.push_back(buddy); } void Account::removeBuddy(Buddy *buddy) { pj_assert(buddy); BuddyVector::iterator it; for (it = buddyList.begin(); it != buddyList.end(); it++) { if (*it == buddy) { buddyList.erase(it); return; } } pj_assert(!"Bug! Buddy to be removed is not in the buddy list!"); }
Java
/** * Copyright (C) ARM Limited 2012-2015. 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 version 2 as * published by the Free Software Foundation. * */ #define NEWLINE_CANARY \ /* Unix */ \ "1\n" \ /* Windows */ \ "2\r\n" \ /* Mac OS */ \ "3\r" \ /* RISC OS */ \ "4\n\r" \ /* Add another character so the length isn't 0x0a bytes */ \ "5" #ifdef MALI_SUPPORT #include "gator_events_mali_common.h" #endif static void marshal_summary(long long timestamp, long long uptime, long long monotonic_delta, const char *uname) { unsigned long flags; int cpu = 0; char buf[32]; local_irq_save(flags); gator_buffer_write_packed_int(cpu, SUMMARY_BUF, MESSAGE_SUMMARY); gator_buffer_write_string(cpu, SUMMARY_BUF, NEWLINE_CANARY); gator_buffer_write_packed_int64(cpu, SUMMARY_BUF, timestamp); gator_buffer_write_packed_int64(cpu, SUMMARY_BUF, uptime); gator_buffer_write_packed_int64(cpu, SUMMARY_BUF, monotonic_delta); gator_buffer_write_string(cpu, SUMMARY_BUF, "uname"); gator_buffer_write_string(cpu, SUMMARY_BUF, uname); gator_buffer_write_string(cpu, SUMMARY_BUF, "PAGESIZE"); snprintf(buf, sizeof(buf), "%lu", PAGE_SIZE); gator_buffer_write_string(cpu, SUMMARY_BUF, buf); #if GATOR_IKS_SUPPORT gator_buffer_write_string(cpu, SUMMARY_BUF, "iks"); gator_buffer_write_string(cpu, SUMMARY_BUF, ""); #endif #ifdef CONFIG_PREEMPT_RTB gator_buffer_write_string(cpu, SUMMARY_BUF, "preempt_rtb"); gator_buffer_write_string(cpu, SUMMARY_BUF, ""); #endif #ifdef CONFIG_PREEMPT_RT_FULL gator_buffer_write_string(cpu, SUMMARY_BUF, "preempt_rt_full"); gator_buffer_write_string(cpu, SUMMARY_BUF, ""); #endif /* Let Streamline know which GPU is used so that it can label the GPU Activity appropriately. This is a temporary fix, to be improved in a future release. */ #ifdef MALI_SUPPORT gator_buffer_write_string(cpu, SUMMARY_BUF, "mali_type"); #if (MALI_SUPPORT == MALI_4xx) gator_buffer_write_string(cpu, SUMMARY_BUF, "4xx"); #elif (MALI_SUPPORT == MALI_MIDGARD) gator_buffer_write_string(cpu, SUMMARY_BUF, "6xx"); #else gator_buffer_write_string(cpu, SUMMARY_BUF, "unknown"); #endif #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 2, 0) gator_buffer_write_string(cpu, SUMMARY_BUF, "nosync"); gator_buffer_write_string(cpu, SUMMARY_BUF, ""); #endif gator_buffer_write_string(cpu, SUMMARY_BUF, ""); /* Commit the buffer now so it can be one of the first frames read by Streamline */ local_irq_restore(flags); gator_commit_buffer(cpu, SUMMARY_BUF, gator_get_time()); } static bool marshal_cookie_header(const char *text) { int cpu = get_physical_cpu(); return buffer_check_space(cpu, NAME_BUF, strlen(text) + 3 * MAXSIZE_PACK32); } static void marshal_cookie(int cookie, const char *text) { int cpu = get_physical_cpu(); /* buffer_check_space already called by marshal_cookie_header */ gator_buffer_write_packed_int(cpu, NAME_BUF, MESSAGE_COOKIE); gator_buffer_write_packed_int(cpu, NAME_BUF, cookie); gator_buffer_write_string(cpu, NAME_BUF, text); buffer_check(cpu, NAME_BUF, gator_get_time()); } static void marshal_thread_name(int pid, char *name) { unsigned long flags, cpu; u64 time; local_irq_save(flags); cpu = get_physical_cpu(); time = gator_get_time(); if (buffer_check_space(cpu, NAME_BUF, TASK_COMM_LEN + 3 * MAXSIZE_PACK32 + MAXSIZE_PACK64)) { gator_buffer_write_packed_int(cpu, NAME_BUF, MESSAGE_THREAD_NAME); gator_buffer_write_packed_int64(cpu, NAME_BUF, time); gator_buffer_write_packed_int(cpu, NAME_BUF, pid); gator_buffer_write_string(cpu, NAME_BUF, name); } local_irq_restore(flags); buffer_check(cpu, NAME_BUF, time); } static void marshal_link(int cookie, int tgid, int pid) { unsigned long cpu = get_physical_cpu(), flags; u64 time; local_irq_save(flags); time = gator_get_time(); if (buffer_check_space(cpu, ACTIVITY_BUF, MAXSIZE_PACK64 + 5 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, MESSAGE_LINK); gator_buffer_write_packed_int64(cpu, ACTIVITY_BUF, time); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, cookie); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, tgid); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, pid); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, ACTIVITY_BUF, time); } static bool marshal_backtrace_header(int exec_cookie, int tgid, int pid, u64 time) { int cpu = get_physical_cpu(); if (!buffer_check_space(cpu, BACKTRACE_BUF, MAXSIZE_PACK64 + 5 * MAXSIZE_PACK32 + gator_backtrace_depth * 2 * MAXSIZE_PACK32)) { /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, BACKTRACE_BUF, time); return false; } gator_buffer_write_packed_int64(cpu, BACKTRACE_BUF, time); gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, exec_cookie); gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, tgid); gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, pid); return true; } static void marshal_backtrace(unsigned long address, int cookie, int in_kernel) { int cpu = get_physical_cpu(); if (cookie == 0 && !in_kernel) cookie = UNRESOLVED_COOKIE; gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, cookie); gator_buffer_write_packed_int64(cpu, BACKTRACE_BUF, address); } static void marshal_backtrace_footer(u64 time) { int cpu = get_physical_cpu(); gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, MESSAGE_END_BACKTRACE); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, BACKTRACE_BUF, time); } static bool marshal_event_header(u64 time) { unsigned long flags, cpu = get_physical_cpu(); bool retval = false; local_irq_save(flags); if (buffer_check_space(cpu, BLOCK_COUNTER_BUF, MAXSIZE_PACK32 + MAXSIZE_PACK64)) { gator_buffer_write_packed_int(cpu, BLOCK_COUNTER_BUF, 0); /* key of zero indicates a timestamp */ gator_buffer_write_packed_int64(cpu, BLOCK_COUNTER_BUF, time); retval = true; } local_irq_restore(flags); return retval; } static void marshal_event(int len, int *buffer) { unsigned long i, flags, cpu = get_physical_cpu(); if (len <= 0) return; /* length must be even since all data is a (key, value) pair */ if (len & 0x1) { pr_err("gator: invalid counter data detected and discarded\n"); return; } /* events must be written in key,value pairs */ local_irq_save(flags); for (i = 0; i < len; i += 2) { if (!buffer_check_space(cpu, BLOCK_COUNTER_BUF, 2 * MAXSIZE_PACK32)) break; gator_buffer_write_packed_int(cpu, BLOCK_COUNTER_BUF, buffer[i]); gator_buffer_write_packed_int(cpu, BLOCK_COUNTER_BUF, buffer[i + 1]); } local_irq_restore(flags); } static void marshal_event64(int len, long long *buffer64) { unsigned long i, flags, cpu = get_physical_cpu(); if (len <= 0) return; /* length must be even since all data is a (key, value) pair */ if (len & 0x1) { pr_err("gator: invalid counter data detected and discarded\n"); return; } /* events must be written in key,value pairs */ local_irq_save(flags); for (i = 0; i < len; i += 2) { if (!buffer_check_space(cpu, BLOCK_COUNTER_BUF, 2 * MAXSIZE_PACK64)) break; gator_buffer_write_packed_int64(cpu, BLOCK_COUNTER_BUF, buffer64[i]); gator_buffer_write_packed_int64(cpu, BLOCK_COUNTER_BUF, buffer64[i + 1]); } local_irq_restore(flags); } static void __maybe_unused marshal_event_single(int core, int key, int value) { unsigned long flags, cpu; u64 time; local_irq_save(flags); cpu = get_physical_cpu(); time = gator_get_time(); if (buffer_check_space(cpu, COUNTER_BUF, MAXSIZE_PACK64 + 3 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int64(cpu, COUNTER_BUF, time); gator_buffer_write_packed_int(cpu, COUNTER_BUF, core); gator_buffer_write_packed_int(cpu, COUNTER_BUF, key); gator_buffer_write_packed_int(cpu, COUNTER_BUF, value); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, COUNTER_BUF, time); } static void __maybe_unused marshal_event_single64(int core, int key, long long value) { unsigned long flags, cpu; u64 time; local_irq_save(flags); cpu = get_physical_cpu(); time = gator_get_time(); if (buffer_check_space(cpu, COUNTER_BUF, 2 * MAXSIZE_PACK64 + 2 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int64(cpu, COUNTER_BUF, time); gator_buffer_write_packed_int(cpu, COUNTER_BUF, core); gator_buffer_write_packed_int(cpu, COUNTER_BUF, key); gator_buffer_write_packed_int64(cpu, COUNTER_BUF, value); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, COUNTER_BUF, time); } static void marshal_sched_trace_switch(int pid, int state) { unsigned long cpu = get_physical_cpu(), flags; u64 time; if (!per_cpu(gator_buffer, cpu)[SCHED_TRACE_BUF]) return; local_irq_save(flags); time = gator_get_time(); if (buffer_check_space(cpu, SCHED_TRACE_BUF, MAXSIZE_PACK64 + 5 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, MESSAGE_SCHED_SWITCH); gator_buffer_write_packed_int64(cpu, SCHED_TRACE_BUF, time); gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, pid); gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, state); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, SCHED_TRACE_BUF, time); } static void marshal_sched_trace_exit(int tgid, int pid) { unsigned long cpu = get_physical_cpu(), flags; u64 time; if (!per_cpu(gator_buffer, cpu)[SCHED_TRACE_BUF]) return; local_irq_save(flags); time = gator_get_time(); if (buffer_check_space(cpu, SCHED_TRACE_BUF, MAXSIZE_PACK64 + 2 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, MESSAGE_SCHED_EXIT); gator_buffer_write_packed_int64(cpu, SCHED_TRACE_BUF, time); gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, pid); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, SCHED_TRACE_BUF, time); } #if GATOR_CPU_FREQ_SUPPORT static void marshal_idle(int core, int state) { unsigned long flags, cpu; u64 time; local_irq_save(flags); cpu = get_physical_cpu(); time = gator_get_time(); if (buffer_check_space(cpu, IDLE_BUF, MAXSIZE_PACK64 + 2 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, IDLE_BUF, state); gator_buffer_write_packed_int64(cpu, IDLE_BUF, time); gator_buffer_write_packed_int(cpu, IDLE_BUF, core); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, IDLE_BUF, time); } #endif #if defined(__arm__) || defined(__aarch64__) static void marshal_core_name(const int core, const int cpuid, const char *name) { int cpu = get_physical_cpu(); unsigned long flags; local_irq_save(flags); if (buffer_check_space(cpu, SUMMARY_BUF, MAXSIZE_PACK32 + MAXSIZE_CORE_NAME)) { gator_buffer_write_packed_int(cpu, SUMMARY_BUF, MESSAGE_CORE_NAME); gator_buffer_write_packed_int(cpu, SUMMARY_BUF, core); gator_buffer_write_packed_int(cpu, SUMMARY_BUF, cpuid); gator_buffer_write_string(cpu, SUMMARY_BUF, name); } /* Commit core names now so that they can show up in live */ local_irq_restore(flags); gator_commit_buffer(cpu, SUMMARY_BUF, gator_get_time()); } #endif static void marshal_activity_switch(int core, int key, int activity, int pid, int state) { unsigned long cpu = get_physical_cpu(), flags; u64 time; if (!per_cpu(gator_buffer, cpu)[ACTIVITY_BUF]) return; local_irq_save(flags); time = gator_get_time(); if (buffer_check_space(cpu, ACTIVITY_BUF, MAXSIZE_PACK64 + 5 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, MESSAGE_SWITCH); gator_buffer_write_packed_int64(cpu, ACTIVITY_BUF, time); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, core); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, key); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, activity); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, pid); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, state); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, ACTIVITY_BUF, time); } void gator_marshal_activity_switch(int core, int key, int activity, int pid) { /* state is reserved for cpu use only */ marshal_activity_switch(core, key, activity, pid, 0); }
Java
BeginningDev ============ Beginning Development Initiatives
Java
/** * card_view = new BaristaCardView({el: $("target_selector", url:"", title:"", subtitle:"", fg_color: "#1b9e77", image:"", span_class: "col-lg-12"}); * * A Backbone View that displays a card of information wrapped in link * The view is meant to be a top level entry point to other pages * basic use: card_view = new BaristaCardView(); * optional arguments: * @param {string} url the link to navigate to if the card is clicked, defaults to "" * @param {string} title the title of the card. defaults to "title" * @param {string} subtitle the subtitle of the card. defaults to "subtitle" * @param {string} image the link to an image to show as the cards main content. defaults to "" * @param {string} fg_color the hex color code to use as the foreground color of the view, defaults to * #1b9e77 * @param {string} span_class a bootstrap span class to size the width of the view, defaults to * "col-lg-12" */ Barista.Views.BaristaCardView = Backbone.View.extend({ /** * give the view a name to be used throughout the View's functions when it needs to know what its class * name is * @type {String} */ name: "BaristaCardView", /** * supply a base model for the view * Overide this if you need to use it for dynamic content * @type {Backbone} */ model: new Backbone.Model(), /** * overide the view's default initialize method in order to catch options and render a custom template */ initialize: function(){ // set up color options. default if not specified this.fg_color = (this.options.fg_color !== undefined) ? this.options.fg_color : "#1b9e77"; // set up the span size this.span_class = (this.options.span_class !== undefined) ? this.options.span_class : "col-lg-12"; // set up the url this.url = (this.options.url !== undefined) ? this.options.url : ""; // set up the title this.title = (this.options.title !== undefined) ? this.options.title : "Title"; // set up the subtitle this.subtitle = (this.options.subtitle !== undefined) ? this.options.subtitle : "subtitle"; // set up the image this.image = (this.options.image !== undefined) ? this.options.image : ""; // bind render to model changes this.listenTo(this.model,'change', this.update); // compile the default template for the view this.compile_template(); }, /** * use Handlebars to compile the template for the view */ compile_template: function(){ var self = this; this.div_string = 'barista_view' + new Date().getTime();; this.$el.append(BaristaTemplates.CMapCard({div_string: this.div_string, span_class: this.span_class, url: this.url, title: this.title, subtitle: this.subtitle, image: this.image, fg_color: this.fg_color})); } });
Java
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link href='https://fonts.googleapis.com/css?family=Architects+Daughter' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="/stylesheets/stylesheet.css" media="screen" /> <link rel="stylesheet" type="text/css" href="/stylesheets/pygment_trac.css" media="screen" /> <link rel="stylesheet" type="text/css" href="/stylesheets/print.css" media="print" /> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <title>puppix by puppix</title> </head> <body> <a href="https://github.com/puppix/puppix.github.io"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://github-camo.global.ssl.fastly.net/52760788cde945287fbb584134c4cbc2bc36f904/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f77686974655f6666666666662e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png"></a> <header> <div class="inner"> <h1><a href="/">puppix</a></h1> <h2>Puppet for Enterprise Linux</h2> <a href="https://github.com/puppix" class="button"><small>Follow me on</small>GitHub</a> </div> </header> <div id="content-wrapper"> <div class="inner clearfix"> <section id="main-content"> {{ content }} </section> <aside id="sidebar"> <p> <a href="https://github.com/puppix">./github</a> - GitHub Page<br /> <a href="https://github.com/puppix/puppix.github.io/issues">./issues</a> - Global Tracker<br /> <a href="/codingstyle">./style</a> - Coding Style<br /> </p> <strong>Blog Posts</strong> <ul class="posts"> {% for post in site.posts %} <li> <a href="{{ post.url }}">{{ post.title }}</a><br /> &raquo; <span>{{ post.date | date_to_string }}</span> </li> {% endfor %} </ul> </aside> </div> </div> </body> </html>
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ludum2D.Tiles; using Ludum2D.World; using Microsoft.Xna.Framework; namespace Ludum2D.Core { public class LudumCore { private static LudumCore instance; public static LudumCore Instance { get { if (instance == null) { instance = new LudumCore(); } return instance; } } private LudumCore() { } public bool Initialized { get; private set; } /// <summary> /// Initialize the cores of the engine /// </summary> public void Initialize() { } /// <summary> /// Sets the size of a tile /// </summary> /// <param name="sq">Width and height of a tile; Must be x^2</param> public void SetTileSize(int sq) { if (!Initialized) { throw new Exception("The tile size cannot be modified once the the LudumCore has been initialized"); } Tile.Width = sq; } } }
Java
\section{Laser and Solar Panel} For this project a laser pointer and four solar panels is made available. The purpose of a laser pointer and solar panels is to show how the system works by pointing on a solar panel with the laser. The solar panels is all equal in size, with the dimensions of 3x3 cm. \todo[inline]{Some more info on the laser and the solar panel.}
Java
<?php /** * @group Echo */ class SuppressionMaintenanceTest extends MediaWikiTestCase { public static function provider_updateRow() { $input = array( 'event_id' => 2, 'event_type' => 'mention', 'event_variant' => null, 'event_agent_id' => 3, 'event_agent_ip' => null, 'event_page_title' => '', 'event_page_namespace' => 0, 'event_page_extra' => null, 'event_extra' => null, 'event_page_id' => null, ); return array( array( 'Unrelated row must result in no update', array(), $input ), array( 'Page title and namespace for non-existant page must move into event_extra', array( // expected update 'event_extra' => serialize( array( 'page_title' => 'Yabba Dabba Do', 'page_namespace' => NS_MAIN ) ), ), array( // input row 'event_page_title' => 'Yabba Dabba Do', 'event_page_namespace' => NS_MAIN, ) + $input, ), array( 'Page title and namespace for existing page must be result in update to event_page_id', array( // expected update 'event_page_id' => 42, ), array( // input row 'event_page_title' => 'Mount Rushmore', 'event_page_namespace' => NS_MAIN, ) + $input, self::attachTitleFor( 42, 'Mount Rushmore', NS_MAIN ) ), array( 'When updating non-existant page must keep old extra data', array( // expected update 'event_extra' => serialize( array( 'foo' => 'bar', 'page_title' => 'Yabba Dabba Do', 'page_namespace' => NS_MAIN ) ), ), array( // input row 'event_page_title' => 'Yabba Dabba Do', 'event_page_namespace' => NS_MAIN, 'event_extra' => serialize( array( 'foo' => 'bar' ) ), ) + $input, ), array( 'Must update link-from-title/namespace to link-from-page-id for page-linked events', array( // expected update 'event_extra' => serialize( array( 'link-from-page-id' => 99 ) ), ), array( //input row 'event_type' => 'page-linked', 'event_extra' => serialize( array( 'link-from-title' => 'Horse', 'link-from-namespace' => NS_USER_TALK ) ), ) + $input, self::attachTitleFor( 99, 'Horse', NS_USER_TALK ) ), array( 'Must perform both generic update and page-linked update at same time', array( // expected update 'event_extra' => serialize( array( 'link-from-page-id' => 8675309 ) ), 'event_page_id' => 8675309, ), array( //input row 'event_type' => 'page-linked', 'event_extra' => serialize( array( 'link-from-title' => 'Jenny', 'link-from-namespace' => NS_MAIN, ) ), 'event_page_title' => 'Jenny', 'event_page_namespace' => NS_MAIN, ) + $input, self::attachTitleFor( 8675309, 'Jenny', NS_MAIN ), ), ); } protected static function attachTitleFor( $id, $providedText, $providedNamespace ) { return function( $test, $gen ) use ( $id, $providedText, $providedNamespace ) { $title = $test->getMock( 'Title' ); $title->expects( $test->any() ) ->method( 'getArticleId' ) ->will( $test->returnValue( $id ) ); $titles = array( $providedNamespace => array( $providedText => $title ) ); $gen->setNewTitleFromText( function( $text, $defaultNamespace ) use( $titles ) { if ( isset( $titles[$defaultNamespace][$text] ) ) { return $titles[$defaultNamespace][$text]; } return Title::newFromText( $text, $defaultNamespace ); } ); }; } /** * @dataProvider provider_updateRow */ public function testUpdateRow( $message, $expected, $input, $callable = null ) { $gen = new EchoSuppressionRowUpdateGenerator; if ( $callable ) { call_user_func( $callable, $this, $gen ); } $update = $gen->update( (object) $input ); $this->assertEquals( $expected, $update, $message ); } }
Java