repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
4thAce/evilhow
lib/x/index.php
466
<?php // $Id: /cvsroot/tikiwiki/tiki/lib/x/index.php,v 1.1.2.1 2007-11-04 22:08:35 nyloth Exp $ // Copyright (c) 2002-2007, Luis Argerich, Garland Foster, Eduardo Polidor, et. al. // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // This redirects to the sites root to prevent directory browsing header ("location: ../index.php"); die; ?>
lgpl-2.1
wr0ngway/tivohmo
lib/tivohmo/adapters/streamio/transcoder.rb
9901
module TivoHMO module Adapters module StreamIO # Transcodes video to tivo format using the streamio gem (ffmpeg) class Transcoder include TivoHMO::API::Transcoder include GemLogger::LoggerSupport # TODO: add ability to pass through data (copy codec) # for files that are already (partially?) in the right # format for tivo. Check against a mapping of # tivo serial->allowed_formats # https://code.google.com/p/streambaby/wiki/video_compatibility def transcode(writeable_io, format="video/x-tivo-mpeg") tmpfile = Tempfile.new('tivohmo_transcode') begin transcode_thread = run_transcode(tmpfile.path, format) # give the transcode thread a chance to start up before we # start copying from it. Not strictly necessary, but makes # the log messages show up in the right order sleep 0.1 run_copy(tmpfile.path, writeable_io, transcode_thread) ensure tmpfile.close tmpfile.unlink end nil end def transcoder_options(format="video/x-tivo-mpeg") opts = { video_max_bitrate: 30_000_000, buffer_size: 4096, audio_bitrate: 448_000, format: format, custom: [] } opts = select_video_frame_rate(opts) opts = select_video_dimensions(opts) opts = select_video_codec(opts) opts = select_video_bitrate(opts) opts = select_audio_codec(opts) opts = select_audio_bitrate(opts) opts = select_audio_sample_rate(opts) opts = select_container(opts) opts = select_subtitle(opts) custom = opts.delete(:custom) opts[:custom] = custom.join(" ") if custom opts.delete(:format) opts end protected def movie @movie ||= FFMPEG::Movie.new(item.file) end def video_info @video_info ||= begin info_attrs = %w[ path duration time bitrate rotation creation_time video_stream video_codec video_bitrate colorspace dar audio_stream audio_codec audio_bitrate audio_sample_rate calculated_aspect_ratio size audio_channels frame_rate container resolution width height ] Hash[info_attrs.collect {|attr| [attr.to_sym, movie.send(attr)] }] end end def select_container(opts) if opts[:format] == 'video/x-tivo-mpeg-ts' opts[:custom] << "-f mpegts" else opts[:custom] << "-f vob" end opts end def select_audio_sample_rate(opts) if video_info[:audio_sample_rate] if AUDIO_SAMPLE_RATES.include?(video_info[:audio_sample_rate]) opts[:audio_sample_rate] = video_info[:audio_sample_rate] else opts[:audio_sample_rate] = 48000 end end opts end def select_audio_bitrate(opts) # transcode assumes unit of Kbit, whilst video_info has unit of bit opts[:audio_bitrate] = (opts[:audio_bitrate] / 1000).to_i opts end def select_audio_codec(opts) if video_info[:audio_codec] if AUDIO_CODECS.any? { |ac| video_info[:audio_codec] =~ /#{ac}/ } opts[:audio_codec] = 'copy' if video_info[:video_codec] =~ /mpeg2video/ opts[:custom] << "-copyts" end else opts[:audio_codec] = 'ac3' end end opts end def select_video_bitrate(opts) vbr = video_info[:video_bitrate] default_vbr = 16_384_000 if vbr && vbr > 0 if vbr >= opts[:video_max_bitrate] opts[:video_bitrate] = (opts[:video_max_bitrate] * 0.95).to_i elsif vbr > default_vbr opts[:video_bitrate] = vbr else opts[:video_bitrate] = default_vbr end end opts[:video_bitrate] ||= default_vbr # transcode assumes unit of Kbit, whilst video_info has unit of bit opts[:video_bitrate] = (opts[:video_bitrate] / 1000).to_i opts[:video_max_bitrate] = (opts[:video_max_bitrate] / 1000).to_i opts end def select_video_codec(opts) if VIDEO_CODECS.any? { |vc| video_info[:video_codec] =~ /#{vc}/ } opts[:video_codec] = 'copy' if video_info[:video_codec] =~ /h264/ opts[:custom] << "-bsf h264_mp4toannexb" end else opts[:video_codec] = 'mpeg2video' opts[:custom] << "-pix_fmt yuv420p" end opts end def select_video_dimensions(opts) video_width = video_info[:width].to_i VIDEO_WIDTHS.each do |w| w = w.to_i if video_width >= w video_width = w opts[:preserve_aspect_ratio] = :width break end end video_width = VIDEO_WIDTHS.last.to_i unless video_width video_height = video_info[:height].to_i VIDEO_WIDTHS.each do |h| h = h.to_i if video_height >= h video_height = h opts[:preserve_aspect_ratio] = :height break end end video_height = VIDEO_HEIGHTS.last.to_i unless video_height opts[:resolution] = "#{video_width}x#{video_height}" opts[:preserve_aspect_ratio] ||= :height opts end def select_video_frame_rate(opts) frame_rate = video_info[:frame_rate] if frame_rate =~ /\A[0-9\.]+\Z/ frame_rate = frame_rate.to_f elsif frame_rate =~ /\A\((\d+)\/(\d+)\)\Z/ frame_rate = $1.to_f / $2.to_f end VIDEO_FRAME_RATES.each do |r| opts[:frame_rate] = r break if frame_rate >= r.to_f end opts end def select_subtitle(opts) st = item.subtitle if st case st.type when :file code = st.language_code file = st.location if File.exist?(file) logger.info "Using subtitles present at: #{file}" opts[:custom] << "-vf subtitles=\"#{file}\"" else logger.error "Subtitle doesn't exist at: #{file}" end when :embedded file = item.file idx = st.location logger.info "Using embedded subtitles [#{idx}] present at: #{file}" opts[:custom] << "-vf subtitles=\"#{file}\":si=#{idx}" else logger.error "Unknown subtitle type: #{st.type}" end end opts end def run_transcode(output_filename, format) logger.info "Movie Info: " + video_info.collect {|k, v| "#{k}=#{v.inspect}"}.join(' ') opts = transcoder_options(format) logger.info "Transcoding options: " + opts.collect {|k, v| "#{k}='#{v}'"}.join(' ') aspect_opt = opts.delete(:preserve_aspect_ratio) t_opts = {} t_opts[:preserve_aspect_ratio] = aspect_opt if aspect_opt transcode_thread = Thread.new do begin logger.info "Starting transcode of '#{movie.path}' to '#{output_filename}'" transcoded_movie = movie.transcode(output_filename, opts, t_opts) do |progress| logger.debug ("[%3i%%] Transcoding #{File.basename(movie.path)}" % (progress * 100).to_i) raise "Halted" if Thread.current[:halt] end logger.info "Transcoding completed, transcoded file size: #{File.size(output_filename)}" rescue => e logger.error ("Transcode failed: #{e}") end end return transcode_thread end # we could avoid this if streamio-ffmpeg had a way to output to an IO, but # it only supports file based output for now, so have to manually copy the # file's bytes to our output stream def run_copy(transcoded_filename, writeable_io, transcode_thread) logger.info "Starting stream copy from: #{transcoded_filename}" file = File.open(transcoded_filename, 'rb') begin bytes_copied = 0 # copying the IO from transcoded file to web output # stream is faster than the transcoding, and thus we # hit eof before transcode is done. Therefore we need # to keep retrying while the transcode thread is alive, # then to avoid a race condition at the end, we keep # going till we've copied all the bytes while transcode_thread.alive? || bytes_copied < File.size(transcoded_filename) # sleep a bit at start of thread so we don't have a # wasteful tight loop when transcoding is really slow sleep 0.2 while data = file.read(4096) break unless data.size > 0 writeable_io << data bytes_copied += data.size end end logger.info "Stream copy completed, #{bytes_copied} bytes copied" rescue => e logger.error ("Stream copy failed: #{e}") transcode_thread[:halt] = true ensure file.close end end end end end end
lgpl-2.1
zaps166/DSPBlocks
Blocks/General/Clip.cpp
2440
#include "Clip.hpp" #include "Array.hpp" Clip::Clip() : Block( "Clip", "Ucina sygnał", 1, 1, PROCESSING ), min( -1.0f ), max( 1.0f ) {} bool Clip::start() { if ( inputsCount() != outputsCount() ) return false; settings->setRunMode( true ); buffer.reset( new float[ inputsCount() ]() ); return true; } void Clip::setSample( int input, float sample ) { buffer[ input ] = sample; } void Clip::exec( Array< Sample > &samples ) { for ( int i = 0 ; i < outputsCount() ; ++i ) { if ( buffer[ i ] > max ) buffer[ i ] = max; else if ( buffer[ i ] < min ) buffer[ i ] = min; samples += ( Sample ){ getTarget( i ), buffer[ i ] }; } } void Clip::stop() { settings->setRunMode( false ); buffer.reset(); } Block *Clip::createInstance() { Clip *block = new Clip; block->settings = new Settings( *block, true, 1, maxIO, true, 1, maxIO, true, new ClipUI( *block ) ); block->setLabel(); return block; } void Clip::serialize( QDataStream &ds ) const { ds << min << max; } void Clip::deSerialize( QDataStream &ds ) { ds >> min >> max; setLabel(); } void Clip::setLabel() { label = QString( getName() + "\n[%1 - %2]" ).arg( min ).arg( max ); update(); } #include <QDoubleSpinBox> #include <QPushButton> #include <QLayout> #include <QLabel> ClipUI::ClipUI( Clip &block ) : AdditionalSettings( block ), block( block ) { QLabel *minL = new QLabel( "Minimum: " ); minL->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Expanding ); QLabel *maxL = new QLabel( "Maximum: " ); maxL->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Expanding ); minB = new QDoubleSpinBox; minB->setDecimals( 4 ); minB->setSingleStep( 0.01 ); minB->setRange( -1000.0, 1000.0 ); maxB = new QDoubleSpinBox; maxB->setDecimals( 4 ); maxB->setSingleStep( 0.01 ); maxB->setRange( -1000.0, 1000.0 ); QGridLayout *layout = new QGridLayout( this ); layout->addWidget( minL, 0, 0 ); layout->addWidget( minB, 0, 1 ); layout->addWidget( maxL, 1, 0 ); layout->addWidget( maxB, 1, 1 ); layout->setMargin( 3 ); } void ClipUI::prepare() { minB->setValue( block.min ); maxB->setValue( block.max ); connect( minB, SIGNAL( valueChanged( double ) ), this, SLOT( setMinValue( double ) ) ); connect( maxB, SIGNAL( valueChanged( double ) ), this, SLOT( setMaxValue( double ) ) ); } void ClipUI::setMinValue( double v ) { block.min = v; block.setLabel(); } void ClipUI::setMaxValue( double v ) { block.max = v; block.setLabel(); }
lgpl-2.1
jusa/lipstick
src/compositor/lipstickcompositorwindow.cpp
8709
/*************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Aaron Kennedy <aaron.kennedy@jollamobile.com> ** ** This file is part of lipstick. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QCoreApplication> #include <QWaylandCompositor> #include <QWaylandInputDevice> #include <QTimer> #include <sys/types.h> #include <signal.h> #include "lipstickcompositor.h" #include "lipstickcompositorwindow.h" LipstickCompositorWindow::LipstickCompositorWindow(int windowId, const QString &category, QWaylandSurface *surface, QQuickItem *parent) : QWaylandSurfaceItem(surface, parent), m_windowId(windowId), m_category(category), m_ref(0), m_delayRemove(false), m_windowClosed(false), m_removePosted(false), m_mouseRegionValid(false) { setFlags(QQuickItem::ItemIsFocusScope | flags()); refreshMouseRegion(); // Handle ungrab situations connect(this, SIGNAL(visibleChanged()), SLOT(handleTouchCancel())); connect(this, SIGNAL(enabledChanged()), SLOT(handleTouchCancel())); connect(this, SIGNAL(touchEventsEnabledChanged()), SLOT(handleTouchCancel())); } QVariant LipstickCompositorWindow::userData() const { return m_data; } void LipstickCompositorWindow::setUserData(QVariant data) { if (m_data == data) return; m_data = data; emit userDataChanged(); } int LipstickCompositorWindow::windowId() const { return m_windowId; } qint64 LipstickCompositorWindow::processId() const { if (surface()) return surface()->processId(); else return 0; } bool LipstickCompositorWindow::delayRemove() const { return m_delayRemove; } void LipstickCompositorWindow::setDelayRemove(bool delay) { if (delay == m_delayRemove) return; m_delayRemove = delay; emit delayRemoveChanged(); tryRemove(); } QString LipstickCompositorWindow::category() const { return m_category; } QString LipstickCompositorWindow::title() const { if (surface()) return surface()->title(); return QString(); } void LipstickCompositorWindow::imageAddref() { ++m_ref; } void LipstickCompositorWindow::imageRelease() { Q_ASSERT(m_ref); --m_ref; tryRemove(); } bool LipstickCompositorWindow::canRemove() const { return m_windowClosed && !m_delayRemove && m_ref == 0; } void LipstickCompositorWindow::tryRemove() { if (canRemove() && !m_removePosted) { m_removePosted = true; QCoreApplication::postEvent(this, new QEvent(QEvent::User)); } } QRect LipstickCompositorWindow::mouseRegionBounds() const { if (m_mouseRegionValid) return m_mouseRegion.boundingRect(); else return QRect(0, 0, width(), height()); } void LipstickCompositorWindow::refreshMouseRegion() { QWaylandSurface *s = surface(); if (s) { QVariantMap properties = s->windowProperties(); if (properties.contains(QLatin1String("MOUSE_REGION"))) { m_mouseRegion = s->windowProperties().value("MOUSE_REGION").value<QRegion>(); m_mouseRegionValid = true; if (LipstickCompositor::instance()->debug()) qDebug() << "Window" << windowId() << "mouse region set:" << m_mouseRegion; } else { m_mouseRegionValid = false; if (LipstickCompositor::instance()->debug()) qDebug() << "Window" << windowId() << "mouse region cleared"; } emit mouseRegionBoundsChanged(); } } void LipstickCompositorWindow::refreshGrabbedKeys() { QWaylandSurface *s = surface(); if (s) { const QStringList grabbedKeys = s->windowProperties().value( QLatin1String("GRABBED_KEYS")).value<QStringList>(); if (m_grabbedKeys.isEmpty() && !grabbedKeys.isEmpty()) { qApp->installEventFilter(this); } else if (!m_grabbedKeys.isEmpty() && grabbedKeys.isEmpty()) { qApp->removeEventFilter(this); } m_grabbedKeys.clear(); foreach (const QString &key, grabbedKeys) m_grabbedKeys.append(key.toInt()); if (LipstickCompositor::instance()->debug()) qDebug() << "Window" << windowId() << "grabbed keys changed:" << grabbedKeys; } } bool LipstickCompositorWindow::eventFilter(QObject *, QEvent *event) { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QWaylandSurface *m_surface = surface(); if (m_surface && m_grabbedKeys.contains(ke->key())) { QWaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice(); inputDevice->sendFullKeyEvent(m_surface, ke); return true; } } return false; } bool LipstickCompositorWindow::isInProcess() const { return false; } bool LipstickCompositorWindow::event(QEvent *e) { bool rv = QWaylandSurfaceItem::event(e); if (e->type() == QEvent::User) { m_removePosted = false; if (canRemove()) delete this; } return rv; } void LipstickCompositorWindow::mousePressEvent(QMouseEvent *event) { QWaylandSurface *m_surface = surface(); if (m_surface && (!m_mouseRegionValid || m_mouseRegion.contains(event->pos()))) { QWaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice(); if (inputDevice->mouseFocus() != m_surface) inputDevice->setMouseFocus(m_surface, event->pos(), event->globalPos()); inputDevice->sendMousePressEvent(event->button(), event->pos(), event->globalPos()); } else { event->ignore(); } } void LipstickCompositorWindow::mouseMoveEvent(QMouseEvent *event) { QWaylandSurface *m_surface = surface(); if (m_surface){ QWaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice(); inputDevice->sendMouseMoveEvent(m_surface, event->pos(), event->globalPos()); } else { event->ignore(); } } void LipstickCompositorWindow::mouseReleaseEvent(QMouseEvent *event) { QWaylandSurface *m_surface = surface(); if (m_surface){ QWaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice(); inputDevice->sendMouseReleaseEvent(event->button(), event->pos(), event->globalPos()); } else { event->ignore(); } } void LipstickCompositorWindow::wheelEvent(QWheelEvent *event) { QWaylandSurface *m_surface = surface(); if (m_surface) { QWaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice(); inputDevice->sendMouseWheelEvent(event->orientation(), event->delta()); } else { event->ignore(); } } void LipstickCompositorWindow::touchEvent(QTouchEvent *event) { QWaylandSurface *m_surface = surface(); if (touchEventsEnabled() && m_surface) { QList<QTouchEvent::TouchPoint> points = event->touchPoints(); if (m_mouseRegionValid && points.count() == 1 && event->touchPointStates() & Qt::TouchPointPressed && !m_mouseRegion.contains(points.at(0).pos().toPoint())) { event->ignore(); return; } QWaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice(); event->accept(); if (inputDevice->mouseFocus() != m_surface) { QPoint pointPos; if (!points.isEmpty()) pointPos = points.at(0).pos().toPoint(); inputDevice->setMouseFocus(m_surface, pointPos, pointPos); } inputDevice->sendFullTouchEvent(event); } else { event->ignore(); } } void LipstickCompositorWindow::handleTouchCancel() { QWaylandSurface *m_surface = surface(); if (!m_surface) return; QWaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice(); if (inputDevice->mouseFocus() == m_surface && (!isVisible() || !isEnabled() || !touchEventsEnabled())) { inputDevice->sendTouchCancelEvent(); inputDevice->setMouseFocus(0, QPointF()); } } void LipstickCompositorWindow::terminateProcess(int killTimeout) { kill(processId(), SIGTERM); QTimer::singleShot(killTimeout, this, SLOT(killProcess())); } void LipstickCompositorWindow::killProcess() { kill(processId(), SIGKILL); }
lgpl-2.1
cacheonix/cacheonix-core
src/org/cacheonix/impl/util/logging/spi/ErrorHandler.java
3022
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cacheonix.impl.util.logging.spi; import org.cacheonix.impl.util.logging.Appender; import org.cacheonix.impl.util.logging.Logger; /** * Appenders may delegate their error handling to <code>ErrorHandlers</code>. * <p/> * <p>Error handling is a particularly tedious to get right because by definition errors are hard to predict and to * reproduce. * <p/> * <p/> * <p>Please take the time to contact the author in case you discover that errors are not properly handled. You are most * welcome to suggest new error handling policies or criticize existing policies. * * @author Ceki G&uuml;lc&uuml; */ public interface ErrorHandler extends OptionHandler { /** * Add a reference to a logger to which the failing appender might be attached to. The failing appender will be * searched and replaced only in the loggers you add through this method. * * @param logger One of the loggers that will be searched for the failing appender in view of replacement. * @since 1.2 */ void setLogger(Logger logger); /** * Equivalent to the {@link #error(String, Exception, int, LoggingEvent event)} with the the event parameter set to * <code>null</code>. */ void error(String message, Exception e, int errorCode); /** * This method is normally used to just print the error message passed as a parameter. */ void error(String message); /** * This method is invoked to handle the error. * * @param message The message associated with the error. * @param e The Exception that was thrown when the error occurred. * @param errorCode The error code associated with the error. * @param event The logging event that the failing appender is asked to log. * @since 1.2 */ void error(String message, Exception e, int errorCode, LoggingEvent event); /** * Set the appender for which errors are handled. This method is usually called when the error handler is * configured. * * @since 1.2 */ void setAppender(Appender appender); /** * Set the appender to fallback upon in case of failure. * * @since 1.2 */ void setBackupAppender(Appender appender); }
lgpl-2.1
SixTrack/SixTrack
test/collimation_jaw_fit_b4_offsets_tilts/plotImpacts.py
14374
import matplotlib.pyplot as plt import numpy as np import math def fitProfile( x, fitParams, cLen ): ''' fitParams[0]: const term fitParams[1]: linear term ... fitParams[-2]: n-th order term fitParams[-1]: scaling factor ''' y=0.0 for ii in range(len(fitParams)-1): if (ii==2): y+=(x**ii)*fitParams[ii]/cLen else: y+=(x**ii)*fitParams[ii] return y*fitParams[-1] def rotateBy(xIn,yIn,skewAngle=0.0,direct=True): if (type(xIn) is list and type(yIn) is list): xOut=[]; yOut=[] for tmpX,tmpY in zip(xIn,yIn): xOut.append(tmpX*math.cos(skewAngle)+math.sin(skewAngle)*tmpY) yOut.append(tmpY*math.cos(skewAngle)-math.sin(skewAngle)*tmpX) else: xOut=xIn*math.cos(skewAngle)+math.sin(skewAngle)*yIn yOut=yIn*math.cos(skewAngle)-math.sin(skewAngle)*xIn return xOut,yOut def parseFirstImpacts(iFileName='FirstImpacts.dat'): print 'parsing file %s ...'%(iFileName) data=[] with open(iFileName,'r') as iFile: for line in iFile.readlines(): if (line.startswith('#')): continue data.append([]) tmpData=line.strip().split() for ii,tmpDatum in zip(range(len(tmpData)),tmpData): data[-1].append(float(tmpDatum)) if ( ii<=3 ): data[-1][-1]=int(data[-1][-1]) print '...done - read %i lines.'%(len(data)) return data def parseFlukaImpacts(iFileName='FLUKA_impacts.dat'): print 'parsing file %s ...'%(iFileName) data=[] with open(iFileName,'r') as iFile: for line in iFile.readlines(): if (line.startswith('#')): continue data.append([]) tmpData=line.strip().split() for ii,tmpDatum in zip(range(len(tmpData)),tmpData): data[-1].append(float(tmpDatum)) if ( ii==0 or ii>=7 ): data[-1][-1]=int(data[-1][-1]) print '...done - read %i lines.'%(len(data)) return data def parseJawProfiles(iFileName='jaw_profiles.dat'): print 'parsing file %s ...'%(iFileName) data=[] with open(iFileName,'r') as iFile: for line in iFile.readlines(): if (line.startswith('#')): continue data.append([]) tmpData=line.strip().split() for ii,tmpDatum in zip(range(len(tmpData)),tmpData): data[-1].append(float(tmpDatum)) if ( ii<=2 ): data[-1][-1]=int(data[-1][-1]) print '...done - read %i lines.'%(len(data)) return data def getFittingData(iFileName='fort.6'): print 'parsing file %s ...'%(iFileName) profiles=[ [], [], [] ] with open(iFileName,'r') as iFile: for line in iFile.readlines(): line=line.strip() if (line.startswith('Fit point #')): data=line.split() profiles[0].append(float(data[4])) profiles[1].append(float(data[5])*1000) profiles[2].append(float(data[6])*1000) return profiles def parseCollGaps(iFileName='collgaps.dat'): print 'parsing file %s ...'%(iFileName) collData=[] with open(iFileName,'r') as iFile: for line in iFile.readlines(): line=line.strip() if (line.startswith('#')): continue data=line.split() for ii in range(len(data)): if ( ii!=1 and ii !=6): data[ii]=float(data[ii]) if ( ii==0 ): data[ii]=int(data[ii]+1E-4) collData.append(data[:]) print ' ...acquired %i collimators'%(len(collData)) return collData def parseCollDBtemp(iFileName='collimator-temp.db'): print 'parsing file %s ...'%(iFileName) collData=[] with open(iFileName,'r') as iFile: for line in iFile.readlines(): line=line.strip() if (line.startswith('#')): # a new collimator collData.append([]) else: collData[-1].append(line) if (len(collData[-1])>2): collData[-1][-1]=float(collData[-1][-1]) print ' ...acquired %i collimators'%(len(collData)) return collData def plotFirstImpacts(iCols,lCols,fitProfileS,fitProfileY1,fitProfileY2,sixCurves,data): plt.figure('First impacts',figsize=(16,16)) iPlot=0 for iCol,lCol,jCol in zip(iCols,lCols,range(len(lCols))): Ss_in=[] ; Ss_out=[] Hs_in=[] ; Hs_out=[] Vs_in=[] ; Vs_out=[] for datum in data: if (datum[2]==iCol): # - s_in: entrance at jaw/slice or actual impact point; # - x_in,xp_in,y_in,yp_in (jaw ref sys): particle at front face of # collimator/slice, not at impact on jaw # - x_out,xp_out,y_out,yp_out (jaw ref sys): particle exit point at # collimator/slice, or coordinate of hard interaction ss=datum[4] xx=datum[6] yy=datum[8] Ss_in.append(ss) Hs_in.append(xx*1000) Vs_in.append(yy*1000) ss=datum[5] xx=datum[10] yy=datum[12] Ss_out.append(ss) Hs_out.append(xx*1000) Vs_out.append(yy*1000) iPlot+=1 plt.subplot(len(iCols),3,iPlot) if ( jCol==0 ): plt.plot(sixCurves[0],sixCurves[1],'ro-',label='6T fit-L') plt.plot(sixCurves[0],sixCurves[2],'mo-',label='6T fit-R') plt.plot(fitProfileS[jCol],fitProfileY1[jCol],'b-',label='expected-L') plt.plot(fitProfileS[jCol],fitProfileY2[jCol],'c-',label='expected-R') plt.plot(Ss_in,Hs_in,'go',label='in') plt.plot(Ss_out,Hs_out,'yo',label='out') plt.xlabel(r's_{jaw} [m]') plt.ylabel(r'x_{jaw} [mm]') plt.title('iColl=%i - Cleaning plane'%(iCol)) plt.legend(loc='best',fontsize=10) plt.tight_layout() plt.grid() iPlot+=1 plt.subplot(len(iCols),3,iPlot) plt.plot(Ss_in,Vs_in,'go',label='in') plt.plot(Ss_out,Vs_out,'yo',label='out') plt.xlabel(r's_{jaw} [m]') plt.ylabel(r'y_{jaw} [mm]') plt.title('iColl=%i - Ortoghonal plane'%(iCol)) plt.legend(loc='best',fontsize=10) plt.tight_layout() plt.grid() iPlot+=1 plt.subplot(len(iCols),3,iPlot) plt.plot(Hs_in,Vs_in,'go',label='in') plt.plot(Hs_out,Vs_out,'yo',label='out') plt.xlabel(r'x_{jaw} [mm]') plt.ylabel(r'y_{jaw} [mm]') plt.title('iColl=%i - transverse plane'%(iCol)) plt.legend(loc='best',fontsize=10) plt.tight_layout() plt.grid() plt.show() def plotFlukaImpacts(iCols,lCols,fitProfileS,fitProfileY1,fitProfileY2,sixCurves,data,skewAngles): plt.figure('FLUKA impacts',figsize=(16,16)) iPlot=0 for iCol,lCol,jCol,skewAngle in zip(iCols,lCols,range(len(lCols)),skewAngles): Ss=[] Hs=[] Vs=[] for datum in data: if (datum[0]==iCol): ss=datum[2] xx=datum[3] yy=datum[5] Ss.append(ss) Hs.append(xx) Vs.append(yy) if ( jCol==0 ): xx1,yy1=rotateBy(sixCurves[1],[0.0 for col in range(len(sixCurves[0]))],skewAngle=-skewAngle) xx2,yy2=rotateBy(sixCurves[2],[0.0 for col in range(len(sixCurves[0]))],skewAngle=-skewAngle) xp1,yp1=rotateBy(fitProfileY1[jCol],[0.0 for col in range(len(fitProfileS[jCol]))],skewAngle=-skewAngle) xp2,yp2=rotateBy(fitProfileY2[jCol],[0.0 for col in range(len(fitProfileS[jCol]))],skewAngle=-skewAngle) iPlot+=1 plt.subplot(len(iCols),3,iPlot) if ( jCol==0 ): plt.plot(sixCurves[0],xx1,'ro-',label='6T fit-L') plt.plot(sixCurves[0],xx2,'mo-',label='6T fit-R') plt.plot(Ss,Hs,'go',label='impact') plt.plot(fitProfileS[jCol],xp1,'b-',label='expected-L') plt.plot(fitProfileS[jCol],xp2,'c-',label='expected-R') plt.xlabel(r's [m]') plt.ylabel(r'x [mm]') plt.title('iColl=%i - x-s plane'%(iCol)) plt.legend(loc='best',fontsize=10) plt.tight_layout() plt.grid() iPlot+=1 plt.subplot(len(iCols),3,iPlot) if ( jCol==0 ): plt.plot(sixCurves[0],yy1,'ro-',label='6T fit-L') plt.plot(sixCurves[0],yy2,'mo-',label='6T fit-R') plt.plot(Ss,Vs,'go',label='impact') plt.plot(fitProfileS[jCol],yp1,'b-',label='expected-L') plt.plot(fitProfileS[jCol],yp2,'c-',label='expected-R') plt.xlabel(r's [m]') plt.ylabel(r'y [mm]') plt.title('iColl=%i - y-s plane'%(iCol)) plt.legend(loc='best',fontsize=10) plt.tight_layout() plt.grid() iPlot+=1 plt.subplot(len(iCols),3,iPlot) if ( jCol==0 ): plt.plot(xx1,yy1,'ro-',label='6T fit-L') plt.plot(xx2,yy2,'mo-',label='6T fit-R') plt.plot(Hs,Vs,'go',label='impact') plt.plot(xp1,yp1,'b-',label='expected-L') plt.plot(xp2,yp2,'c-',label='expected-R') plt.xlabel(r'x [mm]') plt.ylabel(r'y [mm]') plt.title('iColl=%i - x-y plane'%(iCol)) plt.legend(loc='best',fontsize=10) plt.tight_layout() plt.grid() plt.show() def plotJawProfiles(iCols,lCols,fitProfileS,fitProfileY1,fitProfileY2,sixCurves,data): plt.figure('Jaw Profiles',figsize=(16,16)) iPlot=0 for iCol,lCol,jCol in zip(iCols,lCols,range(len(lCols))): Ss_in=[] ; Ss_out=[] Hs_in=[] ; Hs_out=[] Vs_in=[] ; Vs_out=[] for datum in data: if (datum[0]==iCol): ss=datum[7] xx=datum[3] yy=datum[5] if ( datum[-1]==1 ): # entrance Ss_in.append(ss) Hs_in.append(xx*1000) Vs_in.append(yy*1000) else: # exit Ss_out.append(ss) Hs_out.append(xx*1000) Vs_out.append(yy*1000) iPlot+=1 plt.subplot(len(iCols),3,iPlot) if ( jCol==0 ): plt.plot(sixCurves[0],sixCurves[1],'ro-',label='6T fit-L') plt.plot(sixCurves[0],sixCurves[2],'mo-',label='6T fit-R') plt.plot(fitProfileS[jCol],fitProfileY1[jCol],'b-',label='expected-L') plt.plot(fitProfileS[jCol],fitProfileY2[jCol],'c-',label='expected-R') plt.plot(Ss_in,Hs_in,'go',label='in') plt.plot(Ss_out,Hs_out,'yo',label='out') plt.xlabel(r's_{jaw} [m]') plt.ylabel(r'x_{jaw} [mm]') plt.title('iColl=%i - Cleaning plane'%(iCol)) plt.legend(loc='best',fontsize=10) plt.tight_layout() plt.grid() iPlot+=1 plt.subplot(len(iCols),3,iPlot) plt.plot(Ss_in,Vs_in,'go',label='in') plt.plot(Ss_out,Vs_out,'yo',label='out') plt.xlabel(r's_{jaw} [m]') plt.ylabel(r'y_{jaw} [mm]') plt.title('iColl=%i - Ortoghonal plane'%(iCol)) plt.legend(loc='best',fontsize=10) plt.tight_layout() plt.grid() iPlot+=1 plt.subplot(len(iCols),3,iPlot) plt.plot(Hs_in,Vs_in,'go',label='in') plt.plot(Hs_out,Vs_out,'yo',label='out') plt.xlabel(r'x_{jaw} [mm]') plt.ylabel(r'y_{jaw} [mm]') plt.title('iColl=%i - transverse plane'%(iCol)) plt.legend(loc='best',fontsize=10) plt.tight_layout() plt.grid() plt.show() if ( __name__ == "__main__" ): iCols=[9,10,11,15] fitParams=[ # iCol=9 [ 2.70E-3, -0.18, 0.18, 0.0, 0.0, 0.0, 2 ], [ 5.1962E-4, 0.09, -0.27, 50.0, 0.0, 0.0, 2 ], # iCol=10 [ 0., 1. ], [ 0., 1. ], # iCol=11 [ 0., 1. ], [ 0., 1. ], # iCol=15 [ 0., 1. ], [ 0., 1. ] ] nPoints=110 lDebug=False collData=parseCollGaps() lCols=[] ; hGaps=[] ; skewAngles=[] ; tilt1=[] ; tilt2=[] for iCol in iCols: for collDatum in collData: if ( collDatum[0]==iCol ): lCols.append(collDatum[7]) hGaps.append(collDatum[5]) skewAngles.append(collDatum[2]) tilt1.append(collDatum[10]) tilt2.append(collDatum[11]) break collDBdata=parseCollDBtemp() offSets=[] for iCol in iCols: offSets.append(collDBdata[iCol-1][4]) if (lDebug): for iCol,jCol in zip(iCols,range(len(iCols))): print iCol, lCols[jCol], hGaps[jCol], skewAngles[jCol], tilt1[jCol], tilt2[jCol], offSets[jCol] fitProfileS=[] ; fitProfileY1=[] ; fitProfileY2=[] for lCol,hGap,jCol in zip(lCols,hGaps,range(len(iCols))): Ss=[ float(ii)/nPoints*lCol for ii in range(nPoints+1) ] if ( tilt1[jCol]>0 ): Y1s=[ ( fitProfile(s,fitParams[ 2*jCol],lCol)+hGap+tilt1[jCol]*(s )+offSets[jCol])*1000 for s in Ss ] else: Y1s=[ ( fitProfile(s,fitParams[ 2*jCol],lCol)+hGap+tilt1[jCol]*(s-lCol)+offSets[jCol])*1000 for s in Ss ] if ( tilt2[jCol]>0 ): Y2s=[ (-fitProfile(s,fitParams[1+2*jCol],lCol)-hGap+tilt2[jCol]*(s-lCol)+offSets[jCol])*1000 for s in Ss ] else: Y2s=[ (-fitProfile(s,fitParams[1+2*jCol],lCol)-hGap+tilt2[jCol]*(s )+offSets[jCol])*1000 for s in Ss ] fitProfileS.append(Ss[:]) fitProfileY1.append(Y1s[:]) fitProfileY2.append(Y2s[:]) sixCurves=getFittingData() sixCurves[1]=[tmpPoint+offSets[0]*1000 for tmpPoint in sixCurves[1]] sixCurves[2]=[tmpPoint+offSets[0]*1000 for tmpPoint in sixCurves[2]] data=parseFirstImpacts() plotFirstImpacts(iCols,lCols,fitProfileS,fitProfileY1,fitProfileY2,sixCurves,data) data=parseFlukaImpacts() plotFlukaImpacts(iCols,lCols,fitProfileS,fitProfileY1,fitProfileY2,sixCurves,data,skewAngles) data=parseJawProfiles() plotJawProfiles(iCols,lCols,fitProfileS,fitProfileY1,fitProfileY2,sixCurves,data)
lgpl-2.1
JiriOndrusek/wildfly-core
discovery/src/main/java/org/wildfly/extension/discovery/DiscoveryExtension.java
4843
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.discovery; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.wildfly.discovery.spi.DiscoveryProvider; /** * The extension class for the WildFly Discovery extension. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class DiscoveryExtension implements Extension { // shared constants static final String SUBSYSTEM_NAME = "discovery"; static final String NAMESPACE = "urn:jboss:domain:discovery:1.0"; // XML and DMR name strings static final String ABSTRACT_TYPE = "abstract-type"; static final String ABSTRACT_TYPE_AUTHORITY = "abstract-type-authority"; static final String AGGREGATE_PROVIDER = "aggregate-provider"; static final String ATTRIBUTE = "attribute"; static final String ATTRIBUTES = "attributes"; static final String DISCOVERY = "discovery"; static final String NAME = "name"; static final String PROVIDERS = "providers"; static final String SERVICE = "service"; static final String SERVICES = "services"; static final String STATIC_PROVIDER = "static-provider"; static final String URI = "uri"; static final String URI_SCHEME_AUTHORITY = "uri-scheme-authority"; static final String VALUE = "value"; static final String RESOURCE_NAME = DiscoveryExtension.class.getPackage().getName() + ".LocalDescriptions"; static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, SUBSYSTEM_NAME); static final String DISCOVERY_PROVIDER_CAPABILITY = "org.wildfly.discovery.provider"; static final RuntimeCapability<?> DISCOVERY_PROVIDER_RUNTIME_CAPABILITY = RuntimeCapability.Builder.of(DISCOVERY_PROVIDER_CAPABILITY, true).setServiceType(DiscoveryProvider.class).build(); /** * Construct a new instance. */ public DiscoveryExtension() { } @Override public void initialize(final ExtensionContext context) { final SubsystemRegistration subsystemRegistration = context.registerSubsystem(SUBSYSTEM_NAME, ModelVersion.create(1, 0)); subsystemRegistration.setHostCapable(); subsystemRegistration.registerXMLElementWriter(DiscoverySubsystemParser::new); final ManagementResourceRegistration resourceRegistration = subsystemRegistration.registerSubsystemModel(DiscoverySubsystemDefinition.getInstance()); resourceRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); } @Override public void initializeParsers(final ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE, DiscoverySubsystemParser::new); } static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefixes) { StringBuilder sb = new StringBuilder(SUBSYSTEM_NAME); if (keyPrefixes != null) { for (String current : keyPrefixes) { sb.append(".").append(current); } } return new StandardResourceDescriptionResolver(sb.toString(), RESOURCE_NAME, DiscoveryExtension.class.getClassLoader(), true, false); } }
lgpl-2.1
xwiki/xwiki-platform
xwiki-platform-core/xwiki-platform-wysiwyg/xwiki-platform-wysiwyg-api/src/main/java/org/xwiki/wysiwyg/internal/converter/DefaultRequestParameterConverter.java
10042
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.wysiwyg.internal.converter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.wysiwyg.converter.HTMLConverter; import org.xwiki.wysiwyg.converter.RequestParameterConverter; import org.xwiki.wysiwyg.filter.MutableServletRequest; import org.xwiki.wysiwyg.filter.MutableServletRequestFactory; /** * Default implementation of {@link RequestParameterConverter} that handles HTML conversion of parameters needing such * conversion. * * @version $Id$ * @since 13.5RC1 */ @Component @Singleton public class DefaultRequestParameterConverter implements RequestParameterConverter { /** * The name of the request parameter whose multiple values indicate the request parameters that require HTML * conversion. For instance, if this parameter's value is {@code [description, content]} then the request has two * parameters, {@code description} and {@code content}, requiring HTML conversion. The syntax these parameters must * be converted to is found also on the request, under {@code description_syntax} and {@code content_syntax} * parameters. */ private static final String REQUIRES_HTML_CONVERSION = "RequiresHTMLConversion"; /** * The name of the session attribute holding the conversion output. The conversion output is stored in a {@link Map} * of {@link Map}s. The first key identifies the request and the second key is the name of the request parameter * that required HTML conversion. */ private static final String CONVERSION_OUTPUT = "com.xpn.xwiki.wysiwyg.server.converter.output"; /** * The name of the session attribute holding the conversion exceptions. The conversion exceptions are stored in a * {@link Map} of {@link Map}s. The first key identifies the request and the second key is the name of the request * parameter that required HTML conversion. */ private static final String CONVERSION_ERRORS = "com.xpn.xwiki.wysiwyg.server.converter.errors"; @Inject private MutableServletRequestFactory mutableServletRequestFactory; @Inject private HTMLConverter htmlConverter; @Inject private Logger logger; @Override public Optional<ServletRequest> convert(ServletRequest request, ServletResponse response) throws IOException { Optional<ServletRequest> result = Optional.of(request); // Take the list of request parameters that require HTML conversion. String[] parametersRequiringHTMLConversion = request.getParameterValues(REQUIRES_HTML_CONVERSION); if (parametersRequiringHTMLConversion != null) { // Wrap the current request in order to be able to change request parameters. MutableServletRequest mreq = this.mutableServletRequestFactory.newInstance(request); // Remove the list of request parameters that require HTML conversion to avoid recurrency. mreq.removeParameter(REQUIRES_HTML_CONVERSION); // Try to convert each parameter from the list and save caught exceptions. Map<String, Throwable> errors = new HashMap<>(); // Save also the output to prevent loosing data in case of conversion exceptions. Map<String, String> output = new HashMap<>(); convertHTML(parametersRequiringHTMLConversion, mreq, output, errors); if (!errors.isEmpty()) { handleConversionErrors(errors, output, mreq, response); result = Optional.empty(); } else { result = Optional.of(mreq); } } return result; } private void convertHTML(String[] parametersRequiringHTMLConversion, MutableServletRequest request, Map<String, String> output, Map<String, Throwable> errors) { for (String parameterName : parametersRequiringHTMLConversion) { String html = request.getParameter(parameterName); // Remove the syntax parameter from the request to avoid interference with further request processing. String syntax = request.removeParameter(parameterName + "_syntax"); if (html == null || syntax == null) { continue; } try { request.setParameter(parameterName, this.htmlConverter.fromHTML(html, syntax)); } catch (Exception e) { this.logger.error(e.getLocalizedMessage(), e); errors.put(parameterName, e); } // If the conversion fails the output contains the value before the conversion. output.put(parameterName, request.getParameter(parameterName)); } } private void handleConversionErrors(Map<String, Throwable> errors, Map<String, String> output, MutableServletRequest mreq, ServletResponse res) throws IOException { ServletRequest req = mreq.getRequest(); if (req instanceof HttpServletRequest && "XMLHttpRequest".equals(((HttpServletRequest) req).getHeader("X-Requested-With"))) { // If this is an AJAX request then we should simply send back the error. StringBuilder errorMessage = new StringBuilder(); // Aggregate all error messages (for all fields that have conversion errors). for (Map.Entry<String, Throwable> entry : errors.entrySet()) { errorMessage.append(entry.getKey()).append(": "); errorMessage.append(entry.getValue().getLocalizedMessage()).append('\n'); } ((HttpServletResponse) res).sendError(400, errorMessage.substring(0, errorMessage.length() - 1)); return; } // Otherwise, if this is a normal request, we have to redirect the request back and provide a key to // access the exception and the value before the conversion from the session. // Redirect to the error page specified on the request. String redirectURL = mreq.getParameter("xerror"); if (redirectURL == null) { // Redirect to the referrer page. redirectURL = mreq.getReferer(); } // Extract the query string. String queryString = StringUtils.substringAfterLast(redirectURL, String.valueOf('?')); // Remove the query string. redirectURL = StringUtils.substringBeforeLast(redirectURL, String.valueOf('?')); // Remove the previous key from the query string. We have to do this since this might not be the first // time the conversion fails for this redirect URL. queryString = queryString.replaceAll("key=.*&?", ""); if (queryString.length() > 0 && !queryString.endsWith(String.valueOf('&'))) { queryString += '&'; } // Save the output and the caught exceptions on the session. queryString += "key=" + save(mreq, output, errors); mreq.sendRedirect(res, redirectURL + '?' + queryString); } /** * Saves on the session the conversion output and the caught conversion exceptions, after a conversion failure. * * @param mreq the request used to access the session * @param output the conversion output for the given request * @param errors the conversion exceptions for the given request * @return a key that can be used along with the name of the request parameters that required HTML conversion to * extract the conversion output and the conversion exceptions from the {@link #CONVERSION_OUTPUT} and * {@value #CONVERSION_ERRORS} session attributes */ @SuppressWarnings("unchecked") private String save(MutableServletRequest mreq, Map<String, String> output, Map<String, Throwable> errors) { // Generate a random key to identify the request. String key = RandomStringUtils.randomAlphanumeric(4); // Save the output on the session. Map<String, Map<String, String>> conversionOutput = (Map<String, Map<String, String>>) mreq.getSessionAttribute(CONVERSION_OUTPUT); if (conversionOutput == null) { conversionOutput = new HashMap<>(); mreq.setSessionAttribute(CONVERSION_OUTPUT, conversionOutput); } conversionOutput.put(key, output); // Save the errors on the session. Map<String, Map<String, Throwable>> conversionErrors = (Map<String, Map<String, Throwable>>) mreq.getSessionAttribute(CONVERSION_ERRORS); if (conversionErrors == null) { conversionErrors = new HashMap<>(); mreq.setSessionAttribute(CONVERSION_ERRORS, conversionErrors); } conversionErrors.put(key, errors); return key; } }
lgpl-2.1
aumuell/open-inventor
libSoXt/src/viewers/SoXtPlaneVwr.c++
30652
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ /* * Copyright (C) 1990,91 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.3 $ | | Classes : SoXtPlaneViewer | | Author(s) : Alain Dumesny | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #include <cmath> #include <inttypes.h> #include <X11/Intrinsic.h> #include <X11/Xlib.h> #include <X11/keysym.h> #include <Inventor/SbPList.h> #include <Inventor/nodes/SoOrthographicCamera.h> #include <Inventor/nodes/SoPerspectiveCamera.h> #include <Inventor/Xt/SoXtCursors.h> #include <Inventor/Xt/viewers/SoXtPlaneViewer.h> #include <Inventor/Xt/SoXtIcons.h> #include <Inventor/Xt/SoXtResource.h> #include "SoXtBitmapButton.h" #include <GL/gl.h> /* * Defines */ enum ViewerModes { PICK_MODE, VIEW_MODE, DOLLY_MODE_ACTIVE, PAN_MODE, PAN_MODE_ACTIVE, ROLL_MODE_ACTIVE, SEEK_MODE }; // list of custom push buttons enum { X_PUSH = 0, Y_PUSH, Z_PUSH, CAM_PUSH, PUSH_NUM }; // Resources for labels. typedef struct { char *planeViewer; char *transX; char *transY; char *planeViewerPreferenceSheet; char *dolly; char *zoom; } RES_LABELS; static RES_LABELS rl; static char *defaultLabel[]={ "Plane Viewer", "transX", "transY", "Plane Viewer Preference Sheet", "Dolly", "Zoom" }; //////////////////////////////////////////////////////////////////////// // // Public constructor - build the widget right now // SoXtPlaneViewer::SoXtPlaneViewer( Widget parent, const char *name, SbBool buildInsideParent, SoXtFullViewer::BuildFlag b, SoXtViewer::Type t) : SoXtFullViewer( parent, name, buildInsideParent, b, t, FALSE) // tell base class not to build just yet // //////////////////////////////////////////////////////////////////////// { // In this case, render area is what the app wants, so buildNow = TRUE constructorCommon(TRUE); } //////////////////////////////////////////////////////////////////////// // // SoEXTENDER constructor - the subclass tells us whether to build or not // SoXtPlaneViewer::SoXtPlaneViewer( Widget parent, const char *name, SbBool buildInsideParent, SoXtFullViewer::BuildFlag b, SoXtViewer::Type t, SbBool buildNow) : SoXtFullViewer( parent, name, buildInsideParent, b, t, FALSE) // tell base class not to build just yet // //////////////////////////////////////////////////////////////////////// { // In this case, render area may be what the app wants, // or it may want a subclass of render area. Pass along buildNow // as it was passed to us. constructorCommon(buildNow); } //////////////////////////////////////////////////////////////////////// // // Called by the constructors // // private // void SoXtPlaneViewer::constructorCommon(SbBool buildNow) // //////////////////////////////////////////////////////////////////////// { // init local vars mode = isViewing() ? VIEW_MODE : PICK_MODE; createdCursors = FALSE; transCursor = dollyCursor = seekCursor = 0; setSize( SbVec2s(520, 470) ); // default size setClassName("SoXtPlaneViewer"); // Initialize buttonList. for (int i=0; i<PUSH_NUM; i++) buttonList[i] = NULL; // Build the widget tree, and let SoXtComponent know about our base widget. if (buildNow) { Widget w = buildWidget(getParentWidget()); setBaseWidget(w); } } //////////////////////////////////////////////////////////////////////// // // Description: // Destructor. // // Use: public SoXtPlaneViewer::~SoXtPlaneViewer() // //////////////////////////////////////////////////////////////////////// { for (int i=0; i<PUSH_NUM; i++) delete buttonList[i]; // free the viewer cursors Display *display = getDisplay(); if (display) { if (transCursor) XFreeCursor(display, transCursor); if (dollyCursor) XFreeCursor(display, dollyCursor); if (seekCursor) XFreeCursor(display, seekCursor); } } //////////////////////////////////////////////////////////////////////// // // Description: // Build the parent class widget, then add buttons. // // Use: protected Widget SoXtPlaneViewer::buildWidget(Widget parent) // //////////////////////////////////////////////////////////////////////// { SoXtResource xp(parent); if (!xp.getResource( "planeViewer", "PlaneViewer", rl.planeViewer )) rl.planeViewer = defaultLabel[0]; setPopupMenuString( rl.planeViewer ); // Create the root widget and register it with a class name Widget w = SoXtFullViewer::buildWidget(parent); // get resources... SoXtResource xr(w); if (!xr.getResource( "transX", "TransX", rl.transX )) rl.transX = defaultLabel[1]; if (!xr.getResource( "transY", "TransY", rl.transY )) rl.transY = defaultLabel[2]; if (!xr.getResource( "planeViewerPreferenceSheet","PlaneViewerPreferenceSheet",rl.planeViewerPreferenceSheet )) rl.planeViewerPreferenceSheet = defaultLabel[3]; if (!xr.getResource( "dolly", "Dolly", rl.dolly )) rl.dolly = defaultLabel[4]; if (!xr.getResource( "zoom", "Zoom", rl.zoom )) rl.zoom = defaultLabel[5]; // assign decoration titles setBottomWheelString( rl.transX ); setLeftWheelString( rl. transY ); setPrefSheetString( rl.planeViewerPreferenceSheet ); return w; } //////////////////////////////////////////////////////////////////////// // // Description: // add our own button to the existing list // // Use: virtual protected void SoXtPlaneViewer::createViewerButtons(Widget parent) // //////////////////////////////////////////////////////////////////////// { // get the default buttons SoXtFullViewer::createViewerButtons(parent); // allocate the custom buttons for (int i=0; i<PUSH_NUM; i++) { buttonList[i] = new SoXtBitmapButton(parent, FALSE); Widget w = buttonList[i]->getWidget(); XtVaSetValues(w, XmNuserData, this, NULL); XtAddCallback(w, XmNactivateCallback, (XtCallbackProc) SoXtPlaneViewer::pushButtonCB, (XtPointer) (unsigned long) i); // add this button to the list... viewerButtonWidgets->append(w); } // set the button images buttonList[X_PUSH]->setIcon(so_xt_X_bits, so_xt_icon_width, so_xt_icon_height); buttonList[Y_PUSH]->setIcon(so_xt_Y_bits, so_xt_icon_width, so_xt_icon_height); buttonList[Z_PUSH]->setIcon(so_xt_Z_bits, so_xt_icon_width, so_xt_icon_height); buttonList[CAM_PUSH]->setIcon(so_xt_persp_bits, so_xt_icon_width, so_xt_icon_height); } //////////////////////////////////////////////////////////////////////// // // Description: // Call the base class and sets the correct cursor on the window // // Use: virtual public void SoXtPlaneViewer::setViewing(SbBool flag) // //////////////////////////////////////////////////////////////////////// { if (flag == viewingFlag) return; // call the base class SoXtFullViewer::setViewing(flag); switchMode(isViewing() ? VIEW_MODE : PICK_MODE); } //////////////////////////////////////////////////////////////////////// // // Description: // Enables/Disable the viewer cursor on the window. // // Use: virtual public void SoXtPlaneViewer::setCursorEnabled(SbBool flag) // //////////////////////////////////////////////////////////////////////// { if (flag == cursorEnabledFlag) return; cursorEnabledFlag = flag; if (! isViewing()) return; updateCursor(); } //////////////////////////////////////////////////////////////////////// // // Description: // Call the parent class and change the right thumbwheel label. // // Use: virtual public void SoXtPlaneViewer::setCamera(SoCamera *newCamera) // //////////////////////////////////////////////////////////////////////// { if (camera == newCamera) return; // set the right thumbwheel label and toggle button image based on // the camera type if (newCamera != NULL && (camera == NULL || newCamera->getTypeId() != camera->getTypeId())) { if (newCamera->isOfType(SoOrthographicCamera::getClassTypeId())) { if (buttonList[CAM_PUSH]) buttonList[CAM_PUSH]->setIcon(so_xt_ortho_bits, so_xt_icon_width, so_xt_icon_height); setRightWheelString( rl.zoom ); } else { if (buttonList[CAM_PUSH]) buttonList[CAM_PUSH]->setIcon(so_xt_persp_bits, so_xt_icon_width, so_xt_icon_height); setRightWheelString( rl.dolly ); } } // call parent class SoXtFullViewer::setCamera(newCamera); } //////////////////////////////////////////////////////////////////////// // // Description: // Process the given event to do viewing stuff // // Use: virtual protected void SoXtPlaneViewer::processEvent(XAnyEvent *xe) // //////////////////////////////////////////////////////////////////////// { if ( processCommonEvents(xe) ) return; if (!createdCursors) updateCursor(); XButtonEvent *be; XMotionEvent *me; XKeyEvent *ke; XCrossingEvent *ce; KeySym keysym; SbVec2s raSize = getGlxSize(); switch(xe->type) { case ButtonPress: case ButtonRelease: be = (XButtonEvent *)xe; if (be->button != Button1 && be->button != Button2) break; locator[0] = be->x; locator[1] = raSize[1] - be->y; if (mode == SEEK_MODE) { if (xe->type == ButtonPress) seekToPoint(locator); } else { if (xe->type == ButtonPress) interactiveCountInc(); else // ButtonRelease interactiveCountDec(); updateViewerMode(be->state); } break; case KeyPress: case KeyRelease: ke = (XKeyEvent *)xe; keysym = XLookupKeysym(ke, 0); locator[0] = ke->x; locator[1] = raSize[1] - ke->y; if (keysym == XK_Control_L || keysym == XK_Control_R) updateViewerMode(ke->state); break; case MotionNotify: me = (XMotionEvent *)xe; switch (mode) { case DOLLY_MODE_ACTIVE: dollyCamera( SbVec2s(me->x, raSize[1] - me->y) ); break; case PAN_MODE_ACTIVE: translateCamera(SbVec2f(me->x/float(raSize[0]), (raSize[1] - me->y)/float(raSize[1]))); break; case ROLL_MODE_ACTIVE: rollCamera( SbVec2s(me->x, raSize[1] - me->y) ); break; } break; case LeaveNotify: case EnterNotify: ce = (XCrossingEvent *)xe; // // because the application might use Ctrl-key for motif menu // accelerators we might not receive a key-up event, so make sure // to reset any Ctrl mode if we loose focus, but don't do anything // if Ctrl-key is not down (nothing to do) or if a mouse button // is down (we will get another leaveNotify). // if (! (ce->state & ControlMask)) break; if (ce->state & Button1Mask || ce->state & Button2Mask) break; if (xe->type == LeaveNotify) switchMode(VIEW_MODE); else updateViewerMode(ce->state); break; } } //////////////////////////////////////////////////////////////////////// // // Description: // sets the viewer mode based on what keys and buttons are being pressed // // Use: private void SoXtPlaneViewer::updateViewerMode(unsigned int state) // //////////////////////////////////////////////////////////////////////// { // ??? WARNING - this routine ONLY works because of // ??? SoXtViewer::updateEventState() which is called for us // ??? by SoXtViewer::processCommonEvents(). // ??? (XEvent state for button and modifier keys is not updated // ??? until after the event is received. WEIRD) // LEFT+MIDDLE down if (state & Button1Mask && state & Button2Mask) { switchMode(DOLLY_MODE_ACTIVE); } // LEFT down else if (state & Button1Mask) { if (state & ControlMask) switchMode(PAN_MODE_ACTIVE); else switchMode(DOLLY_MODE_ACTIVE); } // MIDDLE DOWN else if (state & Button2Mask) { if (state & ControlMask) switchMode(ROLL_MODE_ACTIVE); else switchMode(PAN_MODE_ACTIVE); } // no buttons down... else { if (state & ControlMask) switchMode(PAN_MODE); else switchMode(VIEW_MODE); } } //////////////////////////////////////////////////////////////////////// // // Description: // switches to the specified viewer mode // // Use: private void SoXtPlaneViewer::switchMode(int newMode) // //////////////////////////////////////////////////////////////////////// { Widget raWidget = getRenderAreaWidget(); // assing new mode SbBool redrawNeeded = FALSE; int prevMode = mode; mode = newMode; // update the cursor updateCursor(); // check the old viewer mode for redraw need if (prevMode == ROLL_MODE_ACTIVE) redrawNeeded = TRUE; // switch to new viewer mode switch (newMode) { case PICK_MODE: if (raWidget && XtWindow(raWidget)) { // ???? is if are going into PICK mode and some of our // mouse buttons are still down, make sure to decrement // interactive count correctly (correct draw style). One // for the LEFT and one for MIDDLE mouse. Window root_return, child_return; int root_x_return, root_y_return; int win_x_return, win_y_return; unsigned int mask_return; XQueryPointer(XtDisplay(raWidget), XtWindow(raWidget), &root_return, &child_return, &root_x_return, &root_y_return, &win_x_return, &win_y_return, &mask_return); if (mask_return & Button1Mask && prevMode != SEEK_MODE) interactiveCountDec(); if (mask_return & Button2Mask && prevMode != SEEK_MODE) interactiveCountDec(); } break; case PAN_MODE_ACTIVE: { // Figure out the focal plane SbMatrix mx; mx = camera->orientation.getValue(); SbVec3f forward(-mx[2][0], -mx[2][1], -mx[2][2]); SbVec3f fp = camera->position.getValue() + forward * camera->focalDistance.getValue(); focalplane = SbPlane(forward, fp); // map mouse starting position onto the panning plane SbVec2s raSize = getGlxSize(); SbViewVolume cameraVolume; SbLine line; cameraVolume = camera->getViewVolume(raSize[0]/float(raSize[1])); cameraVolume.projectPointToLine( SbVec2f(locator[0]/float(raSize[0]), locator[1]/float(raSize[1])), line); focalplane.intersect(line, locator3D); } break; case ROLL_MODE_ACTIVE: redrawNeeded = TRUE; break; } if (redrawNeeded) scheduleRedraw(); } //////////////////////////////////////////////////////////////////////// // // Description: // switches to the specified viewer mode // // Use: private void SoXtPlaneViewer::updateCursor() // //////////////////////////////////////////////////////////////////////// { Widget w = getRenderAreaWidget(); Display *display = w ? XtDisplay(w) : NULL; Window window = w ? XtWindow(w) : 0; if (! window) return; if (! createdCursors) defineCursors(); // the viewer cursor are not enabled, then we don't set a new cursor. // Instead erase the old viewer cursor. if (! cursorEnabledFlag) { XUndefineCursor(display, window); return; } // ...else set the right cursor for the viewer mode.... switch(mode) { case PICK_MODE: case ROLL_MODE_ACTIVE: XUndefineCursor(display, window); break; case VIEW_MODE: case DOLLY_MODE_ACTIVE: XDefineCursor(display, window, dollyCursor); break; case PAN_MODE: case PAN_MODE_ACTIVE: XDefineCursor(display, window, transCursor); break; case SEEK_MODE: XDefineCursor(display, window, seekCursor); break; } } //////////////////////////////////////////////////////////////////////// // // Description: // draws viewer feedback during a render area redraw of the scene. // // Use: virtual protected void SoXtPlaneViewer::actualRedraw() // //////////////////////////////////////////////////////////////////////// { // have the base class draw the scene SoXtFullViewer::actualRedraw(); // now draw the viewer feedback if (isViewing() && mode == ROLL_MODE_ACTIVE) { setFeedbackOrthoProjection(getGlxSize()); drawViewerRollFeedback(getGlxSize()/2, locator); // now restore state restoreGLStateAfterFeedback(); } } //////////////////////////////////////////////////////////////////////// // // Description: // Call the base class and sets the correct cursor on the window // // Use: virtual protected void SoXtPlaneViewer::setSeekMode(SbBool flag) // //////////////////////////////////////////////////////////////////////// { if ( !isViewing() ) return; // call the base class SoXtFullViewer::setSeekMode(flag); mode = isSeekMode() ? SEEK_MODE : VIEW_MODE; updateCursor(); } //////////////////////////////////////////////////////////////////////// // // Description: // Redefine this routine to add some viewer specific stuff. // // Use: virtual protected void SoXtPlaneViewer::createPrefSheet() // //////////////////////////////////////////////////////////////////////// { // create the preference sheet shell and form widget Widget shell, form; createPrefSheetShellAndForm(shell, form); // create all of the parts Widget widgetList[20]; int num = 0; createDefaultPrefSheetParts(widgetList, num, form); layoutPartsAndMapPrefSheet(widgetList, num, form, shell); } //////////////////////////////////////////////////////////////////////// // // Description: // Redefine this to keep the same camera rotation when seeking // // Use: virtual protected void SoXtPlaneViewer::computeSeekFinalOrientation() // //////////////////////////////////////////////////////////////////////// { newCamOrientation = camera->orientation.getValue(); } //////////////////////////////////////////////////////////////////////// // // Description: // Brings the viewer help card (called by "?" push button) // // Use: virtual protected void SoXtPlaneViewer::openViewerHelpCard() // //////////////////////////////////////////////////////////////////////// { // tell the base class to open the file for us openHelpCard("SoXtPlaneViewer.help"); } //////////////////////////////////////////////////////////////////////// // // Description: // Translate the camera right/left (called by thumb wheel). // // Use: virtual protected void SoXtPlaneViewer::bottomWheelMotion(float newVal) // //////////////////////////////////////////////////////////////////////// { if (camera == NULL) return; // get camera right vector and translate camera by given amount SbMatrix mx; mx = camera->orientation.getValue(); SbVec3f rightVector(mx[0][0], mx[0][1], mx[0][2]); float dist = transXspeed * (bottomWheelVal - newVal); camera->position = camera->position.getValue() + dist * rightVector; bottomWheelVal = newVal; } //////////////////////////////////////////////////////////////////////// // // Description: // Translate the camera up/down (called by thumb wheel). // // Use: virtual protected void SoXtPlaneViewer::leftWheelMotion(float newVal) // //////////////////////////////////////////////////////////////////////// { if (camera == NULL) return; // get camera up vector and translate camera by given amount SbMatrix mx; mx = camera->orientation.getValue(); SbVec3f upVector(mx[1][0], mx[1][1], mx[1][2]); float dist = transYspeed * (leftWheelVal - newVal); camera->position = camera->position.getValue() + dist * upVector; leftWheelVal = newVal; } //////////////////////////////////////////////////////////////////////// // // Description: // Moves the camera closer/further away from the plane of interest // (perspective camera case), else change the camera height (orthographic // camera case). // // Use: virtual protected void SoXtPlaneViewer::rightWheelMotion(float newVal) // //////////////////////////////////////////////////////////////////////// { if (camera == NULL) return; if (camera->isOfType(SoOrthographicCamera::getClassTypeId())) { // change the ortho camera height SoOrthographicCamera *cam = (SoOrthographicCamera *) camera; cam->height = cam->height.getValue() * powf(2.0, newVal - rightWheelVal); } else { // shorter/grow the focal distance given the wheel rotation float focalDistance = camera->focalDistance.getValue();; float newFocalDist = focalDistance; newFocalDist *= powf(2.0, newVal - rightWheelVal); // finally reposition the camera SbMatrix mx; mx = camera->orientation.getValue(); SbVec3f forward(-mx[2][0], -mx[2][1], -mx[2][2]); camera->position = camera->position.getValue() + (focalDistance - newFocalDist) * forward; camera->focalDistance = newFocalDist; } rightWheelVal = newVal; } //////////////////////////////////////////////////////////////////////// // // Description: // This routine is used to define cursors (can only be called after // window has been realized). // // Use: private void SoXtPlaneViewer::defineCursors() // //////////////////////////////////////////////////////////////////////// { XColor foreground; Pixmap source; Display *display = getDisplay(); Drawable d = DefaultRootWindow(display); // set color foreground.red = 65535; foreground.green = foreground.blue = 0; // view plane translate cursor source = XCreateBitmapFromData(display, d, so_xt_flat_hand_bits, so_xt_flat_hand_width, so_xt_flat_hand_height); transCursor = XCreatePixmapCursor(display, source, source, &foreground, &foreground, so_xt_flat_hand_x_hot, so_xt_flat_hand_y_hot); XFreePixmap(display, source); // dolly cursor source = XCreateBitmapFromData(display, d, so_xt_pointing_hand_bits, so_xt_pointing_hand_width, so_xt_pointing_hand_height); dollyCursor = XCreatePixmapCursor(display, source, source, &foreground, &foreground, so_xt_pointing_hand_x_hot, so_xt_pointing_hand_y_hot); XFreePixmap(display, source); // seek cursor source = XCreateBitmapFromData(display, d, so_xt_target_bits, so_xt_target_width, so_xt_target_height); seekCursor = XCreatePixmapCursor(display, source, source, &foreground, &foreground, so_xt_target_x_hot, so_xt_target_y_hot); XFreePixmap(display, source); createdCursors = TRUE; } //////////////////////////////////////////////////////////////////////// // // Description: // Rolls the camera around it's forward direction given the new mouse // location. // // Use: private void SoXtPlaneViewer::rollCamera(const SbVec2s &newLocator) // //////////////////////////////////////////////////////////////////////// { if (camera == NULL) return; SbVec2s center = getGlxSize()/2; SbVec2s p1, p2; float angle; // get angle of rotation p1 = locator - center; p2 = newLocator - center; // checking needed so that NaN won't occur angle = (p2[0]==0 && p2[1]==0) ? 0 : atan2(p2[1], p2[0]); angle -= (p1[0]==0 && p1[1]==0) ? 0 : atan2(p1[1], p1[0]); // now find the rotation and rotate camera SbVec3f axis(0, 0, -1); SbRotation rot; rot.setValue(axis, angle); camera->orientation = rot * camera->orientation.getValue(); locator = newLocator; } //////////////////////////////////////////////////////////////////////// // // Description: // Moves the camera into the plane defined by the camera forward vector // and the focal point to follow the new mouse location. // // Use: private void SoXtPlaneViewer::translateCamera(const SbVec2f &newLocator) // //////////////////////////////////////////////////////////////////////// { if (camera == NULL) return; // map new mouse location into the camera focal plane SbViewVolume cameraVolume; SbLine line; SbVec3f newLocator3D; SbVec2s raSize = getGlxSize(); cameraVolume = camera->getViewVolume(raSize[0]/float(raSize[1])); cameraVolume.projectPointToLine(newLocator, line); focalplane.intersect(line, newLocator3D); // move the camera by the delta 3D position amount camera->position = camera->position.getValue() + (locator3D - newLocator3D); // You would think we would have to set locator3D to // newLocator3D here. But we don't, because moving the camera // essentially makes locator3D equal to newLocator3D in the // transformed space, and we will project the next newLocator3D in // this transformed space. } //////////////////////////////////////////////////////////////////////// // // Description: // Moves the camera forward/backward based on the new mouse potion. // (perspective camera), else change the camera height (orthographic // camera case). // // Use: private void SoXtPlaneViewer::dollyCamera(const SbVec2s &newLocator) // //////////////////////////////////////////////////////////////////////// { if (camera == NULL) return; // moving the mouse up/down will move the camera futher/closer. // moving the camera sideway will not move the camera at all float d = (newLocator[1] - locator[1]) / 40.0; if (camera->isOfType(SoOrthographicCamera::getClassTypeId())) { // change the ortho camera height SoOrthographicCamera *cam = (SoOrthographicCamera *) camera; cam->height = cam->height.getValue() * powf(2.0, d); } else { // shorter/grow the focal distance given the mouse move float focalDistance = camera->focalDistance.getValue();; float newFocalDist = focalDistance * powf(2.0, d); // finally reposition the camera SbMatrix mx; mx = camera->orientation.getValue(); SbVec3f forward(-mx[2][0], -mx[2][1], -mx[2][2]); camera->position = camera->position.getValue() + (focalDistance - newFocalDist) * forward; camera->focalDistance = newFocalDist; } locator = newLocator; } //////////////////////////////////////////////////////////////////////// // // Description: // Moves the camera to be aligned with the given plane // // Use: private void SoXtPlaneViewer::setPlane(const SbVec3f &newNormal, const SbVec3f &newRight) // //////////////////////////////////////////////////////////////////////// { if (camera == NULL) return; // get center of rotation SbRotation camRot = camera->orientation.getValue(); float radius = camera->focalDistance.getValue(); SbMatrix mx; mx = camRot; SbVec3f forward( -mx[2][0], -mx[2][1], -mx[2][2]); SbVec3f center = camera->position.getValue() + radius * forward; // rotate the camera to be aligned with the new plane normal SbRotation rot( -forward, newNormal); camRot = camRot * rot; // rotate the camera to be aligned with new right direction mx = camRot; SbVec3f right(mx[0][0], mx[0][1], mx[0][2]); rot.setValue(right, newRight); camRot = camRot * rot; camera->orientation = camRot; // reposition camera to look at pt of interest mx = camRot; forward.setValue( -mx[2][0], -mx[2][1], -mx[2][2]); camera->position = center - radius * forward; } //////////////////////////////////////////////////////////////////////// // // Description: // Called by the bottom and left thumbwheels to compute the // translation factors (how fast should we translate given a wheel // rotation). // // Use: private void SoXtPlaneViewer::computeTranslateValues() // //////////////////////////////////////////////////////////////////////// { if (camera == NULL) return; float height; if (camera->isOfType(SoPerspectiveCamera::getClassTypeId())) { float angle = ((SoPerspectiveCamera *)camera)->heightAngle.getValue(); float dist = camera->focalDistance.getValue(); height = dist * tanf(angle); } else if (camera->isOfType(SoOrthographicCamera::getClassTypeId())) height = ((SoOrthographicCamera *)camera)->height.getValue(); transYspeed = height / 2; transXspeed = transYspeed * camera->aspectRatio.getValue(); } // // redefine those generic virtual functions // const char * SoXtPlaneViewer::getDefaultWidgetName() const { return "SoXtPlaneViewer"; } const char * SoXtPlaneViewer::getDefaultTitle() const { return rl.planeViewer; } const char * SoXtPlaneViewer::getDefaultIconTitle() const { return rl.planeViewer; } void SoXtPlaneViewer::bottomWheelStart() { interactiveCountInc(); computeTranslateValues(); } void SoXtPlaneViewer::leftWheelStart() { interactiveCountInc(); computeTranslateValues(); } // //////////////////////////////////////////////////////////////////////// // static callbacks stubs //////////////////////////////////////////////////////////////////////// // // // viewer push button callbacks // void SoXtPlaneViewer::pushButtonCB(Widget w, int id, void *) { SoXtPlaneViewer *v; XtVaGetValues(w, XmNuserData, &v, NULL); switch (id) { case X_PUSH: v->setPlane( SbVec3f(1, 0, 0), SbVec3f(0, 0, -1) ); break; case Y_PUSH: v->setPlane( SbVec3f(0, 1, 0), SbVec3f(1, 0, 0) ); break; case Z_PUSH: v->setPlane( SbVec3f(0, 0, 1), SbVec3f(1, 0, 0) ); break; case CAM_PUSH: v->toggleCameraType(); break; } }
lgpl-2.1
cacheonix/cacheonix-core
3rdparty/hibernate-3.2/test/org/hibernate/test/collection/original/User.java
1351
//$Id: User.java 7628 2005-07-24 06:55:01Z oneovthafew $ package org.hibernate.test.collection.original; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Gavin King */ public class User { private String userName; private List permissions = new ArrayList(); private List emailAddresses = new ArrayList(); private Map sessionData = new HashMap(); private Set sessionAttributeNames = new HashSet(); User() {} public User(String name) { userName = name; } public List getPermissions() { return permissions; } public void setPermissions(List permissions) { this.permissions = permissions; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public List getEmailAddresses() { return emailAddresses; } public void setEmailAddresses(List emailAddresses) { this.emailAddresses = emailAddresses; } public Map getSessionData() { return sessionData; } public void setSessionData(Map sessionData) { this.sessionData = sessionData; } public Set getSessionAttributeNames() { return sessionAttributeNames; } public void setSessionAttributeNames(Set sessionAttributeNames) { this.sessionAttributeNames = sessionAttributeNames; } }
lgpl-2.1
lilobase/ICONTO-EcoleNumerique
project/modules/public/stable/standard/copixtest/templates/tests.launch.php
4735
<?php _tag ('mootools', array ('plugin'=>'progressbar')); ?> <div id="progessDiv"> <div id="statusProgressBar" style="width: 300px;text-align: center">&nbsp;</div> <div id="progressBar" style="border: 1px solid #000; width: 300px;"></div> <div id="CopixAjaxResults"></div> </div> <script defer language="Javascript"> var linkList; var position = 0; var progressBar1; function doIndex (List) { var i = 0; linkList = List; progressBar1 = new ProgressBar ('progressBar', {steps: linkList.length, length: 300, statusBar: 'statusProgressBar'}); makeCall (); } function sleep(millis) { var notifier = new EventNotifier(); setTimeout (notifier, millis); notifier.wait(); } function makeCall () { if (position < linkList.length){ new Ajax ('<?php echo _url (); ?>test.php?xml=1&tests[]='+linkList[position], {onComplete: function (e){ $('CopixAjaxResults').setHTML (linkList[position]); if (! evalResults (this.response['xml'])){ markUnknownResponse (linkList[position], this.response['text']); } progressBar1.step (); makeCall (); }}).request (); }else{ $('progessDiv').setHTML (''); } position = position+1; } function markUnknownResponse (tested, text) { addLineToResults (tested, 0, 0, 100, 0, new Array (), 'ffff00'); } function getFirstTagContent (list, tagName) { var element = list.getElementsByTagName (tagName); if (element[0]){ return element[0].textContent; } return null; } function addTextLineToResults (name, text1, text2) { var tableTestResults = document.getElementById ("TableTestsTextResults"); newRow = tableTestResults.insertRow (-1); newCell = newRow.insertCell (0); newCell.innerHTML = name; newRow = tableTestResults.insertRow (-1); newCell = newRow.insertCell (0); newCell.innerHTML = text1; newRow = tableTestResults.insertRow (-1); newCell = newRow.insertCell (0); newCell.innerHTML = text2; } function addLineToResults (name, error, failure, incomplete, success, color) { var tableTestResults = document.getElementById ("TableTestsResults"); newRow = tableTestResults.insertRow (-1); newCell = newRow.insertCell (0); newCell.innerHTML = name; newCell = newRow.insertCell (1); newCell.innerHTML = error; newCell = newRow.insertCell (2); newCell.innerHTML = incomplete; newCell = newRow.insertCell (3); newCell.innerHTML = failure; newCell = newRow.insertCell (4); newCell.innerHTML = success; styleRow = new Fx.Style(newRow, 'background-color', {duration: 1000}); styleRow.start ('ffffff', color); } function evalResults (XMLResponse) { if (XMLResponse){ var color = '00ff00'; var name = getFirstTagContent (XMLResponse, 'name'); var error = getFirstTagContent (XMLResponse, 'error'); var failure = getFirstTagContent (XMLResponse, 'failure'); var incomplete = getFirstTagContent (XMLResponse, 'incomplete'); var success = getFirstTagContent (XMLResponse, 'success'); if (error != '0' || failure != '0'){ color = 'ff0000'; }else if (incomplete != '0'){ color = 'ffff00'; } addLineToResults (name, error, failure, incomplete, success, color); addErrors (XMLResponse.getElementsByTagName ('errors'), 'Errors'); addErrors (XMLResponse.getElementsByTagName ('failures'), 'Failures'); addErrors (XMLResponse.getElementsByTagName ('incompletes'), 'Incompletes'); addErrors (XMLResponse.getElementsByTagName ('skipped'), 'Skipped'); return true; } return false; } function addErrors (ErrorList, ErrorType) { var i = 0; for (i=0; i<ErrorList.length; i++){ addTextLineToResults (ErrorType, getFirstTagContent (ErrorList[i], 'name'), getFirstTagContent (ErrorList[i], 'description')); } } <?php $array = array (); foreach ($ppo->arTests as $moduleName=>$modulesTest){ if (count ($modulesTest)){ foreach ($modulesTest as $test){ $array[] = '"'.$test.'"'; } } } echo 'doIndex (new Array ('.implode (",", $array).'));'; ?> </script> <table class="CopixTable" id="TableTestsTextResults"> <thead> <tr> <th>Problèmes</th> </tr> </thead> <tbody> <tr> </tr> </tbody> </table> <br /> <table class="CopixTable" id="TableTestsResults"> <thead> <tr> <th>Nom</th> <th width="50">Erreur</th> <th width="50">Incomplet</th> <th width="50">Echec</th> <th width="50">Succès</th> </tr> </thead> <tbody> <tr> </tr> </tbody> </table>
lgpl-2.1
ailncode/gorgw
entity/bucket.go
366
/*------------------------ name bucket describe bucket entity author ailn(z.ailn@wmntec.com) create 2016-05-07 version 1.0 ------------------------*/ package entity type Bucket struct { Guid string //ceph namespace guid Name string //user bucket name Owner string //bucket owner guid IsPublic bool CreateTime int64 }
lgpl-2.1
FedoraScientific/salome-paravis
test/VisuPrs/Animation/A8.py
2952
# Copyright (C) 2010-2014 CEA/DEN, EDF R&D # # This library 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. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # #This case corresponds to: /visu/animation/A8 case #%Create animation for Cut Lines for 'pression' field of the the given MED file and dumps picture files in TIFF format % import sys import os from paravistest import * from presentations import * from pvsimple import * import pvserver as paravis #import file myParavis = paravis.myParavis # Directory for saving snapshots picturedir = get_picture_dir("Animation/A8") theFileName = datadir + "TimeStamps.med" print " --------------------------------- " print "file ", theFileName print " --------------------------------- " OpenDataFile(theFileName) aProxy = GetActiveSource() if aProxy is None: raise RuntimeError, "Error: can't import file." else: print "OK" print "Creating a Viewer.........................", aView = GetRenderView() reset_view(aView) Render(aView) if aView is None : print "Error" else : print "OK" # Cut Lines creation prs= CutLinesOnField(aProxy,EntityType.CELL,'pression' , 2) prs.Visibility=1 aView.ResetCamera() print "Creating an Animation.....................", my_format = "tiff" print "Current format to save snapshots: ",my_format # Add path separator to the end of picture path if necessery if not picturedir.endswith(os.sep): picturedir += os.sep # Select only the current field: aProxy.AllArrays = [] aProxy.UpdatePipeline() aProxy.AllArrays = ['TS0/dom/ComSup0/pression@@][@@P0'] aProxy.UpdatePipeline() # Animation creation and saving into set of files into picturedir scene = AnimateReader(aProxy,aView,picturedir+"A8_dom."+my_format) nb_frames = len(scene.TimeKeeper.TimestepValues) pics = os.listdir(picturedir) if len(pics) != nb_frames: print "FAILED!!! Number of made pictures is equal to ", len(pics), " instead of ", nb_frames for pic in pics: os.remove(picturedir+pic) # Prepare animation performance scene.PlayMode = 1 # set RealTime mode for animation performance # set period scene.Duration = 30 # correspond to set the speed of animation in VISU scene.GoToFirst() print "Animation.................................", scene.Play() scene.GoToFirst()
lgpl-2.1
bisailb/phpwebtk
testscripts/sessiontest.php
847
<?php $start = microtime ( 1 ); // Includes and evaluates named constants and third party dependencies require_once ('configuration/constants.php'); // Registers the given function as an __autoload() implementation spl_autoload_register ( function ($class) { // Includes and evaluates class file dependencies require_once CLASS_PATH . strtolower ( $class ) . '.class.php'; } ); ob_start (); $Session = new Session (); $Session->OpenSession (); print ('Cookie Name: ' . $Session->GetName ()) ; print ('<br>Cookie Content: ' . $Session->GetId ()) ; // Comment out the following line to view the session cookie in your web browser // and at the savePath location defined in the phpwebtk.xml configuration file. $Session->CloseSession (); ob_end_flush (); $stop = microtime ( 1 ); $time = $stop - $start; print ('<br />Time Elapsed: ' . $time) ; ?>
lgpl-2.1
genman/rhq-plugins
hive/src/main/java/com/apple/iad/rhq/hadoop/hive/HiveTableDiscovery.java
2364
package com.apple.iad.rhq.hadoop.hive; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; /** * Discovers a list of Hadoop Hive tables matching a query and regular expression. * Uses (MySQL) JDBC to access the metadata, not the Hive JDBC driver. */ public class HiveTableDiscovery implements ResourceDiscoveryComponent { @Override public Set<DiscoveredResourceDetails> discoverResources( ResourceDiscoveryContext context) throws InvalidPluginConfigurationException, Exception { Set<DiscoveredResourceDetails> details = new HashSet<DiscoveredResourceDetails>(); HiveServerComponent server = (HiveServerComponent) context.getParentResourceComponent(); Configuration conf = context.getParentResourceContext().getPluginConfiguration(); String sql = conf.getSimpleValue("table.query", "select distinct t.tbl_name from TBLS"); Pattern pattern = Pattern.compile(conf.getSimpleValue("table.match", ".*")); Connection connection = server.getConnection(); PreparedStatement ps = connection.prepareStatement(sql); try { ResultSet rs = ps.executeQuery(); while (rs.next()) { String name = rs.getString(1); if (!pattern.matcher(name).find()) continue; DiscoveredResourceDetails detail = new DiscoveredResourceDetails( context.getResourceType(), name, // database key name, // UI name null, // Version "Hive Table " + name, context.getDefaultPluginConfiguration(), null); // process info details.add(detail); } } finally { ps.close(); } return details; } }
lgpl-2.1
Jajcus/pyxmpp2
pyxmpp2/test/streamsasl.py
9755
#!/usr/bin/python # -*- coding: UTF-8 -*- # pylint: disable=C0111 import unittest import re import base64 import binascii import os import pyxmpp2.etree if "PYXMPP2_ETREE" not in os.environ: # one of tests fails when xml.etree.ElementTree is used try: from xml.etree import cElementTree pyxmpp2.etree.ElementTree = cElementTree except ImportError: pass from pyxmpp2.etree import ElementTree from pyxmpp2.streambase import StreamBase from pyxmpp2.streamsasl import StreamSASLHandler from pyxmpp2.streamevents import * # pylint: disable=W0614,W0401 from pyxmpp2.exceptions import SASLAuthenticationFailed from pyxmpp2.settings import XMPPSettings from pyxmpp2.test._util import EventRecorder from pyxmpp2.test._util import InitiatorSelectTestCase from pyxmpp2.test._util import ReceiverSelectTestCase C2S_SERVER_STREAM_HEAD = (b'<stream:stream version="1.0" from="127.0.0.1"' b' xmlns:stream="http://etherx.jabber.org/streams"' b' xmlns="jabber:client">') C2S_CLIENT_STREAM_HEAD = (b'<stream:stream version="1.0" to="127.0.0.1"' b' xmlns:stream="http://etherx.jabber.org/streams"' b' xmlns="jabber:client">') AUTH_FEATURES = b"""<stream:features> <mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'> <mechanism>PLAIN</mechanism> </mechanisms> </stream:features>""" BIND_FEATURES = b"""<stream:features> <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/> </stream:features>""" PLAIN_AUTH = ("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'" " mechanism='PLAIN'>{0}</auth>") STREAM_TAIL = b'</stream:stream>' PARSE_ERROR_RESPONSE = (b'<stream:error><xml-not-well-formed' b' xmlns="urn:ietf:params:xml:ns:xmpp-streams"/>' b'</stream:error></stream:stream>') TIMEOUT = 1.0 # seconds class TestInitiator(InitiatorSelectTestCase): def test_auth(self): handler = EventRecorder() settings = XMPPSettings({ u"username": u"user", u"password": u"secret", }) self.stream = StreamBase(u"jabber:client", None, [StreamSASLHandler(settings), handler], settings) self.start_transport([handler]) self.stream.initiate(self.transport) self.connect_transport() self.server.write(C2S_SERVER_STREAM_HEAD) self.server.write(AUTH_FEATURES) xml = self.wait(expect = re.compile(br".*(<auth.*</auth>)")) self.assertIsNotNone(xml) element = ElementTree.XML(xml) self.assertEqual(element.tag, "{urn:ietf:params:xml:ns:xmpp-sasl}auth") mech = element.get("mechanism") self.assertEqual(mech, "PLAIN") data = binascii.a2b_base64(element.text.encode("utf-8")) self.assertEqual(data, b"\000user\000secret") self.server.rdata = b"" self.server.write( b"<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>") stream_start = self.wait(expect = re.compile( br"(<stream:stream[^>]*>)")) self.assertIsNotNone(stream_start) self.assertTrue(self.stream.authenticated) self.server.write(C2S_SERVER_STREAM_HEAD) self.server.write(BIND_FEATURES) self.server.write(b"</stream:stream>") self.server.disconnect() self.wait() event_classes = [e.__class__ for e in handler.events_received] self.assertEqual(event_classes, [ConnectingEvent, ConnectedEvent, StreamConnectedEvent, GotFeaturesEvent, AuthenticatedEvent, StreamRestartedEvent, GotFeaturesEvent, DisconnectedEvent]) def test_auth_fail(self): handler = EventRecorder() settings = XMPPSettings({ u"username": u"user", u"password": u"bad", }) self.stream = StreamBase(u"jabber:client", None, [StreamSASLHandler(settings), handler], settings) self.start_transport([handler]) self.stream.initiate(self.transport) self.connect_transport() self.server.write(C2S_SERVER_STREAM_HEAD) self.server.write(AUTH_FEATURES) xml = self.wait(expect = re.compile(br".*(<auth.*</auth>)")) self.assertIsNotNone(xml) element = ElementTree.XML(xml) self.assertEqual(element.tag, "{urn:ietf:params:xml:ns:xmpp-sasl}auth") mech = element.get("mechanism") self.assertEqual(mech, "PLAIN") data = binascii.a2b_base64(element.text.encode("utf-8")) self.assertNotEqual(data, b"\000user\000secret") self.server.write(b"""<failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'> <not-authorized/></failure>""") with self.assertRaises(SASLAuthenticationFailed): self.wait() self.assertFalse(self.stream.authenticated) self.server.disconnect() self.wait() event_classes = [e.__class__ for e in handler.events_received] self.assertEqual(event_classes, [ConnectingEvent, ConnectedEvent, StreamConnectedEvent, GotFeaturesEvent, DisconnectedEvent]) class TestReceiver(ReceiverSelectTestCase): def test_auth(self): handler = EventRecorder() self.start_transport([handler]) settings = XMPPSettings({ u"user_passwords": { u"user": u"secret", }, u"sasl_mechanisms": ["SCRAM-SHA-1", "PLAIN"], }) self.stream = StreamBase(u"jabber:client", None, [StreamSASLHandler(settings), handler], settings) self.stream.receive(self.transport, self.addr[0]) self.client.write(C2S_CLIENT_STREAM_HEAD) xml = self.wait(expect = re.compile( br".*<stream:features>(.*)</stream:features>")) self.assertIsNotNone(xml) element = ElementTree.XML(xml) self.assertEqual(element.tag, "{urn:ietf:params:xml:ns:xmpp-sasl}mechanisms") self.assertEqual(element[0].tag, "{urn:ietf:params:xml:ns:xmpp-sasl}mechanism") self.assertEqual(element[0].text, "SCRAM-SHA-1") self.assertEqual(element[1].tag, "{urn:ietf:params:xml:ns:xmpp-sasl}mechanism") self.assertEqual(element[1].text, "PLAIN") response = base64.standard_b64encode(b"\000user\000secret") self.client.write(PLAIN_AUTH.format(response.decode("utf-8")) .encode("utf-8")) xml = self.wait(expect = re.compile(br".*(<success.*>)")) self.assertIsNotNone(xml) self.client.write(C2S_CLIENT_STREAM_HEAD) xml = self.wait(expect = re.compile(br".*(<stream:stream.*>)")) self.assertIsNotNone(xml) self.assertTrue(self.stream.peer_authenticated) self.client.write(b"</stream:stream>") self.client.disconnect() self.wait() event_classes = [e.__class__ for e in handler.events_received] self.assertEqual(event_classes, [ StreamConnectedEvent, AuthenticatedEvent, StreamRestartedEvent, DisconnectedEvent]) def test_auth_fail(self): handler = EventRecorder() self.start_transport([handler]) settings = XMPPSettings({ u"user_passwords": { u"user": u"secret", }, u"sasl_mechanisms": ["SCRAM-SHA-1", "PLAIN"], }) self.stream = StreamBase(u"jabber:client", None, [StreamSASLHandler(settings), handler], settings) self.stream.receive(self.transport, self.addr[0]) self.client.write(C2S_CLIENT_STREAM_HEAD) xml = self.wait(expect = re.compile( br".*<stream:features>(.*)</stream:features>")) self.assertIsNotNone(xml) element = ElementTree.XML(xml) self.assertEqual(element.tag, "{urn:ietf:params:xml:ns:xmpp-sasl}mechanisms") self.assertEqual(element[0].tag, "{urn:ietf:params:xml:ns:xmpp-sasl}mechanism") self.assertEqual(element[0].text, "SCRAM-SHA-1") self.assertEqual(element[1].tag, "{urn:ietf:params:xml:ns:xmpp-sasl}mechanism") self.assertEqual(element[1].text, "PLAIN") response = base64.standard_b64encode(b"\000user\000bad") self.client.write(PLAIN_AUTH.format(response.decode("us-ascii")) .encode("utf-8")) with self.assertRaises(SASLAuthenticationFailed): self.wait() self.client.write(b"</stream:stream>") self.client.disconnect() self.wait() event_classes = [e.__class__ for e in handler.events_received] self.assertEqual(event_classes, [StreamConnectedEvent, DisconnectedEvent]) # pylint: disable=W0611 from pyxmpp2.test._support import load_tests, setup_logging def setUpModule(): setup_logging() if __name__ == "__main__": unittest.main()
lgpl-2.1
thiblahute/hotdoc
hotdoc/extensions/gi/gtkdoc_links.py
2900
import os from lxml import etree from hotdoc.extensions.gi.utils import DATADIR from hotdoc.utils.loggable import info GTKDOC_HREFS = {} def parse_devhelp_index(dir_): path = os.path.join(dir_, os.path.basename(dir_) + '.devhelp2') if not os.path.exists(path): return False dh_root = etree.parse(path).getroot() online = dh_root.attrib.get('online') name = dh_root.attrib.get('name') author = dh_root.attrib.get('author') if not online: if not name: return False online = 'https://developer.gnome.org/%s/unstable/' % name keywords = dh_root.findall('.//{http://www.devhelp.net/book}keyword') for kw in keywords: name = kw.attrib["name"] type_ = kw.attrib['type'] link = kw.attrib['link'] if type_ in ['macro', 'function']: name = name.rstrip(u' ()') elif type_ in ['struct', 'enum', 'union']: split = name.split(' ', 1) if len(split) == 2: name = split[1] else: name = split[0] elif type_ in ['signal', 'property']: anchor = link.split('#', 1)[1] if author == 'hotdoc': name = anchor else: split = anchor.split('-', 1) if type_ == 'signal': name = '%s::%s' % (split[0], split[1].lstrip('-')) else: name = '%s:%s' % (split[0], split[1].lstrip('-')) GTKDOC_HREFS[name] = online + link return True def parse_sgml_index(dir_): remote_prefix = "" n_links = 0 path = os.path.join(dir_, "index.sgml") with open(path, 'r') as f: for l in f: if l.startswith("<ONLINE"): remote_prefix = l.split('"')[1] elif not remote_prefix: break elif l.startswith("<ANCHOR"): split_line = l.split('"') filename = split_line[3].split('/', 1)[-1] title = split_line[1].replace('-', '_') if title.endswith(":CAPS"): title = title [:-5] if remote_prefix: href = '%s/%s' % (remote_prefix, filename) else: href = filename GTKDOC_HREFS[title] = href n_links += 1 def gather_gtk_doc_links (): gtkdoc_dir = os.path.join(DATADIR, "gtk-doc", "html") if not os.path.exists(gtkdoc_dir): info("no gtk doc to gather links from in %s" % gtkdoc_dir) return for node in os.listdir(gtkdoc_dir): dir_ = os.path.join(gtkdoc_dir, node) if os.path.isdir(dir_): if not parse_devhelp_index(dir_): try: parse_sgml_index(dir_) except IOError: pass gather_gtk_doc_links()
lgpl-2.1
amccarthy/qtlocation
src/plugins/position/maemo/dbuscomm_maemo.cpp
8648
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "dbuscomm_maemo_p.h" #include <iostream> using namespace std; QT_BEGIN_NAMESPACE const QString DBusComm::positioningdService = QString("com.nokia.positioningd.client"); const QString DBusComm::positioningdPath = QString("/com/nokia/positioningd/client"); const QString DBusComm::positioningdInterface = QString("com.nokia.positioningd.client"); DBusComm::DBusComm(QObject *parent) : QObject(parent), minimumUpdateInterval(1000), availablePositioningMethods(QGeoPositionInfoSource::AllPositioningMethods) { } int DBusComm::init() { if (!QDBusConnection::sessionBus().isConnected()) { cerr << "Cannot connect to the D-BUS session bus.\n"; return -1; } // Application auto-start by dbus may take a while, so try // connecting a few times. int cnt = 10; positioningdProxy = new QDBusInterface(positioningdService, positioningdPath, positioningdInterface, QDBusConnection::sessionBus()); while (cnt && (positioningdProxy->isValid() == false)) { // cout << "Connecting to positioning daemon..." << endl; usleep(200000); positioningdProxy = new QDBusInterface(positioningdService, positioningdPath, positioningdInterface, QDBusConnection::sessionBus()); cnt--; } if (positioningdProxy->isValid() == false) { cerr << "DBus connection to positioning daemon failed.\n"; return -1; } serviceDisconnectWatcher = new QDBusServiceWatcher (positioningdService, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForUnregistration, this); QObject::connect(serviceDisconnectWatcher, SIGNAL(serviceUnregistered ( const QString &)), this,SLOT(onServiceDisconnect(const QString &))); serviceConnectWatcher = new QDBusServiceWatcher (positioningdService, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForRegistration, this); QObject::connect(serviceConnectWatcher, SIGNAL(serviceRegistered ( const QString &)), this,SLOT(onServiceConnect(const QString &))); if (createUniqueName() == false) { // set myService, myPath return -1; } dbusServer = new DBusServer(&serverObj, this); QDBusConnection::sessionBus().registerObject(myPath, &serverObj); if (!QDBusConnection::sessionBus().registerService(myService)) { cerr << qPrintable(QDBusConnection::sessionBus().lastError().message()) << endl; return -1; } sendDBusRegister(); return 0; } void DBusComm::onServiceDisconnect(const QString &name) { Q_UNUSED(name); emit serviceDisconnected(); } void DBusComm::onServiceConnect(const QString &name) { Q_UNUSED(name); sendDBusRegister(); emit serviceConnected(); } void DBusComm::receivePositionUpdate(const QGeoPositionInfo &update) { emit receivedPositionUpdate(update); } void DBusComm::receiveSatellitesInView(const QList<QGeoSatelliteInfo> &info) { emit receivedSatellitesInView(info); } void DBusComm::receiveSatellitesInUse(const QList<QGeoSatelliteInfo> &info) { emit receivedSatellitesInUse(info); } void DBusComm::receiveSettings(QGeoPositionInfoSource::PositioningMethod methods, qint32 interval) { availablePositioningMethods = methods; minimumUpdateInterval = interval; } bool DBusComm::sendDBusRegister() { QDBusMessage reply = positioningdProxy->call("registerListener", myService.toLatin1().constData(), myPath.toLatin1().constData()); if (reply.type() == QDBusMessage::ReplyMessage) { QList<QVariant> values = reply.arguments(); clientId = values.takeFirst().toInt(); quint32 m = values.takeFirst().toUInt(); availablePositioningMethods = (QGeoPositionInfoSource::PositioningMethod) m; minimumUpdateInterval = values.takeFirst().toUInt(); } else { cerr << endl << "DBus error:\n"; cerr << reply.errorName().toLatin1().constData() << endl; cerr << reply.errorMessage().toLatin1().constData() << endl; return false; } return true; } QGeoPositionInfoSource::PositioningMethods DBusComm::availableMethods() const { return availablePositioningMethods; } int DBusComm::minimumInterval() const { return minimumUpdateInterval; } bool DBusComm::sendConfigRequest(Command command, QGeoPositionInfoSource::PositioningMethods method, int interval) const { QDBusReply<int> reply; reply = positioningdProxy->call("configSession", clientId, command, int(method), interval); //cout << "sessionConfigRequest cmd: cmd:" << command << " method: "; //cout << method << " interval: " << interval << "\n"; if (reply.isValid()) { int n = reply.value(); } else { cerr << endl << "DBus error:\n"; cerr << reply.error().name().toLatin1().constData() << endl; cerr << reply.error().message().toLatin1().constData() << endl; return false; } return true; } QGeoPositionInfo &DBusComm::requestLastKnownPosition(bool satelliteMethodOnly) { QDBusReply<QByteArray> reply; reply = positioningdProxy->call("latestPosition", satelliteMethodOnly); static QGeoPositionInfo update; if (reply.isValid()) { // cout << "requestLastKnownPosition(): received update\n"; QByteArray message = reply.value(); QDataStream stream(message); stream >> update; } else { cerr << endl << "DBus error:\n"; cerr << reply.error().name().toLatin1().constData() << endl; cerr << reply.error().message().toLatin1().constData() << endl; update = QGeoPositionInfo(); } return update; } bool DBusComm::createUniqueName() { QFile uuidfile("/proc/sys/kernel/random/uuid"); if (!uuidfile.open(QIODevice::ReadOnly)) { cerr << "UUID file failed."; return false; } QTextStream in(&uuidfile); QString uuid = 'I' + in.readLine(); uuid.replace('-', 'I'); myService = "com.nokia.qlocation." + uuid; myPath = "/com/nokia/qlocation/" + uuid; return true; } #include "moc_dbuscomm_maemo_p.cpp" QT_END_NAMESPACE
lgpl-2.1
geotools/geotools
modules/plugin/geopkg/src/main/java/org/geotools/geopkg/wps/GeoPackageProcessRequest.java
11098
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2010, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.geopkg.wps; import java.awt.Color; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.xml.namespace.QName; import org.geotools.geopkg.TileMatrix; import org.locationtech.jts.geom.Envelope; import org.opengis.filter.Filter; import org.opengis.filter.sort.SortBy; /** * GeoPackage Process Request. Object representation of the XML submitted to the GeoPackage process. * * @author Niels Charlier */ public class GeoPackageProcessRequest { protected String name; public enum LayerType { FEATURES, TILES }; public abstract static class Layer { protected String name = null; protected String identifier = null; protected String description = null; protected URI srs = null; protected Envelope bbox = null; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public URI getSrs() { return srs; } public void setSrs(URI srs) { this.srs = srs; } public Envelope getBbox() { return bbox; } public void setBbox(Envelope bbox) { this.bbox = bbox; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public abstract LayerType getType(); } public static class Overview implements Comparable<Overview> { String name; double distance; double scaleDenominator; Filter filter; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } public Filter getFilter() { return filter; } public void setFilter(Filter filter) { this.filter = filter; } @Override public int compareTo(Overview o) { // compare both in case the distance and scale denominators are set int diff = (int) Math.signum(distance - o.distance); if (diff != 0) return diff; return (int) Math.signum(scaleDenominator - o.scaleDenominator); } public double getScaleDenominator() { return scaleDenominator; } public void setScaleDenominator(double scaleDenominator) { this.scaleDenominator = scaleDenominator; } } public static class FeaturesLayer extends Layer { protected QName featureType = null; protected Set<QName> propertyNames = null; protected Filter filter = null; protected SortBy[] sort = null; protected boolean indexed = false; protected boolean styles = true; protected boolean metadata = true; protected List<Overview> overviews; @Override public LayerType getType() { return LayerType.FEATURES; } public QName getFeatureType() { return featureType; } public void setFeatureType(QName featureType) { this.featureType = featureType; } public Set<QName> getPropertyNames() { return propertyNames; } public void setPropertyNames(Set<QName> propertyNames) { this.propertyNames = propertyNames; } public Filter getFilter() { return filter; } public void setFilter(Filter filter) { this.filter = filter; } public SortBy[] getSort() { return sort; } public void setSort(SortBy[] sort) { this.sort = sort; } public boolean isIndexed() { return indexed; } public void setIndexed(boolean indexed) { this.indexed = indexed; } public boolean isStyles() { return styles; } public void setStyles(boolean styles) { this.styles = styles; } public boolean isMetadata() { return metadata; } public void setMetadata(boolean metadata) { this.metadata = metadata; } public List<Overview> getOverviews() { return overviews; } public void setOverviews(List<Overview> overviews) { this.overviews = overviews; } } public static class Parameter { String name; String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } public static class TilesLayer extends Layer { public static class TilesCoverage { protected Integer minZoom = null; protected Integer maxZoom = null; protected Integer minColumn = null; protected Integer maxColumn = null; protected Integer minRow = null; protected Integer maxRow = null; public Integer getMinZoom() { return minZoom; } public void setMinZoom(Integer minZoom) { this.minZoom = minZoom; } public Integer getMaxZoom() { return maxZoom; } public void setMaxZoom(Integer maxZoom) { this.maxZoom = maxZoom; } public Integer getMinColumn() { return minColumn; } public void setMinColumn(Integer minColumn) { this.minColumn = minColumn; } public Integer getMaxColumn() { return maxColumn; } public void setMaxColumn(Integer maxColumn) { this.maxColumn = maxColumn; } public Integer getMinRow() { return minRow; } public void setMinRow(Integer minRow) { this.minRow = minRow; } public Integer getMaxRow() { return maxRow; } public void setMaxRow(Integer maxRow) { this.maxRow = maxRow; } } protected List<QName> layers = null; protected String format = null; protected Color bgColor = null; protected boolean transparent = false; protected List<String> styles = null; protected URI sld = null; protected String sldBody = null; protected String gridSetName = null; protected List<TileMatrix> grids = null; protected TilesCoverage coverage = null; protected List<Parameter> parameters; @Override public LayerType getType() { return LayerType.TILES; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public Color getBgColor() { return bgColor; } public void setBgColor(Color bgColor) { this.bgColor = bgColor; } public boolean isTransparent() { return transparent; } public void setTransparent(boolean transparent) { this.transparent = transparent; } public List<String> getStyles() { return styles; } public void setStyles(List<String> styles) { this.styles = styles; } public URI getSld() { return sld; } public void setSld(URI sld) { this.sld = sld; } public String getSldBody() { return sldBody; } public void setSldBody(String sldBody) { this.sldBody = sldBody; } public String getGridSetName() { return gridSetName; } public void setGridSetName(String gridSetName) { this.gridSetName = gridSetName; } public List<TileMatrix> getGrids() { return grids; } public void setGrids(List<TileMatrix> grids) { this.grids = grids; } public TilesCoverage getCoverage() { return coverage; } public void setCoverage(TilesCoverage coverage) { this.coverage = coverage; } public List<QName> getLayers() { return layers; } public void setLayers(List<QName> layers) { this.layers = layers; } public List<Parameter> getParameters() { return parameters; } public void setParameters(List<Parameter> parameters) { this.parameters = parameters; } } protected List<Layer> layers = new ArrayList<>(); protected URL path = null; protected boolean remove = true; protected boolean context = true; public Boolean getRemove() { return remove; } public void setRemove(Boolean remove) { this.remove = remove; } public void addLayer(Layer layer) { layers.add(layer); } public Layer getLayer(int i) { return layers.get(i); } public int getLayerCount() { return layers.size(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public URL getPath() { return path; } public void setPath(URL path) { this.path = path; } public boolean isContext() { return context; } public void setContext(boolean context) { this.context = context; } }
lgpl-2.1
deegree/deegree3
deegree-core/deegree-core-base/src/main/java/org/deegree/gml/utils/XMLTransformer.java
11513
//$HeadURL$ /*---------------- FILE HEADER ------------------------------------------ This file is part of deegree. Copyright (C) 2001-2009 by: Department of Geography, University of Bonn http://www.giub.uni-bonn.de/deegree/ lat/lon GmbH http://www.lat-lon.de This library 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. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: Andreas Poth lat/lon GmbH Aennchenstr. 19 53177 Bonn Germany E-Mail: poth@lat-lon.de Prof. Dr. Klaus Greve Department of Geography University of Bonn Meckenheimer Allee 166 53115 Bonn Germany E-Mail: greve@giub.uni-bonn.de ---------------------------------------------------------------------------*/ package org.deegree.gml.utils; import static javax.xml.stream.XMLStreamConstants.CDATA; import static javax.xml.stream.XMLStreamConstants.CHARACTERS; import static javax.xml.stream.XMLStreamConstants.COMMENT; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; import static org.deegree.gml.GMLInputFactory.createGMLStreamReader; import static org.deegree.gml.GMLOutputFactory.createGMLStreamWriter; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.deegree.commons.xml.XMLParsingException; import org.deegree.commons.xml.stax.XMLStreamUtils; import org.deegree.cs.coordinatesystems.ICRS; import org.deegree.cs.exceptions.OutsideCRSDomainException; import org.deegree.cs.exceptions.TransformationException; import org.deegree.cs.exceptions.UnknownCRSException; import org.deegree.cs.transformations.Transformation; import org.deegree.geometry.Geometry; import org.deegree.geometry.GeometryTransformer; import org.deegree.gml.GMLStreamReader; import org.deegree.gml.GMLStreamWriter; import org.deegree.gml.GMLVersion; /** * The <code>XMLTransformer</code> transforms any xml documents containing gml geometries. Only the geometries will be * transformed all other data (including comments and cdata) will be copied. * * @author <a href="mailto:bezema@lat-lon.de">Rutger Bezema</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class XMLTransformer extends GeometryTransformer { /** * @param targetCRS * @throws IllegalArgumentException * @throws UnknownCRSException */ public XMLTransformer( ICRS targetCRS ) throws IllegalArgumentException { super( targetCRS ); } /** * @param targetCRS * @throws IllegalArgumentException * @throws UnknownCRSException */ public XMLTransformer( String targetCRS ) throws IllegalArgumentException, UnknownCRSException { super( targetCRS ); } /** * @param transformation * @throws IllegalArgumentException */ public XMLTransformer( Transformation transformation ) throws IllegalArgumentException { super( transformation ); } /** * Transforms the given input stream, and streams the input into the output directly. If a geometry is found, the * geometry is transformed into the target crs. All other events are just copied. * * @param reader * an XMLStream containing some GML Geometries. * @param writer * the output will be written to this writer, the writer have been opened ( * {@link XMLStreamWriter#writeStartDocument()}. No {@link XMLStreamWriter#writeEndDocument()} will be * written as well. * @param sourceCRS * to be used if the geometries do not define a srsName (or the like) attribute. * @param gmlVersion * the version of the expected geometries. * @param testValidArea * true if the incoming geometries should be checked against the valid domain of the crs they are defined * in. * @param requestedTransformation * can be <code>null</code> * @throws XMLStreamException * @throws XMLParsingException * @throws IllegalArgumentException * @throws OutsideCRSDomainException * @throws UnknownCRSException * @throws TransformationException */ public void transform( XMLStreamReader reader, XMLStreamWriter writer, ICRS sourceCRS, GMLVersion gmlVersion, boolean testValidArea, List<Transformation> requestedTransformation ) throws XMLStreamException, XMLParsingException, IllegalArgumentException, OutsideCRSDomainException, UnknownCRSException, TransformationException { if ( reader == null ) { throw new NullPointerException( "The input stream may not be null" ); } if ( writer == null ) { throw new NullPointerException( "The output stream may not be null" ); } GMLStreamReader gmlReader = createGMLStreamReader( gmlVersion, reader ); GMLStreamWriter gmlWriter = createGMLStreamWriter( gmlVersion, writer ); transformStream( gmlReader, gmlWriter, sourceCRS, testValidArea, requestedTransformation ); } /** * Transforms the given input stream, and streams the input into the output directly. If a geometry is found, the * geometry is transformed into the target crs. All other events are just copied. * * @param reader * an XMLStream containing some GML Geometries. * @param writer * the output will be written to this writer, the writer have been opened ( * {@link XMLStreamWriter#writeStartDocument()}. No {@link XMLStreamWriter#writeEndDocument()} will be * written as well. * @param gmlVersion * the version of the expected geometries. * @throws XMLStreamException * @throws XMLParsingException * @throws IllegalArgumentException * @throws OutsideCRSDomainException * @throws UnknownCRSException * @throws TransformationException */ public void transform( XMLStreamReader reader, XMLStreamWriter writer, GMLVersion gmlVersion ) throws XMLStreamException, XMLParsingException, IllegalArgumentException, OutsideCRSDomainException, UnknownCRSException, TransformationException { transform( reader, writer, null, gmlVersion, false, null ); } private void transformStream( GMLStreamReader gmlReader, GMLStreamWriter gmlWriter, ICRS sourceCRS, boolean testValidArea, List<Transformation> toBeUsedTransformations ) throws XMLStreamException, XMLParsingException, UnknownCRSException, IllegalArgumentException, TransformationException, OutsideCRSDomainException { XMLStreamReader input = gmlReader.getXMLReader(); int eventType = input.getEventType(); if ( eventType == XMLStreamConstants.START_DOCUMENT ) { XMLStreamUtils.nextElement( input ); } eventType = input.getEventType(); if ( input.getEventType() != XMLStreamConstants.START_ELEMENT ) { throw new XMLStreamException( "Input stream does not point to a START_ELEMENT event." ); } XMLStreamWriter output = gmlWriter.getXMLStream(); int openElements = 0; boolean firstRun = true; while ( firstRun || openElements > 0 ) { firstRun = false; eventType = input.getEventType(); switch ( eventType ) { case COMMENT: output.writeComment( input.getText() ); break; case CDATA: { output.writeCData( input.getText() ); break; } case CHARACTERS: { output.writeCharacters( input.getTextCharacters(), input.getTextStart(), input.getTextLength() ); break; } case END_ELEMENT: { output.writeEndElement(); openElements--; break; } case START_ELEMENT: { QName name = input.getName(); if ( gmlReader.isGeometryOrEnvelopeElement() ) { Geometry geom = gmlReader.readGeometryOrEnvelope(); if ( geom != null ) { ICRS geomCRS = sourceCRS; if ( geomCRS == null ) { ICRS gCRS = geom.getCoordinateSystem(); if ( gCRS != null ) { geomCRS = gCRS; } else { throw new TransformationException( "Could not determine Coordinate System of geometry: " + geom ); } } geom = super.transform( geom, geomCRS, testValidArea, toBeUsedTransformations ); // write transformed geometry gmlWriter.write( geom ); } } else { output.writeStartElement( name.getPrefix() == null ? "" : name.getPrefix(), input.getLocalName(), input.getNamespaceURI() ); // copy all namespace bindings for ( int i = 0; i < input.getNamespaceCount(); i++ ) { String nsPrefix = input.getNamespacePrefix( i ); String nsURI = input.getNamespaceURI( i ); output.writeNamespace( nsPrefix, nsURI ); } // copy all attributes for ( int i = 0; i < input.getAttributeCount(); i++ ) { String localName = input.getAttributeLocalName( i ); String nsPrefix = input.getAttributePrefix( i ); String value = input.getAttributeValue( i ); String nsURI = input.getAttributeNamespace( i ); if ( nsURI == null ) { output.writeAttribute( localName, value ); } else { output.writeAttribute( nsPrefix, nsURI, localName, value ); } } openElements++; break; } } default: { break; } } if ( openElements > 0 ) { input.next(); } } } }
lgpl-2.1
iulian787/spack
var/spack/repos/builtin/packages/py-pandas/package.py
5778
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyPandas(PythonPackage): """pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the Python programming language.""" homepage = "https://pandas.pydata.org/" url = "https://pypi.io/packages/source/p/pandas/pandas-1.1.5.tar.gz" maintainers = ['adamjstewart'] import_modules = [ 'pandas', 'pandas.compat', 'pandas.core', 'pandas.util', 'pandas.io', 'pandas.tseries', 'pandas._libs', 'pandas.plotting', 'pandas.arrays', 'pandas.api', 'pandas.errors', 'pandas._config', 'pandas.compat.numpy', 'pandas.core.reshape', 'pandas.core.tools', 'pandas.core.util', 'pandas.core.dtypes', 'pandas.core.groupby', 'pandas.core.internals', 'pandas.core.computation', 'pandas.core.arrays', 'pandas.core.ops', 'pandas.core.sparse', 'pandas.core.indexes', 'pandas.io.msgpack', 'pandas.io.formats', 'pandas.io.excel', 'pandas.io.json', 'pandas.io.sas', 'pandas.io.clipboard', 'pandas._libs.tslibs', 'pandas.plotting._matplotlib', 'pandas.api.types', 'pandas.api.extensions' ] version('1.1.5', sha256='f10fc41ee3c75a474d3bdf68d396f10782d013d7f67db99c0efbfd0acb99701b') version('1.1.4', sha256='a979d0404b135c63954dea79e6246c45dd45371a88631cdbb4877d844e6de3b6') version('1.1.3', sha256='babbeda2f83b0686c9ad38d93b10516e68cdcd5771007eb80a763e98aaf44613') version('1.1.2', sha256='b64ffd87a2cfd31b40acd4b92cb72ea9a52a48165aec4c140e78fd69c45d1444') version('1.1.1', sha256='53328284a7bb046e2e885fd1b8c078bd896d7fc4575b915d4936f54984a2ba67') version('1.1.0', sha256='b39508562ad0bb3f384b0db24da7d68a2608b9ddc85b1d931ccaaa92d5e45273') version('1.0.5', sha256='69c5d920a0b2a9838e677f78f4dde506b95ea8e4d30da25859db6469ded84fa8') version('1.0.4', sha256='b35d625282baa7b51e82e52622c300a1ca9f786711b2af7cbe64f1e6831f4126') version('1.0.3', sha256='32f42e322fb903d0e189a4c10b75ba70d90958cc4f66a1781ed027f1a1d14586') version('1.0.2', sha256='76334ba36aa42f93b6b47b79cbc32187d3a178a4ab1c3a478c8f4198bcd93a73') version('1.0.1', sha256='3c07765308f091d81b6735d4f2242bb43c332cc3461cae60543df6b10967fe27') version('1.0.0', sha256='3ea6cc86931f57f18b1240572216f09922d91b19ab8a01cf24734394a3db3bec') version('0.25.3', sha256='52da74df8a9c9a103af0a72c9d5fdc8e0183a90884278db7f386b5692a2220a4') version('0.25.2', sha256='ca91a19d1f0a280874a24dca44aadce42da7f3a7edb7e9ab7c7baad8febee2be') version('0.25.1', sha256='cb2e197b7b0687becb026b84d3c242482f20cbb29a9981e43604eb67576da9f6') version('0.25.0', sha256='914341ad2d5b1ea522798efa4016430b66107d05781dbfe7cf05eba8f37df995') version('0.24.2', sha256='4f919f409c433577a501e023943e582c57355d50a724c589e78bc1d551a535a2') version('0.24.1', sha256='435821cb2501eabbcee7e83614bd710940dc0cf28b5afbc4bdb816c31cec71af') version('0.23.4', sha256='5b24ca47acf69222e82530e89111dd9d14f9b970ab2cd3a1c2c78f0c4fbba4f4') version('0.21.1', sha256='c5f5cba88bf0659554c41c909e1f78139f6fce8fa9315a29a23692b38ff9788a') version('0.20.0', sha256='54f7a2bb2a7832c0446ad51d779806f07ec4ea2bb7c9aea4b83669fa97e778c4') version('0.19.2', sha256='6f0f4f598c2b16746803c8bafef7c721c57e4844da752d36240c0acf97658014') version('0.19.0', sha256='4697606cdf023c6b7fcb74e48aaf25cf282a1a00e339d2d274cf1b663748805b') version('0.18.0', sha256='c975710ce8154b50f39a46aa3ea88d95b680191d1d9d4b5dd91eae7215e01814') version('0.16.1', sha256='570d243f8cb068bf780461b9225d2e7bef7c90aa10d43cf908fe541fc92df8b6') version('0.16.0', sha256='4013de6f8796ca9d2871218861823bd9878a8dfacd26e08ccf9afdd01bbad9f1') # Required dependencies # https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html#dependencies depends_on('python@3.6.1:', type=('build', 'run'), when='@1:') depends_on('python@3.5.3:', type=('build', 'run'), when='@0.25:') # https://pandas.pydata.org/docs/whatsnew/v1.0.0.html#build-changes depends_on('py-cython@0.29.13:2', type='build', when='@1:') depends_on('py-cython@0.29.16:2', type='build', when='@1.1:') depends_on('py-cython@0.29.21:2', type='build', when='@1.1.3:') depends_on('py-setuptools@24.2.0:', type='build') depends_on('py-numpy', type=('build', 'run')) depends_on('py-numpy@1.13.3:', type=('build', 'run'), when='@0.25:') depends_on('py-numpy@1.15.4:', type=('build', 'run'), when='@1.1:') depends_on('py-python-dateutil', type=('build', 'run')) depends_on('py-python-dateutil@2.6.1:', type=('build', 'run'), when='@0.25:') depends_on('py-python-dateutil@2.7.3:', type=('build', 'run'), when='@1.1:') depends_on('py-pytz@2017.2:', type=('build', 'run')) # Recommended dependencies # https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html#recommended-dependencies depends_on('py-numexpr', type=('build', 'run')) depends_on('py-numexpr@2.6.2:', type=('build', 'run'), when='@0.25:') depends_on('py-bottleneck', type=('build', 'run')) depends_on('py-bottleneck@1.2.1:', type=('build', 'run'), when='@0.25:') # Optional dependencies # https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html#optional-dependencies # Test dependencies # https://pandas.pydata.org/pandas-docs/stable/development/contributing.html#running-the-test-suite depends_on('py-pytest@4.0.2:', type='test') depends_on('py-pytest-xdist', type='test') depends_on('py-hypothesis@3.58:', type='test') depends_on('py-pyarrow@0.10.0:', type='test')
lgpl-2.1
FernCreek/tinymce
modules/sand/src/demo/ts/ephox/sand/demo/Demo.ts
284
import { document } from '@ephox/dom-globals'; import * as PlatformDetection from 'ephox/sand/api/PlatformDetection'; const platform = PlatformDetection.detect(); const ephoxUi = document.querySelector('#ephox-ui'); ephoxUi.innerHTML = 'You are using: ' + platform.browser.current;
lgpl-2.1
cordoval/myhdl-python
myhdl/__init__.py
5229
# This file is part of the myhdl library, a Python package for using # Python as a Hardware Description Language. # # Copyright (C) 2003-2013 Jan Decaluwe # # The myhdl library 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. # # This library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ myhdl package initialization. This module provides the following myhdl objects: Simulation -- simulation class StopStimulation -- exception that stops a simulation now -- function that returns the current time Signal -- factory function to model hardware signals SignalType -- Signal base class ConcatSignal -- factory function that models a concatenation shadow signal TristateSignal -- factory function that models a tristate shadow signal delay -- callable to model delay in a yield statement posedge -- callable to model a rising edge on a signal in a yield statement negedge -- callable to model a falling edge on a signal in a yield statement join -- callable to join clauses in a yield statement intbv -- mutable integer class with bit vector facilities modbv -- modular bit vector class downrange -- function that returns a downward range bin -- returns a binary string representation. The optional width specifies the desired string width: padding of the sign-bit is used. concat -- function to concat ints, bitstrings, bools, intbvs, Signals -- returns an intbv instances -- function that returns all instances defined in a function always -- always_comb -- decorator that returns an input-sensitive generator always_seq -- ResetSignal -- enum -- function that returns an enumeration type traceSignals -- function that enables signal tracing in a VCD file toVerilog -- function that converts a design to Verilog """ __version__ = "0.8" import sys import warnings class StopSimulation(Exception): """ Basic exception to stop a Simulation """ pass class _SuspendSimulation(Exception): """ Basic exception to suspend a Simulation """ pass class Error(Exception): def __init__(self, kind, msg="", info=""): self.kind = kind self.msg = msg self.info = info def __str__(self): s = "%s%s" % (self.info, self.kind) if self.msg: s += ": %s" % self.msg return s class AlwaysError(Error): pass class AlwaysCombError(Error): pass class InstanceError(Error): pass class CosimulationError(Error): pass class ExtractHierarchyError(Error): pass class SimulationError(Error): pass class ToVerilogError(Error): pass class TraceSignalsError(Error): pass class ConversionError(Error): pass class ToVerilogError(ConversionError): pass class ToVHDLError(ConversionError): pass class ConversionWarning(UserWarning): pass class ToVerilogWarning(ConversionWarning): pass class ToVHDLWarning(ConversionWarning): pass # warnings.filterwarnings('always', r".*", ToVerilogWarning) def showwarning(message, category, filename, lineno, *args): print >> sys.stderr, "** %s: %s" % (category.__name__, message) warnings.showwarning = showwarning from _bin import bin from _concat import concat from _intbv import intbv from _modbv import modbv from _join import join from _Signal import posedge, negedge, Signal, SignalType from _ShadowSignal import ConcatSignal from _ShadowSignal import TristateSignal from _simulator import now from _delay import delay from _Cosimulation import Cosimulation from _Simulation import Simulation from _misc import instances, downrange from _always_comb import always_comb from _always_seq import always_seq, ResetSignal from _always import always from _instance import instance from _enum import enum, EnumType, EnumItemType from _traceSignals import traceSignals from myhdl import conversion from conversion import toVerilog from conversion import toVHDL from _tristate import Tristate __all__ = ["bin", "concat", "intbv", "modbv", "join", "posedge", "negedge", "Signal", "SignalType", "ConcatSignal", "TristateSignal", "now", "delay", "downrange", "StopSimulation", "Cosimulation", "Simulation", "instances", "instance", "always_comb", "always_seq", "ResetSignal", "always", "enum", "EnumType", "EnumItemType", "traceSignals", "toVerilog", "toVHDL", "conversion", "Tristate" ]
lgpl-2.1
alphabetsoup/gpstk
lib/procframe/PCSmoother.cpp
6682
#pragma ident "$Id$" /** * @file PCSmoother.cpp * This class smoothes PC code observables using the corresponding LC * phase observable. */ //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Dagoberto Salazar - gAGE ( http:// www.gage.es ). 2007, 2008, 2011 // //============================================================================ #include "PCSmoother.hpp" namespace gpstk { // Returns a string identifying this object. std::string PCSmoother::getClassName() const { return "PCSmoother"; } /* Returns a satTypeValueMap object, adding the new data generated * when calling this object. * * @param gData Data object holding the data. */ satTypeValueMap& PCSmoother::Process(satTypeValueMap& gData) throw(ProcessingException) { try { double codeObs(0.0); double phaseObs(0.0); double flagObs1(0.0); double flagObs2(0.0); SatIDSet satRejectedSet; // Loop through all satellites satTypeValueMap::iterator it; for (it = gData.begin(); it != gData.end(); ++it) { try { // Try to extract the values codeObs = (*it).second(codeType); phaseObs = (*it).second(phaseType); } catch(...) { // If some value is missing, then schedule this satellite // for removal satRejectedSet.insert( (*it).first ); continue; } try { // Try to get the first cycle slip flag flagObs1 = (*it).second(csFlag1); } catch(...) { // If flag #1 is not found, no cycle slip is assumed // You REALLY want to have BOTH CS flags properly set flagObs1 = 0.0; } try { // Try to get the second cycle slip flag flagObs2 = (*it).second(csFlag2); } catch(...) { // If flag #2 is not found, no cycle slip is assumed // You REALLY want to have BOTH CS flags properly set flagObs2 = 0.0; } // Get the smoothed PC. (*it).second[resultType] = getSmoothing( (*it).first, codeObs, phaseObs, flagObs1, flagObs2 ); } // End of 'for (it = gData.begin(); it != gData.end(); ++it)' // Remove satellites with missing data gData.removeSatID(satRejectedSet); return gData; } catch(Exception& u) { // Throw an exception if something unexpected happens ProcessingException e( getClassName() + ":" + u.what() ); GPSTK_THROW(e); } } // End of method 'PCSmoother::Process()' /* Method to set the maximum size of filter window, in samples. * * @param maxSize Maximum size of filter window, in samples. */ PCSmoother& PCSmoother::setMaxWindowSize(const int& maxSize) { // Don't allow window sizes less than 1 if (maxSize > 1) { maxWindowSize = maxSize; } else { maxWindowSize = 1; } return (*this); } // End of method 'PCSmoother::setMaxWindowSize()' /* Compute the smoothed code observable. * * @param sat Satellite object. * @param code Code measurement. * @param phase Phase measurement. * @param flag1 Cycle slip flag in L1. * @param flag2 Cycle slip flag in L2. */ double PCSmoother::getSmoothing( const SatID& sat, const double& code, const double& phase, const double& flag1, const double& flag2 ) { // In case we have a cycle slip either in L1 or L2 if ( (flag1!=0.0) || (flag2!=0.0) ) { // Prepare the structure for the next iteration SmoothingData[sat].previousCode = code; SmoothingData[sat].previousPhase = phase; SmoothingData[sat].windowSize = 1; // We don't need any further processing return code; } // In case we didn't have cycle slip double smoothedCode(0.0); // Increment size of window and check limit ++SmoothingData[sat].windowSize; if (SmoothingData[sat].windowSize > maxWindowSize) { SmoothingData[sat].windowSize = maxWindowSize; } // The formula used is the following: // // CSn = (1/n)*Cn + ((n-1)/n)*(CSn-1 + Ln - Ln-1) // // As window size "n" increases, the former formula gives more // weight to the previous smoothed code CSn-1 plus the phase bias // (Ln - Ln-1), and less weight to the current code observation Cn smoothedCode = ( code + ((static_cast<double>(SmoothingData[sat].windowSize)) - 1.0) * (SmoothingData[sat].previousCode + (phase - SmoothingData[sat].previousPhase) ) ) / (static_cast<double>(SmoothingData[sat].windowSize)); // Store results for next iteration SmoothingData[sat].previousCode = smoothedCode; SmoothingData[sat].previousPhase = phase; return smoothedCode; } // End of method 'PCSmoother::getSmoothing()' } // End of namespace gpstk
lgpl-2.1
kuba1/qtcreator
src/plugins/analyzerbase/detailederrorview.cpp
11936
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "detailederrorview.h" #include <coreplugin/coreconstants.h> #include <coreplugin/editormanager/editormanager.h> #include <utils/qtcassert.h> #include <QApplication> #include <QClipboard> #include <QContextMenuEvent> #include <QFontMetrics> #include <QPainter> #include <QScrollBar> namespace Analyzer { DetailedErrorDelegate::DetailedErrorDelegate(QListView *parent) : QStyledItemDelegate(parent), m_detailsWidget(0) { connect(parent->verticalScrollBar(), &QScrollBar::valueChanged, this, &DetailedErrorDelegate::onVerticalScroll); } QSize DetailedErrorDelegate::sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const { if (!index.isValid()) return QStyledItemDelegate::sizeHint(opt, index); const QListView *view = qobject_cast<const QListView *>(parent()); const int viewportWidth = view->viewport()->width(); const bool isSelected = view->selectionModel()->currentIndex() == index; const int dy = 2 * s_itemMargin; if (!isSelected) { QFontMetrics fm(opt.font); return QSize(viewportWidth, fm.height() + dy); } if (m_detailsWidget && m_detailsIndex != index) { m_detailsWidget->deleteLater(); m_detailsWidget = 0; } if (!m_detailsWidget) { m_detailsWidget = createDetailsWidget(opt.font, index, view->viewport()); QTC_ASSERT(m_detailsWidget->parent() == view->viewport(), m_detailsWidget->setParent(view->viewport())); m_detailsIndex = index; } else { QTC_ASSERT(m_detailsIndex == index, /**/); } const int widthExcludingMargins = viewportWidth - 2 * s_itemMargin; m_detailsWidget->setFixedWidth(widthExcludingMargins); m_detailsWidgetHeight = m_detailsWidget->heightForWidth(widthExcludingMargins); // HACK: it's a bug in QLabel(?) that we have to force the widget to have the size it said // it would have. m_detailsWidget->setFixedHeight(m_detailsWidgetHeight); return QSize(viewportWidth, dy + m_detailsWidget->heightForWidth(widthExcludingMargins)); } void DetailedErrorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &basicOption, const QModelIndex &index) const { QStyleOptionViewItemV4 opt(basicOption); initStyleOption(&opt, index); const QListView *const view = qobject_cast<const QListView *>(parent()); const bool isSelected = view->selectionModel()->currentIndex() == index; QFontMetrics fm(opt.font); QPoint pos = opt.rect.topLeft(); painter->save(); const QColor bgColor = isSelected ? opt.palette.highlight().color() : opt.palette.background().color(); painter->setBrush(bgColor); // clear background painter->setPen(Qt::NoPen); painter->drawRect(opt.rect); pos.rx() += s_itemMargin; pos.ry() += s_itemMargin; if (isSelected) { // only show detailed widget and let it handle everything QTC_ASSERT(m_detailsIndex == index, /**/); QTC_ASSERT(m_detailsWidget, return); // should have been set in sizeHint() m_detailsWidget->move(pos); // when scrolling quickly, the widget can get stuck in a visible part of the scroll area // even though it should not be visible. therefore we hide it every time the scroll value // changes and un-hide it when the item with details widget is paint()ed, i.e. visible. m_detailsWidget->show(); const int viewportWidth = view->viewport()->width(); const int widthExcludingMargins = viewportWidth - 2 * s_itemMargin; QTC_ASSERT(m_detailsWidget->width() == widthExcludingMargins, /**/); QTC_ASSERT(m_detailsWidgetHeight == m_detailsWidget->height(), /**/); } else { // the reference coordinate for text drawing is the text baseline; move it inside the view rect. pos.ry() += fm.ascent(); const QColor textColor = opt.palette.text().color(); painter->setPen(textColor); // draw only text + location const SummaryLineInfo info = summaryInfo(index); const QString errorText = info.errorText; painter->drawText(pos, errorText); const int whatWidth = QFontMetrics(opt.font).width(errorText); const int space = 10; const int widthLeft = opt.rect.width() - (pos.x() + whatWidth + space + s_itemMargin); if (widthLeft > 0) { QFont monospace = opt.font; monospace.setFamily(QLatin1String("monospace")); QFontMetrics metrics(monospace); QColor nameColor = textColor; nameColor.setAlphaF(0.7); painter->setFont(monospace); painter->setPen(nameColor); QPoint namePos = pos; namePos.rx() += whatWidth + space; painter->drawText(namePos, metrics.elidedText(info.errorLocation, Qt::ElideLeft, widthLeft)); } } // Separator lines (like Issues pane) painter->setPen(QColor::fromRgb(150,150,150)); painter->drawLine(0, opt.rect.bottom(), opt.rect.right(), opt.rect.bottom()); painter->restore(); } void DetailedErrorDelegate::onCurrentSelectionChanged(const QModelIndex &now, const QModelIndex &previous) { if (m_detailsWidget) { m_detailsWidget->deleteLater(); m_detailsWidget = 0; } m_detailsIndex = QModelIndex(); if (now.isValid()) emit sizeHintChanged(now); if (previous.isValid()) emit sizeHintChanged(previous); } void DetailedErrorDelegate::onLayoutChanged() { if (m_detailsWidget) { m_detailsWidget->deleteLater(); m_detailsWidget = 0; m_detailsIndex = QModelIndex(); } } void DetailedErrorDelegate::onViewResized() { const QListView *view = qobject_cast<const QListView *>(parent()); if (m_detailsWidget) emit sizeHintChanged(view->selectionModel()->currentIndex()); } void DetailedErrorDelegate::onVerticalScroll() { if (m_detailsWidget) m_detailsWidget->hide(); } // Expects "file://some/path[:line[:column]]" - the line/column part is optional void DetailedErrorDelegate::openLinkInEditor(const QString &link) { const QString linkWithoutPrefix = link.mid(int(strlen("file://"))); const QChar separator = QLatin1Char(':'); const int lineColon = linkWithoutPrefix.indexOf(separator, /*after drive letter + colon =*/ 2); const QString path = linkWithoutPrefix.left(lineColon); const QString lineColumn = linkWithoutPrefix.mid(lineColon + 1); const int line = lineColumn.section(separator, 0, 0).toInt(); const int column = lineColumn.section(separator, 1, 1).toInt(); Core::EditorManager::openEditorAt(path, qMax(line, 0), qMax(column, 0)); } void DetailedErrorDelegate::copyToClipboard() { QApplication::clipboard()->setText(textualRepresentation()); } DetailedErrorView::DetailedErrorView(QWidget *parent) : QListView(parent), m_copyAction(0) { } DetailedErrorView::~DetailedErrorView() { itemDelegate()->deleteLater(); } void DetailedErrorView::setItemDelegate(QAbstractItemDelegate *delegate) { QListView::setItemDelegate(delegate); DetailedErrorDelegate *myDelegate = qobject_cast<DetailedErrorDelegate *>(itemDelegate()); connect(this, &DetailedErrorView::resized, myDelegate, &DetailedErrorDelegate::onViewResized); m_copyAction = new QAction(this); m_copyAction->setText(tr("Copy")); m_copyAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY))); m_copyAction->setShortcut(QKeySequence::Copy); m_copyAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(m_copyAction, &QAction::triggered, myDelegate, &DetailedErrorDelegate::copyToClipboard); addAction(m_copyAction); } void DetailedErrorView::setModel(QAbstractItemModel *model) { QListView::setModel(model); DetailedErrorDelegate *delegate = qobject_cast<DetailedErrorDelegate *>(itemDelegate()); QTC_ASSERT(delegate, return); connect(selectionModel(), &QItemSelectionModel::currentChanged, delegate, &DetailedErrorDelegate::onCurrentSelectionChanged); connect(model, &QAbstractItemModel::layoutChanged, delegate, &DetailedErrorDelegate::onLayoutChanged); } void DetailedErrorView::resizeEvent(QResizeEvent *e) { emit resized(); QListView::resizeEvent(e); } void DetailedErrorView::contextMenuEvent(QContextMenuEvent *e) { if (selectionModel()->selectedRows().isEmpty()) return; QMenu menu; menu.addActions(commonActions()); const QList<QAction *> custom = customActions(); if (!custom.isEmpty()) { menu.addSeparator(); menu.addActions(custom); } menu.exec(e->globalPos()); } void DetailedErrorView::updateGeometries() { if (model()) { QModelIndex index = model()->index(0, modelColumn(), rootIndex()); QStyleOptionViewItem option = viewOptions(); // delegate for row / column QSize step = itemDelegate()->sizeHint(option, index); horizontalScrollBar()->setSingleStep(step.width() + spacing()); verticalScrollBar()->setSingleStep(step.height() + spacing()); } QListView::updateGeometries(); } void DetailedErrorView::goNext() { QTC_ASSERT(rowCount(), return); setCurrentRow((currentRow() + 1) % rowCount()); } void DetailedErrorView::goBack() { QTC_ASSERT(rowCount(), return); const int prevRow = currentRow() - 1; setCurrentRow(prevRow >= 0 ? prevRow : rowCount() - 1); } int DetailedErrorView::rowCount() const { return model() ? model()->rowCount() : 0; } QList<QAction *> DetailedErrorView::commonActions() const { QList<QAction *> actions; actions << m_copyAction; return actions; } QList<QAction *> DetailedErrorView::customActions() const { return QList<QAction *>(); } int DetailedErrorView::currentRow() const { const QModelIndex index = selectionModel()->currentIndex(); return index.row(); } void DetailedErrorView::setCurrentRow(int row) { const QModelIndex index = model()->index(row, 0); selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); scrollTo(index); } } // namespace Analyzer
lgpl-2.1
alphabetsoup/gpstk
src/PositionSatStore.hpp
9406
/// @file PositionSatStore.hpp /// Store a tabular list of ephemeris data (position, velocity, acceleration) /// for several satellites, and compute values at any timetag from this table /// using Lagrange interpolation. Inherits TabularSatStore. #ifndef GPSTK_POSITION_SAT_STORE_INCLUDE #define GPSTK_POSITION_SAT_STORE_INCLUDE #include <map> #include <iostream> #include "TabularSatStore.hpp" #include "Exception.hpp" #include "SatID.hpp" #include "CommonTime.hpp" #include "Triple.hpp" #include "SP3Data.hpp" namespace gpstk { /** @addtogroup ephemstore */ //@{ /// Data record for storing clock data. See note on units in class PositionStore. typedef struct PositionStoreDataRecord { Triple Pos, sigPos; ///< position (ECEF Cartesian) and sigmas Triple Vel, sigVel; ///< velocity and sigmas Triple Acc, sigAcc; ///< acceleration and sigmas } PositionRecord; /// Output stream operator is used by dump() in TabularSatStore std::ostream& operator<<(std::ostream& os, const PositionRecord& cdr) throw(); // This is a helper for SWIG processing - it needs a template instation of the // base type of PositionSatStore before it is used, so this statement must be between // the PositionStoreDataRecord and PositionSatStore declarations. #ifdef SWIG %template(TabularSatStore_PositionRecord) gpstk::TabularSatStore<gpstk::PositionRecord>; #endif /// Store a table of data vs time for each of several satellites. /// The data are stored as PositionRecords, one for each (satellite,time) pair. /// The getValue(sat, t) routine interpolates the table for sat at time t and /// returns the result as a DataRecord object. /// NB this class (dump()) requires that operator<<(DataRecord) be defined, /// unless dump() is declared and defined in this class. /// NB. It is assumed that the units of the quanitities are 'coordinated' /// meaning that units(vel) == units(pos)/sec, units(acc) == units(pos)/sec/sec /// and units(sigX) == units(X). This assumption is critical only when /// interpolation is used to estimate X/sec from X data. /// No other assumptions are made about units. /// Note that SP3 data (in the file and in SP3Data) are NOT coordinated; users /// and derived classes must deal with units consistently. class PositionSatStore : public TabularSatStore<PositionRecord> { // member data protected: // NB havePosition and haveVelocity are in TabularSatStore /// flag indicating whether acceleration data is present bool haveAcceleration; /// Flag to reject bad positions, default true bool rejectBadPosFlag; /// Order of Lagrange interpolation used in interpolation of the data tables. /// Should be even; is forced to be even in setInterpolationOrder. /// Usually for 15min data, interpOrder = 10. unsigned int interpOrder; /// Store half the interpolation order, for convenience unsigned int Nhalf; // member functions public: /// Default constructor PositionSatStore() throw() : haveAcceleration(false), rejectBadPosFlag(true), Nhalf(5) { interpOrder = 2*Nhalf; havePosition = true; haveVelocity = false; haveClockBias = false; haveClockDrift = false; } /// Destructor ~PositionSatStore() {}; /// Tabular does not have this... bool hasAccleration() const throw() { return haveAcceleration; } /// Return value for the given satellite at the given time (usually via /// interpolation of the data table). This interface from TabularSatStore. /// @param[in] sat the SatID of the satellite of interest /// @param[in] ttag the time (CommonTime) of interest /// @return object of type PositionRecord containing the data value(s). /// @throw InvalidRequest if data value cannot be computed, for example because /// a) the time t does not lie within the time limits of the data table /// b) checkDataGap is true and there is a data gap /// c) checkInterval is true and the interval is larger than maxInterval PositionRecord getValue(const SatID& sat, const CommonTime& ttag) const throw(InvalidRequest); /// Return the position for the given satellite at the given time /// @param[in] sat the SatID of the satellite of interest /// @param[in] ttag the time (CommonTime) of interest /// @return Triple containing the position ECEF XYZ meters /// @throw InvalidRequest if result cannot be computed, for example because /// a) the time t does not lie within the time limits of the data table /// b) checkDataGap is true and there is a data gap /// c) checkInterval is true and the interval is larger than maxInterval Triple getPosition(const SatID& sat, const CommonTime& ttag) const throw(InvalidRequest); /// Return the velocity for the given satellite at the given time /// @param[in] sat the SatID of the satellite of interest /// @param[in] ttag the time (CommonTime) of interest /// @return Triple containing the velocity ECEF XYZ meters/second /// @throw InvalidRequest if result cannot be computed, for example because /// a) the time t does not lie within the time limits of the data table /// b) checkDataGap is true and there is a data gap /// c) checkInterval is true and the interval is larger than maxInterval Triple getVelocity(const SatID& sat, const CommonTime& ttag) const throw(InvalidRequest); /// Return the acceleration for the given satellite at the given time /// @param[in] sat the SatID of the satellite of interest /// @param[in] ttag the time (CommonTime) of interest /// @return Triple containing the acceleration ECEF XYZ meters/second/second /// @throw InvalidRequest if result cannot be computed, for example because /// a) the time t does not lie within the time limits of the data table /// b) checkDataGap is true and there is a data gap /// c) checkInterval is true and the interval is larger than maxInterval /// d) neither velocity nor acceleration data are present Triple getAcceleration(const SatID& sat, const CommonTime& ttag) const throw(InvalidRequest); /// Dump information about the object to an ostream. /// @param[in] os ostream to receive the output; defaults to std::cout /// @param[in] detail integer level of detail to provide; allowed values are /// 0: number of satellites, time step and time limits, flags, /// gap and interval flags and values, and file information /// 1: number of data/sat /// 2: above plus all the data tables virtual void dump(std::ostream& os = std::cout, int detail = 0) const throw() { os << "Dump of PositionSatStore(" << detail << "):\n"; os << " This store " << (haveAcceleration ? "contains":"does not contain") << " acceleration data." << std::endl; os << " Interpolation is Lagrange, of order " << interpOrder << " (" << Nhalf << " points on each side)" << std::endl; TabularSatStore<PositionRecord>::dump(os,detail); os << "End dump of PositionSatStore.\n"; } /// Add a complete PositionRecord to the store; this is the preferred method /// of adding data to the tables. /// NB. If these addXXX() routines are used more than once for the same record /// (sat,ttag), be aware that since ttag is used as they key in a std::map, /// the value used must be EXACTLY the same in all calls; (numerical noise could /// cause the std::map to consider two "equal" ttags as different). void addPositionRecord(const SatID& sat, const CommonTime& ttag, const PositionRecord& rec) throw(InvalidRequest); /// Add position data to the store; nothing else is changed void addPositionData(const SatID& sat, const CommonTime& ttag, const Triple& Pos, const Triple& Sig=Triple()) throw(InvalidRequest); /// Add velocity data to the store; nothing else is changed void addVelocityData(const SatID& sat, const CommonTime& ttag, const Triple& Vel, const Triple& Sig=Triple()) throw(InvalidRequest); /// Add acceleration data to the store; nothing else is changed void addAccelerationData(const SatID& sat, const CommonTime& ttag, const Triple& Acc, const Triple& Sig=Triple()) throw(InvalidRequest); /// Get current interpolation order. unsigned int getInterpolationOrder(void) throw() { return interpOrder; } /// Set the interpolation order; this routine forces the order to be even. void setInterpolationOrder(unsigned int order) throw() { Nhalf = (order+1)/2; interpOrder = 2*Nhalf; } /// Set the flag; if true then bad position values are rejected when /// adding data to the store. void rejectBadPositions(const bool flag) { rejectBadPosFlag=flag; } }; // end class PositionSatStore //@} } // End of namespace gpstk #endif // GPSTK_POSITION_SAT_STORE_INCLUDE
lgpl-2.1
solmix/datax
generator/core/src/main/java/org/solmix/generator/codegen/mybatis/javamapper/elements/annotated/AnnotatedUpdateByExampleSelectiveMethodGenerator.java
1927
/** * Copyright 2006-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.solmix.generator.codegen.mybatis.javamapper.elements.annotated; import org.solmix.generator.api.java.FullyQualifiedJavaType; import org.solmix.generator.api.java.Interface; import org.solmix.generator.api.java.Method; import org.solmix.generator.codegen.mybatis.javamapper.elements.UpdateByExampleSelectiveMethodGenerator; /** * * @author Jeff Butler */ public class AnnotatedUpdateByExampleSelectiveMethodGenerator extends UpdateByExampleSelectiveMethodGenerator { public AnnotatedUpdateByExampleSelectiveMethodGenerator() { super(); } @Override public void addMapperAnnotations(Method method) { FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(introspectedTable.getMyBatis3SqlProviderType()); StringBuilder sb = new StringBuilder(); sb.append("@UpdateProvider(type="); sb.append(fqjt.getShortName()); sb.append(".class, method=\""); sb.append(introspectedTable.getUpdateByExampleSelectiveStatementId()); sb.append("\")"); method.addAnnotation(sb.toString()); } @Override public void addExtraImports(Interface interfaze) { interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.UpdateProvider")); } }
lgpl-2.1
hoffmanc/FileHelpers
FileHelpers.WizardApp/FileBrowser.cs
6485
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.Collections.ObjectModel; using System.Drawing.Drawing2D; using System.Windows.Forms.Design; using System.ComponentModel; namespace FileHelpers.WizardApp { [Designer(typeof(FileBrowser.FileBrowserDesigner))] public class FileBrowser: ScrollableControl { private class FileBrowserDesigner:ControlDesigner { protected override void PostFilterProperties(System.Collections.IDictionary properties) { base.PostFilterProperties(properties); properties.Remove("Font"); } } public FileBrowser() { mColumns.AddRange(new ColumnInfo[] { new ColumnInfo(11), new ColumnInfo(38), new ColumnInfo(72-50), new ColumnInfo(110-72), new ColumnInfo(151-110), new ColumnInfo(169-151), new ColumnInfo(15) }); PenEvenRule = new Pen(ColorEvenRule); PenOddRule = new Pen(ColorOddRule); PenOverRule = new Pen(ColorOverRule); this.Font = new System.Drawing.Font("Courier New", mFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(0))); this.VerticalScroll.Enabled = true; this.DoubleBuffered = true; } int mTextTop = 25; private int mFontSize = 16; public int FontSize { get { return mFontSize; } set { mFontSize = value; mCharWidth = -1; this.Font = new System.Drawing.Font("Courier New", mFontSize, System.Drawing.FontStyle.Regular); this.Invalidate(); } } public int TextTop { get { return mTextTop; } set { mTextTop = value; this.Invalidate(); } } int mTextLeft = 10; public int TextLeft { get { return mTextLeft; } set { mTextLeft = value; this.Invalidate(); } } private List<ColumnInfo> mColumns = new List<ColumnInfo>(); public List<ColumnInfo> Columns { get { return mColumns; } } private Color ColorEvenRule = Color.DarkOrange; private Color ColorOddRule = Color.RoyalBlue; private Color ColorOverRule = Color.Black; private Color ColorOverColumn = Color.LightGoldenrodYellow; private Pen PenEvenRule; private Pen PenOddRule; private Pen PenOverRule; int mCharWidth = -1; int mOverColumn = -1; protected override void OnPaint(PaintEventArgs e) { if (mCharWidth == -1) mCharWidth = (int)e.Graphics.MeasureString("m", this.Font).Width - 5; int width; int left = mTextLeft; int rulesTop = mTextTop - 2; int rulesNumberTop = rulesTop - 13; bool even = true; for (int i = 0; i < mColumns.Count; i++) { width = mCharWidth * mColumns[i].Width; Brush backBrush; if (i == mOverColumn) backBrush = new SolidBrush(ColorOverColumn); else backBrush = new SolidBrush(mColumns[i].Color); e.Graphics.FillRectangle(backBrush, left, 0, width, this.Height - 1); backBrush.Dispose(); Pen rulePen; rulePen = even ? PenEvenRule : PenOddRule; even = !even; if (i == mOverColumn) rulePen = PenOverRule; e.Graphics.DrawLine(rulePen, left + 1, rulesTop, left + width - 1, rulesTop); Brush widthBrush; if (i == mOverColumn) widthBrush = new SolidBrush(Color.Black); else widthBrush = Brushes.DarkRed; e.Graphics.DrawString(mColumns[i].Width.ToString(), this.Font, widthBrush, left + width / 2 - 10, rulesNumberTop); left += width; } Brush b = new SolidBrush(this.ForeColor); e.Graphics.DrawString(Text, this.Font, b, mTextLeft, mTextTop); b.Dispose(); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); int oldCol = mOverColumn; mOverColumn = CalculateColumn(e.X); if (oldCol != mOverColumn) this.Invalidate(); } private int CalculateColumn(int x) { if (x < mTextLeft) return -1; int left = mTextLeft; for (int i = 0; i < mColumns.Count; i++) { left += mCharWidth * mColumns[i].Width; if (x < left) return i; } return -1; } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); mCharWidth = -1; } public class ColumnInfo { private int mWidth; public int Width { get { return mWidth; } set { mWidth = value; } } private Color mColor; public Color Color { get { return mColor; } set { mColor = value; } } public static bool even = false; public ColumnInfo() { if (even) Color = Color.AliceBlue; else Color = Color.White; even = !even; } public ColumnInfo(int width) : this() { this.Width = width; } } } }
lgpl-2.1
bsc-performance-tools/extrae
src/launcher/dyninst/demo-launcher.C
4504
/*****************************************************************************\ * ANALYSIS PERFORMANCE TOOLS * * Extrae * * Instrumentation package for parallel applications * ***************************************************************************** * ___ This library is free software; you can redistribute it and/or * * / __ modify it under the terms of the GNU LGPL as published * * / / _____ by the Free Software Foundation; either version 2.1 * * / / / \ of the License, or (at your option) any later version. * * ( ( ( B S C ) * * \ \ \_____/ This library is distributed in 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 LGPL for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * The GNU LEsser General Public License is contained in the file COPYING. * * --------- * * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion * \*****************************************************************************/ #include "common.h" #if HAVE_STDLIB_H # include <stdlib.h> #endif #if HAVE_STDIO_H # include <stdio.h> #endif #if HAVE_STRING_H # include <string.h> #endif #if HAVE_UNISTD_H # include <unistd.h> #endif #if HAVE_LIBGEN_H # include <libgen.h> #endif #include <sys/stat.h> #include <string> #include <iostream> #include <fstream> #include <algorithm> using namespace std; #include <BPatch.h> BPatch *bpatch; void error_function (BPatchErrorLevel level, int num, const char* const* params) { if (num == 0) { if (level == BPatchInfo) fprintf (stderr, "%s\n", params[0]); else fprintf (stderr, "%s", params[0]); } else { char line[256]; const char *msg = bpatch->getEnglishErrorString(num); bpatch->formatErrorString(line, sizeof(line), msg, params); if (num != -1) if (num != 112) fprintf (stderr, "Error #%d (level %d): %s\n", num, level, line); } } static void ForkCallback (BPatch_thread *parent, BPatch_thread *child) { if (child == NULL) { /* preFork */ } else { /* postFork */ parent->oneTimeCodeAsync (BPatch_nullExpr()); // BPatch_process *p = parent->getProcess(); // p->stopExecution(); // p->oneTimeCode (BPatch_nullExpr()); // p->continueExecution(); } } int main (int argc, char *argv[]) { char *env_var; if (argc != 2) { cout << "Options: binary" << endl; exit (-1); } if ((env_var = getenv ("DYNINSTAPI_RT_LIB")) == NULL) { env_var = (char*) malloc ((1+strlen("DYNINSTAPI_RT_LIB=")+strlen(DYNINST_RT_LIB))*sizeof(char)); if (env_var == NULL) { cerr << PACKAGE_NAME << ": Cannot allocate memory to define DYNINSTAPI_RT_LIB!" << endl; exit (-1); } sprintf (env_var, "DYNINSTAPI_RT_LIB=%s", DYNINST_RT_LIB); putenv (env_var); } else cout << PACKAGE_NAME << ": Warning, DYNINSTAPI_RT_LIB already set and pointing to " << env_var << endl; /* Create an instance of the BPatch library */ bpatch = new BPatch; /* Register a callback function that prints any error messages */ bpatch->registerErrorCallback (error_function); /* Don't check recursion in snippets */ bpatch->setTrampRecursive (true); cout << PACKAGE_NAME << ": Creating process for image binary " << argv[1] << endl; BPatch_process *appProcess = bpatch->processCreate ((const char*) argv[1], (const char**) NULL, (const char**) environ); bpatch->registerPreForkCallback (ForkCallback); bpatch->registerPostForkCallback (ForkCallback); if (!appProcess->continueExecution()) { /* If the application cannot continue, terminate the mutatee and exit */ cerr << PACKAGE_NAME << ": Cannot continue execution of the target application" << endl; appProcess->terminateExecution(); exit (-1); } while (!appProcess->isTerminated()) bpatch->waitForStatusChange(); return 0; }
lgpl-2.1
DavBfr/cf
Core/classes/Rest.class.php
8991
<?php namespace DavBfr\CF; /** * Copyright (C) 2013-2016 David PHAM-VAN * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ abstract class Rest { const REQUEST_DIR = "request"; const REQUEST_PREFIX = "|^v\d+/|"; private $list = array(); private $routes = array(); private $complex_routes = array(); private $jsonpost_data = null; protected $path = null; protected $method = null; protected $mp = null; /** * Rest constructor. */ public function __construct() { $this->getRoutes(); } /** * @param string $path * @param string $method * @param callable $callback * @param array $openapi */ protected function addRoute($path, $method, $callback, $openapi = array()) { $this->list[] = array($path, $method, $callback, $openapi); if (strpos($path, ":") !== false) { $vars = array(); $aPath = explode("/", $path); foreach ($aPath as $key => $item) { if (substr($item, 0, 1) == ":") { $vars[] = substr($item, 1); $aPath[$key] = "([^/]+)"; } else { $aPath[$key] = str_replace(".", "\\.", $item); } } $rPath = "#^" . implode("/", $aPath) . "$#"; $this->complex_routes[$method . "@" . $path] = array($method, $rPath, $vars, $callback); } else { $this->routes[$method . "@" . $path] = $callback; } } /** * */ abstract protected function getRoutes(); /** * @return array * @throws \Exception */ protected function jsonpost() { if ($this->jsonpost_data === null) { $this->jsonpost_data = Input::decodeJsonPost(); } return $this->jsonpost_data; } /** * @param string $mp * @return bool */ protected function preCheck($mp) { return true; } /** * @param array $r */ protected function preProcess($r) { } /** * @param string $method * @throws \Exception */ protected function processNotFound($method) { ErrorHandler::error(404, null, get_class($this) . "::" . $method); } /** * @param string $method * @param string $path * @return array */ public function getRequestHeaders($method, $path) { return []; } /** * @param string $method * @param string $path * @throws \Exception */ public function handleRequest($method, $path) { foreach($this->getRequestHeaders($method, $path) as $header => $value) { if (is_array($value)) { $value = implode(', ', $value); } header("$header: $value"); } if ($method == 'OPTIONS') { Output::finish(); } if ($path == "") $path = "/"; $this->method = $method; $this->path = $path; $this->mp = $method . "@" . $path; if (isset($this->routes[$this->mp])) { restore_exception_handler(); try { if (!$this->preCheck($this->mp)) { ErrorHandler::error(401); } $this->preProcess(array()); call_user_func(array($this, $this->routes[$this->mp]), array()); } catch (\Exception $e) { ErrorHandler::getInstance()->exceptionHandler($e); } ErrorHandler::error(204); } else { foreach ($this->complex_routes as $cPath => $route) { list($m, $p, $v, $c) = $route; if ($m == $method) { if (preg_match($p, $path, $matches) != false) { $pa = array(); foreach ($v as $i => $k) { $pa[$k] = $matches[$i + 1]; } $this->mp = $cPath; restore_exception_handler(); try { if (!$this->preCheck($this->mp)) { ErrorHandler::error(401); } $this->preProcess($pa); call_user_func(array($this, $c), $pa); } catch (\Exception $e) { ErrorHandler::getInstance()->exceptionHandler($e); } ErrorHandler::error(204); } } } $this->processNotFound($this->mp); } } /** * @param string $method * @param string $path * @throws \Exception */ public static function handle($method = null, $path = null) { if ($path == null) { $path = @$_SERVER["PATH_INFO"]; } if ($method == null) { $method = $_SERVER["REQUEST_METHOD"]; } while (strlen($path) > 0 && $path[0] == "/") $path = substr($path, 1); if ($path == "") $path = "index"; if (preg_match(self::REQUEST_PREFIX, $path, $matches) != false) { $prefix = $matches[0]; $path = substr($path, strlen($prefix)); } else { $prefix = ""; } $pos = strpos($path, "/"); if ($pos === false) { $request = $path; $next_path = ""; } else { $request = substr($path, 0, $pos); $next_path = substr($path, $pos); } $request = str_replace(".", "_", $request); $request = str_replace("-", " ", $request); $request = ucwords($request); $request = str_replace(" ", "", $request) . "Rest"; $request_file = Plugins::find(self::REQUEST_DIR . DIRECTORY_SEPARATOR . $prefix . $request . ".class.php"); if ($request_file === null) { ErrorHandler::error(404, null, $prefix . $request . ".class.php"); } require_once($request_file); $class_name = __NAMESPACE__ . "\\" . $request; /** @var Rest $instance */ $instance = new $class_name(); $instance->handleRequest($method, $next_path); ErrorHandler::error(204); } /** * @return array * @throws \ReflectionException */ public function buildApi() { $classname = explode('\\', get_class($this)); $tag = substr(array_pop($classname), 0, -4); // Todo: Manage special cases // $request = str_replace(".", "_", $request); // $request = str_replace("-", " ", $request); // $request = ucwords($request); // $request = str_replace(" ", "", $request) . "Rest"; $prefix = "/" . strtolower($tag); $class = new \ReflectionClass($this); $path = basename(dirname($class->getFileName())); if (preg_match("|v\d+|", $path, $matches) != false) { $prefix = "/" . $path . $prefix; } $paths = array(); foreach ($this->list as $route) { list($path, $method, $callback, $openapi) = $route; $path = $prefix . $path; $vars = array(); if (strpos($path, ":") !== false) { $aPath = explode("/", $path); foreach ($aPath as $key => $item) { if (substr($item, 0, 1) == ":") { $item = substr($item, 1); $vars[] = array( "name" => $item, "in" => "path", "required" => true, "description" => $item, "schema" => array("type" => "string"), ); $aPath[$key] = "{" . $item . "}"; } } $path = implode("/", $aPath); } if (!array_key_exists($path, $paths)) $paths[$path] = array(); $paths[$path][strtolower($method)] = array_merge(array( "summary" => $callback, "tags" => array($tag), "operationId" => $callback, "parameters" => $vars, "responses" => array( 200 => array("description" => "OK"), 400 => array("description" => ErrorHandler::$messagecode[400]), 401 => array("description" => ErrorHandler::$messagecode[401]), 417 => array("description" => ErrorHandler::$messagecode[417]), 500 => array("description" => ErrorHandler::$messagecode[500]), ), ), $openapi); } return $paths; } /** * @return array * @throws \ReflectionException */ public static function getOpenApi() { $config = Config::getInstance(); $authors = $config->get("composer.authors"); $api = array( "openapi" => "3.0.0", "info" => array( "version" => $config->get("composer.version"), "title" => $config->get("title"), "description" => $config->get("description"), "contact" => array( "name" => $authors[0]["name"], "email" => $authors[0]["email"], ), ), "license" => array( "name" => $config->get("composer.license"), ), "servers" => array( array("url" => "http" . (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] ? "s" : "") . "://" . HttpHeaders::get('host') . Options::get('REST_PATH')), ), ); $paths = array(); foreach (Plugins::get_plugins() as $plugin) { $request = Plugins::get($plugin)->getDir() . DIRECTORY_SEPARATOR . Rest::REQUEST_DIR; $files = System::globRec($request . DIRECTORY_SEPARATOR . "*Rest.class.php"); foreach ($files as $file) { $cn = __NAMESPACE__ . "\\" . substr(basename($file), 0, -10); try { if (!class_exists($cn, false)) { require_once($file); } /** @var Rest $req */ $req = new $cn(); } catch (\Exception $e) { continue; } $paths = array_merge($paths, $req->buildApi()); } } $api["paths"] = $paths; return $api; } }
lgpl-2.1
davidB/yuicompressor-maven-plugin
src/it/demo01/src/main/webapp/static/toAggregateAndRemove/bar.js
15
var bar="bar";
lgpl-2.1
tmcguire/qt-mobility
tests/auto/qsensor/tst_qsensor.cpp
31778
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //TESTED_COMPONENT=src/sensors #include <QObject> #include <QTest> #include <QDebug> #include <QSettings> #include <QFile> #include <QSignalSpy> #include "qsensor.h" #include "test_sensor.h" #include "test_sensor2.h" #include "test_sensorimpl.h" #include "test_backends.h" // The unit test needs to change the behaviour of the library. It does this // through an exported but undocumented function. QTM_BEGIN_NAMESPACE Q_SENSORS_EXPORT void sensors_unit_test_hook(int index); bool operator==(const qoutputrange &orl1, const qoutputrange &orl2) { return (orl1.minimum == orl2.minimum && orl1.maximum == orl2.maximum && orl1.accuracy == orl2.accuracy); } QTM_END_NAMESPACE QTM_USE_NAMESPACE namespace QTest { template<> char *toString(const qoutputrangelist &orl) { QStringList list; foreach (const qoutputrange &item, orl) { list << QString("%1-%2%3%4").arg(item.minimum).arg(item.maximum).arg(QString::fromWCharArray(L"\u00B1")).arg(item.accuracy); } QString ret = QString("qoutputrangelist: (%1)").arg(list.join("), (")); return qstrdup(ret.toLatin1().data()); } template<> char *toString(const QList<QByteArray> &data) { QStringList list; foreach (const QByteArray &str, data) { list << QString::fromLatin1(str); } QString ret = QString("QList<QByteArray>: (%1)").arg(list.join("), (")); return qstrdup(ret.toLatin1().data()); } } class MyFilter : public TestSensorFilter { bool filter(TestSensorReading *) { return false; } }; class ModFilter : public TestSensorFilter { bool filter(TestSensorReading *reading) { reading->setTest(3); return true; } }; class MyFactory : public QSensorBackendFactory { QSensorBackend *createBackend(QSensor * /*sensor*/) { return 0; } }; /* Unit test for QSensor class. */ class tst_QSensor : public QObject { Q_OBJECT public: tst_QSensor() { sensors_unit_test_hook(0); // change some flags the library uses } private slots: void initTestCase() { QSettings settings(QLatin1String("Nokia"), QLatin1String("Sensors")); settings.clear(); } void cleanupTestCase() { QSettings settings(QLatin1String("Nokia"), QLatin1String("Sensors")); settings.clear(); #ifdef WAIT_AT_END QFile _stdin; _stdin.open(1, QIODevice::ReadOnly); _stdin.readLine(); #endif } // This test MUST be first void testRecursiveLoadPlugins() { TestSensor sensor; // This confirms that legacy static plugins can still be registered QTest::ignoreMessage(QtWarningMsg, "Loaded the LegacySensorPlugin "); // The logic for the test is in test_sensorplugin.cpp (which warns and aborts if the test fails) (void)QSensor::sensorTypes(); // Checking that the availableSensorsChanged() signal was not emitted too many times while loading plugins. QCOMPARE(sensor.sensorsChangedEmitted, 1); } void testTypeRegistered() { QList<QByteArray> expected; expected << TestSensor::type << TestSensor2::type; QList<QByteArray> actual = QSensor::sensorTypes(); qSort(actual); // The actual list is not in a defined order QCOMPARE(actual, expected); } void testSensorRegistered() { QList<QByteArray> expected; expected << "test sensor 2" << "test sensor 3" << testsensorimpl::id; QList<QByteArray> actual = QSensor::sensorsForType(TestSensor::type); qSort(actual); // The actual list is not in a defined order QCOMPARE(actual, expected); } void testSensorDefault() { QByteArray expected = testsensorimpl::id; QByteArray actual = QSensor::defaultSensorForType(TestSensor::type); QCOMPARE(actual, expected); } void testBadDefaultFromConfig() { QSettings settings(QLatin1String("Nokia"), QLatin1String("Sensors")); settings.setValue(QString(QLatin1String("Default/%1")).arg(QString::fromLatin1(TestSensor::type)), QByteArray("bogus id")); settings.sync(); QByteArray expected = testsensorimpl::id; QByteArray actual = QSensor::defaultSensorForType(TestSensor::type); QCOMPARE(actual, expected); } void testGoodDefaultFromConfig() { QSettings settings(QLatin1String("Nokia"), QLatin1String("Sensors")); settings.setValue(QString(QLatin1String("Default/%1")).arg(QString::fromLatin1(TestSensor::type)), QByteArray(testsensorimpl::id)); settings.sync(); QByteArray expected = testsensorimpl::id; QByteArray actual = QSensor::defaultSensorForType(TestSensor::type); QCOMPARE(actual, expected); settings.clear(); } void testNoSensorsForType() { QList<QByteArray> expected; QList<QByteArray> actual = QSensor::sensorsForType("bogus type"); QCOMPARE(actual, expected); } void testNoDefaultForType() { QByteArray expected; QByteArray actual = QSensor::defaultSensorForType("bogus type"); QCOMPARE(actual, expected); } void testCreation() { TestSensor sensor; sensor.connectToBackend(); QByteArray expected = testsensorimpl::id; QByteArray actual = sensor.identifier(); QCOMPARE(actual, expected); } void testSetIdentifierFail() { TestSensor sensor; sensor.setIdentifier(testsensorimpl::id); sensor.connectToBackend(); QVERIFY(sensor.isConnectedToBackend()); QByteArray expected = testsensorimpl::id; QByteArray actual = sensor.identifier(); QCOMPARE(actual, expected); QTest::ignoreMessage(QtWarningMsg, "ERROR: Cannot call QSensor::setIdentifier while connected to a backend! "); sensor.setIdentifier("dummy.accelerometer"); expected = testsensorimpl::id; actual = sensor.identifier(); QCOMPARE(actual, expected); } void testBadDefaultCreation() { QSettings settings(QLatin1String("Nokia"), QLatin1String("Sensors")); settings.setValue(QString(QLatin1String("Default/%1")).arg(QString::fromLatin1(TestSensor::type)), QByteArray("test sensor 2")); settings.sync(); TestSensor sensor; QTest::ignoreMessage(QtWarningMsg, "Can't create backend \"test sensor 2\" "); sensor.connectToBackend(); QByteArray expected = testsensorimpl::id; QByteArray actual = sensor.identifier(); QCOMPARE(actual, expected); settings.clear(); } void testBadCreation() { QSensor sensor("bogus type"); sensor.connectToBackend(); QByteArray expected; // should be null QByteArray actual = sensor.identifier(); QCOMPARE(actual, expected); } void testTimestamp() { TestSensor sensor; sensor.connectToBackend(); QVERIFY(sensor.reading() != 0); quint64 timestamp = sensor.reading()->timestamp(); QVERIFY(timestamp == qtimestamp()); sensor.setProperty("doThis", "setOne"); sensor.start(); timestamp = sensor.reading()->timestamp(); QVERIFY(timestamp == 1); } void testStart() { TestSensor sensor; sensor.start(); QVERIFY(sensor.isActive()); sensor.start(); QVERIFY(sensor.isActive()); } void testBadStart() { QSensor sensor("bogus type"); sensor.start(); QVERIFY(!sensor.isActive()); } void testStop() { TestSensor sensor; sensor.stop(); QVERIFY(!sensor.isActive()); sensor.start(); QVERIFY(sensor.isActive()); sensor.stop(); QVERIFY(!sensor.isActive()); } void testMetaData() { TestSensor sensor; { bool actual = sensor.isConnectedToBackend(); bool expected = false; QCOMPARE(actual, expected); } sensor.connectToBackend(); { bool actual = sensor.isConnectedToBackend(); bool expected = true; QCOMPARE(actual, expected); } { QString actual = sensor.description(); QString expected = "sensor description"; QCOMPARE(actual, expected); } { qoutputrangelist actual = sensor.outputRanges(); qoutputrangelist expected; qoutputrange r; r.minimum = 0; r.maximum = 1; r.accuracy = 0.5; expected << r; r.minimum = 0; r.maximum = 2; r.accuracy = 1; expected << r; QCOMPARE(actual, expected); } { int actual = sensor.outputRange(); int expected = -1; QCOMPARE(actual, expected); sensor.setOutputRange(0); actual = sensor.outputRange(); expected = 0; QCOMPARE(actual, expected); } { qrangelist actual = sensor.availableDataRates(); qrangelist expected = qrangelist() << qrange(100,100); QCOMPARE(actual, expected); } { TestSensor sensor; sensor.setProperty("doThis", "rates"); sensor.connectToBackend(); qrangelist actual = sensor.availableDataRates(); qrangelist expected = qrangelist() << qrange(100,100); QCOMPARE(actual, expected); } { TestSensor sensor; sensor.setProperty("doThis", "rates(0)"); QTest::ignoreMessage(QtWarningMsg, "ERROR: Cannot call QSensorBackend::setDataRates with 0 "); sensor.connectToBackend(); } { TestSensor sensor; sensor.setProperty("doThis", "rates(nodef)"); QTest::ignoreMessage(QtWarningMsg, "ERROR: Cannot call QSensorBackend::setDataRates with an invalid sensor "); sensor.connectToBackend(); } { int actual = sensor.dataRate(); int expected = 0; QCOMPARE(actual, expected); sensor.setDataRate(100); actual = sensor.dataRate(); expected = 100; QCOMPARE(actual, expected); } // Test the generic accessor functions TestSensorReading *reading = sensor.reading(); QCOMPARE(reading->valueCount(), 1); reading->setTest(1); QCOMPARE(reading->test(), reading->value(0).toInt()); } void testFilter() { TestSensor sensor; sensor.connectToBackend(); QList<QSensorFilter*> actual = sensor.filters(); QList<QSensorFilter*> expected = QList<QSensorFilter*>(); QCOMPARE(actual, expected); QTest::ignoreMessage(QtWarningMsg, "addFilter: passed a null filter! "); sensor.addFilter(0); QTest::ignoreMessage(QtWarningMsg, "removeFilter: passed a null filter! "); sensor.removeFilter(0); MyFilter *filter = new MyFilter; sensor.addFilter(filter); actual = sensor.filters(); expected = QList<QSensorFilter*>() << filter; QCOMPARE(actual, expected); MyFilter *filter2 = new MyFilter; sensor.addFilter(filter2); actual = sensor.filters(); expected = QList<QSensorFilter*>() << filter << filter2; QCOMPARE(actual, expected); delete filter2; actual = sensor.filters(); expected = QList<QSensorFilter*>() << filter; QCOMPARE(actual, expected); sensor.removeFilter(filter); actual = sensor.filters(); expected = QList<QSensorFilter*>(); QCOMPARE(actual, expected); delete filter; } void testFilter2() { TestSensor sensor; sensor.setProperty("doThis", "setOne"); TestSensorFilter *filter1 = new ModFilter; TestSensorFilter *filter2 = new MyFilter; sensor.addFilter(filter1); sensor.start(); QCOMPARE(sensor.reading()->test(), 3); sensor.stop(); sensor.reading()->setTest(1); sensor.addFilter(filter2); sensor.start(); QCOMPARE(sensor.reading()->test(), 1); sensor.stop(); delete filter1; delete filter2; } void testFilter3() { TestSensor sensor; sensor.setProperty("doThis", "setOne"); QSignalSpy spy(&sensor, SIGNAL(readingChanged())); sensor.start(); QCOMPARE(spy.count(), 1); // reading changes sensor.stop(); TestSensorFilter *filter2 = new MyFilter; sensor.addFilter(filter2); sensor.start(); QCOMPARE(spy.count(), 1); // filter suppresses reading so it does not change sensor.stop(); delete filter2; TestSensorFilter *filter1 = new ModFilter; sensor.addFilter(filter1); sensor.start(); QCOMPARE(spy.count(), 2); // filter does not suppress reading sensor.stop(); delete filter1; } void testStart2() { TestSensor sensor; sensor.connectToBackend(); sensor.setProperty("doThis", "stop"); sensor.start(); QVERIFY(!sensor.isActive()); sensor.stop(); sensor.setProperty("doThis", "error"); sensor.start(); QVERIFY(sensor.error() == 1); // Yes, this is non-intuitive but the sensor // decides if an error is fatal or not. // In this case our test sensor is reporting a // non-fatal error so the sensor will start. QVERIFY(sensor.isActive()); sensor.stop(); sensor.setProperty("doThis", "setOne"); sensor.start(); QCOMPARE(sensor.reading()->timestamp(), qtimestamp(1)); QCOMPARE(sensor.reading()->test(), 1); sensor.stop(); sensor.setProperty("doThis", "setTwo"); sensor.start(); QCOMPARE(sensor.reading()->timestamp(), qtimestamp(2)); QCOMPARE(sensor.reading()->test(), 2); sensor.stop(); } void testSetBadDataRate() { TestSensor sensor; sensor.connectToBackend(); sensor.setDataRate(1); QCOMPARE(sensor.dataRate(), 1); sensor.setDataRate(1000); QCOMPARE(sensor.dataRate(), 1000); } void testSetBadDataRateWhenNotConnected() { TestSensor sensor; sensor.setDataRate(0); QCOMPARE(sensor.dataRate(), 0); sensor.setDataRate(300); QCOMPARE(sensor.dataRate(), 300); sensor.setDataRate(350); sensor.connectToBackend(); QCOMPARE(sensor.dataRate(), 350); } void testSetBadOutputRange() { TestSensor sensor; sensor.connectToBackend(); sensor.setOutputRange(-1); QCOMPARE(sensor.outputRange(), -1); QTest::ignoreMessage(QtWarningMsg, "setOutputRange: 300 is not supported by the sensor. "); sensor.setOutputRange(300); QCOMPARE(sensor.outputRange(), -1); } void testSetBadOutputRangeWhenNotConnected() { TestSensor sensor; sensor.setOutputRange(300); QCOMPARE(sensor.outputRange(), 300); sensor.setOutputRange(350); QTest::ignoreMessage(QtWarningMsg, "setOutputRange: 350 is not supported by the sensor. "); sensor.connectToBackend(); QCOMPARE(sensor.outputRange(), -1); QTest::ignoreMessage(QtWarningMsg, "setOutputRange: -2 is not supported by the sensor. "); sensor.setOutputRange(-2); QCOMPARE(sensor.outputRange(), -1); } void testEnumHandling() { { QAmbientLightReading reading; for (int i = 0; i <= 6; i++) { QAmbientLightReading::LightLevel setting = static_cast<QAmbientLightReading::LightLevel>(i); QAmbientLightReading::LightLevel expected = setting; if (i == 6) expected = QAmbientLightReading::Undefined; reading.setLightLevel(setting); QCOMPARE(reading.lightLevel(), expected); } } { QOrientationReading reading; for (int i = 0; i <= 7; i++) { QOrientationReading::Orientation setting = static_cast<QOrientationReading::Orientation>(i); QOrientationReading::Orientation expected = setting; if (i == 7) expected = QOrientationReading::Undefined; reading.setOrientation(setting); QCOMPARE(reading.orientation(), expected); } } { QTapReading reading; reading.setTapDirection(QTapReading::Undefined); QCOMPARE(reading.tapDirection(), QTapReading::Undefined); reading.setTapDirection(QTapReading::X_Pos); QCOMPARE(reading.tapDirection(), QTapReading::X_Pos); reading.setTapDirection(QTapReading::X_Neg); QCOMPARE(reading.tapDirection(), QTapReading::X_Neg); reading.setTapDirection(QTapReading::Y_Pos); QCOMPARE(reading.tapDirection(), QTapReading::Y_Pos); reading.setTapDirection(QTapReading::Y_Neg); QCOMPARE(reading.tapDirection(), QTapReading::Y_Neg); reading.setTapDirection(QTapReading::Z_Pos); QCOMPARE(reading.tapDirection(), QTapReading::Z_Pos); reading.setTapDirection(QTapReading::Z_Neg); QCOMPARE(reading.tapDirection(), QTapReading::Z_Neg); // Directions can be ORed together reading.setTapDirection(QTapReading::X_Both); QCOMPARE(reading.tapDirection(), QTapReading::X_Both); reading.setTapDirection(QTapReading::Y_Both); QCOMPARE(reading.tapDirection(), QTapReading::Y_Both); reading.setTapDirection(QTapReading::Z_Both); QCOMPARE(reading.tapDirection(), QTapReading::Z_Both); // You can't set just the Axis reading.setTapDirection(QTapReading::X); QCOMPARE(reading.tapDirection(), QTapReading::Undefined); reading.setTapDirection(QTapReading::Y); QCOMPARE(reading.tapDirection(), QTapReading::Undefined); reading.setTapDirection(QTapReading::Z); QCOMPARE(reading.tapDirection(), QTapReading::Undefined); reading.setTapDirection(static_cast<QTapReading::TapDirection>(0x1000)); QCOMPARE(reading.tapDirection(), QTapReading::Undefined); } } void testDynamicDefaultsAndGenericHandling() { QByteArray expected; QByteArray actual; MyFactory factory; // The default for this type is null expected = QByteArray(); actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); // Register a bogus backend QSensorManager::registerBackend("random", "generic.random", &factory); // The default for this type is the newly-registered backend expected = "generic.random"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); // Register a non-generic bogus backend QSensorManager::registerBackend("random", "not.generic.random", &factory); // The default for this type is the newly-registered backend expected = "not.generic.random"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); // Unregister the non-generic bogus backend QSensorManager::unregisterBackend("random", "not.generic.random"); // The default for this type is the generic backend expected = "generic.random"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); // Unregister a bogus backend QSensorManager::unregisterBackend("random", "generic.random"); // The default for this type is null again expected = QByteArray(); actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); // Now test out some more of the logic // Register 2 backends and unregister the first. QSensorManager::registerBackend("random", "random.1", &factory); expected = "random.1"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); QSensorManager::registerBackend("random", "random.2", &factory); expected = "random.1"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); QSensorManager::unregisterBackend("random", "random.1"); expected = "random.2"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); QSensorManager::unregisterBackend("random", "random.2"); expected = QByteArray(); actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); // Now stick a generic backend into the mix and ensure the correct thing happens QSensorManager::registerBackend("random", "random.1", &factory); expected = "random.1"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); QSensorManager::registerBackend("random", "generic.random.2", &factory); expected = "random.1"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); QSensorManager::registerBackend("random", "random.2", &factory); expected = "random.1"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); QSensorManager::unregisterBackend("random", "random.1"); expected = "random.2"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); QSensorManager::unregisterBackend("random", "generic.random.2"); expected = "random.2"; actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); QSensorManager::unregisterBackend("random", "random.2"); expected = QByteArray(); actual = QSensor::defaultSensorForType("random"); QCOMPARE(expected, actual); } void testCreation2() { MyFactory factory; QSensorManager::registerBackend("random", "random.1", &factory); QSensorManager::registerBackend("random", "random.2", &factory); QSensor random("random"); // This is a sensorlog, not a warning //QTest::ignoreMessage(QtWarningMsg, "no suitable backend found for requested identifier \"\" and type \"random\" "); random.connectToBackend(); QVERIFY(!random.isConnectedToBackend()); random.setIdentifier("random.3"); // This is a sensorlog, not a warning //QTest::ignoreMessage(QtWarningMsg, "no backend with identifier \"random.3\" for type \"random\" "); random.connectToBackend(); QVERIFY(!random.isConnectedToBackend()); random.setIdentifier("random.1"); random.connectToBackend(); QVERIFY(!random.isConnectedToBackend()); QSensorManager::unregisterBackend("random", "random.1"); QSensorManager::unregisterBackend("random", "random.2"); } void testSensorsChangedSignal() { TestSensor sensor; MyFactory factory; // Register a bogus backend sensor.sensorsChangedEmitted = 0; QSensorManager::registerBackend("a random type", "a random id", &factory); QCOMPARE(sensor.sensorsChangedEmitted, 1); // Register it again (creates a warning) sensor.sensorsChangedEmitted = 0; QTest::ignoreMessage(QtWarningMsg, "A backend with type \"a random type\" and identifier \"a random id\" has already been registered! "); QSensorManager::registerBackend("a random type", "a random id", &factory); QCOMPARE(sensor.sensorsChangedEmitted, 0); // Unregister a bogus backend sensor.sensorsChangedEmitted = 0; QSensorManager::unregisterBackend("a random type", "a random id"); QCOMPARE(sensor.sensorsChangedEmitted, 1); // Unregister an unknown identifier sensor.sensorsChangedEmitted = 0; QTest::ignoreMessage(QtWarningMsg, "Identifier \"a random id\" is not registered "); QSensorManager::unregisterBackend(TestSensor::type, "a random id"); QCOMPARE(sensor.sensorsChangedEmitted, 0); // Unregister for an unknown type sensor.sensorsChangedEmitted = 0; QTest::ignoreMessage(QtWarningMsg, "No backends of type \"foo\" are registered "); QSensorManager::unregisterBackend("foo", "bar"); QCOMPARE(sensor.sensorsChangedEmitted, 0); // Make sure we've cleaned up the list of available types QList<QByteArray> expected; expected << TestSensor::type << TestSensor2::type; QList<QByteArray> actual = QSensor::sensorTypes(); qSort(actual); // The actual list is not in a defined order QCOMPARE(actual, expected); } void testSetActive() { TestSensor sensor; sensor.setActive(true); // doesn't start till the event loop is hit QVERIFY(!sensor.isActive()); // hit the event loop QTest::qWait(0); QVERIFY(sensor.isActive()); sensor.setActive(true); QVERIFY(sensor.isActive()); // it does stop immediately sensor.setActive(false); QVERIFY(!sensor.isActive()); } void testIsRegistered() { bool expected; bool actual; expected = true; actual = QSensorManager::isBackendRegistered(TestSensor::type, testsensorimpl::id); QCOMPARE(expected, actual); expected = false; actual = QSensorManager::isBackendRegistered(TestSensor::type, "random"); QCOMPARE(expected, actual); expected = false; actual = QSensorManager::isBackendRegistered("random", "random"); QCOMPARE(expected, actual); } void testAllTheInterfaces() { register_test_backends(); TEST_SENSORINTERFACE(QAccelerometer, QAccelerometerReading, { QCOMPARE(reading->x(), 1.0); QCOMPARE(reading->y(), 1.0); QCOMPARE(reading->z(), 1.0); }) TEST_SENSORINTERFACE(QAmbientLightSensor, QAmbientLightReading, { QCOMPARE(reading->lightLevel(), QAmbientLightReading::Twilight); }) TEST_SENSORINTERFACE(QCompass, QCompassReading, { QCOMPARE(reading->azimuth(), 1.0); QCOMPARE(reading->calibrationLevel(), 1.0); }) TEST_SENSORINTERFACE(QGyroscope, QGyroscopeReading, { QCOMPARE(reading->x(), 1.0); QCOMPARE(reading->y(), 1.0); QCOMPARE(reading->z(), 1.0); }) TEST_SENSORINTERFACE(QLightSensor, QLightReading, { QCOMPARE(reading->lux(), 1.0); }) TEST_SENSORINTERFACE(QMagnetometer, QMagnetometerReading, { QCOMPARE(reading->x(), 1.0); QCOMPARE(reading->y(), 1.0); QCOMPARE(reading->z(), 1.0); QCOMPARE(reading->calibrationLevel(), 1.0); }) TEST_SENSORINTERFACE(QOrientationSensor, QOrientationReading, { QCOMPARE(reading->orientation(), QOrientationReading::LeftUp); }) TEST_SENSORINTERFACE(QProximitySensor, QProximityReading, { QCOMPARE(reading->close(), true); }) TEST_SENSORINTERFACE(QRotationSensor, QRotationReading, { QCOMPARE(reading->x(), 1.0); QCOMPARE(reading->y(), 1.0); QCOMPARE(reading->z(), 1.0); }) TEST_SENSORINTERFACE(QTapSensor, QTapReading, { QCOMPARE(reading->tapDirection(), QTapReading::Z_Both); QCOMPARE(reading->isDoubleTap(), true); }) unregister_test_backends(); } void testReadingBC() { // QSensorReading changed in 1.0.1 due to QTMOBILITY-226 // This test verifies that a backend built against the 1.0.0 // version of qsensor.h still runs. TestSensor2 sensor; sensor.setProperty("doThis", "setOne"); sensor.start(); QCOMPARE(sensor.reading()->timestamp(), qtimestamp(1)); QCOMPARE(sensor.reading()->test(), 1); sensor.stop(); sensor.setProperty("doThis", "setTwo"); sensor.start(); QCOMPARE(sensor.reading()->timestamp(), qtimestamp(2)); QCOMPARE(sensor.reading()->test(), 2); sensor.stop(); } void testBusyChanged() { // Start an exclusive sensor TestSensor sensor1; sensor1.setProperty("exclusive", true); sensor1.start(); QVERIFY(sensor1.isActive()); // Try to start another one, sensor reports busy TestSensor sensor2; sensor2.setProperty("exclusive", true); sensor2.start(); QVERIFY(sensor2.isBusy()); QVERIFY(!sensor2.isActive()); // Stopping the first instance causes the busyChanged signal to be emitted from the second instance QSignalSpy spy(&sensor2, SIGNAL(busyChanged())); sensor1.stop(); QCOMPARE(spy.count(), 1); // Now we can start the second instance sensor2.start(); QVERIFY(sensor2.isActive()); } // This test must be LAST or it will interfere with the other tests void testLoadingPlugins() { // Go ahead and load the actual plugins (as a test that plugin loading works) sensors_unit_test_hook(1); // Hmm... There's no real way to tell if this worked or not. // If it doesn't work the unit test will probably crash. // That's what it did on Symbian before plugin loading was fixed. } }; QTEST_MAIN(tst_QSensor) #include "tst_qsensor.moc"
lgpl-2.1
nikhilsinghmus/csound
Opcodes/padsynth_gen.cpp
16604
/* padsynt_gen.cpp: Copyright (C) 2015 Michael Gogins after Nasca O Paul This file is part of Csound. The Csound Library 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ extern "C" { #include "csdl.h" } #include <cmath> #include <complex> #include <random> /** Paul Octavian Nasca's "padsynth algorithm" adds bandwidth to each partial of a periodic weaveform. This bandwidth is heard as color, movement, and additional richness of sound. First, the waveform is defined by the user as a series of harmonic partials. Then, bandwidth is added by independently spreading each partial of the original waveform from a single frequency across neighboring frequencies, according to a "profile" function: a Gaussian curve, a square, or a rising and then falling expontential. The partials of the original waveform may be considered to be samples in a discrete Fourier transform of the waveform. Normally there is not an exact one-to-one correspondence between the frequencies of the samples (frequency bins) of the discrete Fourier transform with the frequencies of the partials of the original waveform, because any frequency in the inverse of the discrete Fourier transform might be synthesized by interference between any number of bins. However, the padsynth algorithm uses a simple trick to create this correspondence. The discrete Fourier transform is simply made so large that the frequency of any partial of the original waveform will be very close to the frequency of the corresponding bin in the Fourier transform. Once this correspondence has been created, the bandwidth profile can be applied by centering it over the frequency bin of the original partial, scaling the profile by the bandwidth, and simply multiplying the original partial by each sample of the profile and adding the product to the corresponding bin of the Fourier transform. As the frequencies of the partials increase, their bandwidth may optionally become wider or (less often) narrower. Once each partial has been spread out in this way, the discrete Fourier transform may be given random phases, and is then simply inverted to synthesize the desired waveform, which may be used as the wavetable for a digital oscillator. N.B.: The size of the function table does NOT necessarily reflect one periodic cycle of the waveform that it contains. The fundamental frequency must be used to generate the desired pitch from an oscillator using the function table, e.g. oscillator_hz = desired_hz * (sr / padsynth_size / fundamental_hz) The parameters of the function table statement are: p1 "padsynth" p2 Score time (usually 0). p3 Function table size (must be a power of 2, should be large, e.g. 2^18 == 262144). p4 Function table number (auto-generated if 0). p5 Fundamental frequency of the generated waveform (cycles per second). p6 Bandwidth of the partials (cents). p7 Scaling factor for partial bandwidth (log of increase/decrease with partial frequency, 0 is no stretch or shrink). p8 Harmonic stretch/shrink of the partial (1 is harmonic). p9 Number specifying the shape of the bandwidth profile: 1 Gaussian 2 Square 3 Exponential p10 Profile function parameter. p11-pN The amplitudes of the partials (may be 0). */ static void log(CSOUND *csound, const char *format, ...) { va_list args; va_start(args, format); if (csound) { if (csound->GetMessageLevel(csound) & WARNMSG) csound->MessageV(csound, 0, format, args); } else { vfprintf(stdout, format, args); } va_end(args); } static void warn(CSOUND *csound, const char *format, ...) { if (csound) { if (csound->GetMessageLevel(csound) & WARNMSG) { va_list args; va_start(args, format); csound->MessageV(csound, CSOUNDMSG_WARNING, format, args); va_end(args); } } else { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); } } /* unused static MYFLT profile_original(MYFLT fi, MYFLT bwi) { MYFLT x=fi/bwi; x*=x; if (x>14.71280603) { return 0.0; //this avoids computing the e^(-x^2) where it's results are very close to zero } return exp(-x)/bwi; }; */ // profile(p9_profile_shape, profile_sample_index_normalized, bandwidth_samples, // p10_profile_parameter); static MYFLT profile(int shape, MYFLT fi, MYFLT bwi, MYFLT a) { MYFLT x = fi / bwi; MYFLT y = 0; switch (shape) { case 1: y = std::exp(-(x * x * a)); break; case 2: // The idea is to take profile 1 and simply say y goes to 0 if below a and // to 1 if above a. y = std::exp(-(x * x * a)); if (a < 0.00001) { a = 0.00001; } else if (a > 0.99999) { a = 0.99999; } if (y < a) { y = 0; } else { y = 1; } break; case 3: y = std::exp(-(std::fabs(x) * std::sqrt(a))); break; } return y / bwi; } #if 0 // Keep this stuff around, it might come in handy later. #define FUNC(b) MYFLT base_function_##b(MYFLT x, MYFLT a) static MYFLT base_function_pulse(MYFLT x, MYFLT a) { return (std::fmod(x, 1.0) < a) ? -1.0 : 1.0; } FUNC(saw) { if(a < 0.00001f) { a = 0.00001f; } else if(a > 0.99999f) { a = 0.99999f; } x = fmod(x, 1); if(x < a) { return x / a * 2.0f - 1.0f; } else { return (1.0f - x) / (1.0f - a) * 2.0f - 1.0f; } } FUNC(triangle) { x = fmod(x + 0.25f, 1); a = 1 - a; if(a < 0.00001f) { a = 0.00001f; } if(x < 0.5f) { x = x * 4 - 1.0f; } else { x = (1.0f - x) * 4 - 1.0f; } x /= -a; if(x < -1.0f) { x = -1.0f; } if(x > 1.0f) { x = 1.0f; } return x; } FUNC(power) { x = fmod(x, 1); if(a < 0.00001f) { a = 0.00001f; } else if(a > 0.99999f) { a = 0.99999f; } return powf(x, expf((a - 0.5f) * 10.0f)) * 2.0f - 1.0f; } FUNC(gauss) { x = fmod(x, 1) * 2.0f - 1.0f; if(a < 0.00001f) { a = 0.00001f; } return expf(-x * x * (expf(a * 8) + 5.0f)) * 2.0f - 1.0f; } FUNC(diode) { if(a < 0.00001f) { a = 0.00001f; } else if(a > 0.99999f) { a = 0.99999f; } a = a * 2.0f - 1.0f; x = cosf((x + 0.5f) * 2.0f * PI) - a; if(x < 0.0f) { x = 0.0f; } return x / (1.0f - a) * 2 - 1.0f; } FUNC(abssine) { x = fmod(x, 1); if(a < 0.00001f) { a = 0.00001f; } else if(a > 0.99999f) { a = 0.99999f; } return sinf(powf(x, expf((a - 0.5f) * 5.0f)) * PI) * 2.0f - 1.0f; } FUNC(pulsesine) { if(a < 0.00001f) { a = 0.00001f; } x = (fmod(x, 1) - 0.5f) * expf((a - 0.5f) * logf(128)); if(x < -0.5f) { x = -0.5f; } else if(x > 0.5f) { x = 0.5f; } x = sinf(x * PI * 2.0f); return x; } FUNC(stretchsine) { x = fmod(x + 0.5f, 1) * 2.0f - 1.0f; a = (a - 0.5f) * 4; if(a > 0.0f) { a *= 2; } a = powf(3.0f, a); float b = powf(fabs(x), a); if(x < 0) { b = -b; } return -sinf(b * PI); } FUNC(chirp) { x = fmod(x, 1.0f) * 2.0f * PI; a = (a - 0.5f) * 4; if(a < 0.0f) { a *= 2.0f; } a = powf(3.0f, a); return sinf(x / 2.0f) * sinf(a * x * x); } FUNC(absstretchsine) { x = fmod(x + 0.5f, 1) * 2.0f - 1.0f; a = (a - 0.5f) * 9; a = powf(3.0f, a); float b = powf(fabs(x), a); if(x < 0) { b = -b; } return -powf(sinf(b * PI), 2); } FUNC(chebyshev) { a = a * a * a * 30.0f + 1.0f; return cosf(acosf(x * 2.0f - 1.0f) * a); } FUNC(sqr) { a = a * a * a * a * 160.0f + 0.001f; return -atanf(sinf(x * 2.0f * PI) * a); } FUNC(spike) { float b = a * 0.66666; // the width of the range: if a == 0.5, b == 0.33333 if(x < 0.5) { if(x < (0.5 - (b / 2.0))) { return 0.0; } else { // shift to zero, and expand to range from 0 to 1 x = (x + (b / 2) - 0.5) * (2.0 / b); return x * (2.0 / b); // this is the slope: 1 / (b / 2) } } else { if(x > (0.5 + (b / 2.0))) { return 0.0; } else { x = (x - 0.5) * (2.0 / b); return (1 - x) * (2.0 / b); } } } FUNC(circle) { // a is parameter: 0 -> 0.5 -> 1 // O.5 = circle float b, y; b = 2 - (a * 2); // b goes from 2 to 0 x = x * 4; if(x < 2) { x = x - 1; // x goes from -1 to 1 if((x < -b) || (x > b)) { y = 0; } else { y = sqrt(1 - (x*x) / (b*b)); // normally * a^2, but a stays 1 } } else { x = x - 3; // x goes from -1 to 1 as well if((x < -b) || (x > b)) { y = 0; } else { y = -sqrt(1 - (x*x) / (b*b)); } } return y; } typedef MYFLT (*base_function_t)(MYFLT, MYFLT); static base_function_t get_base_function(int index) { if(!index) { return NULL; } if(index == 127) { //should be the custom wave return NULL; } index--; base_function_t functions[] = { base_function_triangle,comment base_function_pulse, base_function_saw, base_function_power, base_function_gauss, base_function_diode, base_function_abssine, base_function_pulsesine, base_function_stretchsine, base_function_chirp, base_function_absstretchsine, base_function_chebyshev, base_function_sqr, base_function_spike, base_function_circle, }; return functions[index]; } #endif extern "C" { /* Original code: MYFLT PADsynth::profile(MYFLT fi, MYFLT bwi) { MYFLT x=fi/bwi; x*=x; if (x>14.71280603) { return 0.0; //this avoids computing the e^(-x^2) where it's results are very close to zero } return exp(-x)/bwi; }; for (nh=1; nh<number_harmonics; nh++) { //for each harmonic MYFLT bw_Hz;//bandwidth of the current harmonic measured in Hz MYFLT bwi; MYFLT fi; MYFLT rF=f*relF(nh); bw_Hz=(pow(2.0,bw/1200.0)-1.0)*f*pow(relF(nh),bwscale); bwi=bw_Hz/(2.0*samplerate); fi=rF/samplerate; for (i=0; i<N/2; i++) { //here you can optimize, by avoiding to // compute the profile for the full frequency // (usually it's zero or very close to zero) MYFLT hprofile; hprofile=profile((i/(MYFLT)N)-fi,bwi); freq_amp[i]+=hprofile*A[nh]; }; }; */ //#define ROOT2 FL(1.41421356237309504880168872421) /** * This function computes a Csound function table * using Nasca's "padsynth" algorithm.. */ static int padsynth_gen(FGDATA *ff, FUNC *ftp) { CSOUND *csound = ff->csound; MYFLT p1_function_table_number = ff->fno; MYFLT p2_score_time = ff->e.p[2]; int N = ff->flen; MYFLT p5_fundamental_frequency = ff->e.p[5]; MYFLT p6_partial_bandwidth = ff->e.p[6]; MYFLT p7_partial_bandwidth_scale_factor = ff->e.p[7]; MYFLT p8_harmonic_stretch = ff->e.p[8]; int p9_profile_shape = (int)ff->e.p[9]; // base_function_t base_function = get_base_function(p9_profile_shape); MYFLT p10_profile_parameter = ff->e.p[10]; MYFLT samplerate = csound->GetSr(csound); log(csound, "samplerate: %12d\n", (int)samplerate); log(csound, "p1_function_table_number: %9.4f\n", p1_function_table_number); log(csound, "p2_score_time: %9.4f\n", p2_score_time); log(csound, "p3_ftable_size %12d\n", N); log(csound, "p4_gen_id: %12d\n", (int)(ff->e.p[4])); log(csound, "p5_fundamental_frequency: %9.4f\n", p5_fundamental_frequency); log(csound, "p6_partial_bandwidth: %9.4f\n", p6_partial_bandwidth); log(csound, "p7_partial_bandwidth_scale_factor: %9.4f\n", p7_partial_bandwidth_scale_factor); log(csound, "p8_harmonic_stretch: %9.4f\n", p8_harmonic_stretch); log(csound, "p9_profile_shape: %12d\n", p9_profile_shape); // log(csound, "profile_function: 0x%16p\n", base_function); log(csound, "p10_profile_parameter: %9.4f\n", p10_profile_parameter); // The amplitudes of each partial are in pfield 11 and higher. // N.B.: The partials are indexed starting from 1. int partialN = ff->e.pcnt - 10; std::vector<MYFLT> A(partialN + 1); A[0] = FL(0.0); for (int partialI = 1; partialI <= partialN; ++partialI) { A[partialI] = ff->e.p[11 + partialI - 1]; } for (int i = 0; i < N; ++i) { ftp->ftable[i] = FL(0.0); } // N.B.: An in-place IFFT of N/2 complex to N real samples is used. // ftable[1] contains the real part of the Nyquist frequency; we make it 0. std::complex<MYFLT> *spectrum = (std::complex<MYFLT> *)ftp->ftable; int complexN = int(N / 2.0); for (int partialI = 1; partialI <= partialN; ++partialI) { MYFLT partial_Hz = p5_fundamental_frequency * p8_harmonic_stretch * ((MYFLT)partialI); MYFLT frequency_sample_index_normalized = partial_Hz / ((MYFLT)samplerate); int partial_frequency_index = frequency_sample_index_normalized * ((MYFLT)N); MYFLT bandwidth_Hz = (std::pow(2.0, p6_partial_bandwidth / 1200.0) - 1.0) * p5_fundamental_frequency * std::pow(p8_harmonic_stretch * ((MYFLT)partialI), p7_partial_bandwidth_scale_factor); MYFLT bandwidth_samples = bandwidth_Hz / (2.0 * samplerate); log(csound, "partial[%3d]: %9.4f\n", partialI, A[partialI]); warn(csound, " partial_Hz: %9.4f\n", partial_Hz); warn(csound, " frequency_sample_index_normalized: %9.4f\n", frequency_sample_index_normalized); warn(csound, " partial_frequency_index: %12d\n", partial_frequency_index); warn(csound, " bandwidth_Hz: %9.4f\n", bandwidth_Hz); warn(csound, " bandwidth_samples: %12.8f\n", bandwidth_samples); for (int fft_sample_index = 0; fft_sample_index < complexN; ++fft_sample_index) { MYFLT fft_sample_index_normalized = ((MYFLT)fft_sample_index) / ((MYFLT)N); MYFLT profile_sample_index_normalized = fft_sample_index_normalized - frequency_sample_index_normalized; MYFLT profile_sample = profile(p9_profile_shape, profile_sample_index_normalized, bandwidth_samples, p10_profile_parameter); // MYFLT profile_sample = // profile_original(profile_sample_index_normalized, bandwidth_samples); MYFLT real = profile_sample * A[partialI]; spectrum[fft_sample_index] += real; }; }; std::default_random_engine generator; std::uniform_real_distribution<double> distribution(0.0, 6.28318530718); for (int complexI = 0; complexI < complexN; ++complexI) { MYFLT random_phase = distribution(generator); MYFLT real = spectrum[complexI].real(); spectrum[complexI].real(real * std::cos(random_phase)); spectrum[complexI].imag(real * std::sin(random_phase)); }; spectrum[0].imag(0); csound->InverseRealFFT(csound, ftp->ftable, N); // Normalize, MYFLT maximum = FL(0.0); for (int i = 0; i < N; ++i) { if (std::fabs(ftp->ftable[i]) > maximum) { maximum = std::fabs(ftp->ftable[i]); // warn(csound, "maximum at %d: %f\n", i, maximum); } } for (int i = 0; i < N; ++i) { ftp->ftable[i] /= maximum * ROOT2; } return OK; } static NGFENS padsynth_gens[] = {{(char *)"padsynth", padsynth_gen}, {NULL, NULL}}; PUBLIC NGFENS *csound_fgen_init(CSOUND *csound) { IGN(csound); return padsynth_gens; } };
lgpl-2.1
simplesamlphp/saml2
src/SAML2/XML/md/AdditionalMetadataLocation.php
3099
<?php declare(strict_types=1); namespace SimpleSAML\SAML2\XML\md; use DOMElement; use Exception; use SimpleSAML\Assert\Assert; use SimpleSAML\XML\Exception\InvalidDOMElementException; use SimpleSAML\XML\XMLStringElementTrait; use function trim; /** * Class representing SAML 2 metadata AdditionalMetadataLocation element. * * @package simplesamlphp/saml2 */ final class AdditionalMetadataLocation extends AbstractMdElement { use XMLStringElementTrait; /** * The namespace of this metadata. * * @var string */ protected string $namespace; /** * Create a new instance of AdditionalMetadataLocation * * @param string $namespace * @param string $location */ public function __construct(string $namespace, string $location) { $this->setNamespace($namespace); $this->setContent($location); } /** * Validate the content of the element. * * @param string $content The value to go in the XML textContent * @throws \Exception on failure * @return void */ protected function validateContent(/** @scrutinizer ignore-unused */ string $content): void { Assert::notEmpty($content); } /** * Collect the value of the namespace-property * * @return string */ public function getNamespace(): string { return $this->namespace; } /** * Set the value of the namespace-property * * @param string $namespace * @throws \SimpleSAML\Assert\AssertionFailedException */ protected function setNamespace(string $namespace): void { Assert::notEmpty($namespace, 'The namespace in AdditionalMetadataLocation must be a URI.'); $this->namespace = $namespace; } /** * Initialize an AdditionalMetadataLocation element. * * @param \DOMElement $xml The XML element we should load. * @return self * * @throws \SimpleSAML\XML\Exception\InvalidDOMElementException if the qualified name of the supplied element is wrong * @throws \SimpleSAML\XML\Exception\MissingAttributeException if the supplied element is missing any of the mandatory attributes */ public static function fromXML(DOMElement $xml): object { Assert::same($xml->localName, 'AdditionalMetadataLocation', InvalidDOMElementException::class); Assert::same($xml->namespaceURI, AdditionalMetadataLocation::NS, InvalidDOMElementException::class); $namespace = self::getAttribute($xml, 'namespace'); return new self($namespace, trim($xml->textContent)); } /** * Convert this AdditionalMetadataLocation to XML. * * @param \DOMElement|null $parent The element we should append to. * @return \DOMElement This AdditionalMetadataLocation-element. */ public function toXML(DOMElement $parent = null): DOMElement { $e = $this->instantiateParentElement($parent); $e->textContent = $this->content; $e->setAttribute('namespace', $this->namespace); return $e; } }
lgpl-2.1
pbondoer/xwiki-platform
xwiki-platform-core/xwiki-platform-query/xwiki-platform-query-manager/src/main/java/org/xwiki/query/internal/AbstractHiddenFilter.java
2467
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.query.internal; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import org.xwiki.component.annotation.InstantiationStrategy; import org.xwiki.component.descriptor.ComponentInstantiationStrategy; import org.xwiki.component.phase.Initializable; import org.xwiki.configuration.ConfigurationSource; /** * Base class for filtering hidden entities. * * @version $Id$ * @since 7.2M2 */ @InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP) public abstract class AbstractHiddenFilter extends AbstractWhereQueryFilter implements Initializable { /** * Used to retrieve user preference regarding hidden documents. */ @Inject @Named("user") private ConfigurationSource userPreferencesSource; /** * @see #initialize() */ private boolean isActive; /** * Sets the #isActive property, based on the user configuration. */ @Override public void initialize() { Integer preference = userPreferencesSource.getProperty("displayHiddenDocuments", Integer.class); isActive = preference == null || preference != 1; } @Override public String filterStatement(String statement, String language) { String result = statement; if (isActive) { result = filterHidden(statement, language); } return result; } protected abstract String filterHidden(String statement, String language); @Override public List filterResults(List results) { return results; } }
lgpl-2.1
stoq/stoqdrivers
stoqdrivers/abicomp.py
3896
# -*- Mode: Python; coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Stoqdrivers ## Copyright (C) 2007 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## 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. ## ## Author(s): Johan Dahlin <jdahlin@async.com.br> ## # This module implements the ABICOMP codec for python TABLE = { 'À': b'\xa1', 'Á': b'\xa2', 'Â': b'\xa3', 'Ã': b'\xa4', 'Ä': b'\xa5', 'Ç': b'\xa6', 'È': b'\xa7', 'É': b'\xa8', 'Ê': b'\xa9', 'Ë': b'\xaa', 'Ì': b'\xab', 'Í': b'\xac', 'Î': b'\xad', 'Ï': b'\xae', 'Ñ': b'\xaf', 'Ò': b'\xb0', 'Ó': b'\xb1', 'Ô': b'\xb2', 'Õ': b'\xb3', 'Ö': b'\xb4', 'Œ': b'\xb5', 'Ù': b'\xb6', 'Ú': b'\xb7', 'Û': b'\xb8', 'Ü': b'\xb9', 'Ÿ': b'\xba', '˝': b'\xbb', '£': b'\xbc', 'ʻ': b'\xbd', '°': b'\xbe', '¡': b'\xc0', 'à': b'\xc1', 'á': b'\xc2', 'â': b'\xc3', 'ã': b'\xc4', 'ä': b'\xc5', 'ç': b'\xc6', 'è': b'\xc7', 'é': b'\xc8', 'ê': b'\xc9', 'ë': b'\xca', 'ì': b'\xcb', 'í': b'\xcc', 'î': b'\xcd', 'ï': b'\xce', 'ñ': b'\xcf', 'ò': b'\xd0', 'ó': b'\xd1', 'ô': b'\xd2', 'õ': b'\xd3', 'ö': b'\xd4', 'œ': b'\xd5', 'ù': b'\xd6', 'ú': b'\xd7', 'û': b'\xd8', 'ü': b'\xd9', 'ÿ': b'\xda', 'ß': b'\xdb', 'ª': b'\xdc', 'º': b'\xdd', '¿': b'\xde', '±': b'\xdf', } RTABLE = dict([(v, k) for k, v in TABLE.items()]) def encode(input): """ Convert unicode to string. @param input: text to encode @type input: unicode @returns: encoded text @rtype: str """ return [TABLE.get(c) or c.encode() for c in input] def decode(input): """ Convert string in unicode. @param input: text to decode @type input: str @returns: decoded text @rtype: unicode """ # Iterating over bytes produces a sequence of integers bytes_ = [(c, bytes([c])) for c in input] return [RTABLE.get(b) or chr(i) for i, b in bytes_] def register_codec(): import codecs class Codec(codecs.Codec): def encode(self, input, errors='strict'): if not input: return b"", 0 output = encode(input) return b"".join(output), len(output) def decode(self, input, errors='strict'): if not input: return u"", 0 output = decode(input) return u"".join(output), len(output) class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamReader): pass def getregentry(encoding): if encoding != 'abicomp': return None return (Codec().encode, Codec().decode, StreamReader, StreamWriter) codecs.register(getregentry) def test(): register_codec() all = u''.join(TABLE.keys()) assert all == all.encode('abicomp').decode('abicomp') mixed = u'não dîz' assert mixed == mixed.encode('abicomp').decode('abicomp') if __name__ == '__main__': test()
lgpl-2.1
youfoh/webkit-efl
Source/WebKit2/UIProcess/qt/WebPopupMenuProxyQt.cpp
11423
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) * * 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebPopupMenuProxyQt.h" #include "PlatformPopupMenuData.h" #include "WebPopupItem.h" #include "qquickwebview_p.h" #include "qquickwebview_p_p.h" #include <QtCore/QAbstractListModel> #include <QtQml/QQmlContext> #include <QtQml/QQmlEngine> using namespace WebCore; namespace WebKit { static QHash<int, QByteArray> createRoleNamesHash(); class PopupMenuItemModel : public QAbstractListModel { Q_OBJECT public: enum Roles { GroupRole = Qt::UserRole, EnabledRole = Qt::UserRole + 1, SelectedRole = Qt::UserRole + 2, IsSeparatorRole = Qt::UserRole + 3 }; PopupMenuItemModel(const Vector<WebPopupItem>&, bool multiple); virtual int rowCount(const QModelIndex& parent = QModelIndex()) const { return m_items.size(); } virtual QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const; Q_INVOKABLE void select(int); int selectedOriginalIndex() const; bool multiple() const { return m_allowMultiples; } void toggleItem(int); Q_SIGNALS: void indexUpdated(); private: struct Item { Item(const WebPopupItem& webPopupItem, const QString& group, int originalIndex) : text(webPopupItem.m_text) , toolTip(webPopupItem.m_toolTip) , group(group) , originalIndex(originalIndex) , enabled(webPopupItem.m_isEnabled) , selected(webPopupItem.m_isSelected) , isSeparator(webPopupItem.m_type == WebPopupItem::Separator) { } QString text; QString toolTip; QString group; // Keep track of originalIndex because we don't add the label (group) items to our vector. int originalIndex; bool enabled; bool selected; bool isSeparator; }; void buildItems(const Vector<WebPopupItem>& webPopupItems); Vector<Item> m_items; int m_selectedModelIndex; bool m_allowMultiples; }; class ItemSelectorContextObject : public QObject { Q_OBJECT Q_PROPERTY(QRectF elementRect READ elementRect CONSTANT FINAL) Q_PROPERTY(QObject* items READ items CONSTANT FINAL) Q_PROPERTY(bool allowMultiSelect READ allowMultiSelect CONSTANT FINAL) public: ItemSelectorContextObject(const QRectF& elementRect, const Vector<WebPopupItem>&, bool multiple); QRectF elementRect() const { return m_elementRect; } PopupMenuItemModel* items() { return &m_items; } bool allowMultiSelect() { return m_items.multiple(); } Q_INVOKABLE void accept(int index = -1); Q_INVOKABLE void reject() { emit done(); } Q_INVOKABLE void dismiss() { emit done(); } Q_SIGNALS: void acceptedWithOriginalIndex(int); void done(); private Q_SLOTS: void onIndexUpdate(); private: QRectF m_elementRect; PopupMenuItemModel m_items; }; ItemSelectorContextObject::ItemSelectorContextObject(const QRectF& elementRect, const Vector<WebPopupItem>& webPopupItems, bool multiple) : m_elementRect(elementRect) , m_items(webPopupItems, multiple) { connect(&m_items, SIGNAL(indexUpdated()), SLOT(onIndexUpdate())); } void ItemSelectorContextObject::onIndexUpdate() { // Send the update for multi-select list. if (m_items.multiple()) emit acceptedWithOriginalIndex(m_items.selectedOriginalIndex()); } void ItemSelectorContextObject::accept(int index) { // If the index is not valid for multi-select lists, just hide the pop up as the selected indices have // already been sent. if ((index == -1) && m_items.multiple()) emit done(); else { if (index != -1) m_items.toggleItem(index); emit acceptedWithOriginalIndex(m_items.selectedOriginalIndex()); } } static QHash<int, QByteArray> createRoleNamesHash() { QHash<int, QByteArray> roles; roles[Qt::DisplayRole] = "text"; roles[Qt::ToolTipRole] = "tooltip"; roles[PopupMenuItemModel::GroupRole] = "group"; roles[PopupMenuItemModel::EnabledRole] = "enabled"; roles[PopupMenuItemModel::SelectedRole] = "selected"; roles[PopupMenuItemModel::IsSeparatorRole] = "isSeparator"; return roles; } PopupMenuItemModel::PopupMenuItemModel(const Vector<WebPopupItem>& webPopupItems, bool multiple) : m_selectedModelIndex(-1) , m_allowMultiples(multiple) { static QHash<int, QByteArray> roles = createRoleNamesHash(); setRoleNames(roles); buildItems(webPopupItems); } QVariant PopupMenuItemModel::data(const QModelIndex& index, int role) const { if (!index.isValid() || index.row() < 0 || index.row() >= m_items.size()) return QVariant(); const Item& item = m_items[index.row()]; if (item.isSeparator) { if (role == IsSeparatorRole) return true; return QVariant(); } switch (role) { case Qt::DisplayRole: return item.text; case Qt::ToolTipRole: return item.toolTip; case GroupRole: return item.group; case EnabledRole: return item.enabled; case SelectedRole: return item.selected; case IsSeparatorRole: return false; } return QVariant(); } void PopupMenuItemModel::select(int index) { toggleItem(index); emit indexUpdated(); } void PopupMenuItemModel::toggleItem(int index) { int oldIndex = m_selectedModelIndex; if (index < 0 || index >= m_items.size()) return; Item& item = m_items[index]; if (!item.enabled) return; m_selectedModelIndex = index; if (m_allowMultiples) item.selected = !item.selected; else { if (index == oldIndex) return; item.selected = true; if (oldIndex != -1) { Item& oldItem = m_items[oldIndex]; oldItem.selected = false; emit dataChanged(this->index(oldIndex), this->index(oldIndex)); } } emit dataChanged(this->index(index), this->index(index)); } int PopupMenuItemModel::selectedOriginalIndex() const { if (m_selectedModelIndex == -1) return -1; return m_items[m_selectedModelIndex].originalIndex; } void PopupMenuItemModel::buildItems(const Vector<WebPopupItem>& webPopupItems) { QString currentGroup; m_items.reserveInitialCapacity(webPopupItems.size()); for (int i = 0; i < webPopupItems.size(); i++) { const WebPopupItem& webPopupItem = webPopupItems[i]; if (webPopupItem.m_isLabel) { currentGroup = webPopupItem.m_text; continue; } if (webPopupItem.m_isSelected && !m_allowMultiples) m_selectedModelIndex = m_items.size(); m_items.append(Item(webPopupItem, currentGroup, i)); } } WebPopupMenuProxyQt::WebPopupMenuProxyQt(WebPopupMenuProxy::Client* client, QQuickWebView* webView) : WebPopupMenuProxy(client) , m_webView(webView) { } WebPopupMenuProxyQt::~WebPopupMenuProxyQt() { } void WebPopupMenuProxyQt::showPopupMenu(const IntRect& rect, WebCore::TextDirection, double, const Vector<WebPopupItem>& items, const PlatformPopupMenuData& data, int32_t) { m_selectionType = (data.multipleSelections) ? WebPopupMenuProxyQt::MultipleSelection : WebPopupMenuProxyQt::SingleSelection; const QRectF mappedRect= m_webView->mapRectFromWebContent(QRect(rect)); ItemSelectorContextObject* contextObject = new ItemSelectorContextObject(mappedRect, items, (m_selectionType == WebPopupMenuProxyQt::MultipleSelection)); createItem(contextObject); if (!m_itemSelector) { hidePopupMenu(); return; } QQuickWebViewPrivate::get(m_webView)->setDialogActive(true); } void WebPopupMenuProxyQt::hidePopupMenu() { m_itemSelector.clear(); QQuickWebViewPrivate::get(m_webView)->setDialogActive(false); m_context.clear(); if (m_client) { m_client->closePopupMenu(); invalidate(); } } void WebPopupMenuProxyQt::selectIndex(int index) { m_client->changeSelectedIndex(index); } void WebPopupMenuProxyQt::createItem(QObject* contextObject) { QQmlComponent* component = m_webView->experimental()->itemSelector(); if (!component) { delete contextObject; return; } createContext(component, contextObject); QObject* object = component->beginCreate(m_context.get()); if (!object) return; m_itemSelector = adoptPtr(qobject_cast<QQuickItem*>(object)); if (!m_itemSelector) return; connect(contextObject, SIGNAL(acceptedWithOriginalIndex(int)), SLOT(selectIndex(int))); // We enqueue these because they are triggered by m_itemSelector and will lead to its destruction. connect(contextObject, SIGNAL(done()), SLOT(hidePopupMenu()), Qt::QueuedConnection); if (m_selectionType == WebPopupMenuProxyQt::SingleSelection) connect(contextObject, SIGNAL(acceptedWithOriginalIndex(int)), SLOT(hidePopupMenu()), Qt::QueuedConnection); QQuickWebViewPrivate::get(m_webView)->addAttachedPropertyTo(m_itemSelector.get()); m_itemSelector->setParentItem(m_webView); // Only fully create the component once we've set both a parent // and the needed context and attached properties, so that the // dialog can do useful stuff in Component.onCompleted(). component->completeCreate(); } void WebPopupMenuProxyQt::createContext(QQmlComponent* component, QObject* contextObject) { QQmlContext* baseContext = component->creationContext(); if (!baseContext) baseContext = QQmlEngine::contextForObject(m_webView); m_context = adoptPtr(new QQmlContext(baseContext)); contextObject->setParent(m_context.get()); m_context->setContextProperty(QLatin1String("model"), contextObject); m_context->setContextObject(contextObject); } } // namespace WebKit // Since we define QObjects in WebPopupMenuProxyQt.cpp, this will trigger moc to run on .cpp. #include "WebPopupMenuProxyQt.moc" // And we can't compile the moc for WebPopupMenuProxyQt.h by itself, since it doesn't include "config.h" #include "moc_WebPopupMenuProxyQt.cpp"
lgpl-2.1
vityurkiv/Ox
libmesh/src/mesh/mesh_base.C
22973
// The libMesh Finite Element Library. // Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute 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. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // library configuration #include "libmesh/libmesh_config.h" // C++ includes #include <algorithm> // for std::min #include <map> // for std::multimap #include <sstream> // for std::ostringstream // Local includes #include "libmesh/boundary_info.h" #include "libmesh/elem.h" #include "libmesh/ghost_point_neighbors.h" #include "libmesh/mesh_base.h" #include "libmesh/mesh_communication.h" #include "libmesh/mesh_tools.h" #include "libmesh/parallel.h" #include "libmesh/partitioner.h" #include "libmesh/point_locator_base.h" #include "libmesh/threads.h" #include LIBMESH_INCLUDE_UNORDERED_MAP namespace libMesh { // ------------------------------------------------------------ // MeshBase class member functions MeshBase::MeshBase (const Parallel::Communicator & comm_in, unsigned char d) : ParallelObject (comm_in), boundary_info (new BoundaryInfo(*this)), _n_parts (1), _is_prepared (false), _point_locator (), _partitioner (), #ifdef LIBMESH_ENABLE_UNIQUE_ID _next_unique_id(DofObject::invalid_unique_id), #endif _skip_partitioning(libMesh::on_command_line("--skip-partitioning")), _skip_renumber_nodes_and_elements(false), _spatial_dimension(d), _default_ghosting(new GhostPointNeighbors(*this)) { _elem_dims.insert(d); _ghosting_functors.insert(_default_ghosting.get()); libmesh_assert_less_equal (LIBMESH_DIM, 3); libmesh_assert_greater_equal (LIBMESH_DIM, d); libmesh_assert (libMesh::initialized()); } #ifndef LIBMESH_DISABLE_COMMWORLD MeshBase::MeshBase (unsigned char d) : ParallelObject (CommWorld), boundary_info (new BoundaryInfo(*this)), _n_parts (1), _is_prepared (false), _point_locator (), _partitioner (), #ifdef LIBMESH_ENABLE_UNIQUE_ID _next_unique_id(DofObject::invalid_unique_id), #endif _skip_partitioning(libMesh::on_command_line("--skip-partitioning")), _skip_renumber_nodes_and_elements(false), _spatial_dimension(d), _default_ghosting(new GhostPointNeighbors(*this)) { _elem_dims.insert(d); _ghosting_functors.insert(_default_ghosting.get()); libmesh_assert_less_equal (LIBMESH_DIM, 3); libmesh_assert_greater_equal (LIBMESH_DIM, d); libmesh_assert (libMesh::initialized()); } #endif // !LIBMESH_DISABLE_COMMWORLD MeshBase::MeshBase (const MeshBase & other_mesh) : ParallelObject (other_mesh), boundary_info (new BoundaryInfo(*this)), _n_parts (other_mesh._n_parts), _is_prepared (other_mesh._is_prepared), _point_locator (), _partitioner (), #ifdef LIBMESH_ENABLE_UNIQUE_ID _next_unique_id(other_mesh._next_unique_id), #endif _skip_partitioning(libMesh::on_command_line("--skip-partitioning")), _skip_renumber_nodes_and_elements(false), _elem_dims(other_mesh._elem_dims), _spatial_dimension(other_mesh._spatial_dimension), _default_ghosting(new GhostPointNeighbors(*this)), _ghosting_functors(other_mesh._ghosting_functors) { // Make sure we don't accidentally delete the other mesh's default // ghosting functor; we'll use our own if that's needed. if (other_mesh._ghosting_functors.count (other_mesh._default_ghosting.get())) { _ghosting_functors.erase(other_mesh._default_ghosting.get()); _ghosting_functors.insert(_default_ghosting.get()); } if(other_mesh._partitioner.get()) { _partitioner = other_mesh._partitioner->clone(); } } MeshBase::~MeshBase() { this->clear(); libmesh_exceptionless_assert (!libMesh::closed()); } unsigned int MeshBase::mesh_dimension() const { if (!_elem_dims.empty()) return cast_int<unsigned int>(*_elem_dims.rbegin()); return 0; } unsigned int MeshBase::spatial_dimension () const { return cast_int<unsigned int>(_spatial_dimension); } void MeshBase::set_spatial_dimension(unsigned char d) { // The user can set the _spatial_dimension however they wish, // libMesh will only *increase* the spatial dimension, however, // never decrease it. _spatial_dimension = d; } void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements, const bool skip_find_neighbors) { parallel_object_only(); libmesh_assert(this->comm().verify(this->is_serial())); // A distributed mesh may have processors with no elements (or // processors with no elements of higher dimension, if we ever // support mixed-dimension meshes), but we want consistent // mesh_dimension anyways. // // cache_elem_dims() should get the elem_dimensions() and // mesh_dimension() correct later, and we don't need it earlier. // Renumber the nodes and elements so that they in contiguous // blocks. By default, _skip_renumber_nodes_and_elements is false. // // We may currently change that by passing // skip_renumber_nodes_and_elements==true to this function, but we // should use the allow_renumbering() accessor instead. // // Instances where you if prepare_for_use() should not renumber the nodes // and elements include reading in e.g. an xda/r or gmv file. In // this case, the ordering of the nodes may depend on an accompanying // solution, and the node ordering cannot be changed. if (skip_renumber_nodes_and_elements) { libmesh_deprecated(); this->allow_renumbering(false); } // Mesh modification operations might not leave us with consistent // id counts, but our partitioner might need that consistency. if(!_skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); else this->update_parallel_id_counts(); // Let all the elements find their neighbors if(!skip_find_neighbors) this->find_neighbors(); // The user may have set boundary conditions. We require that the // boundary conditions were set consistently. Because we examine // neighbors when evaluating non-raw boundary condition IDs, this // assert is only valid when our neighbor links are in place. #ifdef DEBUG MeshTools::libmesh_assert_valid_boundary_ids(*this); #endif // Search the mesh for all the dimensions of the elements // and cache them. this->cache_elem_dims(); // Search the mesh for elements that have a neighboring element // of dim+1 and set that element as the interior parent this->detect_interior_parents(); // Fix up node unique ids in case mesh generation code didn't take // exceptional care to do so. // MeshCommunication().make_node_unique_ids_parallel_consistent(*this); // We're going to still require that mesh generation code gets // element unique ids consistent. #if defined(DEBUG) && defined(LIBMESH_ENABLE_UNIQUE_ID) MeshTools::libmesh_assert_valid_unique_ids(*this); #endif // Reset our PointLocator. Any old locator is invalidated any time // the elements in the underlying elements in the mesh have changed, // so we clear it here. this->clear_point_locator(); // Allow our GhostingFunctor objects to reinit if necessary. // Do this before partitioning and redistributing, and before // deleting remote elements. std::set<GhostingFunctor *>::iterator gf_it = this->ghosting_functors_begin(); const std::set<GhostingFunctor *>::iterator gf_end = this->ghosting_functors_end(); for (; gf_it != gf_end; ++gf_it) { GhostingFunctor *gf = *gf_it; libmesh_assert(gf); gf->mesh_reinit(); } // Partition the mesh. this->partition(); // If we're using DistributedMesh, we'll want it parallelized. this->delete_remote_elements(); if(!_skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); // The mesh is now prepared for use. _is_prepared = true; #if defined(DEBUG) && defined(LIBMESH_ENABLE_UNIQUE_ID) MeshTools::libmesh_assert_valid_unique_ids(*this); #endif } void MeshBase::clear () { // Reset the number of partitions _n_parts = 1; // Reset the _is_prepared flag _is_prepared = false; // Clear boundary information this->get_boundary_info().clear(); // Clear element dimensions _elem_dims.clear(); // Clear our point locator. this->clear_point_locator(); } void MeshBase::remove_ghosting_functor(GhostingFunctor & ghosting_functor) { // We should only be trying to remove ghosting functors we actually // have libmesh_assert(_ghosting_functors.count(&ghosting_functor)); _ghosting_functors.erase(&ghosting_functor); } void MeshBase::subdomain_ids (std::set<subdomain_id_type> & ids) const { // This requires an inspection on every processor parallel_object_only(); ids.clear(); const_element_iterator el = this->active_local_elements_begin(); const_element_iterator end = this->active_local_elements_end(); for (; el!=end; ++el) ids.insert((*el)->subdomain_id()); // Some subdomains may only live on other processors this->comm().set_union(ids); } subdomain_id_type MeshBase::n_subdomains() const { // This requires an inspection on every processor parallel_object_only(); std::set<subdomain_id_type> ids; this->subdomain_ids (ids); return cast_int<subdomain_id_type>(ids.size()); } dof_id_type MeshBase::n_nodes_on_proc (const processor_id_type proc_id) const { // We're either counting a processor's nodes or unpartitioned // nodes libmesh_assert (proc_id < this->n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<dof_id_type>(std::distance (this->pid_nodes_begin(proc_id), this->pid_nodes_end (proc_id))); } dof_id_type MeshBase::n_elem_on_proc (const processor_id_type proc_id) const { // We're either counting a processor's elements or unpartitioned // elements libmesh_assert (proc_id < this->n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<dof_id_type>(std::distance (this->pid_elements_begin(proc_id), this->pid_elements_end (proc_id))); } dof_id_type MeshBase::n_active_elem_on_proc (const processor_id_type proc_id) const { libmesh_assert_less (proc_id, this->n_processors()); return static_cast<dof_id_type>(std::distance (this->active_pid_elements_begin(proc_id), this->active_pid_elements_end (proc_id))); } dof_id_type MeshBase::n_sub_elem () const { dof_id_type ne=0; const_element_iterator el = this->elements_begin(); const const_element_iterator end = this->elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } dof_id_type MeshBase::n_active_sub_elem () const { dof_id_type ne=0; const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } std::string MeshBase::get_info() const { std::ostringstream oss; oss << " Mesh Information:" << '\n'; if (!_elem_dims.empty()) { oss << " elem_dimensions()={"; std::copy(_elem_dims.begin(), --_elem_dims.end(), // --end() is valid if the set is non-empty std::ostream_iterator<unsigned int>(oss, ", ")); oss << cast_int<unsigned int>(*_elem_dims.rbegin()); oss << "}\n"; } oss << " spatial_dimension()=" << this->spatial_dimension() << '\n' << " n_nodes()=" << this->n_nodes() << '\n' << " n_local_nodes()=" << this->n_local_nodes() << '\n' << " n_elem()=" << this->n_elem() << '\n' << " n_local_elem()=" << this->n_local_elem() << '\n' #ifdef LIBMESH_ENABLE_AMR << " n_active_elem()=" << this->n_active_elem() << '\n' #endif << " n_subdomains()=" << static_cast<std::size_t>(this->n_subdomains()) << '\n' << " n_partitions()=" << static_cast<std::size_t>(this->n_partitions()) << '\n' << " n_processors()=" << static_cast<std::size_t>(this->n_processors()) << '\n' << " n_threads()=" << static_cast<std::size_t>(libMesh::n_threads()) << '\n' << " processor_id()=" << static_cast<std::size_t>(this->processor_id()) << '\n'; return oss.str(); } void MeshBase::print_info(std::ostream & os) const { os << this->get_info() << std::endl; } std::ostream & operator << (std::ostream & os, const MeshBase & m) { m.print_info(os); return os; } void MeshBase::partition (const unsigned int n_parts) { // If we get here and we have unpartitioned elements, we need that // fixed. if (this->n_unpartitioned_elem() > 0) { libmesh_assert (partitioner().get()); libmesh_assert (this->is_serial()); partitioner()->partition (*this, n_parts); } // NULL partitioner means don't repartition // Non-serial meshes may not be ready for repartitioning here. else if(!skip_partitioning() && partitioner().get()) { partitioner()->partition (*this, n_parts); } else { // Adaptive coarsening may have "orphaned" nodes on processors // whose elements no longer share them. We need to check for // and possibly fix that. Partitioner::set_node_processor_ids(*this); // Make sure locally cached partition count this->recalculate_n_partitions(); // Make sure any other locally cached data is correct this->update_post_partitioning(); } } unsigned int MeshBase::recalculate_n_partitions() { // This requires an inspection on every processor parallel_object_only(); const_element_iterator el = this->active_local_elements_begin(); const_element_iterator end = this->active_local_elements_end(); unsigned int max_proc_id=0; for (; el!=end; ++el) max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id())); // The number of partitions is one more than the max processor ID. _n_parts = max_proc_id+1; this->comm().max(_n_parts); return _n_parts; } const PointLocatorBase & MeshBase::point_locator () const { libmesh_deprecated(); if (_point_locator.get() == libmesh_nullptr) { // PointLocator construction may not be safe within threads libmesh_assert(!Threads::in_threads); _point_locator.reset (PointLocatorBase::build(TREE_ELEMENTS, *this).release()); } return *_point_locator; } UniquePtr<PointLocatorBase> MeshBase::sub_point_locator () const { // If there's no master point locator, then we need one. if (_point_locator.get() == libmesh_nullptr) { // PointLocator construction may not be safe within threads libmesh_assert(!Threads::in_threads); // And it may require parallel communication parallel_object_only(); _point_locator.reset (PointLocatorBase::build(TREE_ELEMENTS, *this).release()); } // Otherwise there was a master point locator, and we can grab a // sub-locator easily. return PointLocatorBase::build(TREE_ELEMENTS, *this, _point_locator.get()); } void MeshBase::clear_point_locator () { _point_locator.reset(libmesh_nullptr); } std::string & MeshBase::subdomain_name(subdomain_id_type id) { return _block_id_to_name[id]; } const std::string & MeshBase::subdomain_name(subdomain_id_type id) const { // An empty string to return when no matching subdomain name is found static const std::string empty; std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.find(id); if (iter == _block_id_to_name.end()) return empty; else return iter->second; } subdomain_id_type MeshBase::get_id_by_name(const std::string & name) const { // Linear search over the map values. std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.begin(), end_iter = _block_id_to_name.end(); for ( ; iter != end_iter; ++iter) if (iter->second == name) return iter->first; // If we made it here without returning, we don't have a subdomain // with the requested name, so return Elem::invalid_subdomain_id. return Elem::invalid_subdomain_id; } void MeshBase::cache_elem_dims() { // This requires an inspection on every processor parallel_object_only(); // Need to clear _elem_dims first in case all elements of a // particular dimension have been deleted. _elem_dims.clear(); const_element_iterator el = this->active_elements_begin(); const_element_iterator end = this->active_elements_end(); for (; el!=end; ++el) _elem_dims.insert((*el)->dim()); // Some different dimension elements may only live on other processors this->comm().set_union(_elem_dims); // If the largest element dimension found is larger than the current // _spatial_dimension, increase _spatial_dimension. unsigned int max_dim = this->mesh_dimension(); if (max_dim > _spatial_dimension) _spatial_dimension = cast_int<unsigned char>(max_dim); // _spatial_dimension may need to increase from 1->2 or 2->3 if the // mesh is full of 1D elements but they are not x-aligned, or the // mesh is full of 2D elements but they are not in the x-y plane. // If the mesh is x-aligned or x-y planar, we will end up checking // every node's coordinates and not breaking out of the loop // early... if (_spatial_dimension < 3) { const_node_iterator node_it = this->nodes_begin(); const_node_iterator node_end = this->nodes_end(); for (; node_it != node_end; ++node_it) { Node & node = **node_it; #if LIBMESH_DIM > 1 // Note: the exact floating point comparison is intentional, // we don't want to get tripped up by tolerances. if (node(1) != 0.) { _spatial_dimension = 2; #if LIBMESH_DIM == 2 // If libmesh is compiled in 2D mode, this is the // largest spatial dimension possible so we can break // out. break; #endif } #endif #if LIBMESH_DIM > 2 if (node(2) != 0.) { // Spatial dimension can't get any higher than this, so // we can break out. _spatial_dimension = 3; break; } #endif } } } void MeshBase::detect_interior_parents() { // This requires an inspection on every processor parallel_object_only(); // Check if the mesh contains mixed dimensions. If so, then set interior parents, otherwise return. if (this->elem_dimensions().size() == 1) return; //This map will be used to set interior parents LIBMESH_BEST_UNORDERED_MAP<dof_id_type, std::vector<dof_id_type> > node_to_elem; const_element_iterator el = this->active_elements_begin(); const_element_iterator end = this->active_elements_end(); for (; el!=end; ++el) { const Elem * elem = *el; // Populating the node_to_elem map, same as MeshTools::build_nodes_to_elem_map for (unsigned int n=0; n<elem->n_vertices(); n++) { libmesh_assert_less (elem->id(), this->max_elem_id()); node_to_elem[elem->node_id(n)].push_back(elem->id()); } } // Automatically set interior parents el = this->elements_begin(); for (; el!=end; ++el) { Elem * element = *el; // Ignore an 3D element or an element that already has an interior parent if (element->dim()>=LIBMESH_DIM || element->interior_parent()) continue; // Start by generating a SET of elements that are dim+1 to the current // element at each vertex of the current element, thus ignoring interior nodes. // If one of the SET of elements is empty, then we will not have an interior parent // since an interior parent must be connected to all vertices of the current element std::vector< std::set<dof_id_type> > neighbors( element->n_vertices() ); bool found_interior_parents = false; for (dof_id_type n=0; n < element->n_vertices(); n++) { std::vector<dof_id_type> & element_ids = node_to_elem[element->node_id(n)]; for (std::vector<dof_id_type>::iterator e_it = element_ids.begin(); e_it != element_ids.end(); e_it++) { dof_id_type eid = *e_it; if (this->elem_ref(eid).dim() == element->dim()+1) neighbors[n].insert(eid); } if (neighbors[n].size()>0) { found_interior_parents = true; } else { // We have found an empty set, no reason to continue // Ensure we set this flag to false before the break since it could have // been set to true for previous vertex found_interior_parents = false; break; } } // If we have successfully generated a set of elements for each vertex, we will compare // the set for vertex 0 will the sets for the vertices until we find a id that exists in // all sets. If found, this is our an interior parent id. The interior parent id found // will be the lowest element id if there is potential for multiple interior parents. if (found_interior_parents) { std::set<dof_id_type> & neighbors_0 = neighbors[0]; for (std::set<dof_id_type>::iterator e_it = neighbors_0.begin(); e_it != neighbors_0.end(); e_it++) { found_interior_parents=false; dof_id_type interior_parent_id = *e_it; for (dof_id_type n=1; n < element->n_vertices(); n++) { if (neighbors[n].find(interior_parent_id)!=neighbors[n].end()) { found_interior_parents=true; } else { found_interior_parents=false; break; } } if (found_interior_parents) { element->set_interior_parent(this->elem_ptr(interior_parent_id)); break; } } } } } } // namespace libMesh
lgpl-2.1
GhostMonk3408/MidgarCrusade
src/main/java/fr/toss/FF7itemsb/itemb184.java
159
package fr.toss.FF7itemsb; public class itemb184 extends FF7itemsbbase { public itemb184(int id) { super(id); setUnlocalizedName("itemb184"); } }
lgpl-2.1
xiangke/pycopia
mibs/pycopia/mibs/NETWORK_SERVICES_MIB.py
9373
# python # This file is generated by a program (mib2py). Any edits will be lost. from pycopia.aid import Enum import pycopia.SMI.Basetypes Range = pycopia.SMI.Basetypes.Range Ranges = pycopia.SMI.Basetypes.Ranges from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, NodeObject, ModuleObject, GroupObject # imports from SNMPv2_SMI import OBJECT_TYPE, Counter32, Gauge32, MODULE_IDENTITY, mib_2 from SNMPv2_CONF import MODULE_COMPLIANCE, OBJECT_GROUP from SNMPv2_TC import TimeStamp, TEXTUAL_CONVENTION from SNMP_FRAMEWORK_MIB import SnmpAdminString class NETWORK_SERVICES_MIB(ModuleObject): path = '/usr/share/snmp/mibs/ietf/NETWORK-SERVICES-MIB' conformance = 5 name = 'NETWORK-SERVICES-MIB' language = 2 description = 'The MIB module describing network service applications' # nodes class application(NodeObject): status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27]) name = 'application' class applConformance(NodeObject): OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 3]) name = 'applConformance' class applGroups(NodeObject): OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 3, 1]) name = 'applGroups' class applCompliances(NodeObject): OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 3, 2]) name = 'applCompliances' class applTCPProtoID(NodeObject): OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 4]) name = 'applTCPProtoID' class applUDPProtoID(NodeObject): OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 5]) name = 'applUDPProtoID' # macros # types class DistinguishedName(pycopia.SMI.Basetypes.OctetString): status = 1 ranges = Ranges(Range(0, 255)) format = '255a' class URLString(pycopia.SMI.Basetypes.OctetString): status = 1 ranges = Ranges(Range(0, 255)) format = '255a' # scalars # columns class applIndex(ColumnObject): access = 2 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 1]) syntaxobject = pycopia.SMI.Basetypes.Integer32 class applName(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 2]) syntaxobject = SnmpAdminString class applDirectoryName(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 3]) syntaxobject = DistinguishedName class applVersion(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 4]) syntaxobject = SnmpAdminString class applUptime(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 5]) syntaxobject = pycopia.SMI.Basetypes.TimeStamp class applOperStatus(ColumnObject): status = 1 access = 4 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 6]) syntaxobject = pycopia.SMI.Basetypes.Enumeration enumerations = [Enum(1, 'up'), Enum(2, 'down'), Enum(3, 'halted'), Enum(4, 'congested'), Enum(5, 'restarting'), Enum(6, 'quiescing')] class applLastChange(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 7]) syntaxobject = pycopia.SMI.Basetypes.TimeStamp class applInboundAssociations(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 8]) syntaxobject = pycopia.SMI.Basetypes.Gauge32 class applOutboundAssociations(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 9]) syntaxobject = pycopia.SMI.Basetypes.Gauge32 class applAccumulatedInboundAssociations(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 10]) syntaxobject = pycopia.SMI.Basetypes.Counter32 class applAccumulatedOutboundAssociations(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 11]) syntaxobject = pycopia.SMI.Basetypes.Counter32 class applLastInboundActivity(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 12]) syntaxobject = pycopia.SMI.Basetypes.TimeStamp class applLastOutboundActivity(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 13]) syntaxobject = pycopia.SMI.Basetypes.TimeStamp class applRejectedInboundAssociations(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 14]) syntaxobject = pycopia.SMI.Basetypes.Counter32 class applFailedOutboundAssociations(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 15]) syntaxobject = pycopia.SMI.Basetypes.Counter32 class applDescription(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 16]) syntaxobject = SnmpAdminString class applURL(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1, 17]) syntaxobject = URLString class assocIndex(ColumnObject): access = 2 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 2, 1, 1]) syntaxobject = pycopia.SMI.Basetypes.Integer32 class assocRemoteApplication(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 2, 1, 2]) syntaxobject = SnmpAdminString class assocApplicationProtocol(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 2, 1, 3]) syntaxobject = pycopia.SMI.Basetypes.ObjectIdentifier class assocApplicationType(ColumnObject): status = 1 access = 4 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 2, 1, 4]) syntaxobject = pycopia.SMI.Basetypes.Enumeration enumerations = [Enum(1, 'uainitiator'), Enum(2, 'uaresponder'), Enum(3, 'peerinitiator'), Enum(4, 'peerresponder')] class assocDuration(ColumnObject): access = 4 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 2, 1, 5]) syntaxobject = pycopia.SMI.Basetypes.TimeStamp # rows class applEntry(RowObject): status = 1 index = pycopia.SMI.Objects.IndexObjects([applIndex], False) OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 1, 1]) access = 2 columns = {'applIndex': applIndex, 'applName': applName, 'applDirectoryName': applDirectoryName, 'applVersion': applVersion, 'applUptime': applUptime, 'applOperStatus': applOperStatus, 'applLastChange': applLastChange, 'applInboundAssociations': applInboundAssociations, 'applOutboundAssociations': applOutboundAssociations, 'applAccumulatedInboundAssociations': applAccumulatedInboundAssociations, 'applAccumulatedOutboundAssociations': applAccumulatedOutboundAssociations, 'applLastInboundActivity': applLastInboundActivity, 'applLastOutboundActivity': applLastOutboundActivity, 'applRejectedInboundAssociations': applRejectedInboundAssociations, 'applFailedOutboundAssociations': applFailedOutboundAssociations, 'applDescription': applDescription, 'applURL': applURL} class assocEntry(RowObject): status = 1 index = pycopia.SMI.Objects.IndexObjects([applIndex, assocIndex], False) OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 2, 1]) access = 2 columns = {'assocIndex': assocIndex, 'assocRemoteApplication': assocRemoteApplication, 'assocApplicationProtocol': assocApplicationProtocol, 'assocApplicationType': assocApplicationType, 'assocDuration': assocDuration} # notifications (traps) # groups class applRFC2248Group(GroupObject): access = 2 status = 2 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 3, 1, 3]) group = [applName, applVersion, applUptime, applOperStatus, applLastChange, applInboundAssociations, applOutboundAssociations, applAccumulatedInboundAssociations, applAccumulatedOutboundAssociations, applLastInboundActivity, applLastOutboundActivity, applRejectedInboundAssociations, applFailedOutboundAssociations, applDescription, applURL] class assocRFC2248Group(GroupObject): access = 2 status = 2 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 3, 1, 4]) group = [assocRemoteApplication, assocApplicationProtocol, assocApplicationType, assocDuration] class applRFC2788Group(GroupObject): access = 2 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 3, 1, 5]) group = [applName, applDirectoryName, applVersion, applUptime, applOperStatus, applLastChange, applInboundAssociations, applOutboundAssociations, applAccumulatedInboundAssociations, applAccumulatedOutboundAssociations, applLastInboundActivity, applLastOutboundActivity, applRejectedInboundAssociations, applFailedOutboundAssociations, applDescription, applURL] class assocRFC2788Group(GroupObject): access = 2 status = 1 OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 27, 3, 1, 6]) group = [assocRemoteApplication, assocApplicationProtocol, assocApplicationType, assocDuration] # capabilities # special additions # Add to master OIDMAP. from pycopia import SMI SMI.update_oidmap(__name__)
lgpl-2.1
EgorZhuk/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/modules/parser/ext/factory/templates/DateFieldTemplateDescription.java
1422
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.templates; import org.pentaho.reporting.engine.classic.core.filter.templates.DateFieldTemplate; /** * A date field template description. * * @author Thomas Morgner */ public class DateFieldTemplateDescription extends AbstractTemplateDescription { /** * Creates a new template description. * * @param name * the name. */ public DateFieldTemplateDescription( final String name ) { super( name, DateFieldTemplate.class, true ); } }
lgpl-2.1
neo4j-attic/yajsw
src/ahessian/org/rzo/netty/ahessian/rpc/message/OutputProducer.java
4300
package org.rzo.netty.ahessian.rpc.message; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Timer; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.rzo.netty.ahessian.stopable.StopableHandler; import org.rzo.netty.ahessian.utils.TimedBlockingPriorityQueue; public class OutputProducer extends SimpleChannelHandler implements StopableHandler { private TimedBlockingPriorityQueue<MessageEvent> _pendingCalls = new TimedBlockingPriorityQueue("OutputProducer"); AtomicInteger _producerThreadsCount = new AtomicInteger(0); Lock _lock = new ReentrantLock(); Executor _executor; Timer _timer; List<MessageEvent> _pendingTermination = new ArrayList<MessageEvent>(); volatile boolean _stop = false; public OutputProducer(Executor executor) { _executor = executor; } public void writeRequested(final ChannelHandlerContext ctx, MessageEvent e) throws Exception { //System.out.println(Thread.currentThread()+ " OutputProducer writeRequesed"); GroupedMessage m = (GroupedMessage) e.getMessage(); _pendingCalls.put(e, m.getGroup()); if (_producerThreadsCount.get() < 2) _executor.execute(new Runnable() { public void run() { produce(ctx); } }); } @Override public void channelConnected(final ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); _executor.execute(new Runnable() { public void run() { for (Iterator it = _pendingTermination.iterator(); it.hasNext(); ) { _lock.lock(); try { if (_stop) return; MessageEvent e = (MessageEvent) it.next(); GroupedMessage m = (GroupedMessage) e.getMessage(); _pendingCalls.put(e, m.getGroup()); } catch (Exception ex) { ex.printStackTrace(); } finally { _lock.unlock(); } } produce(ctx); } }); } private void produce(ChannelHandlerContext ctx) { if (_stop) return; if (_producerThreadsCount.incrementAndGet() > 2) { // there is already a thread consuming and another at the gate to consume the last chunk _producerThreadsCount.decrementAndGet(); return; } //System.out.println(Thread.currentThread()+" produce"); boolean produced = false; _lock.lock(); try { MessageEvent toSend = null; while (ctx.getChannel().isConnected() && _pendingCalls.size() > 0) { if (_stop) return; try { toSend = _pendingCalls.take(); //System.out.println(Thread.currentThread()+ " OutputProducer sendMessage"); ctx.sendDownstream(toSend); _pendingTermination.add(toSend); produced = true; } catch (Exception ex) { ex.printStackTrace(); _pendingCalls.put(toSend, ((GroupedMessage) toSend.getMessage()).getGroup()); } } if (produced && _pendingCalls.size() == 0) { //System.out.println(Thread.currentThread()+ " OutputProducer flush"); Channels.write(ctx, Channels.future(ctx.getChannel()), new FlushRequestMessage()); for (Iterator it = _pendingTermination.iterator(); it.hasNext(); ) { if (_stop) return; try { MessageEvent e = (MessageEvent) it.next(); GroupedMessage m = (GroupedMessage) e.getMessage(); it.remove(); e.getFuture().setSuccess(); } catch (Exception ex) { ex.printStackTrace(); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { _producerThreadsCount.decrementAndGet(); _lock.unlock(); } } public boolean isStopEnabled() { return true; } public void setStopEnabled(boolean stopEnabled) { } public void stop() { _stop = true; for (MessageEvent event : _pendingCalls) { event.getFuture().cancel(); } } }
lgpl-2.1
egbertbouman/tribler-g
Tribler/Tools/LoggingTest.py
1076
import logging from logging.handlers import SocketHandler, DEFAULT_TCP_LOGGING_PORT import time import random rootlogger = logging.getLogger('') rootlogger.setLevel(logging.DEBUG) logger1 = logging.getLogger('myapp.area1') #logger2 = logging.getLogger('myapp.area2') socketh = SocketHandler('gamecast.no-ip.org', DEFAULT_TCP_LOGGING_PORT) rootlogger.addHandler(socketh) def foo(): print 'foo()' x = 0 try: y = 10 / x except Exception, e: pass #logging.getLogger('foo').exception("Please don't try to divide by zero") while True: foo() #logger1.debug('Quick zephyrs blow, vexing daft Jim.') #logger1.info('How quickly daft jumping zebras vex.') #logger2.warning('Jail zesty vixen who grabbed pay from quack.') #logger2.error('The five boxing wizards jump quickly.') d = {'event_type' : 'MSG_SEND', 'ip' : '32.123.54.32', 'port' : 123, 'permid' : 'WFDd45fDDW'} msg = '.. to .. with payload ..' logger1.info(msg, extra=d) time.sleep(random.random()*10)
lgpl-2.1
delonnewman/java-posix
LockFile.java
2328
package posix; import java.io.*; /** A simple unix style lock file. The first process to append its process id owns the lock. The lock is stale if the process id no longer exists. There is a race condition when removing stale locks. */ public class LockFile { private java.io.File lockfile; private void checkPID(int mypid) throws IOException { BufferedReader lf = new BufferedReader(new FileReader(lockfile)); String p = lf.readLine(); if (p != null) { try { int pid = Integer.parseInt(p.trim()); if (pid != mypid && IPC.isPidValid(pid)) throw new IOException("Valid lockfile exists: PID " + pid + " - " + lockfile); } catch (NumberFormatException x) { } } lf.close(); } /** Create a unix style lockfile. @param name the unix path name of the lockfile @throws IOException if the lockfile is already owned or cannot be created */ public LockFile(String name) throws IOException { lockfile = new java.io.File(name); synchronized (LockFile.class) { boolean trunc = lockfile.exists(); if (trunc) checkPID(0); // open for appending PrintWriter lf = new PrintWriter(new FileWriter(name,!trunc)); int pid = IPC.pid; lf.println(pid); lf.close(); checkPID(pid); } } /** Remove the lockfile when garbage collected. */ public void finalize() { final java.io.File lockfile = this.lockfile; delete(); if (lockfile != null) System.err.println("Released LockFile: " + lockfile); } /** Remove the lockfile. */ public synchronized void delete() { if (lockfile != null) { lockfile.delete(); lockfile = null; } } /** Exercise LockFile. Create one or more lock files from command line, print an error if they cannot all be locked at once, and remove them when user presses enter. */ public static void main(String[] argv) throws IOException { LockFile[] locks = new LockFile[argv.length]; try { for (int i = 0; i < argv.length; ++i) { locks[i] = new LockFile(argv[i]); } System.in.read(); } catch (IOException x) { System.err.println(x); System.exit(1); } finally { for (int i = 0; i < locks.length; ++i) if (locks[i] != null) locks[i].delete(); } } }
lgpl-2.1
bedrin/kerb4j
kerb4j-server/kerb4j-server-common/src/main/java/com/kerb4j/server/marshall/pac/PacSignature.java
890
package com.kerb4j.server.marshall.pac; import com.kerb4j.server.marshall.Kerb4JException; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; public class PacSignature { private int type; private byte[] checksum; public PacSignature(byte[] data) throws Kerb4JException { try { PacDataInputStream bufferStream = new PacDataInputStream(new DataInputStream( new ByteArrayInputStream(data))); type = bufferStream.readInt(); checksum = new byte[bufferStream.available()]; bufferStream.readFully(checksum); } catch (IOException e) { throw new Kerb4JException("pac.signature.malformed", null, e); } } public int getType() { return type; } public byte[] getChecksum() { return checksum; } }
lgpl-2.1
concord-consortium/framework
src/org/concord/framework/otrunk/view/OTViewContext.java
2688
/** * */ package org.concord.framework.otrunk.view; import org.concord.framework.otrunk.OTObject; /** * Use this interface to access services provided to a view. * * @author scott * */ public interface OTViewContext { /** * Use this method to get a service for example: * OTFrameManager frameManager = * (OTFrameManager)serviceProvider.getViewService(OTFrameManager.class); * * If this viewContext doesn't have the service then the getViewService method * on the parent view context will be called. * * @param serviceClass this can either be a class or interface. * @return the instance of this serviceClass available to a view. Or null * if there is no service implementing this interface. */ public <T> T getViewService(Class<T> serviceClass); /** * Use this method to add services to this viewContext. * Views can access these services by using the {@link OTViewContextAware} * interface to get a viewContext and then call getViewService on the * context. * * @param service */ public <T> void addViewService(Class<T> serviceClass, T service); /** * NOT IMPLEMENTED * * This is not implemented yet, if your view is a OTJComponentView then * your View can implement OTJComponentViewContextAware, and then use * {@link OTJComponentViewContext#getViewByObject(OTObject)} instead. * * If this was implemented it should this returns the first view in this context that is viewing * the passed in object. * * @param obj * @return */ public OTView getViewByObject(OTObject obj); /** * Use this method to create a view factory that can be used for child views. * The returned view factory should be reused for all views that should be siblings of each other * and any returned views from the viewFactory should be closed when this view is closed. * @return */ public OTViewFactory createChildViewFactory(); /** * Get the value of a property. If this viewContext doesn't have the property then * getProperty on the parent will be called. These properties can be used by parent * views to customize their children. * * @param propertyName * @return */ public String getProperty(String propertyName); /** * Add a property to this viewContext. Setting it to null will override any parent * view context and return null for this property. Use unsetProperty to remove this * property from this viewContext. * * @param propertyName * @param propertyValue */ public void setProperty(String propertyName, String propertyValue); public void unsetProperty(String propertyName); }
lgpl-2.1
darksylinc/qt-creator
src/plugins/coreplugin/locator/executefilter.cpp
7218
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "executefilter.h" #include <coreplugin/icore.h> #include <coreplugin/messagemanager.h> #include <coreplugin/variablemanager.h> #include <QMessageBox> using namespace Core; using namespace Core; using namespace Core::Internal; ExecuteFilter::ExecuteFilter() { setId("Execute custom commands"); setDisplayName(tr("Execute Custom Commands")); setShortcutString(QString(QLatin1Char('!'))); setIncludedByDefault(false); m_process = new Utils::QtcProcess(this); m_process->setEnvironment(Utils::Environment::systemEnvironment()); connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus))); connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput())); connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError())); m_runTimer.setSingleShot(true); connect(&m_runTimer, SIGNAL(timeout()), this, SLOT(runHeadCommand())); } QList<LocatorFilterEntry> ExecuteFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry) { QList<LocatorFilterEntry> value; if (!entry.isEmpty()) // avoid empty entry value.append(LocatorFilterEntry(this, entry, QVariant())); QList<LocatorFilterEntry> others; const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry); foreach (const QString &i, m_commandHistory) { if (future.isCanceled()) break; if (i == entry) // avoid repeated entry continue; if (i.startsWith(entry, caseSensitivityForPrefix)) value.append(LocatorFilterEntry(this, i, QVariant())); else others.append(LocatorFilterEntry(this, i, QVariant())); } value.append(others); return value; } void ExecuteFilter::accept(LocatorFilterEntry selection) const { ExecuteFilter *p = const_cast<ExecuteFilter *>(this); const QString value = selection.displayName.trimmed(); const int index = m_commandHistory.indexOf(value); if (index != -1 && index != 0) p->m_commandHistory.removeAt(index); if (index != 0) p->m_commandHistory.prepend(value); bool found; QString workingDirectory = Core::VariableManager::value("CurrentDocument:Path", &found); if (!found || workingDirectory.isEmpty()) workingDirectory = Core::VariableManager::value("CurrentProject:Path", &found); ExecuteData d; d.workingDirectory = workingDirectory; const int pos = value.indexOf(QLatin1Char(' ')); if (pos == -1) { d.executable = value; } else { d.executable = value.left(pos); d.arguments = value.right(value.length() - pos - 1); } if (m_process->state() != QProcess::NotRunning) { const QString info(tr("Previous command is still running ('%1').\nDo you want to kill it?") .arg(p->headCommand())); int r = QMessageBox::question(0, tr("Kill Previous Process?"), info, QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes); if (r == QMessageBox::Yes) m_process->kill(); if (r != QMessageBox::Cancel) p->m_taskQueue.enqueue(d); return; } p->m_taskQueue.enqueue(d); p->runHeadCommand(); } void ExecuteFilter::finished(int exitCode, QProcess::ExitStatus status) { const QString commandName = headCommand(); QString message; if (status == QProcess::NormalExit && exitCode == 0) message = tr("Command '%1' finished.").arg(commandName); else message = tr("Command '%1' failed.").arg(commandName); MessageManager::write(message); m_taskQueue.dequeue(); if (!m_taskQueue.isEmpty()) m_runTimer.start(500); } void ExecuteFilter::readStandardOutput() { QByteArray data = m_process->readAllStandardOutput(); MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(), &m_stdoutState)); } void ExecuteFilter::readStandardError() { static QTextCodec::ConverterState state; QByteArray data = m_process->readAllStandardError(); MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(), &m_stderrState)); } void ExecuteFilter::runHeadCommand() { if (!m_taskQueue.isEmpty()) { const ExecuteData &d = m_taskQueue.head(); const QString fullPath = Utils::Environment::systemEnvironment().searchInPath(d.executable); if (fullPath.isEmpty()) { MessageManager::write(tr("Could not find executable for '%1'.").arg(d.executable)); m_taskQueue.dequeue(); runHeadCommand(); return; } MessageManager::write(tr("Starting command '%1'.").arg(headCommand())); m_process->setWorkingDirectory(d.workingDirectory); m_process->setCommand(fullPath, d.arguments); m_process->start(); m_process->closeWriteChannel(); if (!m_process->waitForStarted(1000)) { MessageManager::write(tr("Could not start process: %1.").arg(m_process->errorString())); m_taskQueue.dequeue(); runHeadCommand(); } } } QString ExecuteFilter::headCommand() const { if (m_taskQueue.isEmpty()) return QString(); const ExecuteData &data = m_taskQueue.head(); if (data.arguments.isEmpty()) return data.executable; else return data.executable + QLatin1Char(' ') + data.arguments; }
lgpl-2.1
SmartJog/python-mxf
sjmxf/avid.py
4254
# -*- coding: utf-8 -*- """ Implements basic classes to parse Avid specific MXF objects. """ from sjmxf.common import InterchangeObject, Singleton from sjmxf.s377m import MXFDataSet, MXFPrimer from sjmxf.rp210 import RP210Avid, RP210 from sjmxf.rp210types import Reference, Integer class AvidObjectDirectory(InterchangeObject): """ Avid ObjectDirectory parser. """ def __init__(self, fdesc, debug=False): InterchangeObject.__init__(self, fdesc, debug) self.data = [] if self.key.encode('hex_codec') != '9613b38a87348746f10296f056e04d2a': raise Exception('Not a valid Avid ObjectDirectory key') def __str__(self): return "<AvidObjectDirectory pos=%d size=%d entries=%d>" % (self.pos, self.length, len(self.data)) def read(self): data = self.fdesc.read(self.length) od_list_size = Integer(data[0:8], 'UInt64').read() od_item_size = Integer(data[8], 'UInt8').read() idx = 9 self.data = [] while od_list_size > len(self.data): self.data.append(( Reference(data[idx:idx+16]).read(), # key Integer(data[idx+16:idx+24], 'UInt64').read(), # offset Integer(data[idx+24], 'UInt8').read(), # flag )) idx += od_item_size if self.debug: print "%d objects of %d bytes size in Object Directory" % (od_list_size, od_item_size) def write(self): ret = [] for key, offset, flag in self.data: ret.append(Reference(key).write()) ret.append(Integer(offset, 'UInt64').write()) ret.append(Integer(flag, 'UInt8').write()) ret = Integer(len(self.data), 'UInt64').write() \ + Integer(len(''.join(ret[0:3])), 'UInt8').write() \ + ''.join(ret) self.pos = self.fdesc.tell() self.length = len(ret) self.fdesc.write(self.key + self.ber_encode_length(self.length, bytes_num=8).decode('hex_codec') + ret) return def human_readable(self): print "Object".rjust(32, ' '), "Offset".rjust(10, ' '), "Flag" for item in self.data: print item[0].encode('hex_codec'), '%10d' % item[1], item[2].encode('hex_codec') return class AvidAAFDefinition(MXFDataSet): """ Avid AAF definition KLV parser. """ _extra_mappings = { '0003': ('StrongReferenceArray', 'Avid links to compound types', ''), '0004': ('StrongReferenceArray', 'Avid links to simple types', ''), '0010': ('Boolean', 'Signedness', ''), '000f': ('UInt8', 'Length in bytes', ''), '001b': ('StrongReference', 'Unkown data 1', ''), } def __init__(self, fdesc, primer, debug=False): # Prepare object specific Primer aprim = MXFPrimer.customize(primer, Singleton(RP210, 'AvidAAFDefinition'), self._extra_mappings) MXFDataSet.__init__(self, fdesc, aprim, debug=debug, dark=True) self.set_type = 'AvidAAFDefinition' class AvidMetadataPreface(MXFDataSet): """ Avid metadata dictionary pseudo Preface parser. """ _extra_mappings = { '0001': ('StrongReference', 'AAF Metadata', 'Avid AAF Metadata Reference'), '0002': ('StrongReference', 'Preface', 'Avid Preface Reference'), '0003': ('AvidOffset', 'Object Directory', 'Position of the Object Directory'), '0004': ('UInt32', 'Audio Channels', 'Number of audio channels in source file'), } def __init__(self, fdesc, primer, debug=False): aprim = MXFPrimer.customize(primer, Singleton(RP210, 'AvidMetadataPreface'), self._extra_mappings) MXFDataSet.__init__(self, fdesc, aprim, debug=debug, dark=True) self.set_type = 'AvidMetadataPreface' class AvidMXFDataSet(MXFDataSet): """ Avid specific DataSet parser. """ _extra_mappings = { '3c07': ('AvidVersion', 'Avid Version Tag', ''), '3c03': ('AvidVersion', 'Avid Version Tag', ''), } def __init__(self, fdesc, primer, debug=False): aprim = MXFPrimer.customize(primer, Singleton(RP210Avid), self._extra_mappings) MXFDataSet.__init__(self, fdesc, aprim, debug=debug, dark=True) self.set_type = 'Avid' + self.set_type
lgpl-2.1
omda12/akelosframework
test/unit/lib/AkActionView/TemplateEngines/AkSintags.php
2272
<?php require_once(dirname(__FILE__).'/../../../../fixtures/config/config.php'); require_once(AK_LIB_DIR.DS.'AkActionView'.DS.'TemplateEngines'.DS.'AkSintags.php'); define('AK_SINTAGS_AVALABLE_HELPERS', 'a:8:{s:7:"url_for";s:10:"url_helper";s:7:"link_to";s:10:"url_helper";s:7:"mail_to";s:10:"url_helper";s:10:"email_link";s:10:"url_helper";s:9:"translate";s:11:"text_helper";s:20:"number_to_human_size";s:13:"number_helper";s:6:"render";s:10:"controller";s:25:"distance_of_time_in_words";s:11:"date_helper";}'); class Test_of_AkSintags extends UnitTestCase { function test_sintags() { $this->_run_from_file('sintags_test_data.txt'); } function test_sintags_helpers() { $this->_run_from_file('sintags_helpers_data.txt'); } function _run_from_file($file_name, $all_in_one_test = true) { $multiple_expected_php = $multiple_sintags = ''; $tests = explode('===================================',file_get_contents(AK_TEST_DIR.DS.'fixtures'.DS.'data'.DS.$file_name)); foreach ($tests as $test) { list($sintags, $php) = explode('-----------------------------------',$test); $sintags = trim($sintags); $expected_php = trim($php); if(empty($sintags)){ break; }else{ $multiple_sintags .= $sintags; $multiple_expected_php .= $expected_php; } $AkSintags =& new AkSintagsParser(); $php = $AkSintags->parse($sintags); if($php != $expected_php){ Ak::trace("GENERATED: \n".$php); Ak::trace("EXPECTED: \n".$expected_php); Ak::trace("SINTAGS: \n".$sintags); } $this->assertEqual($php, $expected_php); } if($all_in_one_test){ $AkSintags =& new AkSintagsParser(); $php = $AkSintags->parse($multiple_sintags); if($php != $multiple_expected_php){ Ak::trace("GENERATED: \n".$php); Ak::trace("EXPECTED: \n".$expected_php); Ak::trace("SINTAGS: \n".$sintags); } $this->assertEqual($php, $multiple_expected_php); } } } ak_test('Test_of_AkSintags'); ?>
lgpl-2.1
Emergya/opensir
sir-admin/sir-admin-base/sir-admin-base-core/src/main/java/com/emergya/ohiggins/dao/impl/OhigginsLayerResourceDaoHibernateImpl.java
4211
/* * OhigginsLayerResourceDaoHibernateImpl.java * * Copyright (C) 2013 * * This file is part of ohiggins-core * * This software 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 software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this library; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * As a special exception, if you link this library with other files to produce * an executable, this library does not by itself cause the resulting executable * to be covered by the GNU General Public License. This exception does not * however invalidate any other reasons why the executable file might be covered * by the GNU General Public License. * * Authors:: Juan Luis Rodríguez Ponce (mailto:jlrodriguez@emergya.com) */ package com.emergya.ohiggins.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import com.emergya.ohiggins.dao.OhigginsLayerResourceDao; import com.emergya.ohiggins.model.AuthorityEntity; import com.emergya.ohiggins.model.LayerResourceEntity; import com.emergya.persistenceGeo.dao.impl.GenericHibernateDAOImpl; import com.emergya.persistenceGeo.utils.GeoserverUtils; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Projections; /** * @author <a href="mailto:jlrodriguez@emergya.com">jlrodriguez</a> * */ @Repository public class OhigginsLayerResourceDaoHibernateImpl extends GenericHibernateDAOImpl<LayerResourceEntity, Long> implements OhigginsLayerResourceDao { private static final String TABLE_PREFIX = "tmpVectLayer"; private static final String TABLE_NAME = "tmpLayerName"; private static final String ID = "id"; /* * (non-Javadoc) * * @see * com.emergya.ohiggins.dao.OhigginsLayerResourceDao#getByTmpLayerName(java * .lang.String) */ @Override public LayerResourceEntity getByTmpLayerName(String tmpLayerName) { Criteria crit = getSession().createCriteria(LayerResourceEntity.class) .add(Restrictions.eq("tmpLayerName", tmpLayerName)); return (LayerResourceEntity) crit.uniqueResult(); } /** * Generates a unused table name with a fixed prefix "shpImported". */ @Override public String generateNameNotYetUsed() { return this.generateNameNotYetUsed(TABLE_PREFIX); } /** * Generates an unused table name with a customizable prefix. */ @Override public String generateNameNotYetUsed(String prefix) { boolean unique = false; String result = null; while (!unique) { String candidate = GeoserverUtils.createUniqueName(prefix); if (getByTmpLayerName(candidate) == null) { unique = true; result = candidate; } } return result; } /** * Obtain number of tables used with a name ilike tableName * * @param tableName * * @return 0 if not found and number of occurrences otherwise */ @Override public Long tableUses(String tableName) { return (Long) getSession() .createCriteria(super.persistentClass) .add(Restrictions.ilike(TABLE_NAME, tableName, MatchMode.ANYWHERE)) .setProjection(Projections.count(ID)).uniqueResult(); } @Override public List<LayerResourceEntity> getByAuth(AuthorityEntity authEntity) { return getSession().createCriteria(super.persistentClass) .add(Restrictions.eq("authority", authEntity)) .list(); } }
lgpl-2.1
Anatoscope/sofa
modules/SofaGraphComponent/RequiredPlugin.cpp
3365
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * 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 2.1 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "RequiredPlugin.h" #include <sofa/core/ObjectFactory.h> #include <sofa/helper/system/PluginManager.h> #include <sofa/helper/logging/Messaging.h> using sofa::helper::system::PluginManager; namespace sofa { namespace component { namespace misc { SOFA_DECL_CLASS(RequiredPlugin) int RequiredPluginClass = core::RegisterObject("Load the required plugins") .add< RequiredPlugin >(); RequiredPlugin::RequiredPlugin() : d_pluginName( initData(&d_pluginName, "pluginName", "Name of the plugin to loaded. If this is empty, the name of this component is used as plugin name.")) { this->f_printLog.setValue(true); // print log by default, to identify which pluging is responsible in case of a crash during loading } void RequiredPlugin::parse(sofa::core::objectmodel::BaseObjectDescription* arg) { Inherit1::parse(arg); const helper::vector<std::string>& pluginName = d_pluginName.getValue(); // if no plugin name is given, try with the component name if(pluginName.empty()) loadPlugin( name.getValue() ); else for( const auto& it: pluginName ) loadPlugin( it ); } void RequiredPlugin::loadPlugin( const std::string& pluginName ) { PluginManager& pluginManager = PluginManager::getInstance(); const std::string path = pluginManager.findPlugin(pluginName); if (path != "") { if (!PluginManager::getInstance().pluginIsLoaded(path)) { PluginManager::getInstance().loadPlugin(pluginName); // load by name to automatically load the gui lib } } else { msg_error("RequiredPlugin") << "Plugin not found: \"" + pluginName + "\""; } } } } }
lgpl-2.1
Tictim/TTMPMOD
libs_n/gregtech/api/gui/GT_Container_3by3.java
1195
package gregtech.api.gui; import gregtech.api.interfaces.tileentity.IGregTechTileEntity; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; public class GT_Container_3by3 extends GT_ContainerMetaTile_Machine { public GT_Container_3by3(InventoryPlayer aInventoryPlayer, IGregTechTileEntity aTileEntity) { super(aInventoryPlayer, aTileEntity); } @Override public void addSlots(InventoryPlayer aInventoryPlayer) { addSlotToContainer(new Slot(mTileEntity, 0, 62, 17)); addSlotToContainer(new Slot(mTileEntity, 1, 80, 17)); addSlotToContainer(new Slot(mTileEntity, 2, 98, 17)); addSlotToContainer(new Slot(mTileEntity, 3, 62, 35)); addSlotToContainer(new Slot(mTileEntity, 4, 80, 35)); addSlotToContainer(new Slot(mTileEntity, 5, 98, 35)); addSlotToContainer(new Slot(mTileEntity, 6, 62, 53)); addSlotToContainer(new Slot(mTileEntity, 7, 80, 53)); addSlotToContainer(new Slot(mTileEntity, 8, 98, 53)); } @Override public int getSlotCount() { return 9; } @Override public int getShiftClickSlotCount() { return 9; } }
lgpl-2.1
bermi/akelos
akelos_utils/doc_builder/models/source_parser.php
12197
<?php # This file is part of the Akelos Framework # (Copyright) 2004-2010 Bermi Ferrer bermi a t bermilabs com # See LICENSE and CREDITS for details class SourceLexer extends AkLexer { public function __construct(&$Parser) { parent::__construct($Parser, 'Text'); $this->mapHandler('Text', 'Text'); $this->addPhpTokens(); } public function addPhpTokens() { $this->addEntryPattern('<\?','Text','PhpCode'); $this->addClassName(); $this->addCategories(); $this->addJavaDocTokens(); $this->addFunctionDeclaration(); $this->addFunctionDefaultOptions(); $this->addExitPattern('\?>','PhpCode'); } public function addCategories() { $this->addEntryPattern('\x2f\x2a\x2a[ \n\t]*[A-Za-z _0-9]+[ \n\t]*\x3d{60,}','PhpCode','CategoryStart'); $this->addPattern('(?<=\x3d{60}\n)See also:[ \n\t]*[a-z,A-Z _0-9]+[ \n\t]*\x2e', 'CategoryStart'); $this->addEntryPattern('(?<=\n)[ \t]*\* ','CategoryStart','CategoryDetails'); $this->addEntryPattern('\* ','CategoryStart','CategoryDetails'); $this->addExitPattern('\n','CategoryDetails'); $this->addExitPattern('\x2a\x2f','CategoryStart'); $this->addSpecialPattern('\x2f\x2a\x2f[A-Za-z _0-9]+\x2a\x2f','PhpCode','CategoryFinish'); } public function addJavaDocTokens() { $this->addEntryPattern('\x2f\x2a\x2a','PhpCode','JavaDoc'); $this->addExitPattern('\x2a\x2f','JavaDoc'); $this->addJavaDocLines(); } public function addJavaDocLines() { $this->addEntryPattern('(?<=\n)[ \t]*\*','JavaDoc','JavaDocLine'); $this->addEntryPattern('\*','JavaDoc','JavaDocLine'); $this->addSpecialPattern('\x40[A-Za-z]+ ','JavaDocLine','JavaDocAttribute'); $this->addExitPattern('\n','JavaDocLine'); } public function addClassName() { $this->addEntryPattern('(?<=\n)[ \t]*class[ \n\t]*', 'PhpCode', 'ClassName'); $this->addPattern('(?!extends)[ \n\t]*[a-z]+[ \n\t]*', 'ClassName'); $this->addEntryPattern('[ \n\t]*extends[ \n\t]*', 'ClassName', 'ParentClassName'); $this->addExitPattern('[ \n\t]*[a-z]+[ \n\t]*', 'ParentClassName'); $this->addExitPattern('[ \n\t]*{', 'ClassName'); } public function addFunctionDeclaration() { $this->addEntryPattern('(?<=\n)[ \t]*function[ \n\t][\x26a-z_]+[ \n\t]*\x28', 'PhpCode', 'FunctionName'); //$this->addPattern('[ \n\t]*[a-z]+[ \n\t]*(?=\x28)', 'FunctionName'); $this->addEntryPattern('\x26?[ \t]*\x24', 'FunctionName', 'FunctionParameter'); $this->addExitPattern(',[ \t]*(?=\x26?[ \t]*\x24)', 'FunctionParameter'); $this->addExitPattern('\x29', 'FunctionParameter'); $this->addExitPattern('\x29?[ \n\t]*{', 'FunctionName'); } public function addFunctionDefaultOptions() { $this->addEntryPattern('\x24default_options[ \t]*\x3d[ \t]*array[ \t]*\x28', 'PhpCode', 'DefaultOptions'); $this->addEntryPattern('\x27', 'DefaultOptions', 'DefaultOption'); $this->addExitPattern('\x27', 'DefaultOption'); $this->addExitPattern(';', 'DefaultOptions'); } } class SourceParser { public $output = ''; public $input = ''; public $_Lexer; public $parsed = array(); public $_current_category = 'none'; public $_current_category_details = ''; public $_current_category_relations = array(); public $_current_class = null; public $_current_class_extends = null; public $_current_method = null; public $_current_params = array(); public $_latest_attributes = array(); public $_current_javadoc_attribute = false; public $_latest_docs = null; public $_is_reference = null; public $package = 'Active Support'; public $subpackage = 'Utils'; public function SourceParser($code) { $this->input = $code; $this->_Lexer = new SourceLexer($this); } public function parse() { $this->beforeParsing(); $this->_Lexer->parse($this->input); $this->afterParsing(); return $this->parsed; } public function afterParsing() { $this->parsed['details'] = array(); $this->parsed['details']['package'] = $this->package; $this->parsed['details']['subpackage'] = $this->subpackage; } public function beforeParsing() { $this->input = preg_replace("/\n[ \t]*/","\n", $this->input); } public function PhpCode($match, $state) { //AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); if($match == AK_LEXER_UNMATCHED){ } return true; } public function ClassName($match, $state) { if(AK_LEXER_MATCHED == $state){ $this->_current_class = trim($match); }elseif(AK_LEXER_EXIT == $state){ if(!empty($this->_current_class)){ $this->parsed['classes'][$this->_current_class] = array( 'doc' => trim($this->_latest_docs, "\n\t "), 'doc_metadata' => $this->_latest_attributes, 'class_name' => $this->_current_class, 'extends' => trim($this->_current_class_extends), 'methods' => array(), //'category' => $this->_current_category, ); } $this->_current_class_extends = null; $this->_latest_docs = ''; $this->_is_reference = false; }elseif (AK_LEXER_ENTER == $state){ $this->_is_reference = strstr($match,'&'); } //AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); return true; } public function ParentClassName($match, $state) { if(AK_LEXER_EXIT == $state){ $this->_current_class_extends = trim($match); } //AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); return true; } public function FunctionName($match, $state) { if(AK_LEXER_ENTER === $state){ $this->_current_method_returns_reference = strstr($match,'&') != ''; $this->_current_method = trim(str_replace(array('function ','(', '&'),'',$match)); }elseif(AK_LEXER_EXIT == $state){ if(!empty($this->_current_class) && !empty($this->_current_method)){ $this->parsed['classes'][$this->_current_class]['methods'][$this->_current_method] = array( 'doc' => trim($this->_latest_docs, "\n\t "), 'doc_metadata' => $this->_latest_attributes, 'method_name' => $this->_current_method, 'is_private' => substr($this->_current_method,0,1) == '_', 'returns_reference' => $this->_current_method_returns_reference, 'params' => $this->_current_params, 'category' => $this->_current_category, 'category_details' => $this->_current_category_details, 'category_relations' => $this->_current_category_relations ); } //AkDebug::trace($this->_current_category_details); $this->_current_method = null; $this->_current_params = array(); $this->_latest_docs = ''; $this->_current_category = 'none'; $this->_current_category_details = ''; $this->_current_category_relations = array(); } //AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); return true; } public function FunctionParameter($match, $state) { if(AK_LEXER_UNMATCHED == $state){ list($param,$value) = explode('=',$match.'='); $type = null; if(strstr($value,'array')){ $type = 'array'; $value = ''; }elseif(strstr($value,'"') || strstr($value,"'")){ $type = 'string'; $value = trim($value,'"\' '); }elseif(strstr($value,'true') || strstr($value,'false')){ $type = 'bool'; }elseif(is_numeric(trim($value))){ $type = 'int'; }elseif(strstr($value,'null') || empty($value)){ $type = null; $value = null; }elseif (preg_match('/[A-Z]/', @$value[0])){ $type = preg_match('/[A-Z]/', @$value[1]) ? 'constant' : 'object'; } array_push($this->_current_params, array( 'name' => trim($param), 'type' => $type, 'value' => trim($value), )); } //AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); return true; } public function CategoryStart($match, $state) { if(AK_LEXER_ENTER === $state){ $this->_current_category = trim($match,"\n= /*"); $this->parsed['categories'][$this->_current_category] = array(); }elseif (AK_LEXER_UNMATCHED == $state){ $match = trim(str_replace(array('See also',"*","\n","\t",'.',':'),'',$match)); if(!empty($match)){ $this->_current_category_relations = array_map('trim', explode(',',$match)); $this->parsed['categories'][$this->_current_category]['relations'] = $this->_current_category_relations; } } // AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); return true; } public function CategoryDetails($match, $state) { if(AK_LEXER_UNMATCHED == $state){ $this->_current_category = 'none'; $this->_current_category_relations = array(); } $this->_current_category_details .= trim($match, '/*'); // AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); return true; } public function CategoryFinish($match, $state) { if(AK_LEXER_SPECIAL == $state){ $this->_current_category_details .= trim($match, '/* '); } //AkDebug::trace($this->_current_category_details); return true; } public function DefaultOptions($match, $state) { //AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); return true; } public function DefaultOption($match, $state) { //AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); return true; } public function JavaDoc($match, $state) { if(AK_LEXER_ENTER === $state){ $this->_current_javadoc_attribute = false; $this->_latest_attributes = array(); }elseif(AK_LEXER_UNMATCHED == $state){ $this->_latest_docs .= (trim($match) == '*'?'':$match)."\n"; } //AkDebug::trace(__FUNCTION__.' '.$match.' '.$state); return true; } public function JavaDocLine($match, $state) { if(AK_LEXER_UNMATCHED == $state){ $match = (trim($match) == '*'?'':$match)."\n"; if(!$this->_current_javadoc_attribute){ $this->_latest_docs .= $match; }elseif(trim($match) != ''){ $handler_name = 'handle'.AkInflector::camelize($this->_current_javadoc_attribute); if(method_exists($this,$handler_name)){ $this->$handler_name($match); }else{ $this->_latest_attributes[$this->_current_javadoc_attribute] = $match; } } } //AkDebug::trace(__FUNCTION__.$match.$state); return true; } public function JavaDocAttribute($match, $state) { $match = trim($match,'@ '); $this->_current_javadoc_attribute = empty($match) ? false : $match; return true; } public function Text($text) { $this->output .= $text; return true; } public function handlePackage($package_description) { $this->package = AkInflector::titleize($package_description); //AkDebug::trace($this->package); } public function handleSubpackage($subpackage_description) { $this->subpackage = AkInflector::titleize($subpackage_description); //AkDebug::trace($this->subpackage); } }
lgpl-2.1
KDE/android-qt-mobility
plugins/multimedia/v4l/v4lserviceplugin.cpp
2357
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qstring.h> #include <QtCore/qfile.h> #include <QtCore/qdebug.h> #include <QtCore/qdir.h> #include "v4lserviceplugin.h" #include "v4lradioservice.h" #include <qmediaserviceprovider.h> QStringList V4LServicePlugin::keys() const { return QStringList() << QLatin1String(Q_MEDIASERVICE_RADIO); } QMediaService* V4LServicePlugin::create(QString const& key) { if (key == QLatin1String(Q_MEDIASERVICE_RADIO)) return new V4LRadioService; return 0; } void V4LServicePlugin::release(QMediaService *service) { delete service; } QList<QByteArray> V4LServicePlugin::devices(const QByteArray &service) const { return QList<QByteArray>(); } QString V4LServicePlugin::deviceDescription(const QByteArray &service, const QByteArray &device) { return QString(); } Q_EXPORT_PLUGIN2(qtmedia_v4lengine, V4LServicePlugin);
lgpl-2.1
artemp/MapQuest-Render-Stack
dqueue/consistent_hash.cpp
1379
/*------------------------------------------------------------------------------ * * This file is part of rendermq * * Author: matt.amos@mapquest.com * * Copyright 2010-1 Mapquest, Inc. All Rights reserved. * * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *-----------------------------------------------------------------------------*/ #include "consistent_hash.hpp" namespace rendermq { namespace hash_helper { template <> uint32_t get_value<uint32_t>(boost::mt19937 &rng) { return rng(); } template <> uint64_t get_value<uint64_t>(boost::mt19937 &rng) { return uint64_t(rng()) | (uint64_t(rng()) << 32); } } // namespace hash_helper } // namespace rendermq
lgpl-2.1
solmix/datax
wmix/src/main/java/org/solmix/datax/wmix/DataxEndpoint.java
4429
/* * Copyright 2015 The Solmix Project * * This 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. * * This software 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 may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.gnu.org/licenses/ * or see the FSF site: http://www.fsf.org. */ package org.solmix.datax.wmix; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.solmix.commons.util.Assert; import org.solmix.datax.DataServiceManager; import org.solmix.datax.wmix.interceptor.OutFaultInterceptor; import org.solmix.datax.wmix.interceptor.SgtInInterceptor; import org.solmix.datax.wmix.interceptor.SgtOutInterceptor; import org.solmix.exchange.Endpoint; import org.solmix.exchange.Service; import org.solmix.exchange.Transporter; import org.solmix.exchange.data.DataProcessor; import org.solmix.exchange.interceptor.support.MessageSenderInterceptor; import org.solmix.exchange.model.ArgumentInfo; import org.solmix.exchange.processor.InFaultChainProcessor; import org.solmix.exchange.processor.OutFaultChainProcessor; import org.solmix.runtime.Container; import org.solmix.wmix.exchange.AbstractWmixEndpoint; import org.solmix.wmix.exchange.WmixMessage; import org.solmix.wmix.mapper.MapperService; /** * 提供基于RestFul的数据输出 * @author solmix.f@gmail.com * @version $Id$ 2015年8月13日 */ public class DataxEndpoint extends AbstractWmixEndpoint implements Endpoint { private static final Logger LOG = LoggerFactory.getLogger(DataxEndpoint.class); private static final long serialVersionUID = 7621213021932655937L; private DataxServiceFactory serviceFactory; private ArgumentInfo argumentInfo; private DataServiceManager dataServiceManager; public DataxEndpoint(){ serviceFactory= new DataxServiceFactory(); } @Override protected void prepareInterceptors() { setInFaultProcessor(new InFaultChainProcessor(container, getPhasePolicy())); setOutFaultProcessor(new OutFaultChainProcessor(container, getPhasePolicy())); getOutInterceptors().add(new MessageSenderInterceptor()); getOutFaultInterceptors().add(new MessageSenderInterceptor()); prepareInInterceptors(); prepareOutInterceptors(); prepareOutFaultInterceptors(); } protected void prepareOutFaultInterceptors(){ getOutFaultInterceptors().add(new OutFaultInterceptor()); } protected void prepareOutInterceptors(){ getOutInterceptors().add(new SgtOutInterceptor()); } protected void prepareInInterceptors(){ SgtInInterceptor in = new SgtInInterceptor(); MapperService mapperService=container.getExtension(MapperService.class); in.setMapperService(mapperService); getInInterceptors().add(in); } @Override protected void setContainer(Container container) { super.setContainer(container); argumentInfo = new ArgumentInfo(); argumentInfo.setTypeClass(Map.class); dataServiceManager=container.getExtension(DataServiceManager.class); Assert.assertNotNull(dataServiceManager,"NO found DataServiceManager"); DataProcessor dataProcessor = container.getExtension(DataProcessor.class); serviceFactory.setDataProcessor(dataProcessor); } @Override public void service(WmixMessage message) throws Exception { message.put(ArgumentInfo.class, argumentInfo); message.getExchange().put(DataServiceManager.class, dataServiceManager); message.getExchange().put(Transporter.class, getTransporter()); getTransporter().invoke(message); } @Override protected Logger getLogger() { return LOG; } @Override protected Service createService() { return serviceFactory.create(); } }
lgpl-2.1
sicily/qt4.8.4
tools/designer/src/components/propertyeditor/fontpropertymanager.cpp
15067
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Designer of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "fontpropertymanager.h" #include "qtpropertymanager.h" #include "qtvariantproperty.h" #include "qtpropertybrowserutils_p.h" #include <qdesigner_utils_p.h> #include <QtCore/QCoreApplication> #include <QtCore/QVariant> #include <QtCore/QString> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QTextStream> #include <QtXml/QXmlStreamReader> QT_BEGIN_NAMESPACE namespace qdesigner_internal { static const char *aliasingC[] = { QT_TRANSLATE_NOOP("FontPropertyManager", "PreferDefault"), QT_TRANSLATE_NOOP("FontPropertyManager", "NoAntialias"), QT_TRANSLATE_NOOP("FontPropertyManager", "PreferAntialias") }; FontPropertyManager::FontPropertyManager() : m_createdFontProperty(0) { const int nameCount = sizeof(aliasingC)/sizeof(const char *); for (int i = 0; i < nameCount; i++) m_aliasingEnumNames.push_back(QCoreApplication::translate("FontPropertyManager", aliasingC[i])); QString errorMessage; if (!readFamilyMapping(&m_familyMappings, &errorMessage)) { designerWarning(errorMessage); } } void FontPropertyManager::preInitializeProperty(QtProperty *property, int type, ResetMap &resetMap) { if (m_createdFontProperty) { PropertyToSubPropertiesMap::iterator it = m_propertyToFontSubProperties.find(m_createdFontProperty); if (it == m_propertyToFontSubProperties.end()) it = m_propertyToFontSubProperties.insert(m_createdFontProperty, PropertyList()); const int index = it.value().size(); m_fontSubPropertyToFlag.insert(property, index); it.value().push_back(property); m_fontSubPropertyToProperty[property] = m_createdFontProperty; resetMap[property] = true; } if (type == QVariant::Font) m_createdFontProperty = property; } // Map the font family names to display names retrieved from the XML configuration static QStringList designerFamilyNames(QStringList families, const FontPropertyManager::NameMap &nm) { if (nm.empty()) return families; const FontPropertyManager::NameMap::const_iterator ncend = nm.constEnd(); const QStringList::iterator end = families.end(); for (QStringList::iterator it = families.begin(); it != end; ++it) { const FontPropertyManager::NameMap::const_iterator nit = nm.constFind(*it); if (nit != ncend) *it = nit.value(); } return families; } void FontPropertyManager::postInitializeProperty(QtVariantPropertyManager *vm, QtProperty *property, int type, int enumTypeId) { if (type != QVariant::Font) return; // This will cause a recursion QtVariantProperty *antialiasing = vm->addProperty(enumTypeId, QCoreApplication::translate("FontPropertyManager", "Antialiasing")); const QFont font = qvariant_cast<QFont>(vm->variantProperty(property)->value()); antialiasing->setAttribute(QLatin1String("enumNames"), m_aliasingEnumNames); antialiasing->setValue(antialiasingToIndex(font.styleStrategy())); property->addSubProperty(antialiasing); m_propertyToAntialiasing[property] = antialiasing; m_antialiasingToProperty[antialiasing] = property; // Fiddle family names if (!m_familyMappings.empty()) { const PropertyToSubPropertiesMap::iterator it = m_propertyToFontSubProperties.find(m_createdFontProperty); QtVariantProperty *familyProperty = vm->variantProperty(it.value().front()); const QString enumNamesAttribute = QLatin1String("enumNames"); QStringList plainFamilyNames = familyProperty->attributeValue(enumNamesAttribute).toStringList(); // Did someone load fonts or something? if (m_designerFamilyNames.size() != plainFamilyNames.size()) m_designerFamilyNames = designerFamilyNames(plainFamilyNames, m_familyMappings); familyProperty->setAttribute(enumNamesAttribute, m_designerFamilyNames); } // Next m_createdFontProperty = 0; } bool FontPropertyManager::uninitializeProperty(QtProperty *property) { const PropertyToPropertyMap::iterator ait = m_propertyToAntialiasing.find(property); if (ait != m_propertyToAntialiasing.end()) { QtProperty *antialiasing = ait.value(); m_antialiasingToProperty.remove(antialiasing); m_propertyToAntialiasing.erase(ait); delete antialiasing; } PropertyToSubPropertiesMap::iterator sit = m_propertyToFontSubProperties.find(property); if (sit == m_propertyToFontSubProperties.end()) return false; m_propertyToFontSubProperties.erase(sit); m_fontSubPropertyToFlag.remove(property); m_fontSubPropertyToProperty.remove(property); return true; } void FontPropertyManager::slotPropertyDestroyed(QtProperty *property) { removeAntialiasingProperty(property); } void FontPropertyManager::removeAntialiasingProperty(QtProperty *property) { const PropertyToPropertyMap::iterator ait = m_antialiasingToProperty.find(property); if (ait == m_antialiasingToProperty.end()) return; m_propertyToAntialiasing[ait.value()] = 0; m_antialiasingToProperty.erase(ait); } bool FontPropertyManager::resetFontSubProperty(QtVariantPropertyManager *vm, QtProperty *property) { const PropertyToPropertyMap::iterator it = m_fontSubPropertyToProperty.find(property); if (it == m_fontSubPropertyToProperty.end()) return false; QtVariantProperty *fontProperty = vm->variantProperty(it.value()); QVariant v = fontProperty->value(); QFont font = qvariant_cast<QFont>(v); unsigned mask = font.resolve(); const unsigned flag = fontFlag(m_fontSubPropertyToFlag.value(property)); mask &= ~flag; font.resolve(mask); v.setValue(font); fontProperty->setValue(v); return true; } int FontPropertyManager::antialiasingToIndex(QFont::StyleStrategy antialias) { switch (antialias) { case QFont::PreferDefault: return 0; case QFont::NoAntialias: return 1; case QFont::PreferAntialias: return 2; default: break; } return 0; } QFont::StyleStrategy FontPropertyManager::indexToAntialiasing(int idx) { switch (idx) { case 0: return QFont::PreferDefault; case 1: return QFont::NoAntialias; case 2: return QFont::PreferAntialias; } return QFont::PreferDefault; } unsigned FontPropertyManager::fontFlag(int idx) { switch (idx) { case 0: return QFont::FamilyResolved; case 1: return QFont::SizeResolved; case 2: return QFont::WeightResolved; case 3: return QFont::StyleResolved; case 4: return QFont::UnderlineResolved; case 5: return QFont::StrikeOutResolved; case 6: return QFont::KerningResolved; case 7: return QFont::StyleStrategyResolved; } return 0; } FontPropertyManager::ValueChangedResult FontPropertyManager::valueChanged(QtVariantPropertyManager *vm, QtProperty *property, const QVariant &value) { QtProperty *antialiasingProperty = m_antialiasingToProperty.value(property, 0); if (!antialiasingProperty) { if (m_propertyToFontSubProperties.contains(property)) { updateModifiedState(property, value); } return NoMatch; } QtVariantProperty *fontProperty = vm->variantProperty(antialiasingProperty); const QFont::StyleStrategy newValue = indexToAntialiasing(value.toInt()); QFont font = qvariant_cast<QFont>(fontProperty->value()); const QFont::StyleStrategy oldValue = font.styleStrategy(); if (newValue == oldValue) return Unchanged; font.setStyleStrategy(newValue); fontProperty->setValue(QVariant::fromValue(font)); return Changed; } void FontPropertyManager::updateModifiedState(QtProperty *property, const QVariant &value) { const PropertyToSubPropertiesMap::iterator it = m_propertyToFontSubProperties.find(property); if (it == m_propertyToFontSubProperties.end()) return; const PropertyList &subProperties = it.value(); QFont font = qvariant_cast<QFont>(value); const unsigned mask = font.resolve(); const int count = subProperties.size(); for (int index = 0; index < count; index++) { const unsigned flag = fontFlag(index); subProperties.at(index)->setModified(mask & flag); } } void FontPropertyManager::setValue(QtVariantPropertyManager *vm, QtProperty *property, const QVariant &value) { updateModifiedState(property, value); if (QtProperty *antialiasingProperty = m_propertyToAntialiasing.value(property, 0)) { QtVariantProperty *antialiasing = vm->variantProperty(antialiasingProperty); if (antialiasing) { QFont font = qvariant_cast<QFont>(value); antialiasing->setValue(antialiasingToIndex(font.styleStrategy())); } } } /* Parse a mappings file of the form: * <fontmappings> * <mapping><family>DejaVu Sans</family><display>DejaVu Sans [CE]</display></mapping> * ... which is used to display on which platforms fonts are available.*/ static const char *rootTagC = "fontmappings"; static const char *mappingTagC = "mapping"; static const char *familyTagC = "family"; static const char *displayTagC = "display"; static QString msgXmlError(const QXmlStreamReader &r, const QString& fileName) { return QString::fromUtf8("An error has been encountered at line %1 of %2: %3:").arg(r.lineNumber()).arg(fileName, r.errorString()); } /* Switch stages when encountering a start element (state table) */ enum ParseStage { ParseBeginning, ParseWithinRoot, ParseWithinMapping, ParseWithinFamily, ParseWithinDisplay, ParseError }; static ParseStage nextStage(ParseStage currentStage, const QStringRef &startElement) { switch (currentStage) { case ParseBeginning: return startElement == QLatin1String(rootTagC) ? ParseWithinRoot : ParseError; case ParseWithinRoot: case ParseWithinDisplay: // Next mapping, was in <display> return startElement == QLatin1String(mappingTagC) ? ParseWithinMapping : ParseError; case ParseWithinMapping: return startElement == QLatin1String(familyTagC) ? ParseWithinFamily : ParseError; case ParseWithinFamily: return startElement == QLatin1String(displayTagC) ? ParseWithinDisplay : ParseError; case ParseError: break; } return ParseError; } bool FontPropertyManager::readFamilyMapping(NameMap *rc, QString *errorMessage) { rc->clear(); const QString fileName = QLatin1String(":/trolltech/propertyeditor/fontmapping.xml"); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { *errorMessage = QString::fromUtf8("Unable to open %1: %2").arg(fileName, file.errorString()); return false; } QXmlStreamReader reader(&file); QXmlStreamReader::TokenType token; QString family; ParseStage stage = ParseBeginning; do { token = reader.readNext(); switch (token) { case QXmlStreamReader::Invalid: *errorMessage = msgXmlError(reader, fileName); return false; case QXmlStreamReader::StartElement: stage = nextStage(stage, reader.name()); switch (stage) { case ParseError: reader.raiseError(QString::fromUtf8("Unexpected element <%1>.").arg(reader.name().toString())); *errorMessage = msgXmlError(reader, fileName); return false; case ParseWithinFamily: family = reader.readElementText(); break; case ParseWithinDisplay: rc->insert(family, reader.readElementText()); break; default: break; } default: break; } } while (token != QXmlStreamReader::EndDocument); return true; } } QT_END_NAMESPACE
lgpl-2.1
FedoraScientific/salome-smesh-plugin-hexablock
src/GUI/HEXABLOCKPlugin_images.ts
1460
<!DOCTYPE TS> <!-- Copyright (C) 2009-2014 CEA/DEN, EDF R&D This library 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. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com --> <TS version="1.1" > <context> <name>@default</name> <message> <source>ICON_DLG_HEXABLOCK_PARAMETERS</source> <translation>mesh_hypo_HEXABLOCK.png</translation> </message> <message> <source>ICON_SMESH_TREE_ALGO_HEXABLOCK_3D</source> <translation>mesh_tree_hypo_HEXABLOCK.png</translation> </message> <message> <source>ICON_SMESH_TREE_HYPO_HEXABLOCK_Parameters</source> <translation>mesh_tree_hypo_HEXABLOCK.png</translation> </message> </context> </TS>
lgpl-2.1
lorddavy/TikiWiki-Improvement-Project
themes/base_files/iconsets/default.php
25623
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. //This the default icon set, it associates icon names to icon fonts. It is used as fallback for all other icon sets. // This script may only be included - so its better to die if called directly. if (strpos($_SERVER['SCRIPT_NAME'], basename(__FILE__)) !== false) { header('location: index.php'); exit; } function iconset_default() { return array( 'name' => tr('Default (Font-awesome)'), // Mandatory, will be displayed as Icon set option in the Look&Feel admin UI 'description' => tr('The default system icon set using Font-awesome fonts'), // TODO display as Icon set description in the Look&Feel admin UI 'tag' => 'span', // The default html tag for the icons in the icon set. 'prepend' => 'fa fa-', 'append' => ' fa-fw', 'icons' => array( /* This is the definition of an icon in the icon set if it's an "alias" to one of the default icons. * The key must be unique, it is the "name" parameter at the icon function, * so eg: {icon name="actions"} * will find 'actions' in the array and apply the specified configuration */ 'actions' => array( 'id' => 'play-circle', // id to match the defaults defined below ), 'admin' => array( 'id' => 'cog', ), 'add' => array( 'id' => 'plus-circle', ), 'admin_ads' => array( 'id' => 'film', ), 'admin_articles' => array( 'id' => 'newspaper-o', ), 'admin_blogs' => array( 'id' => 'bold', ), 'admin_calendar' => array( 'id' => 'calendar', ), 'admin_category' => array( 'id' => 'sitemap fa-rotate-270', ), 'admin_comments' => array( 'id' => 'comment', ), 'admin_community' => array( 'id' => 'group', ), 'admin_connect' => array( 'id' => 'link', ), 'admin_copyright' => array( 'id' => 'copyright', ), 'admin_directory' => array( 'id' => 'folder-o', ), 'admin_faqs' => array( 'id' => 'question', ), 'admin_features' => array( 'id' => 'power-off', ), 'admin_fgal' => array( 'id' => 'folder-open', ), 'admin_forums' => array( 'id' => 'comments', ), 'admin_freetags' => array( 'id' => 'tags', ), 'admin_gal' => array( 'id' => 'file-image-o', ), 'admin_general' => array( 'id' => 'cog', ), 'admin_i18n' => array( 'id' => 'language', ), 'admin_intertiki' => array( 'id' => 'exchange', ), 'admin_login' => array( 'id' => 'sign-in', ), 'admin_user' => array( 'id' => 'user', ), 'admin_look' => array( 'id' => 'image', ), 'admin_maps' => array( 'id' => 'map-marker', ), 'admin_messages' => array( 'id' => 'envelope-o', ), 'admin_metatags' => array( 'id' => 'tag', ), 'admin_module' => array( 'id' => 'cogs', ), 'admin_payment' => array( 'id' => 'credit-card', ), 'admin_performance' => array( 'id' => 'tachometer', ), 'admin_polls' => array( 'id' => 'tasks', ), 'admin_profiles' => array( 'id' => 'cube', ), 'admin_rating' => array( 'id' => 'check-square', ), 'admin_rss' => array( 'id' => 'rss', ), 'admin_score' => array( 'id' => 'trophy', ), 'admin_search' => array( 'id' => 'search', ), 'admin_semantic' => array( 'id' => 'arrows-h', ), 'admin_security' => array( 'id' => 'lock', ), 'admin_sefurl' => array( 'id' => 'search-plus', ), 'admin_share' => array( 'id' => 'share-alt', ), 'admin_socialnetworks' => array( 'id' => 'thumbs-up', ), 'admin_stats' => array( 'id' => 'bar-chart', ), 'admin_textarea' => array( 'id' => 'edit', ), 'admin_trackers' => array( 'id' => 'database', ), 'admin_userfiles' => array( 'id' => 'cog', ), 'admin_video' => array( 'id' => 'video-camera', ), 'admin_webmail' => array( 'id' => 'inbox', ), 'admin_webservices' => array( 'id' => 'cog', ), 'admin_wiki' => array( 'id' => 'file-text-o', ), 'admin_workspace' => array( 'id' => 'desktop', ), 'admin_wysiwyg' => array( 'id' => 'file-text', ), 'admin_print' => array( 'id' => 'print', ), //align-center in defaults //align-justify in defaults //align-left in defaults //align-right in defaults //anchor in defaults 'articles' => array( 'id' => 'newspaper-o', ), //arrow-up in defaults 'attach' => array( 'id' => 'paperclip', ), 'audio' => array( 'id' => 'file-audio-o', ), 'back' => array( 'id' => 'arrow-left', ), 'background-color' => array( 'id' => 'paint-brush', ), 'backlink' => array( 'id' => 'reply', ), //backward in defaults 'backward_step' => array( 'id' => 'step-backward', ), //ban in defaults //book in defaults 'box' => array( 'id' => 'list-alt', ), //caret-left & caret-right in defaults 'cart' => array( 'id' => 'shopping-cart', ), 'chart' => array( 'id' => 'area-chart', ), 'check' => array( 'id' => 'check-square-o', ), //code in defaults 'code_file' => array( 'id' => 'file-code-o', ), 'collapsed' => array( 'id' => 'plus-square-o', ), //columns in defaults 'comments' => array( 'id' => 'comments-o', ), 'compose' => array( 'id' => 'pencil', ), 'computer' => array( 'id' => 'desktop', ), 'contacts' => array( 'id' => 'group', ), 'content-template' => array( 'id' => 'file-o', ), //copy in defaults 'create' => array( 'id' => 'plus', ), //database in defaults 'delete' => array( 'id' => 'times', ), 'difference' => array( 'id' => 'strikethrough', ), 'disable' => array( 'id' => 'minus-square', ), 'documentation' => array( 'id' => 'book', ), 'down' => array( 'id' => 'sort-desc', ), //edit in defaults 'education' => array( 'id' => 'graduation-cap', ), 'envelope' => array( 'id' => 'envelope-o', ), 'erase' => array( 'id' => 'eraser', ), 'error' => array( 'id' => 'exclamation-circle', ), 'excel' => array( 'id' => 'file-excel-o', ), 'expanded' => array( 'id' => 'minus-square-o', ), 'export' => array( 'id' => 'download', ), //facebook in defaults 'file' => array( 'id' => 'file-o', ), 'file-archive' => array( 'id' => 'folder', ), 'file-archive-open' => array( 'id' => 'folder-open', ), //filter in defaults //flag in defaults 'floppy' => array( 'id' => 'floppy-o', ), 'font-color' => array( 'id' => 'font', 'class' => 'text-danger' ), //forward in defaults 'forward_step' => array( 'id' => 'step-forward', ), 'fullscreen' => array( 'id' => 'arrows-alt', ), //group in defaults 'h1' => array( 'id' => 'header', ), 'h2' => array( 'id' => 'header', 'size' => '.9' ), 'h3' => array( 'id' => 'header', 'size' => '.8' ), 'help' => array( 'id' => 'question-circle', ), 'history' => array( 'id' => 'clock-o', ), //history in defaults 'horizontal-rule' => array( 'id' => 'minus', ), 'html' => array( 'id' => 'html5', ), 'image' => array( 'id' => 'file-image-o', ), 'import' => array( 'id' => 'upload', ), //indent in defaults 'index' => array( 'id' => 'spinner', ), 'information' => array( 'id' => 'info-circle', ), //italic in defaults 'keyboard' => array( 'id' => 'keyboard-o', ), 'like' => array( 'id' => 'thumbs-up', ), //link in defaults 'link-external' => array( 'id' => 'external-link', ), 'link-external-alt' => array( 'id' => 'external-link-square', ), //list in defaults 'list-numbered' => array( 'id' => 'list-ol', ), //lock in defaults //same fa icon used for admin_security, but not the same in other icon sets 'log' => array( 'id' => 'history', ), 'login' => array( 'id' => 'sign-in', ), 'logout' => array( 'id' => 'sign-out', ), 'mailbox' => array( 'id' => 'inbox', ), //map in defaults 'menu' => array( 'id' => 'bars', ), 'menu-extra' => array( 'id' => 'chevron-down', ), 'menuitem' => array( 'id' => 'angle-right', ), 'merge' => array( 'id' => 'random', ), 'minimize' => array( 'id' => 'compress', ), //minus in defaults 'module' => array( 'id' => 'cogs', ), 'more' => array( 'id' => 'ellipsis-h', ), 'move' => array( 'id' => 'exchange', ), 'next' => array( 'id' => 'arrow-right', ), 'notepad' => array( 'id' => 'file-text-o', ), 'notification' => array( 'id' => 'bell-o', ), 'off' => array( 'id' => 'power-off', ), 'ok' => array( 'id' => 'check-circle', ), //outdent in defaults 'page-break' => array( 'id' => 'scissors', ), //paste in defaults //pause in defaults 'pdf' => array( 'id' => 'file-pdf-o', ), 'permission' => array( 'id' => 'key', ), //play in defaults 'plugin' => array( 'id' => 'puzzle-piece', ), 'popup' => array( 'id' => 'list-alt', ), 'post' => array( 'id' => 'pencil', ), 'powerpoint' => array( 'id' => 'file-powerpoint-o', ), 'previous' => array( 'id' => 'arrow-left', ), //print in defaults 'quotes' => array( 'id' => 'quote-left', ), 'ranking' => array( 'id' => 'sort-numeric-asc', ), //refresh in defaults //remove in defaults //repeat in defaults //rss in defaults //scissors in defaults 'screencapture' => array( 'id' => 'camera', ), //search in defaults 'selectall' => array( 'id' => 'file-text', ), //send in defaults 'settings' => array( 'id' => 'wrench', ), //share in defaults 'sharethis' => array( 'id' => 'share-alt', ), 'smile' => array( 'id' => 'smile-o', ), //sort in defaults 'sort-down' => array( 'id' => 'sort-desc', ), 'sort-up' => array( 'id' => 'sort-asc', ), //star in defaults 'star-empty' => array( 'id' => 'star-o', ), 'star-empty-selected' => array( 'id' => 'star-o', 'class' => 'text-success' ), 'star-half-rating' => array( 'id' => 'star-half-full', ), 'star-half-selected' => array( 'id' => 'star-half-full', 'class' => 'text-success' ), 'star-selected' => array( 'id' => 'star', 'class' => 'text-success' ), 'status-open' => array( 'id' => 'circle', 'style' => 'color:green' ), 'status-pending' => array( 'id' => 'adjust', 'style' => 'color:orange' ), 'status-closed' => array( 'id' => 'times-circle-o', 'style' => 'color:grey' ), //stop in defaults 'stop-watching' => array( 'id' => 'eye-slash', ), 'structure' => array( 'id' => 'sitemap', ), 'success' => array( 'id' => 'check', ), //table in defaults //tag in defaults //tags in defaults 'textfile' => array( 'id' => 'file-text-o', ), //th-list in defaults 'three-d' => array( 'id' => 'cube', ), //thumbs-down in defaults //thumbs-up in defaults 'time' => array( 'id' => 'clock-o', ), 'title' => array( 'id' => 'text-width', ), 'toggle-off' => array( 'id' => 'toggle-off', ), 'toggle-on' => array( 'id' => 'toggle-on', ), 'trackers' => array( 'id' => 'database', ), 'translate' => array( 'id' => 'language', ), 'trash' => array( 'id' => 'trash-o', ), //twitter in defaults //tv in defaults //undo in defaults //unlink in defaults //unlock in defaults 'unlike' => array( 'id' => 'thumbs-down', ), 'up' => array( 'id' => 'sort-asc', ), 'video' => array( 'id' => 'file-video-o', ), 'video_file' => array( 'id' => 'file-video-o', ), 'vimeo' => array( 'id' => 'vimeo-square', ), 'view' => array( 'id' => 'search-plus', ), 'warning' => array( 'id' => 'exclamation-triangle', ), 'watch' => array( 'id' => 'eye', ), 'watch-group' => array( 'id' => 'group', ), 'wiki' => array( 'id' => 'file-text-o', ), 'wizard' => array( 'id' => 'magic', ), 'word' => array( 'id' => 'file-word-o', ), 'wysiwyg' => array( 'id' => 'file-text', ), 'zip' => array( 'id' => 'file-zip-o', ), ), /* * All the available icons in this set (font-awesome in this case, * from http://fortawesome.github.io/Font-Awesome/cheatsheet/) * Version 4.5 */ 'defaults' => array( '500px', 'adjust', 'adn', 'align-center', 'align-justify', 'align-left', 'align-right', 'amazon', 'ambulance', 'anchor', 'android', 'angellist', 'angle-double-down', 'angle-double-left', 'angle-double-right', 'angle-double-up', 'angle-down', 'angle-left', 'angle-right', 'angle-up', 'apple', 'archive', 'area-chart', 'arrow-circle-down', 'arrow-circle-left', 'arrow-circle-o-down', 'arrow-circle-o-left', 'arrow-circle-o-right', 'arrow-circle-o-up', 'arrow-circle-right', 'arrow-circle-up', 'arrow-down', 'arrow-left', 'arrow-right', 'arrow-up', 'arrows', 'arrows-alt', 'arrows-h', 'arrows-v', 'asterisk', 'at', 'automobile', 'backward', 'balance-scale', 'ban', 'bank', 'bar-chart', 'bar-chart-o', 'barcode', 'bars', 'battery-0', 'battery-1', 'battery-2', 'battery-3', 'battery-4', 'battery-empty', 'battery-full', 'battery-half', 'battery-quarter', 'battery-three-quarters', 'bed', 'beer', 'behance', 'behance-square', 'bell', 'bell-o', 'bell-slash', 'bell-slash-o', 'bicycle', 'binoculars', 'birthday-cake', 'bitbucket', 'bitbucket-square', 'bitcoin', 'black-tie', 'bluetooth', 'bluetooth-b', 'bold', 'bolt', 'bomb', 'book', 'bookmark', 'bookmark-o', 'briefcase', 'btc', 'bug', 'building', 'building-o', 'bullhorn', 'bullseye', 'bus', 'buysellads', 'cab', 'calculator', 'calendar', 'calendar-check-o', 'calendar-minus-o', 'calendar-o', 'calendar-plus-o', 'calendar-times-o', 'camera', 'camera-retro', 'car', 'caret-down', 'caret-left', 'caret-right', 'caret-square-o-down', 'caret-square-o-left', 'caret-square-o-right', 'caret-square-o-up', 'caret-up', 'cart-arrow-down', 'cart-plus', 'cc', 'cc-amex', 'cc-diners-club', 'cc-discover', 'cc-jcb', 'cc-mastercard', 'cc-paypal', 'cc-stripe', 'cc-visa', 'certificate', 'chain', 'chain-broken', 'check', 'check-circle', 'check-circle-o', 'check-square', 'check-square-o', 'chevron-circle-down', 'chevron-circle-left', 'chevron-circle-right', 'chevron-circle-up', 'chevron-down', 'chevron-left', 'chevron-right', 'chevron-up', 'child', 'chrome', 'circle', 'circle-o', 'circle-o-notch', 'circle-thin', 'clipboard', 'clock-o', 'clone', 'close', 'cloud', 'cloud-download', 'cloud-upload', 'cny', 'code', 'code-fork', 'codepen', 'codiepie', 'coffee', 'cog', 'cogs', 'columns', 'comment', 'comment-o', 'commenting', 'commenting-o', 'comments', 'comments-o', 'compass', 'compress', 'connectdevelop', 'contao', 'copy', 'copyright', 'creative-commons', 'credit-card', 'credit-card-alt', 'crop', 'crosshairs', 'css3', 'cube', 'cubes', 'cut', 'cutlery', 'dashboard', 'dashcube', 'database', 'dedent', 'delicious', 'desktop', 'deviantart', 'diamond', 'digg', 'dollar', 'dot-circle-o', 'download', 'dribbble', 'dropbox', 'drupal', 'edge', 'edit', 'eject', 'ellipsis-h', 'ellipsis-v', 'empire', 'envelope', 'envelope-o', 'envelope-square', 'eraser', 'eur', 'euro', 'exchange', 'exclamation', 'exclamation-circle', 'exclamation-triangle', 'expand', 'expeditedssl', 'external-link', 'external-link-square', 'eye', 'eye-slash', 'eyedropper', 'facebook', 'facebook-official', 'facebook-square', 'fast-backward', 'fast-forward', 'fax', 'female', 'fighter-jet', 'file', 'file-archive-o', 'file-audio-o', 'file-code-o', 'file-excel-o', 'file-image-o', 'file-movie-o', 'file-o', 'file-pdf-o', 'file-photo-o', 'file-picture-o', 'file-powerpoint-o', 'file-sound-o', 'file-text', 'file-text-o', 'file-video-o', 'file-word-o', 'file-zip-o', 'files-o', 'film', 'filter', 'fire', 'fire-extinguisher', 'firefox', 'flag', 'flag-checkered', 'flag-o', 'flash', 'flask', 'flickr', 'floppy-o', 'folder', 'folder-o', 'folder-open', 'folder-open-o', 'font', 'fonticons', 'fort-awesome', 'forumbee', 'forward', 'foursquare', 'frown-o', 'futbol-o', 'gamepad', 'gavel', 'gbp', 'ge', 'gear', 'gears', 'genderless', 'get-pocket', 'gg', 'gg-circle', 'gift', 'git', 'git-square', 'github', 'github-alt', 'github-square', 'gittip', 'glass', 'globe', 'google', 'google-plus', 'google-plus-square', 'google-wallet', 'graduation-cap', 'group', 'h-square', 'hacker-news', 'hand-grab-o', 'hand-lizard-o', 'hand-o-down', 'hand-o-left', 'hand-o-right', 'hand-o-up', 'hand-paper-o', 'hand-peace-o', 'hand-pointer-o', 'hand-rock-o', 'hand-scissors-o', 'hand-spock-o', 'hand-stop-o', 'hashtag', 'hdd-o', 'header', 'headphones', 'heart', 'heartbeat', 'heart-o', 'history', 'home', 'hospital-o', 'hotel', 'hourglass', 'hourglass-1', 'hourglass-2', 'hourglass-3', 'hourglass-end', 'hourglass-half', 'hourglass-o', 'hourglass-start', 'houzz', 'html5', 'i-cursor', 'ils', 'image', 'inbox', 'indent', 'industry', 'info', 'info-circle', 'inr', 'instagram', 'institution', 'internet-explorer', 'ioxhost', 'italic', 'joomla', 'jpy', 'jsfiddle', 'key', 'keyboard-o', 'krw', 'language', 'laptop', 'lastfm', 'lastfm-square', 'leaf', 'leanpub', 'legal', 'lemon-o', 'level-down', 'level-up', 'life-bouy', 'life-buoy', 'life-ring', 'life-saver', 'lightbulb-o', 'line-chart', 'link', 'linkedin', 'linkedin-square', 'linux', 'list', 'list-alt', 'list-ol', 'list-ul', 'location-arrow', 'lock', 'long-arrow-down', 'long-arrow-left', 'long-arrow-right', 'long-arrow-up', 'magic', 'magnet', 'mail-forward', 'mail-reply', 'mail-reply-all', 'male', 'map', 'map-marker', 'map-o', 'map-pin', 'map-signs', 'mars', 'mars-double', 'mars-stroke', 'mars-stroke-h', 'mars-stroke-v', 'maxcdn', 'meanpath', 'medium', 'medkit', 'meh-o', 'mercury', 'microphone', 'microphone-slash', 'minus', 'minus-circle', 'minus-square', 'minus-square-o', 'mixcloud', 'mobile', 'mobile-phone', 'modx', 'money', 'moon-o', 'mortar-board', 'motorcycle', 'mouse-pointer', 'music', 'navicon', 'neuter', 'newspaper-o', 'object-group', 'object-ungroup', 'odnoklassniki', 'odnoklassniki-square', 'opencart', 'openid', 'opera', 'optin-monster', 'outdent', 'pagelines', 'paint-brush', 'paper-plane', 'paper-plane-o', 'paperclip', 'paragraph', 'paste', 'pause', 'pause-circle', 'pause-circle-o', 'paw', 'paypal', 'pencil', 'pencil-square', 'pencil-square-o', 'percent', 'phone', 'phone-square', 'photo', 'picture-o', 'pie-chart', 'pied-piper', 'pied-piper-alt', 'pinterest', 'pinterest-p', 'pinterest-square', 'plane', 'play', 'play-circle', 'play-circle-o', 'plug', 'plus', 'plus-circle', 'plus-square', 'plus-square-o', 'power-off', 'print', 'product-hunt', 'puzzle-piece', 'qq', 'qrcode', 'question', 'question-circle', 'quote-left', 'quote-right', 'ra', 'random', 'rebel', 'recycle', 'reddit', 'reddit-alien', 'reddit-square', 'refresh', 'registered', 'remove', 'renren', 'reorder', 'repeat', 'reply', 'reply-all', 'retweet', 'rmb', 'road', 'rocket', 'rotate-left', 'rotate-right', 'rouble', 'rss', 'rss-square', 'rub', 'ruble', 'rupee', 'safari', 'save', 'scissors', 'scribd', 'search', 'search-minus', 'search-plus', 'sellsy', 'send', 'send-o', 'server', 'share', 'share-alt', 'share-alt-square', 'share-square', 'share-square-o', 'shekel', 'sheqel', 'shield', 'ship', 'shirtsinbulk', 'shopping-bag', 'shopping-basket', 'shopping-cart', 'sign-in', 'sign-out', 'signal', 'simplybuilt', 'sitemap', 'skyatlas', 'skype', 'slack', 'sliders', 'slideshare', 'smile-o', 'soccer-ball-o', 'sort', 'sort-alpha-asc', 'sort-alpha-desc', 'sort-amount-asc', 'sort-amount-desc', 'sort-asc', 'sort-desc', 'sort-down', 'sort-numeric-asc', 'sort-numeric-desc', 'sort-up', 'soundcloud', 'space-shuttle', 'spinner', 'spoon', 'spotify', 'square', 'square-o', 'stack-exchange', 'stack-overflow', 'star', 'star-half', 'star-half-empty', 'star-half-full', 'star-half-o', 'star-o', 'steam', 'steam-square', 'step-backward', 'step-forward', 'stethoscope', 'sticky-note', 'sticky-note-o', 'stop', 'stop-circle', 'stop-circle-o', 'street-view', 'strikethrough', 'stumbleupon', 'stumbleupon-circle', 'subscript', 'subway', 'suitcase', 'sun-o', 'superscript', 'support', 'table', 'tablet', 'tachometer', 'tag', 'tags', 'tasks', 'taxi', 'television', 'tencent-weibo', 'terminal', 'text-height', 'text-width', 'th', 'th-large', 'th-list', 'thumb-tack', 'thumbs-down', 'thumbs-o-down', 'thumbs-o-up', 'thumbs-up', 'ticket', 'times', 'times-circle', 'times-circle-o', 'tint', 'toggle-down', 'toggle-left', 'toggle-off', 'toggle-on', 'toggle-right', 'toggle-up', 'trademark', 'train', 'transgender', 'transgender-alt', 'trash', 'trash-o', 'tree', 'trello', 'tripadvisor', 'trophy', 'truck', 'try', 'tty', 'tumblr', 'tumblr-square', 'turkish-lira', 'tv', 'twitch', 'twitter', 'twitter-square', 'umbrella', 'underline', 'undo', 'university', 'unlink', 'unlock', 'unlock-alt', 'unsorted', 'upload', 'usb', 'usd', 'user', 'user-md', 'user-plus', 'user-secret', 'user-times', 'users', 'venus', 'venus-double', 'venus-mars', 'viacoin', 'vimeo', 'video-camera', 'vimeo-square', 'vine', 'vk', 'volume-down', 'volume-off', 'volume-up', 'warning', 'wechat', 'weibo', 'weixin', 'wheelchair', 'wifi', 'wikipedia-w', 'windows', 'won', 'wordpress', 'wrench', 'xing', 'xing-square', 'y-combinator', 'yahoo', 'yc', 'yelp', 'yen', 'youtube', 'youtube-play', 'youtube-square', // new icons with v4.6 'american-sign-language-interpreting', 'asl-interpreting', 'assistive-listening-systems', 'audio-description', 'blind', 'braille', 'deaf', 'deafness', 'envira', 'fa', 'first-order', 'font-awesome', 'gitlab', 'glide', 'glide-g', 'google-plus-circle', 'google-plus-official', 'hard-of-hearing', 'instagram', 'low-vision', 'pied-piper', 'question-circle-o', 'sign-language', 'signing', 'snapchat', 'snapchat-ghost', 'snapchat-square', 'themeisle', 'universal-access', 'viadeo', 'viadeo-square', 'volume-control-phone', 'wheelchair-alt', 'wpbeginner', 'wpforms', 'yoast', // new icons in 4.7 'address-book', 'address-book-o', 'address-card', 'address-card-o', 'bandcamp', 'bath', 'bathtub', 'drivers-license', 'drivers-license-o', 'eercast', 'envelope-open', 'envelope-open-o', 'etsy', 'free-code-camp', 'grav', 'handshake-o', 'id-badge', 'id-card', 'id-card-o', 'imdb', 'linode', 'meetup', 'microchip', 'podcast', 'quora', 'ravelry', 's15', 'shower', 'snowflake-o', 'superpowers', 'telegram', 'thermometer', 'thermometer-0', 'thermometer-1', 'thermometer-2', 'thermometer-3', 'thermometer-4', 'thermometer-empty', 'thermometer-full', 'thermometer-half', 'thermometer-quarter', 'thermometer-three-quarters', 'times-rectangle', 'times-rectangle-o', 'user-circle', 'user-circle-o', 'user-o', 'vcard', 'vcard-o', 'window-close', 'window-close-o', 'window-maximize', 'window-minimize', 'window-restore', 'wpexplorer', ), ); }
lgpl-2.1
MASTmultiphysics/mast-multiphysics
src/mesh/fe_base.cpp
9517
/* * MAST: Multidisciplinary-design Adaptation and Sensitivity Toolkit * Copyright (C) 2013-2020 Manav Bhatia and MAST authors * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // MAST includes #include "mesh/fe_base.h" #include "mesh/geom_elem.h" #include "base/system_initialization.h" #include "base/nonlinear_system.h" MAST::FEBase::FEBase(const MAST::SystemInitialization& sys): _sys (sys), _extra_quadrature_order (0), _init_second_order_derivatives (false), _initialized (false), _elem (nullptr), _fe (nullptr), _qrule (nullptr) { } MAST::FEBase::~FEBase() { if (_fe) delete _fe; if (_qrule) delete _qrule; } void MAST::FEBase::set_extra_quadrature_order(int n) { _extra_quadrature_order = n; } void MAST::FEBase::set_evaluate_second_order_derivatives(bool f) { _init_second_order_derivatives = f; } void MAST::FEBase::init(const MAST::GeomElem& elem, bool init_grads, const std::vector<libMesh::Point>* pts) { libmesh_assert(!_initialized); _elem = &elem; const unsigned int nv = _sys.n_vars(); libMesh::FEType fe_type = _sys.fetype(0); // all variables are assumed to be of same type for (unsigned int i=1; i != nv; ++i) libmesh_assert(fe_type == _sys.fetype(i)); const libMesh::Elem* q_elem = nullptr; if (elem.use_local_elem()) q_elem = &elem.get_quadrature_local_elem(); else q_elem = &elem.get_quadrature_elem(); // Create an adequate quadrature rule _fe = libMesh::FEBase::build(q_elem->dim(), fe_type).release(); _fe->get_phi(); _fe->get_xyz(); _fe->get_JxW(); if (init_grads) { _fe->get_dphi(); _fe->get_dphidxi(); _fe->get_dphideta(); _fe->get_dphidzeta(); } if (_init_second_order_derivatives) _fe->get_d2phi(); if (pts == nullptr) { _qrule = fe_type.default_quadrature_rule (q_elem->dim(), _sys.system().extra_quadrature_order+_extra_quadrature_order).release(); // system extra quadrature _fe->attach_quadrature_rule(_qrule); _fe->reinit(q_elem); } else { _fe->reinit(q_elem, pts); _qpoints = *pts; } // now initialize the global xyz locations if the element uses a locally // defined element. if (elem.use_local_elem()) { const std::vector<libMesh::Point> local_xyz = _fe->get_xyz(); unsigned int n = (unsigned int) local_xyz.size(); _global_xyz.resize(n); for (unsigned int i=0; i<n; i++) elem.transform_point_to_global_coordinate(local_xyz[i], _global_xyz[i]); } _initialized = true; } void MAST::FEBase::init_for_side(const MAST::GeomElem& elem, unsigned int s, bool if_calculate_dphi) { libmesh_assert(!_initialized); _elem = &elem; const unsigned int nv = _sys.n_vars(); libmesh_assert (nv); libMesh::FEType fe_type = _sys.fetype(0); // all variables are assumed to be of same type for (unsigned int i=1; i != nv; ++i) libmesh_assert(fe_type == _sys.fetype(i)); const libMesh::Elem* q_elem = nullptr; if (elem.use_local_elem()) q_elem = &elem.get_quadrature_local_elem(); else q_elem = &elem.get_quadrature_elem(); // Create an adequate quadrature rule _fe = libMesh::FEBase::build(q_elem->dim(), fe_type).release(); _qrule = fe_type.default_quadrature_rule (q_elem->dim()-1, _sys.system().extra_quadrature_order+_extra_quadrature_order).release(); // system extra quadrature _fe->attach_quadrature_rule(_qrule); _fe->get_phi(); _fe->get_xyz(); _fe->get_JxW(); _fe->get_normals(); if (if_calculate_dphi) { _fe->get_dphi(); if (_init_second_order_derivatives) _fe->get_d2phi(); } _fe->reinit(q_elem, s); // now initialize the global xyz locations and normals _local_normals = _fe->get_normals(); if (elem.use_local_elem()) { const std::vector<libMesh::Point> &local_xyz = _fe->get_xyz(); unsigned int n = (unsigned int) local_xyz.size(); _global_xyz.resize(n); _global_normals.resize(n); for (unsigned int i=0; i<n; i++) { elem.transform_point_to_global_coordinate(local_xyz[i], _global_xyz[i]); elem.transform_vector_to_global_coordinate(_local_normals[i], _global_normals[i]); } } else { _global_normals = _local_normals; _global_xyz = _fe->get_xyz(); } _initialized = true; } libMesh::FEType MAST::FEBase::get_fe_type() const { libmesh_assert(_initialized); return _fe->get_fe_type(); } const std::vector<Real>& MAST::FEBase::get_JxW() const { libmesh_assert(_initialized); return _fe->get_JxW(); } const std::vector<libMesh::Point>& MAST::FEBase::get_xyz() const { libmesh_assert(_initialized); if (_elem->use_local_elem()) return _global_xyz; else return _fe->get_xyz(); } unsigned int MAST::FEBase::n_shape_functions() const { libmesh_assert(_initialized); return _fe->n_shape_functions(); } const std::vector<std::vector<Real> >& MAST::FEBase::get_phi() const { libmesh_assert(_initialized); return _fe->get_phi(); } const std::vector<std::vector<libMesh::RealVectorValue> >& MAST::FEBase::get_dphi() const { libmesh_assert(_initialized); return _fe->get_dphi(); } const std::vector<std::vector<libMesh::RealTensorValue>>& MAST::FEBase::get_d2phi() const { libmesh_assert(_initialized); return _fe->get_d2phi(); } const std::vector<Real>& MAST::FEBase::get_dxidx() const { libmesh_assert(_initialized); return _fe->get_dxidx(); } const std::vector<Real>& MAST::FEBase::get_dxidy() const { libmesh_assert(_initialized); return _fe->get_dxidy(); } const std::vector<Real>& MAST::FEBase::get_dxidz() const { libmesh_assert(_initialized); return _fe->get_dxidz(); } const std::vector<Real>& MAST::FEBase::get_detadx() const { libmesh_assert(_initialized); return _fe->get_detadx(); } const std::vector<Real>& MAST::FEBase::get_detady() const { libmesh_assert(_initialized); return _fe->get_detady(); } const std::vector<Real>& MAST::FEBase::get_detadz() const { libmesh_assert(_initialized); return _fe->get_detadz(); } const std::vector<Real>& MAST::FEBase::get_dzetadx() const { libmesh_assert(_initialized); return _fe->get_dzetadx(); } const std::vector<Real>& MAST::FEBase::get_dzetady() const { libmesh_assert(_initialized); return _fe->get_dzetady(); } const std::vector<Real>& MAST::FEBase::get_dzetadz() const { libmesh_assert(_initialized); return _fe->get_dzetadz(); } const std::vector<libMesh::RealVectorValue>& MAST::FEBase::get_dxyzdxi() const { libmesh_assert(_initialized); return _fe->get_dxyzdxi(); } const std::vector<libMesh::RealVectorValue>& MAST::FEBase::get_dxyzdeta() const { libmesh_assert(_initialized); return _fe->get_dxyzdeta(); } const std::vector<libMesh::RealVectorValue>& MAST::FEBase::get_dxyzdzeta() const { libmesh_assert(_initialized); return _fe->get_dxyzdzeta(); } const std::vector<std::vector<Real> >& MAST::FEBase::get_dphidxi() const { libmesh_assert(_initialized); return _fe->get_dphidxi(); } const std::vector<std::vector<Real> >& MAST::FEBase::get_dphideta() const { libmesh_assert(_initialized); return _fe->get_dphideta(); } const std::vector<std::vector<Real> >& MAST::FEBase::get_dphidzeta() const { libmesh_assert(_initialized); return _fe->get_dphidzeta(); } const std::vector<libMesh::Point>& MAST::FEBase::get_normals_for_reference_coordinate() const { libmesh_assert(_initialized); return _global_normals; } const std::vector<libMesh::Point>& MAST::FEBase::get_normals_for_local_coordinate() const { libmesh_assert(_initialized); return _local_normals; } const std::vector<libMesh::Point>& MAST::FEBase::get_qpoints() const { libmesh_assert(_initialized); if (_qrule) // qrule was used return _qrule->get_points(); else // points were specified return _qpoints; } const libMesh::QBase& MAST::FEBase::get_qrule() const { libmesh_assert(_initialized); return *_qrule; }
lgpl-2.1
ExRam/DotSpatial-PCL
DotSpatial.Tools/ClipRasterWithPolygon.cs
4154
// ******************************************************************************************************* // Product: DotSpatial.Tools.RandomGeometry // Description: Tool that clips a raster layer with a polygon. // Copyright & License: See www.DotSpatial.org. // Contributor(s): Open source contributors may list themselves and their modifications here. // Contribution of code constitutes transferral of copyright from authors to DotSpatial copyright holders. //-------------------------------------------------------------------------------------------------------- // Name | Date | Comments //--------------------|--------------------|-------------------------------------------------------------- // Ted Dunsford | 8/24/2009 | Cleaned up some unnecessary references using re-sharper // KP | 9/2009 | Used IDW as model for ClipwithPolygon // Ping | 12/2009 | Cleaning code and fixing bugs. // ******************************************************************************************************** using DotSpatial.Analysis; using DotSpatial.Data; using DotSpatial.Modeling.Forms; namespace DotSpatial.Tools { /// <summary> /// Clip With Polygon /// </summary> public class ClipRasterWithPolygon : Tool { #region Constants and Fields private Parameter[] _inputParam; private Parameter[] _outputParam; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the ClipRasterWithPolygon class. /// </summary> public ClipRasterWithPolygon() { this.Name = TextStrings.ClipRasterLayer; this.Category = TextStrings.Analysis; this.Description = TextStrings.ClipGridswithPolygon; this.ToolTip = TextStrings.ClipRasterLayerwithPolygon; } #endregion #region Public Properties /// <summary> /// Gets or Sets the input paramater array /// </summary> public override Parameter[] InputParameters { get { return _inputParam; } } /// <summary> /// Gets or Sets the output paramater array /// </summary> public override Parameter[] OutputParameters { get { return _outputParam; } } #endregion #region Public Methods /// <summary> /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful /// </summary> public override bool Execute(ICancelProgressHandler cancelProgressHandler) { IRaster raster = _inputParam[0].Value as IRaster; IFeatureSet polygon = _inputParam[1].Value as IFeatureSet; IRaster output = _outputParam[0].Value as IRaster; // Validates the input and output data if (raster == null || polygon == null || output == null) { return false; } ClipRaster.ClipRasterWithPolygon( polygon.Features[0], raster, output.Filename, cancelProgressHandler); return true; } /// <summary> /// The Parameter array should be populated with default values here /// </summary> public override void Initialize() { _inputParam = new Parameter[2]; _inputParam[0] = new RasterParam(TextStrings.input1Raster) { HelpText = TextStrings.InputRasterforCliping }; _inputParam[1] = new PolygonFeatureSetParam(TextStrings.input2PolygonforCliping) { HelpText = TextStrings.InputPolygonforclipingtoRaster }; _outputParam = new Parameter[1]; _outputParam[0] = new RasterParam(TextStrings.OutputRaster) { HelpText = TextStrings.ResultRasterDirectory }; } #endregion } }
lgpl-2.1
mbatchelor/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/modules/output/fast/csv/FastCsvExportTemplate.java
3123
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2006 - 2017 Hitachi Vantara.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.modules.output.fast.csv; import org.pentaho.reporting.engine.classic.core.Band; import org.pentaho.reporting.engine.classic.core.InvalidReportStateException; import org.pentaho.reporting.engine.classic.core.ReportDefinition; import org.pentaho.reporting.engine.classic.core.ReportProcessingException; import org.pentaho.reporting.engine.classic.core.function.ExpressionRuntime; import org.pentaho.reporting.engine.classic.core.layout.output.OutputProcessorMetaData; import org.pentaho.reporting.engine.classic.core.modules.output.fast.FastExportTemplate; import org.pentaho.reporting.engine.classic.core.modules.output.fast.template.FastSheetLayoutProducer; import org.pentaho.reporting.engine.classic.core.modules.output.table.base.SheetLayout; import java.io.OutputStream; public class FastCsvExportTemplate implements FastExportTemplate { private OutputStream outputStream; private String encoding; private SheetLayout sharedSheetLayout; private FastExportTemplate processor; public FastCsvExportTemplate( final OutputStream outputStream, final String encoding ) { this.outputStream = outputStream; this.encoding = encoding; } public void initialize( final ReportDefinition report, final ExpressionRuntime runtime, final boolean pagination ) { OutputProcessorMetaData metaData = runtime.getProcessingContext().getOutputProcessorMetaData(); if ( pagination ) { this.sharedSheetLayout = new SheetLayout( metaData ); this.processor = new FastSheetLayoutProducer( sharedSheetLayout ); this.processor.initialize( report, runtime, pagination ); } else { this.processor = new FastCsvContentProducerTemplate( sharedSheetLayout, outputStream, encoding ); this.processor.initialize( report, runtime, pagination ); } } public void write( final Band band, final ExpressionRuntime runtime ) throws InvalidReportStateException { try { this.processor.write( band, runtime ); } catch ( InvalidReportStateException re ) { throw re; } catch ( Exception e ) { throw new InvalidReportStateException( "Other failure", e ); } } public void finishReport() throws ReportProcessingException { this.processor.finishReport(); } }
lgpl-2.1
terryrao/test
src/main/java/org/raowei/test/concurrents/JoinMain.java
476
package org.raowei.test.concurrents; public class JoinMain { static volatile int i; public static class AddThread extends Thread { @Override public void run() { for ( i = 0; i < 10000; i++) { } } } public static void main(String[] args) throws InterruptedException { Thread t = new AddThread(); t.start(); t.join(); // 等待 t 线程执行完 System.out.println(i); } }
lgpl-2.1
FedoraScientific/salome-kernel
src/UnitTests/UnitTests.py
2489
# -*- coding: iso-8859-1 -*- # Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE # # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS # # This library 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. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # import sys, os,signal,string,commands import subprocess import runSalome import setenv import orbmodule import TestKiller # get SALOME environment : args, modules_list, modules_root_dir = setenv.get_config() setenv.set_env(args, modules_list, modules_root_dir) # set environment for trace in logger # (with file, servers may be killed before the write to the file...) #os.environ["SALOME_trace"] = "file:/tmp/traceUnitTest.log" #os.environ["SALOME_trace"] = "local" os.environ["SALOME_trace"] = "with_logger" # launch CORBA naming server clt=orbmodule.client() # launch CORBA logger server myServer=runSalome.LoggerServer(args) myServer.run() clt.waitLogger("Logger") # launch registry server myServer=runSalome.RegistryServer(args) myServer.run() clt.waitNS("/Registry") # launch module catalog server cataServer=runSalome.CatalogServer(args) cataServer.setpath(modules_list,modules_root_dir) cataServer.run() clt.waitNS("/Kernel/ModulCatalog") # launch container manager server myCmServer = runSalome.LauncherServer(args) myCmServer.setpath(modules_list,modules_root_dir) myCmServer.run() clt.waitNS("/SalomeLauncher") # execute Unit Test command = ['./UnitTests'] ret = subprocess.call(command) # kill containers created by the Container Manager import Engines launcher = clt.waitNS("/SalomeLauncher",Engines.SalomeLauncher) launcher.Shutdown() # kill Test process TestKiller.killProcess(runSalome.process_id) TestKiller.closeSalome() exit(ret)
lgpl-2.1
scorredoira/liteide
liteidex/src/plugins/liteeditor/liteeditor.cpp
55357
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved. ** ** This library 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. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: liteeditor.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditor.h" #include "liteeditorwidget.h" #include "liteeditorfile.h" #include "litecompleter.h" #include "litewordcompleter.h" #include "liteeditor_global.h" #include "colorstyle/colorstyle.h" #include "qtc_texteditor/generichighlighter/highlighter.h" #include "qtc_editutil/uncommentselection.h" #include "functiontooltip.h" #include "quickopenapi/quickopenapi.h" #include <QFileInfo> #include <QVBoxLayout> #include <QToolBar> #include <QAction> #include <QApplication> #include <QClipboard> #include <QMimeData> #include <QComboBox> #include <QLabel> #include <QLineEdit> #include <QTextDocument> #include <QStringListModel> #include <QStandardItemModel> #include <QStandardItem> #include <QTextCursor> #include <QToolTip> #include <QFileDialog> #include <QPrinter> #include <QTextDocumentWriter> #include <QPrintDialog> #include <QPrintPreviewDialog> #include <QPageSetupDialog> #include <QTextCodec> #include <QDebug> #include <QPalette> #include <QTimer> #include <QMessageBox> #include <QTextBlock> #include <QMenu> #include <QInputDialog> #include <QToolButton> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteEditor::LiteEditor(LiteApi::IApplication *app) : m_liteApp(app), m_extension(new Extension), m_completer(0), m_funcTip(0), m_bReadOnly(false) { m_syntax = 0; m_widget = new QWidget; m_editorWidget = new LiteEditorWidget(app,m_widget); m_editorWidget->setCursorWidth(2); //m_editorWidget->setAcceptDrops(false); m_defEditorPalette = m_editorWidget->palette(); createActions(); //createToolBars(); createMenu(); m_editorWidget->setContextMenu(m_contextMenu); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); /* m_toolBar->setStyleSheet("QToolBar {border: 1px ; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #eeeeee, stop: 1 #ababab); }"\ "QToolBar QToolButton { border:1px ; border-radius: 1px; }"\ "QToolBar QToolButton::hover { background-color: #ababab;}"\ "QToolBar::separator {width:2px; margin-left:2px; margin-right:2px; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #dedede, stop: 1 #a0a0a0);}"); */ // QHBoxLayout *toolLayout = new QHBoxLayout; // toolLayout->setMargin(0); // toolLayout->setSpacing(0); // toolLayout->addWidget(m_editToolBar); // //toolLayout->addWidget(m_infoToolBar); // layout->addLayout(toolLayout); // QHBoxLayout *hlayout = new QHBoxLayout; // hlayout->addWidget(m_editorWidget); // hlayout->addWidget(m_editorWidget->navigateArea()); //layout->addLayout(hlayout); layout->addWidget(m_editorWidget); m_widget->setLayout(layout); m_file = new LiteEditorFile(m_liteApp,this); m_file->setDocument(m_editorWidget->document()); // QTextOption option = m_editorWidget->document()->defaultTextOption(); // option.setFlags(option.flags() | QTextOption::ShowTabsAndSpaces); // option.setFlags(option.flags() | QTextOption::AddSpaceForLineAndParagraphSeparators); // option.setTabs(tabs); // m_editorWidget->document()->setDefaultTextOption(option); setEditToolbarVisible(true); connect(m_file->document(),SIGNAL(modificationChanged(bool)),this,SIGNAL(modificationChanged(bool))); connect(m_file->document(),SIGNAL(contentsChanged()),this,SIGNAL(contentsChanged())); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); connect(m_liteApp->editorManager(),SIGNAL(colorStyleSchemeChanged()),this,SLOT(loadColorStyleScheme())); connect(m_liteApp->editorManager(),SIGNAL(editToolbarVisibleChanged(bool)),this,SLOT(setEditToolbarVisible(bool))); //applyOption("option/liteeditor"); LiteApi::IEditContext *editContext = new EditContext(this,this); m_extension->addObject("LiteApi.ITextEditor",this); m_extension->addObject("LiteApi.ILiteEditor",this); //m_extension->addObject("LiteApi.QToolBar.Edit",m_editToolBar); m_extension->addObject("LiteApi.QPlainTextEdit",m_editorWidget); m_extension->addObject("LiteApi.ContextMenu",m_contextMenu); m_extension->addObject("LiteApi.Menu.Edit",m_editMenu); m_extension->addObject("LiteApi.IEditContext",editContext); m_editorWidget->installEventFilter(m_liteApp->editorManager()); connect(m_editorWidget,SIGNAL(cursorPositionChanged()),this,SLOT(editPositionChanged())); connect(m_editorWidget,SIGNAL(navigationStateChanged(QByteArray)),this,SLOT(navigationStateChanged(QByteArray))); //connect(m_editorWidget,SIGNAL(overwriteModeChanged(bool)),m_overInfoAct,SLOT(setVisible(bool))); connect(m_editorWidget,SIGNAL(requestFontZoom(int)),this,SLOT(requestFontZoom(int))); connect(m_editorWidget,SIGNAL(updateLink(QTextCursor,QPoint,bool)),this,SIGNAL(updateLink(QTextCursor,QPoint,bool))); //connect(m_lineInfo,SIGNAL(doubleClickEvent()),this,SLOT(gotoLine())); //connect(m_closeEditorAct,SIGNAL(triggered()),m_liteApp->editorManager(),SLOT(closeEditor())); connect(m_liteApp,SIGNAL(broadcast(QString,QString,QString)),this,SLOT(broadcast(QString,QString,QString))); } LiteEditor::~LiteEditor() { if (m_completer) { delete m_completer; } if (m_funcTip) { delete m_funcTip; } delete m_contextMenu; delete m_editMenu; delete m_extension; delete m_editorWidget; delete m_widget; delete m_file; } QTextDocument *LiteEditor::document() const { return m_editorWidget->document(); } void LiteEditor::setEditorMark(LiteApi::IEditorMark *mark) { m_editorWidget->setEditorMark(mark); m_extension->addObject("LiteApi.IEditorMark",mark); } void LiteEditor::setTextLexer(LiteApi::ITextLexer *lexer) { m_extension->addObject("LiteApi.ITextLexer",lexer); m_editorWidget->setTextLexer(lexer); } void LiteEditor::setSyntaxHighlighter(TextEditor::SyntaxHighlighter *syntax) { m_syntax = syntax; m_extension->addObject("TextEditor::SyntaxHighlighter",syntax); m_commentAct->setVisible(m_syntax && !m_syntax->comment().isEmpty()); } TextEditor::SyntaxHighlighter *LiteEditor::syntaxHighlighter() const { return m_syntax; } void LiteEditor::setCompleter(LiteApi::ICompleter *complter) { if (m_completer) { QObject::disconnect(m_completer, 0, m_editorWidget, 0); delete m_completer; m_completer = 0; } m_completer = complter; if (!m_completer) { return; } m_completer->setEditor(m_editorWidget); m_editorWidget->setCompleter(m_completer); m_extension->addObject("LiteApi.ICompleter",m_completer); connect(m_editorWidget,SIGNAL(completionPrefixChanged(QString,bool)),m_completer,SLOT(completionPrefixChanged(QString,bool))); connect(m_completer,SIGNAL(wordCompleted(QString,QString,QString)),this,SLOT(updateTip(QString,QString,QString))); } void LiteEditor::clipbordDataChanged() { QClipboard *clipboard = QApplication::clipboard(); if (clipboard->mimeData()->hasText() || clipboard->mimeData()->hasHtml()) { m_pasteAct->setEnabled(true); } else { m_pasteAct->setEnabled(false); } } void LiteEditor::createActions() { LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"Editor"); m_undoAct = new QAction(QIcon("icon:liteeditor/images/undo.png"),tr("Undo"),this); actionContext->regAction(m_undoAct,"Undo",QKeySequence::Undo); m_undoAct->setEnabled(false); m_redoAct = new QAction(QIcon("icon:liteeditor/images/redo.png"),tr("Redo"),this); actionContext->regAction(m_redoAct,"Redo","Ctrl+Shift+Z; Ctrl+Y"); m_redoAct->setEnabled(false); m_cutAct = new QAction(QIcon("icon:liteeditor/images/cut.png"),tr("Cut"),this); actionContext->regAction(m_cutAct,"Cut",QKeySequence::Cut); m_cutAct->setEnabled(false); m_copyAct = new QAction(QIcon("icon:liteeditor/images/copy.png"),tr("Copy"),this); actionContext->regAction(m_copyAct,"Copy",QKeySequence::Copy); m_copyAct->setEnabled(false); m_pasteAct = new QAction(QIcon("icon:liteeditor/images/paste.png"),tr("Paste"),this); actionContext->regAction(m_pasteAct,"Paste",QKeySequence::Paste); m_selectAllAct = new QAction(tr("Select All"),this); actionContext->regAction(m_selectAllAct,"SelectAll",QKeySequence::SelectAll); m_exportHtmlAct = new QAction(QIcon("icon:liteeditor/images/exporthtml.png"),tr("Export HTML..."),this); #ifndef QT_NO_PRINTER m_exportPdfAct = new QAction(QIcon("icon:liteeditor/images/exportpdf.png"),tr("Export PDF..."),this); m_filePrintAct = new QAction(QIcon("icon:liteeditor/images/fileprint.png"),tr("Print..."),this); m_filePrintPreviewAct = new QAction(QIcon("icon:liteeditor/images/fileprintpreview.png"),tr("Print Preview..."),this); #endif m_gotoPrevBlockAct = new QAction(tr("Go to Previous Block"),this); actionContext->regAction(m_gotoPrevBlockAct,"GotoPreviousBlock","Ctrl+["); m_gotoNextBlockAct = new QAction(tr("Go to Next Block"),this); actionContext->regAction(m_gotoNextBlockAct,"GotoNextBlock","Ctrl+]"); m_selectBlockAct = new QAction(tr("Select Block"),this); actionContext->regAction(m_selectBlockAct,"SelectBlock","Ctrl+U"); m_gotoMatchBraceAct = new QAction(tr("Go to Matching Brace"),this); actionContext->regAction(m_gotoMatchBraceAct,"GotoMatchBrace","Ctrl+E"); m_gotoDocStartAct = new QAction(tr("Go to Doc Start"),this); actionContext->regAction(m_gotoDocStartAct,"GotoDocStart",""); connect(m_gotoDocStartAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoDocStart())); m_gotoDocEndAct = new QAction(tr("Go to Doc End"),this); actionContext->regAction(m_gotoDocEndAct,"GotoDocEnd",""); connect(m_gotoDocEndAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoDocEnd())); m_gotoLineStartAct = new QAction(tr("Go to Line Start"),this); actionContext->regAction(m_gotoLineStartAct,"GotoLineStart",""); connect(m_gotoLineStartAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoLineStart())); m_gotoLineEndAct = new QAction(tr("Go to Line End"),this); actionContext->regAction(m_gotoLineEndAct,"GotoLineEnd",""); connect(m_gotoLineEndAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoLineEnd())); m_gotoPrevLineAct = new QAction(tr("Go to Previous Line"),this); actionContext->regAction(m_gotoPrevLineAct,"GotoPreviousLine",""); connect(m_gotoPrevLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoPreviousLine())); m_gotoNextLineAct = new QAction(tr("Go to Next Line"),this); actionContext->regAction(m_gotoNextLineAct,"GotoNextLine",""); connect(m_gotoNextLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoNextLine())); m_gotoPrevCharacterAct = new QAction(tr("Go to Previous Character"),this); actionContext->regAction(m_gotoPrevCharacterAct,"GotoPreviousCharacter",""); connect(m_gotoPrevCharacterAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoPreviousCharacter())); m_gotoNextCharacterAct = new QAction(tr("Go to Next Charater"),this); actionContext->regAction(m_gotoNextCharacterAct,"GotoNextCharater",""); connect(m_gotoNextCharacterAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoNextCharacter())); m_gotoPrevWordAct = new QAction(tr("Go to Previous Word"),this); actionContext->regAction(m_gotoPrevWordAct,"GotoPreviousWord",""); connect(m_gotoPrevWordAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoPreviousWord())); m_gotoNextWordAct = new QAction(tr("Go to Next Word"),this); actionContext->regAction(m_gotoNextWordAct,"GotoNextWord",""); connect(m_gotoNextWordAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoNextWord())); m_foldAct = new QAction(tr("Fold"),this); actionContext->regAction(m_foldAct,"Fold","Ctrl+<"); m_unfoldAct = new QAction(tr("Unfold"),this); actionContext->regAction(m_unfoldAct,"Unfold","Ctrl+>"); m_foldAllAct = new QAction(tr("Fold All"),this); actionContext->regAction(m_foldAllAct,"FoldAll",""); m_unfoldAllAct = new QAction(tr("Unfold All"),this); actionContext->regAction(m_unfoldAllAct,"UnfoldAll",""); connect(m_foldAct,SIGNAL(triggered()),m_editorWidget,SLOT(fold())); connect(m_unfoldAct,SIGNAL(triggered()),m_editorWidget,SLOT(unfold())); connect(m_foldAllAct,SIGNAL(triggered()),m_editorWidget,SLOT(foldAll())); connect(m_unfoldAllAct,SIGNAL(triggered()),m_editorWidget,SLOT(unfoldAll())); m_gotoLineAct = new QAction(tr("Go to Line"),this); actionContext->regAction(m_gotoLineAct,"GotoLine","Ctrl+L"); m_lockAct = new QAction(QIcon("icon:liteeditor/images/lock.png"),tr("Locked"),this); m_lockAct->setEnabled(false); m_duplicateAct = new QAction(tr("Duplicate"),this); actionContext->regAction(m_duplicateAct,"Duplicate","Ctrl+Shift+D"); connect(m_duplicateAct,SIGNAL(triggered()),m_editorWidget,SLOT(duplicate())); m_deleteLineAct = new QAction(tr("Delete Line"),this); actionContext->regAction(m_deleteLineAct,"DeleteLine","Ctrl+Shift+K"); connect(m_deleteLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(deleteLine())); m_copyLineAct = new QAction(tr("Copy Line"),this); actionContext->regAction(m_copyLineAct,"CopyLine","Ctrl+Ins"); connect(m_copyLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(copyLine())); m_cutLineAct = new QAction(tr("Cut Line"),this); actionContext->regAction(m_cutLineAct,"CutLine","Shift+Del"); connect(m_cutLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(cutLine())); m_insertLineBeforeAct = new QAction(tr("Insert Line Before"),this); actionContext->regAction(m_insertLineBeforeAct,"InsertLineBefore","Ctrl+Shift+Return"); connect(m_insertLineBeforeAct,SIGNAL(triggered()),m_editorWidget,SLOT(insertLineBefore())); m_insertLineAfterAct = new QAction(tr("Insert Line After"),this); actionContext->regAction(m_insertLineAfterAct,"InsertLineAfter","Ctrl+Return"); connect(m_insertLineAfterAct,SIGNAL(triggered()),m_editorWidget,SLOT(insertLineAfter())); m_increaseFontSizeAct = new QAction(tr("Increase Font Size"),this); actionContext->regAction(m_increaseFontSizeAct,"IncreaseFontSize","Ctrl++"); m_decreaseFontSizeAct = new QAction(tr("Decrease Font Size"),this); actionContext->regAction(m_decreaseFontSizeAct,"DecreaseFontSize","Ctrl+-"); m_resetFontSizeAct = new QAction(tr("Reset Font Size"),this); actionContext->regAction(m_resetFontSizeAct,"ResetFontSize","Ctrl+0"); m_cleanWhitespaceAct = new QAction(tr("Clean Whitespace"),this); actionContext->regAction(m_cleanWhitespaceAct,"CleanWhitespace",""); m_wordWrapAct = new QAction(tr("Word Wrap (MimeType)"),this); m_wordWrapAct->setCheckable(true); actionContext->regAction(m_wordWrapAct,"WordWrap",""); m_codeCompleteAct = new QAction(tr("Code Complete"),this); #ifdef Q_OS_MAC actionContext->regAction(m_codeCompleteAct,"CodeComplete","Meta+Space"); #else actionContext->regAction(m_codeCompleteAct,"CodeComplete","Ctrl+Space"); #endif m_commentAct = new QAction(tr("Toggle Comment"),this); actionContext->regAction(m_commentAct,"Comment","Ctrl+/"); m_blockCommentAct = new QAction(tr("Toggle Block Commnet"),this); actionContext->regAction(m_blockCommentAct,"BlockComment","Ctrl+Shift+/"); m_autoIndentAct = new QAction(tr("Auto-indent Selection"),this); actionContext->regAction(m_autoIndentAct,"AutoIndent","Ctrl+I"); m_autoIndentAct->setVisible(false); m_tabToSpacesAct = new QAction(tr("Tab To Spaces (MimeType)"),this); actionContext->regAction(m_tabToSpacesAct,"TabToSpaces",""); m_tabToSpacesAct->setCheckable(true); m_lineEndingWindowAct = new QAction(tr("Line End Windows (\\r\\n)"),this); actionContext->regAction(m_lineEndingWindowAct,"LineEndingWindow",""); m_lineEndingWindowAct->setCheckable(true); m_lineEndingUnixAct = new QAction(tr("Line End Unix (\\n)"),this); actionContext->regAction(m_lineEndingUnixAct,"LineEndingUnix",""); m_lineEndingUnixAct->setCheckable(true); m_visualizeWhitespaceAct = new QAction(tr("Visualize Whitespace (Global)"),this); actionContext->regAction(m_visualizeWhitespaceAct,"VisualizeWhitespace",""); m_visualizeWhitespaceAct->setCheckable(true); m_commentAct->setVisible(false); m_blockCommentAct->setVisible(false); m_moveLineUpAction = new QAction(tr("Move Line Up"),this); actionContext->regAction(m_moveLineUpAction,"MoveLineUp","Ctrl+Shift+Up"); m_moveLineDownAction = new QAction(tr("Move Line Down"),this); actionContext->regAction(m_moveLineDownAction,"MoveLineDown","Ctrl+Shift+Down"); m_copyLineUpAction = new QAction(tr("Copy Line Up"),this); actionContext->regAction(m_copyLineUpAction,"CopyLineUp","Ctrl+Alt+Up"); m_copyLineDownAction = new QAction(tr("Copy Line Down"),this); actionContext->regAction(m_copyLineDownAction,"CopyLineDown","Ctrl+Alt+Down"); m_joinLinesAction = new QAction(tr("Join Lines"),this); actionContext->regAction(m_joinLinesAction,"JoinLines","Ctrl+J"); connect(m_codeCompleteAct,SIGNAL(triggered()),m_editorWidget,SLOT(codeCompleter())); // m_widget->addAction(m_foldAct); // m_widget->addAction(m_unfoldAct); // m_widget->addAction(m_gotoLineAct); // m_widget->addAction(m_gotoPrevBlockAct); // m_widget->addAction(m_gotoNextBlockAct); // m_widget->addAction(m_selectBlockAct); // m_widget->addAction(m_gotoMatchBraceAct); connect(m_editorWidget,SIGNAL(undoAvailable(bool)),m_undoAct,SLOT(setEnabled(bool))); connect(m_editorWidget,SIGNAL(redoAvailable(bool)),m_redoAct,SLOT(setEnabled(bool))); connect(m_editorWidget,SIGNAL(copyAvailable(bool)),m_cutAct,SLOT(setEnabled(bool))); connect(m_editorWidget,SIGNAL(copyAvailable(bool)),m_copyAct,SLOT(setEnabled(bool))); connect(m_editorWidget,SIGNAL(wordWrapChanged(bool)),m_wordWrapAct,SLOT(setChecked(bool))); connect(m_undoAct,SIGNAL(triggered()),m_editorWidget,SLOT(undo())); connect(m_redoAct,SIGNAL(triggered()),m_editorWidget,SLOT(redo())); connect(m_cutAct,SIGNAL(triggered()),m_editorWidget,SLOT(cut())); connect(m_copyAct,SIGNAL(triggered()),m_editorWidget,SLOT(copy())); connect(m_pasteAct,SIGNAL(triggered()),m_editorWidget,SLOT(paste())); connect(m_selectAllAct,SIGNAL(triggered()),m_editorWidget,SLOT(selectAll())); connect(m_selectBlockAct,SIGNAL(triggered()),m_editorWidget,SLOT(selectBlock())); connect(m_exportHtmlAct,SIGNAL(triggered()),this,SLOT(exportHtml())); #ifndef QT_NO_PRINTER connect(m_exportPdfAct,SIGNAL(triggered()),this,SLOT(exportPdf())); connect(m_filePrintAct,SIGNAL(triggered()),this,SLOT(filePrint())); connect(m_filePrintPreviewAct,SIGNAL(triggered()),this,SLOT(filePrintPreview())); #endif connect(m_gotoPrevBlockAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoPrevBlock())); connect(m_gotoNextBlockAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoNextBlock())); connect(m_gotoMatchBraceAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoMatchBrace())); connect(m_gotoLineAct,SIGNAL(triggered()),this,SLOT(gotoLine())); connect(m_increaseFontSizeAct,SIGNAL(triggered()),this,SLOT(increaseFontSize())); connect(m_decreaseFontSizeAct,SIGNAL(triggered()),this,SLOT(decreaseFontSize())); connect(m_resetFontSizeAct,SIGNAL(triggered()),this,SLOT(resetFontSize())); connect(m_cleanWhitespaceAct,SIGNAL(triggered()),m_editorWidget,SLOT(cleanWhitespace())); connect(m_wordWrapAct,SIGNAL(triggered(bool)),m_editorWidget,SLOT(setWordWrapOverride(bool))); connect(m_commentAct,SIGNAL(triggered()),this,SLOT(comment())); connect(m_blockCommentAct,SIGNAL(triggered()),this,SLOT(blockComment())); connect(m_autoIndentAct,SIGNAL(triggered()),this,SLOT(autoIndent())); connect(m_tabToSpacesAct,SIGNAL(toggled(bool)),this,SLOT(tabToSpacesToggled(bool))); connect(m_visualizeWhitespaceAct,SIGNAL(toggled(bool)),this,SLOT(toggledVisualizeWhitespace(bool))); connect(m_moveLineUpAction,SIGNAL(triggered()),m_editorWidget,SLOT(moveLineUp())); connect(m_moveLineDownAction,SIGNAL(triggered()),m_editorWidget,SLOT(moveLineDown())); connect(m_copyLineUpAction,SIGNAL(triggered()),m_editorWidget,SLOT(copyLineUp())); connect(m_copyLineDownAction,SIGNAL(triggered()),m_editorWidget,SLOT(copyLineDown())); connect(m_joinLinesAction,SIGNAL(triggered()),m_editorWidget,SLOT(joinLines())); //connect(m_lineEndingWindowAct,SIGNAL(triggered()),this,SLOT(lineEndingWindow())); //connect(m_lineEndingUnixAct,SIGNAL(triggered()),this,SLOT(lineEndingUnixAct())); QActionGroup *group = new QActionGroup(this); group->addAction(m_lineEndingWindowAct); group->addAction(m_lineEndingUnixAct); connect(group,SIGNAL(triggered(QAction*)),this,SLOT(triggeredLineEnding(QAction*))); #ifdef Q_OS_WIN QClipboard *clipboard = QApplication::clipboard(); connect(clipboard,SIGNAL(dataChanged()),this,SLOT(clipbordDataChanged())); clipbordDataChanged(); #endif } void LiteEditor::findCodecs() { QMap<QString, QTextCodec *> codecMap; QRegExp iso8859RegExp("ISO[- ]8859-([0-9]+).*"); foreach (int mib, QTextCodec::availableMibs()) { QTextCodec *codec = QTextCodec::codecForMib(mib); QString sortKey = codec->name().toUpper(); int rank; if (sortKey.startsWith("UTF-8")) { rank = 1; } else if (sortKey.startsWith("UTF-16")) { rank = 2; } else if (iso8859RegExp.exactMatch(sortKey)) { if (iso8859RegExp.cap(1).size() == 1) rank = 3; else rank = 4; } else { rank = 5; } sortKey.prepend(QChar('0' + rank)); codecMap.insert(sortKey, codec); } m_codecs = codecMap.values(); } void LiteEditor::createToolBars() { m_editToolBar = new QToolBar("editor",m_widget); m_editToolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); //editor toolbar m_editToolBar->addAction(m_undoAct); m_editToolBar->addAction(m_redoAct); m_editToolBar->addSeparator(); m_editToolBar->addAction(m_cutAct); m_editToolBar->addAction(m_copyAct); m_editToolBar->addAction(m_pasteAct); #ifdef LITEEDITOR_FIND m_findComboBox = new QComboBox(m_widget); m_findComboBox->setEditable(true); m_findComboBox->setMinimumWidth(120); m_findComboBox->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); m_toolBar->addWidget(m_findComboBox); m_toolBar->addSeparator(); connect(m_findComboBox->lineEdit(),SIGNAL(returnPressed()),this,SLOT(findNextText())); #endif //info toolbar m_editToolBar->addSeparator(); //add lock info m_editToolBar->addAction(m_lockAct); //add over info QLabel *overInfo = new QLabel("[Over]"); m_overInfoAct = m_editToolBar->addWidget(overInfo); m_overInfoAct->setVisible(false); //add line info m_lineInfo = new QLabelEx("000:000"); m_editToolBar->addWidget(m_lineInfo); //add close //m_closeEditorAct = new QAction(QIcon("icon:images/closetool.png"),tr("Close Document"),this); //m_infoToolBar->addAction(m_closeEditorAct); } void LiteEditor::createMenu() { m_editMenu = new QMenu(m_editorWidget); m_contextMenu = new QMenu(m_editorWidget); //editor menu m_editMenu->addAction(m_undoAct); m_editMenu->addAction(m_redoAct); m_editMenu->addSeparator(); m_editMenu->addAction(m_cutAct); m_editMenu->addAction(m_copyAct); m_editMenu->addAction(m_pasteAct); m_editMenu->addSeparator(); m_editMenu->addAction(m_selectAllAct); m_editMenu->addSeparator(); QMenu *subMenu = m_editMenu->addMenu(tr("Advanced")); subMenu->addAction(m_duplicateAct); subMenu->addAction(m_copyLineAct); subMenu->addAction(m_deleteLineAct); subMenu->addAction(m_cutLineAct); subMenu->addAction(m_moveLineUpAction); subMenu->addAction(m_moveLineDownAction); subMenu->addAction(m_copyLineUpAction); subMenu->addAction(m_copyLineDownAction); subMenu->addAction(m_joinLinesAction); subMenu->addAction(m_insertLineBeforeAct); subMenu->addAction(m_insertLineAfterAct); subMenu->addSeparator(); subMenu->addAction(m_cleanWhitespaceAct); subMenu->addSeparator(); subMenu->addAction(m_selectBlockAct); subMenu->addAction(m_selectAllAct); #ifndef QT_NO_PRINTER subMenu->addSeparator(); subMenu->addAction(m_exportPdfAct); subMenu->addSeparator(); subMenu->addAction(m_filePrintPreviewAct); subMenu->addAction(m_filePrintAct); #endif subMenu = m_editMenu->addMenu(tr("Goto")); subMenu->addAction(m_gotoLineAct); subMenu->addAction(m_gotoMatchBraceAct); subMenu->addSeparator(); subMenu->addAction(m_gotoPrevBlockAct); subMenu->addAction(m_gotoNextBlockAct); subMenu->addAction(m_gotoLineStartAct); subMenu->addAction(m_gotoLineEndAct); subMenu->addAction(m_gotoPrevLineAct); subMenu->addAction(m_gotoNextLineAct); subMenu->addAction(m_gotoPrevCharacterAct); subMenu->addAction(m_gotoNextCharacterAct); subMenu->addAction(m_gotoPrevWordAct); subMenu->addAction(m_gotoNextWordAct); subMenu->addAction(m_gotoDocStartAct); subMenu->addAction(m_gotoDocEndAct); subMenu = m_editMenu->addMenu(tr("Code Folding")); subMenu->addAction(m_foldAct); subMenu->addAction(m_unfoldAct); subMenu->addAction(m_foldAllAct); subMenu->addAction(m_unfoldAllAct); subMenu = m_editMenu->addMenu(tr("Setup")); subMenu->addAction(m_visualizeWhitespaceAct); subMenu->addSeparator(); subMenu->addAction(m_wordWrapAct); subMenu->addAction(m_tabToSpacesAct); subMenu->addSeparator(); subMenu->addAction(m_increaseFontSizeAct); subMenu->addAction(m_decreaseFontSizeAct); subMenu->addAction(m_resetFontSizeAct); subMenu->addSeparator(); subMenu->addAction(m_lineEndingWindowAct); subMenu->addAction(m_lineEndingUnixAct); m_editMenu->addSeparator(); m_editMenu->addAction(m_codeCompleteAct); m_editMenu->addSeparator(); m_editMenu->addAction(m_commentAct); m_editMenu->addAction(m_blockCommentAct); m_editMenu->addAction(m_autoIndentAct); //context menu m_contextMenu->addAction(m_cutAct); m_contextMenu->addAction(m_copyAct); m_contextMenu->addAction(m_pasteAct); m_contextMenu->addSeparator(); subMenu = m_contextMenu->addMenu(tr("Advanced")); subMenu->addAction(m_duplicateAct); subMenu->addAction(m_copyLineAct); subMenu->addAction(m_deleteLineAct); subMenu->addAction(m_cutLineAct); subMenu->addAction(m_moveLineUpAction); subMenu->addAction(m_moveLineDownAction); subMenu->addAction(m_copyLineUpAction); subMenu->addAction(m_copyLineDownAction); subMenu->addAction(m_joinLinesAction); subMenu->addAction(m_insertLineBeforeAct); subMenu->addAction(m_insertLineAfterAct); subMenu->addSeparator(); subMenu->addAction(m_cleanWhitespaceAct); subMenu->addSeparator(); subMenu->addAction(m_selectBlockAct); subMenu->addAction(m_selectAllAct); subMenu = m_contextMenu->addMenu(tr("Goto")); subMenu->addAction(m_gotoLineAct); subMenu->addAction(m_gotoMatchBraceAct); subMenu->addSeparator(); subMenu->addAction(m_gotoPrevBlockAct); subMenu->addAction(m_gotoNextBlockAct); subMenu->addAction(m_gotoLineStartAct); subMenu->addAction(m_gotoLineEndAct); subMenu->addAction(m_gotoPrevLineAct); subMenu->addAction(m_gotoNextLineAct); subMenu->addAction(m_gotoPrevCharacterAct); subMenu->addAction(m_gotoNextCharacterAct); subMenu->addAction(m_gotoPrevWordAct); subMenu->addAction(m_gotoNextWordAct); subMenu->addAction(m_gotoDocStartAct); subMenu->addAction(m_gotoDocEndAct); subMenu = m_contextMenu->addMenu(tr("Code Folding")); subMenu->addAction(m_foldAct); subMenu->addAction(m_unfoldAct); subMenu->addAction(m_foldAllAct); subMenu->addAction(m_unfoldAllAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_commentAct); m_contextMenu->addAction(m_blockCommentAct); m_contextMenu->addAction(m_autoIndentAct); } #ifdef LITEEDITOR_FIND void LiteEditor::findNextText() { QString text = m_findComboBox->lineEdit()->text(); if (text.isEmpty()) { return; } m_editorWidget->find(text); } #endif LiteApi::IExtension *LiteEditor::extension() { return m_extension; } QWidget *LiteEditor::widget() { return m_widget; } QString LiteEditor::name() const { return QFileInfo(m_file->filePath()).fileName(); } QIcon LiteEditor::icon() const { return QIcon(); } void LiteEditor::initLoad() { m_editorWidget->initLoadDocument(); setReadOnly(m_file->isReadOnly()); m_lineEndingUnixAct->setChecked(m_file->isLineEndUnix()); m_lineEndingWindowAct->setChecked(!m_file->isLineEndUnix()); } bool LiteEditor::createNew(const QString &contents, const QString &mimeType) { bool success = m_file->create(contents,mimeType); if (success) { initLoad(); } return success; } bool LiteEditor::open(const QString &fileName,const QString &mimeType) { bool success = m_file->open(fileName,mimeType); if (success) { initLoad();; } return success; } bool LiteEditor::reload() { QByteArray state = this->saveState(); bool success = open(filePath(),mimeType()); if (success) { this->clearAllNavigateMarks(); this->setNavigateHead(LiteApi::EditorNavigateReload,tr("Reload File")); this->restoreState(state); emit reloaded(); } return success; } bool LiteEditor::save() { if (m_bReadOnly) { return false; } m_completer->clearTemp(); return saveAs(m_file->filePath()); } bool LiteEditor::saveAs(const QString &fileName) { bool cleanWhitespaceonSave = m_liteApp->settings()->value(EDITOR_CLEANWHITESPACEONSAVE,false).toBool(); if (cleanWhitespaceonSave) { m_editorWidget->cleanWhitespace(true); } return m_file->save(fileName); } void LiteEditor::setReadOnly(bool b) { m_lockAct->setVisible(b); m_bReadOnly = b; } bool LiteEditor::isReadOnly() const { return m_bReadOnly; } bool LiteEditor::isModified() const { if (!m_file) { return false; } return m_file->document()->isModified(); } QString LiteEditor::filePath() const { if (!m_file) { return QString(); } return m_file->filePath(); } QString LiteEditor::mimeType() const { if (!m_file) { return QString(); } return m_file->mimeType(); } LiteApi::IFile *LiteEditor::file() { return m_file; } int LiteEditor::line() const { return m_editorWidget->textCursor().blockNumber(); } int LiteEditor::column() const { return m_editorWidget->textCursor().columnNumber(); } int LiteEditor::utf8Position(bool realFile, int pos) const { QTextCursor cur = m_editorWidget->textCursor(); QString src = cur.document()->toPlainText().left(pos >= 0 ? pos : cur.position()); int offset = 0; if (realFile && m_file->isLineEndWindow()) { offset = cur.blockNumber(); } return src.toUtf8().length()+offset+1; } QByteArray LiteEditor::utf8Data() const { QString src = m_editorWidget->document()->toPlainText(); // if (m_file->m_lineTerminatorMode == LiteEditorFile::CRLFLineTerminator) { // src = src.replace("\n","\r\n"); // } return src.toUtf8(); } void LiteEditor::setWordWrap(bool wrap) { m_editorWidget->setWordWrapOverride(wrap); } bool LiteEditor::wordWrap() const { return m_editorWidget->isWordWrap(); } void LiteEditor::gotoLine(int line, int column, bool center) { m_editorWidget->setFocus(); m_editorWidget->gotoLine(line,column,center); } int LiteEditor::position(LiteApi::ITextEditor::PositionOperation posOp, int at) const { QTextCursor tc = m_editorWidget->textCursor(); if (at != -1) tc.setPosition(at); if (posOp == ITextEditor::Current) return tc.position(); switch (posOp) { case ITextEditor::EndOfLine: tc.movePosition(QTextCursor::EndOfLine); return tc.position(); case ITextEditor::StartOfLine: tc.movePosition(QTextCursor::StartOfLine); return tc.position(); case ITextEditor::Anchor: if (tc.hasSelection()) return tc.anchor(); break; case ITextEditor::EndOfDoc: tc.movePosition(QTextCursor::End); return tc.position(); default: break; } return -1; } QString LiteEditor::textAt(int pos, int length) const { QTextCursor c = m_editorWidget->textCursor(); if (pos < 0) pos = 0; c.movePosition(QTextCursor::End); if (pos + length > c.position()) length = c.position() - pos; c.setPosition(pos); c.setPosition(pos + length, QTextCursor::KeepAnchor); return c.selectedText(); } QRect LiteEditor::cursorRect(int pos) const { QTextCursor tc = m_editorWidget->textCursor(); if (pos >= 0) tc.setPosition(pos); QRect result = m_editorWidget->cursorRect(tc); result.moveTo(m_editorWidget->viewport()->mapToGlobal(result.topLeft())); return result; } LiteEditorWidget *LiteEditor::editorWidget() const { return m_editorWidget; } QTextCursor LiteEditor::textCursor() const { return m_editorWidget->textCursor(); } void LiteEditor::applyOption(QString id) { if (id != OPTION_LITEEDITOR) { return; } bool autoIndent = m_liteApp->settings()->value(EDITOR_AUTOINDENT,true).toBool(); bool autoBraces0 = m_liteApp->settings()->value(EDITOR_AUTOBRACE0,true).toBool(); bool autoBraces1 = m_liteApp->settings()->value(EDITOR_AUTOBRACE1,true).toBool(); bool autoBraces2 = m_liteApp->settings()->value(EDITOR_AUTOBRACE2,true).toBool(); bool autoBraces3 = m_liteApp->settings()->value(EDITOR_AUTOBRACE3,true).toBool(); bool autoBraces4 = m_liteApp->settings()->value(EDITOR_AUTOBRACE4,true).toBool(); bool autoBraces5 = m_liteApp->settings()->value(EDITOR_AUTOBRACE5,true).toBool(); bool caseSensitive = m_liteApp->settings()->value(EDITOR_COMPLETER_CASESENSITIVE,false).toBool(); bool fuzzyCompleter = m_liteApp->settings()->value(EDITOR_COMPLETER_FUZZY,false).toBool(); bool lineNumberVisible = m_liteApp->settings()->value(EDITOR_LINENUMBERVISIBLE,true).toBool(); bool codeFoldVisible = m_liteApp->settings()->value(EDITOR_CODEFOLDVISIBLE,true).toBool(); bool rightLineVisible = m_liteApp->settings()->value(EDITOR_RIGHTLINEVISIBLE,true).toBool(); bool eofVisible = m_liteApp->settings()->value(EDITOR_EOFVISIBLE,false).toBool(); bool defaultWordWrap = m_liteApp->settings()->value(EDITOR_DEFAULTWORDWRAP,false).toBool(); bool indentLineVisible = m_liteApp->settings()->value(EDITOR_INDENTLINEVISIBLE,true).toBool(); bool wheelZooming = m_liteApp->settings()->value(EDITOR_WHEEL_SCROLL,true).toBool(); bool visualizeWhitespace = m_liteApp->settings()->value(EDITOR_VISUALIZEWHITESPACE,false).toBool(); int rightLineWidth = m_liteApp->settings()->value(EDITOR_RIGHTLINEWIDTH,80).toInt(); int min = m_liteApp->settings()->value(EDITOR_PREFIXLENGTH,1).toInt(); m_editorWidget->setPrefixMin(min); m_offsetVisible = m_liteApp->settings()->value(EDITOR_OFFSETVISIBLE,false).toBool(); m_editorWidget->setAutoIndent(autoIndent); m_editorWidget->setAutoBraces0(autoBraces0); m_editorWidget->setAutoBraces1(autoBraces1); m_editorWidget->setAutoBraces2(autoBraces2); m_editorWidget->setAutoBraces3(autoBraces3); m_editorWidget->setAutoBraces4(autoBraces4); m_editorWidget->setAutoBraces5(autoBraces5); m_editorWidget->setLineNumberVisible(lineNumberVisible); m_editorWidget->setCodeFoldVisible(codeFoldVisible); m_editorWidget->setEofVisible(eofVisible); m_editorWidget->setIndentLineVisible(indentLineVisible); m_editorWidget->setRightLineVisible(rightLineVisible); m_editorWidget->setRightLineWidth(rightLineWidth); m_editorWidget->setDefaultWordWrap(defaultWordWrap); m_editorWidget->setScrollWheelZooming(wheelZooming); m_editorWidget->setVisualizeWhitespace(visualizeWhitespace); if (m_completer) { m_completer->setCaseSensitivity(caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive); m_completer->setFuzzy(fuzzyCompleter); } updateFont(); QString mime = this->m_file->mimeType(); m_editorWidget->setMimeType(mime); int tabWidth = m_liteApp->settings()->value(EDITOR_TABWIDTH+mime,4).toInt(); bool useSpace = m_liteApp->settings()->value(EDITOR_TABTOSPACES+mime,false).toBool(); this->setTabOption(tabWidth,useSpace); m_visualizeWhitespaceAct->setChecked(visualizeWhitespace); } void LiteEditor::updateTip(const QString &func,const QString &kind,const QString &info) { QString tip = m_editorWidget->textLexer()->fetchFunctionTip(func,kind,info); if (tip.isEmpty()) { return; } if (!m_funcTip) { m_funcTip = new FunctionTooltip(m_liteApp,this,m_editorWidget->textLexer(),20); } m_funcTip->showFunctionHint(this->position(),tip); } void LiteEditor::filePrintPreview() { #ifndef QT_NO_PRINTER QPrinter printer(QPrinter::HighResolution); QPrintPreviewDialog preview(&printer, m_widget); preview.resize(this->m_editorWidget->size()); connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*))); preview.exec(); #endif } void LiteEditor::printPreview(QPrinter *printer) { #ifdef QT_NO_PRINTER Q_UNUSED(printer); #else QPlainTextEdit::LineWrapMode mode = m_editorWidget->lineWrapMode(); m_editorWidget->setLineWrapMode(QPlainTextEdit::WidgetWidth); m_editorWidget->print(printer); m_editorWidget->setLineWrapMode(mode); #endif } void LiteEditor::exportHtml() { QString title; if (m_file) { title = QFileInfo(m_file->filePath()).completeBaseName(); } QString fileName = QFileDialog::getSaveFileName(m_widget, tr("Export HTML"), title, "*.html"); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) fileName.append(".html"); QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QMessageBox::critical(m_widget, tr("Export Failed"), QString(tr("Could not open %1 for writing.")).arg(fileName) ); return; } QTextCursor cur = m_editorWidget->textCursor(); cur.select(QTextCursor::Document); file.write(m_editorWidget->cursorToHtml(cur).toUtf8()); file.close(); } } void LiteEditor::exportPdf() { #ifndef QT_NO_PRINTER //! [0] QString title; if (m_file) { title = QFileInfo(m_file->filePath()).completeBaseName(); } QString fileName = QFileDialog::getSaveFileName(m_widget, tr("Export PDF"), title, "*.pdf"); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) { fileName.append(".pdf"); } QPrinter printer(QPrinter::HighResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); QPlainTextEdit::LineWrapMode mode = m_editorWidget->lineWrapMode(); m_editorWidget->setLineWrapMode(QPlainTextEdit::WidgetWidth); m_editorWidget->print(&printer); m_editorWidget->setLineWrapMode(mode); } //! [0] #endif } void LiteEditor::filePrint() { #ifndef QT_NO_PRINTER QPrinter printer(QPrinter::HighResolution); QPrintDialog *dlg = new QPrintDialog(&printer, m_widget); if (m_editorWidget->textCursor().hasSelection()) dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); dlg->setWindowTitle(tr("Print Document")); if (dlg->exec() == QDialog::Accepted) { QPlainTextEdit::LineWrapMode mode = m_editorWidget->lineWrapMode(); m_editorWidget->setLineWrapMode(QPlainTextEdit::WidgetWidth); m_editorWidget->print(&printer); m_editorWidget->setLineWrapMode(mode); } delete dlg; #endif } void LiteEditor::codecComboBoxChanged(QString codec) { if (!m_file) { return; } if (m_file->document()->isModified()) { QString text = QString(tr("Do you want to permanently discard unsaved modifications and reload %1?")).arg(m_file->filePath()); int ret = QMessageBox::question(m_liteApp->mainWindow(),"Unsaved Modifications",text,QMessageBox::Yes|QMessageBox::No); if (ret != QMessageBox::Yes) { return; } } bool success = m_file->reloadByCodec(codec); if (success) { emit reloaded(); m_editorWidget->initLoadDocument(); setReadOnly(m_file->isReadOnly()); } return; } void LiteEditor::editPositionChanged() { QTextCursor cur = m_editorWidget->textCursor(); //QString src = cur.document()->toPlainText().left(cur.position()); // int offset = 0; // if (m_file->isLineEndWindow()) { // offset = cur.blockNumber(); // } QString line; if (m_offsetVisible) { line = QString("%1:%2 [%3]").arg(cur.blockNumber()+1,3).arg(cur.columnNumber()+1,3).arg(this->utf8Position(true)); } else { line = QString("%1:%2").arg(cur.blockNumber()+1,3).arg(cur.columnNumber()+1,3); } if (m_bReadOnly) { m_liteApp->editorManager()->updateEditInfo(QString("[%1] %2").arg(tr("ReadOnly")).arg(line)); } else { m_liteApp->editorManager()->updateEditInfo(line); } } void LiteEditor::gotoLine() { LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); if (mgr) { LiteApi::IQuickOpen *p = mgr->findById("quickopen/lines"); if (p) { mgr->setCurrentFilter(p); mgr->showQuickOpen(); return; } } int min = 1; int max = m_editorWidget->document()->blockCount(); int old = m_editorWidget->textCursor().blockNumber()+1; bool ok = false; int v = QInputDialog::getInt(this->m_widget,tr("Go To Line"),tr("Line: ")+QString("%1-%2").arg(min).arg(max),old,min,max,1,&ok); if (!ok) { return; } if (v == old) { return; } m_liteApp->editorManager()->addNavigationHistory(); this->gotoLine(v-1,0,true); } QString LiteEditor::textCodec() const { return m_file->textCodec(); } void LiteEditor::setTextCodec(const QString &codec) { bool success = m_file->reloadByCodec(codec); if (success) { m_editorWidget->initLoadDocument(); setReadOnly(m_file->isReadOnly()); emit reloaded(); } } QByteArray LiteEditor::saveState() const { return m_editorWidget->saveState(); } bool LiteEditor::restoreState(const QByteArray &array) { return m_editorWidget->restoreState(array); } void LiteEditor::navigationStateChanged(const QByteArray &state) { m_liteApp->editorManager()->addNavigationHistory(this,state); } void LiteEditor::onActive() { m_editorWidget->setFocus(); //clipbordDataChanged(); editPositionChanged(); //m_editorWidget->saveCurrentCursorPositionForNavigation(); } void LiteEditor::setFindOption(LiteApi::FindOption *opt) { m_editorWidget->setFindOption(opt); } void LiteEditor::setSpellCheckZoneDontComplete(bool b) { m_editorWidget->setSpellCheckZoneDontComplete(b); } void LiteEditor::setNavigateHead(LiteApi::EditorNaviagteType type, const QString &msg) { m_editorWidget->setNavigateHead(type,msg); } void LiteEditor::insertNavigateMark(int line, LiteApi::EditorNaviagteType type, const QString &msg, const char* tag = "") { m_editorWidget->insertNavigateMark(line,type,msg, tag); } void LiteEditor::clearNavigateMarak(int /*line*/) { } void LiteEditor::clearAllNavigateMarks() { m_editorWidget->clearAllNavigateMarks(); } void LiteEditor::clearAllNavigateMark(LiteApi::EditorNaviagteType types, const char *tag = "") { m_editorWidget->clearAllNavigateMark(types, tag); } void LiteEditor::showLink(const LiteApi::Link &link) { m_editorWidget->showLink(link); } void LiteEditor::clearLink() { m_editorWidget->clearLink(); } void LiteEditor::setTabOption(int tabSize, bool tabToSpace) { m_editorWidget->setTabSize(tabSize); m_editorWidget->setTabToSpaces(tabToSpace); if (m_syntax) { m_syntax->setTabSize(tabSize); } m_tabToSpacesAct->setChecked(tabToSpace); } void LiteEditor::setEnableAutoIndentAction(bool b) { m_autoIndentAct->setVisible(b); } bool LiteEditor::isLineEndUnix() const { return m_file->isLineEndUnix(); } void LiteEditor::setLineEndUnix(bool b) { if (m_file->setLineEndUnix(b)) { m_lineEndingUnixAct->setChecked(b); m_lineEndingWindowAct->setChecked(!b); m_liteApp->editorManager()->saveEditor(this,false); } } void LiteEditor::showToolTipInfo(const QPoint &pos, const QString &text) { m_editorWidget->showToolTipInfo(pos,text); } void LiteEditor::selectNextParam() { QTextCursor cur = m_editorWidget->textCursor(); int pos = cur.position(); if (cur.hasSelection()) { pos = cur.selectionEnd(); } QTextBlock block = cur.block(); int offset = pos-block.position(); QRegExp reg("[\\,\\(\\)\\.\\s](\\s*)([\"\'\\w]+)"); int index = reg.indexIn(block.text().mid(offset)); if (index >= 0) { //qDebug() << reg.capturedTexts(); int start = block.position()+offset+index+1+reg.cap(1).length(); cur.setPosition(start); cur.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,reg.cap(2).length()); m_editorWidget->setTextCursor(cur); } } void LiteEditor::increaseFontSize() { this->requestFontZoom(10); } void LiteEditor::decreaseFontSize() { this->requestFontZoom(-10); } void LiteEditor::resetFontSize() { int fontSize = m_liteApp->settings()->value(EDITOR_FONTSIZE,12).toInt(); m_liteApp->settings()->setValue(EDITOR_FONTZOOM,100); QFont font = m_editorWidget->font(); font.setPointSize(fontSize); m_editorWidget->updateFont(font); this->sendUpdateFont(); } void LiteEditor::setEditToolbarVisible(bool /*visible*/) { //m_editToolBar->setVisible(visible); } void LiteEditor::comment() { if (!m_syntax) { return; } TextEditor::SyntaxComment comment = m_syntax->comment(); Utils::CommentDefinition cd; cd.setAfterWhiteSpaces(comment.isCommentAfterWhiteSpaces); cd.setSingleLine(comment.singleLineComment); cd.setMultiLineStart(comment.multiLineCommentStart); cd.setMultiLineEnd(comment.multiLineCommentEnd); Utils::unCommentSelection(m_editorWidget,Utils::AutoComment,cd); } void LiteEditor::blockComment() { } void LiteEditor::autoIndent() { m_editorWidget->autoIndent(); } void LiteEditor::tabToSpacesToggled(bool b) { m_liteApp->settings()->setValue(EDITOR_TABTOSPACES+this->mimeType(),b); m_editorWidget->setTabToSpaces(b); } void LiteEditor::toggledVisualizeWhitespace(bool b) { m_liteApp->settings()->setValue(EDITOR_VISUALIZEWHITESPACE,b); m_editorWidget->setVisualizeWhitespace(b); } void LiteEditor::triggeredLineEnding(QAction *action) { this->setLineEndUnix(action == m_lineEndingUnixAct); } void LiteEditor::broadcast(const QString &module, const QString &id, const QString &param) { if (module == "liteeditor" && id == "font" && param != this->filePath()) { this->updateFont(); } } void LiteEditor::updateFont() { #if defined(Q_OS_WIN) QString fontFamily = m_liteApp->settings()->value(EDITOR_FAMILY,"Courier").toString(); #elif defined(Q_OS_LINUX) QString fontFamily = m_liteApp->settings()->value(EDITOR_FAMILY,"Monospace").toString(); #elif defined(Q_OS_MAC) QString fontFamily = m_liteApp->settings()->value(EDITOR_FAMILY,"Menlo").toString(); #else QString fontFamily = m_liteApp->settings()->value(EDITOR_FAMILY,"Monospace").toString(); #endif int fontSize = m_liteApp->settings()->value(EDITOR_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(EDITOR_FONTZOOM,100).toInt(); bool antialias = m_liteApp->settings()->value(EDITOR_ANTIALIAS,true).toBool(); QFont font = m_editorWidget->font(); font.setFamily(fontFamily); font.setPointSize(fontSize*fontZoom/100.0); if (antialias) { font.setStyleStrategy(QFont::PreferAntialias); } else { font.setStyleStrategy(QFont::NoAntialias); } m_editorWidget->updateFont(font); } void LiteEditor::sendUpdateFont() { m_liteApp->sendBroadcast("liteeditor","font",this->filePath()); } QLabelEx::QLabelEx(const QString &text, QWidget *parent) : QLabel(text,parent) { } void QLabelEx::mouseDoubleClickEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { emit doubleClickEvent(); } } void LiteEditor::requestFontZoom(int zoom) { int fontSize = m_liteApp->settings()->value(EDITOR_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(EDITOR_FONTZOOM,100).toInt(); fontZoom += zoom; if (fontZoom <= 10) { return; } m_liteApp->settings()->setValue(EDITOR_FONTZOOM,fontZoom); QFont font = m_editorWidget->font(); font.setPointSize(fontSize*fontZoom/100.0); m_editorWidget->updateFont(font); this->sendUpdateFont(); } void LiteEditor::loadColorStyleScheme() { const ColorStyleScheme *colorScheme = m_liteApp->editorManager()->colorStyleScheme(); const ColorStyle *extra = colorScheme->findStyle("Extra"); const ColorStyle *indentLine = colorScheme->findStyle("IndentLine"); const ColorStyle *text = colorScheme->findStyle("Text"); const ColorStyle *selection = colorScheme->findStyle("Selection"); const ColorStyle *currentLine = colorScheme->findStyle("CurrentLine"); const ColorStyle *visualWhitespace = colorScheme->findStyle("VisualWhitespace"); if (extra) { m_editorWidget->setExtraColor(extra->foregound(),extra->background()); } if (indentLine) { m_editorWidget->setIndentLineColor(indentLine->foregound()); } if (currentLine) { m_editorWidget->setCurrentLineColor(currentLine->background()); } if (visualWhitespace) { m_editorWidget->setVisualizeWhitespaceColor(visualWhitespace->foregound()); } QPalette p = m_defEditorPalette; if (text) { if (text->foregound().isValid()) { p.setColor(QPalette::Text,text->foregound()); p.setColor(QPalette::Foreground, text->foregound()); } if (text->background().isValid()) { p.setColor(QPalette::Base, text->background()); } } if (selection) { if (selection->foregound().isValid()) { p.setColor(QPalette::HighlightedText, selection->foregound()); } if (selection->background().isValid()) { p.setColor(QPalette::Highlight, selection->background()); } p.setBrush(QPalette::Inactive, QPalette::Highlight, p.highlight()); p.setBrush(QPalette::Inactive, QPalette::HighlightedText, p.highlightedText()); } QString sheet = QString("QPlainTextEdit{color:%1;background-color:%2;selection-color:%3;selection-background-color:%4;}") .arg(p.text().color().name()) .arg(p.base().color().name()) .arg(p.highlightedText().color().name()) .arg(p.highlight().color().name()); m_editorWidget->setPalette(p); //#ifdef Q_OS_MAC // #if QT_VERSION >= 0x050000 // m_editorWidget->setStyleSheet(sheet); // #else // if (QSysInfo::MacintoshVersion <= QSysInfo::MV_10_8) { // m_editorWidget->setStyleSheet(sheet); // } // #endif //#else m_editorWidget->setStyleSheet(sheet); //#endif emit colorStyleChanged(); } EditContext::EditContext(LiteEditor *editor, QObject *parent) : LiteApi::IEditContext(parent), m_editor(editor) { } QWidget *EditContext::focusWidget() const { return m_editor->m_editorWidget; } QMenu *EditContext::focusMenu() const { return m_editor->m_editMenu; } QToolBar *EditContext::focusToolBar() const { return 0;//m_editor->m_editToolBar; }
lgpl-2.1
gi-rust/grust-proof
fake-gen/gio/gio.rs
10605
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2013, 2014 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library 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. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #![crate_name = "grust_gio_2_0"] #![crate_type = "lib"] #![allow(trivial_numeric_casts)] #[macro_use] extern crate grust; #[macro_use] extern crate bitflags; extern crate gio_2_0_sys as ffi; extern crate glib_2_0_sys as glib_ffi; extern crate gobject_2_0_sys as gobject_ffi; extern crate grust_glib_2_0 as glib; extern crate grust_gobject_2_0 as gobject; use grust::enumeration; use grust::enumeration::IntrospectedEnum as _grust_IntrospectedEnumTrait; use grust::error; use grust::gstr; use grust::gtype::GType; use grust::object; use grust::quark; use grust::refcount; use grust::types::{gint, gpointer}; use grust::wrap; use std::fmt; use std::mem; use std::ptr; use std::result; #[repr(C)] pub struct AsyncResult { raw: ffi::GAsyncResult } unsafe impl wrap::Wrapper for AsyncResult { type Raw = ffi::GAsyncResult; } #[repr(C)] pub struct File { raw: ffi::GFile } unsafe impl wrap::Wrapper for File { type Raw = ffi::GFile; } #[repr(C)] pub struct Cancellable { raw: ffi::GCancellable } unsafe impl Send for Cancellable { } unsafe impl Sync for Cancellable { } unsafe impl wrap::Wrapper for Cancellable { type Raw = ffi::GCancellable; } #[repr(C)] pub struct InputStream { raw: ffi::GInputStream } unsafe impl wrap::Wrapper for InputStream { type Raw = ffi::GInputStream; } #[repr(C)] pub struct FileInputStream { raw: ffi::GFileInputStream } unsafe impl wrap::Wrapper for FileInputStream { type Raw = ffi::GFileInputStream; } #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(C)] pub enum IOErrorEnum { Failed = 0, NotFound = 1, Exists = 2, // ... } impl enumeration::IntrospectedEnum for IOErrorEnum { fn from_int(v: gint) -> Result<Self, enumeration::UnknownValue> { match v { 0 => Ok(IOErrorEnum::Failed), 1 => Ok(IOErrorEnum::NotFound), 2 => Ok(IOErrorEnum::Exists), _ => Err(enumeration::UnknownValue(v)) } } fn to_int(&self) -> gint { *self as gint } fn name(&self) -> &'static str { match *self { IOErrorEnum::Failed => "failed", IOErrorEnum::NotFound => "not-found", IOErrorEnum::Exists => "exists", // ... } } } impl enumeration::EnumType for IOErrorEnum { fn get_type() -> GType { unsafe { GType::from_raw(ffi::g_io_error_enum_get_type()) } } } impl error::Domain for IOErrorEnum { fn domain() -> quark::Quark { g_static_quark!(b"g-io-error-quark\0") } } impl fmt::Display for IOErrorEnum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name()) } } pub mod flags { pub mod file_attribute_info { use grust::flags::prelude::*; use ffi; bitflags! { pub flags Flags: ::grust::types::guint { const NONE = 0, const COPY_WITH_FILE = 1, const COPY_WHEN_MOVED = 2, } } impl IntrospectedFlags for Flags { fn from_uint(v: guint) -> Result<Flags, UnknownFlags> { Flags::from_bits(v) .ok_or_else(|| UnknownFlags::new(v, Flags::all().bits())) } #[inline] fn to_uint(&self) -> guint { self.bits() } } impl FlagsType for Flags { fn get_type() -> GType { unsafe { let raw = ffi::g_file_attribute_info_flags_get_type(); GType::from_raw(raw) } } } } } pub use flags::file_attribute_info::Flags as FileAttributeInfoFlags; mod async { use ffi; use gobject_ffi; use gobject; use grust::types::gpointer; use grust::wrap; use std::mem; pub extern "C" fn async_ready_callback<F>(source_object: *mut gobject_ffi::GObject, res: *mut ffi::GAsyncResult, user_data: gpointer) where F: FnOnce(&gobject::Object, &super::AsyncResult) { let cb: Box<F> = unsafe { mem::transmute(user_data) }; let arg1 = unsafe { wrap::from_raw::<gobject::Object>(source_object) }; let arg2 = unsafe { wrap::from_raw::<super::AsyncResult>(res) }; cb(arg1, arg2); } } pub mod cast { use grust::object; use gobject; pub trait AsAsyncResult { fn as_async_result(&self) -> &super::AsyncResult; } impl<T> AsAsyncResult for T where T: object::Upcast<super::AsyncResult> { #[inline] fn as_async_result(&self) -> &super::AsyncResult { self.upcast() } } pub trait AsCancellable : gobject::cast::AsObject { fn as_cancellable(&self) -> &super::Cancellable; } impl<T> AsCancellable for T where T: object::Upcast<super::Cancellable>, T: object::Upcast<gobject::Object> { #[inline] fn as_cancellable(&self) -> &super::Cancellable { self.upcast() } } pub trait AsInputStream : gobject::cast::AsObject { fn as_input_stream(&self) -> &super::InputStream; } impl<T> AsInputStream for T where T: object::Upcast<super::InputStream>, T: object::Upcast<gobject::Object> { #[inline] fn as_input_stream(&self) -> &super::InputStream { self.upcast() } } pub trait AsFileInputStream : AsInputStream { fn as_file_input_stream(&self) -> &super::FileInputStream; } impl<T> AsFileInputStream for T where T: object::Upcast<super::FileInputStream>, T: object::Upcast<super::InputStream>, T: object::Upcast<gobject::Object> { #[inline] fn as_file_input_stream(&self) -> &super::FileInputStream { self.upcast() } } pub trait AsFile { fn as_file(&self) -> &super::File; } impl<T> AsFile for T where T: object::Upcast<super::File> { #[inline] fn as_file(&self) -> &super::File { self.upcast() } } } impl File { pub fn new_for_path(path: &gstr::Utf8) -> refcount::Ref<File> { unsafe { let ret = ffi::g_file_new_for_path(path.as_ptr()); refcount::Ref::from_raw(ret) } } pub fn get_path(&self) -> gstr::OwnedGStr { unsafe { use grust::wrap::Wrapper; let ret = ffi::g_file_get_path(self.as_mut_ptr()); gstr::OwnedGStr::from_ptr(ret) } } pub fn read_async<F>(&self, io_priority: gint, cancellable: Option<&Cancellable>, callback: F) where F: FnOnce(&gobject::Object, &AsyncResult), F: Send + 'static { unsafe { use grust::wrap::Wrapper; let self_raw = self.as_mut_ptr(); let cancellable = { match cancellable { Some(c) => c.as_mut_ptr(), None => std::ptr::null_mut() } }; let callback: gpointer = mem::transmute(Box::new(callback)); ffi::g_file_read_async(self_raw, io_priority, cancellable, Some(async::async_ready_callback::<F>), callback); } } pub fn read_finish(&self, res: &AsyncResult) -> result::Result<refcount::Ref<FileInputStream>, error::Error> { let mut err: *mut glib_ffi::GError = ptr::null_mut(); let ret = unsafe { use grust::wrap::Wrapper; ffi::g_file_read_finish(self.as_mut_ptr(), res.as_mut_ptr(), &mut err) }; if err.is_null() { Ok(unsafe { refcount::Ref::from_raw(ret) }) } else { Err(unsafe { error::Error::from_raw(err) }) } } } unsafe impl object::ObjectType for AsyncResult { fn get_type() -> GType { unsafe { GType::from_raw(ffi::g_async_result_get_type()) } } } unsafe impl object::ObjectType for File { fn get_type() -> GType { unsafe { GType::from_raw(ffi::g_file_get_type()) } } } unsafe impl object::ObjectType for InputStream { fn get_type() -> GType { unsafe { GType::from_raw(ffi::g_input_stream_get_type()) } } } unsafe impl object::ObjectType for FileInputStream { fn get_type() -> GType { unsafe { GType::from_raw(ffi::g_file_input_stream_get_type()) } } } impl object::Upcast<gobject::Object> for Cancellable { #[inline] fn upcast(&self) -> &gobject::Object { unsafe { wrap::from_raw(&self.raw.parent_instance) } } } impl object::Upcast<gobject::Object> for InputStream { #[inline] fn upcast(&self) -> &gobject::Object { unsafe { wrap::from_raw(&self.raw.parent_instance) } } } impl object::Upcast<InputStream> for FileInputStream { #[inline] fn upcast(&self) -> &InputStream { unsafe { wrap::from_raw(&self.raw.parent_instance) } } } impl object::Upcast<gobject::Object> for FileInputStream { #[inline] fn upcast(&self) -> &gobject::Object { use cast::AsInputStream; self.as_input_stream().upcast() } }
lgpl-2.1
lacroixca/sportsmanager
views/modal_edit_stats.php
1065
<div id="sm_edit_stats_modal" class="sm_modal_box sm_modal_edit_info"> <div class="sm_modal_header"> <table class="title"> <tr> <td>Edit Stats</td> </tr> </table> </div> <div class="sm_modal_inner"> <form id="sm_edit_stats_form"> <table class="" border="0" cellspacing="0" cellpadding="0"> <thead> <tr> <th>Stat</th> <th>Code</th> <th>Value</th> </tr> </thead> <tbody> <?php foreach ($stats as $k => $v) { ?> <tr class="stat <?php foreach ($v[2] as $sport) echo $sport.' '; ?>"> <td><?php echo $v[1]; ?></td> <td><?php echo $v[0]; ?></td> <td><input type="text" id="stats-<?php echo $k; ?>" name="<?php echo $k; ?>" value="" tabindex="1" /></td> </tr> <?php }; ?> </tbody> </table> </form> </div> <div class="sm_modal_footer"> <table id="sm_edit_stats_btn" class="save" tabindex="1"> <tr> <td>Save</td> </tr> </table> <table class="loader"> <tr> <td>Wait...</td> </tr> </table> <table class="close" tabindex="1"> <tr> <td>Close</td> </tr> </table> </div> </div>
lgpl-2.1
shuiblue/JDimeForCpp
src/de/fosd/jdime/stats/StatsPrinter.java
3964
/* * Copyright (C) 2013-2014 Olaf Lessenich * Copyright (C) 2014-2015 University of Passau, Germany * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA * * Contributors: * Olaf Lessenich <lessenic@fim.uni-passau.de> */ package de.fosd.jdime.stats; import java.util.ArrayList; import java.util.Collections; import java.util.logging.Level; import java.util.logging.Logger; import de.fosd.jdime.common.MergeContext; import de.fosd.jdime.strategy.LinebasedStrategy; /** * @author Olaf Lessenich * */ public final class StatsPrinter { private static final Logger LOG = Logger.getLogger(StatsPrinter.class.getCanonicalName()); private static String delimiter = "================================================="; /** * Prints statistical information. * * @param context * merge context */ public static void print(final MergeContext context) { assert (context != null); Stats stats = context.getStats(); assert (stats != null); if (LOG.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder(); sb.append("Keys:"); for (String key : stats.getKeys()) { sb.append(" ").append(key); } LOG.fine(sb.toString()); System.out.println(delimiter); System.out.println("Number of conflicts: " + stats.getConflicts()); for (String key : stats.getKeys()) { System.out.println(delimiter); StatsElement element = stats.getElement(key); System.out.println("Added " + key + ": " + element.getAdded()); System.out.println("Deleted " + key + ": " + element.getDeleted()); System.out .println("Merged " + key + ": " + element.getMerged()); System.out.println("Conflicting " + key + ": " + element.getConflicting()); } System.out.println(delimiter); ArrayList<String> operations = new ArrayList<>(stats.getOperations()); Collections.sort(operations); for (String key : operations) { System.out.println("applied " + key + " operations: " + stats.getOperation(key)); } System.out.println(delimiter); } if (context.isConsecutive()) { ASTStats rightStats = stats.getRightStats(); ASTStats leftStats = stats.getLeftStats(); if (rightStats == null) { return; } if (leftStats != null) { rightStats.setRemovalsfromAdditions(leftStats); } System.out.println(rightStats); } else { ASTStats astStats = stats.getAstStats(); System.out.println(astStats); } if (LOG.isLoggable(Level.FINE)) { System.out.println(delimiter); System.out.println("Runtime: " + stats.getRuntime() + " ms"); System.out.println(delimiter); } if (context.getMergeStrategy().getClass().getName() .equals(LinebasedStrategy.class.getName())) { assert (stats.getElement("files").getAdded() + stats.getElement("directories").getAdded() == stats .getOperation("ADD")); assert (stats.getElement("files").getDeleted() + stats.getElement("directories").getDeleted() == stats .getOperation("DELETE")); assert (stats.getElement("files").getMerged() + stats.getElement("directories").getMerged() == stats .getOperation("MERGE")); LOG.fine("Sanity checks for linebased merge passed!"); } } /** * Private constructor. */ private StatsPrinter() { } }
lgpl-2.1
trainboy2019/forge-1-4
src/main/java/com/camp/nchant/NchantmentKnockback.java
1119
package com.camp.nchant; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.util.ResourceLocation; public class NchantmentKnockback extends Enchantment { private static final String __OBFID = "CL_00000118"; public NchantmentKnockback(int p_i45768_1_, ResourceLocation p_i45768_2_, int p_i45768_3_) { super(p_i45768_1_, p_i45768_2_, p_i45768_3_, EnumEnchantmentType.WEAPON); this.setName("knockback"); } /** * Returns the minimal value of enchantability needed on the enchantment level passed. */ public int getMinEnchantability(int enchantmentLevel) { return 5 + 20 * (enchantmentLevel - 1); } /** * Returns the maximum value of enchantability nedded on the enchantment level passed. */ public int getMaxEnchantability(int enchantmentLevel) { return super.getMinEnchantability(enchantmentLevel) + 50; } /** * Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 5; } }
lgpl-2.1
drhee/toxoMine
bio/postprocess/main/src/org/intermine/bio/postprocess/PostProcessOperationsTask.java
14978
package org.intermine.bio.postprocess; /* * Copyright (C) 2002-2014 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.log4j.Logger; import org.apache.tools.ant.BuildException; import org.intermine.api.config.ClassKeyHelper; import org.intermine.metadata.FieldDescriptor; import org.intermine.modelproduction.MetadataManager; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreSummary; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.ObjectStoreWriterFactory; import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; import org.intermine.sql.Database; import org.intermine.task.CreateIndexesTask; import org.intermine.task.DynamicAttributeTask; import org.intermine.task.PrecomputeTask; import org.intermine.util.PropertiesUtil; import org.intermine.web.autocompletion.AutoCompleter; import org.intermine.web.search.KeywordSearch; /** * Run operations on genomic model database after DataLoading * * @author Richard Smith */ public class PostProcessOperationsTask extends DynamicAttributeTask { private static final Logger LOGGER = Logger.getLogger(PostProcessOperationsTask.class); protected String operation, objectStoreWriter, ensemblDb, organisms = null; protected File outputFile; protected ObjectStoreWriter osw; /** * Sets the value of operation * * @param operation the operation to perform eg. 'Download publications' */ public void setOperation(String operation) { this.operation = operation; } /** * Sets the value of objectStoreWriter * * @param objectStoreWriter an objectStoreWriter alias for operations that require one */ public void setObjectStoreWriter(String objectStoreWriter) { this.objectStoreWriter = objectStoreWriter; } /** * Sets the value of outputFile * * @param outputFile an output file for operations that require one */ public void setOutputFile(File outputFile) { this.outputFile = outputFile; } /** * Sets the value of ensemblDb * * @param ensemblDb a database alias */ public void setEnsemblDb(String ensemblDb) { this.ensemblDb = ensemblDb; } private ObjectStoreWriter getObjectStoreWriter() throws Exception { if (objectStoreWriter == null) { throw new BuildException("objectStoreWriter attribute is not set"); } if (osw == null) { osw = ObjectStoreWriterFactory.getObjectStoreWriter(objectStoreWriter); } return osw; } /** * {@inheritDoc} */ @Override public void execute() { if (operation == null) { throw new BuildException("operation attribute is not set"); } long startTime = System.currentTimeMillis(); try { if ("create-chromosome-locations-and-lengths".equals(operation)) { CalculateLocations cl = new CalculateLocations(getObjectStoreWriter()); LOGGER.info("Starting CalculateLocations.setChromosomeLocationsAndLengths()"); cl.setChromosomeLocationsAndLengths(); } else if ("set-missing-chromosome-locations".equals(operation)) { CalculateLocations cl = new CalculateLocations(getObjectStoreWriter()); LOGGER.info("Starting CalculateLocations.setMissingChromosomeLocations()"); cl.setMissingChromosomeLocations(); } else if ("create-references".equals(operation)) { CreateReferences cr = new CreateReferences(getObjectStoreWriter()); LOGGER.info("Starting CreateReferences.insertReferences()"); cr.insertReferences(); } else if ("create-symmetrical-relation-references".equals(operation)) { throw new BuildException("create-symmetrical-relation-references task is" + " deprecated"); } else if ("create-utr-references".equals(operation)) { CreateReferences cr = new CreateReferences(getObjectStoreWriter()); LOGGER.info("Starting CreateReferences.createUtrRefs()"); cr.createUtrRefs(); } else if ("transfer-sequences".equals(operation)) { TransferSequences ts = new TransferSequences(getObjectStoreWriter()); ts = new TransferSequences(getObjectStoreWriter()); LOGGER.info("Starting TransferSequences.transferToLocatedSequenceFeatures()"); ts.transferToLocatedSequenceFeatures(); ts = new TransferSequences(getObjectStoreWriter()); LOGGER.info("Starting TransferSequences.transferToTranscripts()"); ts.transferToTranscripts(); } else if ("transfer-sequences-located-sequence-feature".equals(operation)) { TransferSequences ts = new TransferSequences(getObjectStoreWriter()); LOGGER.info("Starting TransferSequences.transferToLocatedSequenceFeatures()"); ts.transferToLocatedSequenceFeatures(); } else if ("transfer-sequences-transcripts".equals(operation)) { TransferSequences ts = new TransferSequences(getObjectStoreWriter()); LOGGER.info("Starting TransferSequences.transferToTranscripts()"); ts.transferToTranscripts(); } else if ("make-spanning-locations".equals(operation)) { CalculateLocations cl = new CalculateLocations(getObjectStoreWriter()); LOGGER.info("Starting CalculateLocations.createSpanningLocations()"); cl.createSpanningLocations("Transcript", "Exon", "exons"); cl.createSpanningLocations("Gene", "Transcript", "transcripts"); } else if ("create-intergenic-region-features".equals(operation)) { IntergenicRegionUtil ig = new IntergenicRegionUtil(getObjectStoreWriter()); LOGGER.info("Starting IntergenicRegionUtil.createIntergenicRegionFeatures()"); ig.createIntergenicRegionFeatures(); } else if ("create-gene-flanking-features".equals(operation)) { CreateFlankingRegions cfr = new CreateFlankingRegions(getObjectStoreWriter()); LOGGER.info("Starting CreateFlankingRegions.createFlankingFeatures()"); cfr.createFlankingFeatures(); } else if ("create-intron-features".equals(operation)) { IntronUtil iu = new IntronUtil(getObjectStoreWriter()); configureDynamicAttributes(iu); LOGGER.info("Starting IntronUtil.createIntronFeatures()"); iu.createIntronFeatures(); } else if ("create-overlap-relations-flymine".equals(operation)) { LOGGER.info("Starting CalculateLocations.createOverlapRelations()"); List<String> classNamesToIgnoreList = new ArrayList<String>(); String ignoreFileName = "overlap.config"; ClassLoader classLoader = PostProcessOperationsTask.class.getClassLoader(); InputStream classesToIgnoreStream = classLoader.getResourceAsStream(ignoreFileName); if (classesToIgnoreStream == null) { throw new RuntimeException("can't find resource: " + ignoreFileName); } BufferedReader classesToIgnoreReader = new BufferedReader(new InputStreamReader(classesToIgnoreStream)); String line = classesToIgnoreReader.readLine(); while (line != null) { classNamesToIgnoreList.add(line); line = classesToIgnoreReader.readLine(); } CalculateLocations cl = new CalculateLocations(getObjectStoreWriter()); cl.createOverlapRelations(classNamesToIgnoreList, false); } else if ("set-collection-counts".equals(operation)) { SetCollectionCounts setCounts = new SetCollectionCounts(getObjectStoreWriter()); setCounts.setCollectionCount(); } else if ("create-attribute-indexes".equals(operation)) { CreateIndexesTask cit = new CreateIndexesTask(); cit.setAttributeIndexes(true); cit.setObjectStore(getObjectStoreWriter().getObjectStore()); cit.execute(); } else if ("summarise-objectstore".equals(operation)) { System.out .println("summarising objectstore ..."); ObjectStore os = getObjectStoreWriter().getObjectStore(); if (!(os instanceof ObjectStoreInterMineImpl)) { throw new RuntimeException("cannot summarise ObjectStore - must be an " + "instance of ObjectStoreInterMineImpl"); } String configFileName = "objectstoresummary.config.properties"; ClassLoader classLoader = PostProcessOperationsTask.class.getClassLoader(); InputStream configStream = classLoader.getResourceAsStream(configFileName); if (configStream == null) { throw new RuntimeException("can't find resource: " + configFileName); } Properties config = new Properties(); config.load(configStream); ObjectStoreSummary oss = new ObjectStoreSummary(os, config); Database db = ((ObjectStoreInterMineImpl) os).getDatabase(); MetadataManager.store(db, MetadataManager.OS_SUMMARY, PropertiesUtil.serialize(oss.toProperties())); } else if ("precompute-queries".equals(operation)) { (new PrecomputeTask()).precompute(false, getObjectStoreWriter().getObjectStore(), 0); } else if ("create-lucene-index".equals(operation) || "create-autocomplete-index".equals(operation)) { System.out .println("create lucene index ..."); ObjectStore os = getObjectStoreWriter().getObjectStore(); if (!(os instanceof ObjectStoreInterMineImpl)) { throw new RuntimeException("cannot summarise ObjectStore - must be an " + "instance of ObjectStoreInterMineImpl (create lucene index)"); } String configFileName = "objectstoresummary.config.properties"; ClassLoader classLoader = PostProcessOperationsTask.class.getClassLoader(); InputStream configStream = classLoader.getResourceAsStream(configFileName); if (configStream == null) { throw new RuntimeException("can't find resource: " + configFileName); } Properties properties = new Properties(); properties.load(configStream); Database db = ((ObjectStoreInterMineImpl) os).getDatabase(); AutoCompleter ac = new AutoCompleter(os, properties); if (ac.getBinaryIndexMap() != null) { MetadataManager.storeBinary(db, MetadataManager.AUTOCOMPLETE_INDEX, ac.getBinaryIndexMap()); } } else if ("create-search-index".equals(operation)) { System .out.println("Creating lucene index for keyword search..."); ObjectStore os = getObjectStoreWriter().getObjectStore(); if (!(os instanceof ObjectStoreInterMineImpl)) { throw new RuntimeException("Got invalid ObjectStore - must be an " + "instance of ObjectStoreInterMineImpl!"); } ClassLoader classLoader = PostProcessOperationsTask.class.getClassLoader(); /* String configFileName = "objectstoresummary.config.properties"; InputStream configStream = classLoader.getResourceAsStream(configFileName); if (configStream == null) { throw new RuntimeException("can't find resource: " + configFileName); } Properties properties = new Properties(); properties.load(configStream);*/ //read class keys to figure out what are keyFields during indexing InputStream is = classLoader.getResourceAsStream("class_keys.properties"); Properties classKeyProperties = new Properties(); classKeyProperties.load(is); Map<String, List<FieldDescriptor>> classKeys = ClassKeyHelper.readKeys(os.getModel(), classKeyProperties); //index and save KeywordSearch.saveIndexToDatabase(os, classKeys); KeywordSearch.deleteIndexDirectory(); } else if ("create-overlap-view".equals(operation)) { OverlapViewTask ovt = new OverlapViewTask(getObjectStoreWriter()); ovt.createView(); } else if ("create-bioseg-location-index".equals(operation)) { BiosegIndexTask bit = new BiosegIndexTask(getObjectStoreWriter()); bit.createIndex(); } else if ("link-ins".equals(operation)) { CreateFlyBaseLinkIns.createLinkInFile(getObjectStoreWriter().getObjectStore()); } else if ("modmine-metadata-cache".equals(operation)) { CreateModMineMetaDataCache.createCache(getObjectStoreWriter().getObjectStore()); } else if ("populate-child-features".equals(operation)) { PopulateChildFeatures jb = new PopulateChildFeatures(getObjectStoreWriter()); jb.populateCollection(); } } catch (BuildException e) { LOGGER.error("Failed postprocess. Operation was: " + operation, e); throw e; } catch (Exception e) { LOGGER.error("Failed postprocess. Operation was: " + operation, e); throw new BuildException("Operation was:" + operation, e); } finally { try { if (osw != null) { osw.close(); } } catch (Exception e) { throw new BuildException(e); } } } }
lgpl-2.1
cogtool/cogtool
java/edu/cmu/cs/hcii/cogtool/model/PullDownHeader.java
6729
/******************************************************************************* * CogTool Copyright Notice and Distribution Terms * CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University * This software is distributed under the terms of the FSF Lesser * Gnu Public License (see LGPL.txt). * * CogTool 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. * * CogTool 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 CogTool; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * CogTool makes use of several third-party components, with the * following notices: * * Eclipse SWT version 3.448 * Eclipse GEF Draw2D version 3.2.1 * * Unless otherwise indicated, all Content made available by the Eclipse * Foundation is provided to you under the terms and conditions of the Eclipse * Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this * Content and is also available at http://www.eclipse.org/legal/epl-v10.html. * * CLISP version 2.38 * * Copyright (c) Sam Steingold, Bruno Haible 2001-2006 * This software is distributed under the terms of the FSF Gnu Public License. * See COPYRIGHT file in clisp installation folder for more information. * * ACT-R 6.0 * * Copyright (c) 1998-2007 Dan Bothell, Mike Byrne, Christian Lebiere & * John R Anderson. * This software is distributed under the terms of the FSF Lesser * Gnu Public License (see LGPL.txt). * * Apache Jakarta Commons-Lang 2.1 * * This product contains software developed by the Apache Software Foundation * (http://www.apache.org/) * * jopt-simple version 1.0 * * Copyright (c) 2004-2013 Paul R. Holser, Jr. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Mozilla XULRunner 1.9.0.5 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The J2SE(TM) Java Runtime Environment version 5.0 * * Copyright 2009 Sun Microsystems, Inc., 4150 * Network Circle, Santa Clara, California 95054, U.S.A. All * rights reserved. U.S. * See the LICENSE file in the jre folder for more information. ******************************************************************************/ package edu.cmu.cs.hcii.cogtool.model; import edu.cmu.cs.hcii.cogtool.util.ObjectLoader; import edu.cmu.cs.hcii.cogtool.util.ObjectSaver; public class PullDownHeader extends AParentWidget implements TraversableWidget { public static final int edu_cmu_cs_hcii_cogtool_model_PullDownHeader_version = 0; private static ObjectSaver.IDataSaver<PullDownHeader> SAVER = new ObjectSaver.ADataSaver<PullDownHeader>() { @Override public int getVersion() { return edu_cmu_cs_hcii_cogtool_model_PullDownHeader_version; } @Override public void saveData(PullDownHeader v, ObjectSaver saver) throws java.io.IOException { } }; public static void registerSaver() { ObjectSaver.registerSaver(PullDownHeader.class.getName(), SAVER); } private static ObjectLoader.IObjectLoader<PullDownHeader> LOADER = new ObjectLoader.AObjectLoader<PullDownHeader>() { @Override public PullDownHeader createObject() { return new PullDownHeader(FOR_LOADING); } }; public static void registerLoader() { ObjectLoader.registerLoader(PullDownHeader.class.getName(), edu_cmu_cs_hcii_cogtool_model_PullDownHeader_version, LOADER); } public static final boolean FOR_LOADING = false; public static final boolean FOR_DUPLICATION = true; public PullDownHeader(boolean forDuplication) { // For loading or duplicating of subclasses super(forDuplication ? SimpleWidgetGroup.VERTICAL : NO_CHILDREN, AParentWidget.CHILDREN_BELOW); } public PullDownHeader(DoubleRectangle bounds, String useTitle) { super(bounds, WidgetType.PullDownList, SimpleWidgetGroup.VERTICAL, AParentWidget.CHILDREN_BELOW); setTitle(useTitle); } /** * Create a "deep" copy of this widget. * <p> * It is the responsibility of the caller to "place" the copy * (usually by adding it to an Frame). */ @Override public AParentWidget duplicate(Frame.IFrameDuplicator duplicator, SimpleWidgetGroup.IWidgetDuplicator situator) { PullDownHeader headerCopy = new PullDownHeader(FOR_DUPLICATION); headerCopy.copyState(this, duplicator, situator); return headerCopy; } }
lgpl-2.1
exedio/builder
testmodelsrc/com/exedio/cope/builder/test/UnknownPatternItem.java
3428
package com.exedio.cope.builder.test; import static com.exedio.cope.instrument.Visibility.NONE; import com.exedio.cope.IntegerField; import com.exedio.cope.Item; import com.exedio.cope.ItemField; import com.exedio.cope.instrument.WrapperType; import com.exedio.cope.pattern.PartOf; @WrapperType(constructor=NONE, genericConstructor=NONE) final class UnknownPatternItem extends Item { static final ItemField<SimpleItem> parent = ItemField.create(SimpleItem.class).toFinal(); static final IntegerField order = new IntegerField().toFinal(); static final PartOf<SimpleItem> unknowns = PartOf.create(parent, order); /** * Returns the value of {@link #parent}. */ @com.exedio.cope.instrument.Generated // customize with @Wrapper(wrap="get") @java.lang.SuppressWarnings({"FinalMethodInFinalClass","RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedStaticUsage"}) final SimpleItem getParent() { return UnknownPatternItem.parent.get(this); } /** * Returns the value of {@link #order}. */ @com.exedio.cope.instrument.Generated // customize with @Wrapper(wrap="get") @java.lang.SuppressWarnings({"FinalMethodInFinalClass","RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedStaticUsage"}) final int getOrder() { return UnknownPatternItem.order.getMandatory(this); } /** * Returns the container this item is part of by {@link #unknowns}. */ @com.exedio.cope.instrument.Generated // customize with @Wrapper(wrap="getContainer") @java.lang.SuppressWarnings({"FinalMethodInFinalClass","RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedStaticUsage"}) final SimpleItem getUnknownsContainer() { return UnknownPatternItem.unknowns.getContainer(this); } /** * Returns the parts of the given container. */ @com.exedio.cope.instrument.Generated // customize with @Wrapper(wrap="getParts") @java.lang.SuppressWarnings({"FinalMethodInFinalClass","RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedStaticUsage"}) static final java.util.List<UnknownPatternItem> getUnknownsParts(final SimpleItem container) { return UnknownPatternItem.unknowns.getParts(UnknownPatternItem.class,container); } /** * Returns the parts of the given container matching the given condition. */ @com.exedio.cope.instrument.Generated // customize with @Wrapper(wrap="getParts") @java.lang.SuppressWarnings({"FinalMethodInFinalClass","RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedStaticUsage"}) static final java.util.List<UnknownPatternItem> getUnknownsParts(final SimpleItem container,final com.exedio.cope.Condition condition) { return UnknownPatternItem.unknowns.getParts(UnknownPatternItem.class,container,condition); } @com.exedio.cope.instrument.Generated private static final long serialVersionUID = 1l; /** * The persistent type information for unknownPatternItem. */ @com.exedio.cope.instrument.Generated // customize with @WrapperType(type=...) static final com.exedio.cope.Type<UnknownPatternItem> TYPE = com.exedio.cope.TypesBound.newType(UnknownPatternItem.class); /** * Activation constructor. Used for internal purposes only. * @see com.exedio.cope.Item#Item(com.exedio.cope.ActivationParameters) */ @com.exedio.cope.instrument.Generated private UnknownPatternItem(final com.exedio.cope.ActivationParameters ap){super(ap);} }
lgpl-2.1
scalala/Scalala
src/main/scala/scalala/generic/collection/CanSliceVector.scala
1073
/* * Distributed as part of Scalala, a linear algebra library. * * Copyright (C) 2008- Daniel Ramage * * This library 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110 USA */ package scalala; package generic; package collection; /** * Capability trait for slicing a Vector from something. * * @author dramage */ trait CanSliceVector[-From, A, +To] { def apply(from : From, keys : Seq[A]) : To; }
lgpl-2.1
henon/GitSharp
GitSharp/Author.cs
2706
/* * Copyright (C) 2009, Henon <meinrad.recheis@gmail.com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Git Development Community 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 OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GitSharp { /// <summary> /// Represents the Author or Committer of a Commit. /// </summary> public class Author { /// <summary> /// Creates an uninitialized Author. You may use the object initializer syntax with this constructor, i.e. new Author { Name="henon", EmailAddress="henon@gitsharp.com" } /// </summary> public Author() { } /// <summary> /// Creates an Author. /// </summary> public Author(string name, string email) { Name = name; EmailAddress = email; } public string Name { get; set; } public string EmailAddress { get; set; } /// <summary> /// Preconfigured anonymous Author, which may be used by GitSharp if no Author has been configured. /// </summary> public static Author Anonymous { get { return new Author("anonymous", "anonymous@(none).com"); } } public static Author GetDefaultAuthor(Repository repo) { return new Author(repo.Config["user.name"], repo.Config["user.email"]); } } }
lgpl-2.1
lxde/lxqt-panel
panel/translations/lxqt-panel_hu.ts
16871
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="hu"> <context> <name>AddPluginDialog</name> <message> <location filename="../config/addplugindialog.ui" line="14"/> <source>Add Plugins</source> <translation>Bővítmény hozzáadás</translation> </message> <message> <location filename="../config/addplugindialog.ui" line="22"/> <source>Search:</source> <translation>Keresés:</translation> </message> <message> <location filename="../config/addplugindialog.ui" line="98"/> <source>Add Widget</source> <translation>Elem hozzáadás</translation> </message> <message> <location filename="../config/addplugindialog.ui" line="105"/> <source>Close</source> <translation>Bezár</translation> </message> <message> <location filename="../config/addplugindialog.cpp" line="115"/> <source>(only one instance can run at a time)</source> <translation>(egy időben csak egy futhat)</translation> </message> </context> <context> <name>ConfigPanelDialog</name> <message> <location filename="../config/configpaneldialog.cpp" line="31"/> <source>Configure Panel</source> <translation>Panelbeállítás</translation> </message> <message> <location filename="../config/configpaneldialog.cpp" line="38"/> <source>Panel</source> <translation></translation> </message> <message> <location filename="../config/configpaneldialog.cpp" line="42"/> <source>Widgets</source> <translation>Elemek</translation> </message> </context> <context> <name>ConfigPanelWidget</name> <message> <location filename="../config/configpanelwidget.ui" line="20"/> <source>Configure panel</source> <translation>Panelbeállítás</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="44"/> <source>Size</source> <translation>Méret</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="68"/> <source>&lt;p&gt;Negative pixel value sets the panel length to that many pixels less than available screen space.&lt;/p&gt;&lt;p/&gt;&lt;p&gt;&lt;i&gt;E.g. &quot;Length&quot; set to -100px, screen size is 1000px, then real panel length will be 900 px.&lt;/i&gt;&lt;/p&gt;</source> <translation>&lt;p&gt;Negatív pixel érték azt jelöli, hogy mennyivel rövidebb a panel a képernyőnél.&lt;/p&gt;&lt;p/&gt;&lt;p&gt;&lt;i&gt;Például -100px érték esetén az 1000px széles képernyőnél a panel hossza 900px.&lt;/i&gt;&lt;/p</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="81"/> <source>Size:</source> <translation>Méret:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="88"/> <source>Length:</source> <translation>Hossz:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="96"/> <source>%</source> <translation></translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="101"/> <source>px</source> <translation>pixel</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="109"/> <location filename="../config/configpanelwidget.ui" line="153"/> <source> px</source> <translation> pixel</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="166"/> <source>Icon size:</source> <translation>Ikonméret:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="202"/> <source>Alignment &amp;&amp; position</source> <translation>Igazítás &amp;&amp; helyzet</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="250"/> <source>A&amp;uto-hide</source> <translation>A&amp;utomata elrejtés</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="262"/> <location filename="../config/configpanelwidget.ui" line="285"/> <source>Zero means no animation</source> <translation>Nulla esetén nincs animáció</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="288"/> <location filename="../config/configpanelwidget.ui" line="314"/> <source> ms</source> <translation></translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="301"/> <location filename="../config/configpanelwidget.ui" line="311"/> <source>Zero means no delay</source> <translation>Nulla esetén nincs várakozás</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="304"/> <source>Show with delay:</source> <translation>Láthatósági késleltetés:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="330"/> <source>Don&apos;t allow maximized windows go under the panel window</source> <translation>A maximalizált ablakok a panel alá nem lóghatnak</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="333"/> <source>Reserve space on display</source> <translation>A kijelzőn tartalékterület marad</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="237"/> <source>Position:</source> <translation>Helyzet:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="265"/> <source>Animation duration:</source> <translation>Animáció tartam:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="208"/> <source>Alignment:</source> <translation>Igazítás:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="173"/> <source>Rows:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="219"/> <location filename="../config/configpanelwidget.cpp" line="206"/> <source>Left</source> <translation>Balra</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="224"/> <location filename="../config/configpanelwidget.cpp" line="207"/> <location filename="../config/configpanelwidget.cpp" line="213"/> <source>Center</source> <translation>Középre</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="229"/> <location filename="../config/configpanelwidget.cpp" line="208"/> <source>Right</source> <translation>Jobbra</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="349"/> <source>Custom styling</source> <translation>Egyéni stílus</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="370"/> <source>Font color:</source> <translation>Betűszín:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="410"/> <source>Background color:</source> <translation>Háttérszín:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="449"/> <source>Background opacity:</source> <translation>Háttér áttetszőség:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="481"/> <source>&lt;small&gt;Compositing is required for panel transparency.&lt;/small&gt;</source> <translation>&lt;small&gt;Paneláttetszőséghez kompozitálás kell.&lt;/small&gt;</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="509"/> <source>Background image:</source> <translation>Háttér kép:</translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="561"/> <source>A partial workaround for widget styles that cannot give a separate theme to the panel. You might also want to disable: LXQt Appearance Configuration → Icons Theme → Colorize icons based on widget style (palette)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="571"/> <source>Override icon &amp;theme</source> <translation type="unfinished"></translation> </message> <message> <location filename="../config/configpanelwidget.ui" line="586"/> <source>Icon theme for panels:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="172"/> <source>Top of desktop</source> <translation>Az asztal tetejére</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="173"/> <source>Left of desktop</source> <translation>Az asztal bal oldalára</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="174"/> <source>Right of desktop</source> <translation>Az asztal jobb oldalára</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="175"/> <source>Bottom of desktop</source> <translation>Az asztal aljára</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="184"/> <source>Top of desktop %1</source> <translation>A(z) %1. asztal tetejére</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="185"/> <source>Left of desktop %1</source> <translation>A(z) %1. asztal bal oldalára</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="186"/> <source>Right of desktop %1</source> <translation>A(z) %1. asztal jobb oldalára</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="187"/> <source>Bottom of desktop %1</source> <translation>A(z) %1. asztal aljára</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="212"/> <source>Top</source> <translation>Fenn</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="214"/> <source>Bottom</source> <translation>Lenn</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="430"/> <location filename="../config/configpanelwidget.cpp" line="446"/> <source>Pick color</source> <translation>Színválasztás</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="464"/> <source>Pick image</source> <translation>Képválasztás</translation> </message> <message> <location filename="../config/configpanelwidget.cpp" line="464"/> <source>Images (*.png *.gif *.jpg)</source> <translation>Képek (*.png *.gif *.jpg)</translation> </message> </context> <context> <name>ConfigPluginsWidget</name> <message> <location filename="../config/configpluginswidget.ui" line="14"/> <source>Configure Plugins</source> <translation>Bővítménybeállítás</translation> </message> <message> <location filename="../config/configpluginswidget.ui" line="84"/> <source>Note: changes made in this page cannot be reset.</source> <translation>Megjegyzés: ezek a változtatások maradandóak.</translation> </message> <message> <location filename="../config/configpluginswidget.ui" line="112"/> <source>Move up</source> <translation>Föl</translation> </message> <message> <location filename="../config/configpluginswidget.ui" line="115"/> <location filename="../config/configpluginswidget.ui" line="129"/> <location filename="../config/configpluginswidget.ui" line="150"/> <location filename="../config/configpluginswidget.ui" line="164"/> <location filename="../config/configpluginswidget.ui" line="185"/> <source>...</source> <translation></translation> </message> <message> <location filename="../config/configpluginswidget.ui" line="126"/> <source>Move down</source> <translation>Le</translation> </message> <message> <location filename="../config/configpluginswidget.ui" line="147"/> <source>Add</source> <translation>Hozzáadás</translation> </message> <message> <location filename="../config/configpluginswidget.ui" line="161"/> <source>Remove</source> <translation>Törlés</translation> </message> <message> <location filename="../config/configpluginswidget.ui" line="182"/> <source>Configure</source> <translation>Beállítás</translation> </message> </context> <context> <name>LXQtPanel</name> <message> <location filename="../lxqtpanel.cpp" line="1068"/> <location filename="../lxqtpanel.cpp" line="1094"/> <source>Panel</source> <translation></translation> </message> <message> <location filename="../lxqtpanel.cpp" line="1097"/> <source>Configure Panel</source> <translation>Panelbeállítás</translation> </message> <message> <location filename="../lxqtpanel.cpp" line="1102"/> <source>Manage Widgets</source> <translation>Bővítménykezelés</translation> </message> <message> <location filename="../lxqtpanel.cpp" line="1108"/> <source>Add New Panel</source> <translation>Új panel</translation> </message> <message> <location filename="../lxqtpanel.cpp" line="1115"/> <source>Remove Panel</source> <comment>Menu Item</comment> <translation>Panel törlés</translation> </message> <message> <location filename="../lxqtpanel.cpp" line="1120"/> <source>Lock This Panel</source> <translation>A panel zárolása</translation> </message> <message> <location filename="../lxqtpanel.cpp" line="1273"/> <source>Remove Panel</source> <comment>Dialog Title</comment> <translation>Panel törlés</translation> </message> <message> <location filename="../lxqtpanel.cpp" line="1274"/> <source>Removing a panel can not be undone. Do you want to remove this panel?</source> <translation>A panel törlése végleges. Valóban töröljük?</translation> </message> </context> <context> <name>Plugin</name> <message> <location filename="../plugin.cpp" line="411"/> <source>Configure &quot;%1&quot;</source> <translation>&quot;%1&quot; beállítása</translation> </message> <message> <location filename="../plugin.cpp" line="416"/> <source>Move &quot;%1&quot;</source> <translation>&quot;%1&quot; mozgatása</translation> </message> <message> <location filename="../plugin.cpp" line="424"/> <source>Remove &quot;%1&quot;</source> <translation>&quot;%1&quot; törlése</translation> </message> </context> <context> <name>main</name> <message> <location filename="../lxqtpanelapplication.cpp" line="95"/> <source>Use alternate configuration file.</source> <translation>Egyéni beállítófájl használata.</translation> </message> <message> <location filename="../lxqtpanelapplication.cpp" line="96"/> <source>Configuration file</source> <translation>Beállítófájl</translation> </message> </context> </TS>
lgpl-2.1
thdtjsdn/Marble-1
tests/PluginManagerTest.cpp
1519
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008 Patrick Spendrin <ps_ml@gmx.de> // #include <QtTest/QtTest> #include "MarbleDirs.h" #include "PluginManager.h" namespace Marble { class PluginManagerTest : public QObject { Q_OBJECT private slots: void loadPlugins(); }; void PluginManagerTest::loadPlugins() { MarbleDirs::setMarbleDataPath( DATA_PATH ); MarbleDirs::setMarblePluginPath( PLUGIN_PATH ); const int pluginNumber = MarbleDirs::pluginEntryList( "", QDir::Files ).size(); PluginManager pm; const int renderPlugins = pm.renderPlugins().size(); const int networkPlugins = pm.networkPlugins().size(); const int positionPlugins = pm.positionProviderPlugins().size(); const int searchRunnerPlugins = pm.searchRunnerPlugins().size(); const int reverseGeocodingRunnerPlugins = pm.reverseGeocodingRunnerPlugins().size(); const int routingRunnerPlugins = pm.routingRunnerPlugins().size(); const int parsingRunnerPlugins = pm.parsingRunnerPlugins().size(); const int runnerPlugins = searchRunnerPlugins + reverseGeocodingRunnerPlugins + routingRunnerPlugins + parsingRunnerPlugins; QCOMPARE( renderPlugins + networkPlugins + positionPlugins + runnerPlugins, pluginNumber ); } } QTEST_MAIN( Marble::PluginManagerTest ) #include "PluginManagerTest.moc"
lgpl-2.1
GreggHelt2/apollo-test
src/JBrowse/Store/SeqFeature/GFF3.js
13211
define( [ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/_base/array', 'dojo/_base/url', 'JBrowse/Store/NCList', 'JBrowse/Store/SeqFeature/NCList', 'JBrowse/Store/SeqFeature', 'JBrowse/Store/DeferredStatsMixin', 'JBrowse/Store/DeferredFeaturesMixin', 'JBrowse/Util', 'JBrowse/Model/XHRBlob', 'JBrowse/Model/ArrayRepr', './GFF3/GFF3Parser' ], function( declare, lang, array, urlObj, NCList, NCListStore, SeqFeatureStore, DeferredStatsMixin, DeferredFeaturesMixin, Util, XHRBlob, ArrayRepr, GFF3Parser ) { return declare([ NCListStore ], /** * @lends JBrowse.Store.SeqFeature.GFF3 */ { // "-chains-": { constructor: "manual" }, constructor: function( args ) { // had to push some stuff that I'd like in constructor into _load instead, because need before rest of _load, but // _load is getting called at end of NCList (superclass) constructor, so before this constructor called // tried using manual constructor chaining, but this.inherited(args) didn't actually trigger // recursive superclass chaining, just the first parent (NCList) constructor. // Therefore SeqFeature, DeferredFeatureMixin, etc. weren't getting called, and manually // calling every superclass/mixin would be asking for trouble later on... // // this.inherited(arguments); }, _load: function() { var args = this.args; this.data = args.blob; this.name = args.name || ( this.data.url && new urlObj( this.data.url ).path.replace(/^.+\//,'') ) || 'anonymous'; console.log("called GFF3 load"); // load and index the gff3 here var store = this; if (this.data.blob instanceof File) { var fil = this.data.blob; var reader = new FileReader(); reader.onload = function(e) { var content = e.target.result; console.log( "In GFF3 store, got the file: " + fil.name + ", type: " + fil.type + ", size: " + fil.size); store.loadContent(content); }; reader.readAsText(fil); console.log("called reader.readAsText"); } else if (this.data.url) { var gffurl = this.data.url; dojo.xhrGet( { url: gffurl, handleAs: "text", load: function(response, ioArgs) { console.log( "In GFF3 store, got data from URL: ", gffurl); store.loadContent(response); }, error: function(response, ioArgs) { console.error(response); console.error(response.stack); } } ); } }, loadContent: function(content) { var store = this; console.log(" content start: " + content.substr(0, 50)); var gparser = new GFF3Parser(); var gff3_json = gparser.parse(content); console.log("parsed GFF3:"); console.log(gff3_json); var results = this._gff3toJbrowseJson(gff3_json, store.args); console.log("converted GFF3:"); console.log(results); var trackInfo = results.trackInfo; var featArray = results.featArray; store.attrs = new ArrayRepr(trackInfo.intervals.classes); store.nclist.fill(featArray, store.attrs); // should also calculate the feature density (avg features per // bp) and store it in: // store._stats.featureDensity store.globalStats.featureCount = trackInfo.featureCount; // average feature density per base store.globalStats.featureDensity = trackInfo.featureCount / store.refSeq.length; console.log("feature count: " + store.globalStats.featureCount); // when the store is ready to handle requests for stats and features, run: store._deferred.features.resolve({success: true}); store._deferred.stats.resolve({success: true}); }, _gff3toJbrowseJson: function(parsedGFF3, params) { var trackInfo = {}; trackInfo["intervals"] = {}; trackInfo["histograms"] = { "stats" : [ { "basesPerBin" : "1000000", "max" : 1, "mean" : 1 } ], "meta" : [ { "basesPerBin" : "1000000", "arrayParams" : { "length" : 1, "chunkSize" : 10000, "urlTemplate" : "hist-1000000-{Chunk}.json" } } ] }; trackInfo["intervals"]["classes"] = [ { "isArrayAttr" : { "Subfeatures" : 1 }, "attributes" : [ "Start", "End", "Strand", "Source", "Phase", "Type", "Score", "Id", "Name", "Subfeatures" ] }, { "isArrayAttr" : { }, "attributes" : [ "Start", "End", "Strand", "Source", "Phase", "Type", "Score", "Id", "Name", "Subfeatures" ] }, { "isArrayAttr" : { "Sublist" : 1 }, "attributes" : [ "Start", "End", "Chunk" ] } ]; trackInfo["intervals"]["lazyClass"] = 2; trackInfo["intervals"]["urlTemplate"] = "lf-{Chunk}.json"; trackInfo["formatVersion"] = 1; var featureCount = 0; // first check if we have only one feature, in which case parsedData is an object not an array if ( typeof parsedGFF3.parsedData.length == 'undefined' ){ trackInfo["featureCount"] = 1; } else { trackInfo["featureCount"] = parsedGFF3.parsedData.length; } // loop through each top level feature in parsedGFF3 and make array of featureArrays var allGff3Features = new Array; // this is an array of featureArrays containing info for all features in parsedGFF3 for( var k = 0; k < parsedGFF3.parsedData.length; k++ ) { var jbrowseFeat = this._convertParsedGFF3JsonToFeatureArray( parsedGFF3.parsedData[k] ); if (!! jbrowseFeat) { for (l = 0; l < jbrowseFeat.length; l++){ allGff3Features.push( jbrowseFeat[l] ); } } } return { trackInfo: trackInfo, featArray: allGff3Features }; }, /** * takes one parsed GFF3 feature and all of its subfeatures (children/grandchildren/great-grandchildren/...) * from a parsed GFF3 data struct (returned from GFF3toJson()), and returns a a two-level feature array for * the lowest and next-lowest level. For example, given a data struct for a parsed gene/mRNA/exon GFF3 * it would return a two-level feature array for the all mRNA features and their exons. */ _convertParsedGFF3JsonToFeatureArray: function(parsedGff3) { var featureArray = new Array(); // figure out how many levels we are dealing with here, b/c we need to return // only the data for the lowest contained in the next lowest level, since Webapollo // can only deal with two-level features. var gff3Depth = this._determineParsedGff3Depth( parsedGff3 ); // okay, we know the depth, go down to gff3Depth - 1, and pull the features at this // depth and their children. // get parents in parsedGff3.parsedData at depth - 1 var theseParents; if (gff3Depth == 1) { theseParents = [ parsedGff3 ]; } else { theseParents = this._getFeaturesAtGivenDepth(parsedGff3, gff3Depth - 1); } if (! theseParents || theseParents.length < 1) { return featureArray; } for ( j = 0; j < theseParents.length; j++ ){ var thisItem = new Array(); // set to zero because we want jbrowse/webapollo to look at the first entry in attr array to // look up what each of the following fields in thisItem mean thisItem[0] = 0; // // set parent info // var rawdata = theseParents[j].data[0].rawdata; thisItem[1] = parseInt(rawdata[3])-1; // set start (-1 for converting from 1-based to 0-based) thisItem[2] = parseInt(rawdata[4]); // set end thisItem[3] = rawdata[6]; // set strand thisItem[4] = rawdata[1]; // set source thisItem[5] = rawdata[7]; // set phase thisItem[6] = rawdata[2]; // set type thisItem[7] = rawdata[5]; // set score thisItem[8] = theseParents[j].ID; // set id var parsedNinthField = this._parsedNinthGff3Field(rawdata[8]); if ( !!parsedNinthField["Name"] ){ thisItem[9] = parsedNinthField["Name"]; } else { thisItem[9] = null; } // // now set children info // var children = theseParents[j].children; var subfeats = null; // make array for all child features if ( theseParents[j].children && (theseParents[j].children.length > 0)) { subfeats = []; for (var i = 0; i < theseParents[j].children.length; i++ ){ var childData = theseParents[j].children[i].data[0].rawdata; var subfeat = []; subfeat[0] = 1; // ? subfeat[1] = parseInt(childData[3])-1; // start (-1 for converting from 1-based to 0-based) subfeat[2] = parseInt(childData[4]); // end subfeat[3] = childData[6]; // strand subfeat[4] = childData[1]; // source subfeat[5] = childData[7]; // phase subfeat[6] = childData[2]; // type subfeat[7] = childData[5]; // score var childNinthField = this._parsedNinthGff3Field( childData[8] ); if ( !!childNinthField["ID"] ){ subfeat[8] = childNinthField["ID"]; } else { subfeat[8] = null; } if ( !!childNinthField["Name"] ){ subfeat[9] = childNinthField["Name"]; } else { subfeat[9] = null; } subfeats[i] = subfeat; } } thisItem[10] = subfeats; // load up children featureArray.push( thisItem ); } return featureArray; }, // recursive search of this feature to see how many levels there are, // helper for _convertParsedGFF3JsonToFeatureArray. This determines the // depth of the first feature it finds. _determineParsedGff3Depth: function(gffFeature) { var recursion_level = 0; var maximum_recursion_level = 20; // paranoid about infinite recursion var determineNumLevels = function(thisJsonFeature) { recursion_level++; if ( recursion_level > maximum_recursion_level ){ return false; } // recurse if there there are children //if ( !! thisJsonFeature[0] && thisJsonFeature[0]["children"] != null && thisJsonFeature[0]["children"].length > 0 ){ // if ( determineNumLevels(thisJsonFeature[0]["children"][0] ) ){ if ( thisJsonFeature.children != null && thisJsonFeature.children.length > 0 ){ if ( determineNumLevels(thisJsonFeature.children[0]) ){ return true; } } return false; }; // determineNumLevels( parsedGff3.parsedData[0] ); determineNumLevels( gffFeature ); return recursion_level; }, // helper feature for _convertParsedGFF3JsonToFeatureArray // For a given top-level feature, returns descendant features at a given depth _getFeaturesAtGivenDepth: function(gffFeature, depth) { var recursion_level = 0; var maximum_recursion_level = 20; // paranoid about infinite recursion var getFeatures = function(thisJsonFeature, thisDepth, returnedFeatures) { if ( recursion_level > maximum_recursion_level ){ return null; } // are we at the right depth? if ( recursion_level + 1 == thisDepth ){ returnedFeatures.push( thisJsonFeature ); } else if ( thisJsonFeature.children != null && thisJsonFeature.children.length > 0 ){ recursion_level++; for (var m = 0; m < thisJsonFeature.children.length; m++){ getFeatures( thisJsonFeature.children[m], depth, returnedFeatures ); } } }; var results = []; getFeatures( gffFeature, depth, results ); return results; }, // helper feature for _convertParsedGFF3JsonToFeatureArray // that parsed ninth field of gff3 file _parsedNinthGff3Field: function(ninthField) { // parse info in 9th field to get name var ninthFieldArray = ninthField.split(";"); var parsedNinthField = new Object; for (var j = 0; j < ninthFieldArray.length; j++){ var keyVal = ninthFieldArray[j].split("="); parsedNinthField[ keyVal[0] ] = keyVal[1]; } return parsedNinthField; } }); });
lgpl-2.1
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/collection/bag/BagOwner.java
937
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.test.collection.bag; import java.util.ArrayList; import java.util.List; /** * {@inheritDoc} * * @author Steve Ebersole */ public class BagOwner { private String name; private BagOwner parent; private List children = new ArrayList(); public BagOwner() { } public BagOwner(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BagOwner getParent() { return parent; } public void setParent(BagOwner parent) { this.parent = parent; } public List getChildren() { return children; } public void setChildren(List children) { this.children = children; } }
lgpl-2.1
johann8384/opentsdb
test/query/expression/TestAbsolute.java
10100
// This file is part of OpenTSDB. // Copyright (C) 2015 The OpenTSDB Authors. // // 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 2.1 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 Lesser // General Public License for more details. You should have received a copy // of the GNU Lesser General Public License along with this program. If not, // see <http://www.gnu.org/licenses/>. package net.opentsdb.query.expression; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.opentsdb.core.DataPoint; import net.opentsdb.core.DataPoints; import net.opentsdb.core.SeekableView; import net.opentsdb.core.SeekableViewsForTest; import net.opentsdb.core.TSQuery; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PowerMockIgnore({"javax.management.*", "javax.xml.*", "ch.qos.*", "org.slf4j.*", "com.sum.*", "org.xml.*"}) @PrepareForTest({ TSQuery.class }) public class TestAbsolute { private static long START_TIME = 1356998400000L; private static int INTERVAL = 60000; private static int NUM_POINTS = 5; private static String METRIC = "sys.cpu"; private TSQuery data_query; private SeekableView view; private DataPoints dps; private DataPoints[] group_bys; private List<DataPoints[]> query_results; private List<String> params; private Absolute func; @Before public void before() throws Exception { view = SeekableViewsForTest.generator(START_TIME, INTERVAL, NUM_POINTS, true, 1, 1); data_query = mock(TSQuery.class); when(data_query.startTime()).thenReturn(START_TIME); when(data_query.endTime()).thenReturn(START_TIME + (INTERVAL * NUM_POINTS)); dps = PowerMockito.mock(DataPoints.class); when(dps.iterator()).thenReturn(view); when(dps.metricName()).thenReturn(METRIC); group_bys = new DataPoints[] { dps }; query_results = new ArrayList<DataPoints[]>(1); query_results.add(group_bys); params = new ArrayList<String>(1); func = new Absolute(); } @Test public void evaluatePositiveGroupByLong() throws Exception { SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL, NUM_POINTS, true, 10, 1); DataPoints dps2 = PowerMockito.mock(DataPoints.class); when(dps2.iterator()).thenReturn(view2); when(dps2.metricName()).thenReturn("sys.mem"); group_bys = new DataPoints[] { dps, dps2 }; query_results.clear(); query_results.add(group_bys); final DataPoints[] results = func.evaluate(data_query, query_results, params); assertEquals(2, results.length); assertEquals(METRIC, results[0].metricName()); assertEquals("sys.mem", results[1].metricName()); long ts = START_TIME; long v = 1; for (DataPoint dp : results[0]) { assertEquals(ts, dp.timestamp()); assertTrue(dp.isInteger()); assertEquals(v, dp.longValue()); ts += INTERVAL; v += 1; } ts = START_TIME; v = 10; for (DataPoint dp : results[1]) { assertEquals(ts, dp.timestamp()); assertTrue(dp.isInteger()); assertEquals(v, dp.longValue()); ts += INTERVAL; v += 1; } } @Test public void evaluatePositiveGroupByDouble() throws Exception { SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL, NUM_POINTS, false, 10, 1); DataPoints dps2 = PowerMockito.mock(DataPoints.class); when(dps2.iterator()).thenReturn(view2); when(dps2.metricName()).thenReturn("sys.mem"); group_bys = new DataPoints[] { dps, dps2 }; query_results.clear(); query_results.add(group_bys); final DataPoints[] results = func.evaluate(data_query, query_results, params); assertEquals(2, results.length); assertEquals(METRIC, results[0].metricName()); assertEquals("sys.mem", results[1].metricName()); long ts = START_TIME; double v = 1; for (DataPoint dp : results[0]) { assertEquals(ts, dp.timestamp()); assertTrue(dp.isInteger()); assertEquals((long)v, dp.longValue()); ts += INTERVAL; v += 1; } ts = START_TIME; v = 10; for (DataPoint dp : results[1]) { assertEquals(ts, dp.timestamp()); assertFalse(dp.isInteger()); assertEquals(v, dp.doubleValue(), 0.001); ts += INTERVAL; v += 1; } } @Test public void evaluateFactorNegativeGroupByLong() throws Exception { SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL, NUM_POINTS, true, -10, -1); DataPoints dps2 = PowerMockito.mock(DataPoints.class); when(dps2.iterator()).thenReturn(view2); when(dps2.metricName()).thenReturn("sys.mem"); group_bys = new DataPoints[] { dps, dps2 }; query_results.clear(); query_results.add(group_bys); final DataPoints[] results = func.evaluate(data_query, query_results, params); assertEquals(2, results.length); assertEquals(METRIC, results[0].metricName()); assertEquals("sys.mem", results[1].metricName()); long ts = START_TIME; long v = 1; for (DataPoint dp : results[0]) { assertEquals(ts, dp.timestamp()); assertTrue(dp.isInteger()); assertEquals(v, dp.longValue()); ts += INTERVAL; v += 1; } ts = START_TIME; v = 10; for (DataPoint dp : results[1]) { assertEquals(ts, dp.timestamp()); assertTrue(dp.isInteger()); assertEquals(v, dp.longValue()); ts += INTERVAL; v += 1; } } @Test public void evaluateNegativeGroupByDouble() throws Exception { SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL, NUM_POINTS, false, -10, -1); DataPoints dps2 = PowerMockito.mock(DataPoints.class); when(dps2.iterator()).thenReturn(view2); when(dps2.metricName()).thenReturn("sys.mem"); group_bys = new DataPoints[] { dps, dps2 }; query_results.clear(); query_results.add(group_bys); final DataPoints[] results = func.evaluate(data_query, query_results, params); assertEquals(2, results.length); assertEquals(METRIC, results[0].metricName()); assertEquals("sys.mem", results[1].metricName()); long ts = START_TIME; double v = 1; for (DataPoint dp : results[0]) { assertEquals(ts, dp.timestamp()); assertTrue(dp.isInteger()); assertEquals((long)v, dp.longValue()); ts += INTERVAL; v += 1; } ts = START_TIME; v = 10; for (DataPoint dp : results[1]) { assertEquals(ts, dp.timestamp()); assertFalse(dp.isInteger()); assertEquals(v, dp.doubleValue(), 0.001); ts += INTERVAL; v += 1; } } @Test public void evaluateNegativeSubQuerySeries() throws Exception { params.add("1"); SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL, NUM_POINTS, true, -10, -1); DataPoints dps2 = PowerMockito.mock(DataPoints.class); when(dps2.iterator()).thenReturn(view2); when(dps2.metricName()).thenReturn("sys.mem"); group_bys = new DataPoints[] { dps, dps2 }; query_results.clear(); query_results.add(group_bys); final DataPoints[] results = func.evaluate(data_query, query_results, params); assertEquals(2, results.length); assertEquals(METRIC, results[0].metricName()); assertEquals("sys.mem", results[1].metricName()); long ts = START_TIME; long v = 1; for (DataPoint dp : results[0]) { assertEquals(ts, dp.timestamp()); assertTrue(dp.isInteger()); assertEquals(v, dp.longValue()); ts += INTERVAL; v += 1; } ts = START_TIME; v = 10; for (DataPoint dp : results[1]) { assertEquals(ts, dp.timestamp()); assertTrue(dp.isInteger()); assertEquals(v, dp.longValue()); ts += INTERVAL; v += 1; } } @Test (expected = IllegalArgumentException.class) public void evaluateNullQuery() throws Exception { params.add("1"); func.evaluate(null, query_results, params); } @Test public void evaluateNullResults() throws Exception { params.add("1"); final DataPoints[] results = func.evaluate(data_query, null, params); assertEquals(0, results.length); } @Test public void evaluateNullParams() throws Exception { assertNotNull(func.evaluate(data_query, query_results, null)); } @Test public void evaluateEmptyResults() throws Exception { final DataPoints[] results = func.evaluate(data_query, Collections.<DataPoints[]>emptyList(), params); assertEquals(0, results.length); } @Test public void evaluateEmptyParams() throws Exception { assertNotNull(func.evaluate(data_query, query_results, null)); } @Test public void writeStringField() throws Exception { params.add("1"); assertEquals("absolute(inner_expression)", func.writeStringField(params, "inner_expression")); assertEquals("absolute(null)", func.writeStringField(params, null)); assertEquals("absolute()", func.writeStringField(params, "")); assertEquals("absolute(inner_expression)", func.writeStringField(null, "inner_expression")); } }
lgpl-2.1
thahemp/osg-android
src/osg/Uniform.cpp
82389
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * Copyright (C) 2003-2005 3Dlabs Inc. Ltd. * Copyright (C) 2008 Zebra Imaging * Copyright (C) 2012 David Callu * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commercial and non commercial * applications, as long as this copyright notice is maintained. * * This application 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. */ /* file: src/osg/Uniform.cpp * author: Mike Weiblen 2008-01-02 */ #include <string.h> #include <osg/Notify> #include <osg/Uniform> #include <osg/Program> #include <osg/StateSet> #include <limits.h> #include <algorithm> using namespace osg; /////////////////////////////////////////////////////////////////////////// // osg::Uniform /////////////////////////////////////////////////////////////////////////// Uniform::Uniform() : _type(UNDEFINED), _numElements(0), _nameID(UINT_MAX), _modifiedCount(0) { } Uniform::Uniform( Type type, const std::string& name, int numElements ) : _type(type), _numElements(0), _nameID(UINT_MAX), _modifiedCount(0) { setName(name); setNumElements(numElements); allocateDataArray(); } Uniform::Uniform( const Uniform& rhs, const CopyOp& copyop ) : Object(rhs,copyop), _type(rhs._type) { copyData( rhs ); } Uniform::~Uniform() { } void Uniform::addParent(osg::StateSet* object) { OSG_DEBUG_FP<<"Uniform Adding parent"<<std::endl; OpenThreads::ScopedPointerLock<OpenThreads::Mutex> lock(getRefMutex()); _parents.push_back(object); } void Uniform::removeParent(osg::StateSet* object) { OpenThreads::ScopedPointerLock<OpenThreads::Mutex> lock(getRefMutex()); ParentList::iterator pitr = std::find(_parents.begin(),_parents.end(),object); if (pitr!=_parents.end()) _parents.erase(pitr); } bool Uniform::setType( Type t ) { if (_type==t) return true; if( _type != UNDEFINED ) { OSG_WARN << "cannot change Uniform type" << std::endl; return false; } _type = t; allocateDataArray(); return true; } void Uniform::setName( const std::string& name ) { if( _name != "" ) { OSG_WARN << "cannot change Uniform name" << std::endl; return; } Object::setName(name); _nameID = getNameID(_name); } void Uniform::setNumElements( unsigned int numElements ) { if( numElements < 1 ) { OSG_WARN << "Uniform numElements < 1 is invalid" << std::endl; return; } if (numElements == _numElements) return; if( _numElements>0 ) { OSG_WARN << "Warning: Uniform::setNumElements() cannot change Uniform numElements, size already fixed." << std::endl; return; } _numElements = numElements; allocateDataArray(); } void Uniform::allocateDataArray() { // if one array is already allocated, the job is done. if( _floatArray.valid() || _doubleArray.valid() || _intArray.valid() || _uintArray.valid() ) return; // array cannot be created until _type and _numElements are specified int arrayNumElements = getInternalArrayNumElements(); if( arrayNumElements ) { switch( getInternalArrayType(getType()) ) { case GL_FLOAT: _floatArray = new FloatArray(arrayNumElements); return; case GL_DOUBLE: _doubleArray = new DoubleArray(arrayNumElements); return; case GL_INT: _intArray = new IntArray(arrayNumElements); return; case GL_UNSIGNED_INT: _uintArray = new UIntArray(arrayNumElements); return; default: break; } } } bool Uniform::setArray( FloatArray* array ) { if( !array ) return false; // incoming array must match configuration of the Uniform if( getInternalArrayType(getType())!=GL_FLOAT || getInternalArrayNumElements()!=array->getNumElements() ) { OSG_WARN << "Uniform::setArray : incompatible array" << std::endl; return false; } _floatArray = array; _doubleArray = 0; _intArray = 0; _uintArray = 0; dirty(); return true; } bool Uniform::setArray( DoubleArray* array ) { if( !array ) return false; // incoming array must match configuration of the Uniform if( getInternalArrayType(getType())!=GL_DOUBLE || getInternalArrayNumElements()!=array->getNumElements() ) { OSG_WARN << "Uniform::setArray : incompatible array" << std::endl; return false; } _doubleArray = array; _floatArray = 0; _intArray = 0; _uintArray = 0; dirty(); return true; } bool Uniform::setArray( IntArray* array ) { if( !array ) return false; // incoming array must match configuration of the Uniform if( getInternalArrayType(getType())!=GL_INT || getInternalArrayNumElements()!=array->getNumElements() ) { OSG_WARN << "Uniform::setArray : incompatible array" << std::endl; return false; } _intArray = array; _floatArray = 0; _doubleArray = 0; _uintArray = 0; dirty(); return true; } bool Uniform::setArray( UIntArray* array ) { if( !array ) return false; // incoming array must match configuration of the Uniform if( getInternalArrayType(getType())!=GL_UNSIGNED_INT || getInternalArrayNumElements()!=array->getNumElements() ) { OSG_WARN << "Uniform::setArray : incompatible array" << std::endl; return false; } _uintArray = array; _floatArray = 0; _doubleArray = 0; _intArray = 0; dirty(); return true; } /////////////////////////////////////////////////////////////////////////// int Uniform::compare(const Uniform& rhs) const { if( this == &rhs ) return 0; if( _type < rhs._type ) return -1; if( rhs._type < _type ) return 1; if( _numElements < rhs._numElements ) return -1; if( rhs._numElements < _numElements ) return 1; if( _name < rhs._name ) return -1; if( rhs._name < _name ) return 1; return compareData( rhs ); } int Uniform::compareData(const Uniform& rhs) const { // caller must ensure that _type==rhs._type if( _floatArray.valid() ) { if( ! rhs._floatArray ) return 1; if( _floatArray == rhs._floatArray ) return 0; return memcmp( _floatArray->getDataPointer(), rhs._floatArray->getDataPointer(), _floatArray->getTotalDataSize() ); } else if( _doubleArray.valid() ) { if( ! rhs._doubleArray ) return 1; if( _doubleArray == rhs._doubleArray ) return 0; return memcmp( _doubleArray->getDataPointer(), rhs._doubleArray->getDataPointer(), _doubleArray->getTotalDataSize() ); } else if( _intArray.valid() ) { if( ! rhs._intArray ) return 1; if( _intArray == rhs._intArray ) return 0; return memcmp( _intArray->getDataPointer(), rhs._intArray->getDataPointer(), _intArray->getTotalDataSize() ); } else if( _uintArray.valid() ) { if( ! rhs._uintArray ) return 1; if( _uintArray == rhs._uintArray ) return 0; return memcmp( _uintArray->getDataPointer(), rhs._uintArray->getDataPointer(), _uintArray->getTotalDataSize() ); } return -1; // how got here? } void Uniform::copyData(const Uniform& rhs) { // caller must ensure that _type==rhs._type _numElements = rhs._numElements; _nameID = rhs._nameID; if (rhs._floatArray.valid() || rhs._doubleArray.valid() || rhs._intArray.valid() || rhs._uintArray.valid()) allocateDataArray(); if( _floatArray.valid() && rhs._floatArray.valid() ) *_floatArray = *rhs._floatArray; if( _doubleArray.valid() && rhs._doubleArray.valid() ) *_doubleArray = *rhs._doubleArray; if( _intArray.valid() && rhs._intArray.valid() ) *_intArray = *rhs._intArray; if( _uintArray.valid() && rhs._uintArray.valid() ) *_uintArray = *rhs._uintArray; dirty(); } bool Uniform::isCompatibleType( Type t ) const { if( (t==UNDEFINED) || (getType()==UNDEFINED) ) return false; if( t == getType() ) return true; if( getGlApiType(t) == getGlApiType(getType()) ) return true; OSG_WARN << "Cannot assign between Uniform types " << getTypename(t) << " and " << getTypename(getType()) << std::endl; return false; } bool Uniform::isCompatibleType( Type t1, Type t2 ) const { if( (t1==UNDEFINED) || (t2==UNDEFINED) || (getType()==UNDEFINED) ) return false; if( (t1 == getType()) || (t2 == getType()) ) return true; if( getGlApiType(t1) == getGlApiType(getType()) ) return true; if( getGlApiType(t2) == getGlApiType(getType()) ) return true; OSG_WARN << "Cannot assign between Uniform types " << getTypename(t1) << " or " << getTypename(t2) << " and " << getTypename(getType()) << std::endl; return false; } unsigned int Uniform::getInternalArrayNumElements() const { if( getNumElements()<1 || getType()==UNDEFINED ) return 0; return getNumElements() * getTypeNumComponents(getType()); } /////////////////////////////////////////////////////////////////////////// // static methods const char* Uniform::getTypename( Type t ) { switch( t ) { case FLOAT: return "float"; case FLOAT_VEC2: return "vec2"; case FLOAT_VEC3: return "vec3"; case FLOAT_VEC4: return "vec4"; case DOUBLE: return "double"; case DOUBLE_VEC2: return "dvec2"; case DOUBLE_VEC3: return "dvec3"; case DOUBLE_VEC4: return "dvec4"; case INT: return "int"; case INT_VEC2: return "ivec2"; case INT_VEC3: return "ivec3"; case INT_VEC4: return "ivec4"; case UNSIGNED_INT: return "uint"; case UNSIGNED_INT_VEC2: return "uivec2"; case UNSIGNED_INT_VEC3: return "uivec3"; case UNSIGNED_INT_VEC4: return "uivec4"; case BOOL: return "bool"; case BOOL_VEC2: return "bvec2"; case BOOL_VEC3: return "bvec3"; case BOOL_VEC4: return "bvec4"; case FLOAT_MAT2: return "mat2"; case FLOAT_MAT3: return "mat3"; case FLOAT_MAT4: return "mat4"; case FLOAT_MAT2x3: return "mat2x3"; case FLOAT_MAT2x4: return "mat2x4"; case FLOAT_MAT3x2: return "mat3x2"; case FLOAT_MAT3x4: return "mat3x4"; case FLOAT_MAT4x2: return "mat4x2"; case FLOAT_MAT4x3: return "mat4x3"; case DOUBLE_MAT2: return "dmat2"; case DOUBLE_MAT3: return "dmat3"; case DOUBLE_MAT4: return "dmat4"; case DOUBLE_MAT2x3: return "dmat2x3"; case DOUBLE_MAT2x4: return "dmat2x4"; case DOUBLE_MAT3x2: return "dmat3x2"; case DOUBLE_MAT3x4: return "dmat3x4"; case DOUBLE_MAT4x2: return "dmat4x2"; case DOUBLE_MAT4x3: return "dmat4x3"; case SAMPLER_1D: return "sampler1D"; case SAMPLER_2D: return "sampler2D"; case SAMPLER_3D: return "sampler3D"; case SAMPLER_CUBE: return "samplerCube"; case SAMPLER_1D_SHADOW: return "sampler1DShadow"; case SAMPLER_2D_SHADOW: return "sampler2DShadow"; case SAMPLER_1D_ARRAY: return "sampler1DArray"; case SAMPLER_2D_ARRAY: return "sampler2DArray"; case SAMPLER_CUBE_MAP_ARRAY: return "samplerCubeMapArray"; case SAMPLER_1D_ARRAY_SHADOW: return "sampler1DArrayShadow"; case SAMPLER_2D_ARRAY_SHADOW: return "sampler2DArrayShadow"; case SAMPLER_2D_MULTISAMPLE: return "sampler2DMS"; case SAMPLER_2D_MULTISAMPLE_ARRAY: return "sampler2DMSArray"; case SAMPLER_CUBE_SHADOW: return "samplerCubeShadow"; case SAMPLER_CUBE_MAP_ARRAY_SHADOW: return "samplerCubeMapArrayShadow"; case SAMPLER_BUFFER: return "samplerBuffer"; case SAMPLER_2D_RECT: return "sampler2DRect"; case SAMPLER_2D_RECT_SHADOW: return "sampler2DRectShadow"; case INT_SAMPLER_1D: return "isampler1D"; case INT_SAMPLER_2D: return "isampler2D"; case INT_SAMPLER_3D: return "isampler3D"; case INT_SAMPLER_CUBE: return "isamplerCube"; case INT_SAMPLER_1D_ARRAY: return "isampler1DArray"; case INT_SAMPLER_2D_ARRAY: return "isampler2DArray"; case INT_SAMPLER_CUBE_MAP_ARRAY: return "isamplerCubeMapArray"; case INT_SAMPLER_2D_MULTISAMPLE: return "isampler2DMS"; case INT_SAMPLER_2D_MULTISAMPLE_ARRAY: return "isampler2DMSArray"; case INT_SAMPLER_BUFFER: return "isamplerBuffer"; case INT_SAMPLER_2D_RECT: return "isampler2DRect"; case UNSIGNED_INT_SAMPLER_1D: return "usample1D"; case UNSIGNED_INT_SAMPLER_2D: return "usample2D"; case UNSIGNED_INT_SAMPLER_3D: return "usample3D"; case UNSIGNED_INT_SAMPLER_CUBE: return "usampleCube"; case UNSIGNED_INT_SAMPLER_1D_ARRAY: return "usample1DArray"; case UNSIGNED_INT_SAMPLER_2D_ARRAY: return "usample2DArray"; case UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: return "usampleCubeMapArray"; case UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: return "usample2DMS"; case UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: return "usample2DMSArray"; case UNSIGNED_INT_SAMPLER_BUFFER: return "usampleBuffer"; case UNSIGNED_INT_SAMPLER_2D_RECT: return "usample2DRect"; case IMAGE_1D: return "image1D"; case IMAGE_2D: return "image2D"; case IMAGE_3D: return "image3D"; case IMAGE_2D_RECT: return "image2DRect"; case IMAGE_CUBE: return "imageCube"; case IMAGE_BUFFER: return "imageBuffer"; case IMAGE_1D_ARRAY: return "image1DArray"; case IMAGE_2D_ARRAY: return "image2DArray"; case IMAGE_CUBE_MAP_ARRAY: return "imageCubeArray"; case IMAGE_2D_MULTISAMPLE: return "image2DMS"; case IMAGE_2D_MULTISAMPLE_ARRAY: return "image2DMSArray"; case INT_IMAGE_1D: return "iimage1D"; case INT_IMAGE_2D: return "iimage2D"; case INT_IMAGE_3D: return "iimage3D"; case INT_IMAGE_2D_RECT: return "iimage2DRect"; case INT_IMAGE_CUBE: return "iimageCube"; case INT_IMAGE_BUFFER: return "iimageBuffer"; case INT_IMAGE_1D_ARRAY: return "iimage1DArray"; case INT_IMAGE_2D_ARRAY: return "iimage2DArray"; case INT_IMAGE_CUBE_MAP_ARRAY: return "iimageCubeArray"; case INT_IMAGE_2D_MULTISAMPLE: return "iimage2DMS"; case INT_IMAGE_2D_MULTISAMPLE_ARRAY: return "iimage2DMSArray"; case UNSIGNED_INT_IMAGE_1D: return "uimage1D"; case UNSIGNED_INT_IMAGE_2D: return "uimage2D"; case UNSIGNED_INT_IMAGE_3D: return "uimage3D"; case UNSIGNED_INT_IMAGE_2D_RECT: return "uimage2DRect"; case UNSIGNED_INT_IMAGE_CUBE: return "uimageCube"; case UNSIGNED_INT_IMAGE_BUFFER: return "uimageBuffer"; case UNSIGNED_INT_IMAGE_1D_ARRAY: return "uimage1DArray"; case UNSIGNED_INT_IMAGE_2D_ARRAY: return "uimage2DArray"; case UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: return "uimageCubeArray"; case UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: return "uimage2DMS"; case UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: return "uimage2DMSArray"; default: return "UNDEFINED"; } } int Uniform::getTypeNumComponents( Type t ) { switch( t ) { case FLOAT: case DOUBLE: case INT: case UNSIGNED_INT: case BOOL: case SAMPLER_1D: case SAMPLER_2D: case SAMPLER_3D: case SAMPLER_CUBE: case SAMPLER_1D_SHADOW: case SAMPLER_2D_SHADOW: case SAMPLER_1D_ARRAY: case SAMPLER_2D_ARRAY: case SAMPLER_CUBE_MAP_ARRAY: case SAMPLER_1D_ARRAY_SHADOW: case SAMPLER_2D_ARRAY_SHADOW: case SAMPLER_2D_MULTISAMPLE: case SAMPLER_2D_MULTISAMPLE_ARRAY: case SAMPLER_CUBE_SHADOW: case SAMPLER_CUBE_MAP_ARRAY_SHADOW: case SAMPLER_BUFFER: case SAMPLER_2D_RECT: case SAMPLER_2D_RECT_SHADOW: case INT_SAMPLER_1D: case INT_SAMPLER_2D: case INT_SAMPLER_3D: case INT_SAMPLER_CUBE: case INT_SAMPLER_1D_ARRAY: case INT_SAMPLER_2D_ARRAY: case INT_SAMPLER_CUBE_MAP_ARRAY: case INT_SAMPLER_2D_MULTISAMPLE: case INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case INT_SAMPLER_BUFFER: case INT_SAMPLER_2D_RECT: case UNSIGNED_INT_SAMPLER_1D: case UNSIGNED_INT_SAMPLER_2D: case UNSIGNED_INT_SAMPLER_3D: case UNSIGNED_INT_SAMPLER_CUBE: case UNSIGNED_INT_SAMPLER_1D_ARRAY: case UNSIGNED_INT_SAMPLER_2D_ARRAY: case UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: case UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: case UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case UNSIGNED_INT_SAMPLER_BUFFER: case UNSIGNED_INT_SAMPLER_2D_RECT: case IMAGE_1D: case IMAGE_2D: case IMAGE_3D: case IMAGE_2D_RECT: case IMAGE_CUBE: case IMAGE_BUFFER: case IMAGE_1D_ARRAY: case IMAGE_2D_ARRAY: case IMAGE_CUBE_MAP_ARRAY: case IMAGE_2D_MULTISAMPLE: case IMAGE_2D_MULTISAMPLE_ARRAY: case INT_IMAGE_1D: case INT_IMAGE_2D: case INT_IMAGE_3D: case INT_IMAGE_2D_RECT: case INT_IMAGE_CUBE: case INT_IMAGE_BUFFER: case INT_IMAGE_1D_ARRAY: case INT_IMAGE_2D_ARRAY: case INT_IMAGE_CUBE_MAP_ARRAY: case INT_IMAGE_2D_MULTISAMPLE: case INT_IMAGE_2D_MULTISAMPLE_ARRAY: case UNSIGNED_INT_IMAGE_1D: case UNSIGNED_INT_IMAGE_2D: case UNSIGNED_INT_IMAGE_3D: case UNSIGNED_INT_IMAGE_2D_RECT: case UNSIGNED_INT_IMAGE_CUBE: case UNSIGNED_INT_IMAGE_BUFFER: case UNSIGNED_INT_IMAGE_1D_ARRAY: case UNSIGNED_INT_IMAGE_2D_ARRAY: case UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: case UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: case UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: return 1; case FLOAT_VEC2: case DOUBLE_VEC2: case INT_VEC2: case UNSIGNED_INT_VEC2: case BOOL_VEC2: return 2; case FLOAT_VEC3: case DOUBLE_VEC3: case INT_VEC3: case UNSIGNED_INT_VEC3: case BOOL_VEC3: return 3; case FLOAT_VEC4: case DOUBLE_VEC4: case FLOAT_MAT2: case DOUBLE_MAT2: case INT_VEC4: case UNSIGNED_INT_VEC4: case BOOL_VEC4: return 4; case FLOAT_MAT2x3: case FLOAT_MAT3x2: case DOUBLE_MAT2x3: case DOUBLE_MAT3x2: return 6; case FLOAT_MAT2x4: case FLOAT_MAT4x2: case DOUBLE_MAT2x4: case DOUBLE_MAT4x2: return 8; case FLOAT_MAT3: case DOUBLE_MAT3: return 9; case FLOAT_MAT3x4: case FLOAT_MAT4x3: case DOUBLE_MAT3x4: case DOUBLE_MAT4x3: return 12; case FLOAT_MAT4: case DOUBLE_MAT4: return 16; default: return 0; } } Uniform::Type Uniform::getTypeId( const std::string& tname ) { if( tname == "float" ) return FLOAT; if( tname == "vec2" ) return FLOAT_VEC2; if( tname == "vec3" ) return FLOAT_VEC3; if( tname == "vec4" ) return FLOAT_VEC4; if( tname == "double" ) return DOUBLE; if( tname == "dvec2" ) return DOUBLE_VEC2; if( tname == "dvec3" ) return DOUBLE_VEC3; if( tname == "dvec4" ) return DOUBLE_VEC4; if( tname == "int" ) return INT; if( tname == "ivec2" ) return INT_VEC2; if( tname == "ivec3" ) return INT_VEC3; if( tname == "ivec4" ) return INT_VEC4; if( tname == "unsigned int" || tname == "uint" ) return UNSIGNED_INT; if( tname == "uvec2" ) return UNSIGNED_INT_VEC2; if( tname == "uvec3" ) return UNSIGNED_INT_VEC3; if( tname == "uvec4" ) return UNSIGNED_INT_VEC4; if( tname == "bool" ) return BOOL; if( tname == "bvec2" ) return BOOL_VEC2; if( tname == "bvec3" ) return BOOL_VEC3; if( tname == "bvec4" ) return BOOL_VEC4; if( tname == "mat2" || tname == "mat2x2" ) return FLOAT_MAT2; if( tname == "mat3" || tname == "mat3x3" ) return FLOAT_MAT3; if( tname == "mat4" || tname == "mat4x4" ) return FLOAT_MAT4; if( tname == "mat2x3" ) return FLOAT_MAT2x3; if( tname == "mat2x4" ) return FLOAT_MAT2x4; if( tname == "mat3x2" ) return FLOAT_MAT3x2; if( tname == "mat3x4" ) return FLOAT_MAT3x4; if( tname == "mat4x2" ) return FLOAT_MAT4x2; if( tname == "mat4x3" ) return FLOAT_MAT4x3; if( tname == "mat2d" || tname == "mat2x2d" ) return DOUBLE_MAT2; if( tname == "mat3d" || tname == "mat3x3d" ) return DOUBLE_MAT3; if( tname == "mat4d" || tname == "mat4x4d" ) return DOUBLE_MAT4; if( tname == "mat2x3d" ) return DOUBLE_MAT2x3; if( tname == "mat2x4d" ) return DOUBLE_MAT2x4; if( tname == "mat3x2d" ) return DOUBLE_MAT3x2; if( tname == "mat3x4d" ) return DOUBLE_MAT3x4; if( tname == "mat4x2d" ) return DOUBLE_MAT4x2; if( tname == "mat4x3d" ) return DOUBLE_MAT4x3; if( tname == "sampler1D" ) return SAMPLER_1D; if( tname == "sampler2D" ) return SAMPLER_2D; if( tname == "sampler3D" ) return SAMPLER_3D; if( tname == "samplerCube" ) return SAMPLER_CUBE; if( tname == "sampler1DShadow" ) return SAMPLER_1D_SHADOW; if( tname == "sampler2DShadow" ) return SAMPLER_2D_SHADOW; if( tname == "sampler1DArray" ) return SAMPLER_1D_ARRAY; if( tname == "sampler2DArray" ) return SAMPLER_2D_ARRAY; if( tname == "samplerCubeMapArray" ) return SAMPLER_CUBE_MAP_ARRAY; if( tname == "sampler1DArrayShadow" ) return SAMPLER_1D_ARRAY_SHADOW; if( tname == "sampler2DArrayShadow" ) return SAMPLER_2D_ARRAY_SHADOW; if( tname == "sampler2DMS" ) return SAMPLER_2D_MULTISAMPLE; if( tname == "sampler2DMSArray" ) return SAMPLER_2D_MULTISAMPLE_ARRAY; if( tname == "samplerCubeShadow" ) return SAMPLER_CUBE_SHADOW; if( tname == "samplerCubeMapArrayShadow" ) return SAMPLER_CUBE_MAP_ARRAY_SHADOW; if( tname == "samplerBuffer" ) return SAMPLER_BUFFER; if( tname == "sampler2DRect" ) return SAMPLER_2D_RECT; if( tname == "sampler2DRectShadow" ) return SAMPLER_2D_RECT_SHADOW; if( tname == "isampler1D" ) return INT_SAMPLER_1D; if( tname == "isampler2D" ) return INT_SAMPLER_2D; if( tname == "isampler3D" ) return INT_SAMPLER_3D; if( tname == "isamplerCube" ) return INT_SAMPLER_CUBE; if( tname == "isampler1DArray" ) return INT_SAMPLER_1D_ARRAY; if( tname == "isampler2DArray" ) return INT_SAMPLER_2D_ARRAY; if( tname == "isamplerCubeMapArray" ) return INT_SAMPLER_CUBE_MAP_ARRAY; if( tname == "isampler2DMS" ) return INT_SAMPLER_2D_MULTISAMPLE; if( tname == "isampler2DMSArray" ) return INT_SAMPLER_2D_MULTISAMPLE_ARRAY; if( tname == "isamplerBuffer" ) return INT_SAMPLER_BUFFER; if( tname == "isampler2DRect" ) return INT_SAMPLER_2D_RECT; if( tname == "usampler1D" ) return UNSIGNED_INT_SAMPLER_1D; if( tname == "usampler2D" ) return UNSIGNED_INT_SAMPLER_2D; if( tname == "usampler3D" ) return UNSIGNED_INT_SAMPLER_3D; if( tname == "usamplerCube" ) return UNSIGNED_INT_SAMPLER_CUBE; if( tname == "usampler1DArray" ) return UNSIGNED_INT_SAMPLER_1D_ARRAY; if( tname == "usampler2DArray" ) return UNSIGNED_INT_SAMPLER_2D_ARRAY; if( tname == "usamplerCubeMapArray" ) return UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY; if( tname == "usampler2DMS" ) return UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE; if( tname == "usampler2DMSArray" ) return UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY; if( tname == "usamplerBuffer" ) return UNSIGNED_INT_SAMPLER_BUFFER; if( tname == "usampler2DRect" ) return UNSIGNED_INT_SAMPLER_2D_RECT; if( tname == "image1D" ) return IMAGE_1D; if( tname == "image2D" ) return IMAGE_2D; if( tname == "image3D" ) return IMAGE_3D; if( tname == "image2DRect" ) return IMAGE_2D_RECT; if( tname == "imageCube" ) return IMAGE_CUBE; if( tname == "imageBuffer" ) return IMAGE_BUFFER; if( tname == "image1DArray" ) return IMAGE_1D_ARRAY; if( tname == "image2DArray" ) return IMAGE_2D_ARRAY; if( tname == "imageCubeArray" ) return IMAGE_CUBE_MAP_ARRAY; if( tname == "image2DMS" ) return IMAGE_2D_MULTISAMPLE; if( tname == "image2DMSArray" ) return IMAGE_2D_MULTISAMPLE_ARRAY; if( tname == "iimage1D" ) return INT_IMAGE_1D; if( tname == "iimage2D" ) return INT_IMAGE_2D; if( tname == "iimage3D" ) return INT_IMAGE_3D; if( tname == "iimage2DRect" ) return INT_IMAGE_2D_RECT; if( tname == "iimageCube" ) return INT_IMAGE_CUBE; if( tname == "iimageBuffer" ) return INT_IMAGE_BUFFER; if( tname == "iimage1DArray" ) return INT_IMAGE_1D_ARRAY; if( tname == "iimage2DArray" ) return INT_IMAGE_2D_ARRAY; if( tname == "iimageCubeArray" ) return INT_IMAGE_CUBE_MAP_ARRAY; if( tname == "iimage2DMS" ) return INT_IMAGE_2D_MULTISAMPLE; if( tname == "iimage2DMSArray" ) return INT_IMAGE_2D_MULTISAMPLE_ARRAY; if( tname == "uimage1D" ) return UNSIGNED_INT_IMAGE_1D; if( tname == "uimage2D" ) return UNSIGNED_INT_IMAGE_2D; if( tname == "uimage3D" ) return UNSIGNED_INT_IMAGE_3D; if( tname == "uimage2DRect" ) return UNSIGNED_INT_IMAGE_2D_RECT; if( tname == "uimageCube" ) return UNSIGNED_INT_IMAGE_CUBE; if( tname == "uimageBuffer" ) return UNSIGNED_INT_IMAGE_BUFFER; if( tname == "uimage1DArray" ) return UNSIGNED_INT_IMAGE_1D_ARRAY; if( tname == "uimage2DArray" ) return UNSIGNED_INT_IMAGE_2D_ARRAY; if( tname == "uimageCubeArray" ) return UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY; if( tname == "uimage2DMS" ) return UNSIGNED_INT_IMAGE_2D_MULTISAMPLE; if( tname == "uimage2DMSArray" ) return UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY; return UNDEFINED; } Uniform::Type Uniform::getGlApiType( Type t ) { switch( t ) { case BOOL: case SAMPLER_1D: case SAMPLER_2D: case SAMPLER_3D: case SAMPLER_CUBE: case SAMPLER_1D_SHADOW: case SAMPLER_2D_SHADOW: case SAMPLER_1D_ARRAY: case SAMPLER_2D_ARRAY: case SAMPLER_CUBE_MAP_ARRAY: case SAMPLER_1D_ARRAY_SHADOW: case SAMPLER_2D_ARRAY_SHADOW: case SAMPLER_2D_MULTISAMPLE: case SAMPLER_2D_MULTISAMPLE_ARRAY: case SAMPLER_CUBE_SHADOW: case SAMPLER_CUBE_MAP_ARRAY_SHADOW: case SAMPLER_BUFFER: case SAMPLER_2D_RECT: case SAMPLER_2D_RECT_SHADOW: case INT_SAMPLER_1D: case INT_SAMPLER_2D: case INT_SAMPLER_3D: case INT_SAMPLER_CUBE: case INT_SAMPLER_1D_ARRAY: case INT_SAMPLER_2D_ARRAY: case INT_SAMPLER_CUBE_MAP_ARRAY: case INT_SAMPLER_2D_MULTISAMPLE: case INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case INT_SAMPLER_BUFFER: case INT_SAMPLER_2D_RECT: case UNSIGNED_INT_SAMPLER_1D: case UNSIGNED_INT_SAMPLER_2D: case UNSIGNED_INT_SAMPLER_3D: case UNSIGNED_INT_SAMPLER_CUBE: case UNSIGNED_INT_SAMPLER_1D_ARRAY: case UNSIGNED_INT_SAMPLER_2D_ARRAY: case UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: case UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: case UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case UNSIGNED_INT_SAMPLER_BUFFER: case UNSIGNED_INT_SAMPLER_2D_RECT: case IMAGE_1D: case IMAGE_2D: case IMAGE_3D: case IMAGE_2D_RECT: case IMAGE_CUBE: case IMAGE_BUFFER: case IMAGE_1D_ARRAY: case IMAGE_2D_ARRAY: case IMAGE_CUBE_MAP_ARRAY: case IMAGE_2D_MULTISAMPLE: case IMAGE_2D_MULTISAMPLE_ARRAY: case INT_IMAGE_1D: case INT_IMAGE_2D: case INT_IMAGE_3D: case INT_IMAGE_2D_RECT: case INT_IMAGE_CUBE: case INT_IMAGE_BUFFER: case INT_IMAGE_1D_ARRAY: case INT_IMAGE_2D_ARRAY: case INT_IMAGE_CUBE_MAP_ARRAY: case INT_IMAGE_2D_MULTISAMPLE: case INT_IMAGE_2D_MULTISAMPLE_ARRAY: case UNSIGNED_INT_IMAGE_1D: case UNSIGNED_INT_IMAGE_2D: case UNSIGNED_INT_IMAGE_3D: case UNSIGNED_INT_IMAGE_2D_RECT: case UNSIGNED_INT_IMAGE_CUBE: case UNSIGNED_INT_IMAGE_BUFFER: case UNSIGNED_INT_IMAGE_1D_ARRAY: case UNSIGNED_INT_IMAGE_2D_ARRAY: case UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: case UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: case UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: return INT; case BOOL_VEC2: return INT_VEC2; case BOOL_VEC3: return INT_VEC3; case BOOL_VEC4: return INT_VEC4; default: return t; } } GLenum Uniform::getInternalArrayType( Type t ) { switch( t ) { case FLOAT: case FLOAT_VEC2: case FLOAT_VEC3: case FLOAT_VEC4: case FLOAT_MAT2: case FLOAT_MAT3: case FLOAT_MAT4: case FLOAT_MAT2x3: case FLOAT_MAT2x4: case FLOAT_MAT3x2: case FLOAT_MAT3x4: case FLOAT_MAT4x2: case FLOAT_MAT4x3: return GL_FLOAT; case DOUBLE: case DOUBLE_VEC2: case DOUBLE_VEC3: case DOUBLE_VEC4: case DOUBLE_MAT2: case DOUBLE_MAT3: case DOUBLE_MAT4: case DOUBLE_MAT2x3: case DOUBLE_MAT2x4: case DOUBLE_MAT3x2: case DOUBLE_MAT3x4: case DOUBLE_MAT4x2: case DOUBLE_MAT4x3: return GL_DOUBLE; case INT: case INT_VEC2: case INT_VEC3: case INT_VEC4: case BOOL: case BOOL_VEC2: case BOOL_VEC3: case BOOL_VEC4: case SAMPLER_1D: case SAMPLER_2D: case SAMPLER_3D: case SAMPLER_CUBE: case SAMPLER_1D_SHADOW: case SAMPLER_2D_SHADOW: case SAMPLER_1D_ARRAY: case SAMPLER_2D_ARRAY: case SAMPLER_CUBE_MAP_ARRAY: case SAMPLER_1D_ARRAY_SHADOW: case SAMPLER_2D_ARRAY_SHADOW: case SAMPLER_2D_MULTISAMPLE: case SAMPLER_2D_MULTISAMPLE_ARRAY: case SAMPLER_CUBE_SHADOW: case SAMPLER_CUBE_MAP_ARRAY_SHADOW: case SAMPLER_BUFFER: case SAMPLER_2D_RECT: case SAMPLER_2D_RECT_SHADOW: case INT_SAMPLER_1D: case INT_SAMPLER_2D: case INT_SAMPLER_3D: case INT_SAMPLER_CUBE: case INT_SAMPLER_1D_ARRAY: case INT_SAMPLER_2D_ARRAY: case INT_SAMPLER_CUBE_MAP_ARRAY: case INT_SAMPLER_2D_MULTISAMPLE: case INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case INT_SAMPLER_BUFFER: case INT_SAMPLER_2D_RECT: case UNSIGNED_INT_SAMPLER_1D: case UNSIGNED_INT_SAMPLER_2D: case UNSIGNED_INT_SAMPLER_3D: case UNSIGNED_INT_SAMPLER_CUBE: case UNSIGNED_INT_SAMPLER_1D_ARRAY: case UNSIGNED_INT_SAMPLER_2D_ARRAY: case UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: case UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: case UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case UNSIGNED_INT_SAMPLER_BUFFER: case UNSIGNED_INT_SAMPLER_2D_RECT: case IMAGE_1D: case IMAGE_2D: case IMAGE_3D: case IMAGE_2D_RECT: case IMAGE_CUBE: case IMAGE_BUFFER: case IMAGE_1D_ARRAY: case IMAGE_2D_ARRAY: case IMAGE_CUBE_MAP_ARRAY: case IMAGE_2D_MULTISAMPLE: case IMAGE_2D_MULTISAMPLE_ARRAY: case INT_IMAGE_1D: case INT_IMAGE_2D: case INT_IMAGE_3D: case INT_IMAGE_2D_RECT: case INT_IMAGE_CUBE: case INT_IMAGE_BUFFER: case INT_IMAGE_1D_ARRAY: case INT_IMAGE_2D_ARRAY: case INT_IMAGE_CUBE_MAP_ARRAY: case INT_IMAGE_2D_MULTISAMPLE: case INT_IMAGE_2D_MULTISAMPLE_ARRAY: case UNSIGNED_INT_IMAGE_1D: case UNSIGNED_INT_IMAGE_2D: case UNSIGNED_INT_IMAGE_3D: case UNSIGNED_INT_IMAGE_2D_RECT: case UNSIGNED_INT_IMAGE_CUBE: case UNSIGNED_INT_IMAGE_BUFFER: case UNSIGNED_INT_IMAGE_1D_ARRAY: case UNSIGNED_INT_IMAGE_2D_ARRAY: case UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: case UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: case UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: return GL_INT; case UNSIGNED_INT: case UNSIGNED_INT_VEC2: case UNSIGNED_INT_VEC3: case UNSIGNED_INT_VEC4: return GL_UNSIGNED_INT; default: return 0; } } unsigned int Uniform::getNameID(const std::string& name) { typedef std::map<std::string, unsigned int> UniformNameIDMap; static OpenThreads::Mutex s_mutex_uniformNameIDMap; static UniformNameIDMap s_uniformNameIDMap; OpenThreads::ScopedLock<OpenThreads::Mutex> lock(s_mutex_uniformNameIDMap); UniformNameIDMap::iterator it = s_uniformNameIDMap.find(name); if (it != s_uniformNameIDMap.end()) { return it->second; } unsigned int id = s_uniformNameIDMap.size(); s_uniformNameIDMap.insert(UniformNameIDMap::value_type(name, id)); return id; } // Use a proxy to force the initialization of the static variables in the Unifrom::getNameID() method during static initialization OSG_INIT_SINGLETON_PROXY(UniformNameIDStaticInitializationProxy, Uniform::getNameID(std::string())) /////////////////////////////////////////////////////////////////////////// // value constructors for single-element (ie: non-array) uniforms Uniform::Uniform( const char* name, float f ) : _type(FLOAT), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( f ); } Uniform::Uniform( const char* name, const osg::Vec2& v2 ) : _type(FLOAT_VEC2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( v2 ); } Uniform::Uniform( const char* name, const osg::Vec3& v3 ) : _type(FLOAT_VEC3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( v3 ); } Uniform::Uniform( const char* name, const osg::Vec4& v4 ) : _type(FLOAT_VEC4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( v4 ); } Uniform::Uniform( const char* name, const osg::Matrix2& m2 ) : _type(FLOAT_MAT2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m2 ); } Uniform::Uniform( const char* name, const osg::Matrix3& m3 ) : _type(FLOAT_MAT3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m3 ); } Uniform::Uniform( const char* name, const osg::Matrixf& m4 ) : _type(FLOAT_MAT4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m4 ); } Uniform::Uniform( const char* name, const osg::Matrix2x3& m2x3 ) : _type(FLOAT_MAT2x3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m2x3 ); } Uniform::Uniform( const char* name, const osg::Matrix2x4& m2x4 ) : _type(FLOAT_MAT2x4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m2x4 ); } Uniform::Uniform( const char* name, const osg::Matrix3x2& m3x2 ) : _type(FLOAT_MAT3x2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m3x2 ); } Uniform::Uniform( const char* name, const osg::Matrix3x4& m3x4 ) : _type(FLOAT_MAT3x4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m3x4 ); } Uniform::Uniform( const char* name, const osg::Matrix4x2& m4x2 ) : _type(FLOAT_MAT4x2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m4x2 ); } Uniform::Uniform( const char* name, const osg::Matrix4x3& m4x3 ) : _type(FLOAT_MAT4x3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m4x3 ); } Uniform::Uniform( const char* name, double d ) : _type(DOUBLE), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( d ); } Uniform::Uniform( const char* name, const osg::Vec2d& v2 ) : _type(DOUBLE_VEC2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( v2 ); } Uniform::Uniform( const char* name, const osg::Vec3d& v3 ) : _type(DOUBLE_VEC3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( v3 ); } Uniform::Uniform( const char* name, const osg::Vec4d& v4 ) : _type(DOUBLE_VEC4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( v4 ); } Uniform::Uniform( const char* name, const osg::Matrix2d& m2 ) : _type(DOUBLE_MAT2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m2 ); } Uniform::Uniform( const char* name, const osg::Matrix3d& m3 ) : _type(DOUBLE_MAT3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m3 ); } Uniform::Uniform( const char* name, const osg::Matrixd& m4 ) : _type(DOUBLE_MAT4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m4 ); } Uniform::Uniform( const char* name, const osg::Matrix2x3d& m2x3 ) : _type(DOUBLE_MAT2x3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m2x3 ); } Uniform::Uniform( const char* name, const osg::Matrix2x4d& m2x4 ) : _type(DOUBLE_MAT2x4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m2x4 ); } Uniform::Uniform( const char* name, const osg::Matrix3x2d& m3x2 ) : _type(DOUBLE_MAT3x2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m3x2 ); } Uniform::Uniform( const char* name, const osg::Matrix3x4d& m3x4 ) : _type(DOUBLE_MAT3x4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m3x4 ); } Uniform::Uniform( const char* name, const osg::Matrix4x2d& m4x2 ) : _type(DOUBLE_MAT4x2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m4x2 ); } Uniform::Uniform( const char* name, const osg::Matrix4x3d& m4x3 ) : _type(DOUBLE_MAT4x3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( m4x3 ); } Uniform::Uniform( const char* name, int i ) : _type(INT), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( i ); } Uniform::Uniform( const char* name, int i0, int i1 ) : _type(INT_VEC2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( i0, i1 ); } Uniform::Uniform( const char* name, int i0, int i1, int i2 ) : _type(INT_VEC3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( i0, i1, i2 ); } Uniform::Uniform( const char* name, int i0, int i1, int i2, int i3 ) : _type(INT_VEC4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( i0, i1, i2, i3 ); } Uniform::Uniform( const char* name, unsigned int ui ) : _type(UNSIGNED_INT), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( ui ); } Uniform::Uniform( const char* name, unsigned int ui0, unsigned int ui1 ) : _type(UNSIGNED_INT_VEC2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( ui0, ui1 ); } Uniform::Uniform( const char* name, unsigned int ui0, unsigned int ui1, unsigned int ui2 ) : _type(UNSIGNED_INT_VEC3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( ui0, ui1, ui2 ); } Uniform::Uniform( const char* name, unsigned int ui0, unsigned int ui1, unsigned int ui2, unsigned int ui3 ) : _type(UNSIGNED_INT_VEC4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( ui0, ui1, ui2, ui3 ); } Uniform::Uniform( const char* name, bool b ) : _type(BOOL), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( b ); } Uniform::Uniform( const char* name, bool b0, bool b1 ) : _type(BOOL_VEC2), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( b0, b1 ); } Uniform::Uniform( const char* name, bool b0, bool b1, bool b2 ) : _type(BOOL_VEC3), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( b0, b1, b2 ); } Uniform::Uniform( const char* name, bool b0, bool b1, bool b2, bool b3 ) : _type(BOOL_VEC4), _numElements(1), _modifiedCount(0) { setName(name); allocateDataArray(); set( b0, b1, b2, b3 ); } /////////////////////////////////////////////////////////////////////////// // Value assignment for single-element (ie: non-array) uniforms. // (For backwards compatability, if not already configured, set the // Uniform's _numElements=1) bool Uniform::set( float f ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,f) : false; } bool Uniform::set( const osg::Vec2& v2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,v2) : false; } bool Uniform::set( const osg::Vec3& v3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,v3) : false; } bool Uniform::set( const osg::Vec4& v4 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,v4) : false; } bool Uniform::set( const osg::Matrix2& m2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m2) : false; } bool Uniform::set( const osg::Matrix3& m3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m3) : false; } bool Uniform::set( const osg::Matrixf& m4 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m4) : false; } bool Uniform::set( const osg::Matrix2x3& m2x3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m2x3) : false; } bool Uniform::set( const osg::Matrix2x4& m2x4 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m2x4) : false; } bool Uniform::set( const osg::Matrix3x2& m3x2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m3x2) : false; } bool Uniform::set( const osg::Matrix3x4& m3x4 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m3x4) : false; } bool Uniform::set( const osg::Matrix4x2& m4x2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m4x2) : false; } bool Uniform::set( const osg::Matrix4x3& m4x3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m4x3) : false; } bool Uniform::set( double d ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,d) : false; } bool Uniform::set( const osg::Vec2d& v2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,v2) : false; } bool Uniform::set( const osg::Vec3d& v3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,v3) : false; } bool Uniform::set( const osg::Vec4d& v4 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,v4) : false; } bool Uniform::set( const osg::Matrix2d& m2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m2) : false; } bool Uniform::set( const osg::Matrix3d& m3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m3) : false; } bool Uniform::set( const osg::Matrixd& m4 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m4) : false; } bool Uniform::set( const osg::Matrix2x3d& m2x3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m2x3) : false; } bool Uniform::set( const osg::Matrix2x4d& m2x4 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m2x4) : false; } bool Uniform::set( const osg::Matrix3x2d& m3x2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m3x2) : false; } bool Uniform::set( const osg::Matrix3x4d& m3x4 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m3x4) : false; } bool Uniform::set( const osg::Matrix4x2d& m4x2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m4x2) : false; } bool Uniform::set( const osg::Matrix4x3d& m4x3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,m4x3) : false; } bool Uniform::set( int i ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,i) : false; } bool Uniform::set( int i0, int i1 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,i0,i1) : false; } bool Uniform::set( int i0, int i1, int i2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,i0,i1,i2) : false; } bool Uniform::set( int i0, int i1, int i2, int i3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,i0,i1,i2,i3) : false; } bool Uniform::set( unsigned int ui ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,ui) : false; } bool Uniform::set( unsigned int ui0, unsigned int ui1 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,ui0,ui1) : false; } bool Uniform::set( unsigned int ui0, unsigned int ui1, unsigned int ui2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,ui0,ui1,ui2) : false; } bool Uniform::set( unsigned int ui0, unsigned int ui1, unsigned int ui2, unsigned int ui3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,ui0,ui1,ui2,ui3) : false; } bool Uniform::set( bool b ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,b) : false; } bool Uniform::set( bool b0, bool b1 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,b0,b1) : false; } bool Uniform::set( bool b0, bool b1, bool b2 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,b0,b1,b2) : false; } bool Uniform::set( bool b0, bool b1, bool b2, bool b3 ) { if( getNumElements() == 0 ) setNumElements(1); return isScalar() ? setElement(0,b0,b1,b2,b3) : false; } /////////////////////////////////////////////////////////////////////////// // Value query for single-element (ie: non-array) uniforms. bool Uniform::get( float& f ) const { return isScalar() ? getElement(0,f) : false; } bool Uniform::get( osg::Vec2& v2 ) const { return isScalar() ? getElement(0,v2) : false; } bool Uniform::get( osg::Vec3& v3 ) const { return isScalar() ? getElement(0,v3) : false; } bool Uniform::get( osg::Vec4& v4 ) const { return isScalar() ? getElement(0,v4) : false; } bool Uniform::get( osg::Matrix2& m2 ) const { return isScalar() ? getElement(0,m2) : false; } bool Uniform::get( osg::Matrix3& m3 ) const { return isScalar() ? getElement(0,m3) : false; } bool Uniform::get( osg::Matrixf& m4 ) const { return isScalar() ? getElement(0,m4) : false; } bool Uniform::get( osg::Matrix2x3& m2x3 ) const { return isScalar() ? getElement(0,m2x3) : false; } bool Uniform::get( osg::Matrix2x4& m2x4 ) const { return isScalar() ? getElement(0,m2x4) : false; } bool Uniform::get( osg::Matrix3x2& m3x2 ) const { return isScalar() ? getElement(0,m3x2) : false; } bool Uniform::get( osg::Matrix3x4& m3x4 ) const { return isScalar() ? getElement(0,m3x4) : false; } bool Uniform::get( osg::Matrix4x2& m4x2 ) const { return isScalar() ? getElement(0,m4x2) : false; } bool Uniform::get( osg::Matrix4x3& m4x3 ) const { return isScalar() ? getElement(0,m4x3) : false; } bool Uniform::get( double& d ) const { return isScalar() ? getElement(0,d) : false; } bool Uniform::get( osg::Vec2d& v2 ) const { return isScalar() ? getElement(0,v2) : false; } bool Uniform::get( osg::Vec3d& v3 ) const { return isScalar() ? getElement(0,v3) : false; } bool Uniform::get( osg::Vec4d& v4 ) const { return isScalar() ? getElement(0,v4) : false; } bool Uniform::get( osg::Matrix2d& m2 ) const { return isScalar() ? getElement(0,m2) : false; } bool Uniform::get( osg::Matrix3d& m3 ) const { return isScalar() ? getElement(0,m3) : false; } bool Uniform::get( osg::Matrixd& m4 ) const { return isScalar() ? getElement(0,m4) : false; } bool Uniform::get( osg::Matrix2x3d& m2x3 ) const { return isScalar() ? getElement(0,m2x3) : false; } bool Uniform::get( osg::Matrix2x4d& m2x4 ) const { return isScalar() ? getElement(0,m2x4) : false; } bool Uniform::get( osg::Matrix3x2d& m3x2 ) const { return isScalar() ? getElement(0,m3x2) : false; } bool Uniform::get( osg::Matrix3x4d& m3x4 ) const { return isScalar() ? getElement(0,m3x4) : false; } bool Uniform::get( osg::Matrix4x2d& m4x2 ) const { return isScalar() ? getElement(0,m4x2) : false; } bool Uniform::get( osg::Matrix4x3d& m4x3 ) const { return isScalar() ? getElement(0,m4x3) : false; } bool Uniform::get( int& i ) const { return isScalar() ? getElement(0,i) : false; } bool Uniform::get( int& i0, int& i1 ) const { return isScalar() ? getElement(0,i0,i1) : false; } bool Uniform::get( int& i0, int& i1, int& i2 ) const { return isScalar() ? getElement(0,i0,i1,i2) : false; } bool Uniform::get( int& i0, int& i1, int& i2, int& i3 ) const { return isScalar() ? getElement(0,i0,i1,i2,i3) : false; } bool Uniform::get( unsigned int& ui ) const { return isScalar() ? getElement(0,ui) : false; } bool Uniform::get( unsigned int& ui0, unsigned int& ui1 ) const { return isScalar() ? getElement(0,ui0,ui1) : false; } bool Uniform::get( unsigned int& ui0, unsigned int& ui1, unsigned int& ui2 ) const { return isScalar() ? getElement(0,ui0,ui1,ui2) : false; } bool Uniform::get( unsigned int& ui0, unsigned int& ui1, unsigned int& ui2, unsigned int& ui3 ) const { return isScalar() ? getElement(0,ui0,ui1,ui2,ui3) : false; } bool Uniform::get( bool& b ) const { return isScalar() ? getElement(0,b) : false; } bool Uniform::get( bool& b0, bool& b1 ) const { return isScalar() ? getElement(0,b0,b1) : false; } bool Uniform::get( bool& b0, bool& b1, bool& b2 ) const { return isScalar() ? getElement(0,b0,b1,b2) : false; } bool Uniform::get( bool& b0, bool& b1, bool& b2, bool& b3 ) const { return isScalar() ? getElement(0,b0,b1,b2,b3) : false; } /////////////////////////////////////////////////////////////////////////// // Value assignment for array uniforms. bool Uniform::setElement( unsigned int index, float f ) { if( index>=getNumElements() || !isCompatibleType(FLOAT) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_floatArray)[j] = f; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Vec2& v2 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_floatArray)[j] = v2.x(); (*_floatArray)[j+1] = v2.y(); dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Vec3& v3 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_floatArray)[j] = v3.x(); (*_floatArray)[j+1] = v3.y(); (*_floatArray)[j+2] = v3.z(); dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Vec4& v4 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_floatArray)[j] = v4.x(); (*_floatArray)[j+1] = v4.y(); (*_floatArray)[j+2] = v4.z(); (*_floatArray)[j+3] = v4.w(); dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix2& m2 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 4; ++i ) (*_floatArray)[j+i] = m2[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix3& m3 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 9; ++i ) (*_floatArray)[j+i] = m3[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrixf& m4 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); const Matrixf::value_type* p = m4.ptr(); for( int i = 0; i < 16; ++i ) (*_floatArray)[j+i] = p[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix2x3& m2x3 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT2x3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 6; ++i ) (*_floatArray)[j+i] = m2x3[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix2x4& m2x4 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT2x4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 8; ++i ) (*_floatArray)[j+i] = m2x4[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix3x2& m3x2 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT3x2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 6; ++i ) (*_floatArray)[j+i] = m3x2[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix3x4& m3x4 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT3x4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 12; ++i ) (*_floatArray)[j+i] = m3x4[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix4x2& m4x2 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT4x2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 8; ++i ) (*_floatArray)[j+i] = m4x2[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix4x3& m4x3 ) { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT4x3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 12; ++i ) (*_floatArray)[j+i] = m4x3[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, double d ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_doubleArray)[j] = d; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Vec2d& v2 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_doubleArray)[j] = v2.x(); (*_doubleArray)[j+1] = v2.y(); dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Vec3d& v3 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_doubleArray)[j] = v3.x(); (*_doubleArray)[j+1] = v3.y(); (*_doubleArray)[j+2] = v3.z(); dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Vec4d& v4 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_doubleArray)[j] = v4.x(); (*_doubleArray)[j+1] = v4.y(); (*_doubleArray)[j+2] = v4.z(); (*_doubleArray)[j+3] = v4.w(); dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix2d& m2 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 4; ++i ) (*_doubleArray)[j+i] = m2[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix3d& m3 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 9; ++i ) (*_doubleArray)[j+i] = m3[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrixd& m4 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT4, FLOAT_MAT4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); if (_type == DOUBLE_MAT4) { const Matrixd::value_type* p = m4.ptr(); for( int i = 0; i < 16; ++i ) (*_doubleArray)[j+i] = p[i]; } else //if (_type == FLOAT_MAT4) for backward compatibility only { const Matrixd::value_type* p = m4.ptr(); for( int i = 0; i < 16; ++i ) (*_floatArray)[j+i] = static_cast<float>(p[i]); } dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix2x3d& m2x3 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT2x3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 6; ++i ) (*_doubleArray)[j+i] = m2x3[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix2x4d& m2x4 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT2x4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 8; ++i ) (*_doubleArray)[j+i] = m2x4[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix3x2d& m3x2 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT3x2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 6; ++i ) (*_doubleArray)[j+i] = m3x2[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix3x4d& m3x4 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT3x4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 12; ++i ) (*_doubleArray)[j+i] = m3x4[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix4x2d& m4x2 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT4x2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 8; ++i ) (*_doubleArray)[j+i] = m4x2[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, const osg::Matrix4x3d& m4x3 ) { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT4x3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); for( int i = 0; i < 12; ++i ) (*_doubleArray)[j+i] = m4x3[i]; dirty(); return true; } bool Uniform::setElement( unsigned int index, int i ) { if( index>=getNumElements() || !isCompatibleType(INT) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_intArray)[j] = i; dirty(); return true; } bool Uniform::setElement( unsigned int index, int i0, int i1 ) { if( index>=getNumElements() || !isCompatibleType(INT_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_intArray)[j] = i0; (*_intArray)[j+1] = i1; dirty(); return true; } bool Uniform::setElement( unsigned int index, int i0, int i1, int i2 ) { if( index>=getNumElements() || !isCompatibleType(INT_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_intArray)[j] = i0; (*_intArray)[j+1] = i1; (*_intArray)[j+2] = i2; dirty(); return true; } bool Uniform::setElement( unsigned int index, int i0, int i1, int i2, int i3 ) { if( index>=getNumElements() || !isCompatibleType(INT_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_intArray)[j] = i0; (*_intArray)[j+1] = i1; (*_intArray)[j+2] = i2; (*_intArray)[j+3] = i3; dirty(); return true; } bool Uniform::setElement( unsigned int index, unsigned int ui ) { if( index>=getNumElements() || !isCompatibleType(UNSIGNED_INT) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_uintArray)[j] = ui; dirty(); return true; } bool Uniform::setElement( unsigned int index, unsigned int ui0, unsigned int ui1 ) { if( index>=getNumElements() || !isCompatibleType(UNSIGNED_INT_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_uintArray)[j] = ui0; (*_uintArray)[j+1] = ui1; dirty(); return true; } bool Uniform::setElement( unsigned int index, unsigned int ui0, unsigned int ui1, unsigned int ui2 ) { if( index>=getNumElements() || !isCompatibleType(UNSIGNED_INT_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_uintArray)[j] = ui0; (*_uintArray)[j+1] = ui1; (*_uintArray)[j+2] = ui2; dirty(); return true; } bool Uniform::setElement( unsigned int index, unsigned int ui0, unsigned int ui1, unsigned int ui2, unsigned int ui3 ) { if( index>=getNumElements() || !isCompatibleType(UNSIGNED_INT_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_uintArray)[j] = ui0; (*_uintArray)[j+1] = ui1; (*_uintArray)[j+2] = ui2; (*_uintArray)[j+3] = ui3; dirty(); return true; } bool Uniform::setElement( unsigned int index, bool b ) { if( index>=getNumElements() || !isCompatibleType(BOOL) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_intArray)[j] = b; dirty(); return true; } bool Uniform::setElement( unsigned int index, bool b0, bool b1 ) { if( index>=getNumElements() || !isCompatibleType(BOOL_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_intArray)[j] = b0; (*_intArray)[j+1] = b1; dirty(); return true; } bool Uniform::setElement( unsigned int index, bool b0, bool b1, bool b2 ) { if( index>=getNumElements() || !isCompatibleType(BOOL_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_intArray)[j] = b0; (*_intArray)[j+1] = b1; (*_intArray)[j+2] = b2; dirty(); return true; } bool Uniform::setElement( unsigned int index, bool b0, bool b1, bool b2, bool b3 ) { if( index>=getNumElements() || !isCompatibleType(BOOL_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); (*_intArray)[j] = b0; (*_intArray)[j+1] = b1; (*_intArray)[j+2] = b2; (*_intArray)[j+3] = b3; dirty(); return true; } /////////////////////////////////////////////////////////////////////////// // Value query for array uniforms. bool Uniform::getElement( unsigned int index, float& f ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT) ) return false; unsigned int j = index * getTypeNumComponents(getType()); f = (*_floatArray)[j]; return true; } bool Uniform::getElement( unsigned int index, osg::Vec2& v2 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); v2.x() = (*_floatArray)[j]; v2.y() = (*_floatArray)[j+1]; return true; } bool Uniform::getElement( unsigned int index, osg::Vec3& v3 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); v3.x() = (*_floatArray)[j]; v3.y() = (*_floatArray)[j+1]; v3.z() = (*_floatArray)[j+2]; return true; } bool Uniform::getElement( unsigned int index, osg::Vec4& v4 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); v4.x() = (*_floatArray)[j]; v4.y() = (*_floatArray)[j+1]; v4.z() = (*_floatArray)[j+2]; v4.w() = (*_floatArray)[j+3]; return true; } bool Uniform::getElement( unsigned int index, osg::Matrix2& m2 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m2.Matrix2::base_class::set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix3& m3 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m3.Matrix3::base_class::set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrixf& m4 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m4.set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix2x3& m2x3 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT2x3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m2x3.Matrix2x3::base_class::set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix2x4& m2x4 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT2x4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m2x4.Matrix2x4::base_class::set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix3x2& m3x2 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT3x2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m3x2.Matrix3x2::base_class::set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix3x4& m3x4 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT3x4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m3x4.Matrix3x4::base_class::set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix4x2& m4x2 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT4x2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m4x2.Matrix4x2::base_class::set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix4x3& m4x3 ) const { if( index>=getNumElements() || !isCompatibleType(FLOAT_MAT4x3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m4x3.Matrix4x3::base_class::set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, double& d ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE) ) return false; unsigned int j = index * getTypeNumComponents(getType()); d = (*_doubleArray)[j]; return true; } bool Uniform::getElement( unsigned int index, osg::Vec2d& v2 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); v2.x() = (*_doubleArray)[j]; v2.y() = (*_doubleArray)[j+1]; return true; } bool Uniform::getElement( unsigned int index, osg::Vec3d& v3 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); v3.x() = (*_doubleArray)[j]; v3.y() = (*_doubleArray)[j+1]; v3.z() = (*_doubleArray)[j+2]; return true; } bool Uniform::getElement( unsigned int index, osg::Vec4d& v4 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); v4.x() = (*_doubleArray)[j]; v4.y() = (*_doubleArray)[j+1]; v4.z() = (*_doubleArray)[j+2]; v4.w() = (*_doubleArray)[j+3]; return true; } bool Uniform::getElement( unsigned int index, osg::Matrix2d& m2 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m2.Matrix2d::base_class::set( &((*_doubleArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix3d& m3 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m3.Matrix3d::base_class::set( &((*_doubleArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrixd& m4 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT4, FLOAT_MAT4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); if (_type == DOUBLE_MAT4) m4.set( &((*_doubleArray)[j]) ); else // if (_type == FLOAT_MAT4) for backward compatibility only m4.set( &((*_floatArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix2x3d& m2x3 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT2x3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m2x3.Matrix2x3d::base_class::set( &((*_doubleArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix2x4d& m2x4 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT2x4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m2x4.Matrix2x4d::base_class::set( &((*_doubleArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix3x2d& m3x2 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT3x2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m3x2.Matrix3x2d::base_class::set( &((*_doubleArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix3x4d& m3x4 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT3x4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m3x4.Matrix3x4d::base_class::set( &((*_doubleArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix4x2d& m4x2 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT4x2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m4x2.Matrix4x2d::base_class::set( &((*_doubleArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, osg::Matrix4x3d& m4x3 ) const { if( index>=getNumElements() || !isCompatibleType(DOUBLE_MAT4x3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); m4x3.Matrix4x3d::base_class::set( &((*_doubleArray)[j]) ); return true; } bool Uniform::getElement( unsigned int index, int& i ) const { if( index>=getNumElements() || !isCompatibleType(INT) ) return false; unsigned int j = index * getTypeNumComponents(getType()); i = (*_intArray)[j]; return true; } bool Uniform::getElement( unsigned int index, int& i0, int& i1 ) const { if( index>=getNumElements() || !isCompatibleType(INT_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); i0 = (*_intArray)[j]; i1 = (*_intArray)[j+1]; return true; } bool Uniform::getElement( unsigned int index, int& i0, int& i1, int& i2 ) const { if( index>=getNumElements() || !isCompatibleType(INT_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); i0 = (*_intArray)[j]; i1 = (*_intArray)[j+1]; i2 = (*_intArray)[j+2]; return true; } bool Uniform::getElement( unsigned int index, int& i0, int& i1, int& i2, int& i3 ) const { if( index>=getNumElements() || !isCompatibleType(INT_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); i0 = (*_intArray)[j]; i1 = (*_intArray)[j+1]; i2 = (*_intArray)[j+2]; i3 = (*_intArray)[j+3]; return true; } bool Uniform::getElement( unsigned int index, unsigned int& ui ) const { if( index>=getNumElements() || !isCompatibleType(UNSIGNED_INT) ) return false; unsigned int j = index * getTypeNumComponents(getType()); ui = (*_uintArray)[j]; return true; } bool Uniform::getElement( unsigned int index, unsigned int& ui0, unsigned int& ui1 ) const { if( index>=getNumElements() || !isCompatibleType(UNSIGNED_INT_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); ui0 = (*_uintArray)[j]; ui1 = (*_uintArray)[j+1]; return true; } bool Uniform::getElement( unsigned int index, unsigned int& ui0, unsigned int& ui1, unsigned int& ui2 ) const { if( index>=getNumElements() || !isCompatibleType(UNSIGNED_INT_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); ui0 = (*_uintArray)[j]; ui1 = (*_uintArray)[j+1]; ui2 = (*_uintArray)[j+2]; return true; } bool Uniform::getElement( unsigned int index, unsigned int& ui0, unsigned int& ui1, unsigned int& ui2, unsigned int& ui3 ) const { if( index>=getNumElements() || !isCompatibleType(UNSIGNED_INT_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); ui0 = (*_uintArray)[j]; ui1 = (*_uintArray)[j+1]; ui2 = (*_uintArray)[j+2]; ui3 = (*_uintArray)[j+3]; return true; } bool Uniform::getElement( unsigned int index, bool& b ) const { if( index>=getNumElements() || !isCompatibleType(BOOL) ) return false; unsigned int j = index * getTypeNumComponents(getType()); b = ((*_intArray)[j] != 0); return true; } bool Uniform::getElement( unsigned int index, bool& b0, bool& b1 ) const { if( index>=getNumElements() || !isCompatibleType(BOOL_VEC2) ) return false; unsigned int j = index * getTypeNumComponents(getType()); b0 = ((*_intArray)[j] != 0); b1 = ((*_intArray)[j+1] != 0); return true; } bool Uniform::getElement( unsigned int index, bool& b0, bool& b1, bool& b2 ) const { if( index>=getNumElements() || !isCompatibleType(BOOL_VEC3) ) return false; unsigned int j = index * getTypeNumComponents(getType()); b0 = ((*_intArray)[j] != 0); b1 = ((*_intArray)[j+1] != 0); b2 = ((*_intArray)[j+2] != 0); return true; } bool Uniform::getElement( unsigned int index, bool& b0, bool& b1, bool& b2, bool& b3 ) const { if( index>=getNumElements() || !isCompatibleType(BOOL_VEC4) ) return false; unsigned int j = index * getTypeNumComponents(getType()); b0 = ((*_intArray)[j] != 0); b1 = ((*_intArray)[j+1] != 0); b2 = ((*_intArray)[j+2] != 0); b3 = ((*_intArray)[j+3] != 0); return true; } unsigned int Uniform::getNameID() const { return _nameID; } /////////////////////////////////////////////////////////////////////////// void Uniform::apply(const GL2Extensions* ext, GLint location) const { // OSG_NOTICE << "uniform at "<<location<<" "<<_name<< std::endl; GLsizei num = getNumElements(); if( num < 1 ) return; switch( getGlApiType(getType()) ) { case FLOAT: if( _floatArray.valid() ) ext->glUniform1fv( location, num, &_floatArray->front() ); break; case FLOAT_VEC2: if( _floatArray.valid() ) ext->glUniform2fv( location, num, &_floatArray->front() ); break; case FLOAT_VEC3: if( _floatArray.valid() ) ext->glUniform3fv( location, num, &_floatArray->front() ); break; case FLOAT_VEC4: if( _floatArray.valid() ) ext->glUniform4fv( location, num, &_floatArray->front() ); break; case FLOAT_MAT2: if( _floatArray.valid() ) ext->glUniformMatrix2fv( location, num, GL_FALSE, &_floatArray->front() ); break; case FLOAT_MAT3: if( _floatArray.valid() ) ext->glUniformMatrix3fv( location, num, GL_FALSE, &_floatArray->front() ); break; case FLOAT_MAT4: if( _floatArray.valid() ) ext->glUniformMatrix4fv( location, num, GL_FALSE, &_floatArray->front() ); break; case FLOAT_MAT2x3: if( _floatArray.valid() ) ext->glUniformMatrix2x3fv( location, num, GL_FALSE, &_floatArray->front() ); break; case FLOAT_MAT2x4: if( _floatArray.valid() ) ext->glUniformMatrix2x4fv( location, num, GL_FALSE, &_floatArray->front() ); break; case FLOAT_MAT3x2: if( _floatArray.valid() ) ext->glUniformMatrix3x2fv( location, num, GL_FALSE, &_floatArray->front() ); break; case FLOAT_MAT3x4: if( _floatArray.valid() ) ext->glUniformMatrix3x4fv( location, num, GL_FALSE, &_floatArray->front() ); break; case FLOAT_MAT4x2: if( _floatArray.valid() ) ext->glUniformMatrix4x2fv( location, num, GL_FALSE, &_floatArray->front() ); break; case FLOAT_MAT4x3: if( _floatArray.valid() ) ext->glUniformMatrix4x3fv( location, num, GL_FALSE, &_floatArray->front() ); break; case DOUBLE: if( _doubleArray.valid() ) ext->glUniform1dv( location, num, &_doubleArray->front() ); break; case DOUBLE_VEC2: if( _doubleArray.valid() ) ext->glUniform2dv( location, num, &_doubleArray->front() ); break; case DOUBLE_VEC3: if( _doubleArray.valid() ) ext->glUniform3dv( location, num, &_doubleArray->front() ); break; case DOUBLE_VEC4: if( _doubleArray.valid() ) ext->glUniform4dv( location, num, &_doubleArray->front() ); break; case DOUBLE_MAT2: if( _doubleArray.valid() ) ext->glUniformMatrix2dv( location, num, GL_FALSE, &_doubleArray->front() ); break; case DOUBLE_MAT3: if( _doubleArray.valid() ) ext->glUniformMatrix3dv( location, num, GL_FALSE, &_doubleArray->front() ); break; case DOUBLE_MAT4: if( _doubleArray.valid() ) ext->glUniformMatrix4dv( location, num, GL_FALSE, &_doubleArray->front() ); break; case DOUBLE_MAT2x3: if( _doubleArray.valid() ) ext->glUniformMatrix2x3dv( location, num, GL_FALSE, &_doubleArray->front() ); break; case DOUBLE_MAT2x4: if( _doubleArray.valid() ) ext->glUniformMatrix2x4dv( location, num, GL_FALSE, &_doubleArray->front() ); break; case DOUBLE_MAT3x2: if( _doubleArray.valid() ) ext->glUniformMatrix3x2dv( location, num, GL_FALSE, &_doubleArray->front() ); break; case DOUBLE_MAT3x4: if( _doubleArray.valid() ) ext->glUniformMatrix3x4dv( location, num, GL_FALSE, &_doubleArray->front() ); break; case DOUBLE_MAT4x2: if( _doubleArray.valid() ) ext->glUniformMatrix4x2dv( location, num, GL_FALSE, &_doubleArray->front() ); break; case DOUBLE_MAT4x3: if( _doubleArray.valid() ) ext->glUniformMatrix4x3dv( location, num, GL_FALSE, &_doubleArray->front() ); break; case INT: if( _intArray.valid() ) ext->glUniform1iv( location, num, &_intArray->front() ); break; case INT_VEC2: if( _intArray.valid() ) ext->glUniform2iv( location, num, &_intArray->front() ); break; case INT_VEC3: if( _intArray.valid() ) ext->glUniform3iv( location, num, &_intArray->front() ); break; case INT_VEC4: if( _intArray.valid() ) ext->glUniform4iv( location, num, &_intArray->front() ); break; case UNSIGNED_INT: if( _uintArray.valid() ) ext->glUniform1uiv( location, num, &_uintArray->front() ); break; case UNSIGNED_INT_VEC2: if( _uintArray.valid() ) ext->glUniform2uiv( location, num, &_uintArray->front() ); break; case UNSIGNED_INT_VEC3: if( _uintArray.valid() ) ext->glUniform3uiv( location, num, &_uintArray->front() ); break; case UNSIGNED_INT_VEC4: if( _uintArray.valid() ) ext->glUniform4uiv( location, num, &_uintArray->front() ); break; default: OSG_FATAL << "how got here? " __FILE__ ":" << __LINE__ << std::endl; break; } } void Uniform::setUpdateCallback(Callback* uc) { OSG_INFO<<"Uniform::Setting Update callbacks"<<std::endl; if (_updateCallback==uc) return; int delta = 0; if (_updateCallback.valid()) --delta; if (uc) ++delta; _updateCallback = uc; if (delta!=0) { OSG_INFO<<"Going to set Uniform parents"<<std::endl; for(ParentList::iterator itr=_parents.begin(); itr!=_parents.end(); ++itr) { OSG_INFO<<" setting Uniform parent"<<std::endl; (*itr)->setNumChildrenRequiringUpdateTraversal((*itr)->getNumChildrenRequiringUpdateTraversal()+delta); } } } void Uniform::setEventCallback(Callback* ec) { OSG_INFO<<"Uniform::Setting Event callbacks"<<std::endl; if (_eventCallback==ec) return; int delta = 0; if (_eventCallback.valid()) --delta; if (ec) ++delta; _eventCallback = ec; if (delta!=0) { for(ParentList::iterator itr=_parents.begin(); itr!=_parents.end(); ++itr) { (*itr)->setNumChildrenRequiringEventTraversal((*itr)->getNumChildrenRequiringEventTraversal()+delta); } } }
lgpl-2.1
liuwenf/moose
python/MooseDocs/commands/build.py
9630
#pylint: disable=missing-docstring #################################################################################################### # DO NOT MODIFY THIS HEADER # # MOOSE - Multiphysics Object Oriented Simulation Environment # # # # (c) 2010 Battelle Energy Alliance, LLC # # ALL RIGHTS RESERVED # # # # Prepared by Battelle Energy Alliance, LLC # # Under Contract No. DE-AC07-05ID14517 # # With the U. S. Department of Energy # # # # See COPYRIGHT for full restrictions # #################################################################################################### #pylint: enable=missing-docstring import os import multiprocessing import re import shutil import subprocess import logging import livereload import mooseutils import MooseDocs from MooseDocs.MooseMarkdown import MooseMarkdown from MooseDocs import common LOG = logging.getLogger(__name__) def build_options(parser): """ Command-line options for build command. """ parser.add_argument('--config-file', type=str, default='website.yml', help="The configuration file to use for building the documentation using " "MOOSE. (Default: %(default)s)") parser.add_argument('--content', type=str, default='content.yml', help="The YAML file containing the locations containing the markdown " "files (Default: %(default)s). If the file doesn't exists the default " "is {'default':{'base':'docs/content', 'include':'docs/content/*'}}") if MooseDocs.ROOT_DIR == MooseDocs.MOOSE_DIR: parser.add_argument('--init', action='store_true', help="Initialize and/or update the " "large media submodule if needed.") parser.add_argument('--dump', action='store_true', help="Display the website file tree that will be created without " "performing a build.") parser.add_argument('--clean', action='store_true', help="Clean the 'site-dir', this happens by default when the '--serve' " "command is used.") parser.add_argument('--num-threads', '-j', type=int, default=multiprocessing.cpu_count(), help="Specify the number of threads to build pages with.") parser.add_argument('--template', type=str, default='website.html', help="The template html file to utilize (Default: %(default)s).") parser.add_argument('--host', default='127.0.0.1', type=str, help="The local host location for live web server (default: %(default)s).") parser.add_argument('--port', default='8000', type=str, help="The local host port for live web server (default: %(default)s).") parser.add_argument('--site-dir', type=str, default=os.path.join(MooseDocs.ROOT_DIR, 'site'), help="The location to build the website content (Default: %(default)s).") parser.add_argument('--serve', action='store_true', help="Serve the presentation with live reloading, the 'site_dir' is " "ignored for this case.") parser.add_argument('--no-livereload', action='store_true', help="When --serve is used this flag disables the live reloading.") def submodule_status(): """ Return the status of each of the git submodule. """ out = dict() result = subprocess.check_output(['git', 'submodule', 'status'], cwd=MooseDocs.MOOSE_DIR) regex = re.compile(r'(?P<status>[\s\-\+U])(?P<sha1>[a-f0-9]{40})\s(?P<name>.*?)\s') for match in regex.finditer(result): out[match.group('name')] = match.group('status') return out class WebsiteBuilder(common.Builder): """ Builder object for creating websites. """ def __init__(self, content=None, **kwargs): super(WebsiteBuilder, self).__init__(**kwargs) if (content is None) or (not os.path.isfile(content)): LOG.info("Using default content directory configuration " "(i.e., --content does not include a valid filename).") content = dict(default=dict(base=os.path.join(os.getcwd(), 'content'), include=[os.path.join(os.getcwd(), 'content', '*')])) else: content = MooseDocs.yaml_load(content) self._content = content def buildNodes(self): return common.moose_docs_file_tree(self._content) class MooseDocsWatcher(livereload.watcher.Watcher): """ A livereload watcher for MooseDocs that rebuilds the entire content if markdown files are added or removed. """ def __init__(self, builder, num_threads, *args, **kwargs): super(MooseDocsWatcher, self).__init__(*args, **kwargs) self._builder = builder self._num_threads = num_threads self.init() def init(self): """ Define the content to watch. """ self._count = self._builder.count() for page in self._builder: self.watch(page.filename, lambda p=page: self._builder.buildPage(p), delay=2) def reset(self): """ Perform a complete build and establish the items to watch. """ # Clear the current tasks self._tasks = dict() self.filepath = None # Re-build LOG.info('START: Complete re-build of markdown content.') self._builder.build(num_threads=self._num_threads) self.init() LOG.info('FINISH: Complete re-build of markdown content.') def examine(self): """ Override the default function to investigate if the number of markdown files changed. """ self._builder.init() if self._count != self._builder.count(): self.reset() else: super(MooseDocsWatcher, self).examine() return self.filepath, None def build(config_file=None, site_dir=None, num_threads=None, no_livereload=False, content=None, dump=False, clean=False, serve=False, host=None, port=None, template=None, init=False, **template_args): """ The main build command. """ if serve: clean = True site_dir = os.path.abspath(os.path.join(MooseDocs.TEMP_DIR, 'site')) # Clean/create site directory if clean and os.path.exists(site_dir): LOG.info('Cleaning build directory: %s', site_dir) shutil.rmtree(site_dir) # Create the "temp" directory if not os.path.exists(site_dir): os.makedirs(site_dir) # Check submodule for large_media if MooseDocs.ROOT_DIR == MooseDocs.MOOSE_DIR: status = submodule_status() if status['docs/content/media/large_media'] == '-': if init: subprocess.call(['git', 'submodule', 'update', '--init', 'docs/content/media/large_media'], cwd=MooseDocs.MOOSE_DIR) else: LOG.warning("The 'large_media' submodule for storing images above 1MB is not " "initialized, thus some images will not be visible within the " "generated website. Run the build command with the --init flag to " "initialize the submodule.") # Check media files size if MooseDocs.ROOT_DIR == MooseDocs.MOOSE_DIR: media = os.path.join(MooseDocs.MOOSE_DIR, 'docs', 'content', 'media') ignore = set() for base, _, files in os.walk(os.path.join(media, 'large_media')): for name in files: ignore.add(os.path.join(base, name)) large = mooseutils.check_file_size(base=media, ignore=ignore) if large: msg = "Media files above the limit of 1 MB detected, these files should be stored in " \ "large media repository (docs/content/media/large_media):" for name, size in large: msg += '\n{}{} ({:.2f} MB)'.format(' '*4, name, size) LOG.error(msg) # Create the markdown parser config = MooseDocs.load_config(config_file, template=template, template_args=template_args) parser = MooseMarkdown(config) # Create the builder object and build the pages builder = WebsiteBuilder(parser=parser, site_dir=site_dir, content=content) builder.init() if dump: print builder return None builder.build(num_threads=num_threads) # Serve if serve: if not no_livereload: server = livereload.Server(watcher=MooseDocsWatcher(builder, num_threads)) else: server = livereload.Server() server.serve(root=site_dir, host=host, port=port, restart_delay=0) return 0
lgpl-2.1
radekp/qt
doc/src/snippets/audio/main.cpp
3499
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include <QAudioOutput> #include <QAudioDeviceInfo> #include <QAudioInput> class Window2 : public QWidget { Q_OBJECT public slots: //![0] void stateChanged(QAudio::State newState) { switch(newState) { case QAudio::StopState: if (input->error() != QAudio::NoError) { // Error handling } else { } break; //![0] default: ; } } private: QAudioInput *input; }; class Window : public QWidget { Q_OBJECT public: Window() { output = new QAudioOutput; connect(output, SIGNAL(stateChanged(QAudio::State)), this, SLOT(stateChanged(QAudio::State))); } private: void setupFormat() { //![1] QAudioFormat format; format.setFrequency(44100); //![1] format.setChannels(2); format.setSampleSize(16); format.setCodec("audio/pcm"); format.setByteOrder(QAudioFormat::LittleEndian); //![2] format.setSampleType(QAudioFormat::SignedInt); QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice()); if (!info.isFormatSupported(format)) format = info.nearestFormat(format); //![2] } public slots: //![3] void stateChanged(QAudio::State newState) { switch (newState) { case QAudio::StopState: if (output->error() != QAudio::NoError) { // Do your error handlin } else { // Normal stop } break; //![3] // Handle case QAudio::ActiveState: // Handle active state... break; break; default: ; } } private: QAudioOutput *output; }; int main(int argv, char **args) { QApplication app(argv, args); Window window; window.show(); return app.exec(); } #include "main.moc"
lgpl-2.1
pquiring/jfcraft
src/base/jfcraft/move/MoveHostile.java
1193
package jfcraft.move; /** Moves a hostile (zombie, skeleton, etc.) * * @author pquiring */ import jfcraft.data.*; import jfcraft.entity.*; import static jfcraft.entity.EntityBase.*; public class MoveHostile implements MoveBase { public void move(EntityBase entity) { CreatureBase creature = (CreatureBase)entity; if (entity.target == null) { //getTarget(); //test! } else { if (entity.target.health == 0 || entity.target.offline) { entity.target = null; } } boolean moved; boolean wasmoving = entity.mode != MODE_IDLE; if (Static.debugRotate) { //test rotate in a spot entity.ang.y += 1.0f; if (entity.ang.y > 180f) { entity.ang.y = -180f; } entity.ang.x += 1.0f; if (entity.ang.x > 45.0f) { entity.ang.x = -45.0f; } entity.mode = MODE_WALK; moved = true; } else { if (entity.target != null) { creature.moveToTarget(); } else { creature.randomWalking(); } moved = creature.moveEntity(); } if (entity.target != null || moved || wasmoving) Static.server.broadcastEntityMove(entity, false); } }
lgpl-2.1
M4thG33k/M4thThings1_8
src/main/java/com/m4thg33k/m4ththings/packets/PacketHandlerNBT.java
544
package com.m4thg33k.m4ththings.packets; import com.m4thg33k.m4ththings.M4thThings; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; public class PacketHandlerNBT implements IMessageHandler<PacketNBT, IMessage> { @Override public IMessage onMessage(PacketNBT message, MessageContext ctx) { M4thThings.proxy.handleNBTPacket(message); return null; } }
lgpl-2.1
davidsiaw/cappuccino-docs
category_c_p_combo_box_07_c_p_combo_box_delegate_08.js
602
var category_c_p_combo_box_07_c_p_combo_box_delegate_08 = [ [ "comboBoxSelectionDidChange:", "category_c_p_combo_box_07_c_p_combo_box_delegate_08.html#a0ac88c2e41b881ef907c694055e76ff4", null ], [ "comboBoxSelectionIsChanging:", "category_c_p_combo_box_07_c_p_combo_box_delegate_08.html#a4c59a84f133f595dca97fa615af467f9", null ], [ "comboBoxWillDismiss:", "category_c_p_combo_box_07_c_p_combo_box_delegate_08.html#a29d0bb7b0f62c05a0cac61ebb7f08abc", null ], [ "comboBoxWillPopUp:", "category_c_p_combo_box_07_c_p_combo_box_delegate_08.html#a6dc71a6cf8974dd240d38847d9a63b53", null ] ];
lgpl-2.1
joshuaruesweg/WCF
wcfsetup/install/files/lib/system/package/plugin/PagePackageInstallationPlugin.class.php
11638
<?php namespace wcf\system\package\plugin; use wcf\data\package\PackageCache; use wcf\data\page\Page; use wcf\data\page\PageEditor; use wcf\system\devtools\pip\IIdempotentPackageInstallationPlugin; use wcf\system\exception\SystemException; use wcf\system\language\LanguageFactory; use wcf\system\request\RouteHandler; use wcf\system\search\SearchIndexManager; use wcf\system\WCF; use wcf\util\StringUtil; /** * Installs, updates and deletes CMS pages. * * @author Alexander Ebert * @copyright 2001-2017 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Acp\Package\Plugin * @since 3.0 */ class PagePackageInstallationPlugin extends AbstractXMLPackageInstallationPlugin implements IIdempotentPackageInstallationPlugin { /** * @inheritDoc */ public $className = PageEditor::class; /** * page content * @var mixed[] */ protected $content = []; /** * pages objects * @var Page[] */ protected $pages = []; /** * @inheritDoc */ public $tagName = 'page'; /** * @inheritDoc */ protected function handleDelete(array $items) { $sql = "DELETE FROM wcf".WCF_N."_page WHERE identifier = ? AND packageID = ?"; $statement = WCF::getDB()->prepareStatement($sql); WCF::getDB()->beginTransaction(); foreach ($items as $item) { $statement->execute([ $item['attributes']['identifier'], $this->installation->getPackageID() ]); } WCF::getDB()->commitTransaction(); } /** * @inheritDoc */ protected function getElement(\DOMXPath $xpath, array &$elements, \DOMElement $element) { $nodeValue = $element->nodeValue; // read content if ($element->tagName === 'content') { if (!isset($elements['content'])) $elements['content'] = []; $children = []; /** @var \DOMElement $child */ foreach ($xpath->query('child::*', $element) as $child) { $children[$child->tagName] = $child->nodeValue; } $elements[$element->tagName][$element->getAttribute('language')] = $children; } else if ($element->tagName === 'name') { // <name> can occur multiple times using the `language` attribute if (!isset($elements['name'])) $elements['name'] = []; $elements['name'][$element->getAttribute('language')] = $element->nodeValue; } else { $elements[$element->tagName] = $nodeValue; } } /** * @inheritDoc * @throws SystemException */ protected function prepareImport(array $data) { $pageType = $data['elements']['pageType']; if (!empty($data['elements']['content'])) { $content = []; foreach ($data['elements']['content'] as $language => $contentData) { if ($pageType != 'system' && !RouteHandler::isValidCustomUrl($contentData['customURL'])) { throw new SystemException("Invalid custom url for page content '" . $language . "', page identifier '" . $data['attributes']['identifier'] . "'"); } $content[$language] = [ 'content' => (!empty($contentData['content'])) ? StringUtil::trim($contentData['content']) : '', 'customURL' => (!empty($contentData['customURL'])) ? StringUtil::trim($contentData['customURL']) : '', 'metaDescription' => (!empty($contentData['metaDescription'])) ? StringUtil::trim($contentData['metaDescription']) : '', 'metaKeywords' => (!empty($contentData['metaKeywords'])) ? StringUtil::trim($contentData['metaKeywords']) : '', 'title' => (!empty($contentData['title'])) ? StringUtil::trim($contentData['title']) : '' ]; } $data['elements']['content'] = $content; } // pick the display name by choosing the default language, or 'en' or '' (empty string) $defaultLanguageCode = LanguageFactory::getInstance()->getDefaultLanguage()->getFixedLanguageCode(); if (isset($data['elements']['name'][$defaultLanguageCode])) { // use the default language $name = $data['elements']['name'][$defaultLanguageCode]; } else if (isset($data['elements']['name']['en'])) { // use the value for English $name = $data['elements']['name']['en']; } else { // fallback to the display name without/empty language attribute $name = $data['elements']['name']['']; } $parentPageID = null; if (!empty($data['elements']['parent'])) { $sql = "SELECT pageID FROM wcf".WCF_N."_".$this->tableName." WHERE identifier = ?"; $statement = WCF::getDB()->prepareStatement($sql, 1); $statement->execute([$data['elements']['parent']]); $row = $statement->fetchSingleRow(); if ($row === false) { throw new SystemException("Unknown parent page '" . $data['elements']['parent'] . "' for page identifier '" . $data['attributes']['identifier'] . "'"); } $parentPageID = $row['pageID']; } // validate page type $controller = ''; $handler = ''; $controllerCustomURL = ''; $identifier = $data['attributes']['identifier']; $isMultilingual = 0; switch ($pageType) { case 'system': if (empty($data['elements']['controller'])) { throw new SystemException("Missing required element 'controller' for 'system'-type page '{$identifier}'"); } $controller = $data['elements']['controller']; if (!empty($data['elements']['handler'])) { $handler = $data['elements']['handler']; } if (!empty($data['elements']['controllerCustomURL'])) { $controllerCustomURL = $data['elements']['controllerCustomURL']; if ($controllerCustomURL && !RouteHandler::isValidCustomUrl($controllerCustomURL)) { throw new SystemException("Invalid custom url for page identifier '" . $data['attributes']['identifier'] . "'"); } } break; case 'html': case 'text': case 'tpl': if (empty($data['elements']['content'])) { throw new SystemException("Missing required 'content' element(s) for page '{$identifier}'"); } if (count($data['elements']['content']) === 1) { if (!isset($data['elements']['content'][''])) { throw new SystemException("Expected one 'content' element without a 'language' attribute for page '{$identifier}'"); } } else { $isMultilingual = 1; if (isset($data['elements']['content'][''])) { throw new SystemException("Cannot mix 'content' elements with and without 'language' attribute for page '{$identifier}'"); } } break; default: throw new SystemException("Unknown type '{$pageType}' for page '{$identifier}"); break; } // get application package id $applicationPackageID = 1; if ($this->installation->getPackage()->isApplication) { $applicationPackageID = $this->installation->getPackageID(); } if (!empty($data['elements']['application'])) { $application = PackageCache::getInstance()->getPackageByIdentifier($data['elements']['application']); if ($application === null || !$application->isApplication) { throw new SystemException("Unknown application '".$data['elements']['application']."' for page '{$identifier}"); } $applicationPackageID = $application->packageID; } return [ 'pageType' => $pageType, 'content' => (!empty($data['elements']['content'])) ? $data['elements']['content'] : [], 'controller' => $controller, 'handler' => $handler, 'controllerCustomURL' => $controllerCustomURL, 'identifier' => $identifier, 'isMultilingual' => $isMultilingual, 'lastUpdateTime' => TIME_NOW, 'name' => $name, 'originIsSystem' => 1, 'parentPageID' => $parentPageID, 'applicationPackageID' => $applicationPackageID, 'requireObjectID' => (!empty($data['elements']['requireObjectID'])) ? 1 : 0, 'options' => isset($data['elements']['options']) ? $data['elements']['options'] : '', 'permissions' => isset($data['elements']['permissions']) ? $data['elements']['permissions'] : '', 'hasFixedParent' => ($pageType == 'system' && !empty($data['elements']['hasFixedParent'])) ? 1 : 0, 'cssClassName' => isset($data['elements']['cssClassName']) ? $data['elements']['cssClassName'] : '', 'availableDuringOfflineMode' => (!empty($data['elements']['availableDuringOfflineMode'])) ? 1 : 0, 'allowSpidersToIndex' => (!empty($data['elements']['allowSpidersToIndex'])) ? 1 : 0, 'excludeFromLandingPage' => (!empty($data['elements']['excludeFromLandingPage'])) ? 1 : 0 ]; } /** * @inheritDoc */ protected function findExistingItem(array $data) { $sql = "SELECT * FROM wcf".WCF_N."_".$this->tableName." WHERE identifier = ? AND packageID = ?"; $parameters = [ $data['identifier'], $this->installation->getPackageID() ]; return [ 'sql' => $sql, 'parameters' => $parameters ]; } /** * @inheritDoc */ protected function import(array $row, array $data) { // extract content $content = $data['content']; unset($data['content']); /** @var Page $page */ if (!empty($row)) { // allow update of `controller`, `handler` and `excludeFromLandingPage` // only, prevents user modifications form being overwritten if (!empty($data['controller'])) { $page = parent::import($row, [ 'controller' => $data['controller'], 'handler' => $data['handler'], 'options' => $data['options'], 'permissions' => $data['permissions'], 'excludeFromLandingPage' => $data['excludeFromLandingPage'] ]); } else { $baseClass = call_user_func([$this->className, 'getBaseClass']); $page = new $baseClass(null, $row); } } else { // import $page = parent::import($row, $data); } // store content for later import $this->pages[$page->pageID] = $page; $this->content[$page->pageID] = $content; return $page; } /** * @inheritDoc */ protected function postImport() { if (!empty($this->content)) { $sql = "SELECT COUNT(*) AS count FROM wcf".WCF_N."_page_content WHERE pageID = ? AND languageID IS NULL"; $statement = WCF::getDB()->prepareStatement($sql); $sql = "INSERT IGNORE INTO wcf".WCF_N."_page_content (pageID, languageID, title, content, metaDescription, metaKeywords, customURL) VALUES (?, ?, ?, ?, ?, ?, ?)"; $insertStatement = WCF::getDB()->prepareStatement($sql); WCF::getDB()->beginTransaction(); foreach ($this->content as $pageID => $contentData) { foreach ($contentData as $languageCode => $content) { $languageID = null; if ($languageCode != '') { $language = LanguageFactory::getInstance()->getLanguageByCode($languageCode); if ($language === null) continue; $languageID = $language->languageID; } if ($languageID === null) { $statement->execute([$pageID]); if ($statement->fetchColumn()) continue; } $insertStatement->execute([ $pageID, $languageID, $content['title'], $content['content'], $content['metaDescription'], $content['metaKeywords'], $content['customURL'] ]); } } WCF::getDB()->commitTransaction(); // create search index tables SearchIndexManager::getInstance()->createSearchIndices(); // update search index foreach ($this->pages as $pageID => $page) { if ($page->pageType == 'text' || $page->pageType == 'html') { foreach ($page->getPageContents() as $languageID => $pageContent) { SearchIndexManager::getInstance()->set( 'com.woltlab.wcf.page', $pageContent->pageContentID, $pageContent->content, $pageContent->title, 0, null, '', $languageID ?: null ); } } } } } /** * @inheritDoc */ public static function getSyncDependencies() { return ['language']; } }
lgpl-2.1
xpressengine/xe-module-forum
tpl/js/forum_admin.js
5061
/** * @file modules/forum/js/forum_admin.js * @author Arnia (xe_dev@arnia.ro) * @brief forum module admin javascript functions **/ /* function for callback on insert_forum filter */ function completeInsertForum(ret_obj) { var error = ret_obj['error']; var message = ret_obj['message']; var act = ret_obj['act']; var page = ret_obj['page']; var module_srl = ret_obj['module_srl']; alert(message); if(act) { var url = current_url.setQuery('act',act); } else { var url = current_url.setQuery('act','dispForumAdminForumInfo'); } if(module_srl) url = url.setQuery('module_srl',module_srl); if(page) url.setQuery('page',page); location.href = url; } /* function for callback on delete_forum filter */ function completeDeleteForum(ret_obj) { var error = ret_obj['error']; var message = ret_obj['message']; var page = ret_obj['page']; alert(message); var url = current_url.setQuery('act','dispForumAdminContent').setQuery('module_srl',''); if(page) url = url.setQuery('page',page); location.href = url; } /* javascript function used to update category */ function doUpdateCategory(category_srl, mode, message) { if(typeof(message)!='undefined'&&!confirm(message)) return; var fo_obj = xGetElementById('fo_category_info'); fo_obj.category_srl.value = category_srl; fo_obj.mode.value = mode; procFilter(fo_obj, update_category); } /* function for callback on update_category filter */ function completeUpdateCategory(ret_obj) { var error = ret_obj['error']; var message = ret_obj['message']; var module_srl = ret_obj['module_srl']; var page = ret_obj['page']; alert(message); var url = current_url.setQuery('module_srl',module_srl).setQuery('act','dispForumAdminCategoryInfo'); if(page) url.setQuery('page',page); location.href = url; } /* Cart Setup */ function doCartSetup(url) { var module_srl = new Array(); jQuery('#fo_list input[name=cart]:checked').each(function() { module_srl[module_srl.length] = jQuery(this).val(); }); if(module_srl.length<1) return; url += "&module_srls="+module_srl.join(','); popopen(url,'modulesSetup'); } /* List Item setup */ function doInsertItem() { var target_obj = xGetElementById('targetItem'); var display_obj = xGetElementById('displayItem'); if(!target_obj || !display_obj) return; var text = target_obj.options[target_obj.selectedIndex].text; var value = target_obj.options[target_obj.selectedIndex].value; for(var i=0;i<display_obj.options.length;i++) if(display_obj.options[i].value == value) return; var obj = new Option(text, value, true, true); display_obj.options[display_obj.options.length] = obj; } function doDeleteItem() { var sel_obj = xGetElementById('displayItem'); var idx = sel_obj.selectedIndex; if(idx<0 || sel_obj.options.length<2) return; sel_obj.remove(idx); sel_obj.selectedIndex = idx-1; } function doMoveUpItem() { var sel_obj = xGetElementById('displayItem'); var idx = sel_obj.selectedIndex; if(idx<1 || !idx) return; var text = sel_obj.options[idx].text; var value = sel_obj.options[idx].value; sel_obj.options[idx].text = sel_obj.options[idx-1].text; sel_obj.options[idx].value = sel_obj.options[idx-1].value; sel_obj.options[idx-1].text = text; sel_obj.options[idx-1].value = value; sel_obj.selectedIndex = idx-1; } function doMoveDownItem() { var sel_obj = xGetElementById('displayItem'); var idx = sel_obj.selectedIndex; if(idx>=sel_obj.options.length-1) return; var text = sel_obj.options[idx].text; var value = sel_obj.options[idx].value; sel_obj.options[idx].text = sel_obj.options[idx+1].text; sel_obj.options[idx].value = sel_obj.options[idx+1].value; sel_obj.options[idx+1].text = text; sel_obj.options[idx+1].value = value; sel_obj.selectedIndex = idx+1; } function doSaveListConfig(module_srl) { if(!module_srl) return; var sel_obj = xGetElementById('displayItem'); var idx = sel_obj.selectedIndex; var list = new Array(); for(var i=0;i<sel_obj.options.length;i++) list[list.length] = sel_obj.options[i].value; if(list.length<1) return; var params = new Array(); params['module_srl'] = module_srl; params['list'] = list.join(','); var response_tags = new Array('error','message'); exec_xml('forum','procForumAdminInsertListConfig', params, function() { location.reload(); }); } /* function to change category on admin */ function doChangeCategory(fo_obj) { var module_category_srl = fo_obj.module_category_srl.options[fo_obj.module_category_srl.selectedIndex].value; if(module_category_srl==-1) { location.href = current_url.setQuery('act','dispModuleAdminCategory'); return false; } return true; }
lgpl-2.1
FernCreek/tinymce
modules/alloy/src/test/ts/browser/ui/inline/InlineViewTest.ts
9694
import { Assertions, GeneralSteps, Logger, Mouse, Step, UiFinder, Waiter, Chain, ApproxStructure } from '@ephox/agar'; import { UnitTest } from '@ephox/bedrock'; import { Arr, Future, Option, Result } from '@ephox/katamari'; import { Html, Css, Compare } from '@ephox/sugar'; import * as GuiFactory from 'ephox/alloy/api/component/GuiFactory'; import { Button } from 'ephox/alloy/api/ui/Button'; import { Container } from 'ephox/alloy/api/ui/Container'; import { Dropdown } from 'ephox/alloy/api/ui/Dropdown'; import { InlineView } from 'ephox/alloy/api/ui/InlineView'; import { tieredMenu as TieredMenu } from 'ephox/alloy/api/ui/TieredMenu'; import * as TestDropdownMenu from 'ephox/alloy/test/dropdown/TestDropdownMenu'; import * as GuiSetup from 'ephox/alloy/api/testhelpers/GuiSetup'; import * as Sinks from 'ephox/alloy/test/Sinks'; import * as TestBroadcasts from 'ephox/alloy/test/TestBroadcasts'; UnitTest.asynctest('InlineViewTest', (success, failure) => { GuiSetup.setup((store, doc, body) => { return Sinks.relativeSink(); }, (doc, body, gui, component, store) => { const inline = GuiFactory.build( InlineView.sketch({ dom: { tag: 'div', classes: [ 'test-inline' ] }, lazySink (comp) { Assertions.assertEq('Checking InlineView passed through to lazySink', true, Compare.eq(inline.element(), comp.element())); return Result.value(component); }, getRelated () { return Option.some(related); } // onEscape: store.adderH('inline.escape') }) ); const related = GuiFactory.build({ dom: { tag: 'div', classes: [ 'related-to-inline' ], styles: { background: 'blue', width: '50px', height: '50px' } } }); gui.add(related); const sCheckOpen = (label) => { return Logger.t( label, GeneralSteps.sequence([ Waiter.sTryUntil( 'Test inline should not be DOM', UiFinder.sExists(gui.element(), '.test-inline') ), Step.sync(() => { Assertions.assertEq('Checking isOpen API', true, InlineView.isOpen(inline)); }) ]) ); }; const sCheckClosed = (label) => { return Logger.t( label, GeneralSteps.sequence([ Waiter.sTryUntil( 'Test inline should not be in DOM', UiFinder.sNotExists(gui.element(), '.test-inline') ), Step.sync(() => { Assertions.assertEq('Checking isOpen API', false, InlineView.isOpen(inline)); }) ]) ); }; return [ UiFinder.sNotExists(gui.element(), '.test-inline'), Logger.t( 'Check that getContent is none for an inline menu that has not shown anything', Step.sync(() => { const contents = InlineView.getContent(inline); Assertions.assertEq('Should be none', true, contents.isNone()); }) ), Step.sync(() => { InlineView.showAt(inline, { anchor: 'selection', root: gui.element() }, Container.sketch({ dom: { innerHtml: 'Inner HTML' } })); }), sCheckOpen('After show'), Logger.t( 'Check that getContent is some now that the inline menu has shown something', Step.sync(() => { const contents = InlineView.getContent(inline); Assertions.assertEq('Checking HTML of inline contents', 'Inner HTML', Html.get(contents.getOrDie( 'Could not find contents' ).element())); }) ), Logger.t( 'Change the content using setContent and check it is there', Step.sync(() => { InlineView.setContent(inline, { dom: { tag: 'div', innerHtml: 'changed-html' } }); const contents = InlineView.getContent(inline); Assertions.assertEq('Checking HTML of inline contents has changed', 'changed-html', Html.get(contents.getOrDie( 'Could not find contents' ).element())); }) ), Logger.t( 'Check that changed content is in the DOM', Chain.asStep(component.element(), [ UiFinder.cFindIn('.test-inline'), Assertions.cAssertStructure( 'Checking structure of changed content', ApproxStructure.build((s, str, arr) => { return s.element('div', { classes: [ arr.has('test-inline') ], children: [ s.element('div', { html: str.is('changed-html') }) ] }); }) ) ]) ), Step.sync(() => { InlineView.hide(inline); }), Logger.t( 'Check that getContent is none not that inline view has been hidden again', Step.sync(() => { const contents = InlineView.getContent(inline); Assertions.assertEq('Should be none', true, contents.isNone()); }) ), sCheckClosed('After hide'), Step.sync(() => { InlineView.showAt(inline, { anchor: 'makeshift', x: 50, y: 50 }, Container.sketch({ dom: { innerHtml: 'Inner HTML' } })); }), sCheckOpen('After show'), Logger.t( 'Check that inline view has a top and left', Chain.asStep(gui.element(), [ UiFinder.cFindIn('.test-inline'), Chain.op((value) => { Assertions.assertEq('Check view CSS top is 50px', '50px', Css.getRaw(value, 'top').getOr('no top found')); Assertions.assertEq('Check view CSS left is 50px', '50px', Css.getRaw(value, 'left').getOr('no left found')); }) ]) ), Step.sync(() => { InlineView.hide(inline); }), sCheckClosed('After hide'), Logger.t( 'Show inline view again, this time with buttons', Step.sync(() => { InlineView.showAt(inline, { anchor: 'selection', root: gui.element() }, Container.sketch({ components: [ Button.sketch({ uid: 'bold-button', dom: { tag: 'button', innerHtml: 'B', classes: [ 'bold-button' ] }, action: store.adder('bold') }), Button.sketch({ uid: 'italic-button', dom: { tag: 'button', innerHtml: 'I', classes: [ 'italic-button' ] }, action: store.adder('italic') }), Button.sketch({ uid: 'underline-button', dom: { tag: 'button', innerHtml: 'U', classes: [ 'underline-button' ] }, action: store.adder('underline') }), Dropdown.sketch({ dom: { tag: 'button', innerHtml: '+' }, components: [ ], toggleClass: 'alloy-selected', lazySink () { return Result.value(component); }, parts: { menu: TestDropdownMenu.part(store) }, fetch () { const future = Future.pure([ { type: 'item', data: { value: 'option-1', meta: { text: 'Option-1' } } }, { type: 'item', data: { value: 'option-2', meta: { text: 'Option-2' } } } ]); return future.map((f) => { const menu = TestDropdownMenu.renderMenu({ value: 'inline-view-test', items: Arr.map(f, TestDropdownMenu.renderItem) }); return Option.some(TieredMenu.singleData('test', menu)); }); } }) ] })); }) ), sCheckOpen('Should still be open with buttons and a dropdown'), TestBroadcasts.sDismissOn( 'toolbar: should not close', gui, '.bold-button' ), sCheckOpen('Broadcasting dismiss on button should not close inline toolbar'), store.sAssertEq('Check that the store is empty initially', [ ]), Mouse.sClickOn(gui.element(), 'button:contains("B")'), store.sAssertEq('Check that bold activated', [ 'bold' ]), // TODO: Make it not close if the inline toolbar had a dropdown, and the dropdown // item was selected. Requires composition of "isPartOf" Logger.t( 'Check that clicking on a dropdown item in the inline toolbar does not dismiss popup', GeneralSteps.sequence([ // Click on the dropdown Mouse.sClickOn(gui.element(), 'button:contains(+)'), // Wait until dropdown loads. Waiter.sTryUntil( 'Waiting for dropdown list to appear', UiFinder.sExists(gui.element(), 'li:contains("Option-1")') ), TestBroadcasts.sDismissOn( 'dropdown item: should not close', gui, 'li:contains("Option-2")' ), sCheckOpen('Broadcasting dismiss on a dropdown item should not close inline toolbar') ]) ), TestBroadcasts.sDismiss( 'related element: should not close', gui, related.element() ), sCheckOpen('The inline view should not have closed when broadcasting on related'), TestBroadcasts.sDismiss( 'outer gui element: should close', gui, gui.element() ), sCheckClosed('Broadcasting dismiss on a external element should close inline toolbar') ]; }, () => { success(); }, failure); });
lgpl-2.1
huangye177/spring4probe
src/test/java/data/yummynoodlebar/persistence/integration/fakecore/FakeCoreConfiguration.java
650
package data.yummynoodlebar.persistence.integration.fakecore; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import data.yummynoodlebar.core.services.OrderStatusUpdateService; /* * a new test-only Spring Configuration. This will stand in the place of any Core domain Spring configuration * * a standard @Configuration, simply creating a new bean instance of the type OrderStatusUpdateService */ @Configuration public class FakeCoreConfiguration { @Bean OrderStatusUpdateService orderStatusUpdateService() { return new CountingOrderStatusService(); } }
lgpl-3.0
VahidN/PdfReport
Lib/FluentInterface/ExportToBuilder.cs
4360
using System.Collections.Generic; using OfficeOpenXml.Table; using PdfRpt.Core.Contracts; using PdfRpt.Export; namespace PdfRpt.FluentInterface { /// <summary> /// PdfRpt DataExporter Builder Class. /// </summary> public class ExportToBuilder { readonly PdfReport _pdfReport; /// <summary> /// ctor. /// </summary> /// <param name="pdfReport"></param> public ExportToBuilder(PdfReport pdfReport) { _pdfReport = pdfReport; if (_pdfReport.DataBuilder.CustomExportSettings == null) _pdfReport.DataBuilder.CustomExportSettings = new List<IDataExporter>(); } /// <summary> /// Microsoft Excel Worksheet DataExporter /// </summary> /// <param name="description">the produced file's description</param> /// <param name="fileName">the produced file's name</param> /// <param name="worksheetName">the WorksheetName</param> /// <param name="footer">Footer's Text</param> /// <param name="header">Header's Text</param> /// <param name="numberformat">Number format such as #,##0</param> /// <param name="dateTimeFormat">DateTime Format such as yyyy-MM-dd hh:mm</param> /// <param name="timeSpanFormat">TimeSpan Format such as hh:mm:ss</param> /// <param name="pageLayoutView">Sets the view mode of the worksheet to PageLayout.</param> /// <param name="showGridLines">Show GridLines in the worksheet.</param> /// <param name="tableStyle">the produced table's style</param> public void ToExcel( string description = "Exported Data", string fileName = "data.xlsx", string worksheetName = "worksheet1", string footer = "", string header = "", string numberformat = "#,##0", string dateTimeFormat = "yyyy-MM-dd hh:mm", string timeSpanFormat = "hh:mm:ss", bool pageLayoutView = false, bool showGridLines = false, TableStyles tableStyle = TableStyles.Dark9 ) { var exportToExcel = new ExportToExcel { DateTimeFormat = dateTimeFormat, Description = description, FileName = fileName, Footer = footer, Header = header, Numberformat = numberformat, PageLayoutView = pageLayoutView, ShowGridLines = showGridLines, TableStyle = tableStyle, TimeSpanFormat = timeSpanFormat, WorksheetName = worksheetName }; _pdfReport.DataBuilder.CustomExportSettings.Add(exportToExcel); } /// <summary> /// CSV DataExporter /// </summary> /// <param name="description">the produced file's description</param> /// <param name="fileName">the produced file's name</param> public void ToCsv(string description = "Exported Data", string fileName = "data.csv") { var exportToCsv = new ExportToCsv { Description = description, FileName = fileName }; _pdfReport.DataBuilder.CustomExportSettings.Add(exportToCsv); } /// <summary> /// XML DataExporter /// </summary> /// <param name="description">the produced file's description</param> /// <param name="fileName">the produced file's name</param> public void ToXml(string description = "Exported Data", string fileName = "data.xml") { var exportToXml = new ExportToXml { Description = description, FileName = fileName }; _pdfReport.DataBuilder.CustomExportSettings.Add(exportToXml); } /// <summary> /// Sets the desired exporters such as ExportToExcel. /// </summary> /// <param name="exportSettings">export settings</param> public void ToCustomFormat(IDataExporter exportSettings) { _pdfReport.DataBuilder.CustomExportSettings.Add(exportSettings); } } }
lgpl-3.0
cismet/cismap-commons
src/main/java/de/cismet/cismap/commons/gui/options/CismapOptionsCategory.java
1485
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cismap.commons.gui.options; import org.openide.util.ImageUtilities; import org.openide.util.lookup.ServiceProvider; import java.awt.Image; import javax.swing.Icon; import javax.swing.ImageIcon; import de.cismet.lookupoptions.AbstractOptionsCategory; import de.cismet.lookupoptions.OptionsCategory; /** * DOCUMENT ME! * * @author jruiz * @version $Revision$, $Date$ */ @ServiceProvider(service = OptionsCategory.class) public class CismapOptionsCategory extends AbstractOptionsCategory { //~ Methods ---------------------------------------------------------------- @Override public String getName() { return org.openide.util.NbBundle.getMessage(CismapOptionsCategory.class, "CismapOptionsCategory.name"); // NOI18N } @Override public Icon getIcon() { final Image image = ImageUtilities.loadImage("de/cismet/cismap/commons/gui/options/cismap.png"); if (image != null) { return new ImageIcon(image); } else { return null; } } @Override public int getOrder() { return 3; } @Override public String getTooltip() { return org.openide.util.NbBundle.getMessage(CismapOptionsCategory.class, "CismapOptionsCategory.tooltip"); // NOI18N } }
lgpl-3.0
jjm223/MyPet
modules/v1_8_R3/src/main/java/de/Keyle/MyPet/compat/v1_8_R3/skill/skills/ranged/bukkit/CraftMyPetWitherSkull.java
2009
/* * This file is part of MyPet * * Copyright © 2011-2016 Keyle * MyPet is licensed under the GNU Lesser General Public License. * * MyPet 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. * * MyPet is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.Keyle.MyPet.compat.v1_8_R3.skill.skills.ranged.bukkit; import de.Keyle.MyPet.api.entity.MyPetBukkitEntity; import de.Keyle.MyPet.api.skill.skills.ranged.CraftMyPetProjectile; import de.Keyle.MyPet.api.skill.skills.ranged.EntityMyPetProjectile; import de.Keyle.MyPet.api.util.Compat; import net.minecraft.server.v1_8_R3.EntityWitherSkull; import org.bukkit.craftbukkit.v1_8_R3.CraftServer; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftWitherSkull; import org.bukkit.entity.LivingEntity; @Compat("v1_8_R3") public class CraftMyPetWitherSkull extends CraftWitherSkull implements CraftMyPetProjectile { public CraftMyPetWitherSkull(CraftServer server, EntityWitherSkull entity) { super(server, entity); } @Deprecated public LivingEntity _INVALID_getShooter() { return (LivingEntity) super.getShooter(); } @Deprecated public void _INVALID_setShooter(LivingEntity shooter) { super.setShooter(shooter); } public EntityMyPetProjectile getMyPetProjectile() { return ((EntityMyPetProjectile) this.getHandle()); } @Override public MyPetBukkitEntity getShootingMyPet() { return getMyPetProjectile().getShooter().getBukkitEntity(); } }
lgpl-3.0
mybb-de/MyBB-German
lang_deutsch_sie/Sprachdateien/deutsch_sie/admin/tools_backupdb.lang.php
3447
<?php /** * German language pack for MyBB 1.8 (formal) * Deutsches Sprachpaket für MyBB 1.8 "formell" (Sie) * (c) 2005-2014 MyBBoard.de * * Author/Autor: http://www.mybboard.de/ * License/Lizenz: GNU Lesser General Public License, Version 3 */ $l['database_backups'] = "Datenbank-Sicherung"; $l['database_backups_desc'] = "Hier finden Sie eine Liste mit den Datenbank-Sicherungen, die im Moment im MyBB-Sicherungs-Ordner auf dem Server gespeichert sind."; $l['new_database_backup'] = "Neue Datenbank-Sicherung"; $l['new_backup'] = "Neue Sicherung"; $l['new_backup_desc'] = "Hier können Sie neue Sicherungen Ihrer Datenbank machen"; $l['backups'] = "Sicherungen"; $l['existing_database_backups'] = "Vorhandene Datenbank-Sicherungen"; $l['backup_saved_to'] = "Die Sicherung wurde gespeichert in:"; $l['download'] = "Herunterladen"; $l['table_selection'] = "Tabellen-Auswahl"; $l['backup_options'] = "Sicherungs-Optionen"; $l['table_select_desc'] = "Hier können Sie die Tabellen auswählen, für die Sie die Aktion durchführen möchten. Halten Sie STRG gedrückt, um mehrere Tabellen auszuwählen."; $l['select_all'] = "Alle auswählen"; $l['deselect_all'] = "Alle abwählen"; $l['select_forum_tables'] = "Tabellen des Forums wählen"; $l['file_type'] = "Dateityp"; $l['file_type_desc'] = "Wählen Sie den Dateityp, mit dem die Datenbank-Sicherung gespeichert werden soll."; $l['gzip_compressed'] = "GZIP-komprimiert"; $l['plain_text'] = "Textdatei"; $l['save_method'] = "Sicherungs-Methode"; $l['save_method_desc'] = "Hier können Sie die Methode wählen, mit der die Sicherung gespeichert werden soll,"; $l['backup_directory'] = "Sicherungsordner"; $l['backup_contents'] = "Sicherungs-Inhalt"; $l['backup_contents_desc'] = "Hier können Sie die Informationen auswählen, die gespeichert werden sollen."; $l['structure_and_data'] = "Struktur und Daten"; $l['structure_only'] = "Nur Struktur"; $l['data_only'] = "Nur Daten"; $l['analyze_and_optimize'] = "Ausgewählte Tabellen analysieren und optimieren"; $l['analyze_and_optimize_desc'] = "Wollen Sie die ausgewählten Tabellen während der Sicherung analysieren und optimieren?"; $l['perform_backup'] = "Sicherung durchführen"; $l['backup_filename'] = "Dateiname der Sicherung"; $l['file_size'] = "Dateigröße"; $l['creation_date'] = "Erstellungsdatum"; $l['no_backups'] = "Es wurden noch keine Sicherungen gemacht."; $l['error_file_not_specified'] = "Sie haben keine Datenbank-Sicherung zum Herunterladen ausgewählt."; $l['error_invalid_backup'] = "Die ausgewählte Datei ist entweder falsch oder existiert nicht."; $l['error_backup_doesnt_exist'] = "Die ausgewählte Sicherung existiert nicht."; $l['error_backup_not_deleted'] = "Die ausgewählte Sicherung kann nicht gelöscht werden."; $l['error_tables_not_selected'] = "Sie haben keine Tabellen für die Sicherung ausgewählt."; $l['error_no_zlib'] = "Die Zlib-Bibliothek für PHP ist nicht aktiviert, deshalb konnte die Aktion nicht ausgeführt werden."; $l['alert_not_writable'] = "Der Sicherungsordner (im Ordner &quot;admin&quot;) kann nicht beschrieben werden. Sicherungen können nicht auf dem Server gespeichert werden."; $l['confirm_backup_deletion'] = "Wollen Sie diese Sicherung wirklich löschen?"; $l['success_backup_deleted'] = "Die Sicherung wurde erfolgreich gelöscht."; $l['success_backup_created'] = "Die Sicherung wurde erfolgreich erstellt.";
lgpl-3.0
efcs/elib
src/elib/unit_tests/optional/comparison_test.pass.cpp
4383
// REQUIRES: ELIB_CORE #include <elib/optional.hpp> #include "rapid-cxx-test.hpp" using elib::optional; using elib::nullopt; TEST_SUITE(elib_optional_comparison_test_suite) TEST_CASE(empty_identity_compare_test) { const optional<int> o1; TEST_CHECK( o1 == o1 ); TEST_CHECK( not (o1 != o1) ); TEST_CHECK( not (o1 < o1) ); TEST_CHECK( not (o1 > o1) ); TEST_CHECK( o1 <= o1 ); TEST_CHECK( o1 >= o1 ); } TEST_CASE(non_empty_identity_compare_test) { const optional<int> o1(0); TEST_CHECK( o1 == o1 ); TEST_CHECK( not (o1 != o1) ); TEST_CHECK( not (o1 < o1) ); TEST_CHECK( not (o1 > o1) ); TEST_CHECK( o1 <= o1 ); TEST_CHECK( o1 >= o1 ); } TEST_CASE(compare_against_empty_test) { const optional<int> o1; const optional<int> o2(0); TEST_CHECK( not (o1 == o2) ); TEST_CHECK( not (o2 == o1) ); TEST_CHECK( o1 != o2 ); TEST_CHECK( o2 != o1 ); TEST_CHECK( o1 < o2 ); TEST_CHECK( not (o2 < o1) ); TEST_CHECK( not (o1 > o2) ); TEST_CHECK( o2 > o1 ); TEST_CHECK( o1 <= o2 ); TEST_CHECK( not (o2 <= o1) ); TEST_CHECK( not (o1 >= o2) ); TEST_CHECK( o2 >= o1 ); } TEST_CASE(compare_against_non_equal_test) { const optional<int> o2(0); const optional<int> o3(1); TEST_CHECK( not (o2 == o3) ); TEST_CHECK( not (o3 == o2) ); TEST_CHECK( o2 != o3 ); TEST_CHECK( o3 != o2 ); TEST_CHECK( o2 < o3 ); TEST_CHECK( not (o3 < o2) ); TEST_CHECK( not (o2 > o3) ); TEST_CHECK( o3 > o2 ); TEST_CHECK( o2 <= o3 ); TEST_CHECK( not (o3 <= o2) ); TEST_CHECK( not (o2 >= o3) ); TEST_CHECK( o3 >= o2 ); } TEST_CASE(nullopt_compare_empty_test) { const optional<int> o1; TEST_CHECK( o1 == nullopt ); TEST_CHECK( nullopt == o1 ); TEST_CHECK( not (o1 != nullopt) ); TEST_CHECK( not (nullopt != o1) ); TEST_CHECK( not (o1 < nullopt) ); TEST_CHECK( not (nullopt < o1) ); TEST_CHECK( not (o1 > nullopt) ); TEST_CHECK( not (nullopt > o1) ); TEST_CHECK( o1 <= nullopt ); TEST_CHECK( nullopt <= o1 ); TEST_CHECK( o1 >= nullopt ); TEST_CHECK( nullopt >= o1 ); } TEST_CASE(nullopt_compare_non_empty_test) { const optional<int> o2(0); TEST_CHECK( not (o2 == nullopt) ); TEST_CHECK( not (nullopt == o2) ); TEST_CHECK( o2 != nullopt ); TEST_CHECK( nullopt != o2 ); TEST_CHECK( not (o2 < nullopt) ); TEST_CHECK( nullopt < o2 ); TEST_CHECK( o2 > nullopt ); TEST_CHECK( not (nullopt > o2) ); TEST_CHECK( not (o2 <= nullopt) ); TEST_CHECK( nullopt <= o2 ); TEST_CHECK( o2 >= nullopt ); TEST_CHECK( not (nullopt >= o2) ); } TEST_CASE(empty_compare_value_test) { const optional<int> o1; TEST_CHECK( not (o1 == 0) ); TEST_CHECK( not (0 == o1) ); TEST_CHECK( o1 != 0 ); TEST_CHECK( 0 != o1 ); TEST_CHECK( o1 < 0 ); TEST_CHECK( not (0 < o1) ); TEST_CHECK( not (o1 > 0) ); TEST_CHECK( 0 > o1 ); TEST_CHECK( o1 <= 0 ); TEST_CHECK( not (0 <= o1) ); TEST_CHECK( not (o1 >= 0) ); TEST_CHECK( 0 >= o1 ); } TEST_CASE(non_empty_compare_with_value_test) { optional<int> const o2(0); TEST_CHECK( o2 == 0 ); TEST_CHECK( 0 == o2 ); TEST_CHECK( not (o2 == 1) ); TEST_CHECK( not (1 == o2) ); TEST_CHECK( not (o2 != 0) ); TEST_CHECK( not (0 != o2) ); TEST_CHECK( o2 != 1 ); TEST_CHECK( 1 != o2 ); TEST_CHECK( not (o2 < 0) ); TEST_CHECK( not (0 < o2) ); TEST_CHECK( -1 < o2 ); TEST_CHECK( not (1 < o2) ); TEST_CHECK( o2 < 1 ); TEST_CHECK( not (o2 < -1) ); TEST_CHECK( not (o2 > 0) ); TEST_CHECK( not (0 > o2) ); TEST_CHECK( 1 > o2 ); TEST_CHECK( not (-1 > o2) ); TEST_CHECK( o2 > -1 ); TEST_CHECK( not (o2 > 1) ); TEST_CHECK( o2 <= 0 ); TEST_CHECK( 0 <= o2 ); TEST_CHECK( -1 <= o2 ); TEST_CHECK( not (1 <= o2) ); TEST_CHECK( o2 <= 1 ); TEST_CHECK( not (o2 <= -1) ); TEST_CHECK( o2 >= 0 ); TEST_CHECK( 0 >= o2 ); TEST_CHECK( 1 >= o2 ); TEST_CHECK( not (-1 >= o2) ); TEST_CHECK( o2 >= -1 ); TEST_CHECK( not (o2 >= 1) ); } TEST_SUITE_END()
lgpl-3.0
subes/invesdwin-nowicket
invesdwin-nowicket-examples/invesdwin-nowicket-examples-guide/src/main/java/de/invesdwin/nowicket/examples/guide/page/wicket/wizard/createuser/panel/CreateUserWizardStepControlPanel.java
558
package de.invesdwin.nowicket.examples.guide.page.wicket.wizard.createuser.panel; import javax.annotation.concurrent.NotThreadSafe; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import de.invesdwin.nowicket.generated.binding.GeneratedBinding; @NotThreadSafe public class CreateUserWizardStepControlPanel extends Panel { public CreateUserWizardStepControlPanel(final String id, final IModel<CreateUserWizardStepControl> model) { super(id, model); new GeneratedBinding(this).bind(); } }
lgpl-3.0
jlrisco/xdevs-lib
java/src/xdevs/lib/core/modeling/PortView.java
1487
/* * Copyright (C) 2014-2019 José Luis Risco Martín <jlrisco@ucm.es> * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * - José Luis Risco Martín */ package xdevs.lib.core.modeling; import xdevs.core.modeling.Port; /** * * @author jlrisco */ public class PortView { protected Port port; public PortView(Port port) { this.port = port; } public Port getPort() { return port; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(port.getName()).append("={"); int numElements = 0; for(Object obj : port.getValues()) { if(numElements>0) sb.append(","); sb.append(obj.toString()); numElements++; } sb.append("}"); return sb.toString(); } }
lgpl-3.0
fieldOfView/pyZOCP
examples/BpyZOCP.py
15288
import bpy import sys import time import json import socket import zmq from zocp import ZOCP from mathutils import Vector from bpy.app.handlers import persistent alreadyDeletedObjects = set() camSettings = {} mistSettings = () def toggleDebug(s, ctx): pass # PROPERTIES bpy.types.Scene.zdebug_prop = bpy.props.BoolProperty( name="Toggle Debug", description = "This is a boolean", default=False, update=toggleDebug ) bpy.types.Scene.zmute_prop = bpy.props.BoolProperty( name="Mute", description = "This is a boolean", default=False ) bpy.types.Scene.zname_prop = bpy.props.StringProperty(name="Node Name", default=socket.gethostname(),description = "This can be used to identify your node") # Menu in UI region # class UIPanel(bpy.types.Panel): bl_label = "ZOCP Control" bl_space_type = "VIEW_3D" bl_region_type = "UI" def draw(self, context): scn = bpy.context.scene self.layout.operator("send.all", text='Send all object data') self.layout.prop( scn, "zdebug_prop" ) self.layout.prop( scn, "zmute_prop" ) self.layout.prop( scn, "zname_prop" ) class OBJECT_OT_SendMesh(bpy.types.Operator): bl_idname = "send.all" bl_label = "Send Object Data" def execute(self, context): z.refresh_objects(); return{'FINISHED'} class OBJECT_OT_HelloButton(bpy.types.Operator): bl_idname = "send.zocpdebug" bl_label = "Send Debug" def execute(self, context): print("Sending debug!") z.shout("ZOCP", {"MOD": {"debug": True}}) return{'FINISHED'} def sendCameraSettings(camera): """ send camera fov and lensshhift """ global camSettings angle = camera.angle lx = camera.shift_x ly = camera.shift_y print("sending new camera settings for %s" %camera.name) z.shout("ZOCP", json.dumps({ "MOD": { camera.name+".angle": {"value": camera.angle}, camera.name+".shift_x": {"value": camera.shift_x}, camera.name+".shift_y": {"value": camera.shift_y}, } }).encode('utf-8')) z.capability[camera.name+".angle"]['value'] = angle z.capability[camera.name+".shift_x"]['value'] = lx z.capability[camera.name+".shift_y"]['value'] = ly camSettings[camera.name] = (angle, lx, ly) # @persistent # def update_data(scene): # for obj in scene.objects: # if obj.type == 'MESH': # only send the object if it is a mesh or a Camera # z.capability[obj.name+".x"]['value'] = obj.location.x # z.capability[obj.name+".y"]['value'] = obj.location.y # z.capability[obj.name+".z"]['value'] = obj.location.z # sendObjectData(obj) # elif obj.type == 'CAMERA': # angle = obj.data.angle # lx = obj.data.shift_x # ly = obj.data.shift_y # if not ( [angle, lx, ly] == camSettings.get(obj.data.name)): # print("camera settings changed for %s", obj.name) # sendCameraSettings(obj.data) # def register(): # for obj in bpy.context.scene.objects: # if obj.type == 'MESH': # only send the object if it is a mesh or a Camera # z.register_float(obj.name+".x", obj.location.x, 'r') # z.register_float(obj.name+".y", obj.location.y, 'r') # z.register_float(obj.name+".z", obj.location.z, 'r') # elif obj.type == 'CAMERA': # z.register_float(obj.name+".angle", obj.data.angle, 'r') # z.register_float(obj.name+".shift_x", obj.data.shift_x, 'r') # z.register_float(obj.name+".shift_y", obj.data.shift_y, 'r') class BpyZOCP(ZOCP): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.set_name("Blender@" + socket.gethostname() + ":" + bpy.app.version_string) self.start() @persistent def clear_objects(self): print("CLEAR OBJECTS") if not self.capability.get('objects'): return self.set_object() self.capability['objects'].clear() self._on_modified(self.capability) def register_objects(self): print("REGISTER OBJECTS") self._running = False for obj in bpy.context.scene.objects: print(obj.name) if obj.type in ['MESH', 'CAMERA', 'LAMP']: if obj.type == "LAMP": self._register_lamp(obj) elif obj.type == "CAMERA": self._register_camera(obj) else: self._register_mesh(obj) self._running = True @persistent def refresh_objects(self): print("REFRESHING OBJECTS") for obj in bpy.context.scene.objects: print(obj.name) if obj.type in ['MESH', 'CAMERA', 'LAMP']: if obj.type == "LAMP": self._register_lamp(obj) elif obj.type == "CAMERA": self._register_camera(obj) else: self._register_mesh(obj) def _register_lamp(self, obj): self.set_object(obj.name, "BPY_Lamp") self.register_vec3f("location", obj.location[:], 're') #self.register_mat3f("worldOrientation", obj.worldOrientation[:], 're') self.register_vec3f("orientation", obj.rotation_euler[:], 're') self.register_vec3f("scale", obj.scale[:], 're') self.register_vec3f("color", obj.data.color[:], 're') self.register_float("energy", obj.data.energy, 're') self.register_float("distance", obj.data.distance, 're') #self.register_int ("state", obj.state) #self.register_float("mass", obj.mass) def _register_camera(self, obj): self.set_object(obj.name, "BPY_Camera") self.register_vec3f("location", obj.location[:], 're') #self.register_mat3f("worldOrientation", obj.worldOrientation[:], 're') self.register_vec3f("orientation", obj.rotation_euler[:], 're') self.register_float("angle", obj.data.angle, 're') self.register_float("shift_x", obj.data.shift_x, 're') self.register_float("shift_y", obj.data.shift_y, 're') def _register_mesh(self, obj): self.set_object(obj.name, "BPY_Mesh") self.register_vec3f("location", obj.location[:], 're') #self.register_mat3f("worldOrientation", obj.worldOrientation[:], 're') self.register_vec3f("orientation", obj.rotation_euler[:], 're') self.register_vec3f("scale", obj.scale[:], 're') self.register_vec4f("color", obj.color[:], 're') #self.register_int ("state", obj.state, 're') #self.register_float("mass", obj.mass, 're') def send_object_changes(self, obj): self.set_object(obj.name, "BPY_Mesh") if self._cur_obj.get("location", {}).get("value") != obj.location[:]: #self.register_vec3f("location", obj.location[:]) self.emit_signal("location", obj.location[:]) if self._cur_obj.get("orientation", {}).get("value") != obj.rotation_euler[:]: #self.register_vec3f("orientation", obj.rotation_euler[:]) self.emit_signal("orientation", obj.rotation_euler[:]) if self._cur_obj.get("scale", {}).get("value") != obj.scale[:]: #self.register_vec3f("scale", obj.scale[:]) self.emit_signal("scale", obj.scale[:]) if obj.type == "LAMP": if self._cur_obj.get("color", {}).get("value") != obj.data.color[:]: #self.register_vec3f("color", obj.data.color[:]) self.emit_signal("color", obj.data.color[:]) if self._cur_obj.get("energy", {}).get("value") != obj.data.energy[:]: self.register_float("energy", obj.data.energy[:]) if self._cur_obj.get("distance", {}).get("value") != obj.data.distance[:]: self.register_float("color", obj.data.distance[:]) elif obj.type == "MESH": if self._cur_obj.get("color", {}).get("value") != obj.color[:]: self.register_vec4f("color", obj.color[:]) elif obj.type == "CAMERA": self._register_camera(obj) def emit_signal(self, name, data): super().emit_signal(".".join(self._cur_obj_keys + (name, )), data) ######################################### # Event methods. These can be overwritten ######################################### def on_peer_enter(self, peer, name, *args, **kwargs): print("ZOCP ENTER : %s" %(name)) # create an empty for peer # name = self.peers[peer].get("_name", peer.hex) # bpy.ops.object.empty_add(type="PLAIN_AXES") # bpy.context.object.name = name # # get projectors on peer # objects = self.peers[peer].get("objects", {}) # for obj, data in objects.items(): # if data.get("type", "") == "projector": # loc = data.get("location", (0,0,0)) # ori = data.get("orientation", (0,0,0)) # bpy.ops.object.camera_add(view_align=True, # enter_editmode=False, # location=loc, # rotation=ori, # layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False) # ) # bpy.context.object.name = obj def on_peer_exit(self, peer, name, *args, **kwargs): print("ZOCP EXIT : %s" %(name)) # bpy.ops.object.select_all(action='DESELECT') # objects = self.peers[peer].get("objects", {}) # for obj, data in objects.items(): # if data.get("type", "") == "projector": # bpy.ops.object.select_pattern(pattern=obj) # bpy.ops.object.delete() # # delete empty # name = self.peers[peer].get("_name", peer.hex) # bpy.ops.object.select_pattern(pattern=name) # bpy.ops.object.delete() # bpy.ops.object.select_pattern(pattern=peer.hex) # bpy.ops.object.delete() # bpy.ops.object.select_all(action='DESELECT') def on_peer_modified(self, peer, name, data, *args, **kwargs): #print("ZOCP PEER MODIFIED: %s modified %s" %(name, data)) name = data.get("_name", "") if name.startswith("BGE"): # If we have camera for it send it the settings # otherwise create new camera try: c=bpy.data.objects[name] except KeyError as e: print("WE FOUND AN UNKNOWN BGE NODE, creating a camera for it") # create a new camera loc = data.get("location", (0,0,0)) ori = data.get("orientation", (0,0,0)) bpy.ops.object.camera_add(view_align=True, enter_editmode=False, location=loc, rotation=ori, layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False) ) bpy.context.object.name = name else: print("WE FOUND A BGE NODE, sending camera data") self._register_camera(c) def on_modified(self, peer, name, data, *args, **kwargs): pass # if data.get('objects'): # for obj,val in data['objects'].items(): # if val.get("Type") # bpy.ops.object.select_all(action='DESELECT') # bpy.ops.object.select_pattern(pattern=obj) # try: # blenderobj = bpy.context.scene.objects[obj] # except KeyError as e: # print(e) # else: # for key,val2 in val.items(): # try: # setattr(blenderobj, key, val) # except AttributeError as e: # print(e) # except TypeError as e: # print(e) # except ValueError as e: # print(e) #except (KeyboardInterrupt, SystemExit): # self.stop() z = BpyZOCP() compobj = {} for ob in bpy.data.objects: print(ob.name) compobj[ob.name] = ob.matrix_world.copy() # Needed for delaying toffset = 1/30.0 tstamp = time.time() @persistent def clear_objects(context): global compobj compobj.clear() z.clear_objects() @persistent def register_objects(context): global compobj z.register_objects() for ob in bpy.data.objects: compobj[ob.name] = ob.matrix_world.copy() @persistent def scene_update(context): global toffset global tstamp # only once per 'toffset' seconds to lessen the burden if time.time() > tstamp + toffset: tstamp = time.time() z.run_once(timeout=0) update_objects() #else: # print("delayed", tstamp, time.time()) @persistent def frame_update(context): global compobj for ob in bpy.data.objects: if not compobj.get(ob.name): compobj[ob.name] = ob.matrix_world.copy() z.send_object_changes(ob) elif ob.is_updated and ob.matrix_world != compobj[ob.name]: z.send_object_changes(ob) compobj[ob.name] = ob.matrix_world.copy() def update_objects(): global compobj if bpy.data.objects.is_updated: for ob in bpy.data.objects: ###### TODO: BETTER CODE FOR MANAGING CHANGED DATA if not compobj.get(ob.name): compobj[ob.name] = ob.matrix_world.copy() z.send_object_changes(ob) elif ob.is_updated and ob.matrix_world != compobj[ob.name]: z.send_object_changes(ob) compobj[ob.name] = ob.matrix_world.copy() #register cameras #register() bpy.utils.register_module(__name__) #bpy.app.handlers.scene_update_post.append(update_data) #bpy.app.handlers.frame_change_pre.clear() #bpy.app.handlers.frame_change_pre.append(update_data) bpy.app.handlers.load_pre.clear() bpy.app.handlers.load_post.clear() bpy.app.handlers.load_pre.append(clear_objects) bpy.app.handlers.load_post.append(register_objects) bpy.app.handlers.scene_update_post.clear() bpy.app.handlers.scene_update_post.append(scene_update) bpy.app.handlers.frame_change_post.clear() bpy.app.handlers.frame_change_post.append(frame_update)
lgpl-3.0
webmaza75/try-t4-mini
protected/Models/Article.php
78
<?php namespace App\Models; use T4\Core\Std; class Article extends Std { }
lgpl-3.0
SergiyKolesnikov/fuji
examples/DiGraph/fop/DiGraph/features/DiGraph/ArcType.java
2748
// @(#)$Id: ArcType.java 1199 2009-02-17 19:42:32Z smshaner $ // Copyright (C) 1998, 1999 Iowa State University // This file is part of JML // JML 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. // JML 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 JML; see the file COPYING. If not, write to // the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. /*@ pure */ public class ArcType implements JMLType { //@ public model NodeType from; //@ public model NodeType to; //@ public invariant from != null && to != null; private NodeType _from; //@ in from; private NodeType _to; //@ in to; //@ private represents from <- _from; //@ private represents to <- _to; //@ private invariant_redundantly _from != null && _to != null; /*@ public normal_behavior @ requires from != null && to != null; @ assignable this.from, this.to; @ ensures this.from.equals(from) @ && this.to.equals(to); @*/ public ArcType(NodeType from, NodeType to) { _from = from; _to = to; } /*@ also @ public normal_behavior @ {| @ requires o instanceof ArcType; @ ensures \result @ <==> ((ArcType)o).from.equals(from) @ && ((ArcType)o).to.equals(to); @ also @ requires !(o instanceof ArcType); @ ensures \result == false; @ |} @*/ public boolean equals(/*@ nullable @*/ Object o) { return o instanceof ArcType && ((ArcType)o)._from.equals(_from) && ((ArcType)o)._to.equals(_to); } public int hashCode() { return _from.hashCode() + _to.hashCode(); } //@ ensures \result == from; public NodeType getFrom() { return _from; } //@ ensures \result == to; public NodeType getTo() { return _to; } /*@ also @ public normal_behavior @ ensures \result instanceof ArcType @ && ((ArcType)\result).equals(this); @*/ public Object clone() { return new ArcType(_from, _to); } protected String className() { return "ArcType"; } public String toString() { return className() + "[from: " + _from + ", to: " + _to + "]"; } }
lgpl-3.0
hoverkey/honeybee
sdk/examples/k9mail/src/com/fsck/k9/crypto/CryptoProvider.java
1826
package com.fsck.k9.crypto; import android.app.Activity; import android.content.Context; import android.content.Intent; import com.fsck.k9.mail.Message; /** * A CryptoProvider provides functionalities such as encryption, decryption, digital signatures. * It currently also stores the results of such encryption or decryption. * TODO: separate the storage from the provider */ abstract public class CryptoProvider { static final long serialVersionUID = 0x21071234; abstract public boolean isAvailable(Context context); abstract public boolean isEncrypted(Message message); abstract public boolean isSigned(Message message); abstract public boolean onActivityResult(Activity activity, int requestCode, int resultCode, Intent data, PgpData pgpData); abstract public boolean selectSecretKey(Activity activity, PgpData pgpData); abstract public boolean selectEncryptionKeys(Activity activity, String emails, PgpData pgpData); abstract public boolean encrypt(Activity activity, String data, PgpData pgpData); abstract public boolean decrypt(Activity activity, String data, PgpData pgpData); abstract public long[] getSecretKeyIdsFromEmail(Context context, String email); abstract public long[] getPublicKeyIdsFromEmail(Context context, String email); abstract public boolean hasSecretKeyForEmail(Context context, String email); abstract public boolean hasPublicKeyForEmail(Context context, String email); abstract public String getUserId(Context context, long keyId); abstract public String getName(); abstract public boolean test(Context context); public static CryptoProvider createInstance(String name) { if (Apg.NAME.equals(name)) { return Apg.createInstance(); } return None.createInstance(); } }
lgpl-3.0