repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtsensors/src/plugins/sensors/android/src/androidgyroscope.cpp
2630
/**************************************************************************** ** ** Copyright (C) 2016 BogDan Vatra <[email protected]> ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtSensors 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 The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://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 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "androidgyroscope.h" #include <math.h> AndroidGyroscope::AndroidGyroscope(AndroidSensors::AndroidSensorType type, QSensor *sensor) : AndroidCommonSensor<QGyroscopeReading>(type, sensor) {} void AndroidGyroscope::onSensorChanged(jlong timestamp, const jfloat *values, uint size) { if (size < 3) return; m_reader.setTimestamp(timestamp/1000); // check https://developer.android.com/reference/android/hardware/SensorEvent.html#values m_reader.setX(values[0]*180/M_PI); m_reader.setY(values[1]*180/M_PI); m_reader.setZ(values[2]*180/M_PI); newReadingAvailable(); } void AndroidGyroscope::onAccuracyChanged(jint accuracy) { Q_UNUSED(accuracy) }
gpl-3.0
Konstantin-Surzhin/letsgo
jhipster-blog/src/test/javascript/spec/helpers/spyobject.ts
1586
export interface GuinessCompatibleSpy extends jasmine.Spy { /** By chaining the spy with and.returnValue, all calls to the function will return a specific * value. */ andReturn(val: any): GuinessCompatibleSpy; /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied * function. */ andCallFake(fn: Function): GuinessCompatibleSpy; /** removes all recorded calls */ reset(): void; } export class SpyObject { constructor(type?: any) { if (type) { Object.keys(type.prototype).forEach(prop => { let m = null; try { m = type.prototype[prop]; } catch (e) { // As we are creating spys for abstract classes, // these classes might have getters that throw when they are accessed. // As we are only auto creating spys for methods, this // should not matter. } if (typeof m === 'function') { this.spy(prop); } }); } } spy(name: string): GuinessCompatibleSpy { if (!this[name]) { this[name] = this.createGuinnessCompatibleSpy(name); } return this[name]; } private createGuinnessCompatibleSpy(name: string): GuinessCompatibleSpy { const newSpy: GuinessCompatibleSpy = jasmine.createSpy(name) as any; newSpy.andCallFake = newSpy.and.callFake as any; newSpy.andReturn = newSpy.and.returnValue as any; newSpy.reset = newSpy.calls.reset as any; // revisit return null here (previously needed for rtts_assert). newSpy.and.returnValue(null); return newSpy; } }
gpl-3.0
mjeanrichard/OutdoorTracker
OutdoorTracker/Controls/CurrentLocation.cs
7175
// // Outdoor Tracker - Copyright(C) 2016 Meinard Jean-Richard // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Numerics; using Windows.UI; using Windows.UI.Xaml; using Microsoft.Graphics.Canvas; using OutdoorTracker.Views.Map; using UniversalMapControl.Interfaces; namespace OutdoorTracker.Controls { public class CurrentLocation : BaseCanvasItem { public static readonly DependencyProperty LocationProperty = DependencyProperty.Register("Location", typeof(ILocation), typeof(CurrentLocation), new PropertyMetadata(default(ILocation), DependencyPropertyChanged)); public static readonly DependencyProperty AccuracyMeterProperty = DependencyProperty.Register("AccuracyMeter", typeof(double), typeof(CurrentLocation), new PropertyMetadata(default(double), DependencyPropertyChanged)); public double AccuracyMeter { get { return (double)GetValue(AccuracyMeterProperty); } set { SetValue(AccuracyMeterProperty, value); } } public static readonly DependencyProperty AccuracyTypeProperty = DependencyProperty.Register("AccuracyType", typeof(LocationAccuracy), typeof(CurrentLocation), new PropertyMetadata(LocationAccuracy.None, DependencyPropertyChanged)); public LocationAccuracy AccuracyType { get { return (LocationAccuracy)GetValue(AccuracyTypeProperty); } set { SetValue(AccuracyTypeProperty, value); } } private static async void DependencyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { await ((CurrentLocation)d).OnLayoutChanged(); } public ILocation Location { get { return (ILocation)GetValue(LocationProperty); } set { SetValue(LocationProperty, value); } } public static readonly DependencyProperty ShowAccuracyProperty = DependencyProperty.Register("ShowAccuracy", typeof(bool), typeof(CurrentLocation), new PropertyMetadata(false, DependencyPropertyChanged)); public bool ShowAccuracy { get { return (bool)GetValue(ShowAccuracyProperty); } set { SetValue(ShowAccuracyProperty, value); } } public static readonly DependencyProperty ShowCurrentPositionProperty = DependencyProperty.Register("ShowCurrentPosition", typeof(bool), typeof(CurrentLocation), new PropertyMetadata(false, DependencyPropertyChanged)); public bool ShowCurrentPosition { get { return (bool)GetValue(ShowCurrentPositionProperty); } set { SetValue(ShowCurrentPositionProperty, value); } } private static Color CreateAlphaColor(Color color, byte alpha) { return Color.FromArgb(alpha, color.R, color.G, color.B); } private bool _isGeometryValid; private Vector2 _locationVector; private float _accuracyRadius; private Color _innerCircleColor; private Color _accuracyCircleColor; private Color _outerCircleColor; public CurrentLocation() { AccuracyCircleColor = Colors.LightSkyBlue; OuterCircleColor = Colors.Yellow; HighAccuracyColor = Colors.ForestGreen; LowAccuracyColor = Colors.Orange; NoneAccuracyColor = Colors.Red; InnerCircleWidth = 3f; OuterCircleWidth = 5f; CircleRadius = 12; LocationCircleAlpha = 170; AccuracyCircleAlpha = 125; } public Color NoneAccuracyColor { get; set; } private Color HighAccuracyColor { get; set; } private Color LowAccuracyColor { get; set; } public Color AccuracyCircleColor { get; set; } public Color OuterCircleColor { get; set; } public float InnerCircleWidth { get; set; } public float OuterCircleWidth { get; set; } public float CircleRadius { get; set; } public byte LocationCircleAlpha { get; set; } public byte AccuracyCircleAlpha { get; set; } public override void InvalidateInternal() { _isGeometryValid = false; } public override void Draw(CanvasDrawingSession drawingSession, CanvasItemsLayer canvasItemsLayer) { if (!_isGeometryValid) { ILocation location = Location; if (location == null) { return; } Recalculate(canvasItemsLayer, location); } if (ShowAccuracy) { drawingSession.FillCircle(_locationVector, canvasItemsLayer.Scale(_accuracyRadius), _accuracyCircleColor); } if (ShowCurrentPosition) { drawingSession.DrawCircle(_locationVector, CircleRadius, _outerCircleColor, OuterCircleWidth); drawingSession.DrawCircle(_locationVector, CircleRadius, _innerCircleColor, InnerCircleWidth); } } private void Recalculate(CanvasItemsLayer canvasItemsLayer, ILocation location) { _accuracyCircleColor = CreateAlphaColor(AccuracyCircleColor, AccuracyCircleAlpha); _outerCircleColor = CreateAlphaColor(OuterCircleColor, LocationCircleAlpha); switch (AccuracyType) { case LocationAccuracy.High: _innerCircleColor = CreateAlphaColor(HighAccuracyColor, LocationCircleAlpha); break; case LocationAccuracy.Low: _innerCircleColor = CreateAlphaColor(LowAccuracyColor, LocationCircleAlpha); break; case LocationAccuracy.None: _innerCircleColor = CreateAlphaColor(NoneAccuracyColor, LocationCircleAlpha); break; default: throw new ArgumentOutOfRangeException(); } IProjection viewPortProjection = canvasItemsLayer.ParentMap.ViewPortProjection; _locationVector = canvasItemsLayer.Scale(viewPortProjection.ToCartesian(location)); double accuracyScale = viewPortProjection.CartesianScaleFactor(location); _accuracyRadius = Convert.ToSingle(AccuracyMeter * accuracyScale); _isGeometryValid = true; } } }
gpl-3.0
DarkSino98/Essentials
Essentials/src/com/earth2me/essentials/commands/Commandkick.java
1546
package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; import java.util.logging.Level; import org.bukkit.Server; public class Commandkick extends EssentialsCommand { public Commandkick() { super("kick"); } @Override public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } final User target = getPlayer(server, args, 0, true, false); if (sender.isPlayer()) { User user = ess.getUser(sender.getPlayer()); if (target.isHidden() && !user.isAuthorized("essentials.vanish.interact")) { throw new PlayerNotFoundException(); } if (target.isAuthorized("essentials.kick.exempt")) { throw new Exception(_("kickExempt")); } } String kickReason = args.length > 1 ? getFinalArg(args, 1) : _("kickDefault"); kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n")); target.kickPlayer(kickReason); final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; server.getLogger().log(Level.INFO, _("playerKicked", senderName, target.getName(), kickReason)); ess.broadcastMessage("essentials.kick.notify", _("playerKicked", senderName, target.getName(), kickReason)); } }
gpl-3.0
littleguy77/mupen64plus-ae
src/paulscode/android/mupen64plusae/SplashActivity.java
11302
/** * Mupen64PlusAE, an N64 emulator for the Android platform * * Copyright (C) 2012 Paul Lamb * * This file is part of Mupen64PlusAE. * * Mupen64PlusAE 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. * * Mupen64PlusAE 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 Mupen64PlusAE. If not, see <http://www.gnu.org/licenses/>. * * Authors: paulscode, lioncash, littleguy77 */ package paulscode.android.mupen64plusae; import java.io.File; import java.util.List; import org.mupen64plusae.v3.alpha.R; import paulscode.android.mupen64plusae.cheat.CheatUtils; import paulscode.android.mupen64plusae.persistent.AppData; import paulscode.android.mupen64plusae.persistent.GlobalPrefs; import paulscode.android.mupen64plusae.preference.PrefUtil; import paulscode.android.mupen64plusae.task.ExtractAssetsTask; import paulscode.android.mupen64plusae.task.ExtractAssetsTask.ExtractAssetsListener; import paulscode.android.mupen64plusae.task.ExtractAssetsTask.Failure; import paulscode.android.mupen64plusae.util.FileUtil; import paulscode.android.mupen64plusae.util.Notifier; import tv.ouya.console.api.OuyaFacade; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.view.WindowManager.LayoutParams; import android.widget.ImageView; import android.widget.TextView; /** * The main activity that presents the splash screen, extracts the assets if necessary, and launches * the main menu activity. */ public class SplashActivity extends AppCompatActivity implements ExtractAssetsListener { /** * Asset version number, used to determine stale assets. Increment this number every time the * assets are updated on disk. */ private static final int ASSET_VERSION = 73; /** The total number of assets to be extracted (for computing progress %). */ private static final int TOTAL_ASSETS = 120; /** The minimum duration that the splash screen is shown, in milliseconds. */ private static final int SPLASH_DELAY = 1000; /** PaulsCode OUYA developer UUID */ private static final String DEVELOPER_ID = "68d84579-c1e2-4418-8976-cda2692133f1"; /** * The subdirectory within the assets directory to extract. A subdirectory is necessary to avoid * extracting all the default system assets in addition to ours. */ private static final String SOURCE_DIR = "mupen64plus_data"; /** The text view that displays extraction progress info. */ private TextView mTextView; /** The running count of assets extracted. */ private int mAssetsExtracted; // App data and user preferences private AppData mAppData = null; private GlobalPrefs mGlobalPrefs = null; private SharedPreferences mPrefs = null; // These constants must match the keys used in res/xml/preferences*.xml private static final String DISPLAY_ORIENTATION = "displayOrientation"; private static final String DISPLAY_POSITION = "displayPosition"; private static final String DISPLAY_RESOLUTION = "displayResolution"; private static final String DISPLAY_SCALING = "displayScaling"; private static final String VIDEO_HARDWARE_TYPE = "videoHardwareType"; private static final String AUDIO_PLUGIN = "audioPlugin"; private static final String AUDIO_SDL_BUFFER_SIZE = "audioSDLBufferSize"; private static final String AUDIO_SLES_BUFFER_SIZE = "audioSLESBufferSize"; private static final String AUDIO_SLES_BUFFER_NBR = "audioSLESBufferNbr"; private static final String TOUCHSCREEN_STYLE = "touchscreenStyle"; private static final String TOUCHSCREEN_AUTO_HOLD = "touchscreenAutoHold"; private static final String TOUCHPAD_LAYOUT = "touchpadLayout"; private static final String NAVIGATION_MODE = "navigationMode"; /* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); // Get app data and user preferences mAppData = new AppData( this ); mGlobalPrefs = new GlobalPrefs( this ); mGlobalPrefs.enforceLocale( this ); mPrefs = PreferenceManager.getDefaultSharedPreferences( this ); // Ensure that any missing preferences are populated with defaults (e.g. preference added to // new release) PreferenceManager.setDefaultValues( this, R.xml.preferences_global, false ); // Ensure that selected plugin names and other list preferences are valid // @formatter:off Resources res = getResources(); PrefUtil.validateListPreference( res, mPrefs, DISPLAY_ORIENTATION, R.string.displayOrientation_default, R.array.displayOrientation_values ); PrefUtil.validateListPreference( res, mPrefs, DISPLAY_POSITION, R.string.displayPosition_default, R.array.displayPosition_values ); PrefUtil.validateListPreference( res, mPrefs, DISPLAY_RESOLUTION, R.string.displayResolution_default, R.array.displayResolution_values ); PrefUtil.validateListPreference( res, mPrefs, DISPLAY_SCALING, R.string.displayScaling_default, R.array.displayScaling_values ); PrefUtil.validateListPreference( res, mPrefs, VIDEO_HARDWARE_TYPE, R.string.videoHardwareType_default, R.array.videoHardwareType_values ); PrefUtil.validateListPreference( res, mPrefs, AUDIO_PLUGIN, R.string.audioPlugin_default, R.array.audioPlugin_values ); PrefUtil.validateListPreference( res, mPrefs, AUDIO_SDL_BUFFER_SIZE, R.string.audioSDLBufferSize_default, R.array.audioSDLBufferSize_values ); PrefUtil.validateListPreference( res, mPrefs, AUDIO_SLES_BUFFER_SIZE, R.string.audioSLESBufferSize_default, R.array.audioSLESBufferSize_values ); PrefUtil.validateListPreference( res, mPrefs, AUDIO_SLES_BUFFER_NBR, R.string.audioSLESBufferNbr_default, R.array.audioSLESBufferNbr_values ); PrefUtil.validateListPreference( res, mPrefs, TOUCHSCREEN_STYLE, R.string.touchscreenStyle_default, R.array.touchscreenStyle_values ); PrefUtil.validateListPreference( res, mPrefs, TOUCHSCREEN_AUTO_HOLD, R.string.touchscreenAutoHold_default, R.array.touchscreenAutoHold_values ); PrefUtil.validateListPreference( res, mPrefs, TOUCHPAD_LAYOUT, R.string.touchpadLayout_default, R.array.touchpadLayout_values ); PrefUtil.validateListPreference( res, mPrefs, NAVIGATION_MODE, R.string.navigationMode_default, R.array.navigationMode_values ); // @formatter:on // Refresh the preference data wrapper mGlobalPrefs = new GlobalPrefs( this ); // Initialize the OUYA interface if running on OUYA if( AppData.IS_OUYA_HARDWARE ) OuyaFacade.getInstance().init( this, DEVELOPER_ID ); // Initialize the toast/status bar notifier Notifier.initialize( this ); // Don't let the activity sleep in the middle of extraction getWindow().setFlags( LayoutParams.FLAG_KEEP_SCREEN_ON, LayoutParams.FLAG_KEEP_SCREEN_ON ); // Lay out the content setContentView( R.layout.splash_activity ); mTextView = (TextView) findViewById( R.id.mainText ); if( mGlobalPrefs.isBigScreenMode ) { ImageView splash = (ImageView) findViewById( R.id.mainImage ); splash.setImageResource( R.drawable.publisherlogo_ouya ); } // Extract the assets in a separate thread and launch the menu activity // Handler.postDelayed ensures this runs only after activity has resumed final Handler handler = new Handler(); handler.postDelayed( extractAssetsTaskLauncher, SPLASH_DELAY ); } /** Runnable that launches the non-UI thread from the UI thread after the activity has resumed. */ private final Runnable extractAssetsTaskLauncher = new Runnable() { @Override public void run() { if( mAppData.getAssetVersion() != ASSET_VERSION ) { // Extract and merge the assets if they are out of date FileUtil.deleteFolder( new File( mAppData.coreSharedDataDir ) ); mAssetsExtracted = 0; new ExtractAssetsTask( getAssets(), SOURCE_DIR, mAppData.coreSharedDataDir, SplashActivity.this ).execute(); } else { // Assets already extracted, just launch gallery activity, passing ROM path if it was provided externally ActivityHelper.startGalleryActivity( SplashActivity.this, getIntent().getData() ); // We never want to come back to this activity, so finish it finish(); } } }; @Override public void onExtractAssetsProgress( String nextFileToExtract ) { final float percent = ( 100f * mAssetsExtracted ) / (float) TOTAL_ASSETS; final String text = getString( R.string.assetExtractor_progress, percent, nextFileToExtract ); mTextView.setText( text ); mAssetsExtracted++; } @Override public void onExtractAssetsFinished( List<Failure> failures ) { if( failures.size() == 0 ) { // Extraction succeeded, record new asset version and merge cheats mTextView.setText( R.string.assetExtractor_finished ); mAppData.putAssetVersion( ASSET_VERSION ); CheatUtils.mergeCheatFiles( mAppData.mupencheat_default, mGlobalPrefs.customCheats_txt, mAppData.mupencheat_txt ); // Launch gallery activity, passing ROM path if it was provided externally ActivityHelper.startGalleryActivity( this, getIntent().getData() ); // We never want to come back to this activity, so finish it finish(); } else { // Extraction failed, update the on-screen text and don't start next activity String weblink = getResources().getString( R.string.assetExtractor_uriHelp ); String message = getString( R.string.assetExtractor_failed, weblink ); String textHtml = message.replace( "\n", "<br/>" ) + "<p><small>"; for( Failure failure : failures ) { textHtml += failure.toString() + "<br/>"; } textHtml += "</small>"; mTextView.setText( Html.fromHtml( textHtml ) ); } } }
gpl-3.0
jonaski/strawberry
src/settings/moodbarsettingspage.cpp
3541
/* * Strawberry Music Player * This file was part of Clementine. * Copyright 2012, David Sansome <[email protected]> * * Strawberry 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. * * Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>. * */ #include "config.h" #include <QIODevice> #include <QFile> #include <QVariant> #include <QByteArray> #include <QPixmap> #include <QPainter> #include <QSettings> #include <QCheckBox> #include <QComboBox> #include <QSize> #include "core/iconloader.h" #include "core/logging.h" #include "settingsdialog.h" #include "settingspage.h" #ifdef HAVE_MOODBAR # include "moodbar/moodbarrenderer.h" #endif #include "moodbarsettingspage.h" #include "ui_moodbarsettingspage.h" const char *MoodbarSettingsPage::kSettingsGroup = "Moodbar"; const int MoodbarSettingsPage::kMoodbarPreviewWidth = 150; const int MoodbarSettingsPage::kMoodbarPreviewHeight = 18; MoodbarSettingsPage::MoodbarSettingsPage(SettingsDialog* dialog) : SettingsPage(dialog), ui_(new Ui_MoodbarSettingsPage), initialised_(false) { ui_->setupUi(this); setWindowIcon(IconLoader::Load("moodbar")); Load(); } MoodbarSettingsPage::~MoodbarSettingsPage() { delete ui_; } void MoodbarSettingsPage::Load() { QSettings s; s.beginGroup(kSettingsGroup); ui_->moodbar_enabled->setChecked(s.value("enabled", false).toBool()); ui_->moodbar_show->setChecked(s.value("show", false).toBool()); ui_->moodbar_style->setCurrentIndex(s.value("style", 0).toInt()); ui_->moodbar_save->setChecked(s.value("save", false).toBool()); s.endGroup(); InitMoodbarPreviews(); Init(ui_->layout_moodbarsettingspage->parentWidget()); } void MoodbarSettingsPage::Save() { QSettings s; s.beginGroup(kSettingsGroup); s.setValue("enabled", ui_->moodbar_enabled->isChecked()); s.setValue("show", ui_->moodbar_show->isChecked()); s.setValue("style", ui_->moodbar_style->currentIndex()); s.setValue("save", ui_->moodbar_save->isChecked()); s.endGroup(); } void MoodbarSettingsPage::Cancel() {} void MoodbarSettingsPage::InitMoodbarPreviews() { if (initialised_) return; initialised_ = true; const QSize preview_size(kMoodbarPreviewWidth, kMoodbarPreviewHeight); ui_->moodbar_style->setIconSize(preview_size); // Read the sample data QFile file(":/mood/sample.mood"); if (!file.open(QIODevice::ReadOnly)) { qLog(Warning) << "Unable to open moodbar sample file"; return; } QByteArray file_data = file.readAll(); // Render and set each preview for (int i = 0; i < MoodbarRenderer::StyleCount; ++i) { const MoodbarRenderer::MoodbarStyle style = MoodbarRenderer::MoodbarStyle(i); const ColorVector colors = MoodbarRenderer::Colors(file_data, style, palette()); QPixmap pixmap(preview_size); QPainter p(&pixmap); MoodbarRenderer::Render(colors, &p, pixmap.rect()); p.end(); ui_->moodbar_style->addItem(MoodbarRenderer::StyleName(style)); ui_->moodbar_style->setItemData(i, pixmap, Qt::DecorationRole); } }
gpl-3.0
georchestra/georchestra
console/src/main/java/org/georchestra/console/ws/utils/Validation.java
6523
/* * Copyright (C) 2009 by the geOrchestra PSC * * This file is part of geOrchestra. * * geOrchestra 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. * * geOrchestra 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 * geOrchestra. If not, see <http://www.gnu.org/licenses/>. */ package org.georchestra.console.ws.utils; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONException; import org.json.JSONObject; import org.springframework.util.StringUtils; import org.springframework.validation.Errors; /** * Validation class for user and org forms * * Possible values: * * * There are hardcoded mandatory fields for user and organizations creation: * * mandatory user fields: * email * uid * password * confirmPassword * * mandatory org fields: * name * */ public class Validation { private Set<String> requiredUserFields; private Set<String> requiredOrgFields; /** * Create a validation class with field list formated as comma separated list. * List can contains spaces. * * @param requiredFields comma separated list of required fields (ex: "surname, * orgType, orgAddress") */ public Validation(String requiredFields) { String[] configuredFields = requiredFields.split("\\s*,\\s*"); this.requiredUserFields = new HashSet<String>(); this.requiredOrgFields = new HashSet<String>(); // Add mandatory fields for user this.requiredUserFields.add("email"); this.requiredUserFields.add("uid"); this.requiredUserFields.add("password"); this.requiredUserFields.add("confirmPassword"); // Add mandatory field for org this.requiredOrgFields.add("name"); this.requiredOrgFields.add("shortName"); this.requiredOrgFields.add("type"); // Extract all fields starting by Org and change next letter to lower case // orgShortName --> shortName Pattern regexp = Pattern.compile("^org([A-Z].*)$"); for (String field : configuredFields) { field = field.trim(); if (field.length() == 0) continue; Matcher m = regexp.matcher(field); if (m.matches()) { // This is a org field, so remove 'org' prefix String match = m.group(1); match = match.substring(0, 1).toLowerCase() + match.substring(1); this.requiredOrgFields.add(match); } else { // This is a user field this.requiredUserFields.add(field); } } } /** * Return a set of required fields for user creation or update * * @return a Set that contains all required fields for user forms. */ public Set<String> getRequiredUserFields() { return this.requiredUserFields; } /** * Return a set of required fields for organization creation or update * * @return a Set that contains all required fields for organization forms. */ public Set<String> getRequiredOrgFields() { return this.requiredOrgFields; } /** * Return true if specified field is required for user creation or update * * @param field field to check requirement * @return true id 'field' is required for user forms */ public boolean isUserFieldRequired(String field) { return this.requiredUserFields.contains(field); } /** * Return true if specified field is required for organization creation or * update * * @param field field to check requirement * @return true id 'field' is required for organization forms */ public boolean isOrgFieldRequired(String field) { return this.requiredOrgFields.contains(field); } public void validateUserField(String field, String value, Errors errors) { if (!validateUserField(field, value)) errors.rejectValue(field, "error.required", "required"); } public boolean validateUserFieldWithSpecificMsg(String field, String value, Errors errors) { if (!validateUserField(field, value)) { errors.rejectValue(field, String.format("%s.error.required", field), "required"); return false; } return true; } protected boolean validateUserField(String field, String value) { return !this.isUserFieldRequired(field) || StringUtils.hasLength(value); } public void validatePrivacyPolicyAgreedField(boolean value, Errors errors) { if (!value) errors.rejectValue("privacyPolicyAgreed", "error.required", "required"); } public boolean validateOrgField(String field, JSONObject json) { try { return !this.isOrgFieldRequired(field) || (json.has(field) && StringUtils.hasLength(json.getString(field))); } catch (JSONException e) { return false; } } public void validateOrgField(String field, String value, Errors errors) { if (!validateOrgField(field, value)) { errors.rejectValue(String.format("org%s", StringUtils.capitalize(field)), "error.required", "required"); } } public boolean validateOrgField(String field, String value) { return !this.isOrgFieldRequired(field) || StringUtils.hasLength(value); } public boolean validateUrl(String value) { if (value == null || value.length() == 0) { return true; } try { new URL(value); return true; } catch (MalformedURLException e) { return false; } } public boolean validateUrlFieldWithSpecificMsg(String fullyQualifiedField, String value, Errors errors) { if (!validateUrl(value)) { errors.rejectValue(fullyQualifiedField, "error.badUrl", "badUrl"); return false; } return true; } }
gpl-3.0
drslump/sdb
src/Commands/ResetCommand.cs
1393
/* * SDB - Mono Soft Debugger Client * Copyright 2013 Alex Rønne Petersen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System.Collections.Generic; namespace Mono.Debugger.Client.Commands { sealed class ResetCommand : Command { public override string[] Names { get { return new[] { "reset" }; } } public override string Summary { get { return "Reset inferior environment variables, arguments, etc."; } } public override string Syntax { get { return "reset"; } } public override void Process(string args) { Debugger.Reset(); Configuration.Apply(); Log.Info("All debugger state reset"); } } }
gpl-3.0
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Core/System/Linq/Parallel/IntersectQueryOperator`1.cs
10624
// Decompiled with JetBrains decompiler // Type: System.Linq.Parallel.IntersectQueryOperator`1 // Assembly: System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: BA37026F-1371-4849-854A-E2CCE7CAD02B // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Core.dll using System; using System.Collections.Generic; using System.Linq; using System.Runtime; using System.Threading; namespace System.Linq.Parallel { internal sealed class IntersectQueryOperator<TInputOutput> : BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput> { private readonly IEqualityComparer<TInputOutput> m_comparer; internal override bool LimitsParallelism { get { return false; } } internal IntersectQueryOperator(ParallelQuery<TInputOutput> left, ParallelQuery<TInputOutput> right, IEqualityComparer<TInputOutput> comparer) : base(left, right) { this.m_comparer = comparer; this.m_outputOrdered = this.LeftChild.OutputOrdered; this.SetOrdinalIndex(OrdinalIndexState.Shuffled); } internal override QueryResults<TInputOutput> Open(QuerySettings settings, bool preferStriping) { return (QueryResults<TInputOutput>) new BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput>.BinaryQueryOperatorResults(this.LeftChild.Open(settings, false), this.RightChild.Open(settings, false), (BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput>) this, settings, false); } public override void WrapPartitionedStream<TLeftKey, TRightKey>(PartitionedStream<TInputOutput, TLeftKey> leftPartitionedStream, PartitionedStream<TInputOutput, TRightKey> rightPartitionedStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, bool preferStriping, QuerySettings settings) { if (this.OutputOrdered) this.WrapPartitionedStreamHelper<TLeftKey, TRightKey>(ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TLeftKey>(leftPartitionedStream, (Func<TInputOutput, NoKeyMemoizationRequired>) null, (IEqualityComparer<NoKeyMemoizationRequired>) null, this.m_comparer, settings.CancellationState.MergedCancellationToken), rightPartitionedStream, outputRecipient, settings.CancellationState.MergedCancellationToken); else this.WrapPartitionedStreamHelper<int, TRightKey>(ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TLeftKey>(leftPartitionedStream, (Func<TInputOutput, NoKeyMemoizationRequired>) null, (IEqualityComparer<NoKeyMemoizationRequired>) null, this.m_comparer, settings.CancellationState.MergedCancellationToken), rightPartitionedStream, outputRecipient, settings.CancellationState.MergedCancellationToken); } private void WrapPartitionedStreamHelper<TLeftKey, TRightKey>(PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftHashStream, PartitionedStream<TInputOutput, TRightKey> rightPartitionedStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, CancellationToken cancellationToken) { int partitionCount = leftHashStream.PartitionCount; PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, int> partitionedStream1 = ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TRightKey>(rightPartitionedStream, (Func<TInputOutput, NoKeyMemoizationRequired>) null, (IEqualityComparer<NoKeyMemoizationRequired>) null, this.m_comparer, cancellationToken); PartitionedStream<TInputOutput, TLeftKey> partitionedStream2 = new PartitionedStream<TInputOutput, TLeftKey>(partitionCount, leftHashStream.KeyComparer, OrdinalIndexState.Shuffled); for (int index = 0; index < partitionCount; ++index) partitionedStream2[index] = !this.OutputOrdered ? (QueryOperatorEnumerator<TInputOutput, TLeftKey>) new IntersectQueryOperator<TInputOutput>.IntersectQueryOperatorEnumerator<TLeftKey>(leftHashStream[index], partitionedStream1[index], this.m_comparer, cancellationToken) : (QueryOperatorEnumerator<TInputOutput, TLeftKey>) new IntersectQueryOperator<TInputOutput>.OrderedIntersectQueryOperatorEnumerator<TLeftKey>(leftHashStream[index], partitionedStream1[index], this.m_comparer, leftHashStream.KeyComparer, cancellationToken); outputRecipient.Receive<TLeftKey>(partitionedStream2); } internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { return Enumerable.Intersect<TInputOutput>(CancellableEnumerable.Wrap<TInputOutput>(this.LeftChild.AsSequentialQuery(token), token), CancellableEnumerable.Wrap<TInputOutput>(this.RightChild.AsSequentialQuery(token), token), this.m_comparer); } private class IntersectQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, int> { private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> m_leftSource; private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, int> m_rightSource; private IEqualityComparer<TInputOutput> m_comparer; private Set<TInputOutput> m_hashLookup; private CancellationToken m_cancellationToken; private Shared<int> m_outputLoopCount; [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] internal IntersectQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftSource, QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, int> rightSource, IEqualityComparer<TInputOutput> comparer, CancellationToken cancellationToken) { this.m_leftSource = leftSource; this.m_rightSource = rightSource; this.m_comparer = comparer; this.m_cancellationToken = cancellationToken; } internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey) { if (this.m_hashLookup == null) { this.m_outputLoopCount = new Shared<int>(0); this.m_hashLookup = new Set<TInputOutput>(this.m_comparer); Pair<TInputOutput, NoKeyMemoizationRequired> currentElement1 = new Pair<TInputOutput, NoKeyMemoizationRequired>(); int currentKey1 = 0; int num = 0; while (this.m_rightSource.MoveNext(ref currentElement1, ref currentKey1)) { if ((num++ & 63) == 0) CancellationState.ThrowIfCanceled(this.m_cancellationToken); this.m_hashLookup.Add(currentElement1.First); } } Pair<TInputOutput, NoKeyMemoizationRequired> currentElement2 = new Pair<TInputOutput, NoKeyMemoizationRequired>(); TLeftKey currentKey2 = default (TLeftKey); while (this.m_leftSource.MoveNext(ref currentElement2, ref currentKey2)) { if ((this.m_outputLoopCount.Value++ & 63) == 0) CancellationState.ThrowIfCanceled(this.m_cancellationToken); if (this.m_hashLookup.Contains(currentElement2.First)) { this.m_hashLookup.Remove(currentElement2.First); currentElement = currentElement2.First; return true; } } return false; } protected override void Dispose(bool disposing) { this.m_leftSource.Dispose(); this.m_rightSource.Dispose(); } } private class OrderedIntersectQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, TLeftKey> { private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> m_leftSource; private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, int> m_rightSource; private IEqualityComparer<Wrapper<TInputOutput>> m_comparer; private IComparer<TLeftKey> m_leftKeyComparer; private Dictionary<Wrapper<TInputOutput>, Pair<TInputOutput, TLeftKey>> m_hashLookup; private CancellationToken m_cancellationToken; internal OrderedIntersectQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftSource, QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, int> rightSource, IEqualityComparer<TInputOutput> comparer, IComparer<TLeftKey> leftKeyComparer, CancellationToken cancellationToken) { this.m_leftSource = leftSource; this.m_rightSource = rightSource; this.m_comparer = (IEqualityComparer<Wrapper<TInputOutput>>) new WrapperEqualityComparer<TInputOutput>(comparer); this.m_leftKeyComparer = leftKeyComparer; this.m_cancellationToken = cancellationToken; } internal override bool MoveNext(ref TInputOutput currentElement, ref TLeftKey currentKey) { int num = 0; if (this.m_hashLookup == null) { this.m_hashLookup = new Dictionary<Wrapper<TInputOutput>, Pair<TInputOutput, TLeftKey>>(this.m_comparer); Pair<TInputOutput, NoKeyMemoizationRequired> currentElement1 = new Pair<TInputOutput, NoKeyMemoizationRequired>(); TLeftKey currentKey1 = default (TLeftKey); while (this.m_leftSource.MoveNext(ref currentElement1, ref currentKey1)) { if ((num++ & 63) == 0) CancellationState.ThrowIfCanceled(this.m_cancellationToken); Wrapper<TInputOutput> key = new Wrapper<TInputOutput>(currentElement1.First); Pair<TInputOutput, TLeftKey> pair; if (!this.m_hashLookup.TryGetValue(key, out pair) || this.m_leftKeyComparer.Compare(currentKey1, pair.Second) < 0) this.m_hashLookup[key] = new Pair<TInputOutput, TLeftKey>(currentElement1.First, currentKey1); } } Pair<TInputOutput, NoKeyMemoizationRequired> currentElement2 = new Pair<TInputOutput, NoKeyMemoizationRequired>(); int currentKey2 = 0; while (this.m_rightSource.MoveNext(ref currentElement2, ref currentKey2)) { if ((num++ & 63) == 0) CancellationState.ThrowIfCanceled(this.m_cancellationToken); Pair<TInputOutput, TLeftKey> pair; if (this.m_hashLookup.TryGetValue(new Wrapper<TInputOutput>(currentElement2.First), out pair)) { currentElement = pair.First; currentKey = pair.Second; this.m_hashLookup.Remove(new Wrapper<TInputOutput>(pair.First)); return true; } } return false; } protected override void Dispose(bool disposing) { this.m_leftSource.Dispose(); this.m_rightSource.Dispose(); } } } }
gpl-3.0
EPSZ-DAW2/daw2-2016-actividades-y-eventos
basic/views/Etiquetas/_search.php
630
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\EtiquetasSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="etiquetas-search"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?= $form->field($model, 'id') ?> <?= $form->field($model, 'nombre') ?> <div class="form-group"> <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?> <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div>
gpl-3.0
Jose3212/Bork
Bork v1.0/include/jugador.hpp
1016
#ifndef _JUGADOR #define _JUGADOR #include <string> #include <algorithm> #include <vector> #include "mensaje.hpp" class Jugador{ private: string nombre; Mensaje jugador_mensaje; vector <Objeto> inventario; Objeto equipado; int num_tesoros = 0; int max_obj = 5; int hp = 50; int ataque = 2; public: Jugador(){}; Jugador(string nombre){this->nombre=nombre;inventario.reserve(max_obj);} enum acciones{ LUCHA,HUYE,NADA,ABRE,USA }; enum movimiento{ ADELANTE=0,RETROCEDE=1,GIRA_IZQUIERDA=2,GIRA_DERECHA=3 }; void pierde(); void aniade_a_inventario(Objeto o1); void aniade_tesoro(){num_tesoros++;} void elimina_de_inventario(int posicion); void equipa(Objeto o1); void usar(Objeto o1); string get_nombre(); vector<Objeto> get_inventario(){return inventario;} int get_hp(){return hp;} int get_tesoros(){return num_tesoros;} Objeto get_equipo(){return equipado;} int get_ataque(){return ataque;} }; #endif
gpl-3.0
talek69/curso
109-dominion-test/src/com/dominion/dbunit/ExportarDatos.java
2273
package com.dominion.dbunit; import java.io.FileOutputStream; import java.sql.Connection; import java.sql.DriverManager; import org.dbunit.database.DatabaseConnection; import org.dbunit.database.IDatabaseConnection; import org.dbunit.database.QueryDataSet; import org.dbunit.database.search.TablesDependencyHelper; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSet; @SuppressWarnings("rawtypes") public abstract class ExportarDatos { private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DB_URL = "jdbc:oracle:thin:@a3-server:1521:XE"; private static final String DB_USUARIO = "master"; private static final String DB_PASSWORD = "master"; private static Connection jdbcConnection = null; private static IDatabaseConnection dbunitConnection = null; static { try { @SuppressWarnings("unused") Class driverClass = Class.forName(DB_DRIVER); jdbcConnection = DriverManager.getConnection(DB_URL, DB_USUARIO, DB_PASSWORD); dbunitConnection = new DatabaseConnection(jdbcConnection); } catch (Exception e) { e.printStackTrace(); } } public static void exportar_Tabla(String nombre_tabla, String fichero_salida) throws Exception { QueryDataSet conjunto_datosparciales = new QueryDataSet(dbunitConnection); conjunto_datosparciales.addTable(nombre_tabla); FlatXmlDataSet.write(conjunto_datosparciales, new FileOutputStream(fichero_salida)); } public static void exportar_TablaConCondicion(String nombre_tabla, String fichero_salida, String condicion) throws Exception { QueryDataSet conjunto_datosparciales = new QueryDataSet(dbunitConnection); conjunto_datosparciales.addTable(nombre_tabla, condicion); FlatXmlDataSet.write(conjunto_datosparciales, new FileOutputStream(fichero_salida)); } public void exportar_TablaConDependencias(String nombre_tabla, String fichero_salida) throws Exception { String[] tablas_relacionadas; tablas_relacionadas = TablesDependencyHelper.getAllDependentTables(dbunitConnection, nombre_tabla); IDataSet conjunto_datos = dbunitConnection.createDataSet(tablas_relacionadas); FlatXmlDataSet.write(conjunto_datos, new FileOutputStream(fichero_salida)); } }
gpl-3.0
ushainformatique/whatacart
protected/common/modules/catalog/modules/products/dao/ReviewDAO.php
1676
<?php /** * @copyright Copyright (C) 2016 Usha Singhai Neo Informatique Pvt. Ltd * @license https://www.gnu.org/licenses/gpl-3.0.html */ namespace products\dao; use usni\UsniAdaptor; use yii\caching\DbDependency; /** * Implements data access functionality related to product reviews * * @package products\dao */ class ReviewDAO extends \yii\base\Component { /** * Get product review * @param int $reviewId * @param string $language * @return array */ public static function getReview($reviewId, $language) { $reviewTableName = UsniAdaptor::tablePrefix() . 'product_review'; $reviewTrTableName = UsniAdaptor::tablePrefix() . 'product_review_translated'; $productTableName = UsniAdaptor::tablePrefix() . 'product'; $productTrTableName = UsniAdaptor::tablePrefix() . 'product_translated'; $dependency = new DbDependency(['sql' => "SELECT MAX(modified_datetime) FROM $reviewTableName"]); $sql = "SELECT pr.*, prt.review, ptt.name AS product_name FROM $reviewTableName pr, $reviewTrTableName prt, $productTableName pt, $productTrTableName ptt WHERE pr.id = :id AND pr.id = prt.owner_id AND prt.language = :lan1 AND pr.product_id = pt.id AND pt.id = ptt.owner_id AND ptt.language = :lan2 "; $connection = UsniAdaptor::app()->getDb(); return $connection->createCommand($sql, [':id' => $reviewId, ':lan1' => $language, ':lan2' => $language])->cache(0, $dependency)->queryOne(); } }
gpl-3.0
dskvr/Graffitar
prototype/dep/graffitar-ORIGINAL.php
8248
<?php //RE: All you see is crime include 'config.php'; $mtime = microtime(); $mtime = explode(' ', $mtime); $mtime = $mtime[1] + $mtime[0]; $starttime = $mtime; include('gml.php'); include('smooth-line.php'); $random = $_GET['random_gmlid']; /**/ function random_gml(){ global $random; return black_book_feed($random); } function black_book_feed($id){ return 'http://000000book.com/data/'.$id.'.gml'; } function get_points($drawing, $multi_stroke){ // global $drawing, $multi_stroke; if($multi_stroke) : $x = $drawing['stroke'][$stroke_i]['pt'][$i]['x']; $y = $drawing['stroke'][$stroke_i]['pt'][$i]['y']; else : $x = $drawing['stroke']['pt'][$i]['x']; $y = $drawing['stroke']['pt'][$i]['y']; endif; $p = array('x' => $x, 'y' => $y); return $p; } function round_rec($img, $x1, $y1, $x2, $y2, $radius, $color,$filled=1) { if ($filled==1){ imagefilledrectangle($img, $x1+$radius, $y1, $x2-$radius, $y2, $color); imagefilledrectangle($img, $x1, $y1+$radius, $x1+$radius-1, $y2-$radius, $color); imagefilledrectangle($img, $x2-$radius+1, $y1+$radius, $x2, $y2-$radius, $color); imagefilledarc($img,$x1+$radius, $y1+$radius, $radius*2, $radius*2, 180 , 270, $color, IMG_ARC_PIE); imagefilledarc($img,$x2-$radius, $y1+$radius, $radius*2, $radius*2, 270 , 360, $color, IMG_ARC_PIE); imagefilledarc($img,$x1+$radius, $y2-$radius, $radius*2, $radius*2, 90 , 180, $color, IMG_ARC_PIE); imagefilledarc($img,$x2-$radius, $y2-$radius, $radius*2, $radius*2, 360 , 90, $color, IMG_ARC_PIE); }else{ imageline($img, $x1+$radius, $y1, $x2-$radius, $y1, $color); imageline($img, $x1+$radius, $y2, $x2-$radius, $y2, $color); imageline($img, $x1, $y1+$radius, $x1, $y2-$radius, $color); imageline($img, $x2, $y1+$radius, $x2, $y2-$radius, $color); imagearc($img,$x1+$radius, $y1+$radius, $radius*2, $radius*2, 180 , 270, $color); imagearc($img,$x2-$radius, $y1+$radius, $radius*2, $radius*2, 270 , 360, $color); imagearc($img,$x1+$radius, $y2-$radius, $radius*2, $radius*2, 90 , 180, $color); imagearc($img,$x2-$radius, $y2-$radius, $radius*2, $radius*2, 360 , 90, $color); } } /*Colors!*/ //Bg $bg_color = (isset($_GET['bgc']) && $_GET['bgc']) ? $_GET['bgc'] : BGRGB; $bg_rgb = explode(',',$bg_color); //Shadow $sh_color = (isset($_GET['shc']) && $_GET['shc']) ? $_GET['shc'] : false; $sh_rgb = explode(',',$sh_color); //Stroke $sw = (isset($_GET['sw']) && $_GET['sw']) ? $_GET['sw'] : STROKEWIDTH; $stroke_color = (isset($_GET['sc']) && $_GET['sc']) ? $_GET['sc'] : STROKERGB; $stroke_rgb = explode(',',$stroke_color); $force_shadow = (empty($_GET['gml']) || $_GET['random'] == 'on') ? false : true; if( $_GET['random'] == 'on') : $load = random_gml(); $gmlid = $random; elseif(!empty($_GET['gmlid'])) : $load = black_book_feed($_GET['gmlid']); $gmlid = $_GET['gmlid']; else : $load = (!empty($_GET['gml'])) ? $_GET['gml'] : '1love.gml'; endif; $gml = new GML($load); /* echo '<pre>'; print_r($gml); die(); */ //$rotate = ($gml->gml['tag']['header']['client']['username'] == 'FatTag') ? true : false; $imw = (isset($gml->gml['tag']['environment']['screenBounds']['x'])) ? $gml->gml['tag']['environment']['screenBounds']['x'] : 1020; $imh = (isset($gml->gml['tag']['environment']['screenBounds']['y'])) ? $gml->gml['tag']['environment']['screenBounds']['y'] : 768; $drawing = $gml->gml['tag']['drawing']; $multi_stroke = (count($drawing['stroke']) > 1) ? true : false; //print_r($gml->gml->tag->drawing->stroke->pt); //exit; header ("Content-type: image/png"); $canvas = ImageCreate ($imw, $imh) or die ("Cannot Initialize new GD image stream"); //Canvas Resource imageantialias($canvas, true); $background_color = ImageColorAllocate ($canvas, $bg_rgb[0],$bg_rgb[1],$bg_rgb[2]); $text_color = ImageColorAllocate ($canvas, $stroke_rgb[0], $stroke_rgb[1], $stroke_rgb[2]); $data_background_color = ImageColorAllocateAlpha ($canvas, 255, 255, 255, 70); $total_strokes = count($drawing['stroke']); $total_points = 0; /* if((bool) $gml->gml['tag']['environment']['up']['x'] == 1) : $tagw = $imh; $tagh = $imw; // $rotate = true; else : $tagw = $imw; $tagh = $imh; endif; */ $tagw = $imw; $tagh = $imh; $tag = ImageCreate($tagw, $tagh) or die('shit muffins.'); imageantialias($tag, true); $background_color = ImageColorAllocate ($tag, $bg_rgb[0],$bg_rgb[1],$bg_rgb[2]); $stroke_color = ImageColorAllocate ($tag, $stroke_rgb[0], $stroke_rgb[1], $stroke_rgb[2]); $shadow_color = (!empty($sh_rgb)) ? ImageColorAllocate ($tag, $sh_rgb[0], $sh_rgb[1], $sh_rgb[2]) : ImageColorAllocateAlpha ($tag, $stroke_rgb[0], $stroke_rgb[1], $stroke_rgb[2], 70); for($stroke_i=0;$stroke_i<$total_strokes;$stroke_i++) : if($multi_stroke) : $t = count($drawing['stroke'][$stroke_i]['pt']); else : $t = count($drawing['stroke']['pt']); endif; $total_points = $total_points + $t; //Do Shadows First if($_GET['shadow'] == 'on' || $force_shadow === true) : for($i=0;$i<$t;$i++) : if($multi_stroke) : $x = $drawing['stroke'][$stroke_i]['pt'][$i]['x']; $y = $drawing['stroke'][$stroke_i]['pt'][$i]['y']; else : $x = $drawing['stroke']['pt'][$i]['x']; $y = $drawing['stroke']['pt'][$i]['y']; endif; if($i == 0) : $x_1 = $x*$imw; $y_1 = $y*$imh; else : $x_2 = $x*$imw; $y_2 = $y*$imh; // $gml->mop($im,$x_1+6,$y_1+6,$x_2+6,$y_2+6,$shadow6 1); $shadow_value = 150; $shadow_pos = $sw-1; $shadow_spread = (!empty($_GET['ss'])) ? $_GET['ss'] : SHSPREAD; $shadow_distance = (!empty($_GET['sd']) && (int) $_GET['sd'] < 75) ? $_GET['sd'] : SHDIST; $gradient_progression = round(100/$shadow_distance); $gradient_progression = ($gradient_progression < 255) ? $gradient_progression : 255; // $shadow_color = ImageColorAllocateAlpha ($im, $shadow_value, $shadow_value, $shadow_value ); for($shadow_i=0;$shadow_i<$shadow_distance;$shadow_i++) : //$this_line_value = $gradient_progression * $shadow_i; //$shadow_color = ImageColorAllocate ($im,$this_line_value,$this_line_value,$this_line_value); $shadow_pos = $shadow_i; $spread = $sw-($shadow_pos*$shadow_spread); $sx1 = $x_1-$spread; $sy1 = $y_1-$spread; $sx2 = $x_2-$spread; $sy2 = $y_2-$spread; $gml->mop($tag,$sx1,$sy1,$sx2,$sy2,$shadow_color,1); endfor; //Next. $x_1 = $x_2; $y_1 = $y_2; endif; endfor; endif; //Now for the main attraction. for($i=0;$i<$t;$i++) : if($multi_stroke) : $x = $drawing['stroke'][$stroke_i]['pt'][$i]['x']; $y = $drawing['stroke'][$stroke_i]['pt'][$i]['y']; else : $x = $drawing['stroke']['pt'][$i]['x']; $y = $drawing['stroke']['pt'][$i]['y']; endif; if((bool) $gml->gml['tag']['environment']['up']['x'] == 1) GML::flipXY($x,$y); if($i == 0) : $x_1 = $x*$imw; $y_1 = $y*$imh; else : $x_2 = $x*$imw; $y_2 = $y*$imh; //Dropping the bomb for($s=0;$s<$sw;$s++) : $gml->mop($tag,$x_1-$s,$y_1-$s,$x_2-$s,$y_2-$s,$stroke_color,2); endfor; //... as if it were in fashion. $x_1 = $x_2; $y_1 = $y_2; endif; // $im = imageSmoothAlphaLine ($im, $x_1-$s, $y_1-$s, $x_2-$s, $y_2-$s, 0, 0, 0); endfor; //end points endfor; //end strokes //Rotate the image if rotate = true (before adding txt!) //if($rotate) $tag = imagerotate($tag, 90, 0); imagecopymerge($canvas,$tag,1,1,1,1,$imw,$imh,100); //Stats Box round_rec($canvas, 5, $imh-5, $imw-5, $imh-15-5, 0, $data_background_color); //000BOOK! YESYES. if(isset($gmlid)) : imagestring ($canvas, 1, 10, $imh-15, '000Book.com/data/'.$gmlid, $text_color); endif; $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $endtime = $mtime; $totaltime = ($endtime - $starttime); //Stats imagestring ($canvas, 1, $imw/2-120, $imh-15, $total_strokes.' Strokes '.$total_points.' Points & generated in '.round($totaltime,2).' seconds.', $text_color); //GRAFFITAR! YESYES. imagestring ($canvas, 1, $imw-110, $imh-15, 'GRAFFITAR '.version.' BETA', $text_color); ImagePng ($canvas); /* echo '0.118750x1028 = '.(0.118750*1028).'<br />'; echo '1.118750x1028 = '.(1.118750*1028); */ // ... in the source code. ?>
gpl-3.0
hlim/studio
alfresco-svcs/src/main/java/org/craftercms/cstudio/alfresco/dm/to/DmOrderTO.java
2705
/******************************************************************************* * Crafter Studio Web-content authoring solution * Copyright (C) 2007-2013 Crafter Software Corporation. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.craftercms.cstudio.alfresco.dm.to; /** * This class represents the sorting order of DM Content Item * * @author hyanghee * @author Dejan Brkic * */ public class DmOrderTO implements Comparable<DmOrderTO> { protected String _id; protected double _order; protected String _name; protected String _disabled; protected String _placeInNav; /** * default constructor */ public DmOrderTO() { } /** * copy constructor * * @param order */ public DmOrderTO(DmOrderTO order) { this._id = order._id; this._order = order._order; this._name = order._name; this._disabled = order._disabled; this._placeInNav = order._placeInNav; } public String getId() { return _id; } public void setId(String id) { this._id = id; } public double getOrder() { return _order; } public void setOrder(double order) { this._order = order; } public String getName() { return _name; } public void setName(String name) { this._name = name; } public String getDisabled() { return _disabled; } public void setDisabled(String disabled) { this._disabled = disabled; } public String getPlaceInNav() { return _placeInNav; } public void setPlaceInNav(String placeInNav) { this._placeInNav = placeInNav; } @Override public int compareTo(DmOrderTO o) { if (this.getOrder() > o.getOrder()) { return 1; } else if (this.getOrder() == o.getOrder()) { return 0; } else { return -1; } } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DmOrderTO other = (DmOrderTO) obj; if (!_id.equals(other._id)) return false; return true; } }
gpl-3.0
EterniaLogic/TekkitRestrict
EEPatch_TR/src/ee/ItemRedKatar.java
16830
package ee; import java.util.*; import ee.events.EEEventManager; import ee.events.EEEnums.EEAction; import ee.events.EEEnums.EEAction2; import ee.events.rm.EERedKatarEvent; import net.minecraft.server.*; public class ItemRedKatar extends ItemRedTool { protected ItemRedKatar(int var1) { super(var1, 4, 18, blocksEffectiveAgainst); } public boolean a(ItemStack item, int id, int x, int y, int z, EntityLiving var6) { boolean var7 = false; if (!EEMaps.isLeaf(id) && id != Block.WEB.id && id != Block.VINE.id && id != BlockFlower.LONG_GRASS.id && id != BlockFlower.DEAD_BUSH.id) var7 = true; if (!var7) EEProxy.dropBlockAsItemStack(Block.byId[id], var6, x, y, z, new ItemStack(id, 1, id != Block.LEAVES.id ? ((int) (((ItemEECharged) item.getItem()).getShort(item, "lastMeta"))) : ((ItemEECharged) item.getItem()).getShort(item, "lastMeta") & 3)); return super.a(item, id, x, y, z, var6); } public boolean canDestroySpecialBlock(Block var1) { return var1.id == Block.WEB.id; } public boolean ConsumeReagent(int var1, ItemStack item, EntityHuman entityPlayer, boolean var4) { if (getFuelRemaining(item) >= 16) { setFuelRemaining(item, getFuelRemaining(item) - 16); return true; } int var5 = getFuelRemaining(item); while (getFuelRemaining(item) < 16) { ConsumeReagent(item, entityPlayer, var4); if (var5 == getFuelRemaining(item)) break; var5 = getFuelRemaining(item); if (getFuelRemaining(item) >= 16) { setFuelRemaining(item, getFuelRemaining(item) - 16); return true; } } return false; } public float getStrVsBlock(ItemStack item, Block var2, int var3) { if (getShort(item, "lastMeta") != var3) setShort(item, "lastMeta", var3); if (var2.id != Block.VINE.id && var2.id != Block.LEAVES.id && var2.id != Block.WEB.id) { if (var2.id == Block.WOOL.id) return 5F; if (var2.material != Material.EARTH && var2.material != Material.GRASS) { return var2.material != Material.WOOD ? super.getDestroySpeed(item, var2) : 18F + chargeLevel(item) * 2; } else { float var4 = 18F + chargeLevel(item) * 4; return var4; } } else { return 15F; } } /** Attacks mobs in a range */ public void doSwordBreak(ItemStack item, World var2, EntityHuman var3) { if (chargeLevel(item) > 0) { boolean var4 = false; int var5; for (var5 = 1; var5 <= chargeLevel(item); var5++) { if (var5 == chargeLevel(item)) var4 = true; if (ConsumeReagent(1, item, var3, var4)) continue; var5--; break; } if (var5 < 1) return; var3.C_(); var2.makeSound(var3, "flash", 0.8F, 1.5F); List<Entity> var6 = var2.getEntities(var3, AxisAlignedBB.b((float) var3.locX - (var5 / 1.5D + 2D), var3.locY - (var5 / 1.5D + 2D), (float) var3.locZ - (var5 / 1.5D + 2D), (float) var3.locX + var5 / 1.5D + 2D, var3.locY + var5 / 1.5D + 2D, (float) var3.locZ + var5 / 1.5D + 2D)); for (int var7 = 0; var7 < var6.size(); var7++) { Entity var8 = var6.get(var7); if (((var8 instanceof EntityLiving) && (EEBase.getSwordMode(var3)) || (var8 instanceof EntityMonster))) { var8.damageEntity(DamageSource.playerAttack(var3), weaponDamage + chargeLevel(item) * 2); } } } } //private long delay = 0; public boolean interactWith(ItemStack item, EntityHuman human, World world, int x, int y, int z, int var7) { if (EEProxy.isClient(world)) return false; //if (human.getBukkitEntity().hasPermission("eepatch.delay") && delay > System.currentTimeMillis()){ // return false; //} //delay = System.currentTimeMillis()+1000*5; int id = world.getTypeId(x, y, z); chargeLevel(item); if (EEMaps.isLeaf(id) || id == Block.WEB.id || id == Block.VINE.id || id == longGrass || id == bush){ if (EEEventManager.callEvent(new EERedKatarEvent(item, EEAction.RIGHTCLICK, human, x, y, z, EEAction2.BreakRadius))) return false; onItemUseShears(item, human, world, x, y, z, var7); } else if ((id == Block.DIRT.id || id == Block.GRASS.id) && world.getTypeId(x, y + 1, z) == 0){ //Event in method. onItemUseHoe(item, human, world, x, y, z, var7); } else if (EEMaps.isWood(id)){ if (EEEventManager.callEvent(new EERedKatarEvent(item, EEAction.RIGHTCLICK, human, x, y, z, EEAction2.BreakRadius))) return false; onItemUseAxe(item, human, world, x, y, z, var7); } return false; } public boolean onItemUseShears(ItemStack item, EntityHuman var2, World var3, int x, int y, int z, int var7) { int charge = chargeLevel(item); if (charge < 1) return false; //boolean var8 = false; cleanDroplist(item); var2.C_(); var3.makeSound(var2, "flash", 0.8F, 1.5F); for (int var9 = -(charge + 2); var9 <= charge + 2; var9++) { for (int var10 = -(charge + 2); var10 <= charge + 2; var10++) { for (int var11 = -(charge + 2); var11 <= charge + 2; var11++) { int id = var3.getTypeId(x + var9, y + var10, z + var11); int nx = x + var9; int ny = y + var10; int nz = z + var11; if ((EEMaps.isLeaf(id) || id == Block.VINE.id || id == Block.WEB.id || id == longGrass || id == bush) && attemptBreak(var2, nx, ny, nz)) { if (getFuelRemaining(item) < 1) ConsumeReagent(item, var2, false); if (getFuelRemaining(item) > 0) { int data = var3.getData(nx, ny, nz); if (!EEMaps.isLeaf(id) && id != Block.VINE.id && id != Block.WEB.id && id != longGrass && id != bush) { ArrayList<ItemStack> var14 = Block.byId[id].getBlockDropped(var3, nx, ny, nz, data, 0); ItemStack var16; for (Iterator<ItemStack> var15 = var14.iterator(); var15.hasNext(); addToDroplist(item, var16)) var16 = var15.next(); } else if (id == Block.LEAVES.id) addToDroplist(item, new ItemStack(Block.LEAVES.id, 1, data & 3)); else addToDroplist(item, new ItemStack(Block.byId[id], 1, data)); setShort(item, "fuelRemaining", getFuelRemaining(item) - 1); var3.setTypeId(nx, ny, nz, 0); if (var3.random.nextInt(8) == 0) var3.a("largesmoke", nx, ny, nz, 0.0D, 0.0D, 0.0D); if (var3.random.nextInt(8) == 0) var3.a("explode", nx, ny, nz, 0.0D, 0.0D, 0.0D); } } } } } ejectDropList(var3, item, x, y, z); return false; } public boolean onItemUseHoe(ItemStack item, EntityHuman human, World world, int x, int y, int z, int var7) { int id = world.getTypeId(x, y, z); int charge = chargeLevel(item); if (charge > 0) { if (EEEventManager.callEvent(new EERedKatarEvent(item, EEAction.RIGHTCLICK, human, x, y, z, EEAction2.TillRadius))) return false; human.C_(); world.makeSound(human, "flash", 0.8F, 1.5F); if (id == yFlower || id == rFlower || id == bMush || id == rMush || id == longGrass || id == bush) y--; for (int var8 = -(charge * charge) - 1; var8 <= charge * charge + 1; var8++) { for (int var9 = -(charge * charge) - 1; var9 <= charge * charge + 1; var9++) { int nx = x + var8; int nz = z + var9; int id2 = world.getTypeId(nx, y, nz); int id3 = world.getTypeId(nx, y + 1, nz); if ((id3 == yFlower || id3 == rFlower || id3 == bMush || id3 == rMush || id3 == longGrass || id3 == bush) && attemptBreak(human, nx, y + 1, nz)) { Block.byId[id3].dropNaturally(world, nx, y + 1, nz, world.getData(nx, y + 1, nz), 1.0F, 1); world.setTypeId(nx, y + 1, nz, 0); id3 = 0; } if (id3 == 0 && (id2 == Block.DIRT.id || id2 == Block.GRASS.id) && attemptBreak(human, nx, y, nz)) { if (getFuelRemaining(item) < 1) ConsumeReagent(item, human, false); if (getFuelRemaining(item) > 0) { world.setTypeId(nx, y, nz, 60); setShort(item, "fuelRemaining", getFuelRemaining(item) - 1); if (world.random.nextInt(8) == 0) world.a("largesmoke", nx, y, nz, 0.0D, 0.0D, 0.0D); if (world.random.nextInt(8) == 0) world.a("explode", nx, y, nz, 0.0D, 0.0D, 0.0D); } } } } return false; } if (human != null && !human.d(x, y, z)) return false; int var9 = world.getTypeId(x, y + 1, z); if ((var7 == 0 || var9 != 0 || id != Block.GRASS.id) && id != Block.DIRT.id) return false; Block var10 = Block.SOIL; world.makeSound(x + 0.5F, y + 0.5F, z + 0.5F, var10.stepSound.getName(), (var10.stepSound.getVolume1() + 1.0F) / 2.0F, var10.stepSound.getVolume2() * 0.8F); if (world.isStatic) return true; if (!attemptBreak(human, x, y, z)) return false; world.setTypeId(x, y, z, var10.id); return true; } public boolean onItemUseAxe(ItemStack item, EntityHuman human, World world, int x, int y, int z, int var7) { int charge = chargeLevel(item); if (charge < 1) return false; boolean var14 = false; cleanDroplist(item); if (chargeLevel(item) < 1) return false; human.C_(); world.makeSound(human, "flash", 0.8F, 1.5F); for (int var15 = -(charge * 2) + 1; var15 <= charge * 2 - 1; var15++) { for (int var16 = charge * 2 + 1; var16 >= -2; var16--) { for (int var17 = -(charge * 2) + 1; var17 <= charge * 2 - 1; var17++) { int nx = x + var15; int ny = y + var16; int nz = z + var17; int id = world.getTypeId(nx, ny, nz); if ((EEMaps.isWood(id) || EEMaps.isLeaf(id)) && attemptBreak(human, nx, ny, nz)) { if (getFuelRemaining(item) < 1) if (var15 == chargeLevel(item) && var17 == chargeLevel(item)) { ConsumeReagent(item, human, var14); var14 = false; } else { ConsumeReagent(item, human, false); } if (getFuelRemaining(item) > 0) { int data = world.getData(nx, ny, nz); ArrayList<ItemStack> var23 = Block.byId[id].getBlockDropped(world, nx, ny, nz, data, 0); ItemStack var25; for (Iterator<ItemStack> var24 = var23.iterator(); var24.hasNext(); addToDroplist(item, var25)) var25 = var24.next(); world.setTypeId(nx, ny, nz, 0); if (!EEMaps.isLeaf(id)) setShort(item, "fuelRemaining", getFuelRemaining(item) - 1); if (world.random.nextInt(8) == 0) world.a("largesmoke", nx, ny, nz, 0.0D, 0.0D, 0.0D); if (world.random.nextInt(8) == 0) world.a("explode", nx, ny, nz, 0.0D, 0.0D, 0.0D); } } } } } ejectDropList(world, item, x, y, z); return false; } public boolean isFull3D() { return true; } public EnumAnimation d(ItemStack var1) { return EnumAnimation.d; } public int c(ItemStack var1) { return 72000; } public ItemStack a(ItemStack item, World var2, EntityHuman var3) { if (EEProxy.isClient(var2)) return item; var3.a(item, c(item)); return item; } public void doShear(ItemStack item, World var2, EntityHuman var3, Entity var4) { if (chargeLevel(item) > 0) { //boolean var5 = false; int var6 = 0; if (getFuelRemaining(item) < 10) ConsumeReagent(item, var3, false); if (getFuelRemaining(item) < 10) ConsumeReagent(item, var3, false); if (getFuelRemaining(item) < 10) ConsumeReagent(item, var3, false); while (getFuelRemaining(item) >= 10 && var6 < chargeLevel(item)) { setShort(item, "fuelRemaining", getFuelRemaining(item) - 10); var6++; if (getFuelRemaining(item) < 10) ConsumeReagent(item, var3, false); if (getFuelRemaining(item) < 10) ConsumeReagent(item, var3, false); if (getFuelRemaining(item) < 10) ConsumeReagent(item, var3, false); } if (var6 > 0) { var3.C_(); var2.makeSound(var3, "flash", 0.8F, 1.5F); int var7 = 3 * var6; if (var4 instanceof EntitySheep) { if (var2.random.nextInt(100) < var7) { EntitySheep var8 = new EntitySheep(var2); double var9 = var4.locX - var3.locX; double var11 = var4.locZ - var3.locZ; if (var9 < 0.0D) var9 *= -1D; if (var11 < 0.0D) var11 *= -1D; var9 += var4.locX; var11 += var4.locZ; double var13 = var4.locY; for (int var15 = -5; var15 <= 5; var15++) { if (var2.getTypeId((int) var9, (int) var13 + var15, (int) var11) == 0 || var2.getTypeId((int) var9, (int) var13 + var15 + 1, (int) var11) != 0) continue; var8.setPosition(var9, var13 + var15 + 1.0D, var11); var8.setColor(((EntitySheep) var4).getColor()); var2.addEntity(var8); break; } } ((EntitySheep) var4).setSheared(true); int var19 = 3 + var2.random.nextInt(2) + chargeLevel(item) / 2; EntityItem var21 = null; for (int var10 = 0; var10 < var19; var10++) var21 = new EntityItem(var2, var3.locX, var3.locY, var3.locZ, new ItemStack(Block.WOOL.id, var19, ((EntitySheep) var4).getColor())); var2.addEntity(var21); } else if (var4 instanceof EntityMushroomCow) { if (var2.random.nextInt(100) < var7) { EntityMushroomCow var18 = new EntityMushroomCow(var2); double var9 = var4.locX - var3.locX; double var11 = var4.locZ - var3.locZ; if (var9 < 0.0D) var9 *= -1D; if (var11 < 0.0D) var11 *= -1D; var9 += var4.locX; var11 += var4.locZ; double var13 = var4.locY; for (int var15 = -5; var15 <= 5; var15++) { if (var2.getTypeId((int) var9, (int) var13 + var15, (int) var11) == 0 || var2.getTypeId((int) var9, (int) var13 + var15 + 1, (int) var11) != 0) continue; var18.setPosition(var9, var13 + var15 + 1.0D, var11); var2.addEntity(var18); break; } } ((EntityMushroomCow) var4).die(); EntityCow var20 = new EntityCow(var2); var20.setPositionRotation(var4.locX, var4.locY, var4.locZ, var4.yaw, var4.pitch); var20.setHealth(((EntityMushroomCow) var4).getHealth()); var20.V = ((EntityMushroomCow) var4).V; var2.addEntity(var20); var2.a("largeexplode", var4.locX, var4.locY + (var4.length / 2.0F), var4.locZ, 0.0D, 0.0D, 0.0D); int var23 = 5 + var2.random.nextInt(2) + chargeLevel(item) / 2; //Object var22 = null; for (int var24 = 0; var24 < var23; var24++) new EntityItem(var2, var3.locX, var3.locY, var3.locZ, new ItemStack(Block.RED_MUSHROOM, var23)); } } } else if (var4 instanceof EntitySheep) { new EntitySheep(var2); ((EntitySheep) var4).setSheared(true); int var6 = 3 + var2.random.nextInt(2); EntityItem var17 = null; for (int var19 = 0; var19 < var6; var19++) var17 = new EntityItem(var2, var3.locX, var3.locY, var3.locZ, new ItemStack(Block.WOOL.id, var6, ((EntitySheep) var4).getColor())); var2.addEntity(var17); } else if (var4 instanceof EntityMushroomCow) { ((EntityMushroomCow) var4).die(); EntityCow var16 = new EntityCow(((EntityMushroomCow) var4).world); var16.setPositionRotation(((EntityMushroomCow) var4).locX, ((EntityMushroomCow) var4).locY, ((EntityMushroomCow) var4).locZ, ((EntityMushroomCow) var4).yaw, ((EntityMushroomCow) var4).pitch); var16.setHealth(((EntityMushroomCow) var4).getHealth()); var16.V = ((EntityMushroomCow) var4).V; ((EntityMushroomCow) var4).world.addEntity(var16); ((EntityMushroomCow) var4).world.a("largeexplode", ((EntityMushroomCow) var4).locX, ((EntityMushroomCow) var4).locY + (((EntityMushroomCow) var4).length / 2.0F), ((EntityMushroomCow) var4).locZ, 0.0D, 0.0D, 0.0D); for (int var6 = 0; var6 < 5; var6++) ((EntityMushroomCow) var4).world.addEntity(new EntityItem(((EntityMushroomCow) var4).world, ((EntityMushroomCow) var4).locX, ((EntityMushroomCow) var4).locY + ((EntityMushroomCow) var4).length, ((EntityMushroomCow) var4).locZ, new ItemStack( Block.RED_MUSHROOM))); } } public int a(Entity var1) { return (var1 instanceof EntitySheep) || (var1 instanceof EntityMushroomCow) ? 1 : weaponDamage; } public boolean a(ItemStack item, EntityLiving var2, EntityLiving var3) { if (!(var3 instanceof EntityHuman)) return true; EntityHuman var4 = (EntityHuman) var3; if (EEEventManager.callEvent(new EERedKatarEvent(item, EEAction.RIGHTCLICK, var4, EEAction2.Shear))) return true; if (var2 instanceof EntitySheep) { if (!((EntitySheep) var2).isSheared()) doShear(item, var4.world, var4, var2); var2.heal(1); } else if (var2 instanceof EntityMushroomCow) { doShear(item, var4.world, var4, var2); var2.heal(1); } return true; } public void doAlternate(ItemStack item, World var2, EntityHuman var3) { //if (EEEventManager.callEvent(new EERedKatarEvent(item, EEAction.ALTERNATE, var3, EEAction2.UpdateSwordMode))) return; EEBase.updateSwordMode(var3); } public void doRelease(ItemStack item, World var2, EntityHuman var3) { if (EEEventManager.callEvent(new EERedKatarEvent(item, EEAction.RELEASE, var3, EEAction2.AttackRadius))) return; doSwordBreak(item, var2, var3); } public void doToggle(ItemStack itemstack, World world, EntityHuman entityhuman) {} public boolean itemCharging; private static Block blocksEffectiveAgainst[]; static { blocksEffectiveAgainst = (new Block[] { Block.WOOD, Block.BOOKSHELF, Block.LOG, Block.CHEST, Block.DIRT, Block.GRASS, Block.LEAVES, Block.WEB, Block.WOOL }); } }
gpl-3.0
machawk1/webarchiveplayer
archiveplayer/version.py
79
__version__= '1.1.1' INFO_URL = 'https://github.com/ikreymer/webarchiveplayer'
gpl-3.0
Estada1401/anuwhscript
GameServer/src/com/aionemu/gameserver/model/templates/spawns/iuspawns/IuSpawn.java
1952
/* * This file is part of Encom. **ENCOM FUCK OTHER SVN** * * Encom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Encom 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Encom. If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.model.templates.spawns.iuspawns; import java.util.*; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import com.aionemu.gameserver.model.templates.spawns.Spawn; import com.aionemu.gameserver.model.iu.IuStateType; /** * @author Rinzler (Encom) */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "IuSpawn") public class IuSpawn { @XmlAttribute(name = "id") private int id; public int getId() { return id; } @XmlElement(name = "iu_type") private List<IuSpawn.IuStateTemplate> IuStateTemplate; public List<IuStateTemplate> getSiegeModTemplates() { return IuStateTemplate; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "IuStateTemplate") public static class IuStateTemplate { @XmlElement(name = "spawn") private List<Spawn> spawns; @XmlAttribute(name = "iustate") private IuStateType iuType; public List<Spawn> getSpawns() { return spawns; } public IuStateType getIuType() { return iuType; } } }
gpl-3.0
zetaops/ulakbus
ulakbus/lib/doc_render/__init__.py
532
# -*- coding: utf-8 -*- # Copyright (C) 2015 ZetaOps Inc. # # This file is licensed under the GNU General Public License v3 # (GPLv3). See LICENSE.txt for details. from .bap_komisyon_toplanti_tutanagi import * from .bap_muayene_ve_kabul_komisyon_tutanagi import * from .bap_sozlesme import * from .dogrudan_tek_kaynak import * from .mal_ve_hizmet_alimlari_onay_belgesi import * from .muayene_gorevlendirmesi import * from .piyasa_fiyat_arastirmasi_tutanagi import * from .siparis_formu import * from .tasinir_islem_fisi import *
gpl-3.0
schuylernathaniel/PixelDungeon2--edited
src/com/watabou/pixeldungeon/actors/blobs/WaterOfTransmutation.java
5740
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.pixeldungeon.actors.blobs; import com.watabou.pixeldungeon.Journal; import com.watabou.pixeldungeon.Journal.Feature; import com.watabou.pixeldungeon.effects.BlobEmitter; import com.watabou.pixeldungeon.effects.Speck; import com.watabou.pixeldungeon.items.Generator; import com.watabou.pixeldungeon.items.Item; import com.watabou.pixeldungeon.items.Generator.Category; import com.watabou.pixeldungeon.items.potions.Potion; import com.watabou.pixeldungeon.items.potions.PotionOfMight; import com.watabou.pixeldungeon.items.potions.PotionOfStrength; import com.watabou.pixeldungeon.items.rings.Ring; import com.watabou.pixeldungeon.items.scrolls.Scroll; import com.watabou.pixeldungeon.items.scrolls.ScrollOfUpgrade; import com.watabou.pixeldungeon.items.scrolls.ScrollOfWeaponUpgrade; import com.watabou.pixeldungeon.items.wands.Wand; import com.watabou.pixeldungeon.items.weapon.Weapon.Enchantment; import com.watabou.pixeldungeon.items.weapon.melee.*; import com.watabou.pixeldungeon.plants.Plant; public class WaterOfTransmutation extends WellWater { @Override protected Item affectItem( Item item ) { if (item instanceof MeleeWeapon) { return changeWeapon( (MeleeWeapon)item ); } else if (item instanceof Scroll) { //Journal.remove( Feature.WELL_OF_TRANSMUTATION ); return changeScroll( (Scroll)item ); } else if (item instanceof Potion) { //Journal.remove( Feature.WELL_OF_TRANSMUTATION ); return changePotion( (Potion)item ); } else if (item instanceof Ring) { //Journal.remove( Feature.WELL_OF_TRANSMUTATION ); return changeRing( (Ring)item ); } else if (item instanceof Wand) { //Journal.remove( Feature.WELL_OF_TRANSMUTATION ); return changeWand( (Wand)item ); } else if (item instanceof Plant.Seed) { //Journal.remove( Feature.WELL_OF_TRANSMUTATION ); return changeSeed( (Plant.Seed)item ); } else { return null; } } @Override public void use( BlobEmitter emitter ) { super.use( emitter ); emitter.start( Speck.factory( Speck.CHANGE ), 0.2f, 0 ); } private MeleeWeapon changeWeapon( MeleeWeapon w ) { MeleeWeapon n = null; if (w instanceof Knuckles) { n = new Dagger(); } else if (w instanceof Dagger) { n = new Knuckles(); } else if (w instanceof Spear) { n = new Quarterstaff(); } else if (w instanceof Quarterstaff) { n = new Spear(); } else if (w instanceof Sword) { n = new Mace(); } else if (w instanceof Mace) { n = new Sword(); } else if (w instanceof Longsword) { n = new BattleAxe(); } else if (w instanceof BattleAxe) { n = new Longsword(); } else if (w instanceof Glaive) { n = new WarHammer(); } else if (w instanceof WarHammer) { n = new Glaive(); } if (n != null) { int level = w.level; if (level > 0) { n.upgrade( level ); } else if (level < 0) { n.degrade( -level ); } if (w.isEnchanted()) { n.enchant( Enchantment.random() ); } n.levelKnown = w.levelKnown; n.cursedKnown = w.cursedKnown; n.cursed = w.cursed; //Journal.remove( Feature.WELL_OF_TRANSMUTATION ); return n; } else { return null; } } private Ring changeRing( Ring r ) { Ring n; do { n = (Ring)Generator.random( Category.RING ); } while (n.getClass() == r.getClass()); n.level = 0; int level = r.level; if (level > 0) { n.upgrade( level ); } else if (level < 0) { n.degrade( -level ); } n.levelKnown = r.levelKnown; n.cursedKnown = r.cursedKnown; n.cursed = r.cursed; return n; } private Wand changeWand( Wand w ) { Wand n; do { n = (Wand)Generator.random( Category.WAND ); } while (n.getClass() == w.getClass()); n.level = 0; n.upgrade( w.level ); n.levelKnown = w.levelKnown; n.cursedKnown = w.cursedKnown; n.cursed = w.cursed; return n; } private Plant.Seed changeSeed( Plant.Seed s ) { Plant.Seed n; do { n = (Plant.Seed)Generator.random( Category.SEED ); } while (n.getClass() == s.getClass()); return n; } private Scroll changeScroll( Scroll s ) { if (s instanceof ScrollOfUpgrade) { return new ScrollOfWeaponUpgrade(); } else if (s instanceof ScrollOfWeaponUpgrade) { return new ScrollOfUpgrade(); } else { Scroll n; do { n = (Scroll)Generator.random( Category.SCROLL ); } while (n.getClass() == s.getClass()); return n; } } private Potion changePotion( Potion p ) { if (p instanceof PotionOfStrength) { return new PotionOfMight(); } else if (p instanceof PotionOfMight) { return new PotionOfStrength(); } else { Potion n; do { n = (Potion)Generator.random( Category.POTION ); } while (n.getClass() == p.getClass()); return n; } } @Override public String tileDesc() { return "Power of change radiates from the water of this well. " + "Throw an item into the well to turn it into something else."; } }
gpl-3.0
WendySanarwanto/udemy-the-complete-guide-to-angular-4
assignments/basics-assignment2-start/src/app/app.module.ts
568
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { InputPanelComponent } from './input-panel/input-panel.component'; @NgModule({ declarations: [ AppComponent, InputPanelComponent ], imports: [ BrowserModule, FormsModule // Imported @angular/forms/FormsModule, because I need to get 2 way data binding working. ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
gpl-3.0
rickyminecraft/fence
com/ricky30/fence/event/blocEvent.java
9458
package com.ricky30.fence.event; import java.util.Map; import java.util.UUID; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockState.Builder; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.data.translator.ConfigurateTranslator; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.block.ChangeBlockEvent; import org.spongepowered.api.event.block.InteractBlockEvent; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.text.Text; import org.spongepowered.api.world.World; import com.flowpowered.math.vector.Vector3i; import com.ricky30.fence.fence; import com.ricky30.fence.utils.manageSet; import com.ricky30.fence.utils.managePole; import ninja.leaping.configurate.ConfigurationNode; public class blocEvent { private ConfigurationNode config = null; @Listener public void oninteractblockPlace(ChangeBlockEvent.Place Event, @First Player player) { this.config = fence.plugin.getConfig(); if (config.getNode("pole").isVirtual()) { return; } for (final Transaction<BlockSnapshot> blocksnap : Event.getTransactions()) { Vector3i Pos = blocksnap.getDefault().getLocation().get().getBlockPosition(); final World world = player.getWorld(); final Map<Object, ? extends ConfigurationNode> Pole = config.getNode("pole").getChildrenMap(); boolean Ok = false; Pos = Pos.add(0, Pole.size(), 0); Pos = CheckPole(Pos, world, Pole.size()); Pos = Pos.sub(0, Pole.size()-1, 0); Ok = CheckPole2(Pos, world, Pole, Pole.size()); if (Ok) { int PoleNumber = 0; if (!config.getNode("fence", "pole", "Set0").getChildrenMap().isEmpty()) { for (final Object pole : config.getNode("fence", "pole", "Set0").getChildrenMap().keySet()) { int PoleNumbertmp; PoleNumbertmp = this.config.getNode("fence", "pole", "Set0", pole.toString(), "Number").getInt(); if (PoleNumbertmp > PoleNumber) { PoleNumber = PoleNumbertmp; } } PoleNumber++; } final String Number = String.valueOf(Pos.getX()) + String.valueOf(Pos.getY()) + String.valueOf(Pos.getZ()); final byte[] b = Number.getBytes(); final String Name = UUID.nameUUIDFromBytes(b).toString(); this.config.getNode("fence", "pole", "Set0", Name, "X").setValue(Pos.getX()); this.config.getNode("fence", "pole", "Set0", Name, "Y").setValue(Pos.getY()); this.config.getNode("fence", "pole", "Set0", Name, "Z").setValue(Pos.getZ()); this.config.getNode("fence", "pole", "Set0", Name, "world").setValue(world.getUniqueId().toString()); this.config.getNode("fence", "pole", "Set0", Name, "Number").setValue(PoleNumber); fence.plugin.save(); player.sendMessage(Text.of("A pole has been made")); } } } @Listener public void oninteractblockRemove(ChangeBlockEvent.Break Event, @First Player player) { this.config = fence.plugin.getConfig(); if (config.getNode("pole").isVirtual()) { return; } for (final Transaction<BlockSnapshot> blocksnap : Event.getTransactions()) { Vector3i Pos = blocksnap.getDefault().getLocation().get().getBlockPosition(); final World world = player.getWorld(); final Map<Object, ? extends ConfigurationNode> Pole = config.getNode("pole").getChildrenMap(); Pos = Pos.add(0, Pole.size(), 0); Pos = CheckPole(Pos, world, Pole.size()); Pos = Pos.sub(0, 1, 0); final String Number = String.valueOf(Pos.getX()) + String.valueOf(Pos.getY()) + String.valueOf(Pos.getZ()); final byte[] b = Number.getBytes(); final String Name = UUID.nameUUIDFromBytes(b).toString(); for (final Object node : this.config.getNode("fence", "pole").getChildrenMap().keySet()) { if (this.config.getNode("fence", "pole", node.toString()).getChildrenMap().containsKey(Name)) { if (world.getUniqueId().equals(UUID.fromString(this.config.getNode("fence", "pole", node.toString(), Name, "world").getString()))) { this.config.getNode("fence", "pole", node.toString()).removeChild(Name); fence.plugin.save(); player.sendMessage(Text.of("A pole has been broken")); } } } } } @Listener public void oninteractblockPrimary(InteractBlockEvent.Secondary Event, @First Player player) { this.config = fence.plugin.getConfig(); if (manageSet.IsSetactive()) { manageSet.SetActive(false); Vector3i Pos = Event.getTargetBlock().getPosition(); final World world = player.getWorld(); final Map<Object, ? extends ConfigurationNode> Pole = config.getNode("pole").getChildrenMap(); boolean Ok = false; Pos = Pos.add(0, Pole.size(), 0); Pos = CheckPole(Pos, world, Pole.size()); Pos = Pos.sub(0, Pole.size()-1, 0); Ok = CheckPole2(Pos, world, Pole, Pole.size()); if (Ok) { final String Number = String.valueOf(Pos.getX()) + String.valueOf(Pos.getY()) + String.valueOf(Pos.getZ()); final byte[] b = Number.getBytes(); final String Name = UUID.nameUUIDFromBytes(b).toString(); int x = 0, y = 0, z = 0; UUID Worlduid = null; boolean Done = false; for (final Object node : this.config.getNode("fence", "pole").getChildrenMap().keySet()) { if (this.config.getNode("fence", "pole", node.toString()).getChildrenMap().containsKey(Name)) { x = config.getNode("fence", "pole", node.toString(), Name, "X").getInt(); y = config.getNode("fence", "pole", node.toString(), Name, "Y").getInt(); z = config.getNode("fence", "pole", node.toString(), Name, "Z").getInt(); Worlduid = UUID.fromString(config.getNode("fence", "pole", node.toString(), Name, "world").getString()); if (world.getUniqueId().equals(Worlduid)) { Done = true; this.config.getNode("fence", "pole", node.toString()).removeChild(Name); } } } if (Done) { final String set = "Set" + manageSet.loadSetnumber(); int PoleNumber = 0; if (!config.getNode("fence", "pole", set).getChildrenMap().isEmpty()) { for (final Object pole : config.getNode("fence", "pole", set).getChildrenMap().keySet()) { int PoleNumbertmp; PoleNumbertmp = this.config.getNode("fence", "pole", set, pole.toString(), "Number").getInt(); if (PoleNumbertmp > PoleNumber) { PoleNumber = PoleNumbertmp; } } PoleNumber++; } this.config.getNode("fence", "pole", set, Name, "X").setValue(x); this.config.getNode("fence", "pole", set, Name, "Y").setValue(y); this.config.getNode("fence", "pole", set, Name, "Z").setValue(z); this.config.getNode("fence", "pole", set, Name, "world").setValue(Worlduid.toString()); this.config.getNode("fence", "pole", set, Name, "Number").setValue(PoleNumber); fence.plugin.save(); player.sendMessage(Text.of("Pole added to pole set number ",manageSet.loadSetnumber())); } } } if (managePole.IsSetactive()) { managePole.SetActive(false); //faire une boucle jusqu'en haut Vector3i pos = Event.getTargetBlock().getPosition(); final World world = player.getWorld(); int position = 0; final Map<Object, ? extends ConfigurationNode> cn = this.config.getNode("pole").getChildrenMap(); for (final Object node :cn.keySet()) { this.config.getNode("pole").removeChild(node); } while (!world.getBlock(pos).getType().equals(BlockTypes.AIR)) { final BlockState block = world.getBlock(pos); this.config.getNode("pole", String.valueOf(position), "BlockState").setValue(block.toString()); position++; pos = pos.add(0, 1, 0); } fence.plugin.save(); player.sendMessage(Text.of("Pole style defined")); } } ////// // start from above a pole and go down one by one to check size and return the lowest position (min: height - pole size) // args: position vector, the world, pole size // return: new position // ////// private Vector3i CheckPole(Vector3i Pos, World world, int Size) { int Position = 0; boolean Ok = false; //if we get AIR then go below while (!Ok) { if (world.getBlock(Pos).getType().equals(BlockTypes.AIR)) { Pos = Pos.add(0, -1, 0); Position +=1; } else { Ok = true; } if (Position > Size) { Ok = true; } } return Pos; } ////// // // check if the blocks (starting from the current position) are equal to the defined pole style // args: position vector, the world, the map of poles nodes, pole size // return: if this is equal : true else false // ////// private boolean CheckPole2(Vector3i Pos, World world, Map<Object, ? extends ConfigurationNode> Pole, int Size) { int Position = 0; boolean Ok = true; while (Position < Size) { final ConfigurateTranslator tr = ConfigurateTranslator.instance(); final ConfigurationNode node = Pole.get(String.valueOf(Position)); final DataContainer cont = tr.translateFrom(node); final Builder builder = Sponge.getRegistry().createBuilder(Builder.class); final BlockState block_Conf = builder.build(cont).get(); final BlockState block_World = world.getBlock(Pos); Pos = Pos.add(0, 1, 0); Position++; if (!block_Conf.equals(block_World)) { Ok = false; } } return Ok; } }
gpl-3.0
tsujamin/digi-approval
chef-repo/cookbooks/statsd/metadata.rb
299
maintainer "Jon Wood" maintainer_email "[email protected]" license "Apache 2.0" description "Installs/Configures statsd" long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc')) version "0.0.1" depends "build-essential" depends "git" supports "ubuntu"
gpl-3.0
ysenel/pdpSmithDr
tests/test_ImageFiltering.cpp
8070
/* Copyright (C) 2011 The SmithDR team, [email protected] This file is part of SmithDR. SmithDR 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. SmithDR 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 SmithDR. If not, see <http://www.gnu.org/licenses/>. */ #include <SmithDRDefs.hpp> #include <frontend/lib/plugins/PluginManager.hpp> #include <frontend/lib/LoaderManager.hpp> #include <frontend/lib/SaverManager.hpp> #include <core/image/Image.hpp> #include <core/image/ImageView_.hpp> #include <imageprocessing/filters/Filter.hpp> #include <imageprocessing/filters/StructuralElement.hpp> #include <imageprocessing/filters/GaussianLinearFilter.hpp> #include <imageprocessing/filters/DogFilter.hpp> #include <imageprocessing/filters/LogFilter.hpp> #include <imageprocessing/filters/UniformFilter.hpp> #include <imageprocessing/filters/MedianFilter.hpp> #include <imageprocessing/filters/PrewittFilter.hpp> #include <imageprocessing/filters/RobertsFilter.hpp> #include <imageprocessing/filters/SobelFilter.hpp> #include <imageprocessing/filters/KirschFilter.hpp> #include <imageprocessing/filters/DilationFilter.hpp> #include <imageprocessing/filters/ErosionFilter.hpp> #include <imageprocessing/filters/GaussianFrequencyFilter.hpp> #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <cmath> #include <algorithm> using namespace sd::imageprocessing; template<typename T> void saveImage(sd::core::ImageView_<T> *img, std::string outFilename) { unsigned int width = img->size().width(); unsigned int height = img->size().height(); unsigned int nbSlices = img->size().depth(); int n = width * height * nbSlices; double mini = *std::min_element(img->begin(), img->end()); double maxi = *std::max_element(img->begin(), img->end()); sd::UINT8 *data = new sd::UINT8[n]; auto it = img->begin(); for (int i = 0; it != img->end() && i < n; ++i, ++it) data[i] = 255. * (*it - mini) / (maxi-mini); sd::core::ImageViewInfo info(sd::GRAYLEVEL, sd::Z_AXIS, sd::Size(width, height, nbSlices, 1)); sd::core::Image<sd::UINT8> im(info); im.setData(data); bool saved = sd::frontend::saveFile((sd::core::ImageView*) &im, outFilename); if (!saved) std::cerr << "Unable to save file: " << outFilename << ".\n\n"; } void usage(std::string progName) { std::cerr << "\nUsage: " << progName << " <image.pgm> <output.pgm> <filter> [options]\n"; std::cerr << "\tFilters:\n\n"; std::cerr << "\t\t<kirsch,prewitt,roberts>\n"; std::cerr << "\t\t\tAll are 3x3 filters\n\n"; std::cerr << "\t\t<uniform,median,sobel> <kernel_size>\n\n"; std::cerr << "\t\t<log,gaussian> <kernel_size> <sigma>\n"; std::cerr << "\t\t\tlog is Lapacian of Gaussian\n"; std::cerr << "\t\t\tgaussian is applied in spatial domain\n\n"; std::cerr << "\t\tgaussian <sigma>\n"; std::cerr << "\t\t\tgaussian is applied in frequency domain\n\n"; std::cerr << "\t\tdog <kernel_size> <sigma1> <sigma2>\n"; std::cerr << "\t\t\tdog is Difference of Gaussian\n\n"; std::cerr << "\t\t<dilation,erosion,closing,opening> <structual_element> [params]\n"; std::cerr << "\t\tStructural elements:\n"; std::cerr << "\t\t\t<square> <side>\n"; std::cerr << "\t\t\t<circle> <radius>\n"; std::cerr << "\t\t\t<cross> <side> <isDiagonal>\n"; std::cerr << std::endl; } int main(int argc, char *argv[]) { if (argc < 4) { usage(argv[0]); return EXIT_FAILURE; } std::string filenameIn(argv[1]); std::string filenameOut(argv[2]); std::string filterName(argv[3]); sd::frontend::plugins::PluginManager& pm = sd::frontend::plugins::PluginManager::instance(); std::cout << "Load LoaderPgmPlugin\n"; pm.loadPlugin(PLUGIN_DIR, "LoaderPgmPlugin"); std::cout << "Load SaverPgmPlugin\n"; pm.loadPlugin(PLUGIN_DIR, "SaverPgmPlugin"); sd::core::ImageView* image = NULL; bool loaded = sd::frontend::loadFile(filenameIn, image); if (!loaded || !image) { std::cerr << "Unable to load file: " << filenameIn << ".\n\n"; return EXIT_FAILURE; } typedef sd::UINT8 Type; sd::core::ImageView_<Type>* im = dynamic_cast<sd::core::ImageView_<Type>*>(image); if (!im) { std::cout << "Only UINT8 data type is accepted. Sorry!\n"; return EXIT_FAILURE; } sd::UINT16 width = im->size().width(); sd::UINT16 height = im->size().height(); Filter<Type>* filter = NULL; StructuralElement* sel = NULL; if (filterName == "kirsch") { filter = new KirschFilter<Type>; } else if (filterName == "prewitt") { filter = new PrewittFilter<Type>; } else if (filterName == "roberts") { filter = new RobertsFilter<Type>; } else if (filterName == "uniform" || filterName == "median" || filterName == "sobel") { if (argc != 5) { usage(argv[0]); return EXIT_FAILURE; } unsigned int fsize = atoi(argv[4]); if (filterName == "uniform") filter = new UniformFilter<Type>(fsize, fsize, 1); else if (filterName == "median") filter = new MedianFilter<Type>(fsize, fsize, 1); else if (filterName == "sobel") filter = new SobelFilter<Type>(fsize); } else if (filterName == "log") { if (argc != 6) { usage(argv[0]); return EXIT_FAILURE; } unsigned int fsize = atoi(argv[4]); double sigma = atof(argv[5]); filter = new LogFilter<Type>(fsize, fsize, 1, sigma); } else if (filterName == "gaussian") { if (argc == 5) { double sigma = atof(argv[4]); filter = new GaussianFrequencyFilter<Type>(width, height, 1, sigma); } else if (argc == 6) { unsigned int fsize = atoi(argv[4]); double sigma = atof(argv[5]); filter = new GaussianLinearFilter<Type>(fsize, fsize, 1, sigma); } else { usage(argv[0]); return EXIT_FAILURE; } } else if (filterName == "dog") { if (argc != 7) { usage(argv[0]); return EXIT_FAILURE; } unsigned int fsize = atoi(argv[4]); double sigma1 = atof(argv[5]); double sigma2 = atof(argv[6]); filter = new DogFilter<Type>(fsize, fsize, 1, sigma1, sigma2); } else if (filterName == "dilation" || filterName == "erosion" || filterName == "closing" || filterName == "opening") { if (argc < 6) { usage(argv[0]); return EXIT_FAILURE; } std::string selName(argv[4]); unsigned int fsize = atoi(argv[5]); if (selName == "square") sel = StructuralElement::buildSquare(fsize); else if (selName == "circle") sel = StructuralElement::buildCircle(fsize); else if (selName == "cross") { if (argc != 7) { usage(argv[0]); return EXIT_FAILURE; } unsigned int diagonal = atoi(argv[6]); sel = StructuralElement::buildCross(fsize, diagonal); } else { usage(argv[0]); return EXIT_FAILURE; } if (filterName == "dilation" || filterName == "closing") filter = new DilationFilter<Type>(*sel); else if (filterName == "erosion" || filterName == "opening") filter = new ErosionFilter<Type>(*sel); } else { usage(argv[0]); return EXIT_FAILURE; } // apply filter if (filter) { sd::core::Image<Type> conv; filter->applyTo(conv, *im); delete filter; if (filterName == "opening") { filter = new DilationFilter<Type>(*sel); filter->applyTo(conv, conv); delete filter; } else if (filterName == "closing") { filter = new ErosionFilter<Type>(*sel); filter->applyTo(conv, conv); delete filter; } if (sel) delete sel; saveImage(&conv, filenameOut); } delete image; }
gpl-3.0
myLiveNotes/myLiveNotes
resources/i18n/sankore_zh_TW.ts
119008
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="zh_TW"> <context> <name>BlackoutWidget</name> <message> <source>Click to Return to Application</source> <translation>按滑鼠回到應用程式</translation> </message> </context> <context> <name>DownloadDialog</name> <message> <source>Downloads</source> <translation>下載</translation> </message> <message> <source>Clean Up</source> <translation>清理乾淨</translation> </message> <message> <source>0 Items</source> <translation>零個項目</translation> </message> </context> <context> <name>DownloadItem</name> <message> <source>Form</source> <translation>表格</translation> </message> <message> <source>Filename</source> <translation>檔名</translation> </message> <message> <source>Try Again</source> <translation>再試一次</translation> </message> <message> <source>Stop</source> <translation>結束</translation> </message> <message> <source>Open</source> <translation>開啟</translation> </message> </context> <context> <name>IntranetPodcastPublishingDialog</name> <message> <source>Publish Podcast to YouTube</source> <translation>發佈Podcast至YouTube</translation> </message> <message> <source>Title</source> <translation>標題</translation> </message> <message> <source>Description</source> <translation>描述</translation> </message> <message> <source>Author</source> <translation>作者</translation> </message> </context> <context> <name>MainWindow</name> <message> <source>Board</source> <translation>演示版</translation> </message> <message> <source>Web</source> <translation>網頁</translation> </message> <message> <source>Documents</source> <translation>文件</translation> </message> <message> <source>Stylus</source> <translation>桌面工具</translation> </message> <message> <source>Ctrl+T</source> <translation>Ctrl+T</translation> </message> <message> <source>Backgrounds</source> <translation>背景</translation> </message> <message> <source>Text</source> <translation>文字</translation> </message> <message> <source>Capture</source> <translation>擷取</translation> </message> <message> <source>Add To Current Page</source> <translation>新增至目前頁面</translation> </message> <message> <source>Add To New Page</source> <translation>新增至新頁面</translation> </message> <message> <source>Add To Library</source> <translation>新增至圖書館</translation> </message> <message> <source>Pages</source> <translation>頁面</translation> </message> <message> <source>New Page</source> <translation>新頁面</translation> </message> <message> <source>Undo</source> <translation>回復</translation> </message> <message> <source>Change Background</source> <translation>更換背景</translation> </message> <message> <source>Ctrl+Z</source> <translation>Ctrl+Z</translation> </message> <message> <source>Redo</source> <translation>重做</translation> </message> <message> <source>Ctrl+Y</source> <translation>Ctrl+Y</translation> </message> <message> <source>Previous</source> <translation>上一頁</translation> </message> <message> <source>Previous Page</source> <translation>上一頁</translation> </message> <message> <source>PgUp</source> <translation>往上</translation> </message> <message> <source>Next</source> <translation>下一頁</translation> </message> <message> <source>Next Page</source> <translation>下一頁</translation> </message> <message> <source>PgDown</source> <translation>往下</translation> </message> <message> <source>Manage Documents</source> <translation>文件管理</translation> </message> <message> <source>Ctrl+D</source> <translation>Ctrl+D</translation> </message> <message> <source>Web Browsing</source> <translation>網頁瀏覽</translation> </message> <message> <source>Ctrl+W</source> <translation>Ctrl+W</translation> </message> <message> <source>Small Line</source> <translation>細</translation> </message> <message> <source>Medium Line</source> <translation>中</translation> </message> <message> <source>Large Line</source> <translation>粗</translation> </message> <message> <source>Smalle Eraser</source> <translation>細</translation> </message> <message> <source>Medium Eraser</source> <translation>中</translation> </message> <message> <source>Large Eraser</source> <translation>粗</translation> </message> <message> <source>Reload Current Page</source> <translation>重新載入目前頁面</translation> </message> <message> <source>Load Home Page</source> <translation>載入主頁</translation> </message> <message> <source>Show Bookmarks</source> <translation>顯示書籤</translation> </message> <message> <source>Add Bookmark</source> <translation>新增書籤</translation> </message> <message> <source>Display Board</source> <translation>顯示演示板</translation> </message> <message> <source>Erase Content</source> <translation>清除內容</translation> </message> <message> <source>Display Preferences</source> <translation>顯示偏好設定</translation> </message> <message> <source>Show Library</source> <translation>顯示圖書館</translation> </message> <message> <source>Show Computer Desktop</source> <translation>顯示本機桌面</translation> </message> <message> <source>Ctrl+Shift+H</source> <translation>Ctrl+Shift+H</translation> </message> <message> <source>Create a New Folder</source> <translation>新建檔案夾</translation> </message> <message> <source>Create a New Document</source> <translation>建立新文件</translation> </message> <message> <source>Import a Document</source> <translation>匯入文件</translation> </message> <message> <source>Export a Document</source> <translation>匯出文件</translation> </message> <message> <source>Open Page in Board</source> <translation>於演示板開啟頁面</translation> </message> <message> <source>Duplicate Selected Content</source> <translation>複製所選內容</translation> </message> <message> <source>Delete Selected Content</source> <translation>刪除所選內容</translation> </message> <message> <source>Add Content to Document</source> <translation>新增內容至文件</translation> </message> <message> <source>Rename Content</source> <translation>重新命名內容</translation> </message> <message> <source>Display Tools</source> <translation>顯示工具</translation> </message> <message> <source>Use Document Wide Size (16/9)</source> <translation>採寬尺寸文件(16/9)</translation> </message> <message> <source>Use Document Regular Size (4/3)</source> <translation>採一般尺寸文件 (4/3)</translation> </message> <message> <source>Use Custom Document Size</source> <translation>自訂文件尺寸</translation> </message> <message> <source>Stop Loading Web Page</source> <translation>停止載入網頁</translation> </message> <message> <source>Put Presentation to Sleep</source> <translation>演示進入睡眠狀態</translation> </message> <message> <source>Display Virtual Keyboard</source> <translation>顯示虛擬鍵盤</translation> </message> <message> <source>Record Presentation to Video</source> <translation>錄製演示影片</translation> </message> <message> <source>Erase Items</source> <translation>清除項目</translation> </message> <message> <source>Erase All Items</source> <translation>清除所有項目</translation> </message> <message> <source>Erase Annotations</source> <translation>清除桌面標注</translation> </message> <message> <source>Erase All Annotations</source> <translation>清除所有桌面標注</translation> </message> <message> <source>Clear All Elements</source> <translation>清空所有元件</translation> </message> <message> <source>Pen</source> <translation>電子筆</translation> </message> <message> <source>Annotate Document</source> <translation>標注文件</translation> </message> <message> <source>Ctrl+I</source> <translation>Ctrl+I</translation> </message> <message> <source>Erase Annotation</source> <translation>清除桌面標注</translation> </message> <message> <source>Ctrl+E</source> <translation>Ctrl+E</translation> </message> <message> <source>Marker</source> <translation>提示筆</translation> </message> <message> <source>Highlight </source> <translation>亮點</translation> </message> <message> <source>Ctrl+M</source> <translation>Ctrl+M</translation> </message> <message> <source>Selector</source> <translation>選擇器</translation> </message> <message> <source>Select And Modify Objects</source> <translation>選擇並修改物件</translation> </message> <message> <source>Ctrl+F</source> <translation>Ctrl+F</translation> </message> <message> <source>Hand</source> <translation>手型工具</translation> </message> <message> <source>Capture Part of the Screen</source> <translation>部份截圖</translation> </message> <message> <source>Custom Capture</source> <translation>自訂截圖範圍</translation> </message> <message> <source>Capture a Window</source> <translation>擷取視窗</translation> </message> <message> <source>Show Main Screen on Display Screen</source> <translation>在顯示器上顯示主螢幕</translation> </message> <message> <source>Erase all Annotations</source> <translation>清除所有桌面標注</translation> </message> <message> <source>eduMedia</source> <translation>eduMedia</translation> </message> <message> <source>Import eduMedia simulation</source> <translation>匯入eduMedia模擬程序</translation> </message> <message> <source>Open the tutorial</source> <translation>開啟教學檔</translation> </message> <message> <source>Check Update</source> <translation>更新檢查</translation> </message> <message> <source>Ctrl+H</source> <translation>Ctrl+H</translation> </message> <message> <source>Zoom In</source> <translation>放大</translation> </message> <message> <source>Zoom Out</source> <translation>縮小</translation> </message> <message> <source>Line</source> <translation>線條粗細</translation> </message> <message> <source>Quit</source> <translation>結束</translation> </message> <message> <source>Eraser</source> <translation>橡皮擦</translation> </message> <message> <source>Color</source> <translation>顏色</translation> </message> <message> <source>Back</source> <translation>退回</translation> </message> <message> <source>Left</source> <translation>向左</translation> </message> <message> <source>Forward</source> <translation>前進</translation> </message> <message> <source>Right</source> <translation>向右</translation> </message> <message> <source>Reload</source> <translation>重新載入</translation> </message> <message> <source>Home</source> <translation>主頁</translation> </message> <message> <source>Bookmarks</source> <translation>書籤</translation> </message> <message> <source>Bookmark</source> <extracomment>tooltip</extracomment> <translation>書籤</translation> </message> <message> <source>Ctrl+B</source> <translation>Ctrl+B</translation> </message> <message> <source>Clear Page</source> <translation>清空頁面</translation> </message> <message> <source>Preferences</source> <translation>偏好設定</translation> </message> <message> <source>Tutorial</source> <translation>教學檔</translation> </message> <message> <source>Erase</source> <translation>清除</translation> </message> <message> <source>Library</source> <translation>圖書館</translation> </message> <message> <source>Ctrl+L</source> <translation>Ctrl+L</translation> </message> <message> <source>Show Desktop</source> <translation>顯示桌面</translation> </message> <message> <source>Bigger</source> <translation>放大</translation> </message> <message> <source>Ctrl++</source> <translation>Ctrl++</translation> </message> <message> <source>Smaller</source> <translation>縮小</translation> </message> <message> <source>Ctrl+-</source> <translation>Ctrl+-</translation> </message> <message> <source>New Folder</source> <translation>新檔案夾</translation> </message> <message> <source>New Document</source> <translation>新文件</translation> </message> <message> <source>Import</source> <translation>匯入</translation> </message> <message> <source>Export</source> <translation>匯出</translation> </message> <message> <source>Open in Board</source> <translation>於演示板開啟</translation> </message> <message> <source>Ctrl+O</source> <translation>Ctrl+O</translation> </message> <message> <source>Duplicate</source> <translation>複製</translation> </message> <message> <source>Delete</source> <translation>刪除</translation> </message> <message> <source>Del</source> <translation>Del</translation> </message> <message> <source>Add to Working Document</source> <translation>新增至運作中文件</translation> </message> <message> <source>Add Selected Content to Open Document</source> <translation>新增所選內容至開啟的文件</translation> </message> <message> <source>Add</source> <translation>新增</translation> </message> <message> <source>Rename</source> <translation>重新命名</translation> </message> <message> <source>Cut</source> <translation>剪下</translation> </message> <message> <source>Copy</source> <translation>複製</translation> </message> <message> <source>Paste</source> <translation>貼上</translation> </message> <message> <source>Grid Light Background</source> <translation>淡色網格背景</translation> </message> <message> <source>Grid Dark Background</source> <translation>深色網格背景</translation> </message> <message> <source>Start Screen Recording</source> <translation>開始螢幕錄影</translation> </message> <message> <source>Scroll Page</source> <translation>捲動頁面</translation> </message> <message> <source>Laser Pointer</source> <translation>簡報筆</translation> </message> <message> <source>Virtual Laser Pointer</source> <translation>虛擬簡報筆</translation> </message> <message> <source>Ctrl+G</source> <translation>Ctrl+G</translation> </message> <message> <source>Draw Lines</source> <translation>繪線</translation> </message> <message> <source>Ctrl+J</source> <translation>Ctrl+J</translation> </message> <message> <source>Write Text</source> <translation>文字書寫</translation> </message> <message> <source>Ctrl+K</source> <translation>Ctrl+K</translation> </message> <message> <source>Add Item To Current Page</source> <translation>新增項目至目前頁面</translation> </message> <message> <source>Add Item To New Page</source> <translation>新增項目至新頁面</translation> </message> <message> <source>Add Item To Library</source> <translation>新增項目至圖書館</translation> </message> <message> <source>Create a New Page</source> <translation>建立新頁面</translation> </message> <message> <source>Duplicate Page</source> <translation>複製頁面</translation> </message> <message> <source>Duplicate the Current Page</source> <translation>複製目前頁面</translation> </message> <message> <source>Import Page</source> <translation>匯入頁面</translation> </message> <message> <source>Import an External Page</source> <translation>匯入外部頁面</translation> </message> <message> <source>Pause</source> <translation>暫停</translation> </message> <message> <source>Pause Podcast Recording</source> <translation>暫停錄製Podcast</translation> </message> <message> <source>Podcast Config</source> <translation>Podcast設定</translation> </message> <message> <source>Configure Podcast Recording</source> <translation>Podcast錄製設定</translation> </message> <message> <source>Web Trap</source> <translation>網頁擷取</translation> </message> <message> <source>Trap Web Content</source> <translation>擷取網頁內容</translation> </message> <message> <source>Window Capture</source> <translation>螢幕擷取</translation> </message> <message> <source>Show on Display</source> <translation>於顯示器上顯示</translation> </message> <message> <source>Sleep</source> <translation>睡眠狀態</translation> </message> <message> <source>Virtual Keyboard</source> <translation>虛擬鍵盤</translation> </message> <message> <source>Plain Light Background</source> <translation>淡色背景</translation> </message> <message> <source>Light</source> <translation>淡色</translation> </message> <message> <source>Plain Dark Background</source> <translation>深色背景</translation> </message> <message> <source>Dark</source> <translation>深色</translation> </message> <message> <source>Podcast</source> <translation>Podcast</translation> </message> <message> <source>Record</source> <translation>錄製</translation> </message> <message> <source>Tools</source> <translation>工具</translation> </message> <message> <source>Multi Screen</source> <translation>多螢幕顯示</translation> </message> <message> <source>Wide Size (16/9)</source> <translation>寬螢幕顯示(16/9)</translation> </message> <message> <source>Regular Size (4/3)</source> <translation>一般螢幕顯示(4/3)</translation> </message> <message> <source>Custom Size</source> <translation>自訂螢幕大小</translation> </message> <message> <source>Stop Loading</source> <translation>停止載入</translation> </message> <message utf8="true"> <source>Open-Sankoré</source> <translation>Open-Sankoré</translation> </message> <message utf8="true"> <source>Quit Open-Sankoré</source> <translation>退出Open-Sankoré</translation> </message> <message utf8="true"> <source>Open-Sankoré Editor</source> <translation>Open-Sankoré編輯器</translation> </message> <message utf8="true"> <source>Show Open-Sankoré Widgets Editor</source> <translation>顯示Open-Sankoré小工具編輯器</translation> </message> <message utf8="true"> <source>Hide Open-Sankoré</source> <translation>隱藏Open-Sankoré</translation> </message> <message utf8="true"> <source>Hide Open-Sankoré Application</source> <translation>隱藏Open-Sankoré應用程式</translation> </message> <message> <source>Import Uniboard Documents</source> <translation>匯入Uniboard文件</translation> </message> <message> <source>Import old Sankore or Uniboard documents</source> <translation>匯入舊Sankore或Uniboard文件</translation> </message> <message> <source>Group items</source> <translation>群組</translation> </message> <message> <source>Play</source> <translation>播放</translation> </message> <message> <source>Interact with items</source> <translation>互動</translation> </message> <message> <source>Erase Background</source> <translation>清除背景</translation> </message> <message> <source>Remove the backgound</source> <translation>移除背景</translation> </message> <message> <source>Group</source> <translation>群組</translation> </message> <message> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;p, li { white-space: pre-wrap; }&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom:2px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Download to&lt;/p&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;library&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;p, li { white-space: pre-wrap; }&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom:2px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Download to&lt;/p&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;library&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <source>Download to library</source> <translation>下載至圖書館</translation> </message> <message> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;p, li { white-space: pre-wrap; }&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom:2px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Download to&lt;/p&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;current page&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;p, li { white-space: pre-wrap; }&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom:2px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Download to&lt;/p&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;current page&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <source>Download to current page</source> <translation>下載至目前頁面</translation> </message> <message> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;p, li { white-space: pre-wrap; }&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom:2px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Add link to&lt;/p&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;library&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;p, li { white-space: pre-wrap; }&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom:2px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Add link to&lt;/p&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;library&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <source>Add link to library</source> <translation>新增連結至圖書館</translation> </message> <message> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;p, li { white-space: pre-wrap; }&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom:2px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Add link to&lt;/p&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;current page&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;p, li { white-space: pre-wrap; }&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom:2px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Add link to&lt;/p&gt;&lt;p align=&quot;center&quot; style=&quot; margin-top:2px; margin-bottom12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;current page&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <source>Add link to current page</source> <translation>新增連結至目前頁面</translation> </message> <message> <source>Bookmark</source> <comment>tooltip</comment> <translation type="unfinished">書籤</translation> </message> </context> <context> <name>PasswordDialog</name> <message> <source>Authentication Required</source> <translation>需要驗證</translation> </message> <message> <source>Username:</source> <translation>帳號:</translation> </message> <message> <source>Password:</source> <translation>密碼:</translation> </message> </context> <context> <name>ProxyDialog</name> <message> <source>Proxy Authentication</source> <translation>Proxy驗證</translation> </message> <message> <source>Connect to Proxy</source> <translation>連接至Proxy</translation> </message> <message> <source>Username:</source> <translation>帳號:</translation> </message> <message> <source>Password:</source> <translation>密碼:</translation> </message> <message> <source>Save username and password for future use</source> <translation>儲存帳號密碼</translation> </message> </context> <context> <name>QObject</name> <message> <source>Element ID = </source> <translation>元件ID =</translation> </message> <message> <source>Content is not supported in destination format.</source> <translation>內容格式不支援。</translation> </message> <message> <source>Remove Page</source> <translation>移除頁面</translation> </message> <message> <source>Are you sure you want to remove 1 page from the selected document &apos;%0&apos;?</source> <translation>確定要移除所選文件 &apos;%0&apos; 的一個頁面 ?</translation> </message> </context> <context> <name>UBApplication</name> <message> <source>Page Size</source> <translation>頁面大小</translation> </message> <message> <source>Podcast</source> <translation>Podcast</translation> </message> </context> <context> <name>UBApplicationController</name> <message> <source>Web</source> <translation>網頁</translation> </message> <message> <source>New update available, would you go to the web page ?</source> <translation>可更新,要上網頁嗎?</translation> </message> <message> <source>No update available</source> <translation>目前並無更新</translation> </message> <message> <source>Update available</source> <translation>目前可更新</translation> </message> <message> <source>Update</source> <translation>更新</translation> </message> </context> <context> <name>UBBoardController</name> <message> <source>Downloading content %1 failed</source> <translation>目前 %1 下載失敗</translation> </message> <message> <source>Download finished</source> <translation>下載完成</translation> </message> <message> <source>Unknown tool type %1</source> <translation>陌生工具型態 %1</translation> </message> <message> <source>Add Item</source> <translation>新增項目</translation> </message> <message> <source>All Supported (%1)</source> <translation>全部已支援(%1)</translation> </message> <message> <source>Unknown content type %1</source> <translation>陌生內容型態 %1</translation> </message> <message> <source>Delete page %1 from document</source> <translation>刪除文件的第 %1 頁</translation> </message> <message> <source>Page %1 deleted</source> <translation>已刪除第 %1 頁</translation> </message> <message> <source>Add file operation failed: file copying error</source> <translation>新增檔案失敗:檔案複製有錯誤</translation> </message> <message> <source>Group</source> <translation>群組</translation> </message> <message> <source>Ungroup</source> <translation>取消群組</translation> </message> <message> <source>Failed to duplicate %1</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to paste %1</source> <translation type="unfinished"></translation> </message> <message> <source>Duplication successful</source> <translation type="unfinished"></translation> </message> <message> <source>Paste successful</source> <translation type="unfinished"></translation> </message> </context> <context> <name>UBBoardPaletteManager</name> <message> <source>Error Adding Image to Library</source> <translation>錯誤新增圖像至圖書館</translation> </message> <message> <source>CapturedImage</source> <translation>圖像擷取</translation> </message> </context> <context> <name>UBCachePropertiesWidget</name> <message> <source>Cache Properties</source> <translation>Cache屬性</translation> </message> <message> <source>Color:</source> <translation>顏色:</translation> </message> <message> <source>Shape:</source> <translation>形狀:</translation> </message> <message> <source>Alpha:</source> <translation>Alpha:</translation> </message> <message> <source>Geometry:</source> <translation>形狀:</translation> </message> <message> <source>Width: </source> <translation>寬:</translation> </message> <message> <source>Height:</source> <translation>高:</translation> </message> <message> <source>Keep proportions</source> <translation>保持等比例</translation> </message> <message> <source>Mode:</source> <translation>Mode:</translation> </message> <message> <source>Preview:</source> <translation>預覽:</translation> </message> <message> <source>Close cache</source> <translation>關閉 cache</translation> </message> <message> <source>On Click</source> <translation type="unfinished"></translation> </message> <message> <source>Persistent</source> <translation type="unfinished"></translation> </message> </context> <context> <name>UBCreateLinkLabel</name> <message> <source>&lt;drop content&gt;</source> <translation>&lt;drop content&gt;</translation> </message> <message> <source>Images are not accepted</source> <translation>圖像不被辨識接受</translation> </message> <message> <source>Cannot display data</source> <translation>資料無法顯示</translation> </message> <message> <source>Dropped file isn&apos;t reconized to be an audio file</source> <translation>檔案不被辨識為音訊檔</translation> </message> </context> <context> <name>UBCreateLinkPalette</name> <message> <source>Play an audio file</source> <translation>播放音訊檔</translation> </message> <message> <source>Add Link to Page</source> <translation>新增頁面連結</translation> </message> <message> <source>Add Link to a Web page</source> <translation>新增網頁連結</translation> </message> <message> <source>Drag and drop the audio file from the library in this box</source> <translation>從圖書館拖曳音訊檔</translation> </message> <message> <source>Ok</source> <translation>Ok</translation> </message> <message> <source>Next Page</source> <translation>下一頁</translation> </message> <message> <source>Previous Page</source> <translation>上一頁</translation> </message> <message> <source>Title Page</source> <translation>標題頁</translation> </message> <message> <source>Last Page</source> <translation>前一頁</translation> </message> <message> <source>Page Number</source> <translation>頁面編號</translation> </message> <message> <source>Insert url text here</source> <translation>此處插入url</translation> </message> </context> <context> <name>UBDesktopPalette</name> <message> <source>Capture Part of the Screen</source> <translation>擷取部份螢幕</translation> </message> <message> <source>Capture the Screen</source> <translation>擷取螢幕</translation> </message> <message> <source>Show the stylus palette</source> <translation>顯示桌面工具</translation> </message> <message> <source>Show Board on Secondary Screen</source> <translation>於第二螢幕顯示演示板</translation> </message> <message> <source>Show Desktop on Secondary Screen</source> <translation>於第二螢幕顯示桌面</translation> </message> <message> <source>Show Open-Sankore</source> <translation>顯示Open-Sankore</translation> </message> </context> <context> <name>UBDocumentController</name> <message> <source>New Folder</source> <translation>新檔案夾</translation> </message> <message> <source>Page %1</source> <translation>第 %1 頁</translation> </message> <message> <source>Add Folder of Images</source> <translation>新增圖像檔案夾</translation> </message> <message> <source>Add Images</source> <translation>新增圖像</translation> </message> <message> <source>Add Pages from File</source> <translation>從檔案新增頁面</translation> </message> <message> <source>Duplicating Document %1</source> <translation>文件 %1 複製中</translation> </message> <message> <source>Document %1 copied</source> <translation>文件 %1 已複製</translation> </message> <message> <source>Remove Page</source> <translation>移除頁面</translation> </message> <message> <source>Open Supported File</source> <translation>開啟支援的檔案</translation> </message> <message> <source>Importing file %1...</source> <translation>檔案 %1 匯入中...</translation> </message> <message> <source>Failed to import file ... </source> <translation>匯入檔案失敗...</translation> </message> <message> <source>Import all Images from Folder</source> <translation>從檔案夾匯入所有圖像</translation> </message> <message> <source>Delete</source> <translation>刪除</translation> </message> <message> <source>Empty</source> <translation>清空</translation> </message> <message> <source>Trash</source> <translation>回收桶</translation> </message> <message> <source>Open Document</source> <translation>開啟文件</translation> </message> <message> <source>Add all Images to Document</source> <translation>新增所有圖像至文件</translation> </message> <message> <source>All Images (%1)</source> <translation>所有圖像( %1 )</translation> </message> <message> <source>Selection does not contain any image files!</source> <translation>所選內容並沒有圖像檔!</translation> </message> <message> <source>The document &apos;%1&apos; has been generated with a newer version of Sankore (%2). By opening it, you may lose some information. Do you want to proceed?</source> <translation>文件 &apos;%1&apos; 係由新版的Sankore (%2)所製作。若仍要開啟,可能會損失部份內容。確定要進行嗎?</translation> </message> <message numerus="yes"> <source>Are you sure you want to remove %n page(s) from the selected document &apos;%1&apos;?</source> <translation> <numerusform>確定要從所選文件 &apos;%1&apos; 移除 %n 頁?</numerusform> </translation> </message> <message> <source>Title page</source> <translation>標題頁面</translation> </message> <message> <source>Folder does not contain any image files</source> <translation>檔案夾並沒有圖像檔</translation> </message> <message> <source>Untitled Documents</source> <translation>未命名文件</translation> </message> <message> <source>This is an irreversible action!</source> <translation type="unfinished"></translation> </message> <message> <source>The model documents are not editable. Copy it to &quot;My documents&quot; to be able to work with</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> <source>duplicated %1 page</source> <comment>duplicated %1 pages</comment> <translation type="unfinished"> <numerusform></numerusform> </translation> </message> </context> <context> <name>UBDocumentManager</name> <message> <source>images</source> <translation>圖像</translation> </message> <message> <source>videos</source> <translation>影片</translation> </message> <message> <source>objects</source> <translation>物件</translation> </message> <message> <source>widgets</source> <translation>小工具</translation> </message> <message> <source>All supported files (*.%1)</source> <translation>所有支援的檔案 (*.%1)</translation> </message> <message> <source>File %1 saved</source> <translation>已儲存檔案 %1 </translation> </message> <message> <source>Inserting page %1 of %2</source> <translation>頁面 %2 的 %1 插入中</translation> </message> <message> <source>Import successful.</source> <translation>匯入成功。</translation> </message> <message> <source>Import of file %1 successful.</source> <translation>檔案 %1 匯入成功。</translation> </message> <message> <source>Importing file %1</source> <translation>匯入檔案 %1</translation> </message> </context> <context> <name>UBDocumentNavigator</name> <message> <source>Page %0</source> <translation>第 %0 頁</translation> </message> <message> <source>Title page</source> <translation>標題頁</translation> </message> </context> <context> <name>UBDocumentPublisher</name> <message> <source>Export failed.</source> <translation>匯出失敗。</translation> </message> <message> <source>Export canceled ...</source> <translation>已取消匯出...</translation> </message> <message> <source>Converting page %1/%2 ...</source> <translation>轉換頁面 %1/%2 ...</translation> </message> <message> <source>Credentials has to not been filled out yet.</source> <translation>尚未處理驗證。</translation> </message> <message> <source>Uploading Sankore File on Web.</source> <translation>Sankore檔案上傳至網際網路中。</translation> </message> <message> <source>Document uploaded correctly on the web.</source> <translation>文件已正確上傳至網際網路。</translation> </message> <message> <source>Failed to upload document on the web.</source> <translation>文件上傳至網際網路失敗。</translation> </message> </context> <context> <name>UBDocumentReplaceDialog</name> <message> <source>Accept</source> <translation>接受</translation> </message> <message> <source>Replace</source> <translation>置換</translation> </message> <message> <source>Cancel</source> <translation>取消</translation> </message> <message> <source>The name %1 is allready used. Keeping this name will replace the document. Providing a new name will create a new document.</source> <translation> %1 名稱已被使用。 使用本名稱,文件會被置換。 使用新名稱,則會產生新文件。</translation> </message> </context> <context> <name>UBDocumentTreeModel</name> <message> <source>My documents</source> <translation>我的文件</translation> </message> <message> <source>Models</source> <translation>Models</translation> </message> <message> <source>Trash</source> <translation>回收桶</translation> </message> <message> <source>Untitled documents</source> <translation>尙未標題文件</translation> </message> <message numerus="yes"> <source>%1 pages copied</source> <translation type="unfinished"> <numerusform>已複製 %1 頁</numerusform> </translation> </message> </context> <context> <name>UBDocumentTreeView</name> <message numerus="yes"> <source>%1 pages copied</source> <translation type="unfinished"> <numerusform>已複製 %1 頁</numerusform> </translation> </message> </context> <context> <name>UBDocumentTreeWidget</name> <message> <source>%1 (copy)</source> <translation>%1 (copy)</translation> </message> <message> <source>Copying page %1/%2</source> <translation>頁面 %1/%2 複製中</translation> </message> <message numerus="yes"> <source>%1 pages copied</source> <translation> <numerusform>已複製 %1 頁</numerusform> </translation> </message> </context> <context> <name>UBDownloadManager</name> <message> <source>Download failed.</source> <translation>下載失敗</translation> </message> <message> <source>the remote server refused the connection (the server is not accepting requests)</source> <translation>外部remote server 拒絕連線 (the server is not accepting requests)</translation> </message> <message> <source>the remote server closed the connection prematurely, before the entire reply was received and processed</source> <translation>早在reply被接收且處理之前,外部remote server 就關閉連線。</translation> </message> <message> <source>the remote host name was not found (invalid hostname)</source> <translation>the remote host name was not found (invalid hostname)</translation> </message> <message> <source>the connection to the remote server timed out</source> <translation>外部伺服器remote server timed out</translation> </message> <message> <source>the operation was canceled via calls to abort() or close() before it was finished.</source> <translation>the operation was canceled via calls to abort() or close() before it was finished.</translation> </message> <message> <source>the SSL/TLS handshake failed and the encrypted channel could not be established. The sslErrors() signal should have been emitted.</source> <translation>the SSL/TLS handshake failed and the encrypted channel could not be established. The sslErrors() signal should have been emitted.</translation> </message> <message> <source>the connection was broken due to disconnection from the network, however the system has initiated roaming to another access point. The request should be resubmitted and will be processed as soon as the connection is re-established.</source> <translation>網路連線失效。系統已啟動它點roaming。需重新提交request,待連線回復方能處理。</translation> </message> <message> <source>the connection to the proxy server was refused (the proxy server is not accepting requests)</source> <translation>proxy伺服器連結被拒 (the proxy server is not accepting requests)</translation> </message> <message> <source>the proxy server closed the connection prematurely, before the entire reply was received and processed</source> <translation>早在reply被接收且處理之前,proxy server 就關閉連線。</translation> </message> <message> <source>the proxy host name was not found (invalid proxy hostname)</source> <translation>the proxy host name was not found (invalid proxy hostname)</translation> </message> <message> <source>the connection to the proxy timed out or the proxy did not reply in time to the request sent</source> <translation>proxy timed out 或 the proxy 沒有回應</translation> </message> <message> <source>the proxy requires authentication in order to honour the request but did not accept any credentials offered (if any)</source> <translation>proxy 需要認証才能處理要求,但並未通過任何提供的資料(如果有的話)</translation> </message> <message> <source>the access to the remote content was denied (similar to HTTP error 401)</source> <translation>外部內容存取被拒 (similar to HTTP error 401)</translation> </message> <message> <source>the operation requested on the remote content is not permitted</source> <translation>外部的request不被允許</translation> </message> <message> <source>the remote content was not found at the server (similar to HTTP error 404)</source> <translation>the remote content was not found at the server (similar to HTTP error 404)</translation> </message> <message> <source>the remote server requires authentication to serve the content but the credentials provided were not accepted (if any)</source> <translation>外部remote server 需要認証才能處理,但並未通過任何提供的資料(如果有的話)</translation> </message> <message> <source>the request needed to be sent again, but this failed for example because the upload data could not be read a second time.</source> <translation>the request needed to be sent again, but this failed for example because the upload data could not be read a second time.</translation> </message> <message> <source>the Network Access API cannot honor the request because the protocol is not known</source> <translation>因為protocol 未知,Network Access API的request不被處理。</translation> </message> <message> <source>the requested operation is invalid for this protocol</source> <translation>the requested operation is invalid for this protocol</translation> </message> <message> <source>an unknown network-related error was detected</source> <translation>偵測到網路有錯誤</translation> </message> <message> <source>an unknown proxy-related error was detected</source> <translation>偵測到proxy相關的錯誤</translation> </message> <message> <source>an unknown error related to the remote content was detected</source> <translation>偵測到外部內容有錯誤</translation> </message> <message> <source>a breakdown in protocol was detected (parsing error, invalid or unexpected responses, etc.)</source> <translation>偵測到protocol錯誤 (parsing error, invalid or unexpected responses, etc.)</translation> </message> </context> <context> <name>UBDownloadWidget</name> <message> <source>Downloading files</source> <translation>檔案下載中</translation> </message> <message> <source>Cancel</source> <translation>取消</translation> </message> </context> <context> <name>UBExportAdaptor</name> <message> <source>Warnings during export was appeared</source> <translation>匯出過程出現警告</translation> </message> </context> <context> <name>UBExportCFF</name> <message> <source>Export to IWB</source> <translation>匯出至IWB</translation> </message> <message> <source>Export as IWB File</source> <translation>以IWB格式匯出</translation> </message> <message> <source>Exporting document...</source> <translation>匯出文件...</translation> </message> <message> <source>Export successful.</source> <translation>成功匯出。</translation> </message> <message> <source>Export failed.</source> <translation>匯出失敗。</translation> </message> </context> <context> <name>UBExportDocument</name> <message> <source>Page</source> <translation>頁面</translation> </message> <message> <source>Export as UBZ File</source> <translation>以UBZ格式匯出</translation> </message> <message> <source>Exporting document...</source> <translation>文件匯出中...</translation> </message> <message> <source>Export successful.</source> <translation>匯出成功。</translation> </message> <message> <source>Exporting %1 %2 of %3</source> <translation> %3 的 %1 %2 匯出中</translation> </message> <message> <source>Export to Sankore Format</source> <translation>匯出成Sankore格式</translation> </message> </context> <context> <name>UBExportDocumentSetAdaptor</name> <message> <source>Failed to export...</source> <translation>匯出失敗...</translation> </message> <message> <source>Export as UBX File</source> <translation>以UBZ格式匯出</translation> </message> <message> <source>Exporting document...</source> <translation>文件匯出中...</translation> </message> <message> <source>Export successful.</source> <translation>匯出成功。</translation> </message> <message> <source>Export failed.</source> <translation>匯出失敗。</translation> </message> <message> <source>Export to Sankore UBX Format</source> <translation>匯出成Sankore UBX格式</translation> </message> </context> <context> <name>UBExportFullPDF</name> <message> <source>Export as PDF File</source> <translation>以PDF格式匯出</translation> </message> <message> <source>Exporting document...</source> <translation>匯出文件中...</translation> </message> <message> <source>Export to PDF</source> <translation>匯出成PDF</translation> </message> <message> <source>Export successful.</source> <translation>匯出成功。</translation> </message> </context> <context> <name>UBExportPDF</name> <message> <source>Export as PDF File</source> <translation>以PDF格式匯出</translation> </message> <message> <source>Exporting page %1 of %2</source> <translation>頁面 %2 的 %1 匯出中</translation> </message> <message> <source>Export successful.</source> <translation>匯出成功。</translation> </message> <message> <source>Exporting document...</source> <translation>匯出文件中...</translation> </message> <message> <source>Export to PDF</source> <translation>匯出成PDF</translation> </message> </context> <context> <name>UBExportWeb</name> <message> <source>Page</source> <translation>頁面</translation> </message> <message> <source>Export as Web data</source> <translation>以網頁資料格式匯出</translation> </message> <message> <source>Exporting document...</source> <translation>匯出文件中...</translation> </message> <message> <source>Export successful.</source> <translation>匯出成功。</translation> </message> <message> <source>Export failed.</source> <translation>匯出失敗。</translation> </message> <message> <source>Export to Web Browser</source> <translation>匯出成網頁瀏覽</translation> </message> </context> <context> <name>UBFeatureProperties</name> <message> <source>Add to page</source> <translation>新增至頁面</translation> </message> <message> <source>Set as background</source> <translation>設定成背景</translation> </message> <message> <source>Add to library</source> <translation>新增至圖書館</translation> </message> <message> <source>Object informations</source> <translation>物件資訊</translation> </message> <message> <source>Add</source> <translation type="unfinished">新增</translation> </message> </context> <context> <name>UBFeaturesActionBar</name> <message> <source>Add to favorites</source> <translation>新增至我的最愛</translation> </message> <message> <source>Share</source> <translation>分享</translation> </message> <message> <source>Search</source> <translation>搜尋</translation> </message> <message> <source>Delete</source> <translation>刪除</translation> </message> <message> <source>Back to folder</source> <translation>回到檔案夾</translation> </message> <message> <source>Remove from favorites</source> <translation>從我的最愛移除</translation> </message> <message> <source>Create new folder</source> <translation>新建檔案夾</translation> </message> <message> <source>Rescan file system</source> <translation>重新掃描檔案系統</translation> </message> </context> <context> <name>UBFeaturesController</name> <message> <source>ImportedImage</source> <translation>匯入的圖像</translation> </message> <message> <source>Audios</source> <translation>音訊</translation> </message> <message> <source>Movies</source> <translation>影片</translation> </message> <message> <source>Pictures</source> <translation>圖案</translation> </message> <message> <source>Animations</source> <translation>動畫</translation> </message> <message> <source>Interactivities</source> <translation>互動</translation> </message> <message> <source>Applications</source> <translation>應用程式</translation> </message> <message> <source>Shapes</source> <translation>形狀</translation> </message> <message> <source>Favorites</source> <translation>我的最愛</translation> </message> <message> <source>Web search</source> <translation>網路搜尋</translation> </message> <message> <source>Trash</source> <translation>回收桶</translation> </message> <message> <source>Bookmarks</source> <translation>書籤</translation> </message> <message> <source>Web</source> <translation>網路</translation> </message> </context> <context> <name>UBFeaturesNewFolderDialog</name> <message> <source>Accept</source> <translation>接受</translation> </message> <message> <source>Cancel</source> <translation>取消</translation> </message> <message> <source>Enter a new folder name</source> <translation>鍵入檔案名稱</translation> </message> </context> <context> <name>UBFeaturesProgressInfo</name> <message> <source>Loading </source> <translation>載入中</translation> </message> </context> <context> <name>UBGraphicsGroupContainerItemDelegate</name> <message> <source>Locked</source> <translation>鎖定</translation> </message> <message> <source>Visible on Extended Screen</source> <translation>於延伸螢幕可見</translation> </message> <message> <source>Add an action</source> <translation>新增動作</translation> </message> <message> <source>Remove link to audio</source> <translation>移除音訊檔連結</translation> </message> <message> <source>Remove link to page</source> <translation>移除頁面連結</translation> </message> <message> <source>Remove link to web url</source> <translation>移除網路url連結</translation> </message> </context> <context> <name>UBGraphicsItemDelegate</name> <message> <source>Locked</source> <translation>鎖定</translation> </message> <message> <source>Visible on Extended Screen</source> <translation>於延伸螢幕可見</translation> </message> <message> <source>Go to Content Source</source> <translation>至內容來源</translation> </message> <message> <source>Add an action</source> <translation>新增動作</translation> </message> <message> <source>Remove link to audio</source> <translation>移除音訊檔連結</translation> </message> <message> <source>Remove link to page</source> <translation>移除頁面連結</translation> </message> <message> <source>Remove link to web url</source> <translation>移除網路url連結</translation> </message> </context> <context> <name>UBGraphicsTextItem</name> <message> <source>&lt;Type Text Here&gt;</source> <translation>&lt;此處鍵入文字&gt;</translation> </message> </context> <context> <name>UBGraphicsTextItemDelegate</name> <message> <source>Text Color</source> <translation>文字顏色</translation> </message> <message> <source>Editable</source> <translation>可編輯</translation> </message> </context> <context> <name>UBGraphicsWidgetItem</name> <message> <source>Loading ...</source> <translation>載入中...</translation> </message> </context> <context> <name>UBGraphicsWidgetItemDelegate</name> <message> <source>Frozen</source> <translation>凍結</translation> </message> <message> <source>Transform as Tool </source> <translation>轉換為工具</translation> </message> </context> <context> <name>UBImportCFF</name> <message> <source>Common File Format (</source> <translation>常見檔案格式 (</translation> </message> <message> <source>Importing file %1...</source> <translation>檔案 %1 匯入中...</translation> </message> <message> <source>Import of file %1 failed.</source> <translation>檔案 %1 匯入失敗。</translation> </message> <message> <source>Import successful.</source> <translation>匯入成功。</translation> </message> <message> <source>Import failed.</source> <translation>匯入失敗。</translation> </message> </context> <context> <name>UBImportDocument</name> <message> <source>Importing file %1...</source> <translation>檔案 %1 匯入中...</translation> </message> <message> <source>Import successful.</source> <translation>匯入成功。</translation> </message> <message> <source>Import of file %1 failed.</source> <translation>檔案 %1 匯入失敗。</translation> </message> <message> <source>Open-Sankore (*.ubz)</source> <translation>Open-Sankore (*.ubz)</translation> </message> </context> <context> <name>UBImportDocumentSetAdaptor</name> <message> <source>Open-Sankore (set of documents) (*.ubx)</source> <translation>Open-Sankore (set of documents) (*.ubx)</translation> </message> </context> <context> <name>UBImportImage</name> <message> <source>Image Format (</source> <translation>圖像格式(</translation> </message> </context> <context> <name>UBImportPDF</name> <message> <source>Portable Document Format (*.pdf)</source> <translation>Portable Document Format (*.pdf)</translation> </message> <message> <source>PDF import failed.</source> <translation>PDF匯入失敗。</translation> </message> <message> <source>Importing page %1 of %2</source> <translation>頁面 %2 的 %1 匯入中</translation> </message> </context> <context> <name>UBIntranetPodcastPublisher</name> <message> <source>Error while publishing video to intranet (%1)</source> <translation>影片發佈到內部網路 (%1) 時有錯誤</translation> </message> <message> <source>Publishing to Intranet in progress %1 %</source> <translation>發佈到內部網路中 %1 %</translation> </message> </context> <context> <name>UBIntranetPodcastPublishingDialog</name> <message> <source>Publish</source> <translation>發佈</translation> </message> </context> <context> <name>UBKeyboardPalette</name> <message> <source>Enter</source> <translation>鍵入</translation> </message> </context> <context> <name>UBMainWindow</name> <message> <source>Yes</source> <translation>是</translation> </message> <message> <source>No</source> <translation>否</translation> </message> <message> <source>Ok</source> <translation>Ok</translation> </message> </context> <context> <name>UBMessagesDialog</name> <message> <source>Close</source> <translation>關閉</translation> </message> </context> <context> <name>UBNetworkAccessManager</name> <message> <source>&lt;qt&gt;Enter username and password for &quot;%1&quot; at %2&lt;/qt&gt;</source> <translation>&lt;qt&gt;輸入 &quot;%1&quot; 在 %2 的帳號密碼&lt;/qt&gt;</translation> </message> <message> <source>Failed to log to Proxy</source> <translation>登入Proxy失敗</translation> </message> <message> <source>Yes</source> <translation>是</translation> </message> <message> <source>No</source> <translation>否</translation> </message> <message> <source>SSL Errors: %1 %2 Do you want to ignore these errors for this host?</source> <translation>SSL Errors: %1 %2 是否要忽略這些錯誤?</translation> </message> </context> <context> <name>UBPersistenceManager</name> <message> <source>(copy)</source> <translation>(複製)</translation> </message> <message> <source>Document Repository Loss</source> <translation>文件資料庫遺失</translation> </message> <message> <source>Sankore has lost access to the document repository &apos;%1&apos;. Unfortunately the application must shut down to avoid data corruption. Latest changes may be lost as well.</source> <translation>Sankore已經與文件資料庫 &apos;%1&apos; 失去連繫. 很不幸本程式必須關閉以免資料毀損,相對的變動也將無效。</translation> </message> </context> <context> <name>UBPlatformUtils</name> <message> <source>English</source> <translation>英文</translation> </message> <message> <source>Russian</source> <translation>俄文</translation> </message> <message> <source>German</source> <translation>德文</translation> </message> <message> <source>French</source> <translation>法文</translation> </message> <message> <source>Swiss French</source> <translation>法文(瑞士)</translation> </message> </context> <context> <name>UBPodcastController</name> <message> <source>Failed to start encoder ...</source> <translation>編碼器(encoder)啟動失敗...</translation> </message> <message> <source>No Podcast encoder available ...</source> <translation>沒有可用的Podcast編碼器(encoder)...</translation> </message> <message> <source>Part %1</source> <translation>Part %1</translation> </message> <message> <source>on your desktop ...</source> <translation>在您的桌面...</translation> </message> <message> <source>in folder %1</source> <translation>在檔案夾 %1 中</translation> </message> <message> <source>Podcast created %1</source> <translation>Podcast 已建立 %1</translation> </message> <message> <source>Podcast recording error (%1)</source> <translation>Podcast錄製有錯誤 (%1)</translation> </message> <message> <source>Default Audio Input</source> <translation>預設的音頻輸入</translation> </message> <message> <source>No Audio Recording</source> <translation>無音頻錄製</translation> </message> <message> <source>Small</source> <translation>小</translation> </message> <message> <source>Medium</source> <translation>中</translation> </message> <message> <source>Full</source> <translation>大</translation> </message> <message> <source>Publish to Intranet</source> <translation>發佈到內部網路</translation> </message> <message> <source>Publish to Youtube</source> <translation>發佈至YouTube</translation> </message> <message> <source>Sankore Cast</source> <translation>Sankore Cast</translation> </message> </context> <context> <name>UBPreferencesController</name> <message> <source>version: </source> <translation>版本:</translation> </message> <message> <source>Marker is pressure sensitive</source> <translation>感壓型提示筆</translation> </message> <message> <source>Default</source> <translation>預設</translation> </message> <message> <source>Arabic</source> <translation>阿拉伯文</translation> </message> <message> <source>Bulgarian</source> <translation>Bulgarian</translation> </message> <message> <source>Catalan</source> <translation>Catalan</translation> </message> <message> <source>Czech</source> <translation>Czech</translation> </message> <message> <source>Danish</source> <translation>Danish</translation> </message> <message> <source>German</source> <translation>德文</translation> </message> <message> <source>Greek</source> <translation>希臘文</translation> </message> <message> <source>English</source> <translation>英文</translation> </message> <message> <source>English UK</source> <translation>英文-UK</translation> </message> <message> <source>Spanish</source> <translation>西班牙文</translation> </message> <message> <source>French</source> <translation>法文</translation> </message> <message> <source>Swiss French</source> <translation>法文(瑞士)</translation> </message> <message> <source>Italian</source> <translation>義大利文</translation> </message> <message> <source>Hebrew</source> <translation>希伯來文</translation> </message> <message> <source>Japanese</source> <translation>日文</translation> </message> <message> <source>Korean</source> <translation>韓文</translation> </message> <message> <source>Malagasy</source> <translation>Malagasy</translation> </message> <message> <source>Norwegian</source> <translation>挪威文</translation> </message> <message> <source>Dutch</source> <translation>Dutch</translation> </message> <message> <source>Polish</source> <translation>波蘭文</translation> </message> <message> <source>Romansh</source> <translation>Romansh</translation> </message> <message> <source>Romanian</source> <translation>Romanian</translation> </message> <message> <source>Russian</source> <translation>俄文</translation> </message> <message> <source>Slovak</source> <translation>Slovak</translation> </message> <message> <source>Swedish</source> <translation>瑞典文</translation> </message> <message> <source>Turkish</source> <translation>土耳其文</translation> </message> <message> <source>Chinese</source> <translation>中文</translation> </message> <message> <source>Chinese Simplified</source> <translation>簡體中文</translation> </message> <message> <source>Chinese Traditional</source> <translation>正體中文</translation> </message> <message> <source>Corsican</source> <translation type="unfinished"></translation> </message> <message> <source>Hindi</source> <translation type="unfinished"></translation> </message> <message> <source>Portuguese</source> <translation type="unfinished"></translation> </message> <message> <source>Basque</source> <translation type="unfinished"></translation> </message> <message> <source>Bambara</source> <translation type="unfinished"></translation> </message> <message> <source>Galician</source> <translation type="unfinished"></translation> </message> </context> <context> <name>UBProxyLoginDlg</name> <message> <source>Proxy Login</source> <translation>Proxy登入</translation> </message> <message> <source>Username:</source> <translation>帳號:</translation> </message> <message> <source>Password:</source> <translation>密碼:</translation> </message> </context> <context> <name>UBPublicationDlg</name> <message> <source>Publish document on the web</source> <translation>發佈文件至網路</translation> </message> <message> <source>Title:</source> <translation>標題:</translation> </message> <message> <source>Description:</source> <translation>描述:</translation> </message> <message> <source>Publish</source> <translation>發佈</translation> </message> </context> <context> <name>UBSettings</name> <message> <source>My Movies</source> <translation>我的影片</translation> </message> <message> <source>/Web</source> <translation>/Web</translation> </message> </context> <context> <name>UBStartupHintsPalette</name> <message> <source>Visible next time</source> <translation>下次顯現</translation> </message> </context> <context> <name>UBTGActionWidget</name> <message> <source>Teacher</source> <translation>教師</translation> </message> <message> <source>Student</source> <translation>學生</translation> </message> <message> <source>Type task here ...</source> <translation>此處鍵入任務...</translation> </message> </context> <context> <name>UBTGMediaWidget</name> <message> <source>drop media here ...</source> <translation>此處放置媒體...</translation> </message> <message> <source>Type title here...</source> <translation>此處鍵入標題...</translation> </message> <message> <source>Drag and drop</source> <translation type="unfinished"></translation> </message> <message> <source>The currect action is not supported. The teacher bar is design to work only with media stored locally.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>UBTGUrlWidget</name> <message> <source>Insert link title here...</source> <translation>此處插入標題連結...</translation> </message> </context> <context> <name>UBTeacherGuideEditionWidget</name> <message> <source>Type title here ...</source> <translation>此處鍵入標題...</translation> </message> <message> <source>Type comment here ...</source> <translation>此處鍵入評語...</translation> </message> <message> <source>Add an action</source> <translation>新增動作</translation> </message> <message> <source>Add a media</source> <translation>新增媒體</translation> </message> <message> <source>Add a link</source> <translation>新增連結</translation> </message> <message> <source>Page: %0</source> <translation>第 %0 頁</translation> </message> </context> <context> <name>UBTeacherGuidePageZeroWidget</name> <message> <source>Type session title here ...</source> <translation>於此處輸入標題...</translation> </message> <message> <source>Author(s)</source> <translation>作者</translation> </message> <message> <source>Type authors here ...</source> <translation>此處鍵入作者...</translation> </message> <message> <source>Objective(s)</source> <translation>目標</translation> </message> <message> <source>Type objectives here...</source> <translation>此處鍵入目標內容...</translation> </message> <message> <source>Resource indexing</source> <translation>Resource indexing</translation> </message> <message> <source>Keywords:</source> <translation>關鍵字:</translation> </message> <message> <source>Type keywords here ...</source> <translation>此處鍵入關鍵字...</translation> </message> <message> <source>Level:</source> <translation>等級:</translation> </message> <message> <source>Subjects:</source> <translation>主題:</translation> </message> <message> <source>Type:</source> <translation>類型:</translation> </message> <message> <source>Licence</source> <translation>授權</translation> </message> <message> <source>Attribution CC BY</source> <translation>Attribution CC BY</translation> </message> <message> <source>Attribution-NoDerivs CC BY-ND</source> <translation>Attribution-NoDerivs CC BY-ND</translation> </message> <message> <source>Attribution-ShareAlike CC BY-SA</source> <translation>Attribution-ShareAlike CC BY-SA</translation> </message> <message> <source>Attribution-NonCommercial CC BY-NC</source> <translation>Attribution-NonCommercial CC BY-NC</translation> </message> <message> <source>Attribution-NonCommercial-NoDerivs CC BY-NC-ND</source> <translation>Attribution-NonCommercial-NoDerivs CC BY-NC-ND</translation> </message> <message> <source>Attribution-NonCommercial-ShareAlike CC BY-NC-SA</source> <translation>Attribution-NonCommercial-ShareAlike CC BY-NC-SA</translation> </message> <message> <source>Public domain</source> <translation>Public domain</translation> </message> <message> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <source>Created the: </source> <translation>已建立: </translation> </message> <message> <source>Updated the: </source> <translation>已更新: </translation> </message> <message> <source>Title page</source> <translation>標題頁</translation> </message> </context> <context> <name>UBTeacherGuidePresentationWidget</name> <message> <source>Page: %0</source> <translation>第 %0 頁</translation> </message> </context> <context> <name>UBThumbnailAdaptor</name> <message> <source>Generating preview thumbnails ...</source> <translation>產生預覽縮圖中...</translation> </message> <message> <source>%1 thumbnails generated ...</source> <translation>已產生縮圖 %1...</translation> </message> </context> <context> <name>UBToolsManager</name> <message> <source>Compass</source> <translation>圓規</translation> </message> <message> <source>Ruler</source> <translation>尺</translation> </message> <message> <source>Protractor</source> <translation>量角器</translation> </message> <message> <source>Mask</source> <translation>遮罩</translation> </message> <message> <source>Triangle</source> <translation>三角形</translation> </message> <message> <source>Magnifier</source> <translation>放大鏡</translation> </message> <message> <source>Cache</source> <translation>Cache</translation> </message> </context> <context> <name>UBTrapWebPageContentController</name> <message> <source>Whole page</source> <translation>整頁</translation> </message> <message> <source>Embed </source> <translation>Embed </translation> </message> </context> <context> <name>UBUpdateDlg</name> <message> <source>Document updater</source> <translation>文件更新器</translation> </message> <message> <source> files require an update.</source> <translation>檔案需要更新。</translation> </message> <message> <source>Backup path: </source> <translation>備份檔案路徑:</translation> </message> <message> <source>Browse</source> <translation>瀏覽</translation> </message> <message> <source>Update</source> <translation>更新</translation> </message> <message> <source>Select a backup folder</source> <translation>選擇備份檔案夾</translation> </message> <message> <source>Files update successful! Please reboot the application to access the updated documents.</source> <translation>成功更新檔案! 請重新啟動程式使用該檔案。</translation> </message> <message> <source>An error occured during the update. The files have not been affected.</source> <translation>更新過程出現錯誤,原檔案並未更動。</translation> </message> <message> <source>Files update results</source> <translation>檔案更新結果</translation> </message> <message> <source>Updating file </source> <translation>更新檔案中</translation> </message> <message> <source>Please wait the import process will start soon...</source> <translation>即將開始匯入,請稍待...</translation> </message> <message> <source>Remind me later</source> <translation>稍候題提醒我</translation> </message> </context> <context> <name>UBWebPluginWidget</name> <message> <source>Loading...</source> <translation>載入中...</translation> </message> </context> <context> <name>UBWebPublisher</name> <message> <source>Publish Document on Sankore Web</source> <translation>發佈文件在Sankore網頁</translation> </message> </context> <context> <name>UBWidgetUniboardAPI</name> <message> <source>%0 called (method=%1, status=%2)</source> <translation>已呼叫 %0 (方法= %1 , 狀態= %2 )</translation> </message> </context> <context> <name>UBYouTubePublisher</name> <message> <source>YouTube authentication failed.</source> <translation>YouTube驗證失敗。</translation> </message> <message> <source>Error while uploading video to YouTube (%1)</source> <translation>影片上傳至YouTube (%1)過程中有錯誤</translation> </message> <message> <source>Upload to YouTube in progress %1 %</source> <translation>上傳至YouTube中 %1 %</translation> </message> <message> <source>Open-Sankore</source> <translation>Open-Sankore</translation> </message> <message> <source>OpenSankore</source> <translation>OpenSankore</translation> </message> </context> <context> <name>UBYouTubePublishingDialog</name> <message> <source>Upload</source> <translation>上傳</translation> </message> <message> <source>Autos &amp; Vehicles</source> <translation>各類交通工具</translation> </message> <message> <source>Music</source> <translation>音樂</translation> </message> <message> <source>Pets &amp; Animals</source> <translation>寵物與動物</translation> </message> <message> <source>Sports</source> <translation>運動</translation> </message> <message> <source>Travel &amp; Events</source> <translation>旅遊與活動</translation> </message> <message> <source>Gaming</source> <translation>遊戲</translation> </message> <message> <source>Comedy</source> <translation>喜劇</translation> </message> <message> <source>People &amp; Blogs</source> <translation>人物與網誌</translation> </message> <message> <source>News &amp; Politics</source> <translation>新聞與政治</translation> </message> <message> <source>Entertainment</source> <translation>娛樂</translation> </message> <message> <source>Education</source> <translation>教育</translation> </message> <message> <source>Howto &amp; Style</source> <translation>DIY 教學</translation> </message> <message> <source>Nonprofits &amp; Activism</source> <translation>非營利組織與行動主義</translation> </message> <message> <source>Science &amp; Technology</source> <translation>科學與技術</translation> </message> </context> <context> <name>UBZoomPalette</name> <message> <source>%1 x</source> <translation>%1 x</translation> </message> </context> <context> <name>UniboardSankoreTransition</name> <message> <source>Import old Uniboard/Sankore documents</source> <translation>匯入舊的Uniboard/Sankore文件</translation> </message> <message> <source>There are no documents that should be imported</source> <translation>沒有文件需要匯入</translation> </message> </context> <context> <name>WBClearButton</name> <message> <source>Clear</source> <translation>清空</translation> </message> </context> <context> <name>WBDownloadItem</name> <message> <source>Save File</source> <translation>儲存檔案</translation> </message> <message> <source>Download canceled: %1</source> <translation>取消下載: %1</translation> </message> <message> <source>Error opening saved file: %1</source> <translation>已存檔案開啟時有錯誤: %1</translation> </message> <message> <source>Error saving: %1</source> <translation>儲存錯誤: %1</translation> </message> <message> <source>Network Error: %1</source> <translation>網路錯誤: %1</translation> </message> <message> <source>seconds</source> <translation>秒</translation> </message> <message> <source>minutes</source> <translation>分</translation> </message> <message> <source>- %4 %5 remaining</source> <translation>- 還剩下 %4 %5 </translation> </message> <message> <source>%1 of %2 (%3/sec) %4</source> <translation>%2 的 %1 (%3/秒) %4</translation> </message> <message> <source>%1 of %2 - Stopped</source> <translation>%2 的 %1 - 已停止</translation> </message> <message> <source>bytes</source> <translation>bytes</translation> </message> <message> <source>KB</source> <translation>KB</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>?</source> <comment>unknown file size</comment> <translatorcomment>檔案大小未知</translatorcomment> <translation>?</translation> </message> </context> <context> <name>WBDownloadManager</name> <message> <source>1 Download</source> <translation>1 個下載</translation> </message> <message> <source>%1 Downloads</source> <comment>always &gt;= 2</comment> <translatorcomment>永遠 &gt;= 2</translatorcomment> <translation>%1 個下載</translation> </message> </context> <context> <name>WBHistoryModel</name> <message> <source>Title</source> <translation>標題</translation> </message> <message> <source>Address</source> <translation>地址</translation> </message> </context> <context> <name>WBHistoryTreeModel</name> <message> <source>Earlier Today</source> <translation>今日稍早</translation> </message> <message> <source>%1 items</source> <translation>%1 個項目</translation> </message> </context> <context> <name>WBSearchLineEdit</name> <message> <source>Search</source> <translation>搜尋</translation> </message> </context> <context> <name>WBTabBar</name> <message> <source>New &amp;Tab</source> <translation>新建分頁(&amp;T)</translation> </message> <message> <source>Clone Tab</source> <translation>複製分頁</translation> </message> <message> <source>&amp;Close Tab</source> <translation>關閉分頁(&amp;C)</translation> </message> <message> <source>Close &amp;Other Tabs</source> <translation>關閉其他分頁 (&amp;O)</translation> </message> <message> <source>Reload Tab</source> <translation>重新載入分頁</translation> </message> <message> <source>Reload All Tabs</source> <translation>重新載入所有分頁</translation> </message> </context> <context> <name>WBTabWidget</name> <message> <source>Recently Closed Tabs</source> <translation>最近關閉的分頁</translation> </message> <message> <source>(Untitled)</source> <translation>空白頁</translation> </message> </context> <context> <name>WBToolbarSearch</name> <message> <source>Search</source> <translation>搜尋</translation> </message> <message> <source>No Recent Searches</source> <translation>無近期搜尋</translation> </message> <message> <source>Recent Searches</source> <translation>近期搜尋</translation> </message> <message> <source>Clear Recent Searches</source> <translation>清除近期搜尋</translation> </message> </context> <context> <name>WBTrapWebPageContentWindow</name> <message> <source>Select content to trap:</source> <translation>選擇要截取的內容</translation> </message> <message> <source>Application name</source> <translation>應用程式名稱</translation> </message> <message> <source>Restriction and disclaimer. </source> <translation>限制與免責聲明</translation> </message> <message> <source>This feature is developed to work on the most common web pages.</source> <translation>本特色係應一般最常見網頁所開發</translation> </message> <message> <source>Please respect copyrights for creating links or trapping content from the web.</source> <translation>對於任何網路連結或內容截取,請尊重智慧財產權</translation> </message> <message> <source>Download to library</source> <translation type="unfinished"></translation> </message> <message> <source>Download to current page</source> <translation type="unfinished"></translation> </message> <message> <source>Add link to library</source> <translation type="unfinished"></translation> </message> <message> <source>Add link to current page</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WBWebPage</name> <message> <source>Download</source> <translation>下載</translation> </message> <message> <source>Add to Current Document</source> <translation>新增至目前文件</translation> </message> <message> <source>PDF</source> <translation>PDF</translation> </message> <message> <source>Error loading page: %1</source> <translation>頁面載入錯誤: %1</translation> </message> <message> <source>Download PDF Document: would you prefer to download the PDF file or add it to the current Sankore document?</source> <translation>下載PDF文件: 您要下載成PDF檔或是新增至目前的Sankore文件?</translation> </message> </context> <context> <name>WBWebView</name> <message> <source>Open in New Tab</source> <translation>於新分頁中開啟</translation> </message> </context> <context> <name>YouTubePublishingDialog</name> <message> <source>Publish Podcast to YouTube</source> <translation>發佈Podcast至YouTube</translation> </message> <message> <source>Title</source> <translation>標題</translation> </message> <message> <source>Description</source> <translation>描述</translation> </message> <message> <source>Keywords</source> <translation>關鍵字</translation> </message> <message> <source>Uniboard</source> <translation>Uniboard</translation> </message> <message> <source>Category</source> <translation>類別</translation> </message> <message> <source>YouTube Username</source> <translation>YouTube帳號</translation> </message> <message> <source>YouTube Password</source> <translation>YouTube密碼</translation> </message> <message> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:&apos;Lucida Grande&apos;; font-size:10pt;&quot;&gt;By clicking &apos;Upload,&apos; you certify that you own all rights to the content or that you are authorized by the owner to make the content publicly available on YouTube, and that it otherwise complies with the YouTube Terms of Service located at &lt;/span&gt;&lt;a href=&quot;http://www.youtube.com/t/terms&quot;&gt;&lt;span style=&quot; font-family:&apos;Lucida Grande&apos;; font-size:10pt; text-decoration: underline; color:#0000ff;&quot;&gt;http://www.youtube.com/t/terms&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;MS Shell Dlg 2&apos;; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:&apos;Lucida Grande&apos;; font-size:10pt;&quot;&gt;By clicking &apos;Upload,&apos; you certify that you own all rights to the content or that you are authorized by the owner to make the content publicly available on YouTube, and that it otherwise complies with the YouTube Terms of Service located at &lt;/span&gt;&lt;a href=&quot;http://www.youtube.com/t/terms&quot;&gt;&lt;span style=&quot; font-family:&apos;Lucida Grande&apos;; font-size:10pt; text-decoration: underline; color:#0000ff;&quot;&gt;http://www.youtube.com/t/terms&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <source>Restore credentials on reboot</source> <translation>Restore credentials on reboot</translation> </message> </context> <context> <name>brushProperties</name> <message> <source>Opacity</source> <translation>透明度</translation> </message> <message> <source>On Light Background</source> <translation>淡色背景</translation> </message> <message> <source>On Dark Background</source> <translation>深色背景</translation> </message> <message> <source>Line Width</source> <translation>線寬</translation> </message> <message> <source>Medium</source> <translation>中</translation> </message> <message> <source>Strong</source> <translation>粗</translation> </message> <message> <source>Fine</source> <translation>細</translation> </message> <message> <source>Pen is Pressure Sensitive</source> <translation>感壓筆</translation> </message> </context> <context> <name>capturePublishingDialog</name> <message> <source>Dialog</source> <translation>對話</translation> </message> <message> <source>Title</source> <translation>標題</translation> </message> <message> <source>E-mail</source> <translation>E-mail</translation> </message> <message> <source>Author</source> <translation>作者</translation> </message> <message> <source>Description</source> <translation>描述</translation> </message> </context> <context> <name>documentPublishingDialog</name> <message> <source>Dialog</source> <translation>對話</translation> </message> <message> <source>Title</source> <translation>標題</translation> </message> <message> <source>E-mail</source> <translation>E-mail</translation> </message> <message> <source>Author</source> <translation>作者</translation> </message> <message> <source>Description</source> <translation>描述</translation> </message> <message> <source>Attach Downloadable PDF Version</source> <translation>附上可下載的PDF版本</translation> </message> <message> <source>Attach Downloadable Uniboard File (UBZ)</source> <translation>附上可下載的Uniboard(UBZ)版本</translation> </message> <message> <source>Warning: This documents contains video, which will not be displayed properly on the Web</source> <translation>警示: 本文件內含影片,但在網頁上不會正常播放</translation> </message> </context> <context> <name>documents</name> <message> <source>Uniboard Documents</source> <translation>Uniboard文件</translation> </message> </context> <context> <name>preferencesDialog</name> <message> <source>Preferences</source> <translation>偏好設定</translation> </message> <message> <source>Default Settings</source> <translation>預設</translation> </message> <message> <source>Close</source> <translation>關閉</translation> </message> <message> <source>Display</source> <translation>顯示</translation> </message> <message> <source>Show Page with External Browser</source> <translation>用外部瀏覽器顯示頁面</translation> </message> <message> <source>Virtual Keyboard</source> <translation>虛擬鍵盤</translation> </message> <message> <source>Keyboard button size:</source> <translation>按鍵大小:</translation> </message> <message> <source>Positioned at the Top (recommended for tablets)</source> <translation>置放在頂部(平板適用)</translation> </message> <message> <source>Positioned at the Bottom (recommended for white boards)</source> <translation>置放在頂底部(電子白板適用)</translation> </message> <message> <source>Display Text Under Button</source> <translation>在按鈕下顯示文字</translation> </message> <message> <source>Stylus Palette</source> <translation>桌面工具</translation> </message> <message> <source>Horizontal</source> <translation>橫向</translation> </message> <message> <source>Vertical</source> <translation>縱向</translation> </message> <message> <source>About</source> <translation>關於</translation> </message> <message> <source>Software Update</source> <translation>軟體更新</translation> </message> <message> <source>Check software update at launch</source> <translation>啟用時檢查更新</translation> </message> <message> <source>Internet</source> <translation>網際網路</translation> </message> <message> <source>Home Page:</source> <translation>主頁:</translation> </message> <message> <source>Toolbar</source> <translation>工具列</translation> </message> <message> <source>Pen</source> <translation>電子筆</translation> </message> <message> <source>Marker</source> <translation>提示筆</translation> </message> <message utf8="true"> <source>version : …</source> <translation>版本: …</translation> </message> <message> <source>Licences</source> <translation>授權條款</translation> </message> <message> <source>zlib</source> <translation>zlib</translation> </message> <message> <source>Network</source> <translation>網路</translation> </message> <message utf8="true"> <source>Open-Sankoré</source> <translation>Open-Sankoré</translation> </message> <message> <source>Show internal web page content on secondary screen or projector</source> <translation>於第二螢幕或投影機顯示內部網頁內容</translation> </message> <message> <source>Multi display</source> <translation>多重顯示</translation> </message> <message> <source>Swap control display and view display</source> <translation>控制螢幕與顯示螢幕之間切換</translation> </message> <message> <source>Mode</source> <translation>模式</translation> </message> <message> <source>Mode to start in:</source> <translation>啟動模式:</translation> </message> <message> <source>Board</source> <translation>演示板</translation> </message> <message> <source>Desktop</source> <translation>桌面</translation> </message> <message> <source>Proxy User:</source> <translation>Proxy User:</translation> </message> <message> <source>Pass:</source> <translation>密碼:</translation> </message> <message> <source>User:</source> <translation>使用者帳號:</translation> </message> <message> <source>Pass: </source> <translation>密碼:</translation> </message> <message> <source>Credits</source> <translation>貢獻</translation> </message> <message> <source>Start up tips</source> <translation>啟動提示</translation> </message> <message> <source>Show start up tips</source> <translation>顯示啟動提示</translation> </message> <message> <source>Language</source> <translation>語言</translation> </message> <message> <source>Select a language</source> <translation>選擇語言</translation> </message> <message> <source>The new language will be loaded on next restart</source> <translation>下次啟動時,新選語言將會載入</translation> </message> <message utf8="true"> <source>Close Open-Sankoré</source> <translation>關閉Open-Sankoré</translation> </message> <message utf8="true"> <source>Planète Sankoré ID for exporting file</source> <translation>Planète Sankoré ID for exporting file</translation> </message> <message> <source>Restore credentials on reboot </source> <translation>Restore credentials on reboot </translation> </message> <message> <source>OpenSSL</source> <translation>OpenSSL</translation> </message> <message> <source>Xpdf</source> <translation>Xpdf</translation> </message> <message> <source>QuaZIP</source> <translation>QuaZIP</translation> </message> <message> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;Cantarell&apos;; font-size:10pt; font-weight:400; font-style:normal;&quot;&gt; &lt;table border=&quot;0&quot; style=&quot;-qt-table-type: root; margin-top:4px; margin-bottom:4px; margin-left:4px; margin-right:4px;&quot;&gt; &lt;tr&gt; &lt;td style=&quot;border: none;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-family:&apos;Ubuntu&apos;; font-size:11pt;&quot;&gt;The licences are in English to respect the official and legal approved translation.&lt;/span&gt;&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message utf8="true"> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;Cantarell&apos;; font-size:10pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:12pt; font-weight:600;&quot;&gt;Translations&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:12pt; font-weight:600;&quot;&gt;&lt;br /&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt;A special thanks to:&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:11pt;&quot;&gt;&lt;br /&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Alexander Angelov and Iva Ninova for Bulgarian&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Francesc Busquets and Toni Hortal for Catalan&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Christophe Gallego for Corsican&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Jaroslav Krejčí, Janek Wagner for Czech&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Geert Kraeye and Derk Klomp for Dutch&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Christian Oïhénart and François Bocquet for French&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Hans-Peter Zahno and Klaus Tenner for German&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Yannis Kaskamanidis for Greek&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Lalit Mohan for Hindi&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Antonello Comi and Marco Menardi for Italian&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Didier Clerc for Japanese&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Faraniaina Domoina Rabarijaona for Malagasy&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Patricia Fisch and César Marques for Portuguese&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Ilia Ryabokon for Russian&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Anki Chen for Traditional Chinese&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Jaroslav Ryník for Slovak&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Dorian Fuentes and Juan José Gutiérrez Aparicio for Spanish&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Ferhat Ozkasgarli for Turkish&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:11pt;&quot;&gt; • Ana Feito and Enrique Fernandez for Galician&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> </context> <context> <name>trapFlashDialog</name> <message> <source>Trap flash</source> <translation>擷取flash</translation> </message> <message> <source>Select a flash to trap</source> <translation>選擇要擷取的flash動畫</translation> </message> <message> <source>about:blank</source> <translation>空白頁</translation> </message> <message> <source>Application name</source> <translation>應用程式名稱</translation> </message> <message> <source>Create Application</source> <translation>建立應用程式</translation> </message> </context> </TS>
gpl-3.0
unoduetre/MovieRecommendator
featuremaker/plugins/IsGenreAction.py
345
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from Feature import Feature class IsGenreAction(Feature): description = """ Genre: is it action? """.strip() def __init__(self, *args, **kwargs): Feature.__init__(self) def extract(self, m): for g in m.genres: if g['name'] == 'Action': return True return False
gpl-3.0
guiguilechat/EveOnline
model/sde/SDE-Types/src/generated/java/fr/guiguilechat/jcelechat/model/sde/attributes/ShipBonusSupercarrierM4.java
874
package fr.guiguilechat.jcelechat.model.sde.attributes; import fr.guiguilechat.jcelechat.model.sde.IntAttribute; /** * Multiplied by Minmatar Carrier skill level. */ public class ShipBonusSupercarrierM4 extends IntAttribute { public static final ShipBonusSupercarrierM4 INSTANCE = new ShipBonusSupercarrierM4(); @Override public int getId() { return 2393; } @Override public int getCatId() { return 37; } @Override public boolean getHighIsGood() { return true; } @Override public double getDefaultValue() { return 0.0; } @Override public boolean getPublished() { return false; } @Override public boolean getStackable() { return true; } @Override public String toString() { return "ShipBonusSupercarrierM4"; } }
gpl-3.0
Stifenn/projet_harmony_coiffure
app/templates/commentaires/commentaires.php
979
<?php $this->layout('layoutBack', ['title' => 'Gestion des commentaires']) ?> <?php $this->start('main_content') ?> <div class="row" > <div class="col-md-6 col-md-offset-3"> <?php foreach($Commentaires as $CurrentCommentaires) : ?> <article> <p>Pseudo : <?= $CurrentCommentaires['pseudo'] ?></p> <p>Email : <?= $CurrentCommentaires['email'] ?></p> <p>Message : <?= $CurrentCommentaires['commentaire'] ?></p> </article> <aside> <form action="<?= $this->url('modifier_commentaires',['id'=>$CurrentCommentaires['id']])?>" method="POST" accept-charset="utf-8"> <input type="checkbox" name="statut" <?php if($CurrentCommentaires['moderation'] == 1){echo 'checked';} ?>> <input type="submit" name="modifier" class="btn btn-primary" value="Afficher"> <input type="submit" name="supprimer" class="btn btn-danger" value="Supprimer"> </form> </aside> <hr /> <?php endforeach ?> </div> </div> <?php $this->stop('main_content') ?>
gpl-3.0
leokdawson/di-geva
GEVA/src/Operator/Module.java
1587
/* Grammatical Evolution in Java Release: GEVA-v2.0.zip Copyright (C) 2008 Michael O'Neill, Erik Hemberg, Anthony Brabazon, Conor Gilligan Contributors Patrick Middleburgh, Eliott Bartley, Jonathan Hugosson, Jeff Wrigh Separate licences for asm, bsf, antlr, groovy, jscheme, commons-logging, jsci is included in the lib folder. Separate licence for rieps is included in src/com folder. This licence refers to GEVA-v2.0. This software is distributed under the terms of the GNU General Public License. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. />. */ package Operator; import Individuals.Populations.Population; /** * Interface for modules. The module will recive a population. * The module will perform an operation. */ public interface Module { /** * Set the population on which the module will perform its operations * @param p population */ public void setPopulation(Population p); /** * Performs the operation on the population */ public void perform(); }
gpl-3.0
pholda/MalpompaAligxilo
core/shared/src/main/scala/pl/pholda/malpompaaligxilo/form/field/IntField.scala
560
package pl.pholda.malpompaaligxilo.form.field import pl.pholda.malpompaaligxilo.form.FieldType import scala.util.Try case class IntField(min: Option[Int] = None, max: Option[Int] = None, step: Option[Int] = None) extends FieldType[Int] { override def parse(values: Seq[String]): Option[Int] = values.headOption.flatMap(s => Try{s.toInt}.toOption) override val arrayValue: Boolean = false override def separatedValues(value: Option[Int]): List[(String, String)] = value match { case Some(v) => ("" -> v.toString) :: Nil case _ => Nil } }
gpl-3.0
SQLPower/power-matchmaker
doc/tools/xslt/extensions/saxon643/com/nwalsh/saxon/NumberLinesEmitter.java
10153
package com.nwalsh.saxon; import java.util.Stack; import java.util.StringTokenizer; import org.xml.sax.*; import org.w3c.dom.*; import javax.xml.transform.TransformerException; import com.icl.saxon.output.*; import com.icl.saxon.om.*; import com.icl.saxon.Controller; import com.icl.saxon.tree.AttributeCollection; import com.icl.saxon.expr.FragmentValue; /** * <p>Saxon extension to decorate a result tree fragment with line numbers.</p> * * <p>$Id: NumberLinesEmitter.java 903 2006-06-21 22:32:15Z johnson $</p> * * <p>Copyright (C) 2000 Norman Walsh.</p> * * <p>This class provides the guts of a * <a href="http://saxon.sourceforge.net/">Saxon 6.*</a> * implementation of line numbering for verbatim environments. (It is used * by the Verbatim class.)</p> * * <p>The general design is this: the stylesheets construct a result tree * fragment for some verbatim environment. The Verbatim class initializes * a NumberLinesEmitter with information about what lines should be * numbered and how. Then the result tree fragment * is "replayed" through the NumberLinesEmitter; the NumberLinesEmitter * builds a * new result tree fragment from this event stream, decorated with line * numbers, * and that is returned.</p> * * <p><b>Change Log:</b></p> * <dl> * <dt>1.0</dt> * <dd><p>Initial release.</p></dd> * </dl> * * @see Verbatim * * @author Norman Walsh * <a href="mailto:[email protected]">[email protected]</a> * * @version $Id: NumberLinesEmitter.java 903 2006-06-21 22:32:15Z johnson $ * */ public class NumberLinesEmitter extends CopyEmitter { /** A stack for the preserving information about open elements. */ protected Stack elementStack = null; /** The current line number. */ protected int lineNumber = 0; /** Is the next element absolutely the first element in the fragment? */ protected boolean firstElement = false; /** The FO namespace name. */ protected static String foURI = "http://www.w3.org/1999/XSL/Format"; /** The XHTML namespace name. */ protected static String xhURI = "http://www.w3.org/1999/xhtml"; /** The first line number will be <code>startinglinenumber</code>. */ protected int startinglinenumber = 1; /** Every <code>modulus</code> line will be numbered. */ protected int modulus = 5; /** Line numbers are <code>width</code> characters wide. */ protected int width = 3; /** Line numbers are separated from the listing by <code>separator</code>. */ protected String separator = " "; /** Is the stylesheet currently running an FO stylesheet? */ protected boolean foStylesheet = false; /** <p>Constructor for the NumberLinesEmitter.</p> * * @param namePool The name pool to use for constructing elements and attributes. * @param modulus The modulus to use for this listing. * @param width The width to use for line numbers in this listing. * @param separator The separator to use for this listing. * @param foStylesheet Is this an FO stylesheet? */ public NumberLinesEmitter(Controller controller, NamePool namePool, int startingLineNumber, int modulus, int width, String separator, boolean foStylesheet) { super(controller,namePool); elementStack = new Stack(); firstElement = true; this.modulus = modulus; this.startinglinenumber = startingLineNumber; this.width = width; this.separator = separator; this.foStylesheet = foStylesheet; } /** Process characters. */ public void characters(char[] chars, int start, int len) throws TransformerException { // If we hit characters, then there's no first element... firstElement = false; if (lineNumber == 0) { // The first line is always numbered lineNumber = startinglinenumber; formatLineNumber(lineNumber); } // Walk through the text node looking for newlines char[] newChars = new char[len]; int pos = 0; for (int count = start; count < start+len; count++) { if (chars[count] == '\n') { // This is the tricky bit; if we find a newline, make sure // it doesn't occur inside any markup. if (pos > 0) { // Output any characters that preceded this newline rtfEmitter.characters(newChars, 0, pos); pos = 0; } // Close all the open elements... Stack tempStack = new Stack(); while (!elementStack.empty()) { StartElementInfo elem = (StartElementInfo) elementStack.pop(); rtfEmitter.endElement(elem.getNameCode()); tempStack.push(elem); } // Copy the newline to the output newChars[pos++] = chars[count]; rtfEmitter.characters(newChars, 0, pos); pos = 0; // Add the line number formatLineNumber(++lineNumber); // Now "reopen" the elements that we closed... while (!tempStack.empty()) { StartElementInfo elem = (StartElementInfo) tempStack.pop(); AttributeCollection attr = (AttributeCollection)elem.getAttributes(); AttributeCollection newAttr = new AttributeCollection(namePool); for (int acount = 0; acount < attr.getLength(); acount++) { String localName = attr.getLocalName(acount); int nameCode = attr.getNameCode(acount); String type = attr.getType(acount); String value = attr.getValue(acount); String uri = attr.getURI(acount); String prefix = ""; if (localName.indexOf(':') > 0) { prefix = localName.substring(0, localName.indexOf(':')); localName = localName.substring(localName.indexOf(':')+1); } if (uri.equals("") && ((foStylesheet && localName.equals("id")) || (!foStylesheet && (localName.equals("id") || localName.equals("name"))))) { // skip this attribute } else { newAttr.addAttribute(prefix, uri, localName, type, value); } } rtfEmitter.startElement(elem.getNameCode(), newAttr, elem.getNamespaces(), elem.getNSCount()); elementStack.push(elem); } } else { newChars[pos++] = chars[count]; } } if (pos > 0) { rtfEmitter.characters(newChars, 0, pos); pos = 0; } } /** * <p>Add a formatted line number to the result tree fragment.</p> * * @param lineNumber The number of the current line. */ protected void formatLineNumber(int lineNumber) throws TransformerException { char ch = 160; // &nbsp; String lno = ""; if (lineNumber == 1 || (modulus >= 1 && (lineNumber % modulus == 0))) { lno = "" + lineNumber; } while (lno.length() < width) { lno = ch + lno; } lno += separator; char chars[] = new char[lno.length()]; for (int count = 0; count < lno.length(); count++) { chars[count] = lno.charAt(count); } characters(chars, 0, lno.length()); } /** Process end element events. */ public void endElement(int nameCode) throws TransformerException { if (!elementStack.empty()) { // if we didn't push the very first element (an fo:block or // pre or div surrounding the whole block), then the stack will // be empty when we get to the end of the first element... elementStack.pop(); } rtfEmitter.endElement(nameCode); } /** Process start element events. */ public void startElement(int nameCode, org.xml.sax.Attributes attributes, int[] namespaces, int nscount) throws TransformerException { if (!skipThisElement(nameCode)) { StartElementInfo sei = new StartElementInfo(nameCode, attributes, namespaces, nscount); elementStack.push(sei); } firstElement = false; rtfEmitter.startElement(nameCode, attributes, namespaces, nscount); } /** * <p>Protect the outer-most block wrapper.</p> * * <p>Open elements in the result tree fragment are closed and reopened * around callouts (so that callouts don't appear inside links or other * environments). But if the result tree fragment is a single block * (a div or pre in HTML, an fo:block in FO), that outer-most block is * treated specially.</p> * * <p>This method returns true if the element in question is that * outermost block.</p> * * @param nameCode The name code for the element * * @return True if the element is the outer-most block, false otherwise. */ protected boolean skipThisElement(int nameCode) { // FIXME: This is such a gross hack... if (firstElement) { int thisFingerprint = namePool.getFingerprint(nameCode); int foBlockFingerprint = namePool.getFingerprint(foURI, "block"); int htmlPreFingerprint = namePool.getFingerprint("", "pre"); int htmlDivFingerprint = namePool.getFingerprint("", "div"); int xhtmlPreFingerprint = namePool.getFingerprint(xhURI, "pre"); int xhtmlDivFingerprint = namePool.getFingerprint(xhURI, "div"); if ((foStylesheet && thisFingerprint == foBlockFingerprint) || (!foStylesheet && (thisFingerprint == htmlPreFingerprint || thisFingerprint == htmlDivFingerprint || thisFingerprint == xhtmlPreFingerprint || thisFingerprint == xhtmlDivFingerprint))) { // Don't push the outer-most wrapping div, pre, or fo:block return true; } } return false; } /** * <p>A private class for maintaining the information required to call * the startElement method.</p> * * <p>In order to close and reopen elements, information about those * elements has to be maintained. This class is just the little record * that we push on the stack to keep track of that info.</p> */ private class StartElementInfo { private int _nameCode; org.xml.sax.Attributes _attributes; int[] _namespaces; int _nscount; public StartElementInfo(int nameCode, org.xml.sax.Attributes attributes, int[] namespaces, int nscount) { _nameCode = nameCode; _attributes = attributes; _namespaces = namespaces; _nscount = nscount; } public int getNameCode() { return _nameCode; } public org.xml.sax.Attributes getAttributes() { return _attributes; } public int[] getNamespaces() { return _namespaces; } public int getNSCount() { return _nscount; } } }
gpl-3.0
SmartLambda/SmartLambda
src/main/java/edu/teco/smartlambda/identity/IdentityProvider.java
809
package edu.teco.smartlambda.identity; import edu.teco.smartlambda.authentication.entities.User; import org.apache.commons.lang3.tuple.Pair; import java.util.Map; /** * Provide any form of external identity verification */ public interface IdentityProvider { /** * Registers a user with an external identification at the SmartLambda system * * @param parameters A set of parameters required for identity verification. Content depends on verification implementation * * @return A pair of a {@link User} and the name this user is identified with * * @throws IdentityException if the verification process fails */ public Pair<User, String> register(Map<String, String> parameters) throws IdentityException; /** * @return the provider service's name */ public String getName(); }
gpl-3.0
sosilent/euca
clc/modules/www/src/main/java/com/eucalyptus/webui/client/view/DeviceCPUModifyView.java
420
package com.eucalyptus.webui.client.view; import com.google.gwt.user.client.ui.IsWidget; public interface DeviceCPUModifyView extends IsWidget { public void setPresenter(Presenter presenter); public void popup(int cpu_id, String cpu_desc, int cpu_total, int cs_used, String server_name); public interface Presenter { public boolean onOK(int cpu_id, String cpu_desc, int cpu_total, int cs_used); } }
gpl-3.0
jmencia/trivnew
test/src/main/java/oms/framework/transformer/DocumentToStringTransformer.java
1276
package oms.framework.transformer; import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class DocumentToStringTransformer { public String transform(Document doc) { String output = null; try { TransformerFactory tf = TransformerFactory.newInstance(); javax.xml.transform.Transformer transformer; transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); output = writer.getBuffer().toString(); // .replaceAll("\n|\r", ""); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (javax.xml.transform.TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } return output; } }
gpl-3.0
Informatik-AG-KGN-2016/Dokumente
2016-11-28/aufgabe-multiplizierer.py
919
# Multiplizierer mit += 1 # Eingaben erhalten a = input("Dies ist ein Multiplizierer!\nGeben Sie a ein: ") b = input("Geben Sie b ein: ") # Zeichenketten in Zahlen umwandeln a = int(a) b = int(b) # Ergebnisvariable erstellen result = 0 if a == 0 or b == 0: pass # Satz vom Nullprodukt, also keine Rechnung notwendig elif (a > 0 and b > 0) or (a < 0 and b < 0): i = 0 # beide positiv oder beide negativ -> Ergebnis positiv while i < abs(a): j = 0 while j < abs(b): result += 1 # Schleife mit +1 durchlaufen j += 1 i += 1 else: i = 0 # übrig bleibt: while i < abs(a): # eins positiv und eins negativ -> Ergebnis negativ j = 0 while j < abs(b): result -= 1 j += 1 i += 1 # Ergebnis ausgeben print("\nDas Ergebnis ist: " + str(result))
gpl-3.0
kosmonet/neon
src/neon/systems/time/Calendar.java
3989
/* * Neon, a roguelike engine. * Copyright (C) 2018 - Maarten Driesen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package neon.systems.time; /** * The calendar used by the game. It features the following: * <ul> * <li>six-day weeks</li> * <li>five-week months (30 days per month)</li> * <li>12-month years (360 days per year)</li> * <li>212-day religious year</li> * <li>53-year cycles (least common multiple of 212 and 360 days)</li> * </ul> * * @author mdriesen * */ public final class Calendar { public static final int TURNS_PER_DAY = 1200; private static final int DAYS_PER_WEEK = 6; private static final int WEEKS_PER_MONTH = 5; private static final int DAYS_PER_MONTH = DAYS_PER_WEEK*WEEKS_PER_MONTH; private static final int MONTHS_PER_YEAR = 12; private static final int DAYS_PER_YEAR = DAYS_PER_MONTH*MONTHS_PER_YEAR; private static final int WEEKS_PER_YEAR = WEEKS_PER_MONTH*MONTHS_PER_YEAR; private final int ticksPerTurn; private int ticks; public Calendar(int ticks, int ticksPerTurn) { this.ticks = ticks; this.ticksPerTurn = ticksPerTurn; } public void addTicks(int amount) { ticks += amount; } public int getTicks() { return ticks; } public int getDay() { return ticks/(ticksPerTurn*TURNS_PER_DAY); } /** * Returns the day of the week as an integer. * * @param days * @return */ public static int getDayOfWeek(int days) { return (days - 1) % DAYS_PER_WEEK + 1; } /** * Returns the day of the month as an integer. * * @param days * @return */ public static int getDayOfMonth(int days) { return (days - 1) % DAYS_PER_MONTH + 1; } /** * Returns the day of the year as an integer. * * @param days * @return */ public static int getDayOfYear(int days) { return (days - 1) % DAYS_PER_YEAR + 1; } /** * Returns the name of the day. * * @param days * @return */ public static Day getDayName(int days) { return Day.values()[getDayOfWeek(days) - 1]; } /** * Returns the week the given day falls in. * * @param days * @return */ public static int getWeek(int days) { return (days - 1)/DAYS_PER_WEEK + 1; } /** * Return the week of the month. * * @param days * @return */ public static int getWeekOfMonth(int days) { return (getWeek(days) - 1) % WEEKS_PER_MONTH + 1; } /** * Returns the week of the year. * * @param days * @return */ public static int getWeekOfYear(int days) { return (getWeek(days) - 1) % WEEKS_PER_YEAR + 1; } /** * Returns the month the given day falls in. * * @param days * @return */ public static int getMonth(int days) { return (days - 1)/DAYS_PER_MONTH + 1; } /** * Return the month of the year. * * @param days * @return */ public static int getMonthOfYear(int days) { return (getMonth(days) - 1) % MONTHS_PER_YEAR + 1; } /** * Returns the name of the month. * * @param days * @return */ public static Month getMonthName(int days) { return Month.values()[getMonthOfYear(days) - 1]; } /** * Returns the year. * * @param days * @return */ public static int getYear(int days) { return (days - 1)/DAYS_PER_YEAR + 1; } }
gpl-3.0
sayantandutta87/sikhbo
blocks/grade_me/tests/grade_me_test.php
32722
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * PHPUnit data generator tests * * @package block_grade_me * @category phpunit * @copyright 2013 Logan Reynolds {@link http://www.remote-learner.net} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ global $CFG; require_once($CFG->dirroot.'/blocks/moodleblock.class.php'); require_once($CFG->dirroot.'/blocks/grade_me/lib.php'); require_once($CFG->dirroot.'/blocks/grade_me/block_grade_me.php'); require_once($CFG->dirroot.'/blocks/grade_me/plugins/assign/assign_plugin.php'); require_once($CFG->dirroot.'/blocks/grade_me/plugins/assignment/assignment_plugin.php'); require_once($CFG->dirroot.'/blocks/grade_me/plugins/data/data_plugin.php'); require_once($CFG->dirroot.'/blocks/grade_me/plugins/forum/forum_plugin.php'); require_once($CFG->dirroot.'/blocks/grade_me/plugins/glossary/glossary_plugin.php'); require_once($CFG->dirroot.'/blocks/grade_me/plugins/quiz/quiz_plugin.php'); defined('MOODLE_INTERNAL') || die(); class block_grade_me_testcase extends advanced_testcase { /** * Load the testing dataset. Meant to be used by any tests that require the testing dataset. * * @param string $file The name of the data file to load * @param string $type The name of the module we are testing * @return array An array containing an array of user objects and an array of course objects */ protected function create_grade_me_data($file) { // Read the datafile and get the table names. $dataset = $this->createXMLDataSet(__DIR__.'/fixtures/'.$file); $names = array_flip($dataset->getTableNames()); // Generate Data $generator = $this->getDataGenerator(); $users = array($generator->create_user(), $generator->create_user()); $courses = array($generator->create_course()); $plugins = array(); $excludes = array(); $gradeables = array('assign', 'assignment', 'forum', 'glossary', 'quiz'); foreach ($gradeables as $gradeable) { if (array_key_exists($gradeable, $names)) { $pgen = $generator->get_plugin_generator("mod_{$gradeable}"); $table = $dataset->getTable($gradeable); $rows = $table->getRowCount(); $items = array(); for ($row = 0; $row < $rows; $row += 1) { $fields = $table->getRow($row); unset($fields['id']); $fields['course'] = $courses[$fields['course']]->id; $instance = $pgen->create_instance($fields); $context = context_module::instance($instance->cmid); $plugins[] = (object) array('id' => $instance->id, 'cmid' => $instance->cmid, 'contextid' => $context->id); } } $excludes[] = $gradeable; } // Known overrides (compact form) $overrides = array( 'assignment' => array( 'values' => 'plugins', 'param' => 'id', 'tables' => array('assign_grades', 'assign_submission', 'assignment_submissions'), ), 'contextid' => array( 'values' => 'plugins', 'param' => 'contextid', 'tables' => array('rating'), ), 'course' => array( 'values' => 'courses', 'param' => 'id', 'tables' => array( 'assign', 'assignment', 'course_modules', 'forum', 'forum_discussions', 'glossary', 'quiz', ), ), 'courseid' => array( 'values' => 'courses', 'param' => 'id', 'tables' => array('block_grade_me', 'grade_items'), ), 'coursemoduleid' => array( 'values' => 'plugins', 'param' => 'cmid', 'tables' => array('block_grade_me'), ), 'coursename' => array( 'values' => 'courses', 'param' => 'fullname', 'tables' => array('block_grade_me'), ), 'forum' => array( 'values' => 'plugins', 'param' => 'id', 'tables' => array('forum_discussions'), ), 'glossaryid' => array( 'values' => 'plugins', 'param' => 'id', 'tables' => array('glossary_entries'), ), 'iteminstance' => array( 'values' => 'plugins', 'param' => 'id', 'tables' => array('block_grade_me', 'grade_items'), ), 'quiz' => array( 'values' => 'plugins', 'param' => 'id', 'tables' => array('quiz_attempts'), ), 'userid' => array( 'values' => 'users', 'param' => 'id', 'tables' => array( 'assign_grades', 'assign_submission', 'assignment_submissions', 'forum_posts', 'forum_discussions', 'glossary_entries', 'grade_grades', 'question_attempt_steps', 'quiz_attempts', ), ), ); // Generate a table oriented list of overrides. $tables = array(); foreach ($overrides as $field => $override) { foreach ($override['tables'] as $tablename) { // Skip tables that aren't in the dataset if (array_key_exists($tablename, $names)) { if (!array_key_exists($tablename, $tables)) { $tables[$tablename] = array($field => array()); } $tables[$tablename][$field][] = array('list' => $override['values'], 'field' => $override['param']); } } } // Perform the overrides foreach ($tables as $tablename => $translations) { $table = $dataset->getTable($tablename); $rows = $table->getRowCount(); foreach ($translations as $column => $values) { foreach ($values as $value) { $list = $value['list']; $field = $value['field']; for ($row = 0; $row < $rows; $row += 1) { $index = $table->getValue($row, $column); $table->setValue($row, $column, ${$list}[$index]->$field); } } } } // Load the data $filtered = new PHPUnit_Extensions_Database_DataSet_DataSetFilter($dataset); $filtered->addExcludeTables($excludes); $this->loadDataSet($filtered); // Return the generated users and courses because the tests often need them for result calculations return array($users, $courses, $plugins); } /** * Provide input data to the parameters of the test_censusreport_null_grade_check() method. * * @TODO See if this can be merged with provider_single_user * * Test data is composed of: * The plugin to be tested * Regular expressions to matched against the output * A list of users * A list of courses * * @return array An array containing the test data */ public function provider_get_content_multiple_user() { $data = array(); // New assign test $plugin = 'assign'; $matches = array( 1 => '/Go to assign/', 2 => '|mod/assign/view.php|', 3 => '/action=grade&rownum=0&useridlistid=/', 4 => '/action=grade&rownum=1&useridlistid=/', 5 => '/testassignment3/', 6 => '/testassignment4/' ); $data['assign'] = array($plugin, $matches); // Legacy assignment test $plugin = 'assignment'; $matches = array( 1 => '/Go to assignment/', 2 => '|mod/assignment/submissions.php|', 3 => '/userid=[user0]&amp;mode=single/', 4 => '/userid=[user1]&amp;mode=single/', 5 => '/testassignment5/', 6 => '/testassignment6/', ); $data['assignment'] = array($plugin, $matches); return $data; } /** * Provide input data to the parameters of the test_block_grade_me_get_content_single_user() method. * * Test data is composed of: * The plugin to be tested * Regular expressions to matched against the output * A list of users * A list of courses * * @return array An array containing the test data */ public function provider_get_content_single_user() { $data = array(); // New assign test $plugin = 'assign'; $matches = array( 1 => '/Go to assign/', 2 => '|mod/assign/view.php|', 3 => '/action=grade&rownum=0&useridlistid=/', 5 => '/testassignment3/', 6 => '/testassignment4/', ); $data['assign'] = array($plugin, $matches); // Legacy assignment test $plugin = 'assignment'; $matches = array( 1 => '/Go to assignment/', 2 => '|mod/assignment/submissions.php|', 3 => '/userid=[user0]&amp;mode=single/', 5 => '/testassignment5/', 6 => '/testassignment6/', ); $data['assignment'] = array($plugin, $matches); return $data; } /** * Data provider for the forum plugin. * * @TODO Make this data provider less useless. * * @return array Forum items */ public function provider_query_forum() { // Represents forum items that are ready for grading. Forum items that have already been graded are not included. $forumitem1 = array( 'courseid' => 0, 'coursename' => '', 'itemmodule' => 'forum', 'iteminstance' => 0, 'itemname' => 'forumitem1', 'coursemoduleid' => 0, 'itemsortorder' => 0, 'submissionid' => 1, 'userid' => 0, 'timesubmitted' => 0, 'forum_discussion_id' => 1 ); $forumitem2 = array( 'courseid' => 0, 'coursename' => '', 'itemmodule' => 'forum', 'iteminstance' => 0, 'itemname' => 'forumitem1', 'coursemoduleid' => 0, 'itemsortorder' => 0, 'submissionid' => 2, 'userid' => 0, 'timesubmitted' => 0, 'forum_discussion_id' => 2 ); $data = array(array(array($forumitem1, $forumitem2))); return $data; } /** * Data provider for the testing the quiz plugin. * * @return array Glossary entries */ public function provider_query_glossary() { $datafile = 'glossary.xml'; // Represents entries that are finished and ready to be graded. $entries = array(); $entries[0] = array( 'courseid' => 0, 'coursename' => '0', 'itemmodule' => 'glossary', 'iteminstance' => 0, 'itemname' => 'glossaryitem1', 'coursemoduleid' => 0, 'itemsortorder' => 0, 'userid' => 0, 'timesubmitted' => 1424354368, 'submissionid' => 1, ); $entries[1] = array( 'courseid' => 0, 'coursename' => '0', 'itemmodule' => 'glossary', 'iteminstance' => 1, 'itemname' => 'glossaryitem2', 'coursemoduleid' => 1, 'itemsortorder' => 0, 'userid' => 0, 'timesubmitted' => 1424354369, 'submissionid' => 2, ); $entries[2] = array( 'courseid' => 0, 'coursename' => '0', 'itemmodule' => 'glossary', 'iteminstance' => 2, 'itemname' => 'glossaryitem3', 'coursemoduleid' => 2, 'itemsortorder' => 0, 'userid' => 0, 'timesubmitted' => 1424354370, 'submissionid' => 3, ); $data = array( 'test1' => array($datafile, $entries) ); return $data; } /** * Data provider for the testing the quiz plugin. * * @return array Quiz questions */ public function provider_query_quiz() { // Represents questions that are finished and ready to be graded. // In progress questions or questions that are already graded are not included. $items = array(); $items[0] = array( 'courseid' => 0, 'coursename' => '', 'itemmodule' => 'quiz', 'iteminstance' => 1, 'itemname' => 'quizitem2', 'coursemoduleid' => 1, 'itemsortorder' => 0, 'step_id' => 4, 'userid' => 0, 'timesubmitted' => 0, 'submissionid' => 2, 'sequencenumber' => 2 ); $items[1] = array( 'courseid' => 0, 'coursename' => '', 'itemmodule' => 'quiz', 'iteminstance' => 3, 'itemname' => 'quizitem4', 'coursemoduleid' => 3, 'itemsortorder' => 0, 'step_id' => 11, 'userid' => 0, 'timesubmitted' => 0, 'submissionid' => 4, 'sequencenumber' => 2 ); $items[2] = array( 'courseid' => 0, 'coursename' => '', 'itemmodule' => 'quiz', 'iteminstance' => 0, 'itemname' => 'Quiz #1', 'coursemoduleid' => 0, 'itemsortorder' => 0, 'step_id' => 9, 'userid' => 0, 'timesubmitted' => 0, 'submissionid' => 1, 'sequencenumber' => 2 ); $data = array( 'simple' => array('quiz1.xml', array($items[0], $items[1])), 'complexquiz' => array('quiz2.xml', array($items[2])), ); return $data; } /** * Confirm that the block will include the relevant settings.php file * for Moodle 2.4. */ public function test_global_configuration_load() { $this->resetAfterTest(true); $block_inst = block_instance('grade_me'); $this->assertEquals(true, $block_inst->has_config()); } /** * Ensure that we can load our test dataset into the current DB. */ public function test_load_db() { $this->resetAfterTest(true); $this->create_grade_me_data('block_grade_me.xml'); } /** * Test the function block_grade_me_query_assign. * * @depends test_load_db */ public function test_query_assign() { global $DB; $this->resetAfterTest(true); list($users, $courses, $plugins) = $this->create_grade_me_data('block_grade_me.xml'); // Partial query return from block_grade_me_query_assign. list($sql, $insqlparams) = block_grade_me_query_assign(array($users[0]->id)); // Build full query. $sql = "SELECT a.id, bgm.courseid $sql AND bgm.courseid = {$courses[0]->id} AND bgm.itemmodule = 'assign'"; $rec = new stdClass(); $rec->id = $plugins[2]->id; $rec->courseid = $courses[0]->id; $rec->submissionid = '2'; $rec->userid = $users[0]->id; $rec->timesubmitted = '2'; $rec2 = new stdClass(); $rec2->id = $plugins[3]->id; $rec2->courseid = $courses[0]->id; $rec2->submissionid = '3'; $rec2->userid = $users[0]->id; $rec2->timesubmitted = '3'; // Tests resubmission $rec3 = new stdClass(); $rec3->id = $plugins[4]->id; $rec3->courseid = $courses[0]->id; $rec3->submissionid = '7'; $rec3->userid = $users[0]->id; $rec3->timesubmitted = '6'; $expected = array($rec->id => $rec, $rec2->id => $rec2, $rec3->id => $rec3); $actual = $DB->get_records_sql($sql, $insqlparams); $this->assertEquals($expected, $actual); $this->assertFalse(block_grade_me_query_assign(array())); } /** * Test the block_grade_me_query_prefix function */ public function test_query_prefix() { $expected = "SELECT bgm.courseid, bgm.coursename, bgm.itemmodule, bgm.iteminstance, bgm.itemname, bgm.coursemoduleid, bgm.itemsortorder"; $this->assertEquals($expected, block_grade_me_query_prefix()); } /** * Test the block_grade_me_query_suffix function */ public function test_query_suffix() { $expected = " AND bgm.courseid = ? AND bgm.itemmodule = 'assign'"; $this->assertEquals($expected, block_grade_me_query_suffix('assign')); } /** * Dataprovider for testing the cron * * @return array Grade item data */ public function provider_cron() { $item2 = new StdClass(); $item2->id = 2; $item2->itemname = 'testassignment2'; $item2->itemtype = 'mod'; $item2->itemmodule = 'assign'; $item3 = new StdClass(); $item3->id = 3; $item3->itemname = 'testassignment3'; $item3->itemtype = 'mod'; $item3->itemmodule = 'assign'; $item4 = new StdClass(); $item4->id = 4; $item4->itemname = 'testassignment4'; $item4->itemtype = 'mod'; $item4->itemmodule = 'assign'; $item5 = new StdClass(); $item5->id = 5; $item5->itemname = 'testassignment6'; $item5->itemtype = 'mod'; $item5->itemmodule = 'assignment'; // Represents updated record. $item6 = new StdClass(); $item6->id = 6; $item6->itemname = 'testassignment7_UPDATED'; $item6->itemtype = 'mod'; $item6->itemmodule = 'assignment'; $item7 = new StdClass(); $item7->id = 7; $item7->itemname = 'testassignment5'; $item7->itemtype = 'mod'; $item7->itemmodule = 'assign'; $item8 = new StdClass(); $item8->id = 8; $item8->itemname = 'test_forum'; $item8->itemtype = 'mod'; $item8->itemmodule = 'forum'; $data = array( array( array( '2' => $item2, '3' => $item3, '4' => $item4, '5' => $item5, '6' => $item6, '7' => $item7, '8' => $item8 ) ) ); return $data; } /** * Test the cron * * @param array $expected The expected data * @dataProvider provider_cron * @depends test_load_db */ public function test_cron($expected) { global $DB, $CFG; $this->resetAfterTest(true); $this->create_grade_me_data('block_grade_me.xml'); $user = $this->getDataGenerator()->create_user(); $this->setUser($user); $course = $this->getDataGenerator()->create_course(); $grademe = new block_grade_me(); $grademe->cron(); $this->expectOutputRegex('/Updated block_grade_me cache in/'); $actual = $DB->get_records('block_grade_me', array(), '', 'id, itemname, itemtype, itemmodule'); $this->assertEquals($expected, $actual); } /** * Test the quiz plugin where a list of questions not yet graded is returned. * * @param string $datafile The database file to load for the test * @param array $expected The expected results * @dataProvider provider_query_quiz */ public function test_query_quiz($datafile, $expected) { global $DB; $this->resetAfterTest(true); list($users, $courses, $plugins) = $this->create_grade_me_data($datafile); list($sql, $params) = block_grade_me_query_quiz(array($users[0]->id)); $sql = block_grade_me_query_prefix().$sql.block_grade_me_query_suffix('quiz'); $actual = array(); $result = $DB->get_recordset_sql($sql, array($params[0], $courses[0]->id)); foreach ($result as $rec) { $actual[] = (array)$rec; } // Set proper values for the results foreach ($expected as $key => $row) { $row['coursemoduleid'] = $plugins[$row['coursemoduleid']]->cmid; $row['coursename'] = $courses[$row['courseid']]->fullname; $row['courseid'] = $courses[$row['courseid']]->id; $row['iteminstance'] = $plugins[$row['iteminstance']]->id; $row['userid'] = $users[$row['userid']]->id; $expected[$key] = $row; } $this->assertEquals($expected, $actual); } /** * Test the forum plugin where a list of forum activites not yet graded is returned. * * @dataProvider provider_query_forum * @param array $expected The expected results */ public function test_query_forum($expected) { global $DB; $this->resetAfterTest(true); list($users, $courses, $plugins) = $this->create_grade_me_data('forum.xml'); list($sql, $params) = block_grade_me_query_forum(array($users[0]->id)); $sql = block_grade_me_query_prefix().$sql.block_grade_me_query_suffix('forum'); $actual = array(); $result = $DB->get_recordset_sql($sql, array($params[0], $courses[0]->id)); foreach ($result as $rec) { $actual[] = (array)$rec; } // Set proper values for the results foreach ($expected as $key => $row) { $row['coursemoduleid'] = $plugins[$row['coursemoduleid']]->cmid; $row['coursename'] = $courses[$row['courseid']]->fullname; $row['courseid'] = $courses[$row['courseid']]->id; $row['iteminstance'] = $plugins[$row['iteminstance']]->id; $row['userid'] = $users[$row['userid']]->id; $expected[$key] = $row; } $this->assertEquals($expected, $actual); } /** * Test the block_grade_me_query_glossary function * * @param string $datafile The database file to load for the test * @param array $expected The expected results * @dataProvider provider_query_glossary */ public function test_query_glossary($datafile, $expected) { global $USER, $DB; $this->resetAfterTest(true); list($users, $courses, $plugins) = $this->create_grade_me_data($datafile); list($sql, $params) = block_grade_me_query_glossary(array($users[0]->id)); $sql = block_grade_me_query_prefix().$sql.block_grade_me_query_suffix('glossary'); $actual = array(); $result = $DB->get_recordset_sql($sql, array($params[0], $courses[0]->id)); foreach ($result as $rec) { $actual[] = (array)$rec; } // Set proper values for the results foreach ($expected as $key => $row) { $row['coursemoduleid'] = $plugins[$row['coursemoduleid']]->cmid; $row['coursename'] = $courses[$row['courseid']]->fullname; $row['courseid'] = $courses[$row['courseid']]->id; $row['iteminstance'] = $plugins[$row['iteminstance']]->id; $row['userid'] = $users[$row['userid']]->id; $expected[$key] = $row; } $this->assertEquals($expected, $actual); } /** * Test the block_grade_me_query_data function */ public function test_query_data() { global $USER, $DB; $concatid = $DB->sql_concat('dr.id', "'-'", $USER->id); $concatitem = $DB->sql_concat('r.itemid', "'-'", 'r.userid'); $expected = ", dr.id submissionid, dr.userid, dr.timemodified timesubmitted FROM {data_records} dr JOIN {data} d ON d.id = dr.dataid LEFT JOIN {block_grade_me} bgm ON bgm.courseid = d.course AND bgm.iteminstance = d.id WHERE dr.userid IN (?,?) AND d.assessed = 1 AND $concatid NOT IN ( SELECT $concatitem FROM {rating} r WHERE r.contextid IN ( SELECT cx.id FROM {context} cx WHERE cx.contextlevel = 70 AND cx.instanceid = bgm.coursemoduleid ) )"; list($sql, $params) = block_grade_me_query_data(array(2, 3)); $this->assertEquals($expected, $sql); $this->assertEquals(array(2, 3), $params); $this->assertFalse(block_grade_me_query_data(array())); } /** * Test the block_grade_me_query_assignment function */ public function test_query_assignment() { $expected = ", asgn_sub.id submissionid, asgn_sub.userid, asgn_sub.timemodified timesubmitted FROM {assignment_submissions} asgn_sub JOIN {assignment} a ON a.id = asgn_sub.assignment LEFT JOIN {block_grade_me} bgm ON bgm.courseid = a.course AND bgm.iteminstance = a.id WHERE asgn_sub.userid IN (?,?) AND a.grade > 0 AND asgn_sub.timemarked < asgn_sub.timemodified"; list($sql, $params) = block_grade_me_query_assignment(array(2, 3)); $this->assertEquals($expected, $sql); $this->assertEquals(array(2, 3), $params); $this->assertFalse(block_grade_me_query_assignment(array())); } /** * Test the function get_content for one user in the gradebook for a course. * Check that urls returned are what they should be * * @param string $plugin The name of the plugin being tested * @param array $expectedvalues An array of values that should be found in the grade_me block output * @dataProvider provider_get_content_single_user * @depends test_load_db */ public function test_get_content_single_user($plugin, $expectedvalues) { global $CFG, $DB, $USER; $this->resetAfterTest(true); list($users, $courses) = $this->create_grade_me_data('block_grade_me.xml'); // Make sure that the plugin being tested has been enabled if (!$CFG->{'block_grade_me_enable'.$plugin} == true) { set_config('block_grade_me_enable'.$plugin, true); } if (!$CFG->block_grade_me_enableadminviewall) { set_config('block_grade_me_enableadminviewall', true); } $this->setUser($users[0]); $this->setAdminUser($users[1]); $course = $this->getDataGenerator()->create_course(); // Set up gradebook role $context = context_course::instance($courses[0]->id); $roleid = create_role('role', 'role', 'grade me block'); set_role_contextlevels($roleid, array(CONTEXT_COURSE)); role_assign($roleid, $users[0]->id, $context->id); set_config('gradebookroles', $roleid); // Create a manual enrolment record. $manual_enrol_data['enrol'] = 'manual'; $manual_enrol_data['status'] = 0; $manual_enrol_data['courseid'] = 2; $enrolid = $DB->insert_record('enrol', $manual_enrol_data); // Create the user enrolment record. $DB->insert_record('user_enrolments', (object)array( 'status' => 0, 'enrolid' => $enrolid, 'userid' => $users[0]->id )); $grademe = new block_grade_me(); $content = $grademe->get_content(); foreach ($expectedvalues as $expected) { $match = str_replace('[user0]', $users[0]->id, $expected); $this->assertRegExp($match, $content->text); } } /** * Test the function get_content. * Check that urls returned are what they should be * * @TODO See if this plugin can be merged with test_block_grade_me_get_content_single_user * * @param string $plugin The name of the plugin being tested * @param array $expectedvalues An array of values that should be found in the grade_me block output * @dataProvider provider_get_content_multiple_user * @depends test_load_db */ public function test_get_content_multiple_user($plugin, $expectedvalues) { global $CFG, $DB, $USER; $this->resetAfterTest(true); list($users, $courses) = $this->create_grade_me_data('block_grade_me.xml'); // Make sure that the plugin being tested has been enabled if (!$CFG->{'block_grade_me_enable'.$plugin} == true) { set_config('block_grade_me_enable'.$plugin, true); } if (!$CFG->block_grade_me_enableadminviewall) { set_config('block_grade_me_enableadminviewall', true); } // When testing with multiple users // Need multiple gradebookroles and timemodified needs to be different on submission $this->setUser($users[0]); $adminuser = $this->getDataGenerator()->create_user(); $this->setAdminUser($adminuser); // Set up gradebook roles $context = context_course::instance($courses[0]->id); $roleid = create_role('role', 'role', 'grade me block'); $roleid2 = create_role('role2', 'role2', 'grade me block'); set_role_contextlevels($roleid, array(CONTEXT_COURSE)); role_assign($roleid, $users[0]->id, $context->id); role_assign($roleid2, $users[1]->id, $context->id); set_config('gradebookroles', "$roleid, $roleid2"); // Create a manual enrolment record. $manual_enrol_data['enrol'] = 'manual'; $manual_enrol_data['status'] = 0; $manual_enrol_data['courseid'] = 2; $enrolid = $DB->insert_record('enrol', $manual_enrol_data); // Create the user enrolment record. $DB->insert_record('user_enrolments', (object)array( 'status' => 0, 'enrolid' => $enrolid, 'userid' => $users[0]->id )); $DB->insert_record('user_enrolments', (object)array( 'status' => 0, 'enrolid' => $enrolid, 'userid' => $users[1]->id )); $grademe = new block_grade_me(); $content = $grademe->get_content(); foreach ($expectedvalues as $expected) { $match = str_replace('[user0]', $users[0]->id, $expected); $match = str_replace('[user1]', $users[1]->id, $match); $this->assertRegExp($match, $content->text); } } /** * Test that the forum plugin uses the correct ID link to a forum discussion. * * @depends test_load_db */ public function test_tree_uses_correct_forum_discussion_id() { global $DB; $this->resetAfterTest(true); list($users, $courses, $plugins) = $this->create_grade_me_data('block_grade_me.xml'); list($sql, $params) = block_grade_me_query_forum(array($users[0]->id)); $sql = block_grade_me_query_prefix().$sql.block_grade_me_query_suffix('forum'); $result = $DB->get_recordset_sql($sql, array($params[0], 'courseid' => $courses[0]->id)); $gradeables = array(); foreach ($result as $rec) { $gradeables = block_grade_me_array($gradeables, $rec); } $this->assertFalse(empty($gradeables), 'Expected results not found.'); $actual = block_grade_me_tree($gradeables); $this->assertRegExp('/mod\/forum\/discuss.php\?d=100\#p1/', $actual); } }
gpl-3.0
hsab/UMOG
setup.py
11509
''' Copyright (C) 2016 Jacques Lucke [email protected] Created by Jacques Lucke This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' ''' Command Line Arguments: python setup.py --all # recompile all --export # make redistributable version --nocopy # don't copy the build into Blenders addon directory --noversioncheck # allow to create a build with any Python version Generate .html files to debug cython code: cython -a path/to/file.pyx Cleanup Repository: git clean -fdx # make sure you don't have uncommited files! ''' import os import sys import shutil import traceback import numpy from os.path import abspath, dirname, join, relpath addonName = "umog_addon" currentDirectory = dirname(abspath(__file__)) sourceDirectory = join(currentDirectory, addonName) configPath = join(currentDirectory, "config.py") defaultConfigPath = join(currentDirectory, "config.default.py") compilationInfoPath = join(sourceDirectory, "compilation_info.json") config = {} initialArgs = sys.argv[:] expectedArgs = {"--all", "--export", "--nocopy", "--noversioncheck"} unknownArgs = set(initialArgs[1:]) - expectedArgs if len(unknownArgs) > 0: print("Unknown arguments:", unknownArgs) print("Allowed arguments:", expectedArgs) sys.exit() v = sys.version_info if "--noversioncheck" not in initialArgs and (v.major != 3 or v.minor != 5): print("Blender 2.78/2.79 officially uses Python 3.5.x.") print("You are using: {}".format(sys.version)) print() print("Use the --noversioncheck argument to disable this check.") sys.exit() else: print(sys.version) print() def main(): setupAndReadConfigFile() if canCompile(): preprocessor() if "--all" in initialArgs: removeCFiles() removeCompiledFiles() compileCythonFiles() writeCompilationInfoFile() if "--export" in initialArgs: export() if not "--nocopy" in initialArgs: if os.path.isdir(config["addonsDirectory"]): copyToBlender() else: print("The path to Blenders addon directory does not exist") print("The current addons directory is: " + config["addonsDirectory"]) print("Please correct the config.py file.") def setupAndReadConfigFile(): if not os.path.isfile(configPath) and os.path.isfile(defaultConfigPath): shutil.copyfile(defaultConfigPath, configPath) print("Copied the config.default.py file to config.py") print("Please change it manually if needed.") print("Note: git ignores it, so depending on the settings of your editor") print(" it might not be shown inside it.\n\n") if os.path.isfile(configPath): configCode = readFile(configPath) exec(configCode, config, config) else: print("Cannot find any of these files: config.py, config.default.py ") print("Make sure that at least the config.default.py exists.") print("Maybe you have to clone the repository again.") sys.exit() def canCompile(): if "bpy" in sys.modules: return False if not os.path.isdir(sourceDirectory): return False correctSysPath() try: import Cython return True except: print("Cython is not installed for this Python version.") print(sys.version) return False def correctSysPath(): pathsToRemove = [path for path in sys.path if currentDirectory in path] for path in pathsToRemove: sys.path.remove(path) print("Removed from sys.path:", path) # Preprocess - execute .pre files ################################################################### def preprocessor(): for path in iterPathsWithSuffix(".pre"): code = readFile(path) codeBlock = compile(code, path, "exec") context = { "__file__" : abspath(path), "readFile" : readFile, "writeFile" : writeFile, "multiReplace" : multiReplace, "dependenciesChanged" : dependenciesChanged, "changeFileName" : changeFileName} exec(codeBlock, context, context) # Translate .pyx to .c files and compile extension modules ################################################################### def compileCythonFiles(): from distutils.core import setup from Cython.Build import cythonize sys.argv = [sys.argv[0], "build_ext", "--inplace"] extensions = cythonize(getPathsToCythonFiles(), compiler_directives={'cdivision': True, 'cdivision_warnings': False}) setup(name = 'umog_addon', ext_modules = extensions, include_dirs=[numpy.get_include()]) print("Compilation Successful.") sys.argv = [sys.argv[0], "clean"] setup(name = 'umog_addon', ext_modules = extensions) def getPathsToCythonFiles(): return list(iterPathsWithSuffix(".pyx")) def removeCFiles(): for path in iterPathsWithSuffix(".c"): os.remove(path) print("Remove generated .c files.") def removeCompiledFiles(): for path in iterPathsWithSuffix(".so"): os.remove(path) for path in iterPathsWithSuffix(".pyd"): os.remove(path) print("Remove compiled files.") # Compilation Info File ################################################################### def writeCompilationInfoFile(): import Cython info = {} info["sys.version"] = sys.version info["sys.platform"] = sys.platform info["sys.api_version"] = sys.api_version info["sys.version_info"] = sys.version_info info["Cython.__version__"] = Cython.__version__ info["os.name"] = os.name import json writeFile(compilationInfoPath, json.dumps(info, indent = 4)) # Copy to Blenders addons directory ################################################################### def copyToBlender(): print("\n\nCopy changes to addon folder") targetPath = join(config["addonsDirectory"], addonName) try: copyAddonFiles(sourceDirectory, targetPath, verbose = True) except PermissionError: traceback.print_exc() print("\n\nMaybe this error happens because Blender is running.") sys.exit() print("\nCopied all changes") # Export Build ################################################################### def export(): print("\nStart Export") targetPath = join(currentDirectory, addonName + ".zip") zipAddonDirectory(sourceDirectory, targetPath) print("Finished Export") print("Zipped file can be found here:") print(" " + targetPath) # Copy Addon Utilities ################################################################### def copyAddonFiles(source, target, verbose = False): if not os.path.isdir(target): os.mkdir(target) existingFilesInSource = set(iterRelativeAddonFiles(source)) existingFilesInTarget = set(iterRelativeAddonFiles(target)) counter = 0 filesToRemove = existingFilesInTarget - existingFilesInSource for relativePath in filesToRemove: path = join(target, relativePath) removeFile(path) if verbose: print("Removed File: ", path) counter += 1 filesToCreate = existingFilesInSource - existingFilesInTarget for relativePath in filesToCreate: sourcePath = join(source, relativePath) targetPath = join(target, relativePath) copyFile(sourcePath, targetPath) if verbose: print("Created File: ", targetPath) counter += 1 filesToUpdate = existingFilesInSource.intersection(existingFilesInTarget) for relativePath in filesToUpdate: sourcePath = join(source, relativePath) targetPath = join(target, relativePath) sourceModificationTime = os.stat(sourcePath).st_mtime targetModificationTime = os.stat(targetPath).st_mtime if sourceModificationTime > targetModificationTime: overwriteFile(sourcePath, targetPath) if verbose: print("Updated File: ", targetPath) counter += 1 print("Changed {} files.".format(counter)) def removeFile(path): try: os.remove(path) except: if tryGetFileAccessPermission(path): os.remove(path) def copyFile(source, target): directory = dirname(target) if not os.path.isdir(directory): os.makedirs(directory) shutil.copyfile(source, target) def overwriteFile(source, target): removeFile(target) copyFile(source, target) def iterRelativeAddonFiles(directory): if not os.path.isdir(directory): return for root, folders, files in os.walk(directory, topdown = True): for folder in folders: if ignoreAddonDirectory(folder): folders.remove(folder) for fileName in files: if not ignoreAddonFile(fileName): yield relpath(join(root, fileName), directory) def ignoreAddonFile(name): return name.endswith(".c") or name.endswith(".html") def ignoreAddonDirectory(name): return name in {".git", "__pycache__"} def tryRemoveDirectory(path): try: shutil.rmtree(path, onerror = handlePermissionError) except FileNotFoundError: pass def handlePermissionError(function, path, excinfo): if tryGetFileAccessPermission(path): function(path) else: raise def tryGetFileAccessPermission(path): import stat if not os.access(path, os.W_OK): os.chmod(path, stat.S_IWUSR) return True return False def zipAddonDirectory(sourcePath, targetPath): try: os.remove(targetPath) except FileNotFoundError: pass import zipfile with zipfile.ZipFile(targetPath, "w", zipfile.ZIP_DEFLATED) as zipFile: for relativePath in iterRelativeAddonFiles(sourcePath): absolutePath = join(sourcePath, relativePath) zipFile.write(absolutePath, join(addonName, relativePath)) # Utils ################################################################### def iterPathsWithSuffix(suffix): for root, dirs, files in os.walk(sourceDirectory): for fileName in files: if fileName.endswith(suffix): yield join(root, fileName) def writeFile(path, content): with open(path, "wt") as f: f.write(content) print("Changed File:", path) def readFile(path): with open(path, "rt") as f: return f.read() def changeFileName(path, newName): return join(dirname(path), newName) def multiReplace(text, **replacements): for key, value in replacements.items(): text = text.replace(key, value) return text def dependenciesChanged(target, dependencies): try: targetTime = os.stat(target).st_mtime except FileNotFoundError: targetTime = 0 latestDependencyModification = max(os.stat(path).st_mtime for path in dependencies) return targetTime < latestDependencyModification main()
gpl-3.0
946493655/culture
resources/views/admin/common/info.blade.php
1788
{{--这里是展示右侧信息的模板--}} <div class="am-u-sm-12 am-u-md-4 am-u-md-push-8"> <div class="am-panel am-panel-default"> <div class="am-panel-bd"> <div class="user-info"> {{--<p>等级信息</p>--}} {{--<div class="am-progress am-progress-sm">--}} {{--<div class="am-progress-bar" style="width: 60%"></div>--}} {{--</div>--}} {{--<p class="user-info-order">--}} {{--当前等级:<strong>LV8</strong> --}} {{--活跃天数:<strong>587</strong> --}} {{--距离下一级别:<strong>160</strong></p>--}} {{--<p>管理员信息</p>--}} <p class="user-info-order">管理员名称:<strong>{{ Session::get('admin.username') }}</strong></p> <p class="user-info-order">所在角色组:{{ Session::get('admin.role_name') }}<strong></strong></p> <p class="user-info-order">注册时间:<strong>{{ Session::get('admin.createTime') }}</strong></p> <p>登陆时间:<strong>{{ Session::get('admin.loginTime') }}</strong></p> </div> {{--<div class="user-info">--}} {{--<p>信用信息</p>--}} {{--<div class="am-progress am-progress-sm">--}} {{--<div class="am-progress-bar am-progress-bar-success" style="width: 80%"></div>--}} {{--</div>--}} {{--<p class="user-info-order">--}} {{--信用等级:正常当前 --}} {{--信用积分:<strong>80</strong>--}} {{--</p>--}} {{--</div>--}} </div> </div> </div>
gpl-3.0
ZF2-Modulus/ModulusProducts
src/ModulusProducts/Form/ProductsCategory.php
1711
<?php namespace ModulusProducts\Form; use ModulusForm\Form\FormDefault, Zend\Form\Element\Select; use Zend\InputFilter; class ProductsCategory extends FormDefault { public function addElements() { $this->add(array( 'name' => 'id', 'options' => array( 'label' => '', ), 'attributes' => array( 'type' => 'hidden' ), )); $this->add(array( 'name' => 'name', 'options' => array( 'label' => 'Nome: ', ), 'type' => 'Zend\Form\Element\Text', 'attributes' => array( 'placeholder' => 'Entre com o nome da categoria', ), )); $this->add(new \Zend\Form\Element\Csrf('security')); $this->add(array( 'name' => 'submit', 'attributes' => array( 'value' => 'Salvar', 'type' => 'submit', 'class' => 'btn btn-primary', ), )); } public function addInputFilter() { $inputFilter = new InputFilter\InputFilter(); $inputFilter->add(array( 'name' => 'name', 'required' => true, 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'min' => 3, 'max' => 100, ), ), ), 'filters' => array( array('name' => 'StringTrim'), ), )); $this->setInputFilter($inputFilter); } }
gpl-3.0
kuiwang/my-dev
src/main/java/com/taobao/api/request/JuCatitemidsGetRequest.java
4770
package com.taobao.api.request; import java.util.Map; import com.taobao.api.ApiRuleException; import com.taobao.api.TaobaoRequest; import com.taobao.api.internal.util.RequestCheckUtils; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.response.JuCatitemidsGetResponse; /** * TOP API: taobao.ju.catitemids.get request * * @author auto create * @since 1.0, 2014-11-02 16:51:25 */ public class JuCatitemidsGetRequest implements TaobaoRequest<JuCatitemidsGetResponse> { /** * 商品子类目ID。男装:100001,女装:100002。 */ private Long childCategoryid; /** * 查询本地生活团商品时需要用city进行过滤,如果city是all的话,则查询所有城市的本地生活团商品。如果为空,则查询普通商品 */ private String city; private Map<String, String> headerMap = new TaobaoHashMap(); /** * 分页获取商品信息页序号,代表第几页。page_no=0代表第一页。<br /> * 支持最小值为:0 */ private Long pageNo; /** * 每次获取商品列表的数量。最大是100个,如果超出则报41错。<br /> * 支持最大值为:100<br /> * 支持最小值为:1 */ private Long pageSize; /** * 商品父类目ID。服装:100000,保险:1000000。 */ private Long parentCategoryid; /** * 平台ID。搜狗:1008,聚划算:1001,商城:1002,无线WAP:1007,支付宝:1003,淘宝天下:1004,嗨淘:1006 */ private Long platformId; /** * IPHONE,WAP,ANDROID,SINA,163 各种终端类型 */ private String terminalType; private Long timestamp; private TaobaoHashMap udfParams; // add user-defined text parameters @Override public void check() throws ApiRuleException { RequestCheckUtils.checkNotEmpty(pageNo, "pageNo"); RequestCheckUtils.checkMinValue(pageNo, 0L, "pageNo"); RequestCheckUtils.checkNotEmpty(pageSize, "pageSize"); RequestCheckUtils.checkMaxValue(pageSize, 100L, "pageSize"); RequestCheckUtils.checkMinValue(pageSize, 1L, "pageSize"); RequestCheckUtils.checkNotEmpty(parentCategoryid, "parentCategoryid"); } @Override public String getApiMethodName() { return "taobao.ju.catitemids.get"; } public Long getChildCategoryid() { return this.childCategoryid; } public String getCity() { return this.city; } @Override public Map<String, String> getHeaderMap() { return headerMap; } public Long getPageNo() { return this.pageNo; } public Long getPageSize() { return this.pageSize; } public Long getParentCategoryid() { return this.parentCategoryid; } public Long getPlatformId() { return this.platformId; } @Override public Class<JuCatitemidsGetResponse> getResponseClass() { return JuCatitemidsGetResponse.class; } public String getTerminalType() { return this.terminalType; } @Override public Map<String, String> getTextParams() { TaobaoHashMap txtParams = new TaobaoHashMap(); txtParams.put("child_categoryid", this.childCategoryid); txtParams.put("city", this.city); txtParams.put("page_no", this.pageNo); txtParams.put("page_size", this.pageSize); txtParams.put("parent_categoryid", this.parentCategoryid); txtParams.put("platform_id", this.platformId); txtParams.put("terminal_type", this.terminalType); if (this.udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } @Override public Long getTimestamp() { return this.timestamp; } @Override public void putOtherTextParam(String key, String value) { if (this.udfParams == null) { this.udfParams = new TaobaoHashMap(); } this.udfParams.put(key, value); } public void setChildCategoryid(Long childCategoryid) { this.childCategoryid = childCategoryid; } public void setCity(String city) { this.city = city; } public void setPageNo(Long pageNo) { this.pageNo = pageNo; } public void setPageSize(Long pageSize) { this.pageSize = pageSize; } public void setParentCategoryid(Long parentCategoryid) { this.parentCategoryid = parentCategoryid; } public void setPlatformId(Long platformId) { this.platformId = platformId; } public void setTerminalType(String terminalType) { this.terminalType = terminalType; } @Override public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } }
gpl-3.0
campbellfreivin/campbellfreivin.github.io
config/application.rb
1117
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Exampleapp class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
gpl-3.0
RTMC-development-team/RTMCCommon
src/main/java/com/rushteamc/plugin/common/Database/DatabaseManager.java
4269
package com.rushteamc.plugin.common.Database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; public class DatabaseManager { private static Connection connection; private static DatabaseQueryHandler databaseQueryHandler; private static String tablePrefix = ""; public static <returnType> returnType addDatabaseRunnable(DatabaseRunnable<returnType> databaseRunnable) { databaseQueryHandler.addDatabaseRunnable(databaseRunnable); while (databaseRunnable.isBlocking()) { try { Thread.sleep(10L); } catch (InterruptedException e) { e.printStackTrace(); } } return databaseRunnable.getReturnValue(); } public static void setup(String host, String database, String username, String password) { String url = "jdbc:mysql://" + host + "/" + database + "?characterEncoding=UTF-8&autoReconnect=true"; try { connection = DriverManager.getConnection(url, username, password); } catch (SQLException e) { e.printStackTrace(); } databaseQueryHandler = new DatabaseQueryHandler(); addDatabaseRunnable(new DatabaseRunnable<Void>(DatabaseRunnable.Priority.HIGHEST) { public Void run() { try { Statement statement = DatabaseManager.connection.createStatement(); statement.addBatch("CREATE TABLE IF NOT EXISTS `" + DatabaseManager.getTablePrefix() + "Users` (ID int UNSIGNED NOT NULL AUTO_INCREMENT, Username varchar(127) NOT NULL, Password varchar(128) NOT NULL DEFAULT '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', Prefix Text, Suffix Text, PRIMARY KEY (ID) );"); statement.addBatch("CREATE TABLE IF NOT EXISTS `" + DatabaseManager.getTablePrefix() + "UserGroups` (UserID int UNSIGNED NOT NULL, GroupID int UNSIGNED NOT NULL, PRIMARY KEY (UserID, GroupID) );"); statement.addBatch("CREATE TABLE IF NOT EXISTS `" + DatabaseManager.getTablePrefix() + "UserPermissions` (UserID int UNSIGNED NOT NULL, Permission varchar(255) NOT NULL, Granded boolean NOT NULL, PRIMARY KEY (UserID, Permission) );"); statement.addBatch("CREATE TABLE IF NOT EXISTS `" + DatabaseManager.getTablePrefix() + "Groups` (ID int UNSIGNED NOT NULL AUTO_INCREMENT, Groupname varchar(127) NOT NULL, Prefix Text, Suffix Text, `Default` boolean DEFAULT 0 NOT NULL, PRIMARY KEY (ID) );"); statement.addBatch("CREATE TABLE IF NOT EXISTS `" + DatabaseManager.getTablePrefix() + "GroupParents` (GroupID int UNSIGNED NOT NULL, ParentGroupID int UNSIGNED NOT NULL, PRIMARY KEY (GroupID, ParentGroupID) );"); statement.addBatch("CREATE TABLE IF NOT EXISTS `" + DatabaseManager.getTablePrefix() + "GroupPermissions` (GroupID int UNSIGNED NOT NULL, Permission varchar(255) NOT NULL, Granded boolean NOT NULL, PRIMARY KEY (GroupID, Permission) );"); statement.executeBatch(); } catch (SQLException e) { e.printStackTrace(); } return null; } }); } public static void close() { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } connection = null; } } public static PreparedStatement createPreparedStatement(String SQLQuery) throws SQLException { if (connection == null) { throw new ConnectionNotInitializedException(); } return connection.prepareStatement(SQLQuery); } public static PreparedStatement createPreparedInsertStatement(String SQLQuery) throws SQLException { if (connection == null) { throw new ConnectionNotInitializedException(); } return connection.prepareStatement(SQLQuery, 1); } public static PreparedStatement createPreparedInsertStatement(String SQLQuery, String id) throws SQLException { if (connection == null) { throw new ConnectionNotInitializedException(); } return connection.prepareStatement(SQLQuery, new String[] { id }); } public static String getTablePrefix() { return tablePrefix; } public static void setTablePrefix(String tablePrefix) { DatabaseManager.tablePrefix = tablePrefix; } public static class ConnectionNotInitializedException extends SQLException { private static final long serialVersionUID = -6848497979400328468L; } }
gpl-3.0
thebestgirl123/CloudBot
plugins/dogpile.py
1592
import requests import random from urllib import parse from bs4 import BeautifulSoup from cloudbot import hook search_url = "http://dogpile.com/search" HEADERS = {'User-Agent': 'Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19'} opt_out = [] @hook.command("dpis", "gis") def dogpileimage(text, chan): """Uses the dogpile search engine to search for images.""" if chan in opt_out: return image_url = search_url + "/images" params = { 'q': " ".join(text.split())} r = requests.get(image_url, params=params, headers=HEADERS) soup = BeautifulSoup(r.content) linklist = soup.find('div', id="webResults").find_all('a', {'class':'resultThumbnailLink'}) image = parse.unquote(parse.unquote(random.choice(linklist)['href']).split('ru=')[1].split('&')[0]) return image @hook.command("dp", "g", "dogpile") def dogpile(text, chan): """Uses the dogpile search engine to find shit on the web.""" if chan in opt_out: return web_url = search_url + "/web" params = {'q':" ".join(text.split())} r = requests.get(web_url, params=params, headers=HEADERS) soup = BeautifulSoup(r.content) result_url = parse.unquote(parse.unquote(soup.find('div', id="webResults").find_all('a', {'class':'resultDisplayUrl'})[0]['href']).split('ru=')[1].split('&')[0]) result_description = soup.find('div', id="webResults").find_all('div', {'class':'resultDescription'})[0].text return "{} -- \x02{}\x02".format(result_url, result_description)
gpl-3.0
Snapman/rnagios
lib/rnagios/active_status.rb
2051
# Represents the status of an active check. Valid status strings for # Nagios are OK, WARNING, CRITICAL, and UNKNOWN. UNIX/Linux exit codes # are set automatically when you set the status attribute. class ActiveStatus < Status # Indicates everything is good with the service OK = 'OK' # Indicates a status of concern; not necessarily catastrophic WARNING = 'WARNING' # Indicates a serious failure or error CRITICAL = 'CRITICAL' # Indicates that the status is unknown or can not be determined UNKNOWN = 'UNKNOWN' # UNIX/Linux exit code for Nagios OK OK_EXIT_CODE = 0 # UNIX/Linux exit code for Nagios WARNING WARNING_EXIT_CODE = 1 # UNIX/Linux exit code for Nagios CRITICAL CRITICAL_EXIT_CODE = 2 # UNIX/Linux exit code for Nagios UNKNOWN UNKNOWN_EXIT_CODE = 3 # If status is not given, it will default to UNKNOWN. If message # is not given, it will default to <EMPTY>. UNIX/Linux exit codes # are assigned automatically. def initialize(status=nil, message=nil) if status.nil? || (status != OK && status != WARNING && status != CRITICAL && status != UNKNOWN) @status = UNKNOWN else @status = status if !status.nil? end if message.nil? @message = '<EMPTY>' else @message = message end case @status when OK @exit_code = OK_EXIT_CODE when WARNING @exit_code = WARNING_EXIT_CODE when CRITICAL @exit_code = CRITICAL_EXIT_CODE when UNKNOWN @exit_code = UNKNOWN_EXIT_CODE end end def status=(value) if value.nil? || (value != OK && value != WARNING && value != CRITICAL && value != UNKNOWN) @status = UNKNOWN else @status = value end case @status when OK @exit_code = OK_EXIT_CODE when WARNING @exit_code = WARNING_EXIT_CODE when CRITICAL @exit_code = CRITICAL_EXIT_CODE when UNKNOWN @exit_code = UNKNOWN_EXIT_CODE end end def empty? @status == UNKNOWN && (@message.nil? || @message.empty? || @message == '<EMPTY>') end end
gpl-3.0
drslump/sdb
src/Commands/PrintCommand.cs
2131
/* * SDB - Mono Soft Debugger Client * Copyright 2013 Alex Rønne Petersen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System.Collections.Generic; namespace Mono.Debugger.Client.Commands { sealed class PrintCommand : Command { public override string[] Names { get { return new[] { "print", "evaluate" }; } } public override string Summary { get { return "Print (evaluate) a given expression."; } } public override string Syntax { get { return "print|evaluate <expr>"; } } public override void Process(string args) { var f = Debugger.ActiveFrame; if (f == null) { Log.Error("No active stack frame"); return; } if (args.Length == 0) { Log.Error("No expression given"); return; } if (!f.ValidateExpression(args)) { Log.Error("Expression '{0}' is invalid", args); return; } var val = f.GetExpressionValue(args, Debugger.Options.EvaluationOptions); var strErr = Utilities.StringizeValue(val); if (strErr.Item2) { Log.Error(strErr.Item1); return; } Log.Info("{0}{1}{2} it = {3}", Color.DarkGreen, val.TypeName, Color.Reset, strErr.Item1); } } }
gpl-3.0
vitalisator/librenms
LibreNMS/Snmptrap/Handlers/CpUpsDiagPassed.php
1422
<?php /** * CpUpsDiagPassed.php * * -Description- * * CyberPower UPS battery test passed. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @link http://librenms.org * @copyright 2020 KanREN Inc. * @author Heath Barnhart <[email protected]> */ namespace LibreNMS\Snmptrap\Handlers; use App\Models\Device; use LibreNMS\Interfaces\SnmptrapHandler; use LibreNMS\Snmptrap\Trap; use Log; class CpUpsDiagPassed implements SnmptrapHandler { /** * Handle snmptrap. * Data is pre-parsed and delivered as a Trap. * * @param Device $device * @param Trap $trap * @return void */ public function handle(Device $device, Trap $trap) { $diagInfo = CyberPowerUtil::getMessage($trap); Log::event("$diagInfo", $device->device_id, 'trap', 2); } }
gpl-3.0
totallyuneekname/rubiks_cube_solver
src/rubikscube/Color.java
1411
/* * Copyright (C) 2016 Jacob * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package rubikscube; /** * * @author student */ public class Color { private int colorValue; String[] colorLetters = {"O", "W", "R", "Y", "B", "G"}; public Color(int colorValue) { this.colorValue = colorValue; } public Color(String color) { color = color.toUpperCase(); for (int i = 0; i < colorLetters.length; i++) { if (colorLetters[i].equals(color)) { colorValue = i; return; } } System.out.println("Letter is not a valid color."); } public String getColor() { return this.colorLetters[this.colorValue]; } public int getIntegerVal() { return this.colorValue; } }
gpl-3.0
teddy-michel/TMediaPlayer
Sources/IMediaTable.cpp
718
/* Copyright (C) 2012-2016 Teddy Michel This file is part of TMediaPlayer. TMediaPlayer 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. TMediaPlayer 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 TMediaPlayer. If not, see <http://www.gnu.org/licenses/>. */ #include "IMediaTable.hpp"
gpl-3.0
TobiasMiosczka/NaMi
src/main/java/com/github/tobiasmiosczka/nami/applicationforms/DocUtil.java
3618
package com.github.tobiasmiosczka.nami.applicationforms; import org.docx4j.TraversalUtil; import org.docx4j.XmlUtils; import org.docx4j.finders.TableFinder; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart; import org.docx4j.openpackaging.parts.relationships.Namespaces; import org.docx4j.openpackaging.parts.relationships.RelationshipsPart; import org.docx4j.relationships.Relationship; import org.docx4j.wml.CTBorder; import org.docx4j.wml.ObjectFactory; import org.docx4j.wml.P; import org.docx4j.wml.R; import org.docx4j.wml.STBorder; import org.docx4j.wml.Tbl; import org.docx4j.wml.TblBorders; import org.docx4j.wml.TblPr; import org.docx4j.wml.Tc; import org.docx4j.wml.Text; import org.docx4j.wml.Tr; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class DocUtil { private static final ObjectFactory FACTORY = ObjectFactory.get(); public static Text createText(String content) { Text text = FACTORY.createText(); text.setValue(content); return text; } public static R createR(String content) { R r = FACTORY.createR(); r.getContent().add(createText(content)); return r; } public static P createP(String content) { P p = FACTORY.createP(); p.getContent().add(createR(content)); return p; } public static Tc createTc(String content) { Tc tc = FACTORY.createTc(); tc.getContent().add(createP(content)); return tc; } public static Tr createTr(String...contents) { Tr tr = FACTORY.createTr(); for (String content : contents) tr.getContent().add(createTc(content)); return tr; } public static List<Tbl> findTables(List<Object> objects) { TableFinder tableFinder = new TableFinder(); new TraversalUtil(objects, tableFinder); return tableFinder.tblList.stream() .map(XmlUtils::unwrap) .filter(o -> o instanceof Tbl) .map(o -> (Tbl) o) .collect(Collectors.toList()); } public static P getTableCellP(Tbl tbl, int row, int column) { Tr tr = (Tr) tbl.getContent().get(row); Tc tc = (Tc) XmlUtils.unwrap(tr.getContent().get(column)); return tc.getContent().stream() .filter(o -> o instanceof P) .map(o -> (P) o) .findFirst() .orElse(null); } public static List<HeaderPart> findHeaders(WordprocessingMLPackage wordMLPackage) { RelationshipsPart rp = wordMLPackage.getMainDocumentPart().getRelationshipsPart(); List<HeaderPart> result = new ArrayList<>(); for (Relationship r : rp.getRelationships().getRelationship()) if (r.getType().equals(Namespaces.HEADER)) result.add((HeaderPart) rp.getPart(r)); return result; } public static void addBorders(Tbl table) { table.setTblPr(new TblPr()); CTBorder border = new CTBorder(); border.setColor("auto"); border.setSz(new BigInteger("4")); border.setSpace(new BigInteger("0")); border.setVal(STBorder.SINGLE); TblBorders borders = new TblBorders(); borders.setBottom(border); borders.setLeft(border); borders.setRight(border); borders.setTop(border); borders.setInsideH(border); borders.setInsideV(border); table.getTblPr().setTblBorders(borders); } }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtbase/examples/widgets/tools/completer/mainwindow.cpp
9823
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** 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 https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "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 Qt Company Ltd 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtWidgets> #include "fsmodel.h" #include "mainwindow.h" //! [0] MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), completer(0), lineEdit(0) { createMenu(); QWidget *centralWidget = new QWidget; QLabel *modelLabel = new QLabel; modelLabel->setText(tr("Model")); modelCombo = new QComboBox; modelCombo->addItem(tr("QFileSytemModel")); modelCombo->addItem(tr("QFileSytemModel that shows full path")); modelCombo->addItem(tr("Country list")); modelCombo->addItem(tr("Word list")); modelCombo->setCurrentIndex(0); QLabel *modeLabel = new QLabel; modeLabel->setText(tr("Completion Mode")); modeCombo = new QComboBox; modeCombo->addItem(tr("Inline")); modeCombo->addItem(tr("Filtered Popup")); modeCombo->addItem(tr("Unfiltered Popup")); modeCombo->setCurrentIndex(1); QLabel *caseLabel = new QLabel; caseLabel->setText(tr("Case Sensitivity")); caseCombo = new QComboBox; caseCombo->addItem(tr("Case Insensitive")); caseCombo->addItem(tr("Case Sensitive")); caseCombo->setCurrentIndex(0); //! [0] //! [1] QLabel *maxVisibleLabel = new QLabel; maxVisibleLabel->setText(tr("Max Visible Items")); maxVisibleSpinBox = new QSpinBox; maxVisibleSpinBox->setRange(3,25); maxVisibleSpinBox->setValue(10); wrapCheckBox = new QCheckBox; wrapCheckBox->setText(tr("Wrap around completions")); wrapCheckBox->setChecked(true); //! [1] //! [2] contentsLabel = new QLabel; contentsLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); connect(modelCombo, SIGNAL(activated(int)), this, SLOT(changeModel())); connect(modeCombo, SIGNAL(activated(int)), this, SLOT(changeMode(int))); connect(caseCombo, SIGNAL(activated(int)), this, SLOT(changeCase(int))); connect(maxVisibleSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changeMaxVisible(int))); //! [2] //! [3] lineEdit = new QLineEdit; QGridLayout *layout = new QGridLayout; layout->addWidget(modelLabel, 0, 0); layout->addWidget(modelCombo, 0, 1); layout->addWidget(modeLabel, 1, 0); layout->addWidget(modeCombo, 1, 1); layout->addWidget(caseLabel, 2, 0); layout->addWidget(caseCombo, 2, 1); layout->addWidget(maxVisibleLabel, 3, 0); layout->addWidget(maxVisibleSpinBox, 3, 1); layout->addWidget(wrapCheckBox, 4, 0); layout->addWidget(contentsLabel, 5, 0, 1, 2); layout->addWidget(lineEdit, 6, 0, 1, 2); centralWidget->setLayout(layout); setCentralWidget(centralWidget); changeModel(); setWindowTitle(tr("Completer")); lineEdit->setFocus(); } //! [3] //! [4] void MainWindow::createMenu() { QAction *exitAction = new QAction(tr("Exit"), this); QAction *aboutAct = new QAction(tr("About"), this); QAction *aboutQtAct = new QAction(tr("About Qt"), this); connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); QMenu* fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(exitAction); QMenu* helpMenu = menuBar()->addMenu(tr("About")); helpMenu->addAction(aboutAct); helpMenu->addAction(aboutQtAct); } //! [4] //! [5] QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly)) return new QStringListModel(completer); //! [5] //! [6] #ifndef QT_NO_CURSOR QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); #endif QStringList words; while (!file.atEnd()) { QByteArray line = file.readLine(); if (!line.isEmpty()) words << line.trimmed(); } #ifndef QT_NO_CURSOR QApplication::restoreOverrideCursor(); #endif //! [6] //! [7] if (!fileName.contains(QLatin1String("countries.txt"))) return new QStringListModel(words, completer); //! [7] // The last two chars of the countries.txt file indicate the country // symbol. We put that in column 2 of a standard item model //! [8] QStandardItemModel *m = new QStandardItemModel(words.count(), 2, completer); //! [8] //! [9] for (int i = 0; i < words.count(); ++i) { QModelIndex countryIdx = m->index(i, 0); QModelIndex symbolIdx = m->index(i, 1); QString country = words[i].mid(0, words[i].length() - 2).trimmed(); QString symbol = words[i].right(2); m->setData(countryIdx, country); m->setData(symbolIdx, symbol); } return m; } //! [9] //! [10] void MainWindow::changeMode(int index) { QCompleter::CompletionMode mode; if (index == 0) mode = QCompleter::InlineCompletion; else if (index == 1) mode = QCompleter::PopupCompletion; else mode = QCompleter::UnfilteredPopupCompletion; completer->setCompletionMode(mode); } //! [10] void MainWindow::changeCase(int cs) { completer->setCaseSensitivity(cs ? Qt::CaseSensitive : Qt::CaseInsensitive); } //! [11] void MainWindow::changeModel() { delete completer; completer = new QCompleter(this); completer->setMaxVisibleItems(maxVisibleSpinBox->value()); switch (modelCombo->currentIndex()) { default: case 0: { // Unsorted QFileSystemModel QFileSystemModel *fsModel = new QFileSystemModel(completer); fsModel->setRootPath(""); completer->setModel(fsModel); contentsLabel->setText(tr("Enter file path")); } break; //! [11] //! [12] case 1: { // FileSystemModel that shows full paths FileSystemModel *fsModel = new FileSystemModel(completer); completer->setModel(fsModel); fsModel->setRootPath(""); contentsLabel->setText(tr("Enter file path")); } break; //! [12] //! [13] case 2: { // Country List completer->setModel(modelFromFile(":/resources/countries.txt")); QTreeView *treeView = new QTreeView; completer->setPopup(treeView); treeView->setRootIsDecorated(false); treeView->header()->hide(); treeView->header()->setStretchLastSection(false); treeView->header()->setSectionResizeMode(0, QHeaderView::Stretch); treeView->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); contentsLabel->setText(tr("Enter name of your country")); } break; //! [13] //! [14] case 3: { // Word list completer->setModel(modelFromFile(":/resources/wordlist.txt")); completer->setModelSorting(QCompleter::CaseInsensitivelySortedModel); contentsLabel->setText(tr("Enter a word")); } break; } changeMode(modeCombo->currentIndex()); changeCase(caseCombo->currentIndex()); completer->setWrapAround(wrapCheckBox->isChecked()); lineEdit->setCompleter(completer); connect(wrapCheckBox, SIGNAL(clicked(bool)), completer, SLOT(setWrapAround(bool))); } //! [14] //! [15] void MainWindow::changeMaxVisible(int max) { completer->setMaxVisibleItems(max); } //! [15] //! [16] void MainWindow::about() { QMessageBox::about(this, tr("About"), tr("This example demonstrates the " "different features of the QCompleter class.")); } //! [16]
gpl-3.0
Philips14171/qt-creator-opensource-src-4.2.1
src/plugins/android/androidsettingswidget.cpp
26140
/**************************************************************************** ** ** Copyright (C) 2016 BogDan Vatra <[email protected]> ** Contact: https://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 https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "androidsettingswidget.h" #include "ui_androidsettingswidget.h" #include "androidconfigurations.h" #include "androidconstants.h" #include "androidtoolchain.h" #include <utils/environment.h> #include <utils/hostosinfo.h> #include <utils/pathchooser.h> #include <utils/runextensions.h> #include <utils/utilsicons.h> #include <projectexplorer/toolchainmanager.h> #include <projectexplorer/kitmanager.h> #include <projectexplorer/kitinformation.h> #include <qtsupport/qtkitinformation.h> #include <qtsupport/qtversionmanager.h> #include <QFile> #include <QTextStream> #include <QProcess> #include <QTimer> #include <QTime> #include <QDesktopServices> #include <QFileDialog> #include <QMessageBox> #include <QModelIndex> #include <QtCore/QUrl> namespace Android { namespace Internal { void AvdModel::setAvdList(const QVector<AndroidDeviceInfo> &list) { beginResetModel(); m_list = list; endResetModel(); } QModelIndex AvdModel::indexForAvdName(const QString &avdName) const { for (int i = 0; i < m_list.size(); ++i) { if (m_list.at(i).serialNumber == avdName) return index(i, 0); } return QModelIndex(); } QString AvdModel::avdName(const QModelIndex &index) const { return m_list.at(index.row()).avdname; } QVariant AvdModel::data(const QModelIndex &index, int role) const { if (role != Qt::DisplayRole || !index.isValid()) return QVariant(); switch (index.column()) { case 0: return m_list[index.row()].avdname; case 1: return QString::fromLatin1("API %1").arg(m_list[index.row()].sdk); case 2: { QStringList cpuAbis = m_list[index.row()].cpuAbi; return cpuAbis.isEmpty() ? QVariant() : QVariant(cpuAbis.first()); } } return QVariant(); } QVariant AvdModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch (section) { case 0: //: AVD - Android Virtual Device return tr("AVD Name"); case 1: return tr("AVD Target"); case 2: return tr("CPU/ABI"); } } return QAbstractItemModel::headerData(section, orientation, role ); } int AvdModel::rowCount(const QModelIndex &/*parent*/) const { return m_list.size(); } int AvdModel::columnCount(const QModelIndex &/*parent*/) const { return 3; } AndroidSettingsWidget::AndroidSettingsWidget(QWidget *parent) : QWidget(parent), m_sdkState(NotSet), m_ndkState(NotSet), m_javaState(NotSet), m_ui(new Ui_AndroidSettingsWidget), m_androidConfig(AndroidConfigurations::currentConfig()) { m_ui->setupUi(this); connect(&m_checkGdbWatcher, &QFutureWatcherBase::finished, this, &AndroidSettingsWidget::checkGdbFinished); m_ui->SDKLocationPathChooser->setFileName(m_androidConfig.sdkLocation()); m_ui->SDKLocationPathChooser->setPromptDialogTitle(tr("Select Android SDK folder")); m_ui->NDKLocationPathChooser->setFileName(m_androidConfig.ndkLocation()); m_ui->NDKLocationPathChooser->setPromptDialogTitle(tr("Select Android NDK folder")); QString dir; QString filter; if (Utils::HostOsInfo::isWindowsHost()) { dir = QDir::homePath() + QLatin1String("/ant.bat"); filter = QLatin1String("ant (ant.bat)"); } else if (Utils::HostOsInfo::isMacHost()) { // work around QTBUG-7739 that prohibits filters that don't start with * dir = QLatin1String("/usr/bin/ant"); filter = QLatin1String("ant (*ant)"); } else { dir = QLatin1String("/usr/bin/ant"); filter = QLatin1String("ant (ant)"); } m_ui->AntLocationPathChooser->setFileName(m_androidConfig.antLocation()); m_ui->AntLocationPathChooser->setExpectedKind(Utils::PathChooser::Command); m_ui->AntLocationPathChooser->setPromptDialogTitle(tr("Select ant Script")); m_ui->AntLocationPathChooser->setInitialBrowsePathBackup(dir); m_ui->AntLocationPathChooser->setPromptDialogFilter(filter); m_ui->UseGradleCheckBox->setChecked(m_androidConfig.useGrandle()); m_ui->OpenJDKLocationPathChooser->setFileName(m_androidConfig.openJDKLocation()); m_ui->OpenJDKLocationPathChooser->setPromptDialogTitle(tr("Select JDK Path")); m_ui->DataPartitionSizeSpinBox->setValue(m_androidConfig.partitionSize()); m_ui->CreateKitCheckBox->setChecked(m_androidConfig.automaticKitCreation()); m_ui->AVDTableView->setModel(&m_AVDModel); m_ui->AVDTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); m_ui->AVDTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); m_ui->downloadAntToolButton->setVisible(!Utils::HostOsInfo::isLinuxHost()); m_ui->downloadOpenJDKToolButton->setVisible(!Utils::HostOsInfo::isLinuxHost()); const QPixmap warningPixmap = Utils::Icons::WARNING.pixmap(); m_ui->jdkWarningIconLabel->setPixmap(warningPixmap); m_ui->kitWarningIconLabel->setPixmap(warningPixmap); const QPixmap errorPixmap = Utils::Icons::ERROR.pixmap(); m_ui->sdkWarningIconLabel->setPixmap(errorPixmap); m_ui->gdbWarningIconLabel->setPixmap(errorPixmap); m_ui->ndkWarningIconLabel->setPixmap(errorPixmap); connect(m_ui->gdbWarningLabel, &QLabel::linkActivated, this, &AndroidSettingsWidget::showGdbWarningDialog); connect(&m_virtualDevicesWatcher, &QFutureWatcherBase::finished, this, &AndroidSettingsWidget::updateAvds); check(All); applyToUi(All); connect(&m_futureWatcher, &QFutureWatcherBase::finished, this, &AndroidSettingsWidget::avdAdded); connect(m_ui->NDKLocationPathChooser, &Utils::PathChooser::rawPathChanged, this, &AndroidSettingsWidget::ndkLocationEditingFinished); connect(m_ui->SDKLocationPathChooser, &Utils::PathChooser::rawPathChanged, this, &AndroidSettingsWidget::sdkLocationEditingFinished); connect(m_ui->AntLocationPathChooser, &Utils::PathChooser::rawPathChanged, this, &AndroidSettingsWidget::antLocationEditingFinished); connect(m_ui->OpenJDKLocationPathChooser, &Utils::PathChooser::rawPathChanged, this, &AndroidSettingsWidget::openJDKLocationEditingFinished); connect(m_ui->AVDAddPushButton, &QAbstractButton::clicked, this, &AndroidSettingsWidget::addAVD); connect(m_ui->AVDRemovePushButton, &QAbstractButton::clicked, this, &AndroidSettingsWidget::removeAVD); connect(m_ui->AVDStartPushButton, &QAbstractButton::clicked, this, &AndroidSettingsWidget::startAVD); connect(m_ui->AVDTableView, &QAbstractItemView::activated, this, &AndroidSettingsWidget::avdActivated); connect(m_ui->AVDTableView, &QAbstractItemView::clicked, this, &AndroidSettingsWidget::avdActivated); connect(m_ui->DataPartitionSizeSpinBox, &QAbstractSpinBox::editingFinished, this, &AndroidSettingsWidget::dataPartitionSizeEditingFinished); connect(m_ui->manageAVDPushButton, &QAbstractButton::clicked, this, &AndroidSettingsWidget::manageAVD); connect(m_ui->CreateKitCheckBox, &QAbstractButton::toggled, this, &AndroidSettingsWidget::createKitToggled); connect(m_ui->downloadSDKToolButton, &QAbstractButton::clicked, this, &AndroidSettingsWidget::openSDKDownloadUrl); connect(m_ui->downloadNDKToolButton, &QAbstractButton::clicked, this, &AndroidSettingsWidget::openNDKDownloadUrl); connect(m_ui->downloadAntToolButton, &QAbstractButton::clicked, this, &AndroidSettingsWidget::openAntDownloadUrl); connect(m_ui->downloadOpenJDKToolButton, &QAbstractButton::clicked, this, &AndroidSettingsWidget::openOpenJDKDownloadUrl); connect(m_ui->UseGradleCheckBox, &QAbstractButton::toggled, this, &AndroidSettingsWidget::useGradleToggled); } AndroidSettingsWidget::~AndroidSettingsWidget() { delete m_ui; m_futureWatcher.waitForFinished(); } // NOTE: Will be run via QFuture static QPair<QStringList, bool> checkGdbForBrokenPython(const QStringList &paths) { foreach (const QString &path, paths) { QTime timer; timer.start(); QProcess proc; proc.setProcessChannelMode(QProcess::MergedChannels); proc.start(path); proc.waitForStarted(); QByteArray output; while (proc.waitForReadyRead(300)) { output += proc.readAll(); if (output.contains("(gdb)")) break; if (timer.elapsed() > 7 * 1000) return qMakePair(paths, true); // Took too long, abort } output.clear(); proc.write("python import string\n"); proc.write("python print(string.ascii_uppercase)\n"); proc.write("python import struct\n"); proc.write("quit\n"); while (proc.waitForFinished(300)) { if (timer.elapsed() > 9 * 1000) return qMakePair(paths, true); // Took too long, abort } proc.waitForFinished(); output = proc.readAll(); bool error = output.contains("_PyObject_Free") || output.contains("_PyExc_IOError") || output.contains("_sysconfigdata_nd ") || !output.contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); if (error) return qMakePair(paths, error); } return qMakePair(paths, false); } void AndroidSettingsWidget::check(AndroidSettingsWidget::Mode mode) { if (mode & Sdk) { m_sdkState = Okay; if (m_androidConfig.sdkLocation().isEmpty()) m_sdkState = NotSet; else if (!(sdkLocationIsValid() && sdkPlatformToolsInstalled())) m_sdkState = Error; } if (mode & Ndk) { m_ndkState = Okay; Utils::FileName platformPath = m_androidConfig.ndkLocation(); Utils::FileName toolChainPath = m_androidConfig.ndkLocation(); Utils::FileName sourcesPath = m_androidConfig.ndkLocation(); m_ui->gdbWarningIconLabel->setVisible(false); m_ui->gdbWarningLabel->setVisible(false); if (m_androidConfig.ndkLocation().isEmpty()) { m_ndkState = NotSet; } else if (!platformPath.appendPath(QLatin1String("platforms")).exists() || !toolChainPath.appendPath(QLatin1String("toolchains")).exists() || !sourcesPath.appendPath(QLatin1String("sources/cxx-stl")).exists()) { m_ndkState = Error; m_ndkErrorMessage = tr("\"%1\" does not seem to be an Android NDK top folder.") .arg(m_androidConfig.ndkLocation().toUserOutput()); } else if (platformPath.toString().contains(QLatin1Char(' '))) { m_ndkState = Error; m_ndkErrorMessage = tr("The Android NDK cannot be installed into a path with spaces."); } else { QList<AndroidToolChainFactory::AndroidToolChainInformation> compilerPaths = AndroidToolChainFactory::toolchainPathsForNdk(m_androidConfig.ndkLocation()); m_ndkCompilerCount = compilerPaths.count(); // Check for a gdb with a broken python QStringList gdbPaths; foreach (const AndroidToolChainFactory::AndroidToolChainInformation &ati, compilerPaths) { if (ati.language == ProjectExplorer::ToolChain::Language::C) continue; // we only check the arm gdbs, that's indicative enough if (ati.abi.architecture() != ProjectExplorer::Abi::ArmArchitecture) continue; Utils::FileName gdbPath = m_androidConfig.gdbPath(ati.abi, ati.version); if (gdbPath.exists()) gdbPaths << gdbPath.toString(); } if (!gdbPaths.isEmpty()) { m_checkGdbWatcher.setFuture(Utils::runAsync(&checkGdbForBrokenPython, gdbPaths)); m_gdbCheckPaths = gdbPaths; } // See if we have qt versions for those toolchains QSet<ProjectExplorer::Abi> toolchainsForAbi; foreach (const AndroidToolChainFactory::AndroidToolChainInformation &ati, compilerPaths) { if (ati.language == ProjectExplorer::ToolChain::Language::Cxx) toolchainsForAbi.insert(ati.abi); } QSet<ProjectExplorer::Abi> qtVersionsForAbi; foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::unsortedVersions()) { if (qtVersion->type() != QLatin1String(Constants::ANDROIDQT) || qtVersion->qtAbis().isEmpty()) continue; qtVersionsForAbi.insert(qtVersion->qtAbis().first()); } QSet<ProjectExplorer::Abi> missingQtArchs = toolchainsForAbi.subtract(qtVersionsForAbi); if (missingQtArchs.isEmpty()) { m_ndkMissingQtArchs.clear(); } else { if (missingQtArchs.count() == 1) { m_ndkMissingQtArchs = tr("Qt version for architecture %1 is missing.\n" "To add the Qt version, select Options > Build & Run > Qt Versions.") .arg((*missingQtArchs.constBegin()).toString()); } else { m_ndkMissingQtArchs = tr("Qt versions for %1 architectures are missing.\n" "To add the Qt versions, select Options > Build & Run > Qt Versions.") .arg(missingQtArchs.size()); } } } } if (mode & Java) { m_javaState = Okay; if (m_androidConfig.openJDKLocation().isEmpty()) { m_javaState = NotSet; } else { Utils::FileName bin = m_androidConfig.openJDKLocation(); bin.appendPath(QLatin1String("bin/javac" QTC_HOST_EXE_SUFFIX)); if (!m_androidConfig.openJDKLocation().exists() || !bin.exists()) m_javaState = Error; } } } void AndroidSettingsWidget::applyToUi(AndroidSettingsWidget::Mode mode) { if (mode & Sdk) { if (m_sdkState == Error) { m_ui->sdkWarningIconLabel->setVisible(true); m_ui->sdkWarningLabel->setVisible(true); Utils::FileName location = Utils::FileName::fromUserInput(m_ui->SDKLocationPathChooser->rawPath()); if (sdkLocationIsValid()) m_ui->sdkWarningLabel->setText(tr("The Platform tools are missing. Please use the Android SDK Manager to install them.")); else m_ui->sdkWarningLabel->setText(tr("\"%1\" does not seem to be an Android SDK top folder.").arg(location.toUserOutput())); } else { m_ui->sdkWarningIconLabel->setVisible(false); m_ui->sdkWarningLabel->setVisible(false); } } if (mode & Ndk) { if (m_ndkState == NotSet) { m_ui->ndkWarningIconLabel->setVisible(false); m_ui->toolchainFoundLabel->setVisible(false); m_ui->kitWarningIconLabel->setVisible(false); m_ui->kitWarningLabel->setVisible(false); } else if (m_ndkState == Error) { m_ui->toolchainFoundLabel->setText(m_ndkErrorMessage); m_ui->toolchainFoundLabel->setVisible(true); m_ui->ndkWarningIconLabel->setVisible(true); m_ui->kitWarningIconLabel->setVisible(false); m_ui->kitWarningLabel->setVisible(false); } else { if (m_ndkCompilerCount > 0) { m_ui->ndkWarningIconLabel->setVisible(false); m_ui->toolchainFoundLabel->setText(tr("Found %n toolchains for this NDK.", 0, m_ndkCompilerCount)); m_ui->toolchainFoundLabel->setVisible(true); } else { m_ui->ndkWarningIconLabel->setVisible(false); m_ui->toolchainFoundLabel->setVisible(false); } if (m_ndkMissingQtArchs.isEmpty()) { m_ui->kitWarningIconLabel->setVisible(false); m_ui->kitWarningLabel->setVisible(false); } else { m_ui->kitWarningIconLabel->setVisible(true); m_ui->kitWarningLabel->setVisible(true); m_ui->kitWarningLabel->setText(m_ndkMissingQtArchs); } } } if (mode & Java) { Utils::FileName location = m_androidConfig.openJDKLocation(); bool error = m_javaState == Error; m_ui->jdkWarningIconLabel->setVisible(error); m_ui->jdkWarningLabel->setVisible(error); if (error) m_ui->jdkWarningLabel->setText(tr("\"%1\" does not seem to be a JDK folder.").arg(location.toUserOutput())); } if (mode & Sdk || mode & Java) { if (m_sdkState == Okay && m_javaState == Okay) { m_ui->AVDManagerFrame->setEnabled(true); } else { m_ui->AVDManagerFrame->setEnabled(false); } startUpdateAvd(); } } void AndroidSettingsWidget::disableAvdControls() { m_ui->AVDAddPushButton->setEnabled(false); m_ui->AVDTableView->setEnabled(false); m_ui->AVDRemovePushButton->setEnabled(false); m_ui->AVDStartPushButton->setEnabled(false); } void AndroidSettingsWidget::enableAvdControls() { m_ui->AVDTableView->setEnabled(true); m_ui->AVDAddPushButton->setEnabled(true); avdActivated(m_ui->AVDTableView->currentIndex()); } void AndroidSettingsWidget::startUpdateAvd() { disableAvdControls(); m_virtualDevicesWatcher.setFuture(m_androidConfig.androidVirtualDevicesFuture()); } void AndroidSettingsWidget::updateAvds() { m_AVDModel.setAvdList(m_virtualDevicesWatcher.result()); if (!m_lastAddedAvd.isEmpty()) { m_ui->AVDTableView->setCurrentIndex(m_AVDModel.indexForAvdName(m_lastAddedAvd)); m_lastAddedAvd.clear(); } enableAvdControls(); } bool AndroidSettingsWidget::sdkLocationIsValid() const { Utils::FileName androidExe = m_androidConfig.sdkLocation(); Utils::FileName androidBat = m_androidConfig.sdkLocation(); Utils::FileName emulator = m_androidConfig.sdkLocation(); return (androidExe.appendPath(QLatin1String("/tools/android" QTC_HOST_EXE_SUFFIX)).exists() || androidBat.appendPath(QLatin1String("/tools/android" ANDROID_BAT_SUFFIX)).exists()) && emulator.appendPath(QLatin1String("/tools/emulator" QTC_HOST_EXE_SUFFIX)).exists(); } bool AndroidSettingsWidget::sdkPlatformToolsInstalled() const { Utils::FileName adb = m_androidConfig.sdkLocation(); return adb.appendPath(QLatin1String("platform-tools/adb" QTC_HOST_EXE_SUFFIX)).exists(); } void AndroidSettingsWidget::saveSettings() { sdkLocationEditingFinished(); ndkLocationEditingFinished(); antLocationEditingFinished(); openJDKLocationEditingFinished(); dataPartitionSizeEditingFinished(); AndroidConfigurations::setConfig(m_androidConfig); } void AndroidSettingsWidget::sdkLocationEditingFinished() { m_androidConfig.setSdkLocation(Utils::FileName::fromUserInput(m_ui->SDKLocationPathChooser->rawPath())); check(Sdk); if (m_sdkState == Okay) searchForAnt(m_androidConfig.sdkLocation()); applyToUi(Sdk); } void AndroidSettingsWidget::ndkLocationEditingFinished() { m_androidConfig.setNdkLocation(Utils::FileName::fromUserInput(m_ui->NDKLocationPathChooser->rawPath())); check(Ndk); if (m_ndkState == Okay) searchForAnt(m_androidConfig.ndkLocation()); applyToUi(Ndk); } void AndroidSettingsWidget::searchForAnt(const Utils::FileName &location) { if (!m_androidConfig.antLocation().isEmpty()) return; if (location.isEmpty()) return; QDir parentFolder = location.toFileInfo().absoluteDir(); foreach (const QString &file, parentFolder.entryList()) { if (file.startsWith(QLatin1String("apache-ant"))) { Utils::FileName ant = Utils::FileName::fromString(parentFolder.absolutePath()); ant.appendPath(file).appendPath(QLatin1String("bin")); if (Utils::HostOsInfo::isWindowsHost()) ant.appendPath(QLatin1String("ant.bat")); else ant.appendPath(QLatin1String("ant")); if (ant.exists()) { m_androidConfig.setAntLocation(ant); m_ui->AntLocationPathChooser->setFileName(ant); } } } } void AndroidSettingsWidget::antLocationEditingFinished() { m_androidConfig.setAntLocation(Utils::FileName::fromUserInput(m_ui->AntLocationPathChooser->rawPath())); } void AndroidSettingsWidget::openJDKLocationEditingFinished() { m_androidConfig.setOpenJDKLocation(Utils::FileName::fromUserInput(m_ui->OpenJDKLocationPathChooser->rawPath())); check(Java); applyToUi(Java); } void AndroidSettingsWidget::openSDKDownloadUrl() { QDesktopServices::openUrl(QUrl::fromUserInput("https://developer.android.com/studio/")); } void AndroidSettingsWidget::openNDKDownloadUrl() { QDesktopServices::openUrl(QUrl::fromUserInput("https://developer.android.com/ndk/downloads/")); } void AndroidSettingsWidget::openAntDownloadUrl() { QDesktopServices::openUrl(QUrl::fromUserInput("http://ant.apache.org/bindownload.cgi")); } void AndroidSettingsWidget::openOpenJDKDownloadUrl() { QDesktopServices::openUrl(QUrl::fromUserInput("http://www.oracle.com/technetwork/java/javase/downloads/")); } void AndroidSettingsWidget::addAVD() { disableAvdControls(); AndroidConfig::CreateAvdInfo info = m_androidConfig.gatherCreateAVDInfo(this); if (info.target.isEmpty()) { enableAvdControls(); return; } m_futureWatcher.setFuture(m_androidConfig.createAVD(info)); } void AndroidSettingsWidget::avdAdded() { AndroidConfig::CreateAvdInfo info = m_futureWatcher.result(); if (!info.error.isEmpty()) { enableAvdControls(); QMessageBox::critical(this, QApplication::translate("AndroidConfig", "Error Creating AVD"), info.error); return; } startUpdateAvd(); m_lastAddedAvd = info.name; } void AndroidSettingsWidget::removeAVD() { disableAvdControls(); QString avdName = m_AVDModel.avdName(m_ui->AVDTableView->currentIndex()); if (QMessageBox::question(this, tr("Remove Android Virtual Device"), tr("Remove device \"%1\"? This cannot be undone.").arg(avdName), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { enableAvdControls(); return; } m_androidConfig.removeAVD(avdName); startUpdateAvd(); } void AndroidSettingsWidget::startAVD() { m_androidConfig.startAVDAsync(m_AVDModel.avdName(m_ui->AVDTableView->currentIndex())); } void AndroidSettingsWidget::avdActivated(const QModelIndex &index) { m_ui->AVDRemovePushButton->setEnabled(index.isValid()); m_ui->AVDStartPushButton->setEnabled(index.isValid()); } void AndroidSettingsWidget::dataPartitionSizeEditingFinished() { m_androidConfig.setPartitionSize(m_ui->DataPartitionSizeSpinBox->value()); } void AndroidSettingsWidget::createKitToggled() { m_androidConfig.setAutomaticKitCreation(m_ui->CreateKitCheckBox->isChecked()); } void AndroidSettingsWidget::useGradleToggled() { m_androidConfig.setUseGradle(m_ui->UseGradleCheckBox->isChecked()); } void AndroidSettingsWidget::checkGdbFinished() { QPair<QStringList, bool> result = m_checkGdbWatcher.future().result(); if (result.first != m_gdbCheckPaths) // no longer relevant return; m_ui->gdbWarningIconLabel->setVisible(result.second); m_ui->gdbWarningLabel->setVisible(result.second); } void AndroidSettingsWidget::showGdbWarningDialog() { QMessageBox::warning(this, tr("Unsupported GDB"), tr("The GDB inside this NDK seems to not support Python. " "The Qt Project offers fixed GDB builds at: " "<a href=\"http://download.qt.io/official_releases/gdb/\">" "http://download.qt.io/official_releases/gdb/</a>")); } void AndroidSettingsWidget::manageAVD() { QProcess *avdProcess = new QProcess(); connect(this, &QObject::destroyed, avdProcess, &QObject::deleteLater); connect(avdProcess, static_cast<void (QProcess::*)(int)>(&QProcess::finished), avdProcess, &QObject::deleteLater); avdProcess->setProcessEnvironment(m_androidConfig.androidToolEnvironment().toProcessEnvironment()); QString executable = m_androidConfig.androidToolPath().toString(); QStringList arguments = QStringList() << QLatin1String("avd"); avdProcess->start(executable, arguments); } } // namespace Internal } // namespace Android
gpl-3.0
cs-au-dk/Artemis
WebKit/Source/WebKit/chromium/src/WebIDBDatabaseImpl.cpp
4272
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * 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 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 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 "WebIDBDatabaseImpl.h" #if ENABLE(INDEXED_DATABASE) #include "DOMStringList.h" #include "IDBCallbacksProxy.h" #include "IDBDatabaseBackendInterface.h" #include "IDBDatabaseCallbacksProxy.h" #include "IDBTransactionBackendInterface.h" #include "WebIDBCallbacks.h" #include "WebIDBDatabaseCallbacks.h" #include "WebIDBObjectStoreImpl.h" #include "WebIDBTransactionImpl.h" using namespace WebCore; namespace WebKit { WebIDBDatabaseImpl::WebIDBDatabaseImpl(PassRefPtr<IDBDatabaseBackendInterface> databaseBackend) : m_databaseBackend(databaseBackend) { } WebIDBDatabaseImpl::~WebIDBDatabaseImpl() { } WebString WebIDBDatabaseImpl::name() const { return m_databaseBackend->name(); } WebString WebIDBDatabaseImpl::version() const { return m_databaseBackend->version(); } WebDOMStringList WebIDBDatabaseImpl::objectStoreNames() const { return m_databaseBackend->objectStoreNames(); } WebIDBObjectStore* WebIDBDatabaseImpl::createObjectStore(const WebString& name, const WebString& keyPath, bool autoIncrement, const WebIDBTransaction& transaction, WebExceptionCode& ec) { RefPtr<IDBObjectStoreBackendInterface> objectStore = m_databaseBackend->createObjectStore(name, keyPath, autoIncrement, transaction.getIDBTransactionBackendInterface(), ec); if (!objectStore) { ASSERT(ec); return 0; } return new WebIDBObjectStoreImpl(objectStore); } void WebIDBDatabaseImpl::deleteObjectStore(const WebString& name, const WebIDBTransaction& transaction, WebExceptionCode& ec) { m_databaseBackend->deleteObjectStore(name, transaction.getIDBTransactionBackendInterface(), ec); } void WebIDBDatabaseImpl::setVersion(const WebString& version, WebIDBCallbacks* callbacks, WebExceptionCode& ec) { m_databaseBackend->setVersion(version, IDBCallbacksProxy::create(adoptPtr(callbacks)), m_databaseCallbacks, ec); } WebIDBTransaction* WebIDBDatabaseImpl::transaction(const WebDOMStringList& names, unsigned short mode, WebExceptionCode& ec) { RefPtr<DOMStringList> nameList = PassRefPtr<DOMStringList>(names); RefPtr<IDBTransactionBackendInterface> transaction = m_databaseBackend->transaction(nameList.get(), mode, ec); if (!transaction) { ASSERT(ec); return 0; } return new WebIDBTransactionImpl(transaction); } void WebIDBDatabaseImpl::close() { // Use the callbacks that ::open gave us so that the backend in // multi-process chromium knows which database connection is closing. if (!m_databaseCallbacks) return; m_databaseBackend->close(m_databaseCallbacks); m_databaseCallbacks = 0; } void WebIDBDatabaseImpl::open(WebIDBDatabaseCallbacks* callbacks) { ASSERT(!m_databaseCallbacks); m_databaseCallbacks = IDBDatabaseCallbacksProxy::create(adoptPtr(callbacks)); m_databaseBackend->open(m_databaseCallbacks); } } // namespace WebKit #endif // ENABLE(INDEXED_DATABASE)
gpl-3.0
ConsenSys/eth-alerts
alerts/events/migrations/0002_auto_20170313_1305.py
518
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-13 13:05 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('events', '0001_initial'), ] operations = [ migrations.AlterField( model_name='alert', name='dapp', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.DApp'), ), ]
gpl-3.0
gaich/quickapps
app/src/main/java/com/yoavst/quickapps/toggles/fragments/SoundFragment.java
3354
package com.yoavst.quickapps.toggles.fragments; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.media.AudioManager; import android.provider.Settings; import com.yoavst.quickapps.R; import com.yoavst.quickapps.toggles.ToggleFragment; import com.yoavst.quickapps.toggles.TogglesActivity; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.SystemService; import org.androidannotations.annotations.res.StringRes; /** * Created by Yoav. */ @EFragment public class SoundFragment extends ToggleFragment { @StringRes(R.string.sound_sound) String SOUND; @StringRes(R.string.sound_silent) String SILENT; @StringRes(R.string.sound_vibrate) String VIBRATE; @SystemService AudioManager mAudioManager; BroadcastReceiver mRingerReceiver; Resources mSystemUiResources; // resources id of system ui stuff static int soundIcon = -1; static int vibrateIcon = -1; static int silentIcon = -1; @AfterViews void init() { mToggleTitle.setText(SOUND); mSystemUiResources = ((TogglesActivity)getActivity()).getSystemUiResource(); if (mRingerReceiver == null) { mRingerReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { setToggleData(); } }; } if (soundIcon == -1 || vibrateIcon == -1 || silentIcon == -1) { soundIcon = mSystemUiResources.getIdentifier("indi_noti_sound_on", "drawable", "com.android.systemui"); vibrateIcon = mSystemUiResources.getIdentifier("indi_noti_sound_vib_on", "drawable", "com.android.systemui"); silentIcon = mSystemUiResources.getIdentifier("indi_noti_silent_on", "drawable", "com.android.systemui"); } IntentFilter filter = new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION); getActivity().registerReceiver(mRingerReceiver, filter); } @Override public void onDestroy() { super.onDestroy(); try { getActivity().unregisterReceiver(mRingerReceiver); } catch (Exception ignored) { // Do nothing - receiver not registered } } public void setToggleData() { switch (mAudioManager.getRingerMode()) { case AudioManager.RINGER_MODE_NORMAL: mToggleIcon.setImageDrawable(mSystemUiResources.getDrawable(soundIcon)); mToggleText.setText(SOUND); break; case AudioManager.RINGER_MODE_VIBRATE: mToggleIcon.setImageDrawable(mSystemUiResources.getDrawable(vibrateIcon)); mToggleText.setText(VIBRATE); break; case AudioManager.RINGER_MODE_SILENT: mToggleIcon.setImageDrawable(mSystemUiResources.getDrawable(silentIcon)); mToggleText.setText(SILENT); break; } } @Override public void onToggleButtonClicked() { switch (mAudioManager.getRingerMode()) { case AudioManager.RINGER_MODE_NORMAL: mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); break; case AudioManager.RINGER_MODE_VIBRATE: mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); break; case AudioManager.RINGER_MODE_SILENT: mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); break; } } @Override public Intent getIntentForLaunch() { return new Intent(Settings.ACTION_SOUND_SETTINGS); } }
gpl-3.0
IntellectualCrafters/PlotSquared
Core/src/main/java/com/plotsquared/core/plot/flag/types/BooleanFlag.java
3532
/* * _____ _ _ _____ _ * | __ \| | | | / ____| | | * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| * | | * |_| * PlotSquared plot management system for Minecraft * Copyright (C) 2021 IntellectualSites * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.plotsquared.core.plot.flag.types; import com.plotsquared.core.configuration.caption.Caption; import com.plotsquared.core.configuration.caption.TranslatableCaption; import com.plotsquared.core.plot.flag.FlagParseException; import com.plotsquared.core.plot.flag.PlotFlag; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.Arrays; import java.util.Collection; import java.util.Locale; public abstract class BooleanFlag<F extends PlotFlag<Boolean, F>> extends PlotFlag<Boolean, F> { private static final Collection<String> positiveValues = Arrays.asList("1", "yes", "allow", "true"); private static final Collection<String> negativeValues = Arrays.asList("0", "no", "deny", "disallow", "false"); /** * Construct a new flag instance. * * @param value Flag value * @param description Flag description */ protected BooleanFlag(final boolean value, final Caption description) { super(value, TranslatableCaption.miniMessage("flags.flag_category_boolean"), description); } /** * Construct a new boolean flag, with * {@code false} as the default value. * * @param description Flag description */ protected BooleanFlag(final Caption description) { this(false, description); } @Override public F parse(@NonNull String input) throws FlagParseException { if (positiveValues.contains(input.toLowerCase(Locale.ENGLISH))) { return this.flagOf(true); } else if (negativeValues.contains(input.toLowerCase(Locale.ENGLISH))) { return this.flagOf(false); } else { throw new FlagParseException(this, input, TranslatableCaption.miniMessage("flags.flag_error_boolean")); } } @Override public F merge(@NonNull Boolean newValue) { return this.flagOf(getValue() || newValue); } @Override public String getExample() { return "true"; } @Override public String toString() { return this.getValue().toString(); } @Override public Collection<String> getTabCompletions() { return Arrays.asList("true", "false"); } }
gpl-3.0
t08094a/ffManagementSuite
src/main/java/de/leif/ffmanagementsuite/domain/Berichtselement.java
4163
package de.leif.ffmanagementsuite.domain; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.time.Instant; import java.util.Objects; import de.leif.ffmanagementsuite.domain.enumeration.Berichtskategorie; /** * A Berichtselement. */ @Entity @Table(name = "berichtselement") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Berichtselement implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Column(name = "beginn", nullable = false) private Instant beginn; @NotNull @Column(name = "ende", nullable = false) private Instant ende; @NotNull @Column(name = "titel", nullable = false) private String titel; @NotNull @Column(name = "beschreibung", nullable = false) private String beschreibung; @NotNull @Min(value = 0) @Column(name = "stunden", nullable = false) private Integer stunden; @Enumerated(EnumType.STRING) @Column(name = "kategorie") private Berichtskategorie kategorie; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Instant getBeginn() { return beginn; } public Berichtselement beginn(Instant beginn) { this.beginn = beginn; return this; } public void setBeginn(Instant beginn) { this.beginn = beginn; } public Instant getEnde() { return ende; } public Berichtselement ende(Instant ende) { this.ende = ende; return this; } public void setEnde(Instant ende) { this.ende = ende; } public String getTitel() { return titel; } public Berichtselement titel(String titel) { this.titel = titel; return this; } public void setTitel(String titel) { this.titel = titel; } public String getBeschreibung() { return beschreibung; } public Berichtselement beschreibung(String beschreibung) { this.beschreibung = beschreibung; return this; } public void setBeschreibung(String beschreibung) { this.beschreibung = beschreibung; } public Integer getStunden() { return stunden; } public Berichtselement stunden(Integer stunden) { this.stunden = stunden; return this; } public void setStunden(Integer stunden) { this.stunden = stunden; } public Berichtskategorie getKategorie() { return kategorie; } public Berichtselement kategorie(Berichtskategorie kategorie) { this.kategorie = kategorie; return this; } public void setKategorie(Berichtskategorie kategorie) { this.kategorie = kategorie; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Berichtselement berichtselement = (Berichtselement) o; if (berichtselement.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), berichtselement.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Berichtselement{" + "id=" + getId() + ", beginn='" + getBeginn() + "'" + ", ende='" + getEnde() + "'" + ", titel='" + getTitel() + "'" + ", beschreibung='" + getBeschreibung() + "'" + ", stunden='" + getStunden() + "'" + ", kategorie='" + getKategorie() + "'" + "}"; } }
gpl-3.0
martinmladenov/SoftUni-Solutions
Programming Basics/Exercises/2. Simple Calculations/09. Celsius to Fahrenheit.cs
300
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp2 { class Program { static void Main(string[] args) { Console.WriteLine(double.Parse(Console.ReadLine())*1.8+32); } } }
gpl-3.0
ManjaroLinux/captcha-registration
files/lang/French/mod_captcha_registration.php
480
<?php // Language string for mod Captcha Registration $lang_mod_captcha_registration = array( 'Captcha title' => 'Code de vérification', 'Captcha info' => 'Pour éviter les inscriptions automatiques, vous devez entrer un code de vérification. Si vous ne pouvez pas lire l\'image cliquez %sici%s pour rafraichir.', 'Captcha question' => 'Code de vérification', 'Captcha fail' => 'Le code de vérification que vous avez entré est incorrect!', ); ?>
gpl-3.0
esmail/odk_to_spss_syntax
doc/source/conf.py
8602
# -*- coding: utf-8 -*- # # odk_to_spss_syntax documentation build configuration file, created by # sphinx-quickstart on Sat Jun 14 23:52:46 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'odk_to_spss_syntax' copyright = u'2014, Esmail Fadae' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. from odk_to_spss_syntax import __version__ version = __version__ # The full version, including alpha/beta/rc tags. release = __version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['.static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'odk_to_spss_syntaxdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'odk_to_spss_syntax.tex', u'odk\\_to\\_spss\\_syntax Documentation', u'Esmail Fadae', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'odk_to_spss_syntax', u'odk_to_spss_syntax Documentation', [u'Esmail Fadae'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'odk_to_spss_syntax', u'odk_to_spss_syntax Documentation', u'Esmail Fadae', 'odk_to_spss_syntax', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None}
gpl-3.0
gpospelov/BornAgain
GUI/coregui/Views/FitWidgets/FitParameterWidget.cpp
16051
// ************************************************************************************************ // // BornAgain: simulate and fit reflection and scattering // //! @file GUI/coregui/Views/FitWidgets/FitParameterWidget.cpp //! @brief Implements class FitParameterWidget //! //! @homepage http://www.bornagainproject.org //! @license GNU General Public License v3 or higher (see COPYING) //! @copyright Forschungszentrum Jülich GmbH 2018 //! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS) // // ************************************************************************************************ #include "GUI/coregui/Views/FitWidgets/FitParameterWidget.h" #include "GUI/coregui/Models/FilterPropertyProxy.h" #include "GUI/coregui/Models/FitParameterHelper.h" #include "GUI/coregui/Models/FitParameterItems.h" #include "GUI/coregui/Models/FitParameterProxyModel.h" #include "GUI/coregui/Models/FitSuiteItem.h" #include "GUI/coregui/Models/JobItem.h" #include "GUI/coregui/Models/JobModel.h" #include "GUI/coregui/Models/ParameterTreeItems.h" #include "GUI/coregui/Models/SessionModelDelegate.h" #include "GUI/coregui/Views/InfoWidgets/OverlayLabelController.h" #include "GUI/coregui/Views/JobWidgets/ParameterTuningWidget.h" #include "GUI/coregui/mainwindow/mainwindow_constants.h" #include "GUI/coregui/utils/CustomEventFilters.h" #include <QAction> #include <QMenu> #include <QTreeView> #include <QVBoxLayout> FitParameterWidget::FitParameterWidget(QWidget* parent) : SessionItemWidget(parent) , m_treeView(new QTreeView) , m_tuningWidget(0) , m_createFitParAction(0) , m_removeFromFitParAction(0) , m_removeFitParAction(0) , m_fitParameterModel(0) , m_delegate(new SessionModelDelegate(this)) , m_keyboardFilter(new DeleteEventFilter(this)) , m_infoLabel(new OverlayLabelController(this)) { QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(m_treeView); layout->setMargin(0); layout->setSpacing(0); setLayout(layout); init_actions(); m_treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_treeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_treeView->setContextMenuPolicy(Qt::CustomContextMenu); m_treeView->setItemDelegate(m_delegate); m_treeView->setDragEnabled(true); m_treeView->setDragDropMode(QAbstractItemView::DragDrop); m_treeView->installEventFilter(m_keyboardFilter); m_treeView->setAlternatingRowColors(true); m_treeView->setStyleSheet("alternate-background-color: #EFF0F1;"); connect(m_treeView, &QTreeView::customContextMenuRequested, this, &FitParameterWidget::onFitParameterTreeContextMenu); m_infoLabel->setArea(m_treeView); m_infoLabel->setText("Drop parameter(s) to fit here"); } //! Sets ParameterTuningWidget to be able to provide it with context menu and steer //! it behaviour in the course of fit settings or fit runnig void FitParameterWidget::setParameterTuningWidget(ParameterTuningWidget* tuningWidget) { if (tuningWidget == m_tuningWidget) { return; } else { if (m_tuningWidget) disconnect(m_tuningWidget, &ParameterTuningWidget::itemContextMenuRequest, this, &FitParameterWidget::onTuningWidgetContextMenu); m_tuningWidget = tuningWidget; if (!m_tuningWidget) return; connect(m_tuningWidget, &ParameterTuningWidget::itemContextMenuRequest, this, &FitParameterWidget::onTuningWidgetContextMenu, Qt::UniqueConnection); connect(m_tuningWidget, &QObject::destroyed, [this] { m_tuningWidget = nullptr; }); } } // QSize FitParameterWidget::sizeHint() const //{ // return QSize(Constants::REALTIME_WIDGET_WIDTH_HINT, Constants::FIT_PARAMETER_WIDGET_HEIGHT); //} // QSize FitParameterWidget::minimumSizeHint() const //{ // return QSize(25, 25); //} //! Creates context menu for ParameterTuningWidget void FitParameterWidget::onTuningWidgetContextMenu(const QPoint& point) { QMenu menu; initTuningWidgetContextMenu(menu); menu.exec(point); setActionsEnabled(true); } //! Creates context menu for the tree with fit parameters void FitParameterWidget::onFitParameterTreeContextMenu(const QPoint& point) { QMenu menu; initFitParameterTreeContextMenu(menu); menu.exec(m_treeView->mapToGlobal(point + QPoint(2, 22))); setActionsEnabled(true); } void FitParameterWidget::onTuningWidgetSelectionChanged(const QItemSelection& selection) { Q_UNUSED(selection); } //! Propagates selection form the tree with fit parameters to the tuning widget void FitParameterWidget::onFitParametersSelectionChanged(const QItemSelection& selection) { if (selection.indexes().isEmpty()) return; for (auto index : selection.indexes()) { m_tuningWidget->selectionModel()->clearSelection(); SessionItem* item = m_fitParameterModel->itemForIndex(index); if (item->parent()->modelType() == "FitParameterLink") { QString link = item->parent()->getItemValue(FitParameterLinkItem::P_LINK).toString(); m_tuningWidget->makeSelected( FitParameterHelper::getParameterItem(jobItem()->fitParameterContainerItem(), link)); } } } //! Creates fit parameters for all selected ParameterItem's in tuning widget void FitParameterWidget::onCreateFitParAction() { for (auto item : m_tuningWidget->getSelectedParameters()) { if (!FitParameterHelper::getFitParameterItem(jobItem()->fitParameterContainerItem(), item)) { FitParameterHelper::createFitParameter(jobItem()->fitParameterContainerItem(), item); } } } //! All ParameterItem's selected in tuning widget will be removed from link section of //! corresponding fitParameterItem. void FitParameterWidget::onRemoveFromFitParAction() { for (auto item : m_tuningWidget->getSelectedParameters()) { if (FitParameterHelper::getFitParameterItem(jobItem()->fitParameterContainerItem(), item)) { FitParameterHelper::removeFromFitParameters(jobItem()->fitParameterContainerItem(), item); } } } //! All selected FitParameterItem's of FitParameterItemLink's will be removed void FitParameterWidget::onRemoveFitParAction() { FitParameterContainerItem* container = jobItem()->fitParameterContainerItem(); // retrieve both, selected FitParameterItem and FitParameterItemLink QVector<FitParameterLinkItem*> linksToRemove = selectedFitParameterLinks(); for (auto item : linksToRemove) { container->model()->removeRow(item->index().row(), item->index().parent()); } QVector<FitParameterItem*> itemsToRemove = selectedFitParameters(); // By uncommenting line below, removing link from fit parameter will lead to fit parameter // removal too (if it doesn't have other links) // QVector<FitParameterItem *> itemsToRemove = selectedFitParameters()+emptyFitParameters(); for (auto item : itemsToRemove) { container->model()->removeRow(item->index().row(), item->index().parent()); } } //! Add all selected parameters to fitParameter with given index void FitParameterWidget::onAddToFitParAction(int ipar) { QStringList fitParNames = FitParameterHelper::getFitParameterNames(jobItem()->fitParameterContainerItem()); for (auto item : m_tuningWidget->getSelectedParameters()) { FitParameterHelper::addToFitParameter(jobItem()->fitParameterContainerItem(), item, fitParNames.at(ipar)); } } void FitParameterWidget::onFitParameterModelChange() { spanParameters(); updateInfoLabel(); } //! Context menu reimplemented to suppress the default one void FitParameterWidget::contextMenuEvent(QContextMenuEvent* event) { Q_UNUSED(event); } void FitParameterWidget::subscribeToItem() { init_fit_model(); } void FitParameterWidget::init_actions() { m_createFitParAction = new QAction("Create fit parameter", this); connect(m_createFitParAction, &QAction::triggered, this, &FitParameterWidget::onCreateFitParAction); m_removeFromFitParAction = new QAction("Remove from fit parameters", this); connect(m_removeFromFitParAction, &QAction::triggered, this, &FitParameterWidget::onRemoveFromFitParAction); m_removeFitParAction = new QAction("Remove fit parameter", this); connect(m_removeFitParAction, &QAction::triggered, this, &FitParameterWidget::onRemoveFitParAction); connect(m_keyboardFilter, &DeleteEventFilter::removeItem, this, &FitParameterWidget::onRemoveFitParAction); } //! Fills context menu for ParameterTuningWidget with content. void FitParameterWidget::initTuningWidgetContextMenu(QMenu& menu) { if (jobItem()->getStatus() == "Fitting") { setActionsEnabled(false); return; } m_removeFromFitParAction->setEnabled(canRemoveFromFitParameters()); m_createFitParAction->setEnabled(canCreateFitParameter()); menu.addAction(m_createFitParAction); QMenu* addToFitParMenu = menu.addMenu("Add to existing fit parameter"); addToFitParMenu->setEnabled(true); const bool allow_one_fit_parameter_to_have_more_than_one_link = true; if (allow_one_fit_parameter_to_have_more_than_one_link) { QStringList fitParNames = FitParameterHelper::getFitParameterNames(jobItem()->fitParameterContainerItem()); if (fitParNames.isEmpty() || canCreateFitParameter() == false) { addToFitParMenu->setEnabled(false); } for (int i = 0; i < fitParNames.count(); ++i) { QAction* action = new QAction(QString("to ").append(fitParNames.at(i)), addToFitParMenu); connect(action, &QAction::triggered, [=] { onAddToFitParAction(i); }); addToFitParMenu->addAction(action); } } menu.addSeparator(); menu.addAction(m_removeFromFitParAction); } //! Fills context menu for FitParameterTree with content. void FitParameterWidget::initFitParameterTreeContextMenu(QMenu& menu) { if (jobItem()->getStatus() == "Fitting") { setActionsEnabled(false); return; } menu.addAction(m_removeFitParAction); } //! Initializes FitParameterModel and its tree. void FitParameterWidget::init_fit_model() { m_treeView->setModel(0); delete m_fitParameterModel; m_fitParameterModel = new FitParameterProxyModel( jobItem()->fitParameterContainerItem(), jobItem()->fitParameterContainerItem()->model()); m_treeView->setModel(m_fitParameterModel); connect(m_fitParameterModel, &FitParameterProxyModel::dataChanged, this, &FitParameterWidget::onFitParameterModelChange); connect(m_fitParameterModel, &FitParameterProxyModel::modelReset, this, &FitParameterWidget::onFitParameterModelChange); onFitParameterModelChange(); connectFitParametersSelection(true); } //! Returns true if tuning widget contains selected ParameterItem's which can be used to create //! a fit parameter (i.e. it is not linked with some fit parameter already). bool FitParameterWidget::canCreateFitParameter() { QVector<ParameterItem*> selected = m_tuningWidget->getSelectedParameters(); for (auto item : selected) { if (FitParameterHelper::getFitParameterItem(jobItem()->fitParameterContainerItem(), item) == nullptr) return true; } return false; } //! Returns true if tuning widget contains selected ParameterItem's which can be removed from //! fit parameters. bool FitParameterWidget::canRemoveFromFitParameters() { QVector<ParameterItem*> selected = m_tuningWidget->getSelectedParameters(); for (auto item : selected) { if (FitParameterHelper::getFitParameterItem(jobItem()->fitParameterContainerItem(), item)) return true; } return false; } //! Enables/disables all context menu actions. void FitParameterWidget::setActionsEnabled(bool value) { m_createFitParAction->setEnabled(value); m_removeFromFitParAction->setEnabled(value); m_removeFitParAction->setEnabled(value); } //! Returns list of FitParameterItem's currently selected in FitParameterItem tree QVector<FitParameterItem*> FitParameterWidget::selectedFitParameters() { QVector<FitParameterItem*> result; QModelIndexList indexes = m_treeView->selectionModel()->selectedIndexes(); for (auto index : indexes) { if (SessionItem* item = m_fitParameterModel->itemForIndex(index)) { if (item->modelType() == "FitParameter") { FitParameterItem* fitParItem = dynamic_cast<FitParameterItem*>(item); ASSERT(fitParItem); result.push_back(fitParItem); } } } return result; } //! Returns list of FitParameterItem's which doesn't have any links attached. QVector<FitParameterItem*> FitParameterWidget::emptyFitParameters() { QVector<FitParameterItem*> result; for (auto fitParItem : jobItem()->fitParameterContainerItem()->fitParameterItems()) if (fitParItem->getItems(FitParameterItem::T_LINK).empty()) result.push_back(fitParItem); return result; } //! Returns links of FitParameterLink's item selected in FitParameterItem tree QVector<FitParameterLinkItem*> FitParameterWidget::selectedFitParameterLinks() { QVector<FitParameterLinkItem*> result; QModelIndexList indexes = m_treeView->selectionModel()->selectedIndexes(); for (QModelIndex index : indexes) { if (SessionItem* item = m_fitParameterModel->itemForIndex(index)) { if (item->parent()->modelType() == "FitParameterLink") { FitParameterLinkItem* fitParItem = dynamic_cast<FitParameterLinkItem*>(item->parent()); ASSERT(fitParItem); result.push_back(fitParItem); } } } return result; } //! Makes first column in FitParameterItem's tree related to ParameterItem link occupy whole space. void FitParameterWidget::spanParameters() { m_treeView->expandAll(); for (int i = 0; i < m_fitParameterModel->rowCount(QModelIndex()); i++) { QModelIndex parameter = m_fitParameterModel->index(i, 0, QModelIndex()); if (!parameter.isValid()) break; int childRowCount = m_fitParameterModel->rowCount(parameter); if (childRowCount > 0) { for (int j = 0; j < childRowCount; j++) { m_treeView->setFirstColumnSpanned(j, parameter, true); } } } } //! Places overlay label on top of tree view, if there is no fit parameters void FitParameterWidget::updateInfoLabel() { if (!jobItem()) return; bool is_to_show_label = jobItem()->fitParameterContainerItem()->isEmpty(); m_infoLabel->setShown(is_to_show_label); } void FitParameterWidget::connectTuningWidgetSelection(bool active) { ASSERT(m_tuningWidget); if (active) { connect(m_tuningWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &FitParameterWidget::onTuningWidgetSelectionChanged, Qt::UniqueConnection); } else { disconnect(m_tuningWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &FitParameterWidget::onTuningWidgetSelectionChanged); } } void FitParameterWidget::connectFitParametersSelection(bool active) { if (active) { connect(m_treeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &FitParameterWidget::onFitParametersSelectionChanged, Qt::UniqueConnection); } else { disconnect(m_treeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &FitParameterWidget::onFitParametersSelectionChanged); } } JobItem* FitParameterWidget::jobItem() { return dynamic_cast<JobItem*>(currentItem()); }
gpl-3.0
MichaelCoughlinAN/Odds-N-Ends
Python/multicast_listener.py
584
#!/usr/bin/env python import socket import struct MCAST_GRP = '230.0.0.0' MCAST_PORT = 4446 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', MCAST_PORT)) # use MCAST_GRP instead of '' to listen only # to MCAST_GRP, not all groups on MCAST_PORT mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) print 'running' while True: print 'hello' + sock.recv(10240)
gpl-3.0
dadadel/pyment
example.py
2264
def func1(param1: str, param2='default val'): '''Description of func with docstring javadoc style. @param param1: descr of param @type param1: type @return: some value @raise KeyError: raises a key exception ''' pass def func2(param1, param2='default val2') -> list: '''Description of func with docstring reST style. :param param1: descr of param :type param1: type :returns: some value :raises keyError: raises exception ''' pass def func3(param1, param2='default val'): '''Description of func with docstring groups style. Params: param1 - descr of param Returns: some value Raises: keyError: raises key exception TypeError: raises type exception ''' pass class SomeClass(object): '''My class. ''' def method(self, prm): '''description''' pass def method2(self, prm1, prm2='defaultprm'): pass def method_numpy(self): """ My numpydoc description of a kind of very exhautive numpydoc format docstring. Parameters ---------- first : array_like the 1st param name `first` second : the 2nd param third : {'value', 'other'}, optional the 3rd param, by default 'value' Returns ------- string a value in a string Raises ------ KeyError when a key error OtherError when an other error See Also -------- a_func : linked (optional), with things to say on several lines some blabla Note ---- Some informations. Some maths also: .. math:: f(x) = e^{- x} References ---------- Biblio with cited ref [1]_. The ref can be cited in Note section. .. [1] Adel Daouzli, Sylvain Saïghi, Michelle Rudolph, Alain Destexhe, Sylvie Renaud: Convergence in an Adaptive Neural Network: The Influence of Noise Inputs Correlation. IWANN (1) 2009: 140-148 Examples -------- This is example of use >>> print "a" a """ pass
gpl-3.0
marvertin/geokuk
src/main/java/cz/geokuk/plugins/mapy/kachle/podklady/Priority.java
138
package cz.geokuk.plugins.mapy.kachle.podklady; public enum Priority { // čím výše, tím vyšší priorita KACHLE, STAHOVANI, }
gpl-3.0
alblancoc/memetic_open_shop
src/operadoresGeneticos.py
8213
''' En esta clase se definen los operadores geneticos que se usaran en el algoritmo genetico. Se define un operador para el cruce y otro para la mutacion. Created on Apr 26, 2016 @author: Angie Blanco ''' import random import copy class OperadoresGeneticos(object): ''' Constructor de la clase ''' def __init__(self): ''' Este constructor no hace nada mas ''' ''' Este metodo representa la dinamica del operador de mutacion "SwapMutation". Se reciben los padres y se generan los cromosomas de los hijos. @param padre1: Cromosoma del primer padre @param padre2: Cromosoma del segundo padre @return: cromosomas de los dos hijos resultantes ''' def swapMutation(self, padre1, padre2): hijos = [] #vector donde se almacenan los hijos #Se colocan los cromosomas de los padres en los hijos hijos.append(padre1) hijos.append(padre2) #Se generan los puntos de intercambio de forma aleatoria primerPunto = random.randint(0, len(padre1) - 1) segundoPunto = random.randint(0, len(padre1) - 1) #Se verifica que los dos puntos de intercambio no sean los mismos while(primerPunto == segundoPunto): segundoPunto = random.randint(0, len(padre1) - 1) #Se cambian las tareas en el cromosoma del primer hijo (posicion 0) valorTemporal = hijos[0][primerPunto] hijos[0][primerPunto] = hijos[0][segundoPunto] hijos[0][segundoPunto] = valorTemporal #Se cambian las tareas en el cromosoma del segundo hijo (posicion 1) valorTemporal = hijos[1][primerPunto] hijos[1][primerPunto] = hijos[1][segundoPunto] hijos[1][segundoPunto] = valorTemporal return hijos #se retornan los cromosomas obtenidos de los hijos ''' Este metodo representa la dinamica del operador de cruce "2-edge". Se reciben los padres y se generan los cromosomas de los hijos. @param padre1: Cromosoma del primer padre @param padre2: Cromosoma del segundo padre @return: cromosomas de los dos hijos resultantes ''' def edge2Crossover(self, padre1, padre2): tamano = len( padre1 ) hijos = [] tabla = [] #se inicializa la tabla que va a almacenas las adyacencias for i in range(tamano): tabla.append( [] ) #Se agregan a la tabla las tareas adyacentes de acuerdo a la permutacion del padre 1 for i in range(tamano): tabla[ padre1[i] - 1].append( padre1[(i + 1) % tamano] ) tabla[ padre1[i] - 1].append( padre1[(i - 1 + tamano) % tamano] ) #se toma el cromosoma del padre 2, y se compran las adjacencias con la tabla obtenida del padre 1 for i in range(tamano): temporal = padre2[ (i + 1) % tamano ] #se mira la tarea adyacente hacia adelante del indice i encontrado = False for j in range( len( tabla[padre2[i] - 1]) ): if tabla[ padre2[i] - 1][j] == temporal: #si hay una adyacencia en comun, se marca como negativa encontrado = True cambio = tabla[padre2[i] - 1][j] * (-1) primero = tabla[padre2[i] - 1][0] tabla[ padre2[i] - 1 ][j] = primero tabla[ padre2[i] - 1 ][0] = cambio if not encontrado: #si no esta la adyacencia en comun, se agrega la tarea a la tabla de adyacencias tabla[ padre2[i] - 1 ].append(temporal) temporal = padre2[ (i - 1 + tamano) % tamano ] #se mira la tarea adyacente hacia atras del indice i encontrado = False #inicialmente se asume que no existe una adyacencia, y cuando se encuentra se desencadenan las reglas de marcacion logica for j in range( len( tabla[padre2[i] - 1] )): if tabla[ padre2[i] - 1][j] == temporal: #si hay una adyacencia en comun, se marca como negativa encontrado = True cambio = tabla[padre2[i] - 1][j] * (-1) primero = tabla[padre2[i] - 1][0] #se reorganizan las tareas, de tal manera que las negativas pasen a la primera posicion tabla[ padre2[i] - 1 ][j] = primero tabla[ padre2[i] - 1 ][0] = cambio if not encontrado: #si no esta la adyacencia en comun, se agrega la tarea a la tabla de adyacencias tabla[ padre2[i] - 1 ].append(temporal) tabla_ = copy.deepcopy( tabla ) #Se hace una copia de la tabla para procesar el hijo 2 hijos.append( self.crossHijo(tabla, tamano) ) #a partir de la tabla de adyacencias se crea el hijo 1 hijos.append( self.crossHijo(tabla_, tamano) ) #a partir de la tabla de adyacencias se crea el hijo 2 return hijos #se retornan los hijos obtenidos ''' Este metodo es un auxiliar para el operador de cruce 2-edge. En este caso, se recibe la tabla de adyacencias y se crea el cromosoma del hijo. @param tabla: tabla de adyacencias @param tamano: cantidad de tareas en la permutacion @return: cromosoma del nuevo hijo ''' def crossHijo(self, tabla, tamano): hijo = [None] * tamano #se crea el vector donde se almacena el orden de tareas del hijo tarea = random.randint(1, len(tabla) ) #Seleccion aleatoria de la primera tarea hijo[0] = tarea #se asigna la primera tarea indice = 1 #Define la cantidad de tareas agregadas al hijo #Mientras no se hayan agregado toras las tareas while indice < len(tabla): invalido = True #por defecto se considera invalido, ya que se busca encontrar el caso donde no lo sea while (invalido): if len( tabla[tarea - 1] ) > 0: #Se revisa si quedan adjacencias if tabla[tarea - 1][0] < 0: #Si la primera tarea es negativa, se asigna automaticamente enTabla = 0 #al ser negativa, la posicion en la que se encuentra s la inicial else: enTabla = random.randint(0, len( tabla[tarea - 1] ) - 1) #se escoge aleatoriamente de alguna de las tareas en el arreglo nuevaTarea = tabla[tarea - 1][enTabla] #Define cual es la siguiente tarea a procesar tabla[tarea - 1].remove( nuevaTarea ) #Se remueve la tarea asignada de la lista nuevaTarea = abs( nuevaTarea ) #En caso de que sea negativa, se debe colocar en un rango valido else: nuevaTarea = random.randint(1, len(tabla)) #Si la tarea ya no tiene mas adyacencias, se busca aleatoriamente una nueva tarea for i in range(indice): #Verifica si la tarea ya existe en el arreglo if nuevaTarea == hijo[i]: #Si ya existe, hay que repetir el proceso invalido = True break else: invalido = False #no es necesario repetir el proceso tarea = nuevaTarea #La tarea seleccionada en la tabla ahora sera la tarea en la cual se busque la adyacencia hijo[indice] = tarea #Se agrega la tarea seleccionada al cromosoma del hijo indice += 1 #Se mueve en el cromosoma para asignar la siguiente tarea #una vez construido todo el hijo, se acaba el metodo y se retorna el cromosoma return hijo ''' operadores = OperadoresGeneticos() fat1 = [1,2,3,4,5,6,7,8,9] fat2 = [1,3,5,7,9,8,6,4,2] sons = operadores.swapMutation(fat1, fat2) print "Mutation 1" print sons[0] print sons[1] sons = operadores.swapMutation(fat1, fat2) print "Mutation 2" print sons[0] print sons[1] sons = operadores.edge2Crossover(sons[0], sons[1]) print "Cross 1" print sons[0] print sons[1] '''
gpl-3.0
Atizar/RapidCFD-dev
src/TurbulenceModels/turbulenceModels/RAS/derivedFvPatchFields/atmBoundaryLayerInletVelocity/atmBoundaryLayerInletVelocityFvPatchVectorField.C
7626
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "atmBoundaryLayerInletVelocityFvPatchVectorField.H" #include "addToRunTimeSelectionTable.H" #include "fvPatchFieldMapper.H" #include "volFields.H" #include "surfaceFields.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { struct atmBoundaryLayerInletVelocityUStarFunctor { const scalar kappa_; const scalar Uref_; const scalar Href_; atmBoundaryLayerInletVelocityUStarFunctor ( scalar kappa, scalar Uref, scalar Href ): kappa_(kappa), Uref_(Uref), Href_(Href) {} __HOST____DEVICE__ scalar operator()(const scalar& z0_) { return kappa_*Uref_/(log((Href_ + z0_)/max(z0_, 0.001))); } }; struct atmBoundaryLayerInletVelocityUnFunctor { const scalar kappa_; const scalar Uref_; const scalar Href_; atmBoundaryLayerInletVelocityUnFunctor ( scalar kappa, scalar Uref, scalar Href ): kappa_(kappa), Uref_(Uref), Href_(Href) {} __HOST____DEVICE__ scalar operator()(const scalar& z0_, const thrust::tuple<scalar,scalar,scalar>& t) { const scalar& coord = thrust::get<0>(t); const scalar& zGround_ = thrust::get<1>(t); const scalar& Ustar_ = thrust::get<2>(t); if ((coord - zGround_) < Href_) { return (Ustar_/kappa_) * log((coord - zGround_ + z0_)/max(z0_, 0.001)); } else { return Uref_; } } }; // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // atmBoundaryLayerInletVelocityFvPatchVectorField:: atmBoundaryLayerInletVelocityFvPatchVectorField ( const fvPatch& p, const DimensionedField<vector, volMesh>& iF ) : fixedValueFvPatchVectorField(p, iF), Ustar_(0), n_(pTraits<vector>::zero), z_(pTraits<vector>::zero), z0_(0), kappa_(0.41), Uref_(0), Href_(0), zGround_(0) {} atmBoundaryLayerInletVelocityFvPatchVectorField:: atmBoundaryLayerInletVelocityFvPatchVectorField ( const atmBoundaryLayerInletVelocityFvPatchVectorField& ptf, const fvPatch& p, const DimensionedField<vector, volMesh>& iF, const fvPatchFieldMapper& mapper ) : fixedValueFvPatchVectorField(ptf, p, iF, mapper), Ustar_(ptf.Ustar_, mapper), n_(ptf.n_), z_(ptf.z_), z0_(ptf.z0_, mapper), kappa_(ptf.kappa_), Uref_(ptf.Uref_), Href_(ptf.Href_), zGround_(ptf.zGround_, mapper) {} atmBoundaryLayerInletVelocityFvPatchVectorField:: atmBoundaryLayerInletVelocityFvPatchVectorField ( const fvPatch& p, const DimensionedField<vector, volMesh>& iF, const dictionary& dict ) : fixedValueFvPatchVectorField(p, iF), Ustar_(p.size()), n_(dict.lookup("n")), z_(dict.lookup("z")), z0_("z0", dict, p.size()), kappa_(dict.lookupOrDefault<scalar>("kappa", 0.41)), Uref_(readScalar(dict.lookup("Uref"))), Href_(readScalar(dict.lookup("Href"))), zGround_("zGround", dict, p.size()) { if (mag(n_) < SMALL || mag(z_) < SMALL) { FatalErrorIn ( "atmBoundaryLayerInletVelocityFvPatchVectorField" "(" "const fvPatch&, " "const DimensionedField<vector, volMesh>&, " "onst dictionary&" ")" ) << "magnitude of n or z must be greater than zero" << abort(FatalError); } n_ /= mag(n_); z_ /= mag(z_); thrust::transform ( z0_.begin(), z0_.end(), Ustar_.begin(), atmBoundaryLayerInletVelocityUStarFunctor ( kappa_, Uref_, Href_ ) ); const vectorgpuField& c = patch().Cf(); const scalargpuField coord(c & z_); scalargpuField Un(coord.size()); thrust::transform ( z0_.begin(), z0_.end(), thrust::make_zip_iterator(thrust::make_tuple ( coord.begin(), zGround_.begin(), Ustar_.begin() )), Un.begin(), atmBoundaryLayerInletVelocityUnFunctor ( kappa_, Uref_, Href_ ) ); vectorgpuField::operator=(n_*Un); } atmBoundaryLayerInletVelocityFvPatchVectorField:: atmBoundaryLayerInletVelocityFvPatchVectorField ( const atmBoundaryLayerInletVelocityFvPatchVectorField& blpvf, const DimensionedField<vector, volMesh>& iF ) : fixedValueFvPatchVectorField(blpvf, iF), Ustar_(blpvf.Ustar_), n_(blpvf.n_), z_(blpvf.z_), z0_(blpvf.z0_), kappa_(blpvf.kappa_), Uref_(blpvf.Uref_), Href_(blpvf.Href_), zGround_(blpvf.zGround_) {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // void atmBoundaryLayerInletVelocityFvPatchVectorField::autoMap ( const fvPatchFieldMapper& m ) { fixedValueFvPatchVectorField::autoMap(m); z0_.autoMap(m); zGround_.autoMap(m); Ustar_.autoMap(m); } void atmBoundaryLayerInletVelocityFvPatchVectorField::rmap ( const fvPatchVectorField& ptf, const labelgpuList& addr ) { fixedValueFvPatchVectorField::rmap(ptf, addr); const atmBoundaryLayerInletVelocityFvPatchVectorField& blptf = refCast<const atmBoundaryLayerInletVelocityFvPatchVectorField>(ptf); z0_.rmap(blptf.z0_, addr); zGround_.rmap(blptf.zGround_, addr); Ustar_.rmap(blptf.Ustar_, addr); } void atmBoundaryLayerInletVelocityFvPatchVectorField::write(Ostream& os) const { fvPatchVectorField::write(os); z0_.writeEntry("z0", os) ; os.writeKeyword("n") << n_ << token::END_STATEMENT << nl; os.writeKeyword("z") << z_ << token::END_STATEMENT << nl; os.writeKeyword("kappa") << kappa_ << token::END_STATEMENT << nl; os.writeKeyword("Uref") << Uref_ << token::END_STATEMENT << nl; os.writeKeyword("Href") << Href_ << token::END_STATEMENT << nl; zGround_.writeEntry("zGround", os) ; writeEntry("value", os); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // makePatchTypeField ( fvPatchVectorField, atmBoundaryLayerInletVelocityFvPatchVectorField ); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // ************************************************************************* //
gpl-3.0
drkameleon/MathMachine
src/mm_statement.cpp
3844
/* MathMachine Copyright (C) 2009-2011 Dr.Kameleon This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> *//* MM_STATEMENT.CPP */ #include "mathmachine.h" mm_statement::mm_statement(statement_type tp) { this->type = tp; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_exec* execst) { this->type = tp; this->body.exec = execst; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_use* usest) { this->type = tp; this->body.use = usest; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_ret* retst) { this->type = tp; this->body.ret = retst; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_set* setst) { this->type = tp; this->body.set = setst; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_let* letst) { this->type = tp; this->body.let = letst; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_get* getst) { this->type = tp; this->body.get = getst; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_loop* loopst) { this->type = tp; this->body.loop = loopst; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_if* ifst) { this->type = tp; this->body.ifs = ifst; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_put* putst) { this->type = tp; this->body.put = putst; this->myVariables = NULL; } mm_statement::mm_statement(statement_type tp, mm_st_save* savest) { this->type = tp; this->body.save = savest; this->myVariables = NULL; } mm_execution_result* mm_statement::execute(void) { if (this->type==put_statement) return this->body.put->execute(); else if (this->type==use_statement) return this->body.use->execute(); else if (this->type==exec_statement) return this->body.exec->execute(); else if (this->type==if_statement) return this->body.ifs->execute(); else if (this->type==loop_statement) return this->body.loop->execute(); else if (this->type==let_statement) return this->body.let->execute(); else if (this->type==get_statement) return this->body.get->execute(); else if (this->type==set_statement) return this->body.set->execute(); else if (this->type==ret_statement) return this->body.ret->execute(); else if (this->type==save_statement) return this->body.save->execute(); else return new mm_execution_result(execution_failure); } void mm_statement::setLocalVars(mm_variable_list* mvars) { if (this->type==put_statement) this->body.put->myVariables = mvars; else if (this->type==exec_statement) this->body.exec->myVariables = mvars; else if (this->type==if_statement) this->body.ifs->myVariables = mvars; else if (this->type==loop_statement) this->body.loop->myVariables = mvars; else if (this->type==let_statement) this->body.let->myVariables = mvars; else if (this->type==get_statement) this->body.get->myVariables = mvars; else if (this->type==set_statement) this->body.set->myVariables = mvars; else if (this->type==ret_statement) this->body.ret->myVariables = mvars; else if (this->type==save_statement) this->body.save->myVariables = mvars; this->myVariables = mvars; }
gpl-3.0
automatweb/automatweb_dev
addons/pear/SOAP/Transport/TCP.php
4770
<?php /** * This file contains the code for a TCP transport layer. * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 2.02 of the PHP license, * that is bundled with this package in the file LICENSE, and is available at * through the world-wide-web at http://www.php.net/license/2_02.txt. If you * did not receive a copy of the PHP license and are unable to obtain it * through the world-wide-web, please send a note to [email protected] so we can * mail you a copy immediately. * * @category Web Services * @package SOAP * @author Shane Hanna <iordy_at_iordy_dot_com> * @copyright 2003-2005 The PHP Group * @license http://www.php.net/license/2_02.txt PHP License 2.02 * @link http://pear.php.net/package/SOAP */ require_once PEAR_PATH.'SOAP/Base.php'; /** * TCP transport for SOAP. * * @todo use Net_Socket; implement some security scheme; implement support * for attachments * @access public * @package SOAP * @author Shane Hanna <iordy_at_iordy_dot_com> */ class SOAP_Transport_TCP extends SOAP_Base_Object { var $headers = array(); var $urlparts = null; var $url = ''; var $incoming_payload = ''; var $_userAgent = SOAP_LIBRARY_NAME; var $encoding = SOAP_DEFAULT_ENCODING; var $result_encoding = 'UTF-8'; var $result_content_type; /** * socket */ var $socket = null; /** * Constructor. * * @param string $url HTTP url to SOAP endpoint. * * @access public */ function SOAP_Transport_TCP($url, $encoding = SOAP_DEFAULT_ENCODING) { parent::SOAP_Base_Object('TCP'); $this->urlparts = @parse_url($url); $this->url = $url; $this->encoding = $encoding; } function _socket_ping() { // XXX how do we restart after socket_shutdown? //if (!$this->socket) { // Create socket resource. $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->socket < 0) { return 0; } // Connect. $result = socket_connect($this->socket, $this->urlparts['host'], $this->urlparts['port']); if ($result < 0) { return 0; } //} return 1; } /** * Sends and receives SOAP data. * * @param string $msg Outgoing POST data. * @param string $action SOAP Action header data. * * @return string|SOAP_Fault * @access public */ function send($msg, $options = NULL) { $this->incoming_payload = ''; $this->outgoing_payload = $msg; if (!$this->_validateUrl()) { return $this->fault; } // Check for TCP scheme. if (strcasecmp($this->urlparts['scheme'], 'TCP') == 0) { // Check connection. if (!$this->_socket_ping()) { return $this->_raiseSoapFault('Error connecting to ' . $this->url . '; reason: ' . socket_strerror(socket_last_error($this->socket))); } // Write to the socket. if (!@socket_write($this->socket, $this->outgoing_payload, strlen($this->outgoing_payload))) { return $this->_raiseSoapFault('Error sending data to ' . $this->url . '; reason: ' . socket_strerror(socket_last_error($this->socket))); } // Shutdown writing. if(!socket_shutdown($this->socket, 1)) { return $this->_raiseSoapFault('Cannot change socket mode to read.'); } // Read everything we can. while ($buf = @socket_read($this->socket, 1024, PHP_BINARY_READ)) { $this->incoming_payload .= $buf; } // Return payload or die. if ($this->incoming_payload) { return $this->incoming_payload; } return $this->_raiseSoapFault('Error reveiving data from ' . $this->url); } return $this->_raiseSoapFault('Invalid url scheme ' . $this->url); } /** * Validates the url data passed to the constructor. * * @return boolean * @access private */ function _validateUrl() { if (!is_array($this->urlparts) ) { $this->_raiseSoapFault("Unable to parse URL $url"); return false; } if (!isset($this->urlparts['host'])) { $this->_raiseSoapFault("No host in URL $url"); return false; } if (!isset($this->urlparts['path']) || !$this->urlparts['path']) { $this->urlparts['path'] = '/'; } return true; } }
gpl-3.0
zyxist/opentrans
opentrans-visitons/src/main/java/org/invenzzia/opentrans/visitons/render/painters/CurvedTrackPainter.java
3550
/* * Copyright (C) 2013 Invenzzia Group <http://www.invenzzia.org/> * * 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 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 org.invenzzia.opentrans.visitons.render.painters; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Arc2D; import org.invenzzia.opentrans.visitons.geometry.ArcOps; import org.invenzzia.opentrans.visitons.geometry.Geometry; import org.invenzzia.opentrans.visitons.geometry.LineOps; import org.invenzzia.opentrans.visitons.render.CameraModelSnapshot; import org.invenzzia.opentrans.visitons.render.scene.MouseSnapshot; /** * Draws a curved track. * * @author Tomasz Jędrzejewski */ public class CurvedTrackPainter implements ITrackPainter { /** * ID of the painted track: for the mouse hovering. */ private final long id; /** * Data coordinates. */ private double coordinates[]; /** * Committed track metadata are represented in relative values to the segment boundaries * in order to survive world size change. The delta is passed separately then. */ private final double dx, dy; /** * Precomputed arc object. */ private Arc2D.Double arc; public CurvedTrackPainter(long id, double metadata[], double dx, double dy) { this.id = id; this.coordinates = metadata; this.dx = dx; this.dy = dy; } public CurvedTrackPainter(long id, double metadata[]) { this.id = id; this.coordinates = metadata; this.dx = 0.0; this.dy = 0.0; } @Override public long getId() { return this.id; } @Override public void draw(CameraModelSnapshot camera, Graphics2D graphics, boolean editable) { if(null != this.arc) { graphics.draw(this.arc); } } @Override public void refreshData(CameraModelSnapshot camera) { double wh = (double) camera.world2pix(this.coordinates[2]); this.arc = new Arc2D.Double( (double) camera.world2pixX(this.coordinates[0] + this.dx), (double) camera.world2pixY(this.coordinates[1] + this.dy), wh, wh, Math.toDegrees(this.coordinates[4]), Math.toDegrees(this.coordinates[5]), Arc2D.OPEN ); } @Override public boolean hits(Graphics2D graphics, Rectangle rect) { if(null != rect && null != this.arc) { return graphics.hit(rect, this.arc, true); } return false; } @Override public double computePosition(MouseSnapshot snapshot, CameraModelSnapshot camera) { double px = camera.pix2worldX(snapshot.x()); double py = camera.pix2worldY(snapshot.y()); double cx = this.coordinates[6] + this.dx; double cy = this.coordinates[7] + this.dy; double t = ArcOps.coord2Param(cx, cy, this.coordinates[8] + this.dx, this.coordinates[9] + this.dy, this.coordinates[3], px, py ); t = (t / this.coordinates[5]); if(t < 0.0) { return 0.0; } else if(t > 1.0) { return 1.0; } return t; } public double[] _gm() { return this.coordinates; } public double _gx() { return this.dx; } public double _gy() { return this.dy; } }
gpl-3.0
thevpc/upa
upa-impl-core/src/main/java/net/thevpc/upa/impl/DefaultRelationship.java
27648
package net.thevpc.upa.impl; import java.util.*; import net.thevpc.upa.*; import net.thevpc.upa.expressions.*; import net.thevpc.upa.impl.ext.EntityExt; import net.thevpc.upa.impl.upql.util.ThatExpressionReplacer; import net.thevpc.upa.impl.upql.util.UPQLUtils; import net.thevpc.upa.impl.util.NamingStrategyHelper; import net.thevpc.upa.impl.util.PlatformUtils; import net.thevpc.upa.impl.util.StringUtils; import net.thevpc.upa.impl.util.UPAUtils; import net.thevpc.upa.exceptions.IllegalUPAArgumentException; import net.thevpc.upa.types.I18NString; import net.thevpc.upa.exceptions.UPAException; import net.thevpc.upa.expressions.*; import net.thevpc.upa.types.DataType; import net.thevpc.upa.types.RelationDataType; public class DefaultRelationship extends AbstractUPAObject implements Relationship { private RelationshipRole targetRole; private RelationshipRole sourceRole; protected Map<String, String> targetToSourceKeyMap; protected Map<String, String> sourceToTargetKeyMap; protected DataType dataType; private RelationshipType relationType; protected Expression filter; private int tuningMaxInline = 10; private boolean nullable; public DefaultRelationship() { targetRole = new DefaultRelationshipRole(); targetRole.setRelationship(this); targetRole.setRelationshipRoleType(RelationshipRoleType.TARGET); sourceRole = new DefaultRelationshipRole(); sourceRole.setRelationship(this); sourceRole.setRelationshipRoleType(RelationshipRoleType.SOURCE); } @Override public String getAbsoluteName() { return getName(); } public void setNullable(boolean nullable) { this.nullable = nullable; } @Override public void commitModelChanged() throws UPAException { Entity sourceEntity = getSourceRole().getEntity(); Entity targetEntity = getTargetRole().getEntity(); if (sourceEntity == null || targetEntity == null) { throw new UPAException("InvalidRelationDefinition"); } if (!sourceEntity.getUserExcludeModifiers().contains(EntityModifier.VALIDATE_PERSIST)) { sourceEntity.getModifiers().add(EntityModifier.VALIDATE_PERSIST); } if (!sourceEntity.getUserExcludeModifiers().contains(EntityModifier.VALIDATE_UPDATE)) { sourceEntity.getModifiers().add(EntityModifier.VALIDATE_UPDATE); } List<Field> sourceFieldsList = sourceRole.getFields(); Field[] sourceFields = sourceFieldsList.toArray(new Field[sourceFieldsList.size()]); KeyType keyType = new KeyType(targetEntity, filter, false); setDataType(keyType); tuningMaxInline = getPersistenceUnit().getProperties().getInt(Relationship.class.getName() + ".maxInline", 10); List<Field> targetFieldsList = targetEntity.getIdFields(); Field[] targetFields = targetFieldsList.toArray(new Field[targetFieldsList.size()]);; // some checks if (sourceFields.length == 0) { throw new IllegalUPAArgumentException("No source fields are specified"); } if (targetFields.length == 0) { throw new IllegalUPAArgumentException("Target Entity " + targetEntity.getName() + " has no primary fields"); } if (sourceFields.length != targetFields.length) { throw new IllegalUPAArgumentException("source fields and target fields have not the same count"); } sourceEntity.addDependencyOnEntity(targetEntity.getName()); if (dataType == null) { dataType = targetEntity.getDataType(); } if (dataType.isNullable() != nullable) { DataType trCloned = (DataType) dataType.copy(); trCloned.setNullable(nullable); dataType = trCloned; } this.sourceToTargetKeyMap = new HashMap<String, String>(sourceFields.length); this.targetToSourceKeyMap = new HashMap<String, String>(sourceFields.length); // if ((theSourceTable instanceof View)) // this.type = 0; for (int i = 0; i < sourceFields.length; i++) { if (sourceFields[i].getModifiers().contains(FieldModifier.TRANSIENT) && this.relationType != RelationshipType.TRANSIENT) { //Log. System.err.println("Type should be VIEW for " + getName()); this.relationType = RelationshipType.TRANSIENT; } else if (sourceFields[i].getUpdateFormula() != null && this.relationType != RelationshipType.TRANSIENT && this.relationType != RelationshipType.SHADOW_ASSOCIATION) { // Log. System.err.println("Type should be either VIEW or SHADOW for " + name); this.relationType = RelationshipType.SHADOW_ASSOCIATION; } if (((getTargetRole().getEntity().isView()) || (getSourceRole().getEntity().isView())) && relationType != RelationshipType.TRANSIENT) { this.relationType = RelationshipType.TRANSIENT; } this.sourceToTargetKeyMap.put(sourceFields[i].getName(), targetFields[i].getName()); this.targetToSourceKeyMap.put(targetFields[i].getName(), sourceFields[i].getName()); // targetFields[i].addManyToOneRelation(this); ((AbstractField) sourceFields[i]).setEffectiveModifiers(sourceFields[i].getModifiers().add(FieldModifier.FOREIGN)); ((AbstractField) targetFields[i]).setEffectiveModifiers(targetFields[i].getModifiers().add(FieldModifier.REFERENCED)); // if (sourceFields[i].getTitle() == null) { // sourceFields[i].setTitle(targetFields[i].getTitle()); // } if (sourceFields[i].getDataType() == null) { DataType tr = targetFields[i].getDataType(); if (tr.isNullable() == nullable) { sourceFields[i].setDataType(tr); } else { DataType trCloned = (DataType) tr.copy(); trCloned.setNullable(nullable); sourceFields[i].setDataType(trCloned); } } } if (getSourceRole().getEntityField() != null) { Field sourceEntityField = getSourceRole().getEntityField(); DataType dt = sourceEntityField.getDataType(); if (dt instanceof RelationDataType) { RelationDataType edt = (RelationDataType) dt; edt.setRelationship(this); } } if (getTargetRole().getEntityField() != null) { Field targetEntityField = getTargetRole().getEntityField(); DataType dt = targetEntityField.getDataType(); if (dt instanceof RelationDataType) { RelationDataType edt = (RelationDataType) dt; edt.setRelationship(this); } } this.sourceToTargetKeyMap = PlatformUtils.unmodifiableMap(sourceToTargetKeyMap); this.targetToSourceKeyMap = PlatformUtils.unmodifiableMap(targetToSourceKeyMap); setI18NTitle(new I18NString("Relationship").append(getName())); setI18NDescription(getI18NTitle().append(".desc")); // StringBuilder preferredPersistenceName = new StringBuilder(getName().length()); // for (int i = 0; i < getName().length(); i++) { // if (ExpressionHelper.isIdentifierPart(getName().charAt(i))) { // preferredPersistenceName.append(getName().charAt(i)); // } else { // preferredPersistenceName.append('_'); // } // } // setPersistenceName(preferredPersistenceName.toString()); if (getRelationshipType() == RelationshipType.COMPOSITION) { ((EntityExt) sourceEntity).setCompositionRelationship(this); } targetRole.setFields(targetFields); UPAUtils.prepare(getPersistenceUnit(), targetRole, this.getName() + "_" + targetRole.getRelationshipRoleType()); UPAUtils.prepare(getPersistenceUnit(), sourceRole, this.getName() + "_" + sourceRole.getRelationshipRoleType()); if (((getTargetRole().getEntity().isView()) || (getSourceRole().getEntity().isView())) && relationType != RelationshipType.TRANSIENT) { throw new IllegalUPAArgumentException(this + " : Relationship Type must be TRANSIENT. Found " + relationType); } if (((getTargetRole().getEntity().getShield().isTransient()) || (getSourceRole().getEntity().getShield().isTransient())) && relationType != RelationshipType.TRANSIENT) { throw new IllegalUPAArgumentException(this + " : Relationship Type must be TRANSIENT. Found " + relationType); } FlagSet<FieldModifier> modifierstoRemove = FlagSets.ofType(FieldModifier.class) .addAll( FieldModifier.PERSIST, FieldModifier.PERSIST_DEFAULT, FieldModifier.PERSIST_FORMULA, FieldModifier.PERSIST_SEQUENCE, FieldModifier.UPDATE, FieldModifier.UPDATE_DEFAULT, FieldModifier.UPDATE_FORMULA, FieldModifier.UPDATE_SEQUENCE); switch (getSourceRole().getRelationshipUpdateType()) { case FLAT: { Field f = getSourceRole().getEntityField(); if (f != null) { ((AbstractField) f).setEffectiveModifiers(f.getModifiers().removeAll(modifierstoRemove)); } break; } case COMPOSED: { List<Field> fields = getSourceRole().getFields(); if (fields != null) { for (Field f : fields) { ((AbstractField) f).setEffectiveModifiers(f.getModifiers().removeAll(modifierstoRemove)); } } break; } } } public void setDataType(DataType dataType) { this.dataType = dataType; } public RelationshipType getRelationshipType() { return relationType; } public void setRelationshipType(RelationshipType relationType) { this.relationType = relationType; } public int size() { return getSourceRole().getFields().size(); } public DataType getDataType() { return dataType; } // public Entity getSourceEntity() { // return sourceFields[0].getEntity(); // } // // public Entity getTargetEntity() { // return targetFields[0].getEntity(); // } public Map<String, String> getSourceToTargetFieldNamesMap(boolean absolute) throws UPAException { Map<String, String> m = new HashMap<String, String>(getSourceToTargetFieldsMap().size()); if (absolute) { for (Map.Entry<String, String> e : sourceToTargetKeyMap.entrySet()) { m.put(getSourceRole().getEntity().getField(e.getKey()).getName(), getTargetRole().getEntity().getField(e.getValue()).getName()); } } else { for (Map.Entry<String, String> e : sourceToTargetKeyMap.entrySet()) { m.put(e.getKey(), e.getValue()); } } return m; } public Map<String, String> getTargetToSourceFieldNamesMap(boolean absolute) throws UPAException { Map<String, String> m = new HashMap<String, String>(getSourceToTargetFieldsMap().size()); if (absolute) { for (Map.Entry<String, String> e : targetToSourceKeyMap.entrySet()) { m.put(getTargetRole().getEntity().getField(e.getKey()).getName(), getSourceRole().getEntity().getField(e.getValue()).getName()); } } else { for (Map.Entry<String, String> e : targetToSourceKeyMap.entrySet()) { m.put(e.getKey(), e.getValue()); } } return m; } // public int indexOfTargetField(String fieldName) { // for (int i = 0; i < targetFields.length; i++) { // if (targetFields[i].getName().equals(fieldName)) { // return i; // } // } // return -1; // } // // public int indexOfSourceField(String fieldName) { // for (int i = 0; i < sourceFields.length; i++) { // if (sourceFields[i].getName().equals(fieldName)) { // return i; // } // } // return -1; // } public Map<String, String> getSourceToTargetFieldsMap() { return sourceToTargetKeyMap; } public Map<String, String> getTargetToSourceFieldsMap() { return targetToSourceKeyMap; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof DefaultRelationship)) { return false; } else { DefaultRelationship o = (DefaultRelationship) other; return NamingStrategyHelper.equals(getPersistenceUnit().isCaseSensitiveIdentifiers(), getName(), o.getName()); } } @Override public String toString() { return getName(); } // public int compareTo(Object other) { // return toString().compareTo(other.toString()); // } public Expression getTargetCondition(Expression sourceCondition, String sourceAlias, String targetAlias) { Field[] sourceFields = getSourceRole().getFields().toArray(new Field[getSourceRole().getFields().size()]); Field[] targetFields = getTargetRole().getFields().toArray(new Field[getTargetRole().getFields().size()]); Var[] lvar = new Var[sourceFields.length]; Var[] rvar = new Var[targetFields.length]; for (int i = 0; i < lvar.length; i++) { lvar[i] = (sourceAlias == null) ? new Var(sourceFields[i].getName()) : new Var(new Var(sourceAlias), sourceFields[i].getName()); rvar[i] = (targetAlias == null) ? new Var(targetFields[i].getName()) : new Var(new Var(targetAlias), targetFields[i].getName()); } if (tuningMaxInline > 0) { try { List<Document> list = getSourceRole().getEntity().createQuery(new Select().uplet(lvar, "lvar").where(sourceCondition)).getDocumentList(); int j = 0; IdCollectionExpression inCollection = new IdCollectionExpression(rvar); for (Document r : list) { j++; if (j > tuningMaxInline) { return new InSelection(lvar, new Select().from(getSourceRole().getEntity().getName()).uplet(lvar).where(sourceCondition)); } inCollection.add(new Param(null, r.getSingleResult())); //inCollection.add(new Litteral(rs.getObject(1))); } return inCollection; // return new InSelection(rvar, new Select().from(getSourceTable().getPersistenceName()).uplet(lvar).where(inCollection)); } catch (UPAException e) { return new InSelection(rvar, new Select().from(getSourceRole().getEntity().getName()).uplet(lvar).where(sourceCondition)); } } else { return new InSelection(rvar, new Select().from(getSourceRole().getEntity().getName()).uplet(lvar).where(sourceCondition)); } } public Expression getSourceCondition(Expression targetCondition, String sourceAlias, String targetAlias) throws UPAException { //Key Rkey=getTargetTable().getKeyForExpression(targetCondition); Field[] sourceFields = getSourceRole().getFields().toArray(new Field[getSourceRole().getFields().size()]); Field[] targetFields = getTargetRole().getFields().toArray(new Field[getTargetRole().getFields().size()]); if (targetCondition instanceof IdExpression) { Key Rkey = targetRole.getEntity().getBuilder().idToKey(((IdExpression) targetCondition).getId()); if (sourceFields.length == 1) { Var lvar = (sourceAlias == null) ? new Var(sourceFields[0].getName()) : new Var(new Var(sourceAlias), sourceFields[0].getName()); return new Equals(lvar, new Literal(Rkey == null ? null : Rkey.getValue()[0], targetFields[0].getDataType())); } else { Expression a = null; for (int i = 0; i < sourceFields.length; i++) { Var lvar = (sourceAlias == null) ? new Var(sourceFields[i].getName()) : new Var(new Var(sourceAlias), sourceFields[i].getName()); Expression rvar = new Literal(Rkey == null ? null : Rkey.getObjectAt(i), targetFields[i].getDataType()); Expression e = new Equals(lvar, rvar); a = a == null ? e : a; } return a; } } else if (tuningMaxInline > 0) { Var[] lvar = new Var[sourceFields.length]; Var[] rvar = new Var[targetFields.length]; for (int i = 0; i < lvar.length; i++) { lvar[i] = new Var((sourceAlias == null) ? null : new Var(sourceAlias), sourceFields[i].getName()); rvar[i] = new Var((targetAlias == null) ? null : new Var(targetAlias), targetFields[i].getName()); } try { List<Document> list = getTargetRole().getEntity().createQuery(new Select().uplet(rvar, "rval").where(targetCondition)).getDocumentList(); int j = 0; IdCollectionExpression inCollection = new IdCollectionExpression(lvar); for (Document r : list) { j++; if (j > tuningMaxInline) { return new InSelection(lvar, new Select().from(getTargetRole().getEntity().getName()).uplet(rvar).where(targetCondition)); } inCollection.add(new Param(null, r.getSingleResult())); //inCollection.add(new Litteral(rs.getObject(1))); } return inCollection; } catch (UPAException e) { return new InSelection(lvar, new Select().from(getTargetRole().getEntity().getName()).uplet(rvar).where(targetCondition)); } } else { Var[] lvar = new Var[sourceFields.length]; Var[] rvar = new Var[targetFields.length]; for (int i = 0; i < lvar.length; i++) { lvar[i] = new Var((sourceAlias == null) ? null : new Var(sourceAlias), sourceFields[i].getName()); rvar[i] = new Var((targetAlias == null) ? null : new Var(targetAlias), targetFields[i].getName()); } return new InSelection(lvar, new Select().from(getTargetRole().getEntity().getName()).uplet(rvar).where(targetCondition)); } } public Expression getFilter() { return filter; } // public void setTargetFields(Field[] targetFields) { // this.targetFields = targetFields; // } // // public void setTargetRole(RelationRole targetRole) { // this.targetRole = targetRole; // } // public void setTargetToSourceKeyMap(Map<String,String> targetToSourceKeyMap) { // this.targetToSourceKeyMap = targetToSourceKeyMap; // } // // public void setSourceFields(Field[] sourceFields) { // this.sourceFields = sourceFields; // } // // public void setSourceRole(RelationRole sourceRole) { // this.sourceRole = sourceRole; // } // public void setSourceToTargetKeyMap(Map sourceToTargetKeyMap) { // this.sourceToTargetKeyMap = sourceToTargetKeyMap; // } // public void setDataType(DataType dataType) { // this.dataType = dataType; // } // public void setFilter(Expression filter) { this.filter = filter; } // public void setTuningMaxInline(int tuningMaxInline) { // this.tuningMaxInline = tuningMaxInline; // } // public boolean isTransient() { switch (relationType) { case TRANSIENT: { return true; } } return false; } @Override public boolean isFollowLinks() { switch (relationType) { case DEFAULT: case ASSOCIATION: case AGGREGATION: case COMPOSITION: case SHADOW_ASSOCIATION: { return true; } } return false; } @Override public boolean isAskForConfirm() { switch (relationType) { case DEFAULT: case ASSOCIATION: case AGGREGATION: { return true; } } return false; } public RelationshipRole getTargetRole() { return targetRole; } public RelationshipRole getSourceRole() { return sourceRole; } public Entity getTargetEntity() throws UPAException { return targetRole == null ? null : targetRole.getEntity(); } public Entity getSourceEntity() throws UPAException { return sourceRole == null ? null : sourceRole.getEntity(); } // public void setRelationType(RelationType relationType) { // this.relationType = relationType; // } // // @Override // public int hashCode() { // return getName() != null ? getName().hashCode() : 0; // } // @Override // public String getDumpString() { // DumpStringHelper h = new DumpStringHelper(this, false); // h.add("name", name); // h.add("persistenceName", persistenceName); // h.add("title", title); // h.add("dataType", dataType); // h.add("nullable", nullable); // h.add("type", relationType); // h.add("filter", filter); // h.add("targetToSourceKeyMap", targetToSourceKeyMap); // h.add("sourceToTargetKeyMap", sourceToTargetKeyMap); // h.add("targetFields", targetFields); // h.add("sourceFields", sourceFields); // h.add("targetRole", targetRole); // h.add("sourceRole", sourceRole); // h.add("tuningMaxInline", tuningMaxInline); // return h.toString(); // } // public Key[] loadAllSourceKeys(Key targetKey,Expression whereClause, Order criteria, boolean check){ // // } // // public Document[] loadAllSourceDocuments(Key targetKey,Expression whereClause, Field[] fields, Order criteria){ // // } // // public Document[] loadAllSourceDocuments(Expression whereClause, FieldFilter fieldFilter, Order criteria){ // // } // // public Document[] loadAllSourceDocuments(Expression whereClause, String[] fields, Order criteria){ // // } public void close() throws UPAException { // } public Key extractKey(Document sourceDocument) { switch (getSourceRole().getRelationshipUpdateType()) { case COMPOSED: { Object targetEntityVal = sourceDocument.getObject(getSourceRole().getEntityField().getName()); if (targetEntityVal == null) { return null; } EntityBuilder targetConverter = getTargetRole().getEntity().getBuilder(); return targetConverter.objectToKey(targetEntityVal); } case FLAT: { List<Field> relFields = getSourceRole().getFields(); ArrayList<Object> keys = new ArrayList<Object>(relFields.size()); for (Field field : relFields) { Object keyPart = sourceDocument.getObject(field.getName()); if (keyPart == null) { return null; } keys.add(keyPart); } return getTargetRole().getEntity().createKey(keys.toArray()); } } return null; } public Object extractIdByEntityField(Document sourceDocument) { Object targetEntityVal = sourceDocument.getObject(getSourceRole().getEntityField().getName()); if (targetEntityVal == null) { return null; } EntityBuilder targetConverter = getTargetRole().getEntity().getBuilder(); return targetConverter.objectToId(targetEntityVal); } public Object extractIdByForeignFields(Document sourceDocument) { List<Field> relFields = getSourceRole().getFields(); ArrayList<Object> keys = new ArrayList<Object>(relFields.size()); for (Field field : relFields) { Object keyPart = sourceDocument.getObject(field.getName()); if (keyPart == null) { return null; } keys.add(keyPart); } return getTargetRole().getEntity().createId(keys.toArray()); } public Object extractId(Document sourceDocument) { switch (getSourceRole().getRelationshipUpdateType()) { case COMPOSED: { Object o = extractIdByEntityField(sourceDocument); return o; } case FLAT: { return extractIdByForeignFields(sourceDocument); } } return null; } public Expression createTargetListExpression(Object currentInstance, String alias) { if (filter == null) { return null; } HashMap<String, Object> v = new HashMap<String, Object>(); v.put(UPQLUtils.THIS, currentInstance); if (StringUtils.isNullOrEmpty(alias)) { alias = getTargetEntity().getName(); } final String alias2 = alias; ExpressionManager expressionManager = getPersistenceUnit().getExpressionManager(); Expression filter2 = expressionManager.simplifyExpression(filter.copy(), v); filter2 = expressionManager.createEvaluator().evalObject(filter2, null); filter2.visit(new ThatExpressionReplacer(alias2)); if (filter2 instanceof Literal) { if (((Literal) filter2).getValue() instanceof Boolean) { boolean b = (Boolean) ((Literal) filter2).getValue(); if (b) { filter2 = new Equals(new Literal(1), new Literal(1)); } else { filter2 = new Different(new Literal(1), new Literal(1)); } } } return filter2; } @Override public RelationshipInfo getInfo() { RelationshipInfo i = new RelationshipInfo("many2one"); fillObjectInfo(i); i.setAskForConfirm(isAskForConfirm()); i.setFollowLinks(isFollowLinks()); i.setFiltered(getFilter() != null); i.setLive(isTransient()); i.setRelationshipType(getRelationshipType()); i.setNullable(nullable); i.setSource(getSourceEntity() == null ? null : getSourceEntity().getName()); i.setTarget(getTargetEntity() == null ? null : getTargetEntity().getName()); i.setSourceField(getTargetEntity() == null || getSourceRole().getEntityField() == null ? null : getSourceRole().getEntityField().getName()); i.setTargetField(getTargetEntity() == null || getTargetRole().getEntityField() == null ? null : getTargetRole().getEntityField().getName()); i.setSourceFields(getTargetEntity() == null ? new String[0] : toString(getSourceRole().getFields())); i.setTargetFields(getTargetEntity() == null ? new String[0] : toString(getTargetRole().getFields())); return i; } private String[] toString(List<Field> f) { if (f == null) { f = Collections.EMPTY_LIST; } String[] all = new String[f.size()]; for (int i = 0; i < all.length; i++) { all[i] = f.get(i).getName(); } return all; } }
gpl-3.0
CollapsedDom/Stud.IP-Client
core/client/src/main/java/de/danner_web/studip_client/utils/OSValidationUtil.java
471
package de.danner_web.studip_client.utils; public class OSValidationUtil { private static String OS = null; private static String getOsName() { if (OS == null) { OS = System.getProperty("os.name"); } return OS; } public static boolean isWindows() { return getOsName().startsWith("Windows"); } public static boolean isMac() { // TODO Implement return false; } public static boolean isLinux() { return getOsName().startsWith("Linux"); } }
gpl-3.0
Exorde/mlo-sites
vanilla/themes/nebula/views/profile/notifications.php
362
<?php if (!defined('APPLICATION')) exit(); if ($this->ActivityData->NumRows() > 0) { echo '<ul class="DataList">'; include($this->FetchViewLocation('activities', 'activity', 'dashboard')); echo '</ul>'; echo $this->Pager->ToString('more'); } else { ?> <div class="Empty"><?php echo T('You do not have any notifications yet.'); ?></div> <?php }
gpl-3.0
imran04/arcadeengine
Games/DungeonEye/Forms/Asset/MonsterGeneratorForm.Designer.cs
8819
namespace DungeonEye.Forms { partial class MonsterGeneratorForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.DoneBox = new System.Windows.Forms.Button(); this.MonsterTypeBox = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.SpawnCountBox = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.SpawnRateBox = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); this.ActiveBox = new System.Windows.Forms.CheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label4 = new System.Windows.Forms.Label(); this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.switchCountControl1 = new DungeonEye.Forms.SwitchCountControl(); ((System.ComponentModel.ISupportInitialize) (this.SpawnRateBox)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize) (this.numericUpDown1)).BeginInit(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // DoneBox // this.DoneBox.Anchor = ((System.Windows.Forms.AnchorStyles) ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.DoneBox.Location = new System.Drawing.Point(348, 171); this.DoneBox.Name = "DoneBox"; this.DoneBox.Size = new System.Drawing.Size(75, 23); this.DoneBox.TabIndex = 0; this.DoneBox.Text = "Done"; this.DoneBox.UseVisualStyleBackColor = true; // // MonsterTypeBox // this.MonsterTypeBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.MonsterTypeBox.FormattingEnabled = true; this.MonsterTypeBox.Location = new System.Drawing.Point(111, 19); this.MonsterTypeBox.Name = "MonsterTypeBox"; this.MonsterTypeBox.Size = new System.Drawing.Size(121, 21); this.MonsterTypeBox.TabIndex = 1; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(5, 22); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(31, 13); this.label1.TabIndex = 2; this.label1.Text = "Type"; // // SpawnCountBox // this.SpawnCountBox.FormattingEnabled = true; this.SpawnCountBox.Items.AddRange(new object[] { "Random", "1", "2", "3", "4"}); this.SpawnCountBox.Location = new System.Drawing.Point(111, 46); this.SpawnCountBox.Name = "SpawnCountBox"; this.SpawnCountBox.Size = new System.Drawing.Size(121, 21); this.SpawnCountBox.TabIndex = 3; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(3, 49); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(70, 13); this.label2.TabIndex = 2; this.label2.Text = "Spawn count"; // // SpawnRateBox // this.SpawnRateBox.Location = new System.Drawing.Point(123, 19); this.SpawnRateBox.Maximum = new decimal(new int[] { 1410065407, 2, 0, 0}); this.SpawnRateBox.Name = "SpawnRateBox"; this.SpawnRateBox.Size = new System.Drawing.Size(109, 20); this.SpawnRateBox.TabIndex = 4; this.SpawnRateBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.SpawnRateBox.ThousandsSeparator = true; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(7, 21); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(84, 13); this.label3.TabIndex = 2; this.label3.Text = "Rate in seconds"; // // ActiveBox // this.ActiveBox.Appearance = System.Windows.Forms.Appearance.Button; this.ActiveBox.AutoSize = true; this.ActiveBox.Location = new System.Drawing.Point(256, 117); this.ActiveBox.Name = "ActiveBox"; this.ActiveBox.Size = new System.Drawing.Size(57, 23); this.ActiveBox.TabIndex = 5; this.ActiveBox.Text = "Is active"; this.ActiveBox.UseVisualStyleBackColor = true; // // groupBox1 // this.groupBox1.Controls.Add(this.numericUpDown1); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.SpawnRateBox); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Location = new System.Drawing.Point(12, 117); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(238, 78); this.groupBox1.TabIndex = 6; this.groupBox1.TabStop = false; this.groupBox1.Text = "Generation"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 47); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(111, 13); this.label4.TabIndex = 2; this.label4.Text = "Left before deactivate"; // // numericUpDown1 // this.numericUpDown1.Location = new System.Drawing.Point(123, 45); this.numericUpDown1.Maximum = new decimal(new int[] { 1410065407, 2, 0, 0}); this.numericUpDown1.Name = "numericUpDown1"; this.numericUpDown1.Size = new System.Drawing.Size(109, 20); this.numericUpDown1.TabIndex = 4; this.numericUpDown1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.numericUpDown1.ThousandsSeparator = true; // // groupBox2 // this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.MonsterTypeBox); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.SpawnCountBox); this.groupBox2.Location = new System.Drawing.Point(12, 12); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(238, 99); this.groupBox2.TabIndex = 7; this.groupBox2.TabStop = false; this.groupBox2.Text = "Monster"; // // switchCountControl1 // this.switchCountControl1.Location = new System.Drawing.Point(256, 12); this.switchCountControl1.Name = "switchCountControl1"; this.switchCountControl1.Size = new System.Drawing.Size(176, 99); this.switchCountControl1.TabIndex = 8; // // MonsterGeneratorForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(435, 206); this.Controls.Add(this.switchCountControl1); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.ActiveBox); this.Controls.Add(this.DoneBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MonsterGeneratorForm"; this.ShowInTaskbar = false; this.Text = "Monster generator"; ((System.ComponentModel.ISupportInitialize) (this.SpawnRateBox)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize) (this.numericUpDown1)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button DoneBox; private System.Windows.Forms.ComboBox MonsterTypeBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox SpawnCountBox; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown SpawnRateBox; private System.Windows.Forms.Label label3; private System.Windows.Forms.CheckBox ActiveBox; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.NumericUpDown numericUpDown1; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox groupBox2; private SwitchCountControl switchCountControl1; } }
gpl-3.0
abmindiarepomanager/ABMOpenMainet
Mainet1.0/MainetServiceParent/MainetServiceCommon/src/main/java/com/abm/mainet/bill/service/AdjustmentEntryService.java
919
package com.abm.mainet.bill.service; import java.util.List; import com.abm.mainet.cfc.challan.domain.AdjustmentMasterEntity; import com.abm.mainet.cfc.challan.dto.AdjustmentMasterDTO; import com.abm.mainet.common.domain.Organisation; import com.abm.mainet.common.integration.dto.TbBillMas; import com.abm.mainet.common.master.dto.TbTaxMas; public interface AdjustmentEntryService { List<TbBillMas> fetchModuleWiseBills(Long deptId, String ccnNoOrPropNo, Long orgId); List<TbTaxMas> fetchAllModulewiseTaxes(Long deptId, Organisation orgId); boolean saveAdjustmentEntryData(List<TbBillMas> billlist, AdjustmentMasterDTO adjustmentDto); List<AdjustmentMasterDTO> fetchHistory(String refNo, Long dpDeptId); List<AdjustmentMasterEntity> fetchModuleWiseAdjustmentByUniqueIds(Long deptId, List<String> uniqueIds, long orgid); void updateAdjustedAdjustmentData(List<AdjustmentMasterEntity> adjustmentEntity); }
gpl-3.0
gtozzi/pyuo
pyuo/net.py
7844
#!/usr/bin/env python3 ''' Network classes for Python Ultima Online text client Copyright (C) 2015-2016 Gabriele Tozzi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ''' import time import socket import struct import ipaddress import logging from . import packets class Network: ''' Network handler ''' ## Decompression Tree, internal usage. Thanks to UOXNA project DECOMPRESSION_TREE = ( # leaf0, leaf1, #node (2,1), (4,3), (0,5), (7,6), (9,8), #0-4 (11,10), (13,12), (14,-256), (16,15), (18,17), #5-9 (20,19), (22,21), (23,-1), (25,24), (27,26), #10-14 (29,28), (31,30), (33,32), (35,34), (37,36), #15-19 (39,38), (-64,40), (42,41), (44,43), (45,-6), #20-24 (47,46), (49,48), (51,50), (52,-119), (53,-32), #25-29 (-14,54), (-5,55), (57,56), (59,58), (-2,60), #30-34 (62,61), (64,63), (66,65), (68,67), (70,69), #35-39 (72,71), (73,-51), (75,74), (77,76), (-111,-101), #40-44 (-97,-4), (79,78), (80,-110), (-116,81), (83,82), #45-49 (-255,84), (86,85), (88,87), (90,89), (-10,-15), #50-54 (92,91), (93,-21), (94,-117), (96,95), (98,97), #55-59 (100,99), (101,-114), (102,-105), (103,-26), (105,104), #60-64 (107,106), (109,108), (111,110), (-3,112), (-7,113), #65-69 (-131,114), (-144,115), (117,116), (118,-20), (120,119), #70-74 (122,121), (124,123), (126,125), (128,127), (-100,129), #75-79 (-8,130), (132,131), (134,133), (135,-120), (-31,136), #80-84 (138,137), (-234,-109), (140,139), (142,141), (144,143), #85-89 (145,-112), (146,-19), (148,147), (-66,149), (-145,150), #90-94 (-65,-13), (152,151), (154,153), (155,-30), (157,156), #95-99 (158,-99), (160,159), (162,161), (163,-23), (164,-29), #100-104 (165,-11), (-115,166), (168,167), (170,169), (171,-16), #105-109 (172,-34), (-132,173), (-108,174), (-22,175), (-9,176), #110-114 (-84,177), (-37,-17), (178,-28), (180,179), (182,181), #115-119 (184,183), (186,185), (-104,187), (-78,188), (-61,189), #120-124 (-178,-79), (-134,-59), (-25,190), (-18,-83), (-57,191), #125-129 (192,-67), (193,-98), (-68,-12), (195,194), (-128,-55), #130-134 (-50,-24), (196,-70), (-33,-94), (-129,197), (198,-74), #135-139 (199,-82), (-87,-56), (200,-44), (201,-248), (-81,-163), #140-144 (-123,-52), (-113,202), (-41,-48), (-40,-122), (-90,203), #145-149 (204,-54), (-192,-86), (206,205), (-130,207), (208,-53), #150-154 (-45,-133), (210,209), (-91,211), (213,212), (-88,-106), #155-159 (215,214), (217,216), (-49,218), (220,219), (222,221), #160-164 (224,223),(226,225), (-102,227), (228,-160), (229,-46), #165-169 (230,-127), (231,-103), (233,232), (234,-60), (-76,235), #170-174 (-121,236), (-73,237), (238,-149), (-107,239), (240,-35), #175-179 (-27,-71), (241,-69), (-77,-89), (-118,-62), (-85,-75), #180-184 (-58,-72), (-80,-63), (-42,242), (-157,-150), (-236,-139), #185-189 (-243,-126), (-214,-142), (-206,-138), (-146,-240), (-147,-204), #190-194 (-201,-152), (-207,-227), (-209,-154), (-254,-153), (-156,-176), #195-199 (-210,-165), (-185,-172), (-170,-195), (-211,-232), (-239,-219), #200-204 (-177,-200), (-212,-175), (-143,-244), (-171,-246), (-221,-203), #205-209 (-181,-202), (-250,-173), (-164,-184), (-218,-193), (-220,-199), #210-214 (-249,-190), (-217,-230), (-216,-169), (-197,-191), (243,-47), #215-219 (245,244), (247,246), (-159,-148), (249,248), (-93,-92), #220-224 (-225,-96), (-95,-151), (251,250), (252,-241), (-36,-161), #225-229 (254,253), (-39,-135), (-124,-187), (-251,255), (-238,-162), #230-234 (-38,-242), (-125,-43), (-253,-215), (-208,-140), (-235,-137), #235-239 (-237,-158), (-205,-136), (-141,-155), (-229,-228), (-168,-213), #240-244 (-194,-224), (-226,-196), (-233,-183), (-167,-231), (-189,-174), #245-249 (-166,-252), (-222,-198), (-179,-188), (-182,-223), (-186,-180), #250-254 (-247,-245) #255 ) def __init__(self, ip, port): '''! Connects to the socket @param ip IPv4Address: the IP object, from the ipaddress module @param port int: the port ''' ## Logger, for internal usage self.log = logging.getLogger('net') ## Socket connection, for internal usage self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((str(ip), port)) ## Buffer, for internal usage self.buf = b'' ## Wether to use compression or not self.compress = False def close(self): ''' Disconnects, makes this object unusable ''' self.sock.close() def send(self, data): ''' Sends a packet or raw binary data ''' if isinstance(data, packets.Packet): raw = data.encode() assert data.validated elif isinstance(data, bytes): raw = data else: raise ValueError('Expecting Packet or bytes') self.log.debug('-> 0x%0.2X, %d bytes\n"%s"', raw[0], len(raw), raw) self.sock.send(raw) def recv(self, force=False, blocking=True): '''! Reads next packet from the server Always returns a full packet (waiting for full packet is always blocking) @param force bool: Force wait, used internally @param blocking bool: Set blocking mode ''' self.sock.setblocking(blocking) # Wait for a full packet if len(self.buf) < 1 or force: try: data = self.sock.recv(4096) except socket.error: if not blocking: return None else: raise if not len(data): raise RuntimeError("Disconnected"); self.buf += data if self.compress: try: raw, size = self.decompress(self.buf) except NoFullPacketError: # Not enough data to make a full packet. Try again self.log.debug("No full packet. Waiting... (%d bytes in buffer)", len(self.buf)) return self.recv(True) else: raw = self.buf size = len(self.buf) if not raw: raise NotImplementedError() cinfo = '{} compressed'.format(size) if self.compress else 'not compressed' self.log.debug('<- 0x%0.2X, %d bytes, %s\n"%s"', raw[0], len(raw), cinfo, raw) # Creates and instance of the packet from the buffer cmd = raw[0] if cmd not in packets.classes.keys(): raise NotImplementedError( "Unknown packet 0x%0.2X, %d bytes\n%s" % (cmd, len(raw), raw)) pktClass = packets.classes[cmd] pkt = pktClass() pkt.decode(raw) assert pkt.validated assert pkt.length == len(raw) # Remove the processed packet from the buffer the buffer self.buf = self.buf[size:] return pkt def decompress(self, buf): '''! Internal usage, decompress a packet (thanks to UltimaXNA project @return tuple (decompressed, compressed_size) ''' node = 0 leaf = 0 leafVal = 0 bitNum = 8 srcPos = 0 dest = b'' while srcPos < len(buf): # Gets next bit leaf = ( buf[srcPos] >> ( bitNum - 1 ) ) & 1 # Look into decompression table leafVal = self.DECOMPRESSION_TREE[node][leaf] # all numbers below 1 (0..-256) are codewords # if the halt codeword has been found, skip this byte if leafVal == -256: return ( dest, srcPos + 1) elif leafVal < 1: dest += bytes([0 - leafVal]) leafVal = 0 # Go for next bit, if its the end of the byte, go to the next byte bitNum -= 1 node = leafVal if bitNum < 1: bitNum = 8; srcPos += 1 raise NoFullPacketError("No full packet could be read") class NoFullPacketError(Exception): ''' Exception thrown when no full packet is available ''' pass
gpl-3.0
TrinityCore/WowPacketParser
WowPacketParserModule.V9_0_1_36216/Parsers/MiscellaneousHandler.cs
10311
using WowPacketParser.Enums; using WowPacketParser.Misc; using WowPacketParser.Parsing; using WowPacketParser.Proto; using WowPacketParser.Store; using CoreParsers = WowPacketParser.Parsing.Parsers; namespace WowPacketParserModule.V9_0_1_36216.Parsers { public static class MiscellaneousHandler { [Parser(Opcode.SMSG_FEATURE_SYSTEM_STATUS)] public static void HandleFeatureSystemStatus(Packet packet) { packet.ReadByte("ComplaintStatus"); packet.ReadUInt32("ScrollOfResurrectionRequestsRemaining"); packet.ReadUInt32("ScrollOfResurrectionMaxRequestsPerDay"); packet.ReadUInt32("CfgRealmID"); packet.ReadInt32("CfgRealmRecID"); packet.ReadUInt32("MaxRecruits", "RAFSystem"); packet.ReadUInt32("MaxRecruitMonths", "RAFSystem"); packet.ReadUInt32("MaxRecruitmentUses", "RAFSystem"); packet.ReadUInt32("DaysInCycle", "RAFSystem"); packet.ReadUInt32("TwitterPostThrottleLimit"); packet.ReadUInt32("TwitterPostThrottleCooldown"); packet.ReadUInt32("TokenPollTimeSeconds"); packet.ReadUInt32("KioskSessionMinutes"); packet.ReadInt64("TokenBalanceAmount"); packet.ReadUInt32("BpayStoreProductDeliveryDelay"); packet.ReadUInt32("ClubsPresenceUpdateTimer"); packet.ReadUInt32("HiddenUIClubsPresenceUpdateTimer"); packet.ResetBitReader(); packet.ReadBit("VoiceEnabled"); var hasEuropaTicketSystemStatus = packet.ReadBit("HasEuropaTicketSystemStatus"); packet.ReadBit("ScrollOfResurrectionEnabled"); packet.ReadBit("BpayStoreEnabled"); packet.ReadBit("BpayStoreAvailable"); packet.ReadBit("BpayStoreDisabledByParentalControls"); packet.ReadBit("ItemRestorationButtonEnabled"); packet.ReadBit("BrowserEnabled"); var hasSessionAlert = packet.ReadBit("HasSessionAlert"); packet.ReadBit("Enabled", "RAFSystem"); packet.ReadBit("RecruitingEnabled", "RAFSystem"); packet.ReadBit("CharUndeleteEnabled"); packet.ReadBit("RestrictedAccount"); packet.ReadBit("CommerceSystemEnabled"); packet.ReadBit("TutorialsEnabled"); packet.ReadBit("TwitterEnabled"); packet.ReadBit("Unk67"); packet.ReadBit("WillKickFromWorld"); packet.ReadBit("KioskModeEnabled"); packet.ReadBit("CompetitiveModeEnabled"); packet.ReadBit("TokenBalanceEnabled"); packet.ReadBit("WarModeFeatureEnabled"); packet.ReadBit("ClubsEnabled"); packet.ReadBit("ClubsBattleNetClubTypeAllowed"); packet.ReadBit("ClubsCharacterClubTypeAllowed"); packet.ReadBit("ClubsPresenceUpdateEnabled"); packet.ReadBit("VoiceChatDisabledByParentalControl"); packet.ReadBit("VoiceChatMutedByParentalControl"); packet.ReadBit("QuestSessionEnabled"); packet.ReadBit("IsMuted"); packet.ReadBit("ClubFinderEnabled"); packet.ReadBit("Unknown901CheckoutRelated"); if (ClientVersion.AddedInVersion(ClientVersionBuild.V9_1_5_40772)) { packet.ReadBit("TextToSpeechFeatureEnabled"); packet.ReadBit("ChatDisabledByDefault"); packet.ReadBit("ChatDisabledByPlayer"); packet.ReadBit("LFGListCustomRequiresAuthenticator"); } { packet.ResetBitReader(); packet.ReadBit("ToastsDisabled"); packet.ReadSingle("ToastDuration"); packet.ReadSingle("DelayDuration"); packet.ReadSingle("QueueMultiplier"); packet.ReadSingle("PlayerMultiplier"); packet.ReadSingle("PlayerFriendValue"); packet.ReadSingle("PlayerGuildValue"); packet.ReadSingle("ThrottleInitialThreshold"); packet.ReadSingle("ThrottleDecayTime"); packet.ReadSingle("ThrottlePrioritySpike"); packet.ReadSingle("ThrottleMinThreshold"); packet.ReadSingle("ThrottlePvPPriorityNormal"); packet.ReadSingle("ThrottlePvPPriorityLow"); packet.ReadSingle("ThrottlePvPHonorThreshold"); packet.ReadSingle("ThrottleLfgListPriorityDefault"); packet.ReadSingle("ThrottleLfgListPriorityAbove"); packet.ReadSingle("ThrottleLfgListPriorityBelow"); packet.ReadSingle("ThrottleLfgListIlvlScalingAbove"); packet.ReadSingle("ThrottleLfgListIlvlScalingBelow"); packet.ReadSingle("ThrottleRfPriorityAbove"); packet.ReadSingle("ThrottleRfIlvlScalingAbove"); packet.ReadSingle("ThrottleDfMaxItemLevel"); packet.ReadSingle("ThrottleDfBestPriority"); } if (hasSessionAlert) V6_0_2_19033.Parsers.MiscellaneousHandler.ReadClientSessionAlertConfig(packet, "SessionAlert"); packet.ResetBitReader(); V8_0_1_27101.Parsers.MiscellaneousHandler.ReadVoiceChatManagerSettings(packet, "VoiceChatManagerSettings"); if (hasEuropaTicketSystemStatus) { packet.ResetBitReader(); V6_0_2_19033.Parsers.MiscellaneousHandler.ReadCliEuropaTicketConfig(packet, "EuropaTicketSystemStatus"); } } [Parser(Opcode.SMSG_FEATURE_SYSTEM_STATUS2)] public static void HandleFeatureSystemStatus2(Packet packet) { packet.ReadBit("TextToSpeechFeatureEnabled"); } [Parser(Opcode.SMSG_FEATURE_SYSTEM_STATUS_GLUE_SCREEN)] public static void HandleFeatureSystemStatusGlueScreen(Packet packet) { packet.ReadBit("BpayStoreEnabled"); packet.ReadBit("BpayStoreAvailable"); packet.ReadBit("BpayStoreDisabledByParentalControls"); packet.ReadBit("CharUndeleteEnabled"); packet.ReadBit("CommerceSystemEnabled"); packet.ReadBit("Unk14"); packet.ReadBit("WillKickFromWorld"); packet.ReadBit("IsExpansionPreorderInStore"); packet.ReadBit("KioskModeEnabled"); packet.ReadBit("IsCompetitiveModeEnabled"); packet.ReadBit("TrialBoostEnabled"); packet.ReadBit("TokenBalanceEnabled"); packet.ReadBit("LiveRegionCharacterListEnabled"); packet.ReadBit("LiveRegionCharacterCopyEnabled"); packet.ReadBit("LiveRegionAccountCopyEnabled"); packet.ReadBit("LiveRegionKeyBindingsCopyEnabled"); packet.ReadBit("Unknown901CheckoutRelated"); var europaTicket = packet.ReadBit("IsEuropaTicketSystemStatusEnabled"); packet.ResetBitReader(); if (europaTicket) V6_0_2_19033.Parsers.MiscellaneousHandler.ReadCliEuropaTicketConfig(packet, "EuropaTicketSystemStatus"); packet.ReadUInt32("TokenPollTimeSeconds"); packet.ReadUInt32("KioskSessionMinutes"); packet.ReadInt64("TokenBalanceAmount"); packet.ReadInt32("MaxCharactersPerRealm"); var liveRegionCharacterCopySourceRegionsCount = packet.ReadUInt32("LiveRegionCharacterCopySourceRegionsCount"); packet.ReadUInt32("BpayStoreProductDeliveryDelay"); packet.ReadInt32("ActiveCharacterUpgradeBoostType"); packet.ReadInt32("ActiveClassTrialBoostType"); packet.ReadInt32("MinimumExpansionLevel"); packet.ReadInt32("MaximumExpansionLevel"); for (int i = 0; i < liveRegionCharacterCopySourceRegionsCount; i++) packet.ReadUInt32("LiveRegionCharacterCopySourceRegion", i); } [Parser(Opcode.SMSG_SET_ALL_TASK_PROGRESS)] [Parser(Opcode.SMSG_UPDATE_TASK_PROGRESS)] public static void HandleSetAllTaskProgress(Packet packet) { var int4 = packet.ReadUInt32("TaskProgressCount"); for (int i = 0; i < int4; i++) { packet.ReadUInt32("TaskID", i); // these fields might have been shuffled packet.ReadUInt32("FailureTime", i); packet.ReadUInt32("Flags", i); packet.ReadUInt32("Unk", i); var int3 = packet.ReadUInt32("ProgressCounts", i); for (int j = 0; j < int3; j++) packet.ReadUInt16("Counts", i, j); } } [Parser(Opcode.SMSG_PLAY_OBJECT_SOUND)] public static void HandlePlayObjectSound(Packet packet) { PacketPlayObjectSound packetSound = packet.Holder.PlayObjectSound = new PacketPlayObjectSound(); uint sound = packetSound.Sound = packet.ReadUInt32<SoundId>("SoundId"); packetSound.Source = packet.ReadPackedGuid128("SourceObjectGUID"); packetSound.Target = packet.ReadPackedGuid128("TargetObjectGUID"); packet.ReadVector3("Position"); packet.ReadInt32("BroadcastTextID"); Storage.Sounds.Add(sound, packet.TimeSpan); } [Parser(Opcode.SMSG_WORLD_SERVER_INFO)] public static void HandleWorldServerInfo(Packet packet) { CoreParsers.MovementHandler.CurrentDifficultyID = packet.ReadUInt32<DifficultyId>("DifficultyID"); packet.ReadByte("IsTournamentRealm"); packet.ReadBit("XRealmPvpAlert"); packet.ReadBit("BlockExitingLoadingScreen"); var hasRestrictedAccountMaxLevel = packet.ReadBit("HasRestrictedAccountMaxLevel"); var hasRestrictedAccountMaxMoney = packet.ReadBit("HasRestrictedAccountMaxMoney"); var hasInstanceGroupSize = packet.ReadBit("HasInstanceGroupSize"); if (hasRestrictedAccountMaxLevel) packet.ReadUInt32("RestrictedAccountMaxLevel"); if (hasRestrictedAccountMaxMoney) packet.ReadUInt64("RestrictedAccountMaxMoney"); if (hasInstanceGroupSize) packet.ReadUInt32("InstanceGroupSize"); } } }
gpl-3.0
heartvalve/OpenFlipper
ObjectTypes/PolyLine/PluginFunctionsPolyLine.cc
4462
//============================================================================= // // OpenFlipper // Copyright (C) 2008 by Computer Graphics Group, RWTH Aachen // www.openflipper.org // //----------------------------------------------------------------------------- // // License // // OpenFlipper 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. // // OpenFlipper 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 OpenFlipper. If not, see <http://www.gnu.org/licenses/>. // //----------------------------------------------------------------------------- // // $Revision$ // $Author$ // $Date$ // //============================================================================= //============================================================================= // // Plugin Functions for PolyLines // //============================================================================= #include <OpenFlipper/common/Types.hh> #include "PolyLine.hh" #include "PluginFunctionsPolyLine.hh" #include <OpenFlipper/BasePlugin/PluginFunctions.hh> namespace PluginFunctions { // =============================================================================== // Get source polylines // =============================================================================== bool getSourcePolylines( std::vector<PolyLine*>& _polylines ) { _polylines.clear(); for ( ObjectIterator o_it(PluginFunctions::SOURCE_OBJECTS,DATA_POLY_LINE ) ; o_it != PluginFunctions::objectsEnd(); ++o_it) { _polylines.push_back ( PluginFunctions::polyLine( *o_it ) ); if( _polylines.back() == 0) std::cerr << "ERROR: Polyine get_source_polylines fatal error\n"; } return ( !_polylines.empty() ); } // =============================================================================== // Get target polylines // =============================================================================== bool getTargetPolylines( std::vector<PolyLine*>& _polylines ) { _polylines.clear(); for ( ObjectIterator o_it(PluginFunctions::TARGET_OBJECTS,DATA_POLY_LINE ) ; o_it != PluginFunctions::objectsEnd(); ++o_it) { _polylines.push_back ( PluginFunctions::polyLine( *o_it ) ); if( _polylines.back() == 0) std::cerr << "ERROR: Polyine getTargetPolylines fatal error\n"; } return ( !_polylines.empty() ); } // =============================================================================== // Get objects // =============================================================================== bool getObject( int _identifier , PolyLineObject*& _object ) { if ( _identifier == BaseObject::NOOBJECT ) { _object = 0; return false; } // Get object by using the map accelerated plugin function BaseObjectData* object = 0; PluginFunctions::getObject(_identifier,object); _object = dynamic_cast< PolyLineObject* >(object); return ( _object != 0 ); } // =============================================================================== // Getting data from objects and casting between them // =============================================================================== PolyLine* polyLine( BaseObjectData* _object ) { if ( _object->dataType(DATA_POLY_LINE) ) { PolyLineObject* object = dynamic_cast< PolyLineObject* >(_object); return object->line(); } else return 0; } PolyLineObject* polyLineObject( BaseObjectData* _object ) { if ( ! _object->dataType(DATA_POLY_LINE) ) return 0; return dynamic_cast< PolyLineObject* >( _object ); } PolyLineObject* polyLineObject( int _objectId ) { if (_objectId == BaseObject::NOOBJECT) return 0; // Get object by using the map accelerated plugin function BaseObjectData* object = 0; PluginFunctions::getObject(_objectId,object); if ( object == 0 ) return 0; PolyLineObject* meshObject = dynamic_cast< PolyLineObject* >(object); return meshObject; } }
gpl-3.0
MailCleaner/MailCleaner
www/framework/Zend/Search/Lucene/Analysis/TokenFilter/LowerCaseUtf8.php
2336
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Search_Lucene * @subpackage Analysis * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: LowerCaseUtf8.php,v 1.1.2.3 2011-05-30 08:31:05 root Exp $ */ /** Zend_Search_Lucene_Analysis_TokenFilter */ require_once 'Zend/Search/Lucene/Analysis/TokenFilter.php'; /** * Lower case Token filter. * * @category Zend * @package Zend_Search_Lucene * @subpackage Analysis * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Search_Lucene_Analysis_TokenFilter_LowerCaseUtf8 extends Zend_Search_Lucene_Analysis_TokenFilter { /** * Object constructor */ public function __construct() { if (!function_exists('mb_strtolower')) { // mbstring extension is disabled require_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Utf8 compatible lower case filter needs mbstring extension to be enabled.'); } } /** * Normalize Token or remove it (if null is returned) * * @param Zend_Search_Lucene_Analysis_Token $srcToken * @return Zend_Search_Lucene_Analysis_Token */ public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken) { $newToken = new Zend_Search_Lucene_Analysis_Token( mb_strtolower($srcToken->getTermText(), 'UTF-8'), $srcToken->getStartOffset(), $srcToken->getEndOffset()); $newToken->setPositionIncrement($srcToken->getPositionIncrement()); return $newToken; } }
gpl-3.0
nitro2010/moodle
mod/forumng/feature/move/group_form.php
5008
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Form to select a target group when moving to a group forum and it doesn't * already have a valid group. * @package forumngfeature * @subpackage move * @copyright 2011 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once($CFG->libdir.'/formslib.php'); class mod_forumng_group_form extends moodleform { public function definition() { global $CFG, $USER; $mform = $this->_form; $forum = $this->_customdata->targetforum; // Informational paragraph. $mform->addElement('static', '', '', get_string('move_group_info', 'forumngfeature_move', $forum->get_name())); // Get list of allowed groups. $groups = $this->_customdata->groups; $mform->addElement('select', 'group', get_string('group'), $groups); reset($groups); $mform->setDefault('group', key($groups)); // Hidden fields. $mform->addElement('hidden', 'd', $this->_customdata->discussionid); $mform->setType('d', PARAM_INT); $mform->addElement('hidden', 'clone', $this->_customdata->cloneid); $mform->setType('clone', PARAM_INT); $mform->addElement('hidden', 'target', $forum->get_course_module_id()); $mform->setType('target', PARAM_INT); $this->add_action_buttons(true, get_string('move')); } } class mod_forumng_moveall_form extends moodleform { public function definition() { global $CFG, $USER; $mform = $this->_form; $params = $this->_customdata['params']; // Informational paragraph. $mform->addElement('static', '', '', get_string('movediscussionsto', 'forumngfeature_move')); // Get current forum. $forum = $this->_customdata['forum']; // Get array of forums excluding current forum. $forums = get_other_course_forums($forum); $mform->addElement('select', 'forum', get_string('movediscussionsto', 'forumngfeature_move'), $forums); // Hidden fields. foreach ($params as $param => $value) { $mform->addElement('hidden', $param, $value); $mform->setType($param, PARAM_INT); } $this->add_action_buttons(true, get_string('movediscussions', 'forumngfeature_move')); } } class mod_forumng_moveall_groups_form extends moodleform { public function definition() { global $CFG, $USER; $mform = $this->_form; $pageparams = $this->_customdata['params']; $target = $this->_customdata['params']['target']; $forumngid = $this->_customdata['params']['id']; $cloneid = $this->_customdata['params']['clone']; $multigroups = $this->_customdata['params']['multigroups']; $targetgroupmode = $this->_customdata['params']['targetgroupmode']; $targetforum = $this->_customdata['targetforum']; $pageparams = $this->_customdata['params']; foreach ($pageparams as $param => $value) { $mform->addElement('hidden', $param, $value); $mform->setType($param, PARAM_INT); } $selectedids = array(); foreach ($pageparams as $field => $value) { $matches = array(); if (!is_array($value) && (string)$value !== '0' && preg_match('~^selectd([0-9]+)$~', $field, $matches)) { $selectedids[] = ($matches[1]); } } // Get list of allowed groups. $options = array(); // Check to see whether target forum uses group mode. if ($targetgroupmode) { $options = get_allowed_groups($targetforum, false); } // Informational paragraph. $mform->addElement('static', '', '', get_string('move_discussions_group_info', 'forumngfeature_move', $targetforum->get_name())); // Get group from user. $mform->addElement('select', 'chosengroup', get_string('group'), $options); reset($options); $mform->setDefault('group', key($options)); $this->add_action_buttons(true, get_string('movediscussions', 'forumngfeature_move')); } }
gpl-3.0
synweb/rocms
RoCMS/Content/base/vendor/jquery/core/jquery.validate.ru.js
1902
/// <reference path="jquery.validate.js" /> /* * Translated default messages for the jQuery validation plugin. * Locale: RU (Russian; русский язык) */ $.extend( $.validator.messages, { required: "Это поле необходимо заполнить.", remote: "Пожалуйста, введите правильное значение.", email: "Пожалуйста, введите корректный адрес электронной почты.", url: "Пожалуйста, введите корректный URL.", date: "Пожалуйста, введите корректную дату.", dateISO: "Пожалуйста, введите корректную дату в формате ISO.", number: "Пожалуйста, введите число.", digits: "Пожалуйста, вводите только цифры.", creditcard: "Пожалуйста, введите правильный номер кредитной карты.", equalTo: "Пожалуйста, введите такое же значение ещё раз.", extension: "Пожалуйста, выберите файл с правильным расширением.", maxlength: $.validator.format( "Пожалуйста, введите не больше {0} символов." ), minlength: $.validator.format( "Пожалуйста, введите не меньше {0} символов." ), rangelength: $.validator.format( "Пожалуйста, введите значение длиной от {0} до {1} символов." ), range: $.validator.format( "Пожалуйста, введите число от {0} до {1}." ), max: $.validator.format( "Пожалуйста, введите число, меньшее или равное {0}." ), min: $.validator.format( "Пожалуйста, введите число, большее или равное {0}." ) } );
gpl-3.0
WaterSheltieDragon/Wango-the-Robot
facedown.py
398
import time import maestro # servo 0 is left/right # servo 1 is up/down try: servo = maestro.Controller() servo.setRange(0,3000,8200) servo.setRange(1,4000,8000) # about 5 clicks per full motion # 1040 for left/right + is left, - is right. # 800 for up/down + is up, - is down. x = servo.getPosition(1) - 800 servo.setAccel(1,6) servo.setTarget(1,x) finally: servo.close
gpl-3.0
MohamedAbdultawab/FOC_RiceUniv
principles-of-computing-2/mini-project-2-word-wrangler/main.py
3909
# this project has to be run in codeskulptor.org """ Student code for Word Wrangler game """ import urllib2 import codeskulptor import poc_wrangler_provided as provided WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(lst): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative. """ if len(lst) >= 2: if lst[0] != lst[1]: return [lst[0]] + remove_duplicates(lst[1:]) else: return remove_duplicates(lst[1:]) return lst def intersect(lst1, lst2): """ Compute the intersection of two sorted lists. Returns a new sorted list containing only elements that are in both lst1 and lst2. This function can be iterative. """ if len(lst1) > 0: if lst1[0] in lst2: return [lst1[0]] + intersect(lst1[1:], lst2) return intersect(lst1[1:], lst2) return [] # Functions to perform merge sort def merge(lst1, lst2): # O(n1 + n2) Time and O(n1 + n2) Extra Space """ Merge two sorted lists. Returns a new sorted list containing those elements that are in either list1 or list2. This function can be iterative. """ new_lst = [] counter_i, counter_j, = 0, 0 while counter_i < len(lst1) and counter_j < len(lst2): if lst1[counter_i] < lst2[counter_j]: new_lst.append(lst1[counter_i]) counter_i += 1 else: new_lst.append(lst2[counter_j]) counter_j += 1 while counter_i < len(lst1): new_lst.append(lst1[counter_i]) counter_i += 1 while counter_j < len(lst2): new_lst.append(lst2[counter_j]) counter_j += 1 return new_lst def split_list(lst): """ Split list into 2 lists of half size """ return lst[:int(round(len(lst) / 2.0))], lst[int(round(len(lst) / 2.0)):] def merge_sort(lst): """ Sort the elements of list1. Return a new sorted list with the same elements as list1. This function should be recursive. """ if len(lst) <= 1: return lst lst1, lst2 = split_list(lst) return merge(merge_sort(lst1), merge_sort(lst2)) def insert_letter(letter, word): """ Inserts a letter in every position in word """ lst = list(word) word_list = [] for idx in range(len(word) + 1): lst.insert(idx, letter) word_list.append(''.join(lst)) lst.pop(idx) return word_list # Function to generate all strings for the word wrangler game def gen_all_strings(word): """ Generate all strings that can be composed from the letters in word in any order. Returns a list of all strings that can be formed from the letters in word. This function should be recursive. """ if len(word) < 1: return [word] elif len(word) == 1: return [word, ''] else: first = word[0] rest = word[1:] rest_strings = gen_all_strings(rest) res = list(rest_strings) for string in rest_strings: res.extend(insert_letter(first, string)) return res # print gen_all_strings('') # print gen_all_strings('a') # print gen_all_strings('ab') # print gen_all_strings('abc') # Function to load words from a file # def load_words(filename): # """ # Load word list from the file named filename. # Returns a list of strings. # """ # return [] # def run(): # """ # Run game. # """ # words = load_words(WORDFILE) # wrangler = provided.WordWrangler(words, remove_duplicates, # intersect, merge_sort, # gen_all_strings) # provided.run_game(wrangler) # Uncomment when you are ready to try the game # run()
gpl-3.0
web-izmerenie/usadba-parfenova
reviews/index.php
1681
<? define("PAGE_TITLE", "Y"); require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php"); $APPLICATION->SetTitle("Отзывы"); ?> <?$APPLICATION->IncludeComponent( "bitrix:news.list", "reviews.list", array( "IBLOCK_TYPE" => LANGUAGE_ID, "IBLOCK_ID" => "5", "NEWS_COUNT" => "4", "SORT_BY1" => "ACTIVE_FROM", "SORT_ORDER1" => "DESC", "SORT_BY2" => "", "SORT_ORDER2" => "", "FILTER_NAME" => "", "FIELD_CODE" => array( 0 => "", 1 => "", ), "PROPERTY_CODE" => array( 0 => "", 1 => "", ), "CHECK_DATES" => "Y", "DETAIL_URL" => "", "AJAX_MODE" => "N", "AJAX_OPTION_JUMP" => "N", "AJAX_OPTION_STYLE" => "Y", "AJAX_OPTION_HISTORY" => "N", "CACHE_TYPE" => "A", "CACHE_TIME" => "7200", "CACHE_FILTER" => "N", "CACHE_GROUPS" => "Y", "PREVIEW_TRUNCATE_LEN" => "", "ACTIVE_DATE_FORMAT" => "j F Y", "SET_STATUS_404" => "N", "SET_TITLE" => "Y", "INCLUDE_IBLOCK_INTO_CHAIN" => "N", "ADD_SECTIONS_CHAIN" => "N", "HIDE_LINK_WHEN_NO_DETAIL" => "N", "PARENT_SECTION" => "", "PARENT_SECTION_CODE" => "", "INCLUDE_SUBSECTIONS" => "Y", "DISPLAY_DATE" => "Y", "DISPLAY_NAME" => "Y", "DISPLAY_PICTURE" => "Y", "DISPLAY_PREVIEW_TEXT" => "Y", "PAGER_TEMPLATE" => ".default", "DISPLAY_TOP_PAGER" => "N", "DISPLAY_BOTTOM_PAGER" => "Y", "PAGER_TITLE" => "Страницы", "PAGER_SHOW_ALWAYS" => "N", "PAGER_DESC_NUMBERING" => "N", "PAGER_DESC_NUMBERING_CACHE_TIME" => "36000", "PAGER_SHOW_ALL" => "Y", "SET_BROWSER_TITLE" => "Y", "SET_META_KEYWORDS" => "Y", "SET_META_DESCRIPTION" => "Y", "AJAX_OPTION_ADDITIONAL" => "" ), false );?> <?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?>
gpl-3.0
D-K-E/PySesh
pysesh/core/modules/TextOperations/MDCParser/Constants/TextDirection.py
805
################################## # constants taken from the jsesh # ################################ # original author: Serge Rosmorduc # python author: Kaan Eraslan # license: GPL-3, see LICENSE # No Warranty # # Note: Explanations in the docstrings are for the most part taken # from java source files ################################### class TextDirection(object): "Toggle Type as enum class" LEFT_TO_RIGHT = "LEFT_TO_RIGHT" RIGHT_TO_LEFT = "RIGHT_TO_LEFT" # def __init__(self, text_direction: str ) -> None: "Constructor" self.text_direction = text_direction # return None # def isLeftToRight(self) -> bool: "Left to Right check" return bool(self.text_direction == TextDirection.LEFT_TO_RIGHT)
gpl-3.0
MeteorAdminz/dnSpy
Extensions/dnSpy.BamlDecompiler/Handlers/Records/PropertyWithConverterHandler.cs
1299
/* Copyright (c) 2015 Ki Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using dnSpy.BamlDecompiler.Baml; namespace dnSpy.BamlDecompiler.Handlers { internal class PropertyWithConverterHandler : PropertyHandler, IHandler { BamlRecordType IHandler.Type => BamlRecordType.PropertyWithConverter; } }
gpl-3.0
kevinnewesil/Grades2Show
protected/controllers/SubjectController.php
4293
<?php class SubjectController extends Controller { /** * @var string the default layout for the views. Defaults to '//layouts/column2', meaning * using two-column layout. See 'protected/views/layouts/column2.php'. */ public $layout='//layouts/column2'; /** * @return array action filters */ public function filters() { return array( 'accessControl', // perform access control for CRUD operations ); } /** * Specifies the access control rules. * This method is used by the 'accessControl' filter. * @return array access control rules */ public function accessRules() { return array( array('allow', // allow all users to perform 'index' and 'view' actions 'actions'=>array('index','view'), 'users'=>array('*'), ), array('allow', // allow authenticated user to perform 'create' and 'update' actions 'actions'=>array('create','update'), 'users'=>array('@'), ), array('allow', // allow admin user to perform 'admin' and 'delete' actions 'actions'=>array('admin','delete'), 'users'=>array('admin'), ), array('deny', // deny all users 'users'=>array('*'), ), ); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { $this->render('view',array( 'model'=>$this->loadModel($id), )); } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model=new Subject; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Subject'])) { $model->attributes=$_POST['Subject']; if($model->save()) $this->redirect(array('view','id'=>$model->subjectId)); } $this->render('create',array( 'model'=>$model, )); } /** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model=$this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Subject'])) { $model->attributes=$_POST['Subject']; if($model->save()) $this->redirect(array('view','id'=>$model->subjectId)); } $this->render('update',array( 'model'=>$model, )); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete($id) { if(Yii::app()->request->isPostRequest) { // we only allow deletion via POST request $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if(!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin')); } else throw new CHttpException(400,'Invalid request. Please do not repeat this request again.'); } /** * Lists all models. */ public function actionIndex() { $dataProvider=new CActiveDataProvider('Subject'); $this->render('index',array( 'dataProvider'=>$dataProvider, )); } /** * Manages all models. */ public function actionAdmin() { $model=new Subject('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['Subject'])) $model->attributes=$_GET['Subject']; $this->render('admin',array( 'model'=>$model, )); } /** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model=Subject::model()->findByPk($id); if($model===null) throw new CHttpException(404,'The requested page does not exist.'); return $model; } /** * Performs the AJAX validation. * @param CModel the model to be validated */ protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='subject-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } }
gpl-3.0
TotalFreedom/TF-Essentials
Essentials/src/com/earth2me/essentials/utils/FormatUtil.java
4598
package com.earth2me.essentials.utils; import java.util.regex.Pattern; import net.ess3.api.IUser; public class FormatUtil { //Vanilla patterns used to strip existing formats static final transient Pattern VANILLA_PATTERN = Pattern.compile("\u00a7+[0-9A-FK-ORa-fk-or]?"); static final transient Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00a7+[0-9A-Fa-f]"); static final transient Pattern VANILLA_MAGIC_PATTERN = Pattern.compile("\u00a7+[Kk]"); static final transient Pattern VANILLA_FORMAT_PATTERN = Pattern.compile("\u00a7+[L-ORl-or]"); //Essentials '&' convention colour codes static final transient Pattern REPLACE_ALL_PATTERN = Pattern.compile("(?<!&)&([0-9a-fk-orA-FK-OR])"); static final transient Pattern REPLACE_COLOR_PATTERN = Pattern.compile("(?<!&)&([0-9a-fA-F])"); static final transient Pattern REPLACE_MAGIC_PATTERN = Pattern.compile("(?<!&)&([Kk])"); static final transient Pattern REPLACE_FORMAT_PATTERN = Pattern.compile("(?<!&)&([l-orL-OR])"); static final transient Pattern REPLACE_PATTERN = Pattern.compile("&&(?=[0-9a-fk-orA-FK-OR])"); //Used to prepare xmpp output static final transient Pattern LOGCOLOR_PATTERN = Pattern.compile("\\x1B\\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]"); static final transient Pattern URL_PATTERN = Pattern.compile("((?:(?:https?)://)?[\\w-_\\.]{2,})\\.([a-zA-Z]{2,3}(?:/\\S+)?)"); public static final Pattern IPPATTERN = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); //This method is used to simply strip the native minecraft colour codes public static String stripFormat(final String input) { if (input == null) { return null; } return stripColor(input, VANILLA_PATTERN); } //This method is used to simply strip the & convention colour codes public static String stripEssentialsFormat(final String input) { if (input == null) { return null; } return stripColor(input, REPLACE_ALL_PATTERN); } //This is the general permission sensitive message format function, checks for urls. public static String formatMessage(final IUser user, final String permBase, final String input) { if (input == null) { return null; } String message = formatString(user, permBase, input); if (!user.isAuthorized(permBase + ".url")) { message = FormatUtil.blockURL(message); } return message; } //This method is used to simply replace the ess colour codes with minecraft ones, ie &c public static String replaceFormat(final String input) { if (input == null) { return null; } return replaceColor(input, REPLACE_ALL_PATTERN); } static String replaceColor(final String input, final Pattern pattern) { return REPLACE_PATTERN.matcher(pattern.matcher(input).replaceAll("\u00a7$1")).replaceAll("&"); } //This is the general permission sensitive message format function, does not touch urls. public static String formatString(final IUser user, final String permBase, final String input) { if (input == null) { return null; } String message; if (user.isAuthorized(permBase + ".color") || user.isAuthorized(permBase + ".colour")) { message = replaceColor(input, REPLACE_COLOR_PATTERN); } else { message = stripColor(input, VANILLA_COLOR_PATTERN); } if (user.isAuthorized(permBase + ".magic")) { message = replaceColor(message, REPLACE_MAGIC_PATTERN); } else { message = stripColor(message, VANILLA_MAGIC_PATTERN); } if (user.isAuthorized(permBase + ".format")) { message = replaceColor(message, REPLACE_FORMAT_PATTERN); } else { message = stripColor(message, VANILLA_FORMAT_PATTERN); } return message; } public static String stripLogColorFormat(final String input) { if (input == null) { return null; } return stripColor(input, LOGCOLOR_PATTERN); } static String stripColor(final String input, final Pattern pattern) { return pattern.matcher(input).replaceAll(""); } public static String lastCode(final String input) { int pos = input.lastIndexOf('\u00a7'); if (pos == -1 || (pos + 1) == input.length()) { return ""; } return input.substring(pos, pos + 2); } static String blockURL(final String input) { if (input == null) { return null; } String text = URL_PATTERN.matcher(input).replaceAll("$1 $2"); while (URL_PATTERN.matcher(text).find()) { text = URL_PATTERN.matcher(text).replaceAll("$1 $2"); } return text; } public static boolean validIP(String ipAddress) { return IPPATTERN.matcher(ipAddress).matches(); } }
gpl-3.0
115ek/androidclient
app/src/main/java/org/kontalk/ui/view/MessageItemTextView.java
2442
/* * Kontalk Android client * Copyright (C) 2018 Kontalk Devteam <[email protected]> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.ui.view; import android.content.Context; import android.text.Layout; import android.util.AttributeSet; import android.widget.TextView; /** * Text view for text message content. Used by {@link TextContentView}. * @author Daniele Ricci */ public class MessageItemTextView extends TextView { public MessageItemTextView(Context context) { super(context); } public MessageItemTextView(Context context, AttributeSet attrs) { super(context, attrs); } public MessageItemTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /* * Hack for fixing extra space took by the TextView. * I still have to understand why this works and plain getWidth() doesn't. * http://stackoverflow.com/questions/7439748/why-is-wrap-content-in-multiple-line-textview-filling-parent */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); Layout layout = getLayout(); if (layout != null) { int width = (int) Math.ceil(getMaxLineWidth(layout)) + getCompoundPaddingLeft() + getCompoundPaddingRight(); int height = getMeasuredHeight(); setMeasuredDimension(width, height); } } private float getMaxLineWidth(Layout layout) { float max_width = 0.0f; int lines = layout.getLineCount(); for (int i = 0; i < lines; i++) { if (layout.getLineWidth(i) > max_width) { max_width = layout.getLineWidth(i); } } return max_width; } }
gpl-3.0
PHPBoost/PHPBoost
admin/cache/controllers/AdminCacheController.class.php
1620
<?php /** * @copyright &copy; 2005-2022 PHPBoost * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPL-3.0 * @author Benoit SAUTEL <[email protected]> * @version PHPBoost 6.0 - last update: 2021 12 04 * @since PHPBoost 2.0 - 2008 08 05 * @contributor Julien BRISWALTER <[email protected]> * @contributor Sebastien LARTIGUE <[email protected]> */ class AdminCacheController extends DefaultAdminController { public function execute(HTTPRequestCustom $request) { $this->build_form(); if ($this->submit_button->has_been_submited() && $this->form->validate()) { $this->handle_submit(); $this->view->put('MESSAGE_HELPER', MessageHelper::display($this->lang['warning.process.success'], MessageHelper::SUCCESS, 5)); } $this->view->put('CONTENT', $this->form->display()); return new AdminCacheMenuDisplayResponse($this->view, $this->lang['admin.cache']); } protected function build_form() { $form = new HTMLForm(__CLASS__); $fieldset = new FormFieldsetHTML('cache', $this->lang['admin.cache']); $form->add_fieldset($fieldset); $fieldset->add_field(new FormFieldHTML('explain', $this->lang['admin.cache.data.description'], array('class' => 'full-field') )); $this->submit_button = new FormButtonSubmit($this->lang['admin.clear.cache'], 'button'); $form->add_button($this->submit_button); $this->form = $form; } protected function handle_submit() { AppContext::get_cache_service()->clear_cache(); HtaccessFileCache::regenerate(); NginxFileCache::regenerate(); } } ?>
gpl-3.0
PavelLoparev/design-patterns
src/Composite/MenuItem.php
637
<?php /** * @file * MenuItem.php. */ namespace Patterns\Composite; /** * Class MenuItem. * * @package Patterns\Composite */ class MenuItem extends BaseMenuComponent { /** * @var string */ private $name = ''; /** * MenuItem constructor. * @param $name */ public function __construct($name) { $this->name = $name; } /** * @return string */ public function getName() { return $this->name; } /** * @param int $level * * @return string */ public function printMenu($level = 0) { return $item = str_repeat(' ', $level) . '- ' . $this->getName() . PHP_EOL; } }
gpl-3.0
smartstoreag/SmartStoreNET
src/Tests/SmartStore.Data.Tests/Directory/CountryPersistenceTests.cs
2498
using System.Linq; using NUnit.Framework; using SmartStore.Core.Domain.Directory; using SmartStore.Tests; namespace SmartStore.Data.Tests.Directory { [TestFixture] public class CountryPersistenceTests : PersistenceTest { [Test] public void Can_save_and_load_country() { var country = new Country { Name = "United States", AllowsBilling = true, AllowsShipping = true, TwoLetterIsoCode = "US", ThreeLetterIsoCode = "USA", NumericIsoCode = 1, SubjectToVat = true, Published = true, DisplayOrder = 1, LimitedToStores = true }; var fromDb = SaveAndLoadEntity(country); fromDb.ShouldNotBeNull(); fromDb.Name.ShouldEqual("United States"); fromDb.AllowsBilling.ShouldEqual(true); fromDb.AllowsShipping.ShouldEqual(true); fromDb.TwoLetterIsoCode.ShouldEqual("US"); fromDb.ThreeLetterIsoCode.ShouldEqual("USA"); fromDb.NumericIsoCode.ShouldEqual(1); fromDb.SubjectToVat.ShouldEqual(true); fromDb.Published.ShouldEqual(true); fromDb.DisplayOrder.ShouldEqual(1); fromDb.LimitedToStores.ShouldEqual(true); } [Test] public void Can_save_and_load_country_with_states() { var country = new Country { Name = "United States", AllowsBilling = true, AllowsShipping = true, TwoLetterIsoCode = "US", ThreeLetterIsoCode = "USA", NumericIsoCode = 1, SubjectToVat = true, Published = true, DisplayOrder = 1 }; country.StateProvinces.Add ( new StateProvince { Name = "California", Abbreviation = "CA", DisplayOrder = 1 } ); var fromDb = SaveAndLoadEntity(country); fromDb.ShouldNotBeNull(); fromDb.Name.ShouldEqual("United States"); fromDb.StateProvinces.ShouldNotBeNull(); (fromDb.StateProvinces.Count == 1).ShouldBeTrue(); fromDb.StateProvinces.First().Name.ShouldEqual("California"); } } }
gpl-3.0
rstuven/last-horizonte
src/LastHorizonte.App/Model/CheckedMenuItemParams.cs
469
using System; namespace LastHorizonte { internal class CheckedMenuItemParams : IMenuItemParams { public string Text { get; set; } public CheckedMenuItemEventHandler Handler { get; set; } public OpeningHanlder OpeningHandler { get; set; } } internal delegate void CheckedMenuItemEventHandler(object sender, CheckedMenuItemEventArgs args); internal class CheckedMenuItemEventArgs : EventArgs { public bool Checked { get; set; } } }
gpl-3.0
gruppo6/php
assets/pages/scripts/table-datatables-buttons.js
14149
var TableDatatablesButtons = function () { var initTable1 = function () { var table = $('#sample_1'); var oTable = table.dataTable({ // Internationalisation. For more info refer to http://datatables.net/manual/i18n "language": { "aria": { "sortAscending": ": activate to sort column ascending", "sortDescending": ": activate to sort column descending" }, "emptyTable": "Nessun dato disponibile", "info": "Mostro da _START_ a _END_ di _TOTAL_ records totali", "infoEmpty": "Nessun record trovato", "infoFiltered": "(filtered1 from _MAX_ total entries)", "lengthMenu": "_MENU_ entries", "search": "Cerca:", "zeroRecords": "No matching records found" }, // Or you can use remote translation file //"language": { // url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json' //}, buttons: [ { extend: 'print', className: 'btn dark btn-outline' }, { extend: 'copy', className: 'btn red btn-outline' }, { extend: 'pdf', className: 'btn green btn-outline' }, { extend: 'excel', className: 'btn yellow btn-outline ' }, { extend: 'csv', className: 'btn purple btn-outline ' }, { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'} ], // setup responsive extension: http://datatables.net/extensions/responsive/ responsive: true, //"ordering": false, disable column ordering //"paging": false, disable pagination "order": [ [0, 'asc'] ], "lengthMenu": [ [5, 10, 15, 20, -1], [5, 10, 15, 20, "All"] // change per page values here ], // set the initial value "pageLength": 10, "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js). // So when dropdowns used the scrollable div should be removed. //"dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", }); } var initTable2 = function () { var table = $('#sample_2'); var oTable = table.dataTable({ // Internationalisation. For more info refer to http://datatables.net/manual/i18n "language": { "aria": { "sortAscending": ": activate to sort column ascending", "sortDescending": ": activate to sort column descending" }, "emptyTable": "Nessun dato disponibile", "info": "Mostro da _START_ a _END_ di _TOTAL_ records totali", "infoEmpty": "Nessun record trovato", "infoFiltered": "(filtered1 from _MAX_ total entries)", "lengthMenu": "_MENU_ entries", "search": "Cerca:", "zeroRecords": "No matching records found" }, // Or you can use remote translation file //"language": { // url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json' //}, buttons: [ { extend: 'print', className: 'btn default' }, { extend: 'copy', className: 'btn default' }, { extend: 'pdf', className: 'btn default' }, { extend: 'excel', className: 'btn default' }, { extend: 'csv', className: 'btn default' }, { text: 'Reload', className: 'btn default', action: function ( e, dt, node, config ) { //dt.ajax.reload(); alert('Custom Button'); } } ], "order": [ [0, 'asc'] ], "lengthMenu": [ [5, 10, 15, 20, -1], [5, 10, 15, 20, "All"] // change per page values here ], // set the initial value "pageLength": 10, "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js). // So when dropdowns used the scrollable div should be removed. //"dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", }); } var initTable3 = function () { var table = $('#sample_3'); var oTable = table.dataTable({ // Internationalisation. For more info refer to http://datatables.net/manual/i18n "language": { "aria": { "sortAscending": ": activate to sort column ascending", "sortDescending": ": activate to sort column descending" }, "emptyTable": "Nessun dato disponibile", "info": "Mostro da _START_ a _END_ di _TOTAL_ records totali", "infoEmpty": "Nessun record trovato", "infoFiltered": "(filtered1 from _MAX_ total entries)", "lengthMenu": "_MENU_ entries", "search": "Cerca:", "zeroRecords": "No matching records found" }, // Or you can use remote translation file //"language": { // url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json' //}, buttons: [ { extend: 'print', className: 'btn dark btn-outline' }, { extend: 'copy', className: 'btn red btn-outline' }, { extend: 'pdf', className: 'btn green btn-outline' }, { extend: 'excel', className: 'btn yellow btn-outline ' }, { extend: 'csv', className: 'btn purple btn-outline ' }, { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'} ], // setup responsive extension: http://datatables.net/extensions/responsive/ responsive: true, //"ordering": false, disable column ordering //"paging": false, disable pagination "order": [ [0, 'asc'] ], "lengthMenu": [ [5, 10, 15, 20, -1], [5, 10, 15, 20, "All"] // change per page values here ], // set the initial value "pageLength": 10, //"dom": "<'row' <'col-md-12'>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js). // So when dropdowns used the scrollable div should be removed. //"dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", }); // handle datatable custom tools $('#sample_3_tools > li > a.tool-action').on('click', function() { var action = $(this).attr('data-action'); oTable.DataTable().button(action).trigger(); }); } var initAjaxDatatables = function () { //init date pickers $('.date-picker').datepicker({ rtl: App.isRTL(), autoclose: true }); var grid = new Datatable(); grid.init({ src: $("#datatable_ajax"), onSuccess: function (grid, response) { // grid: grid object // response: json object of server side ajax response // execute some code after table records loaded }, onError: function (grid) { // execute some code on network or other general error }, onDataLoad: function(grid) { // execute some code on ajax data load }, loadingMessage: 'Loading...', dataTable: { // here you can define a typical datatable settings from http://datatables.net/usage/options // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/scripts/datatable.js). // So when dropdowns used the scrollable div should be removed. //"dom": "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r>t<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>>", "bStateSave": true, // save datatable state(pagination, sort, etc) in cookie. "lengthMenu": [ [10, 20, 50, 100, 150, -1], [10, 20, 50, 100, 150, "All"] // change per page values here ], "pageLength": 10, // default record count per page "ajax": { "url": "../demo/table_ajax.php", // ajax source }, "order": [ [1, "asc"] ],// set first column as a default sort by asc // Or you can use remote translation file //"language": { // url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json' //}, buttons: [ { extend: 'print', className: 'btn default' }, { extend: 'copy', className: 'btn default' }, { extend: 'pdf', className: 'btn default' }, { extend: 'excel', className: 'btn default' }, { extend: 'csv', className: 'btn default' }, { text: 'Reload', className: 'btn default', action: function ( e, dt, node, config ) { dt.ajax.reload(); alert('Datatable reloaded!'); } } ], } }); // handle group actionsubmit button click grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) { e.preventDefault(); var action = $(".table-group-action-input", grid.getTableWrapper()); if (action.val() != "" && grid.getSelectedRowsCount() > 0) { grid.setAjaxParam("customActionType", "group_action"); grid.setAjaxParam("customActionName", action.val()); grid.setAjaxParam("id", grid.getSelectedRows()); grid.getDataTable().ajax.reload(); grid.clearAjaxParams(); } else if (action.val() == "") { App.alert({ type: 'danger', icon: 'warning', message: 'Please select an action', container: grid.getTableWrapper(), place: 'prepend' }); } else if (grid.getSelectedRowsCount() === 0) { App.alert({ type: 'danger', icon: 'warning', message: 'No record selected', container: grid.getTableWrapper(), place: 'prepend' }); } }); //grid.setAjaxParam("customActionType", "group_action"); //grid.getDataTable().ajax.reload(); //grid.clearAjaxParams(); // handle datatable custom tools $('#datatable_ajax_tools > li > a.tool-action').on('click', function() { var action = $(this).attr('data-action'); grid.getDataTable().button(action).trigger(); }); } return { //main function to initiate the module init: function () { if (!jQuery().dataTable) { return; } initTable1(); initTable2(); initTable3(); initAjaxDatatables(); } }; }(); jQuery(document).ready(function() { TableDatatablesButtons.init(); });
gpl-3.0
timvisee/SafeCreeper
src/main/java/com/timvisee/safecreeper/command/CommandInstallUpdate.java
3441
package com.timvisee.safecreeper.command; import com.timvisee.safecreeper.SafeCreeper; import com.timvisee.safecreeper.handler.SCUpdatesHandler; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class CommandInstallUpdate { public static boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(commandLabel.equalsIgnoreCase("safecreeper") || commandLabel.equalsIgnoreCase("sc")) { if(args.length == 0) { sender.sendMessage(ChatColor.DARK_RED + "Unknown command!"); sender.sendMessage(ChatColor.YELLOW + "Use " + ChatColor.GOLD + "/" + commandLabel + " help " + ChatColor.YELLOW + "to view help"); return true; } if(args[0].equalsIgnoreCase("installupdate") || args[0].equalsIgnoreCase("installupdates")) { // Check wrong command values if(args.length != 1) { sender.sendMessage(ChatColor.DARK_RED + "Wrong command values!"); sender.sendMessage(ChatColor.YELLOW + "Use " + ChatColor.GOLD + "/" + commandLabel + " help " + ChatColor.YELLOW + "to view help"); return true; } // Check permission if(sender instanceof Player) { if(!SafeCreeper.instance.getPermissionsManager().hasPermission((Player) sender, "safecreeper.command.installupdate")) { sender.sendMessage(ChatColor.DARK_RED + "You don't have permission!"); return true; } } // Setup permissions sender.sendMessage(ChatColor.YELLOW + "[SafeCreeper] Checking for updates..."); // Get the update checker and refresh the updates data SCUpdatesHandler uc = SafeCreeper.instance.getUpdatesHandler(); uc.refreshBukkitUpdatesFeedData(); // Check if any update exists if(uc.isUpdateAvailable(true)) { final String newVer = uc.getNewestVersion(true); if(uc.isUpdateDownloaded()) sender.sendMessage(ChatColor.YELLOW + "[SafeCreeper] New version already downloaded (v" + String.valueOf(newVer) + "). Server reload required!"); else { sender.sendMessage(ChatColor.YELLOW + "[SafeCreeper] Downloading new version (v" + String.valueOf(newVer) + ")"); uc.downloadUpdate(); sender.sendMessage(ChatColor.YELLOW + "[SafeCreeper] Update downloaded, server reload required!"); } } else if(uc.isUpdateAvailable(false)) { final String newVer = uc.getNewestVersion(false); sender.sendMessage(ChatColor.YELLOW + "[SafeCreeper] New incompatible Safe Creeper version available: v" + String.valueOf(newVer)); sender.sendMessage(ChatColor.YELLOW + "[SafeCreeper] Please update CraftBukkit to the latest available version!"); } else { sender.sendMessage(ChatColor.YELLOW + "[SafeCreeper] No Safe Creeper update available!"); } return true; } } return false; } }
gpl-3.0
leonindy/camel
camel-admin/src/main/java/com/dianping/phoenix/lb/utils/Md5sumUtil.java
1296
package com.dianping.phoenix.lb.utils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * dianping.com @2015 * slb - soft load balance * <p/> * Created by leon.li(Li Yang) */ public class Md5sumUtil { private Md5sumUtil() { } //根据String生成SHA-1字符串 public static String md5sum(String str) { try { return md5sum(str.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) { return null; } } //根据bytes生成SHA-1字符串 private static String md5sum(byte[] bytes) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("md5"); byte[] byteDigest = md.digest(bytes); ret = byteToString(byteDigest); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return ret; } //将bytes转化为String private static String byteToString(byte[] digest) { String tmpStr = ""; StringBuffer strBuf = new StringBuffer(40); for (int i = 0; i < digest.length; i++) { tmpStr = (Integer.toHexString(digest[i] & 0xff)); if (tmpStr.length() == 1) { strBuf.append("0" + tmpStr); } else { strBuf.append(tmpStr); } } return strBuf.toString(); } }
gpl-3.0
dev-mansonthomas/RedCrossQuest
server/src/DBService/YearlyGoalDBService.php
6214
<?php namespace RedCrossQuest\DBService; use Exception; use PDOException; use RedCrossQuest\Entity\YearlyGoalEntity; class YearlyGoalDBService extends DBService { /** * Get all goals for UL $ulId and a particular year * * @param int $ulId The ID of the Unite Locale * @param string $year The year for which we wants the yearly goals * @return YearlyGoalEntity The YearlyGoalEntity * @throws PDOException if the query fails to execute on the server * @throws Exception in other situations, possibly : parsing error in the entity */ public function getYearlyGoals(int $ulId, string $year):?YearlyGoalEntity { $sql = " SELECT y.`id`, y.`ul_id`, y.`year`, y.`amount`, y.`day_1_percentage`, y.`day_2_percentage`, y.`day_3_percentage`, y.`day_4_percentage`, y.`day_5_percentage`, y.`day_6_percentage`, y.`day_7_percentage`, y.`day_8_percentage`, y.`day_9_percentage` FROM `yearly_goal` AS y WHERE y.ul_id = :ul_id AND y.year = :year "; $parameters = ["ul_id" => $ulId, "year" => $year]; /** @noinspection PhpIncompatibleReturnTypeInspection */ return $this->executeQueryForObject($sql, $parameters, function($row) { return new YearlyGoalEntity($row, $this->logger); }, false); } /** * update a yearly goal * @param YearlyGoalEntity $yearlyGoalEntity info about the dailyStats * @param int $ulId Id of the UL of the user (from JWT Token, to be sure not to update other UL data) * @throws PDOException if the query fails to execute on the server * @throws Exception */ public function update(YearlyGoalEntity $yearlyGoalEntity, int $ulId):void { $sql =" update `yearly_goal` set `amount` = :amount, `day_1_percentage` = :day_1_percentage, `day_2_percentage` = :day_2_percentage, `day_3_percentage` = :day_3_percentage, `day_4_percentage` = :day_4_percentage, `day_5_percentage` = :day_5_percentage, `day_6_percentage` = :day_6_percentage, `day_7_percentage` = :day_7_percentage, `day_8_percentage` = :day_8_percentage, `day_9_percentage` = :day_9_percentage where `id` = :id AND `ul_id` = :ulId "; $parameters = [ "amount" => $yearlyGoalEntity->amount, "day_1_percentage" => $yearlyGoalEntity->day_1_percentage, "day_2_percentage" => $yearlyGoalEntity->day_2_percentage, "day_3_percentage" => $yearlyGoalEntity->day_3_percentage, "day_4_percentage" => $yearlyGoalEntity->day_4_percentage, "day_5_percentage" => $yearlyGoalEntity->day_5_percentage, "day_6_percentage" => $yearlyGoalEntity->day_6_percentage, "day_7_percentage" => $yearlyGoalEntity->day_7_percentage, "day_8_percentage" => $yearlyGoalEntity->day_8_percentage, "day_9_percentage" => $yearlyGoalEntity->day_9_percentage, "id" => $yearlyGoalEntity->id, "ulId" => $ulId ]; $this->executeQueryForUpdate($sql, $parameters); } /** * Create a year of goal * * @param int $ulId Id of the UL for which we create the data * @param string $year year to create * @throws PDOException if the query fails to execute on the server * @throws Exception */ public function createYear(int $ulId, string $year):void { $sql = " INSERT INTO `yearly_goal` ( `ul_id`, `year`, `amount`, `day_1_percentage`, `day_2_percentage`, `day_3_percentage`, `day_4_percentage`, `day_5_percentage`, `day_6_percentage`, `day_7_percentage`, `day_8_percentage`, `day_9_percentage` ) VALUES ( :ul_id, :year, :amount, :day_1_percentage, :day_2_percentage, :day_3_percentage, :day_4_percentage, :day_5_percentage, :day_6_percentage, :day_7_percentage, :day_8_percentage, :day_9_percentage ) "; $parameters = [ "ul_id" => $ulId, "year" => $year, "amount" => 0, "day_1_percentage" => 30, "day_2_percentage" => 15, "day_3_percentage" => 6, "day_4_percentage" => 4, "day_5_percentage" => 6, "day_6_percentage" => 6, "day_7_percentage" => 8, "day_8_percentage" => 15, "day_9_percentage" => 10 ]; $this->executeQueryForInsert($sql, $parameters, false); } /** * Get the current number of YearlyGoals recorded for this year for the Unite Local * * @param int $ulId Id of the UL of the user (from JWT Token, to be sure not to update other UL data) * @return int the number of dailyStats * @throws PDOException if the query fails to execute on the server * @throws Exception */ public function getNumberOfYearlyGoals(int $ulId):int { $sql=" SELECT 1 FROM yearly_goal WHERE ul_id = :ul_id AND year = year(now()) "; $parameters = ["ul_id" => $ulId]; return $this->getCountForSQLQuery($sql, $parameters); } /** * Get all goals for UL $ulId (and if specified, a particular year, all if not) * * @param int $ulId The ID of the Unite Locale * @param string $year The year for which we wants the yearly goals * @return YearlyGoalEntity[] The YearlyGoalEntity * @throws PDOException if the query fails to execute on the server * @throws Exception in other situations, possibly : parsing error in the entity */ public function getYearlyGoalsForExportData(int $ulId, ?string $year):array { $parameters = ["ul_id" => $ulId]; $yearSQL=""; if($year != null) { $yearSQL="AND y.year = :year"; $parameters["year"] = $year; } $sql = " SELECT y.`id`, y.`ul_id`, y.`year`, y.`amount`, y.`day_1_percentage`, y.`day_2_percentage`, y.`day_3_percentage`, y.`day_4_percentage`, y.`day_5_percentage`, y.`day_6_percentage`, y.`day_7_percentage`, y.`day_8_percentage`, y.`day_9_percentage` FROM `yearly_goal` AS y WHERE y.ul_id = :ul_id $yearSQL ORDER BY y.id ASC "; return $this->executeQueryForArray($sql, $parameters, function($row) { return new YearlyGoalEntity($row, $this->logger); }); } }
gpl-3.0
shadowmage45/AncientWarfare2
src/main/java/net/shadowmage/ancientwarfare/npc/command/CommandDebugAI.java
1590
package net.shadowmage.ancientwarfare.npc.command; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.command.WrongUsageException; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.TextComponentTranslation; import net.shadowmage.ancientwarfare.core.gamedata.AWGameData; import net.shadowmage.ancientwarfare.core.gamedata.WorldData; import net.shadowmage.ancientwarfare.npc.config.AWNPCStatics; public class CommandDebugAI extends CommandBase { private int permissionLevel = 2; @Override public String getName() { return "awnpcdebug"; } @Override public String getUsage(ICommandSender var1) { return "command.aw.npcdebug.usage"; } @Override public void execute(MinecraftServer server, ICommandSender var1, String[] var2) throws CommandException { AWNPCStatics.npcAIDebugMode = !AWNPCStatics.npcAIDebugMode; WorldData d = AWGameData.INSTANCE.getPerWorldData(var1.getEntityWorld(), WorldData.class); if (d == null) { throw new WrongUsageException("Couldn't find or build relevant data"); } d.set("NpcAIDebugMode", AWNPCStatics.npcAIDebugMode); var1.sendMessage(new TextComponentTranslation("command.aw.npcdebug.used")); } @Override public boolean checkPermission(MinecraftServer server, ICommandSender sender) { return sender.canUseCommand(this.permissionLevel, this.getName()); } @Override public boolean isUsernameIndex(String[] var1, int var2) { return false; } }
gpl-3.0
Dqiyue/QT
test/mainwindow.cpp
358
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QLabel> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QLabel *label = new QLabel(this); label->setText("hello world"); label->setGeometry(QRect(100,100,200,125)); } MainWindow::~MainWindow() { delete ui; }
gpl-3.0
eyesniper2/skRayFall
src/main/java/net/rayfall/eyesniper2/skrayfall/citizens/expressions/ExprOwnerOfCitizen.java
1671
package net.rayfall.eyesniper2.skrayfall.citizens.expressions; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Name; import ch.njol.skript.doc.RequiredPlugins; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import net.citizensnpcs.api.CitizensAPI; import net.citizensnpcs.api.npc.NPC; import net.citizensnpcs.api.npc.NPCRegistry; import net.citizensnpcs.api.trait.trait.Owner; import org.bukkit.event.Event; import org.eclipse.jdt.annotation.Nullable; @Name("Citizen Owner") @Description("Gets the owner of a citizen.") @RequiredPlugins("Citizens") public class ExprOwnerOfCitizen extends SimpleExpression<String> { // owner of npc %number% Expression<Number> id; @Override public Class<? extends String> getReturnType() { return String.class; } @Override public boolean isSingle() { return true; } @SuppressWarnings("unchecked") @Override public boolean init(Expression<?>[] exp, int arg1, Kleenean arg2, ParseResult arg3) { id = (Expression<Number>) exp[0]; return true; } @Override public String toString(@Nullable Event arg0, boolean arg1) { return null; } @Override @Nullable protected String[] get(Event evt) { NPCRegistry registry = CitizensAPI.getNPCRegistry(); NPC npc = registry.getById(id.getSingle(evt).intValue()); if (npc.hasTrait(Owner.class)) { return new String[]{npc.getTrait(Owner.class).getOwner()}; } return new String[]{}; } }
gpl-3.0
Xunius/Trenches
levels/level03/__init__.py
3035
import pygame import os PATH=os.path.dirname(os.path.realpath(__file__)) BACKGROUND_FILE='image_background_1x600x1x800.png' MASKMAP_FILE='image_via_map.png' MINIMAP_FILE='image_minimap_1x600x1x800.png' WEAPONS_IN_LEVEL=[ 'rifle',\ 'machinegun',\ 'grenade',\ 'mortar',\ #'sniper',\ #'flamer',\ #'medi',\ 'artillery',\ #'ammo'\ ] WAVES_IN_LEVEL=[] ENEMY_LIST=[('rifle',4),('machinegun',2),('grenade',3),('mortar',1)] ENEMY_GROUPS=[ENEMY_LIST,ENEMY_LIST,ENEMY_LIST] INTRA_GROUP_PAUSE=2000 INTER_GROUP_PAUSE=10000 ENEMY_AMMO_DICT={ 'rifle':10,\ 'machinegun':40,\ #'sniper':4,\ 'grenade':3,\ 'mortar':2,\ #'artillery':3\ } #----Should be smaller than weapons.max_weapon_ammo-------------------------- PLAYER_AMMO_DICT={ 'rifle':100,\ 'machinegun':250,\ 'grenade':20,\ 'mortar':15,\ 'artillery':15\ } WEATHER='sunny' MONEY=1000 HQ_LIFE=5 LEVEL='03' LEVEL_TITLE='Our 2nd defence line' LEVEL_TEXTS=[\ "Enemies' 2nd front army has broken through our first defence line.", 'We need to react fast and hold our 2nd line. Losing this, they would encircle us from the west and east.',\ ' ',\ 'Mortars and artilleries are even more destructive and far-reaching, making them worth saving for.'\ ] class LevelInfo(object): def __init__(self): self.level=LEVEL self.background_file=BACKGROUND_FILE self.maskmap_file=MASKMAP_FILE self.weapons_in_level=WEAPONS_IN_LEVEL self.background_file=os.path.join(PATH,BACKGROUND_FILE) self.maskmap_file=os.path.join(PATH,MASKMAP_FILE) self.minimap_file=os.path.join(PATH,MINIMAP_FILE) self.weapons_in_level=WEAPONS_IN_LEVEL #----Background for display-------------------------- self.background_image=pygame.image.load(self.background_file).convert() #----Minimap for display-------------------------- self.minimap_image=pygame.image.load(self.minimap_file).convert() #----Mask image for process-------------------------- mask_image=pygame.image.load(self.maskmap_file).convert() self.mask_image=pygame.surfarray.array3d(mask_image) #----Mask image for display-------------------------- #self.mask_background=pygame.image.load(self.maskmap_file).convert() #----Enemy setups-------------------------- self.enemy_groups=ENEMY_GROUPS self.intra_pause=INTRA_GROUP_PAUSE self.inter_pause=INTER_GROUP_PAUSE #----Start up status-------------------------- self.money=MONEY self.hq_life=HQ_LIFE self.weather=WEATHER #----Ammo-------------------------- self.enemy_ammo_dict=ENEMY_AMMO_DICT self.player_ammo_dict=PLAYER_AMMO_DICT #----Info-------------------------- self.title=LEVEL_TITLE self.texts=LEVEL_TEXTS
gpl-3.0