code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
package main
import (
"log"
"fmt"
"net/http"
"io/ioutil"
"encoding/json"
"flag"
"os"
)
var DEBUG = false
var VERSION = "0.01"
func main() {
var ipAddress = flag.String("i", "NULL", "Specify ip address")
var usFlag = flag.Bool("us", false, "Set this flag to alert if IP address is not in the US. Can be used in monitoring scenarios")
var version = flag.Bool("v", false, "Display version")
flag.BoolVar(&DEBUG, "d", false, "Debugging")
flag.Parse()
if *version {
fmt.Printf("%s - Version: %s\n", os.Args[0], VERSION)
os.Exit(0)
}
if *ipAddress == "NULL" {
flag.Usage()
os.Exit(1)
}
url := fmt.Sprintf("http://www.geoplugin.net/json.gp?ip=%s", *ipAddress)
resp, err := http.Get(url)
if err != nil {
log.Fatalf("Couldn't make http connection\n")
}
defer resp.Body.Close()
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
log.Fatalf("Couldn't read body\n")
}
var objmap map[string]*json.RawMessage
err3 := json.Unmarshal(body, &objmap)
if err3 != nil {
log.Fatalf("Error unmarshalling: %s\n", err3)
log.Fatalf("%+v", objmap)
}
// get the contry and country code
var cc string
var cn string
err = json.Unmarshal(*objmap["geoplugin_countryCode"], &cc)
if err != nil {
log.Fatalf("Error: %s\n", err)
}
err = json.Unmarshal(*objmap["geoplugin_countryName"], &cn)
if err != nil {
log.Fatalf("Error: %s\n", err)
}
if *usFlag {
if cc != "US" {
fmt.Printf("IP: %s not in the US\n", *ipAddress)
fmt.Printf(string(body))
} else {
// since we are only alerting if the IP is *not* in the US we will do nothing
}
} else {
fmt.Printf(string(body))
}
}
| zpeters/iptracker | iptracker.go | GO | gpl-3.0 | 1,632 |
package com.cmput301w13t09.cmput301project.helpers;
import java.util.ArrayList;
import java.util.Collection;
import com.cmput301w13t09.cmput301project.helpers.ElasticSearchResponse;
import com.cmput301w13t09.cmput301project.helpers.Hits;
/**
*
* @author Code Originally by Abram Hindle and Chenlei Zhang used by
* Kyle,Marcus, and Lanre https://github.com/rayzhangcl/ESDemo
* ElasticSearchSeacrchResponse is a class used to stores search
* responses from _search.
* @param <T>
*/
public class ElasticSearchSearchResponse<T> {
int took;
boolean timed_out;
transient Object _shards;
Hits<T> hits;
boolean exists;
public Collection<ElasticSearchResponse<T>> getHits() {
return hits.getHits();
}
public Collection<T> getSources() {
Collection<T> out = new ArrayList<T>();
for (ElasticSearchResponse<T> essrt : getHits()) {
out.add( essrt.getSource() );
}
return out;
}
public String toString() {
return (super.toString() + ":" + took + "," + _shards + "," + exists + "," + hits);
}
} | kylejamesross/CMPUT301W13T09 | CMPUT301Project/src/com/cmput301w13t09/cmput301project/helpers/ElasticSearchSearchResponse.java | Java | gpl-3.0 | 1,169 |
webpackJsonpjwplayer([1],{
/***/ 41:
/*!***********************************!*\
!*** ./src/js/providers/html5.js ***!
\***********************************/
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict';
var _dataNormalizer = __webpack_require__(/*! providers/data-normalizer */ 42);
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! providers/html5-android-hls */ 37), __webpack_require__(/*! utils/css */ 16), __webpack_require__(/*! utils/helpers */ 8), __webpack_require__(/*! utils/dom */ 14), __webpack_require__(/*! utils/underscore */ 6), __webpack_require__(/*! events/events */ 32), __webpack_require__(/*! events/states */ 31), __webpack_require__(/*! providers/default */ 35), __webpack_require__(/*! utils/backbone.events */ 29), __webpack_require__(/*! providers/tracks-mixin */ 43), __webpack_require__(/*! utils/time-ranges */ 51)], __WEBPACK_AMD_DEFINE_RESULT__ = function (getIsAndroidHLS, cssUtils, utils, dom, _, events, states, DefaultProvider, Events, Tracks, timeRangesUtil) {
var clearTimeout = window.clearTimeout;
var STALL_DELAY = 256;
var MIN_DVR_DURATION = 120;
var _isIE = utils.isIE();
var _isIE9 = utils.isIE(9);
var _isMobile = utils.isMobile();
var _isFirefox = utils.isFF();
var _isAndroid = utils.isAndroidNative();
var _isIOS7 = utils.isIOS(7);
var _isIOS8 = utils.isIOS(8);
var _name = 'html5';
function _setupListeners(eventsHash, videoTag) {
utils.foreach(eventsHash, function (evt, evtCallback) {
videoTag.addEventListener(evt, evtCallback, false);
});
}
function _removeListeners(eventsHash, videoTag) {
utils.foreach(eventsHash, function (evt, evtCallback) {
videoTag.removeEventListener(evt, evtCallback, false);
});
}
function VideoProvider(_playerId, _playerConfig) {
// Current media state
this.state = states.IDLE;
// Are we buffering due to seek, or due to playback?
this.seeking = false;
_.extend(this, Events, Tracks);
this.renderNatively = renderNatively(_playerConfig.renderCaptionsNatively);
// Always render natively in iOS, Safari and Edge, where HLS is supported.
// Otherwise, use native rendering when set in the config for browsers that have adequate support.
// FF and IE are excluded due to styling/positioning drawbacks.
function renderNatively(configRenderNatively) {
if (utils.isIOS() || utils.isSafari() || utils.isEdge()) {
return true;
}
return configRenderNatively && utils.isChrome();
}
var _this = this;
var _mediaEvents = {
click: _clickHandler,
durationchange: _durationChangeHandler,
ended: _endedHandler,
error: _errorHandler,
loadstart: _onLoadStart,
loadeddata: _onLoadedData, // we have video tracks (text, audio, metadata)
loadedmetadata: _loadedMetadataHandler, // we have video dimensions
canplay: _canPlayHandler,
play: _loading,
playing: _playingHandler,
progress: _progressHandler,
pause: _pauseHandler,
seeking: _seekingHandler,
seeked: _seekedHandler,
timeupdate: _timeUpdateHandler,
ratechange: _playbackRateHandler,
volumechange: _volumeChangeHandler,
webkitbeginfullscreen: _fullscreenBeginHandler,
webkitendfullscreen: _fullscreenEndHandler
};
var _container;
var _duration;
var _position;
var _canSeek = false;
var _bufferFull;
var _delayedSeek = 0;
var _seekOffset = null;
var _playbackTimeout = -1;
var _buffered = -1;
var _levels;
var _currentQuality = -1;
var _isAndroidHLS = null;
var _isSDK = !!_playerConfig.sdkplatform;
var _fullscreenState = false;
var _beforeResumeHandler = utils.noop;
var _audioTracks = null;
var _currentAudioTrackIndex = -1;
var _visualQuality = { level: {} };
var _staleStreamDuration = 3 * 10 * 1000;
var _staleStreamTimeout = null;
var _lastEndOfBuffer = null;
var _stale = false;
var _edgeOfLiveStream = false;
// Find video tag, or create it if it doesn't exist. View may not be built yet.
var element = document.getElementById(_playerId);
var _videotag = element ? element.querySelector('video, audio') : undefined;
function _setAttribute(name, value) {
_videotag.setAttribute(name, value || '');
}
if (!_videotag) {
_videotag = document.createElement('video');
_videotag.load();
if (_isMobile) {
_setAttribute('jw-gesture-required');
}
}
_videotag.className = 'jw-video jw-reset';
this.isSDK = _isSDK;
this.video = _videotag;
this.supportsPlaybackRate = true;
_setupListeners(_mediaEvents, _videotag);
_setAttribute('disableRemotePlayback', '');
_setAttribute('webkit-playsinline');
_setAttribute('playsinline');
// Enable tracks support for HLS videos
function _onLoadedData() {
_setAudioTracks(_videotag.audioTracks);
_this.setTextTracks(_videotag.textTracks);
_setAttribute('jw-loaded', 'data');
}
function _onLoadStart() {
_setAttribute('jw-loaded', 'started');
}
function _clickHandler(evt) {
_this.trigger('click', evt);
}
function _durationChangeHandler() {
if (_isAndroidHLS) {
return;
}
_updateDuration(_getDuration());
_setBuffered(_getBuffer(), _position, _duration);
}
function _progressHandler() {
_setBuffered(_getBuffer(), _position, _duration);
}
function _timeUpdateHandler() {
clearTimeout(_playbackTimeout);
_canSeek = true;
if (_this.state === states.STALLED) {
_this.setState(states.PLAYING);
} else if (_this.state === states.PLAYING) {
_playbackTimeout = setTimeout(_checkPlaybackStalled, STALL_DELAY);
}
// When video has not yet started playing for androidHLS, we cannot get the correct duration
if (_isAndroidHLS && _videotag.duration === Infinity && _videotag.currentTime === 0) {
return;
}
_updateDuration(_getDuration());
_setPosition(_videotag.currentTime);
// buffer ranges change during playback, not just on file progress
_setBuffered(_getBuffer(), _position, _duration);
// send time events when playing
if (_this.state === states.PLAYING) {
_this.trigger(events.JWPLAYER_MEDIA_TIME, {
position: _position,
duration: _duration
});
_checkVisualQuality();
}
}
function _playbackRateHandler() {
_this.trigger('ratechange', { playbackRate: _videotag.playbackRate });
}
function _checkVisualQuality() {
var level = _visualQuality.level;
if (level.width !== _videotag.videoWidth || level.height !== _videotag.videoHeight) {
level.width = _videotag.videoWidth;
level.height = _videotag.videoHeight;
_setMediaType();
if (!level.width || !level.height || _currentQuality === -1) {
return;
}
_visualQuality.reason = _visualQuality.reason || 'auto';
_visualQuality.mode = _levels[_currentQuality].type === 'hls' ? 'auto' : 'manual';
_visualQuality.bitrate = 0;
level.index = _currentQuality;
level.label = _levels[_currentQuality].label;
_this.trigger('visualQuality', _visualQuality);
_visualQuality.reason = '';
}
}
function _setBuffered(buffered, currentTime, duration) {
if (duration !== 0 && (buffered !== _buffered || duration !== _duration)) {
_buffered = buffered;
_this.trigger(events.JWPLAYER_MEDIA_BUFFER, {
bufferPercent: buffered * 100,
position: currentTime,
duration: duration
});
}
checkStaleStream();
}
function _setPosition(currentTime) {
if (_duration < 0) {
currentTime = -(_getSeekableEnd() - currentTime);
}
_position = currentTime;
}
function _getDuration() {
var duration = _videotag.duration;
var end = _getSeekableEnd();
if (duration === Infinity && end) {
var seekableDuration = end - _getSeekableStart();
if (seekableDuration !== Infinity && seekableDuration > MIN_DVR_DURATION) {
// Player interprets negative duration as DVR
duration = -seekableDuration;
}
}
return duration;
}
function _updateDuration(duration) {
_duration = duration;
// Don't seek when _delayedSeek is set to -1 in _completeLoad
if (_delayedSeek && _delayedSeek !== -1 && duration && duration !== Infinity) {
_this.seek(_delayedSeek);
}
}
function _sendMetaEvent() {
var duration = _getDuration();
if (_isAndroidHLS && duration === Infinity) {
duration = 0;
}
_this.trigger(events.JWPLAYER_MEDIA_META, {
duration: duration,
height: _videotag.videoHeight,
width: _videotag.videoWidth
});
_updateDuration(duration);
}
function _canPlayHandler() {
_canSeek = true;
if (!_isAndroidHLS) {
_setMediaType();
}
if (_isIE9) {
// In IE9, set tracks here since they are not ready
// on load
_this.setTextTracks(_this._textTracks);
}
_sendBufferFull();
}
function _loadedMetadataHandler() {
_setAttribute('jw-loaded', 'meta');
_sendMetaEvent();
}
function _sendBufferFull() {
// Wait until the canplay event on iOS to send the bufferFull event
if (!_bufferFull) {
_bufferFull = true;
_this.trigger(events.JWPLAYER_MEDIA_BUFFER_FULL);
}
}
function _playingHandler() {
_this.setState(states.PLAYING);
if (!_videotag.hasAttribute('jw-played')) {
_setAttribute('jw-played', '');
}
if (_videotag.hasAttribute('jw-gesture-required')) {
_videotag.removeAttribute('jw-gesture-required');
}
_this.trigger(events.JWPLAYER_PROVIDER_FIRST_FRAME, {});
}
function _pauseHandler() {
clearTimeouts();
// Sometimes the browser will fire "complete" and then a "pause" event
if (_this.state === states.COMPLETE) {
return;
}
// If "pause" fires before "complete" or before we've started playback, we still don't want to propagate it
if (!_videotag.hasAttribute('jw-played') || _videotag.currentTime === _videotag.duration) {
return;
}
_this.setState(states.PAUSED);
}
function _stalledHandler() {
// Android HLS doesnt update its times correctly so it always falls in here. Do not allow it to stall.
if (_isAndroidHLS) {
return;
}
if (_videotag.paused || _videotag.ended) {
return;
}
// A stall after loading/error, should just stay loading/error
if (_this.state === states.LOADING || _this.state === states.ERROR) {
return;
}
// During seek we stay in paused state
if (_this.seeking) {
return;
}
// Workaround for iOS not completing after midroll with HLS streams
if (utils.isIOS() && _videotag.duration - _videotag.currentTime <= 0.1) {
_endedHandler();
return;
}
if (atEdgeOfLiveStream()) {
_edgeOfLiveStream = true;
if (checkStreamEnded()) {
return;
}
}
_this.setState(states.STALLED);
}
function _errorHandler() {
_this.trigger(events.JWPLAYER_MEDIA_ERROR, {
message: 'Error loading media: File could not be played'
});
}
function _getPublicLevels(levels) {
var publicLevels;
if (utils.typeOf(levels) === 'array' && levels.length > 0) {
publicLevels = _.map(levels, function (level, i) {
return {
label: level.label || i
};
});
}
return publicLevels;
}
function _setLevels(levels) {
_levels = levels;
_currentQuality = _pickInitialQuality(levels);
var publicLevels = _getPublicLevels(levels);
if (publicLevels) {
// _trigger?
_this.trigger(events.JWPLAYER_MEDIA_LEVELS, {
levels: publicLevels,
currentQuality: _currentQuality
});
}
}
function _pickInitialQuality(levels) {
var currentQuality = Math.max(0, _currentQuality);
var label = _playerConfig.qualityLabel;
if (levels) {
for (var i = 0; i < levels.length; i++) {
if (levels[i].default) {
currentQuality = i;
}
if (label && levels[i].label === label) {
return i;
}
}
}
_visualQuality.reason = 'initial choice';
_visualQuality.level = {};
return currentQuality;
}
function _play() {
var promise = _videotag.play();
if (promise && promise.catch) {
promise.catch(function (err) {
if (_videotag.paused) {
// Send a time update to update ads UI
// `isDurationChange` prevents this from propigating an "adTime" event
_this.trigger(events.JWPLAYER_MEDIA_TIME, {
position: _position,
duration: _duration,
isDurationChange: true
});
_this.setState(states.PAUSED);
}
// User gesture required to start playback
if (err.name === 'NotAllowedError') {
console.warn(err);
if (_videotag.hasAttribute('jw-gesture-required')) {
_this.trigger('autoplayFailed');
}
}
});
} else if (_videotag.hasAttribute('jw-gesture-required')) {
// Autoplay isn't supported in older versions of Safari (<10) and Chrome (<53)
_this.trigger('autoplayFailed');
}
}
function _completeLoad(startTime, duration) {
_delayedSeek = 0;
clearTimeouts();
var previousSource = _videotag.src;
var sourceElement = document.createElement('source');
sourceElement.src = _levels[_currentQuality].file;
var sourceChanged = previousSource !== sourceElement.src;
var loadedSrc = _videotag.getAttribute('jw-loaded');
if (sourceChanged || loadedSrc === 'none' || loadedSrc === 'started') {
_duration = duration;
_setVideotagSource(_levels[_currentQuality]);
_this.setupSideloadedTracks(_this._itemTracks);
if (previousSource && sourceChanged) {
_videotag.load();
}
} else {
// Load event is from the same video as before
if (startTime === 0 && _videotag.currentTime > 0) {
// restart video without dispatching seek event
_delayedSeek = -1;
_this.seek(startTime);
}
}
_position = _videotag.currentTime;
if (startTime > 0) {
_this.seek(startTime);
}
_play();
}
function _setVideotagSource(source) {
_audioTracks = null;
_currentAudioTrackIndex = -1;
if (!_visualQuality.reason) {
_visualQuality.reason = 'initial choice';
_visualQuality.level = {};
}
_canSeek = false;
_bufferFull = false;
_isAndroidHLS = getIsAndroidHLS(source);
if (_isAndroidHLS) {
// Playback rate is broken on Android HLS
_this.supportsPlaybackRate = false;
}
if (source.preload && source.preload !== 'none' && source.preload !== _videotag.getAttribute('preload')) {
_setAttribute('preload', source.preload);
}
var sourceElement = document.createElement('source');
sourceElement.src = source.file;
var sourceChanged = _videotag.src !== sourceElement.src;
if (sourceChanged) {
_setAttribute('jw-loaded', 'none');
_videotag.src = source.file;
}
}
function _clearVideotagSource() {
if (_videotag) {
_this.disableTextTrack();
_videotag.removeAttribute('preload');
_videotag.removeAttribute('src');
_videotag.removeAttribute('jw-loaded');
_videotag.removeAttribute('jw-played');
_videotag.pause();
dom.emptyElement(_videotag);
cssUtils.style(_videotag, {
objectFit: ''
});
_currentQuality = -1;
}
}
function _getSeekableStart() {
var index = _videotag.seekable ? _videotag.seekable.length : 0;
var start = Infinity;
while (index--) {
start = Math.min(start, _videotag.seekable.start(index));
}
return start;
}
function _getSeekableEnd() {
var index = _videotag.seekable ? _videotag.seekable.length : 0;
var end = 0;
while (index--) {
end = Math.max(end, _videotag.seekable.end(index));
}
return end;
}
function _loading() {
_this.setState(states.LOADING);
}
this.stop = function () {
clearTimeouts();
_clearVideotagSource();
this.clearTracks();
// IE/Edge continue to play a video after changing video.src and calling video.load()
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/5383483/ (not fixed in Edge 14)
if (utils.isIE()) {
_videotag.pause();
}
this.setState(states.IDLE);
};
this.destroy = function () {
_beforeResumeHandler = utils.noop;
_removeListeners(_mediaEvents, _videotag);
this.removeTracksListener(_videotag.audioTracks, 'change', _audioTrackChangeHandler);
this.removeTracksListener(_videotag.textTracks, 'change', _this.textTrackChangeHandler);
this.remove();
this.off();
};
this.init = function (item) {
_levels = item.sources;
_currentQuality = _pickInitialQuality(item.sources);
// the loadeddata event determines the mediaType for HLS sources
if (item.sources.length && item.sources[0].type !== 'hls') {
this.sendMediaType(item.sources);
}
_position = item.starttime || 0;
_duration = item.duration || 0;
_visualQuality.reason = '';
var source = _levels[_currentQuality];
if (source.preload !== 'none') {
_setVideotagSource(source);
}
this.setupSideloadedTracks(item.tracks);
};
this.load = function (item) {
_setLevels(item.sources);
if (item.sources.length && item.sources[0].type !== 'hls') {
this.sendMediaType(item.sources);
}
if (!_isMobile || _videotag.hasAttribute('jw-played')) {
// don't change state on mobile before user initiates playback
_loading();
}
_completeLoad(item.starttime || 0, item.duration || 0);
};
this.play = function () {
if (_this.seeking) {
_loading();
_this.once(events.JWPLAYER_MEDIA_SEEKED, _this.play);
return;
}
_beforeResumeHandler();
_play();
};
this.pause = function () {
clearTimeouts();
_videotag.pause();
_beforeResumeHandler = function _beforeResumeHandler() {
var unpausing = _videotag.paused && _videotag.currentTime;
if (unpausing && _videotag.duration === Infinity) {
var end = _getSeekableEnd();
var seekableDuration = end - _getSeekableStart();
var isLiveNotDvr = seekableDuration < MIN_DVR_DURATION;
var behindLiveEdge = end - _videotag.currentTime;
if (isLiveNotDvr && end && (behindLiveEdge > 15 || behindLiveEdge < 0)) {
// resume playback at edge of live stream
_seekOffset = Math.max(end - 10, end - seekableDuration);
_setPosition(_videotag.currentTime);
_videotag.currentTime = _seekOffset;
}
}
};
this.setState(states.PAUSED);
};
this.seek = function (seekPos) {
if (seekPos < 0) {
seekPos += _getSeekableStart() + _getSeekableEnd();
}
if (!_canSeek) {
_canSeek = !!_getSeekableEnd();
}
if (_canSeek) {
_delayedSeek = 0;
// setting currentTime can throw an invalid DOM state exception if the video is not ready
try {
_this.seeking = true;
_seekOffset = seekPos;
_setPosition(_videotag.currentTime);
_videotag.currentTime = seekPos;
} catch (e) {
_this.seeking = false;
_delayedSeek = seekPos;
}
} else {
_delayedSeek = seekPos;
// Firefox isn't firing canplay event when in a paused state
// https://bugzilla.mozilla.org/show_bug.cgi?id=1194624
if (_isFirefox && _videotag.paused) {
_play();
}
}
};
function _seekingHandler() {
var offset = _seekOffset !== null ? _seekOffset : _videotag.currentTime;
_seekOffset = null;
_delayedSeek = 0;
_this.seeking = true;
_this.trigger(events.JWPLAYER_MEDIA_SEEK, {
position: _position,
offset: offset
});
}
function _seekedHandler() {
_this.seeking = false;
_this.trigger(events.JWPLAYER_MEDIA_SEEKED);
}
this.volume = function (vol) {
// volume must be 0.0 - 1.0
vol = utils.between(vol / 100, 0, 1);
_videotag.volume = vol;
};
function _volumeChangeHandler() {
_this.trigger('volume', {
volume: Math.round(_videotag.volume * 100)
});
_this.trigger('mute', {
mute: _videotag.muted
});
}
this.mute = function (state) {
_videotag.muted = !!state;
};
function _checkPlaybackStalled() {
// Browsers, including latest chrome, do not always report Stalled events in a timely fashion
if (_videotag.currentTime === _position) {
_stalledHandler();
} else {
_edgeOfLiveStream = false;
}
}
function _getBuffer() {
var buffered = _videotag.buffered;
var duration = _videotag.duration;
if (!buffered || buffered.length === 0 || duration <= 0 || duration === Infinity) {
return 0;
}
return utils.between(buffered.end(buffered.length - 1) / duration, 0, 1);
}
function _endedHandler() {
if (_this.state !== states.IDLE && _this.state !== states.COMPLETE) {
clearTimeouts();
_currentQuality = -1;
_this.trigger(events.JWPLAYER_MEDIA_COMPLETE);
}
}
function _fullscreenBeginHandler(e) {
_fullscreenState = true;
_sendFullscreen(e);
// show controls on begin fullscreen so that they are disabled properly at end
if (utils.isIOS()) {
_videotag.controls = false;
}
}
function _audioTrackChangeHandler() {
var _selectedAudioTrackIndex = -1;
for (var i = 0; i < _videotag.audioTracks.length; i++) {
if (_videotag.audioTracks[i].enabled) {
_selectedAudioTrackIndex = i;
break;
}
}
_setCurrentAudioTrack(_selectedAudioTrackIndex);
}
function _fullscreenEndHandler(e) {
_fullscreenState = false;
_sendFullscreen(e);
if (utils.isIOS()) {
_videotag.controls = false;
}
}
function _sendFullscreen(e) {
_this.trigger('fullscreenchange', {
target: e.target,
jwstate: _fullscreenState
});
}
/**
* Return the video tag and stop listening to events
*/
this.detachMedia = function () {
clearTimeouts();
_removeListeners(_mediaEvents, _videotag);
// Stop listening to track changes so disabling the current track doesn't update the model
this.removeTracksListener(_videotag.textTracks, 'change', this.textTrackChangeHandler);
// Prevent tracks from showing during ad playback
this.disableTextTrack();
return _videotag;
};
/**
* Begin listening to events again
*/
this.attachMedia = function () {
_setupListeners(_mediaEvents, _videotag);
_canSeek = false;
// If we were mid-seek when detached, we want to allow it to resume
this.seeking = false;
// In case the video tag was modified while we shared it
_videotag.loop = false;
// If there was a showing track, re-enable it
this.enableTextTrack();
if (this.renderNatively) {
this.setTextTracks(this.video.textTracks);
}
this.addTracksListener(_videotag.textTracks, 'change', this.textTrackChangeHandler);
};
this.setContainer = function (containerElement) {
_container = containerElement;
containerElement.insertBefore(_videotag, containerElement.firstChild);
};
this.getContainer = function () {
return _container;
};
this.remove = function () {
// stop video silently
_clearVideotagSource();
clearTimeouts();
// remove
if (_container === _videotag.parentNode) {
_container.removeChild(_videotag);
}
};
this.setVisibility = function (state) {
state = !!state;
if (state || _isAndroid) {
// Changing visibility to hidden on Android < 4.2 causes
// the pause event to be fired. This causes audio files to
// become unplayable. Hence the video tag is always kept
// visible on Android devices.
cssUtils.style(_container, {
visibility: 'visible',
opacity: 1
});
} else {
cssUtils.style(_container, {
visibility: '',
opacity: 0
});
}
};
this.resize = function (width, height, stretching) {
if (!width || !height || !_videotag.videoWidth || !_videotag.videoHeight) {
return false;
}
var style = {
objectFit: '',
width: '',
height: ''
};
if (stretching === 'uniform') {
// snap video to edges when the difference in aspect ratio is less than 9%
var playerAspectRatio = width / height;
var videoAspectRatio = _videotag.videoWidth / _videotag.videoHeight;
if (Math.abs(playerAspectRatio - videoAspectRatio) < 0.09) {
style.objectFit = 'fill';
stretching = 'exactfit';
}
}
// Prior to iOS 9, object-fit worked poorly
// object-fit is not implemented in IE or Android Browser in 4.4 and lower
// http://caniuse.com/#feat=object-fit
// feature detection may work for IE but not for browsers where object-fit works for images only
var fitVideoUsingTransforms = _isIE || _isIOS7 || _isIOS8 || _isAndroid && !_isFirefox;
if (fitVideoUsingTransforms) {
// Use transforms to center and scale video in container
var x = -Math.floor(_videotag.videoWidth / 2 + 1);
var y = -Math.floor(_videotag.videoHeight / 2 + 1);
var scaleX = Math.ceil(width * 100 / _videotag.videoWidth) / 100;
var scaleY = Math.ceil(height * 100 / _videotag.videoHeight) / 100;
if (stretching === 'none') {
scaleX = scaleY = 1;
} else if (stretching === 'fill') {
scaleX = scaleY = Math.max(scaleX, scaleY);
} else if (stretching === 'uniform') {
scaleX = scaleY = Math.min(scaleX, scaleY);
}
style.width = _videotag.videoWidth;
style.height = _videotag.videoHeight;
style.top = style.left = '50%';
style.margin = 0;
cssUtils.transform(_videotag, 'translate(' + x + 'px, ' + y + 'px) scale(' + scaleX.toFixed(2) + ', ' + scaleY.toFixed(2) + ')');
}
cssUtils.style(_videotag, style);
return false;
};
this.setFullscreen = function (state) {
state = !!state;
// This implementation is for iOS and Android WebKit only
// This won't get called if the player container can go fullscreen
if (state) {
var status = utils.tryCatch(function () {
var enterFullscreen = _videotag.webkitEnterFullscreen || _videotag.webkitEnterFullScreen;
if (enterFullscreen) {
enterFullscreen.apply(_videotag);
}
});
if (status instanceof utils.Error) {
// object can't go fullscreen
return false;
}
return _this.getFullScreen();
}
var exitFullscreen = _videotag.webkitExitFullscreen || _videotag.webkitExitFullScreen;
if (exitFullscreen) {
exitFullscreen.apply(_videotag);
}
return state;
};
_this.getFullScreen = function () {
return _fullscreenState || !!_videotag.webkitDisplayingFullscreen;
};
this.setCurrentQuality = function (quality) {
if (_currentQuality === quality) {
return;
}
if (quality >= 0) {
if (_levels && _levels.length > quality) {
_currentQuality = quality;
_visualQuality.reason = 'api';
_visualQuality.level = {};
this.trigger(events.JWPLAYER_MEDIA_LEVEL_CHANGED, {
currentQuality: quality,
levels: _getPublicLevels(_levels)
});
// The playerConfig is not updated automatically, because it is a clone
// from when the provider was first initialized
_playerConfig.qualityLabel = _levels[quality].label;
var time = _videotag.currentTime || 0;
var duration = _videotag.duration || 0;
if (duration <= 0) {
duration = _duration;
}
_loading();
_completeLoad(time, duration);
}
}
};
this.setPlaybackRate = function (playbackRate) {
// Set defaultPlaybackRate so that we do not send ratechange events when setting src
_videotag.playbackRate = _videotag.defaultPlaybackRate = playbackRate;
};
this.getPlaybackRate = function () {
return _videotag.playbackRate;
};
this.getCurrentQuality = function () {
return _currentQuality;
};
this.getQualityLevels = function () {
return _.map(_levels, function (level) {
return (0, _dataNormalizer.qualityLevel)(level);
});
};
this.getName = function () {
return { name: _name };
};
this.setCurrentAudioTrack = _setCurrentAudioTrack;
this.getAudioTracks = _getAudioTracks;
this.getCurrentAudioTrack = _getCurrentAudioTrack;
function _setAudioTracks(tracks) {
_audioTracks = null;
if (!tracks) {
return;
}
if (tracks.length) {
for (var i = 0; i < tracks.length; i++) {
if (tracks[i].enabled) {
_currentAudioTrackIndex = i;
break;
}
}
if (_currentAudioTrackIndex === -1) {
_currentAudioTrackIndex = 0;
tracks[_currentAudioTrackIndex].enabled = true;
}
_audioTracks = _.map(tracks, function (track) {
var _track = {
name: track.label || track.language,
language: track.language
};
return _track;
});
}
_this.addTracksListener(tracks, 'change', _audioTrackChangeHandler);
if (_audioTracks) {
_this.trigger('audioTracks', { currentTrack: _currentAudioTrackIndex, tracks: _audioTracks });
}
}
function _setCurrentAudioTrack(index) {
if (_videotag && _videotag.audioTracks && _audioTracks && index > -1 && index < _videotag.audioTracks.length && index !== _currentAudioTrackIndex) {
_videotag.audioTracks[_currentAudioTrackIndex].enabled = false;
_currentAudioTrackIndex = index;
_videotag.audioTracks[_currentAudioTrackIndex].enabled = true;
_this.trigger('audioTrackChanged', { currentTrack: _currentAudioTrackIndex,
tracks: _audioTracks });
}
}
function _getAudioTracks() {
return _audioTracks || [];
}
function _getCurrentAudioTrack() {
return _currentAudioTrackIndex;
}
function _setMediaType() {
// Send mediaType when format is HLS. Other types are handled earlier by default.js.
if (_levels[0].type === 'hls') {
var mediaType = 'video';
if (_videotag.videoHeight === 0) {
mediaType = 'audio';
}
_this.trigger('mediaType', { mediaType: mediaType });
}
}
// If we're live and the buffer end has remained the same for some time, mark the stream as stale and check if the stream is over
function checkStaleStream() {
var endOfBuffer = timeRangesUtil.endOfRange(_videotag.buffered);
var live = _videotag.duration === Infinity;
if (live && _lastEndOfBuffer === endOfBuffer) {
if (!_staleStreamTimeout) {
_staleStreamTimeout = setTimeout(function () {
_stale = true;
checkStreamEnded();
}, _staleStreamDuration);
}
} else {
clearTimeout(_staleStreamTimeout);
_staleStreamTimeout = null;
_stale = false;
}
_lastEndOfBuffer = endOfBuffer;
}
function checkStreamEnded() {
if (_stale && _edgeOfLiveStream) {
_this.trigger(events.JWPLAYER_MEDIA_ERROR, {
message: 'The live stream is either down or has ended'
});
return true;
}
return false;
}
function atEdgeOfLiveStream() {
if (_videotag.duration !== Infinity) {
return false;
}
// currentTime doesn't always get to the end of the buffered range
var timeFudge = 2;
return timeRangesUtil.endOfRange(_videotag.buffered) - _videotag.currentTime <= timeFudge;
}
function clearTimeouts() {
clearTimeout(_playbackTimeout);
clearTimeout(_staleStreamTimeout);
_staleStreamTimeout = null;
}
}
// Register provider
var F = function F() {};
F.prototype = DefaultProvider;
VideoProvider.prototype = new F();
VideoProvider.getName = function () {
return { name: 'html5' };
};
return VideoProvider;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/***/ 42:
/*!*********************************************!*\
!*** ./src/js/providers/data-normalizer.js ***!
\*********************************************/
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.qualityLevel = qualityLevel;
function qualityLevel(level) {
return {
bitrate: level.bitrate,
label: level.label,
width: level.width,
height: level.height
};
}
/***/ },
/***/ 43:
/*!******************************************!*\
!*** ./src/js/providers/tracks-mixin.js ***!
\******************************************/
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict';
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! utils/underscore */ 6), __webpack_require__(/*! utils/id3Parser */ 18), __webpack_require__(/*! utils/helpers */ 8), __webpack_require__(/*! controller/tracks-loader */ 44), __webpack_require__(/*! controller/tracks-helper */ 50)], __WEBPACK_AMD_DEFINE_RESULT__ = function (_, ID3Parser, utils, tracksLoader, tracksHelper) {
/**
* Used across all providers for loading tracks and handling browser track-related events
*/
var Tracks = {
_itemTracks: null,
_textTracks: null,
_tracksById: null,
_cuesByTrackId: null,
_cachedVTTCues: null,
_metaCuesByTextTime: null,
_currentTextTrackIndex: -1,
_unknownCount: 0,
_activeCuePosition: null,
_initTextTracks: _initTextTracks,
addTracksListener: addTracksListener,
clearTracks: clearTracks,
clearCueData: clearCueData,
disableTextTrack: disableTextTrack,
enableTextTrack: enableTextTrack,
getSubtitlesTrack: getSubtitlesTrack,
removeTracksListener: removeTracksListener,
addTextTracks: addTextTracks,
setTextTracks: setTextTracks,
setupSideloadedTracks: setupSideloadedTracks,
setSubtitlesTrack: setSubtitlesTrack,
textTrackChangeHandler: null,
addTrackHandler: null,
addCuesToTrack: addCuesToTrack,
addCaptionsCue: addCaptionsCue,
addVTTCue: addVTTCue,
addVTTCuesToTrack: addVTTCuesToTrack,
renderNatively: false
};
function setTextTracks(tracks) {
this._currentTextTrackIndex = -1;
if (!tracks) {
return;
}
if (!this._textTracks) {
this._initTextTracks();
} else {
// Remove the 608 captions track that was mutated by the browser
this._textTracks = _.reject(this._textTracks, function (track) {
if (this.renderNatively && track._id === 'nativecaptions') {
delete this._tracksById[track._id];
return true;
}
}, this);
// Remove the ID3 track from the cache
delete this._tracksById.nativemetadata;
}
// filter for 'subtitles' or 'captions' tracks
if (tracks.length) {
var i = 0;
var len = tracks.length;
for (i; i < len; i++) {
var track = tracks[i];
if (!track._id) {
if (track.kind === 'captions' || track.kind === 'metadata') {
track._id = 'native' + track.kind;
if (!track.label && track.kind === 'captions') {
// track label is read only in Safari
// 'captions' tracks without a label need a name in order for the cc menu to work
var labelInfo = tracksHelper.createLabel(track, this._unknownCount);
track.name = labelInfo.label;
this._unknownCount = labelInfo.unknownCount;
}
} else {
track._id = tracksHelper.createId(track, this._textTracks.length);
}
if (this._tracksById[track._id]) {
// tracks without unique ids must not be marked as "inuse"
continue;
}
track.inuse = true;
}
if (!track.inuse || this._tracksById[track._id]) {
continue;
}
// setup TextTrack
if (track.kind === 'metadata') {
// track mode needs to be "hidden", not "showing", so that cues don't display as captions in Firefox
track.mode = 'hidden';
track.oncuechange = _cueChangeHandler.bind(this);
this._tracksById[track._id] = track;
} else if (_kindSupported(track.kind)) {
var mode = track.mode;
var cue;
// By setting the track mode to 'hidden', we can determine if the track has cues
track.mode = 'hidden';
if (!track.cues.length && track.embedded) {
// There's no method to remove tracks added via: video.addTextTrack.
// This ensures the 608 captions track isn't added to the CC menu until it has cues
continue;
}
track.mode = mode;
// Parsed cues may not have been added to this track yet
if (this._cuesByTrackId[track._id] && !this._cuesByTrackId[track._id].loaded) {
var cues = this._cuesByTrackId[track._id].cues;
while (cue = cues.shift()) {
_addCueToTrack(this.renderNatively, track, cue);
}
track.mode = mode;
this._cuesByTrackId[track._id].loaded = true;
}
_addTrackToList.call(this, track);
}
}
}
if (this.renderNatively) {
// Only bind and set this.textTrackChangeHandler once so that removeEventListener works
this.textTrackChangeHandler = this.textTrackChangeHandler || textTrackChangeHandler.bind(this);
this.addTracksListener(this.video.textTracks, 'change', this.textTrackChangeHandler);
if (utils.isEdge() || utils.isFF() || utils.isSafari()) {
// Listen for TextTracks added to the videotag after the onloadeddata event in Edge and Firefox
this.addTrackHandler = this.addTrackHandler || addTrackHandler.bind(this);
this.addTracksListener(this.video.textTracks, 'addtrack', this.addTrackHandler);
}
}
if (this._textTracks.length) {
this.trigger('subtitlesTracks', { tracks: this._textTracks });
}
}
function setupSideloadedTracks(itemTracks) {
// Add tracks if we're starting playback or resuming after a midroll
if (!this.renderNatively) {
return;
}
// Determine if the tracks are the same and the embedded + sideloaded count = # of tracks in the controlbar
var alreadyLoaded = itemTracks === this._itemTracks;
if (!alreadyLoaded) {
tracksLoader.cancelXhr(this._itemTracks);
}
this._itemTracks = itemTracks;
if (!itemTracks) {
return;
}
if (!alreadyLoaded) {
this.disableTextTrack();
_clearSideloadedTextTracks.call(this);
this.addTextTracks(itemTracks);
}
}
function getSubtitlesTrack() {
return this._currentTextTrackIndex;
}
function setSubtitlesTrack(menuIndex) {
if (!this.renderNatively) {
if (this.setCurrentSubtitleTrack) {
this.setCurrentSubtitleTrack(menuIndex - 1);
}
return;
}
if (!this._textTracks) {
return;
}
// 0 = 'Off'
if (menuIndex === 0) {
_.each(this._textTracks, function (track) {
track.mode = track.embedded ? 'hidden' : 'disabled';
});
}
// Track index is 1 less than controlbar index to account for 'Off' = 0.
// Prevent unnecessary track change events
if (this._currentTextTrackIndex === menuIndex - 1) {
return;
}
// Turn off current track
this.disableTextTrack();
// Set the provider's index to the model's index, then show the selected track if it exists
this._currentTextTrackIndex = menuIndex - 1;
if (this._textTracks[this._currentTextTrackIndex]) {
this._textTracks[this._currentTextTrackIndex].mode = 'showing';
}
// Update the model index since the track change may have come from a browser event
this.trigger('subtitlesTrackChanged', {
currentTrack: this._currentTextTrackIndex + 1,
tracks: this._textTracks
});
}
function addCaptionsCue(cueData) {
if (!cueData.text || !cueData.begin || !cueData.end) {
return;
}
var trackId = cueData.trackid.toString();
var track = this._tracksById && this._tracksById[trackId];
if (!track) {
track = {
kind: 'captions',
_id: trackId,
data: []
};
this.addTextTracks([track]);
this.trigger('subtitlesTracks', { tracks: this._textTracks });
}
var cueId;
if (cueData.useDTS) {
// There may not be any 608 captions when the track is first created
// Need to set the source so position is determined from metadata
if (!track.source) {
track.source = cueData.source || 'mpegts';
}
}
cueId = cueData.begin + '_' + cueData.text;
var cue = this._metaCuesByTextTime[cueId];
if (!cue) {
cue = {
begin: cueData.begin,
end: cueData.end,
text: cueData.text
};
this._metaCuesByTextTime[cueId] = cue;
var vttCue = tracksLoader.convertToVTTCues([cue])[0];
track.data.push(vttCue);
}
}
function addVTTCue(cueData) {
if (!this._tracksById) {
this._initTextTracks();
}
var trackId = cueData.track ? cueData.track : 'native' + cueData.type;
var track = this._tracksById[trackId];
var label = cueData.type === 'captions' ? 'Unknown CC' : 'ID3 Metadata';
var vttCue = cueData.cue;
if (!track) {
var itemTrack = {
kind: cueData.type,
_id: trackId,
label: label,
embedded: true
};
track = _createTrack.call(this, itemTrack);
if (this.renderNatively || track.kind === 'metadata') {
this.setTextTracks(this.video.textTracks);
} else {
addTextTracks.call(this, [track]);
}
}
if (_cacheVTTCue.call(this, track, vttCue)) {
if (this.renderNatively || track.kind === 'metadata') {
_addCueToTrack(this.renderNatively, track, vttCue);
} else {
track.data.push(vttCue);
}
}
}
function addCuesToTrack(cueData) {
// convert cues coming from the flash provider into VTTCues, then append them to track
var track = this._tracksById[cueData.name];
if (!track) {
return;
}
track.source = cueData.source;
var cues = cueData.captions || [];
var cuesToConvert = [];
var sort = false;
for (var i = 0; i < cues.length; i++) {
var cue = cues[i];
var cueId = cueData.name + '_' + cue.begin + '_' + cue.end;
if (!this._metaCuesByTextTime[cueId]) {
this._metaCuesByTextTime[cueId] = cue;
cuesToConvert.push(cue);
sort = true;
}
}
if (sort) {
cuesToConvert.sort(function (a, b) {
return a.begin - b.begin;
});
}
var vttCues = tracksLoader.convertToVTTCues(cuesToConvert);
Array.prototype.push.apply(track.data, vttCues);
}
function addTracksListener(tracks, eventType, handler) {
if (!tracks) {
return;
}
// Always remove existing listener
removeTracksListener(tracks, eventType, handler);
if (this.instreamMode) {
return;
}
if (tracks.addEventListener) {
tracks.addEventListener(eventType, handler);
} else {
tracks['on' + eventType] = handler;
}
}
function removeTracksListener(tracks, eventType, handler) {
if (!tracks) {
return;
}
if (tracks.removeEventListener) {
tracks.removeEventListener(eventType, handler);
} else {
tracks['on' + eventType] = null;
}
}
function clearTracks() {
tracksLoader.cancelXhr(this._itemTracks);
var metadataTrack = this._tracksById && this._tracksById.nativemetadata;
if (this.renderNatively || metadataTrack) {
_removeCues(this.renderNatively, this.video.textTracks);
if (metadataTrack) {
metadataTrack.oncuechange = null;
}
}
this._itemTracks = null;
this._textTracks = null;
this._tracksById = null;
this._cuesByTrackId = null;
this._metaCuesByTextTime = null;
this._unknownCount = 0;
this._activeCuePosition = null;
if (this.renderNatively) {
// Removing listener first to ensure that removing cues does not trigger it unnecessarily
this.removeTracksListener(this.video.textTracks, 'change', this.textTrackChangeHandler);
_removeCues(this.renderNatively, this.video.textTracks);
}
}
// Clear track cues to prevent duplicates
function clearCueData(trackId) {
if (this._cachedVTTCues[trackId]) {
this._cachedVTTCues[trackId] = {};
this._tracksById[trackId].data = [];
}
}
function disableTextTrack() {
if (this._textTracks) {
var track = this._textTracks[this._currentTextTrackIndex];
if (track) {
// FF does not remove the active cue from the dom when the track is hidden, so we must disable it
track.mode = 'disabled';
if (track.embedded || track._id === 'nativecaptions') {
track.mode = 'hidden';
}
}
}
}
function enableTextTrack() {
if (this._textTracks) {
var track = this._textTracks[this._currentTextTrackIndex];
if (track) {
track.mode = 'showing';
}
}
}
function textTrackChangeHandler() {
var textTracks = this.video.textTracks;
var inUseTracks = _.filter(textTracks, function (track) {
return (track.inuse || !track._id) && _kindSupported(track.kind);
});
if (!this._textTracks || _tracksModified.call(this, inUseTracks)) {
this.setTextTracks(textTracks);
return;
}
// If a caption/subtitle track is showing, find its index
var selectedTextTrackIndex = -1;
for (var i = 0; i < this._textTracks.length; i++) {
if (this._textTracks[i].mode === 'showing') {
selectedTextTrackIndex = i;
break;
}
}
// Notifying the model when the index changes keeps the current index in sync in iOS Fullscreen mode
if (selectedTextTrackIndex !== this._currentTextTrackIndex) {
this.setSubtitlesTrack(selectedTextTrackIndex + 1);
}
}
// Used in MS Edge to get tracks from the videotag as they're added
function addTrackHandler() {
this.setTextTracks(this.video.textTracks);
}
function addTextTracks(tracksArray) {
if (!tracksArray) {
return;
}
if (!this._textTracks) {
this._initTextTracks();
}
for (var i = 0; i < tracksArray.length; i++) {
var itemTrack = tracksArray[i];
// only add valid and supported kinds https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track
if (itemTrack.kind && !_kindSupported(itemTrack.kind)) {
continue;
}
var textTrackAny = _createTrack.call(this, itemTrack);
_addTrackToList.call(this, textTrackAny);
if (itemTrack.file) {
itemTrack.data = [];
tracksLoader.loadFile(itemTrack, this.addVTTCuesToTrack.bind(this, textTrackAny), _errorHandler);
}
}
if (this._textTracks && this._textTracks.length) {
this.trigger('subtitlesTracks', { tracks: this._textTracks });
}
}
function addVTTCuesToTrack(track, vttCues) {
if (!this.renderNatively) {
return;
}
var textTrack = this._tracksById[track._id];
// the track may not be on the video tag yet
if (!textTrack) {
if (!this._cuesByTrackId) {
this._cuesByTrackId = {};
}
this._cuesByTrackId[track._id] = { cues: vttCues, loaded: false };
return;
}
// Cues already added
if (this._cuesByTrackId[track._id] && this._cuesByTrackId[track._id].loaded) {
return;
}
var cue;
this._cuesByTrackId[track._id] = { cues: vttCues, loaded: true };
while (cue = vttCues.shift()) {
_addCueToTrack(this.renderNatively, textTrack, cue);
}
}
// ////////////////////
// //// PRIVATE METHODS
// ////////////////////
function _addCueToTrack(renderNatively, track, vttCue) {
if (!(utils.isIE() && renderNatively) || !window.TextTrackCue) {
track.addCue(vttCue);
return;
}
// There's no support for the VTTCue interface in IE/Edge.
// We need to convert VTTCue to TextTrackCue before adding them to the TextTrack
// This unfortunately removes positioning properties from the cues
var textTrackCue = new window.TextTrackCue(vttCue.startTime, vttCue.endTime, vttCue.text);
track.addCue(textTrackCue);
}
function _removeCues(renderNatively, tracks) {
if (tracks && tracks.length) {
_.each(tracks, function (track) {
// Let IE & Edge handle cleanup of non-sideloaded text tracks for native rendering
if (utils.isIE() && renderNatively && /^(native|subtitle|cc)/.test(track._id)) {
return;
}
// Cues are inaccessible if the track is disabled. While hidden,
// we can remove cues while the track is in a non-visible state
// Set to disabled before hidden to ensure active cues disappear
track.mode = 'disabled';
track.mode = 'hidden';
for (var i = track.cues.length; i--;) {
track.removeCue(track.cues[i]);
}
if (!track.embedded) {
track.mode = 'disabled';
}
track.inuse = false;
});
}
}
function _kindSupported(kind) {
return kind === 'subtitles' || kind === 'captions';
}
function _initTextTracks() {
this._textTracks = [];
this._tracksById = {};
this._metaCuesByTextTime = {};
this._cuesByTrackId = {};
this._cachedVTTCues = {};
this._unknownCount = 0;
}
function _createTrack(itemTrack) {
var track;
var labelInfo = tracksHelper.createLabel(itemTrack, this._unknownCount);
var label = labelInfo.label;
this._unknownCount = labelInfo.unknownCount;
if (this.renderNatively || itemTrack.kind === 'metadata') {
var tracks = this.video.textTracks;
// TextTrack label is read only, so we'll need to create a new track if we don't
// already have one with the same label
track = _.findWhere(tracks, { label: label });
if (track) {
track.kind = itemTrack.kind;
track.language = itemTrack.language || '';
} else {
track = this.video.addTextTrack(itemTrack.kind, label, itemTrack.language || '');
}
track.default = itemTrack.default;
track.mode = 'disabled';
track.inuse = true;
} else {
track = itemTrack;
track.data = track.data || [];
}
if (!track._id) {
track._id = tracksHelper.createId(itemTrack, this._textTracks.length);
}
return track;
}
function _addTrackToList(track) {
this._textTracks.push(track);
this._tracksById[track._id] = track;
}
function _clearSideloadedTextTracks() {
// Clear VTT textTracks
if (!this._textTracks) {
return;
}
var nonSideloadedTracks = _.filter(this._textTracks, function (track) {
return track.embedded || track.groupid === 'subs';
});
this._initTextTracks();
_.each(nonSideloadedTracks, function (track) {
this._tracksById[track._id] = track;
});
this._textTracks = nonSideloadedTracks;
}
function _cueChangeHandler(e) {
var activeCues = e.currentTarget.activeCues;
if (!activeCues || !activeCues.length) {
return;
}
// Get the most recent start time. Cues are sorted by start time in ascending order by the browser
var startTime = activeCues[activeCues.length - 1].startTime;
// Prevent duplicate meta events for the same list of cues since the cue change handler fires once
// for each activeCue in Safari
if (this._activeCuePosition === startTime) {
return;
}
var dataCues = [];
_.each(activeCues, function (cue) {
if (cue.startTime < startTime) {
return;
}
if (cue.data || cue.value) {
dataCues.push(cue);
} else if (cue.text) {
this.trigger('meta', {
metadataTime: startTime,
metadata: JSON.parse(cue.text)
});
}
}, this);
if (dataCues.length) {
var id3Data = ID3Parser.parseID3(dataCues);
this.trigger('meta', {
metadataTime: startTime,
metadata: id3Data
});
}
this._activeCuePosition = startTime;
}
function _cacheVTTCue(track, vttCue) {
var trackKind = track.kind;
if (!this._cachedVTTCues[track._id]) {
this._cachedVTTCues[track._id] = {};
}
var cachedCues = this._cachedVTTCues[track._id];
var cacheKeyTime;
switch (trackKind) {
case 'captions':
case 'subtitles':
// VTTCues should have unique start and end times, even in cases where there are multiple
// active cues. This is safer than ensuring text is unique, which may be violated on seek.
// Captions within .05s of each other are treated as unique to account for
// quality switches where start/end times are slightly different.
cacheKeyTime = Math.floor(vttCue.startTime * 20);
var cacheLine = '_' + vttCue.line;
var cacheValue = Math.floor(vttCue.endTime * 20);
var cueExists = cachedCues[cacheKeyTime + cacheLine] || cachedCues[cacheKeyTime + 1 + cacheLine] || cachedCues[cacheKeyTime - 1 + cacheLine];
if (cueExists && Math.abs(cueExists - cacheValue) <= 1) {
return false;
}
cachedCues[cacheKeyTime + cacheLine] = cacheValue;
return true;
case 'metadata':
var text = vttCue.data ? new Uint8Array(vttCue.data).join('') : vttCue.text;
cacheKeyTime = vttCue.startTime + text;
if (cachedCues[cacheKeyTime]) {
return false;
}
cachedCues[cacheKeyTime] = vttCue.endTime;
return true;
default:
return false;
}
}
function _tracksModified(inUseTracks) {
// Need to add new textTracks coming from the video tag
if (inUseTracks.length > this._textTracks.length) {
return true;
}
// Tracks may have changed in Safari after an ad
for (var i = 0; i < inUseTracks.length; i++) {
var track = inUseTracks[i];
if (!track._id || !this._tracksById[track._id]) {
return true;
}
}
return false;
}
function _errorHandler(error) {
utils.log('CAPTIONS(' + error + ')');
}
return Tracks;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/***/ 51:
/*!*************************************!*\
!*** ./src/js/utils/time-ranges.js ***!
\*************************************/
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict";
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
function endOfRange(timeRanges) {
if (!timeRanges || !timeRanges.length) {
return 0;
}
return timeRanges.end(timeRanges.length - 1);
}
return {
endOfRange: endOfRange
};
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ }
});
//# sourceMappingURL=provider.html5.a8bf8f3cb1a82cfe5f6e.map | vfremaux/moodle-mod_mplayer | extralib/players/jw/7.12/bin-debug/provider.html5.js | JavaScript | gpl-3.0 | 68,286 |
<html>
<head>
<meta lang="es">
<meta charset="utf-8">
<title>Rest</title>
</head>
<body>
</body>
</html> | DevHart08/rest | srd/index.php | PHP | gpl-3.0 | 172 |
/*
* Copyright (c) 2011 Vinay Pulim <vinay@milewise.com>
* MIT Licensed
*
*/
/*jshint proto:true*/
"use strict";
var sax = require('sax');
var inherits = require('util').inherits;
var HttpClient = require('./http');
var NamespaceContext = require('./nscontext');
var fs = require('fs');
var url = require('url');
var path = require('path');
var assert = require('assert').ok;
var stripBom = require('strip-bom');
var debug = require('debug')('node-soap');
var _ = require('lodash');
var selectn = require('selectn');
var utils = require('./utils');
var TNS_PREFIX = utils.TNS_PREFIX;
var findPrefix = utils.findPrefix;
var Primitives = {
string: 1,
boolean: 1,
decimal: 1,
float: 1,
double: 1,
anyType: 1,
byte: 1,
int: 1,
long: 1,
short: 1,
negativeInteger: 1,
nonNegativeInteger: 1,
positiveInteger: 1,
nonPositiveInteger:1,
unsignedByte: 1,
unsignedInt: 1,
unsignedLong: 1,
unsignedShort: 1,
duration: 0,
dateTime: 0,
time: 0,
date: 0,
gYearMonth: 0,
gYear: 0,
gMonthDay: 0,
gDay: 0,
gMonth: 0,
hexBinary: 0,
base64Binary: 0,
anyURI: 0,
QName: 0,
NOTATION: 0
};
function splitQName(nsName) {
var i = typeof nsName === 'string' ? nsName.indexOf(':') : -1;
return i < 0 ? {prefix: TNS_PREFIX, name: nsName} :
{prefix: nsName.substring(0, i), name: nsName.substring(i + 1)};
}
function xmlEscape(obj) {
if (typeof (obj) === 'string') {
return obj
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
return obj;
}
var trimLeft = /^[\s\xA0]+/;
var trimRight = /[\s\xA0]+$/;
function trim(text) {
return text.replace(trimLeft, '').replace(trimRight, '');
}
/**
* What we want is to copy properties from one object to another one and avoid
* properties overriding. This way we ensure the 'inheritance' of
* <xsd:extension base=...> usage.
*
* NB: 'Element' (and subtypes) don't have any prototyped properties: there's
* no need to process a 'hasOwnProperties' call, we should just iterate over the
* keys.
*/
function extend(base, obj) {
if(base !== null && typeof base === "object" && obj !== null && typeof obj === "object"){
Object.keys(obj).forEach(function(key) {
if(!base.hasOwnProperty(key))
base[key] = obj[key];
});
}
return base;
}
function deepMerge(destination, source) {
return _.merge(destination || {}, source, function(a, b) {
return _.isArray(a) ? a.concat(b) : undefined;
});
}
var Element = function(nsName, attrs, options) {
var parts = splitQName(nsName);
this.nsName = nsName;
this.prefix = parts.prefix;
this.name = parts.name;
this.children = [];
this.xmlns = {};
this._initializeOptions(options);
for (var key in attrs) {
var match = /^xmlns:?(.*)$/.exec(key);
if (match) {
this.xmlns[match[1] ? match[1] : TNS_PREFIX] = attrs[key];
}
else {
if(key === 'value') {
this[this.valueKey] = attrs[key];
} else {
this['$' + key] = attrs[key];
}
}
}
if (this.$targetNamespace !== undefined) {
// Add targetNamespace to the mapping
this.xmlns[TNS_PREFIX] = this.$targetNamespace;
}
};
Element.prototype._initializeOptions = function (options) {
if(options) {
this.valueKey = options.valueKey || '$value';
this.xmlKey = options.xmlKey || '$xml';
this.ignoredNamespaces = options.ignoredNamespaces || [];
} else {
this.valueKey = '$value';
this.xmlKey = '$xml';
this.ignoredNamespaces = [];
}
};
Element.prototype.deleteFixedAttrs = function() {
this.children && this.children.length === 0 && delete this.children;
this.xmlns && Object.keys(this.xmlns).length === 0 && delete this.xmlns;
delete this.nsName;
delete this.prefix;
delete this.name;
};
Element.prototype.allowedChildren = [];
Element.prototype.startElement = function(stack, nsName, attrs, options) {
if (!this.allowedChildren)
return;
var ChildClass = this.allowedChildren[splitQName(nsName).name],
element = null;
if (ChildClass) {
stack.push(new ChildClass(nsName, attrs, options));
}
else {
this.unexpected(nsName);
}
};
Element.prototype.endElement = function(stack, nsName) {
if (this.nsName === nsName) {
if (stack.length < 2)
return;
var parent = stack[stack.length - 2];
if (this !== stack[0]) {
extend(stack[0].xmlns, this.xmlns);
// delete this.xmlns;
parent.children.push(this);
parent.addChild(this);
}
stack.pop();
}
};
Element.prototype.addChild = function(child) {
return;
};
Element.prototype.unexpected = function(name) {
throw new Error('Found unexpected element (' + name + ') inside ' + this.nsName);
};
Element.prototype.description = function(definitions) {
return this.$name || this.name;
};
Element.prototype.init = function() {
};
Element.createSubClass = function() {
var root = this;
var subElement = function() {
root.apply(this, arguments);
this.init();
};
// inherits(subElement, root);
subElement.prototype.__proto__ = root.prototype;
return subElement;
};
var ElementElement = Element.createSubClass();
var AnyElement = Element.createSubClass();
var InputElement = Element.createSubClass();
var OutputElement = Element.createSubClass();
var SimpleTypeElement = Element.createSubClass();
var RestrictionElement = Element.createSubClass();
var ExtensionElement = Element.createSubClass();
var ChoiceElement = Element.createSubClass();
var EnumerationElement = Element.createSubClass();
var ComplexTypeElement = Element.createSubClass();
var ComplexContentElement = Element.createSubClass();
var SimpleContentElement = Element.createSubClass();
var SequenceElement = Element.createSubClass();
var AllElement = Element.createSubClass();
var MessageElement = Element.createSubClass();
var DocumentationElement = Element.createSubClass();
var SchemaElement = Element.createSubClass();
var TypesElement = Element.createSubClass();
var OperationElement = Element.createSubClass();
var PortTypeElement = Element.createSubClass();
var BindingElement = Element.createSubClass();
var PortElement = Element.createSubClass();
var ServiceElement = Element.createSubClass();
var DefinitionsElement = Element.createSubClass();
var ElementTypeMap = {
types: [TypesElement, 'schema documentation'],
schema: [SchemaElement, 'element complexType simpleType include import'],
element: [ElementElement, 'annotation complexType'],
any: [AnyElement, ''],
simpleType: [SimpleTypeElement, 'restriction'],
restriction: [RestrictionElement, 'enumeration all choice sequence'],
extension: [ExtensionElement, 'all sequence choice'],
choice: [ChoiceElement, 'element sequence choice any'],
// group: [GroupElement, 'element group'],
enumeration: [EnumerationElement, ''],
complexType: [ComplexTypeElement, 'annotation sequence all complexContent simpleContent choice'],
complexContent: [ComplexContentElement, 'extension'],
simpleContent: [SimpleContentElement, 'extension'],
sequence: [SequenceElement, 'element sequence choice any'],
all: [AllElement, 'element choice'],
service: [ServiceElement, 'port documentation'],
port: [PortElement, 'address documentation'],
binding: [BindingElement, '_binding SecuritySpec operation documentation'],
portType: [PortTypeElement, 'operation documentation'],
message: [MessageElement, 'part documentation'],
operation: [OperationElement, 'documentation input output fault _operation'],
input: [InputElement, 'body SecuritySpecRef documentation header'],
output: [OutputElement, 'body SecuritySpecRef documentation header'],
fault: [Element, '_fault documentation'],
definitions: [DefinitionsElement, 'types message portType binding service import documentation'],
documentation: [DocumentationElement, '']
};
function mapElementTypes(types) {
var rtn = {};
types = types.split(' ');
types.forEach(function(type) {
rtn[type.replace(/^_/, '')] = (ElementTypeMap[type] || [Element]) [0];
});
return rtn;
}
for (var n in ElementTypeMap) {
var v = ElementTypeMap[n];
v[0].prototype.allowedChildren = mapElementTypes(v[1]);
}
MessageElement.prototype.init = function() {
this.element = null;
this.parts = null;
};
SchemaElement.prototype.init = function() {
this.complexTypes = {};
this.types = {};
this.elements = {};
this.includes = [];
};
TypesElement.prototype.init = function() {
this.schemas = {};
};
OperationElement.prototype.init = function() {
this.input = null;
this.output = null;
this.inputSoap = null;
this.outputSoap = null;
this.style = '';
this.soapAction = '';
};
PortTypeElement.prototype.init = function() {
this.methods = {};
};
BindingElement.prototype.init = function() {
this.transport = '';
this.style = '';
this.methods = {};
};
PortElement.prototype.init = function() {
this.location = null;
};
ServiceElement.prototype.init = function() {
this.ports = {};
};
DefinitionsElement.prototype.init = function() {
if (this.name !== 'definitions')this.unexpected(this.nsName);
this.messages = {};
this.portTypes = {};
this.bindings = {};
this.services = {};
this.schemas = {};
};
DocumentationElement.prototype.init = function() {
};
SchemaElement.prototype.merge = function(source) {
assert(source instanceof SchemaElement);
if (this.$targetNamespace === source.$targetNamespace) {
_.merge(this.complexTypes, source.complexTypes);
_.merge(this.types, source.types);
_.merge(this.elements, source.elements);
_.merge(this.xmlns, source.xmlns);
}
return this;
};
SchemaElement.prototype.addChild = function(child) {
if (child.$name in Primitives)
return;
if (child.name === 'include' || child.name === 'import') {
var location = child.$schemaLocation || child.$location;
if (location) {
this.includes.push({
namespace: child.$namespace || child.$targetNamespace || this.$targetNamespace,
location: location
});
}
}
else if (child.name === 'complexType') {
this.complexTypes[child.$name] = child;
}
else if (child.name === 'element') {
this.elements[child.$name] = child;
}
else if (child.$name) {
this.types[child.$name] = child;
}
this.children.pop();
// child.deleteFixedAttrs();
};
//fix#325
TypesElement.prototype.addChild = function (child) {
assert(child instanceof SchemaElement);
var targetNamespace = child.$targetNamespace;
if(!this.schemas.hasOwnProperty(targetNamespace)) {
this.schemas[targetNamespace] = child;
} else {
console.error('Target-Namespace "'+ targetNamespace +'" already in use by another Schema!');
}
};
InputElement.prototype.addChild = function(child) {
if (child.name === 'body') {
this.use = child.$use;
if (this.use === 'encoded') {
this.encodingStyle = child.$encodingStyle;
}
this.children.pop();
}
};
OutputElement.prototype.addChild = function(child) {
if (child.name === 'body') {
this.use = child.$use;
if (this.use === 'encoded') {
this.encodingStyle = child.$encodingStyle;
}
this.children.pop();
}
};
OperationElement.prototype.addChild = function(child) {
if (child.name === 'operation') {
this.soapAction = child.$soapAction || '';
this.style = child.$style || '';
this.children.pop();
}
};
BindingElement.prototype.addChild = function(child) {
if (child.name === 'binding') {
this.transport = child.$transport;
this.style = child.$style;
this.children.pop();
}
};
PortElement.prototype.addChild = function(child) {
if (child.name === 'address' && typeof (child.$location) !== 'undefined') {
this.location = child.$location;
}
};
DefinitionsElement.prototype.addChild = function(child) {
var self = this;
if (child instanceof TypesElement) {
// Merge types.schemas into definitions.schemas
_.merge(self.schemas, child.schemas);
}
else if (child instanceof MessageElement) {
self.messages[child.$name] = child;
}
else if (child.name === 'import') {
self.schemas[child.$namespace] = new SchemaElement(child.$namespace, {});
self.schemas[child.$namespace].addChild(child);
}
else if (child instanceof PortTypeElement) {
self.portTypes[child.$name] = child;
}
else if (child instanceof BindingElement) {
if (child.transport === 'http://schemas.xmlsoap.org/soap/http' ||
child.transport === 'http://www.w3.org/2003/05/soap/bindings/HTTP/')
self.bindings[child.$name] = child;
}
else if (child instanceof ServiceElement) {
self.services[child.$name] = child;
}
else if (child instanceof DocumentationElement) {
}
this.children.pop();
};
MessageElement.prototype.postProcess = function(definitions) {
var part = null;
var child;
var children = this.children || [];
var ns;
var nsName;
var i;
var type;
for (i in children) {
if ((child = children[i]).name === 'part') {
part = child;
break;
}
}
if (!part) {
return;
}
if (part.$element) {
var lookupTypes = [],
elementChildren ;
delete this.parts;
nsName = splitQName(part.$element);
ns = nsName.prefix;
var schema = definitions.schemas[definitions.xmlns[ns]];
this.element = schema.elements[nsName.name];
if(!this.element) {
debug(nsName.name + " is not present in wsdl and cannot be processed correctly.");
return;
}
this.element.targetNSAlias = ns;
this.element.targetNamespace = definitions.xmlns[ns];
// set the optional $lookupType to be used within `client#_invoke()` when
// calling `wsdl#objectToDocumentXML()
this.element.$lookupType = part.$name;
elementChildren = this.element.children;
// get all nested lookup types (only complex types are followed)
if (elementChildren.length > 0) {
for (i = 0; i < elementChildren.length; i++) {
lookupTypes.push(this._getNestedLookupTypeString(elementChildren[i]));
}
}
// if nested lookup types where found, prepare them for furter usage
if (lookupTypes.length > 0) {
lookupTypes = lookupTypes.
join('_').
split('_').
filter(function removeEmptyLookupTypes (type) {
return type !== '^';
});
var schemaXmlns = definitions.schemas[this.element.targetNamespace].xmlns;
for (i = 0; i < lookupTypes.length; i++) {
lookupTypes[i] = this._createLookupTypeObject(lookupTypes[i], schemaXmlns);
}
}
this.element.$lookupTypes = lookupTypes;
if (this.element.$type) {
type = splitQName(this.element.$type);
var typeNs = schema.xmlns && schema.xmlns[type.prefix] || definitions.xmlns[type.prefix];
if (typeNs) {
if (type.name in Primitives) {
// this.element = this.element.$type;
}
else {
// first check local mapping of ns alias to namespace
schema = definitions.schemas[typeNs];
var ctype = schema.complexTypes[type.name] || schema.types[type.name] || schema.elements[type.name];
if (ctype) {
this.parts = ctype.description(definitions, schema.xmlns);
}
}
}
}
else {
var method = this.element.description(definitions, schema.xmlns);
this.parts = method[nsName.name];
}
this.children.splice(0, 1);
} else {
// rpc encoding
this.parts = {};
delete this.element;
for (i = 0; part = this.children[i]; i++) {
if (part.name === 'documentation') {
// <wsdl:documentation can be present under <wsdl:message>
continue;
}
assert(part.name === 'part', 'Expected part element');
nsName = splitQName(part.$type);
ns = definitions.xmlns[nsName.prefix];
type = nsName.name;
var schemaDefinition = definitions.schemas[ns];
if (typeof schemaDefinition !== 'undefined') {
this.parts[part.$name] = definitions.schemas[ns].types[type] || definitions.schemas[ns].complexTypes[type];
} else {
this.parts[part.$name] = part.$type;
}
if (typeof this.parts[part.$name] === 'object') {
this.parts[part.$name].prefix = nsName.prefix;
this.parts[part.$name].xmlns = ns;
}
this.children.splice(i--, 1);
}
}
this.deleteFixedAttrs();
};
/**
* Takes a given namespaced String(for example: 'alias:property') and creates a lookupType
* object for further use in as first (lookup) `parameterTypeObj` within the `objectToXML`
* method and provides an entry point for the already existing code in `findChildSchemaObject`.
*
* @method _createLookupTypeObject
* @param {String} nsString The NS String (for example "alias:type").
* @param {Object} xmlns The fully parsed `wsdl` definitions object (including all schemas).
* @returns {Object}
* @private
*/
MessageElement.prototype._createLookupTypeObject = function (nsString, xmlns) {
var splittedNSString = splitQName(nsString),
nsAlias = splittedNSString.prefix,
splittedName = splittedNSString.name.split('#'),
type = splittedName[0],
name = splittedName[1],
lookupTypeObj = {};
lookupTypeObj.$namespace = xmlns[nsAlias];
lookupTypeObj.$type = nsAlias + ':' + type;
lookupTypeObj.$name = name;
return lookupTypeObj;
};
/**
* Iterates through the element and every nested child to find any defined `$type`
* property and returns it in a underscore ('_') separated String (using '^' as default
* value if no `$type` property was found).
*
* @method _getNestedLookupTypeString
* @param {Object} element The element which (probably) contains nested `$type` values.
* @returns {String}
* @private
*/
MessageElement.prototype._getNestedLookupTypeString = function (element) {
var resolvedType = '^',
excluded = this.ignoredNamespaces.concat('xs'); // do not process $type values wich start with
if (element.hasOwnProperty('$type') && typeof element.$type === 'string') {
if (excluded.indexOf(element.$type.split(':')[0]) === -1) {
resolvedType += ('_' + element.$type + '#' + element.$name);
}
}
if (element.children.length > 0) {
var self = this;
element.children.forEach(function (child) {
var resolvedChildType = self._getNestedLookupTypeString(child).replace(/\^_/, '');
if (resolvedChildType && typeof resolvedChildType === 'string') {
resolvedType += ('_' + resolvedChildType);
}
});
}
return resolvedType;
};
OperationElement.prototype.postProcess = function(definitions, tag) {
var children = this.children;
for (var i = 0, child; child = children[i]; i++) {
if (child.name !== 'input' && child.name !== 'output')
continue;
if (tag === 'binding') {
this[child.name] = child;
children.splice(i--, 1);
continue;
}
var messageName = splitQName(child.$message).name;
var message = definitions.messages[messageName];
message.postProcess(definitions);
if (message.element) {
definitions.messages[message.element.$name] = message;
this[child.name] = message.element;
}
else {
this[child.name] = message;
}
children.splice(i--, 1);
}
this.deleteFixedAttrs();
};
PortTypeElement.prototype.postProcess = function(definitions) {
var children = this.children;
if (typeof children === 'undefined')
return;
for (var i = 0, child; child = children[i]; i++) {
if (child.name !== 'operation')
continue;
child.postProcess(definitions, 'portType');
this.methods[child.$name] = child;
children.splice(i--, 1);
}
delete this.$name;
this.deleteFixedAttrs();
};
BindingElement.prototype.postProcess = function(definitions) {
var type = splitQName(this.$type).name,
portType = definitions.portTypes[type],
style = this.style,
children = this.children;
if (portType){
portType.postProcess(definitions);
this.methods = portType.methods;
for (var i = 0, child; child = children[i]; i++) {
if (child.name !== 'operation')
continue;
child.postProcess(definitions, 'binding');
children.splice(i--, 1);
child.style || (child.style = style);
var method = this.methods[child.$name];
if (method) {
method.style = child.style;
method.soapAction = child.soapAction;
method.inputSoap = child.input || null;
method.outputSoap = child.output || null;
method.inputSoap && method.inputSoap.deleteFixedAttrs();
method.outputSoap && method.outputSoap.deleteFixedAttrs();
}
}
}
delete this.$name;
delete this.$type;
this.deleteFixedAttrs();
};
ServiceElement.prototype.postProcess = function(definitions) {
var children = this.children,
bindings = definitions.bindings;
if (children && children.length > 0) {
for (var i = 0, child; child = children[i]; i++) {
if (child.name !== 'port')
continue;
var bindingName = splitQName(child.$binding).name;
var binding = bindings[bindingName];
if (binding) {
binding.postProcess(definitions);
this.ports[child.$name] = {
location: child.location,
binding: binding
};
children.splice(i--, 1);
}
}
}
delete this.$name;
this.deleteFixedAttrs();
};
SimpleTypeElement.prototype.description = function(definitions) {
var children = this.children;
for (var i = 0, child; child = children[i]; i++) {
if (child instanceof RestrictionElement)
return this.$name + "|" + child.description();
}
return {};
};
RestrictionElement.prototype.description = function(definitions, xmlns) {
var children = this.children;
var desc;
for (var i=0, child; child=children[i]; i++) {
if (child instanceof SequenceElement ||
child instanceof ChoiceElement) {
desc = child.description(definitions, xmlns);
break;
}
}
if (desc && this.$base) {
var type = splitQName(this.$base),
typeName = type.name,
ns = xmlns && xmlns[type.prefix] || definitions.xmlns[type.prefix],
schema = definitions.schemas[ns],
typeElement = schema && ( schema.complexTypes[typeName] || schema.types[typeName] || schema.elements[typeName] );
desc.getBase = function() {
return typeElement.description(definitions, schema.xmlns);
};
return desc;
}
// then simple element
var base = this.$base ? this.$base + "|" : "";
return base + this.children.map(function(child) {
return child.description();
}).join(",");
};
ExtensionElement.prototype.description = function(definitions, xmlns) {
var children = this.children;
var desc = {};
for (var i=0, child; child=children[i]; i++) {
if (child instanceof SequenceElement ||
child instanceof ChoiceElement) {
desc = child.description(definitions, xmlns);
}
}
if (this.$base) {
var type = splitQName(this.$base),
typeName = type.name,
ns = xmlns && xmlns[type.prefix] || definitions.xmlns[type.prefix],
schema = definitions.schemas[ns];
if (typeName in Primitives) {
return this.$base;
}
else {
var typeElement = schema && ( schema.complexTypes[typeName] ||
schema.types[typeName] || schema.elements[typeName] );
if (typeElement) {
var base = typeElement.description(definitions, schema.xmlns);
extend(desc, base);
}
}
}
return desc;
};
EnumerationElement.prototype.description = function() {
return this[this.valueKey];
};
ComplexTypeElement.prototype.description = function(definitions, xmlns) {
var children = this.children || [];
for (var i=0, child; child=children[i]; i++) {
if (child instanceof ChoiceElement ||
child instanceof SequenceElement ||
child instanceof AllElement ||
child instanceof SimpleContentElement ||
child instanceof ComplexContentElement) {
return child.description(definitions, xmlns);
}
}
return {};
};
ComplexContentElement.prototype.description = function(definitions, xmlns) {
var children = this.children;
for (var i = 0, child; child = children[i]; i++) {
if (child instanceof ExtensionElement) {
return child.description(definitions, xmlns);
}
}
return {};
};
SimpleContentElement.prototype.description = function(definitions, xmlns) {
var children = this.children;
for (var i = 0, child; child = children[i]; i++) {
if (child instanceof ExtensionElement) {
return child.description(definitions, xmlns);
}
}
return {};
};
ElementElement.prototype.description = function(definitions, xmlns) {
var element = {},
name = this.$name;
var isMany = !this.$maxOccurs ? false : (isNaN(this.$maxOccurs) ? (this.$maxOccurs === 'unbounded') : (this.$maxOccurs > 1));
if (this.$minOccurs !== this.$maxOccurs && isMany) {
name += '[]';
}
if (xmlns && xmlns[TNS_PREFIX]) {
this.$targetNamespace = xmlns[TNS_PREFIX];
}
var type = this.$type || this.$ref;
if (type) {
type = splitQName(type);
var typeName = type.name,
ns = xmlns && xmlns[type.prefix] || definitions.xmlns[type.prefix],
schema = definitions.schemas[ns],
typeElement = schema && ( this.$type? schema.complexTypes[typeName] || schema.types[typeName] : schema.elements[typeName] );
if (ns && definitions.schemas[ns]) {
xmlns = definitions.schemas[ns].xmlns;
}
if (typeElement && !(typeName in Primitives)) {
if (!(typeName in definitions.descriptions.types)) {
var elem = {};
definitions.descriptions.types[typeName] = elem;
var description = typeElement.description(definitions, xmlns);
if (typeof description === 'string') {
elem = description;
}
else {
Object.keys(description).forEach(function (key) {
elem[key] = description[key];
});
}
if (this.$ref) {
element = elem;
}
else {
element[name] = elem;
}
if (typeof elem === 'object') {
elem.targetNSAlias = type.prefix;
elem.targetNamespace = ns;
}
definitions.descriptions.types[typeName] = elem;
}
else {
if (this.$ref) {
element = definitions.descriptions.types[typeName];
}
else {
element[name] = definitions.descriptions.types[typeName];
}
}
}
else {
element[name] = this.$type;
}
}
else {
var children = this.children;
element[name] = {};
for (var i = 0, child; child = children[i]; i++) {
if (child instanceof ComplexTypeElement) {
element[name] = child.description(definitions, xmlns);
}
}
}
return element;
};
AllElement.prototype.description =
SequenceElement.prototype.description = function(definitions, xmlns) {
var children = this.children;
var sequence = {};
for (var i = 0, child; child = children[i]; i++) {
if (child instanceof AnyElement) {
continue;
}
var description = child.description(definitions, xmlns);
for (var key in description) {
sequence[key] = description[key];
}
}
return sequence;
};
ChoiceElement.prototype.description = function(definitions, xmlns) {
var children = this.children;
var choice = {};
for (var i=0, child; child=children[i]; i++) {
var description = child.description(definitions, xmlns);
for (var key in description) {
choice[key] = description[key];
}
}
return choice;
};
MessageElement.prototype.description = function(definitions) {
if (this.element) {
return this.element && this.element.description(definitions);
}
var desc = {};
desc[this.$name] = this.parts;
return desc;
};
PortTypeElement.prototype.description = function(definitions) {
var methods = {};
for (var name in this.methods) {
var method = this.methods[name];
methods[name] = method.description(definitions);
}
return methods;
};
OperationElement.prototype.description = function(definitions) {
var inputDesc = this.input ? this.input.description(definitions) : null;
var outputDesc = this.output ? this.output.description(definitions) : null;
return {
input: inputDesc && inputDesc[Object.keys(inputDesc)[0]],
output: outputDesc && outputDesc[Object.keys(outputDesc)[0]]
};
};
BindingElement.prototype.description = function(definitions) {
var methods = {};
for (var name in this.methods) {
var method = this.methods[name];
methods[name] = method.description(definitions);
}
return methods;
};
ServiceElement.prototype.description = function(definitions) {
var ports = {};
for (var name in this.ports) {
var port = this.ports[name];
ports[name] = port.binding.description(definitions);
}
return ports;
};
var WSDL = function(definition, uri, options) {
var self = this,
fromFunc;
this.uri = uri;
this.callback = function() {
};
this._includesWsdl = [];
// initialize WSDL cache
this.WSDL_CACHE = (options || {}).WSDL_CACHE || {};
this._initializeOptions(options);
if (typeof definition === 'string') {
definition = stripBom(definition);
fromFunc = this._fromXML;
}
else if (typeof definition === 'object') {
fromFunc = this._fromServices;
}
else {
throw new Error('WSDL constructor takes either an XML string or service definition');
}
process.nextTick(function() {
try {
fromFunc.call(self, definition);
} catch (e) {
return self.callback(e.message);
}
self.processIncludes(function(err) {
var name;
if (err) {
return self.callback(err);
}
self.definitions.deleteFixedAttrs();
var services = self.services = self.definitions.services;
if (services) {
for (name in services) {
services[name].postProcess(self.definitions);
}
}
var complexTypes = self.definitions.complexTypes;
if (complexTypes) {
for (name in complexTypes) {
complexTypes[name].deleteFixedAttrs();
}
}
// for document style, for every binding, prepare input message element name to (methodName, output message element name) mapping
var bindings = self.definitions.bindings;
for (var bindingName in bindings) {
var binding = bindings[bindingName];
if (typeof binding.style === 'undefined') {
binding.style = 'document';
}
if (binding.style !== 'document')
continue;
var methods = binding.methods;
var topEls = binding.topElements = {};
for (var methodName in methods) {
if (methods[methodName].input) {
var inputName = methods[methodName].input.$name;
var outputName="";
if(methods[methodName].output )
outputName = methods[methodName].output.$name;
topEls[inputName] = {"methodName": methodName, "outputName": outputName};
}
}
}
// prepare soap envelope xmlns definition string
self.xmlnsInEnvelope = self._xmlnsMap();
self.callback(err, self);
});
});
};
WSDL.prototype.ignoredNamespaces = ['tns', 'targetNamespace', 'typedNamespace'];
WSDL.prototype.ignoreBaseNameSpaces = false;
WSDL.prototype.valueKey = '$value';
WSDL.prototype.xmlKey = '$xml';
WSDL.prototype._initializeOptions = function (options) {
this._originalIgnoredNamespaces = (options || {}).ignoredNamespaces;
this.options = {};
var ignoredNamespaces = options ? options.ignoredNamespaces : null;
if (ignoredNamespaces &&
(Array.isArray(ignoredNamespaces.namespaces) || typeof ignoredNamespaces.namespaces === 'string')) {
if (ignoredNamespaces.override) {
this.options.ignoredNamespaces = ignoredNamespaces.namespaces;
} else {
this.options.ignoredNamespaces = this.ignoredNamespaces.concat(ignoredNamespaces.namespaces);
}
} else {
this.options.ignoredNamespaces = this.ignoredNamespaces;
}
this.options.valueKey = options.valueKey || this.valueKey;
this.options.xmlKey = options.xmlKey || this.xmlKey;
// Allow any request headers to keep passing through
this.options.wsdl_headers = options.wsdl_headers;
this.options.wsdl_options = options.wsdl_options;
var ignoreBaseNameSpaces = options ? options.ignoreBaseNameSpaces : null;
if(ignoreBaseNameSpaces !== null && typeof ignoreBaseNameSpaces !== 'undefined' )
this.options.ignoreBaseNameSpaces = ignoreBaseNameSpaces;
else
this.options.ignoreBaseNameSpaces = this.ignoreBaseNameSpaces;
// Works only in client
this.options.forceSoap12Headers = options.forceSoap12Headers;
if(options.overrideRootElement !== undefined) {
this.options.overrideRootElement = options.overrideRootElement;
}
};
WSDL.prototype.onReady = function(callback) {
if (callback)
this.callback = callback;
};
WSDL.prototype._processNextInclude = function(includes, callback) {
var self = this,
include = includes.shift(),
options;
if (!include)
return callback();
var includePath;
if (!/^https?:/.test(self.uri) && !/^https?:/.test(include.location)) {
includePath = path.resolve(path.dirname(self.uri), include.location);
} else {
includePath = url.resolve(self.uri, include.location);
}
options = _.assign({}, this.options);
// follow supplied ignoredNamespaces option
options.ignoredNamespaces = this._originalIgnoredNamespaces || this.options.ignoredNamespaces;
options.WSDL_CACHE = this.WSDL_CACHE;
open_wsdl_recursive(includePath, options, function(err, wsdl) {
if (err) {
return callback(err);
}
self._includesWsdl.push(wsdl);
if(wsdl.definitions instanceof DefinitionsElement){
_.merge(self.definitions, wsdl.definitions, function(a,b) {
return (a instanceof SchemaElement) ? a.merge(b) : undefined;
});
}else{
self.definitions.schemas[include.namespace || wsdl.definitions.$targetNamespace] = deepMerge(self.definitions.schemas[include.namespace || wsdl.definitions.$targetNamespace], wsdl.definitions);
}
self._processNextInclude(includes, function(err) {
callback(err);
});
});
};
WSDL.prototype.processIncludes = function(callback) {
var schemas = this.definitions.schemas,
includes = [];
for (var ns in schemas) {
var schema = schemas[ns];
includes = includes.concat(schema.includes || []);
}
this._processNextInclude(includes, callback);
};
WSDL.prototype.describeServices = function() {
var services = {};
for (var name in this.services) {
var service = this.services[name];
services[name] = service.description(this.definitions);
}
return services;
};
WSDL.prototype.toXML = function() {
return this.xml || '';
};
WSDL.prototype.xmlToObject = function(xml) {
var self = this;
var p = sax.parser(true);
var objectName = null;
var root = {};
var schema = {
Envelope: {
Header: {
Security: {
UsernameToken: {
Username: 'string',
Password: 'string'
}
}
},
Body: {
Fault: {
faultcode: 'string',
faultstring: 'string',
detail: 'string'
}
}
}
};
var stack = [{name: null, object: root, schema: schema}];
var xmlns = {};
var refs = {}, id; // {id:{hrefs:[],obj:}, ...}
p.onopentag = function(node) {
var nsName = node.name;
var attrs = node.attributes;
var name = splitQName(nsName).name,
attributeName,
top = stack[stack.length - 1],
topSchema = top.schema,
elementAttributes = {},
hasNonXmlnsAttribute = false,
hasNilAttribute = false,
obj = {};
var originalName = name;
if (!objectName && top.name === 'Body' && name !== 'Fault') {
var message = self.definitions.messages[name];
// Support RPC/literal messages where response body contains one element named
// after the operation + 'Response'. See http://www.w3.org/TR/wsdl#_names
if (!message) {
// Determine if this is request or response
var isInput = false;
var isOutput = false;
if ((/Response$/).test(name)) {
isOutput = true;
name = name.replace(/Response$/, '');
} else if ((/Request$/).test(name)) {
isInput = true;
name = name.replace(/Request$/, '');
} else if ((/Solicit$/).test(name)) {
isInput = true;
name = name.replace(/Solicit$/, '');
}
// Look up the appropriate message as given in the portType's operations
var portTypes = self.definitions.portTypes;
var portTypeNames = Object.keys(portTypes);
// Currently this supports only one portType definition.
var portType = portTypes[portTypeNames[0]];
if (isInput)
name = portType.methods[name].input.$name;
else
name = portType.methods[name].output.$name;
message = self.definitions.messages[name];
// 'cache' this alias to speed future lookups
self.definitions.messages[originalName] = self.definitions.messages[name];
}
topSchema = message.description(self.definitions);
objectName = originalName;
}
if (attrs.href) {
id = attrs.href.substr(1);
if (!refs[id])
refs[id] = {hrefs: [], obj: null};
refs[id].hrefs.push({par: top.object, key: name, obj: obj});
}
if (id = attrs.id) {
if (!refs[id])
refs[id] = {hrefs: [], obj: null};
}
//Handle element attributes
for(attributeName in attrs){
if(/^xmlns:|^xmlns$/.test(attributeName)){
xmlns[splitQName(attributeName).name] = attrs[attributeName];
continue;
}
hasNonXmlnsAttribute = true;
elementAttributes[attributeName] = attrs[attributeName];
}
for(attributeName in elementAttributes){
var res = splitQName(attributeName);
if(res.name === 'nil' && xmlns[res.prefix] === 'http://www.w3.org/2001/XMLSchema-instance'){
hasNilAttribute = true;
break;
}
}
if(hasNonXmlnsAttribute)obj[self.options.attributesKey] = elementAttributes;
// Pick up the schema for the type specified in element's xsi:type attribute.
var xsiTypeSchema;
var xsiType = elementAttributes['xsi:type'];
if (xsiType) {
var type = splitQName(xsiType);
var typeURI;
if (type.prefix === TNS_PREFIX) {
// In case of xsi:type = "MyType"
typeURI = xmlns[type.prefix] || xmlns.xmlns;
} else {
typeURI = xmlns[type.prefix];
}
var typeDef = self.findSchemaObject(typeURI, type.name);
if (typeDef) {
xsiTypeSchema = typeDef.description(self.definitions);
}
}
if (topSchema && topSchema[name + '[]'])
name = name + '[]';
stack.push({name: originalName, object: obj, schema: (xsiTypeSchema || (topSchema && topSchema[name])), id: attrs.id, nil: hasNilAttribute});
};
p.onclosetag = function(nsName) {
var cur = stack.pop(),
obj = cur.object,
top = stack[stack.length - 1],
topObject = top.object,
topSchema = top.schema,
name = splitQName(nsName).name;
if (typeof cur.schema === 'string' && (cur.schema === 'string' || cur.schema.split(':')[1] === 'string')) {
if (typeof obj === 'object' && Object.keys(obj).length === 0) obj = cur.object = '';
}
if(cur.nil === true) {
return;
}
if (_.isPlainObject(obj) && !Object.keys(obj).length) {
obj = null;
}
if (topSchema && topSchema[name + '[]']) {
if (!topObject[name])
topObject[name] = [];
topObject[name].push(obj);
} else if (name in topObject) {
if (!Array.isArray(topObject[name])) {
topObject[name] = [topObject[name]];
}
topObject[name].push(obj);
} else {
topObject[name] = obj;
}
if (cur.id) {
refs[cur.id].obj = obj;
}
};
p.oncdata = function (text) {
text = trim(text);
if (!text.length)
return;
if (/<\?xml[\s\S]+\?>/.test(text)) {
var top = stack[stack.length - 1];
var value = self.xmlToObject(text);
if (top.object[self.options.attributesKey]) {
top.object[self.options.valueKey] = value;
} else {
top.object = value;
}
} else {
p.ontext(text);
}
};
p.ontext = function(text) {
text = trim(text);
if (!text.length)
return;
var top = stack[stack.length - 1];
var name = splitQName(top.schema).name,
value;
if (name === 'int' || name === 'integer') {
value = parseInt(text, 10);
} else if (name === 'bool' || name === 'boolean') {
value = text.toLowerCase() === 'true' || text === '1';
} else if (name === 'dateTime' || name === 'date') {
value = new Date(text);
} else {
// handle string or other types
if (typeof top.object !== 'string') {
value = text;
} else {
value = top.object + text;
}
}
if(top.object[self.options.attributesKey]) {
top.object[self.options.valueKey] = value;
} else {
top.object = value;
}
};
p.write(xml).close();
// merge obj with href
var merge = function(href, obj) {
for (var j in obj) {
if (obj.hasOwnProperty(j)) {
href.obj[j] = obj[j];
}
}
};
// MultiRef support: merge objects instead of replacing
for (var n in refs) {
var ref = refs[n];
for (var i = 0; i < ref.hrefs.length; i++) {
merge(ref.hrefs[i], ref.obj);
}
}
if (root.Envelope) {
var body = root.Envelope.Body;
if (body.Fault) {
var code = selectn('faultcode.$value', body.Fault) || selectn('faultcode', body.Fault);
var string = selectn('faultstring.$value', body.Fault) || selectn('faultstring', body.Fault);
var detail = selectn('detail.$value', body.Fault) || selectn('detail.message', body.Fault);
var error = new Error(code + ': ' + string + (detail ? ': ' + detail : ''));
error.root = root;
throw error;
}
return root.Envelope;
}
return root;
};
/**
* Look up a XSD type or element by namespace URI and name
* @param {String} nsURI Namespace URI
* @param {String} qname Local or qualified name
* @returns {*} The XSD type/element definition
*/
WSDL.prototype.findSchemaObject = function(nsURI, qname) {
if (!nsURI || !qname) {
return null;
}
var def = null;
if (this.definitions.schemas) {
var schema = this.definitions.schemas[nsURI];
if (schema) {
if (qname.indexOf(':') !== -1) {
qname = qname.substring(qname.indexOf(':') + 1, qname.length);
}
// if the client passed an input element which has a `$lookupType` property instead of `$type`
// the `def` is found in `schema.elements`.
def = schema.complexTypes[qname] || schema.types[qname] || schema.elements[qname];
}
}
return def;
};
/**
* Create document style xml string from the parameters
* @param {String} name
* @param {*} params
* @param {String} nsPrefix
* @param {String} nsURI
* @param {String} type
*/
WSDL.prototype.objectToDocumentXML = function(name, params, nsPrefix, nsURI, type) {
var args = {};
args[name] = params;
var parameterTypeObj = type ? this.findSchemaObject(nsURI, type) : null;
return this.objectToXML(args, null, nsPrefix, nsURI, true, null, parameterTypeObj);
};
/**
* Create RPC style xml string from the parameters
* @param {String} name
* @param {*} params
* @param {String} nsPrefix
* @param {String} nsURI
* @returns {string}
*/
WSDL.prototype.objectToRpcXML = function(name, params, nsPrefix, nsURI) {
var parts = [];
var defs = this.definitions;
var nsAttrName = '_xmlns';
nsPrefix = nsPrefix || findPrefix(defs.xmlns, nsURI);
nsURI = nsURI || defs.xmlns[nsPrefix];
nsPrefix = nsPrefix === TNS_PREFIX ? '' : (nsPrefix + ':');
parts.push(['<', nsPrefix, name, '>'].join(''));
for (var key in params) {
if (!params.hasOwnProperty(key)) continue;
if (key !== nsAttrName) {
var value = params[key];
parts.push(['<', key, '>'].join(''));
parts.push((typeof value === 'object') ? this.objectToXML(value, key, nsPrefix, nsURI) : xmlEscape(value));
parts.push(['</', key, '>'].join(''));
}
}
parts.push(['</', nsPrefix, name, '>'].join(''));
return parts.join('');
};
/**
* Convert an object to XML. This is a recursive method as it calls itself.
*
* @param {Object} obj the object to convert.
* @param {String} name the name of the element (if the object being traversed is
* an element).
* @param {String} nsPrefix the namespace prefix of the object I.E. xsd.
* @param {String} nsURI the full namespace of the object I.E. http://w3.org/schema.
* @param {Boolean} isFirst whether or not this is the first item being traversed.
* @param {?} xmlnsAttr
* @param {?} parameterTypeObject
* @param {NamespaceContext} nsContext Namespace context
*/
WSDL.prototype.objectToXML = function(obj, name, nsPrefix, nsURI, isFirst, xmlnsAttr, schemaObject, nsContext) {
var self = this;
var schema = this.definitions.schemas[nsURI];
var parentNsPrefix = nsPrefix ? nsPrefix.parent : undefined;
if(typeof parentNsPrefix !== 'undefined') {
//we got the parentNsPrefix for our array. setting the namespace-variable back to the current namespace string
nsPrefix = nsPrefix.current;
}
var soapHeader = !schema;
var qualified = schema && schema.$elementFormDefault === 'qualified';
var parts = [];
var prefixNamespace = (nsPrefix || qualified) && nsPrefix !== TNS_PREFIX;
var xmlnsAttrib = '';
if (nsURI && isFirst) {
if(self.options.overrideRootElement && self.options.overrideRootElement.xmlnsAttributes) {
self.options.overrideRootElement.xmlnsAttributes.forEach(function(attribute) {
xmlnsAttrib += ' ' + attribute.name + '="' + attribute.value + '"';
});
} else {
if (prefixNamespace && this.options.ignoredNamespaces.indexOf(nsPrefix) === -1) {
// resolve the prefix namespace
xmlnsAttrib += ' xmlns:' + nsPrefix + '="' + nsURI + '"';
}
// only add default namespace if the schema elementFormDefault is qualified
if (qualified || soapHeader) xmlnsAttrib += ' xmlns="' + nsURI + '"';
}
}
if (!nsContext) {
nsContext = new NamespaceContext();
nsContext.declareNamespace(nsPrefix, nsURI);
} else {
nsContext.pushContext();
}
// explicitly use xmlns attribute if available
if (xmlnsAttr && !(self.options.overrideRootElement && self.options.overrideRootElement.xmlnsAttributes)) {
xmlnsAttrib = xmlnsAttr;
}
var ns = '';
if(self.options.overrideRootElement && isFirst) {
ns = self.options.overrideRootElement.namespace + ':';
} else if (prefixNamespace && ((qualified || isFirst) || soapHeader) && this.options.ignoredNamespaces.indexOf(nsPrefix) === -1) {
// prefix element
ns = nsPrefix.indexOf(":") === -1 ? nsPrefix + ':' : nsPrefix;
}
var i, n;
// start building out XML string.
if (Array.isArray(obj)) {
for (i = 0, n = obj.length; i < n; i++) {
var item = obj[i];
var arrayAttr = self.processAttributes(item, nsContext),
correctOuterNsPrefix = parentNsPrefix || ns; //using the parent namespace prefix if given
parts.push(['<', correctOuterNsPrefix, name, arrayAttr, xmlnsAttrib, '>'].join(''));
parts.push(self.objectToXML(item, name, nsPrefix, nsURI, false, null, schemaObject, nsContext));
parts.push(['</', correctOuterNsPrefix, name, '>'].join(''));
}
} else if (typeof obj === 'object') {
for (name in obj) {
if (!obj.hasOwnProperty(name)) continue;
//don't process attributes as element
if (name === self.options.attributesKey) {
continue;
}
//Its the value of a xml object. Return it directly.
if (name === self.options.xmlKey){
nsContext.popContext();
return obj[name];
}
//Its the value of an item. Return it directly.
if (name === self.options.valueKey) {
nsContext.popContext();
return xmlEscape(obj[name]);
}
var child = obj[name];
if (typeof child === 'undefined')
continue;
var attr = self.processAttributes(child, nsContext);
var value = '';
var nonSubNameSpace = '';
var emptyNonSubNameSpace = false;
var nameWithNsRegex = /^([^:]+):([^:]+)$/.exec(name);
if (nameWithNsRegex) {
nonSubNameSpace = nameWithNsRegex[1] + ':';
name = nameWithNsRegex[2];
} else if(name[0] === ':'){
emptyNonSubNameSpace = true;
name = name.substr(1);
}
if (isFirst) {
value = self.objectToXML(child, name, nsPrefix, nsURI, false, null, schemaObject, nsContext);
} else {
if (self.definitions.schemas) {
if (schema) {
var childSchemaObject = self.findChildSchemaObject(schemaObject, name);
//find sub namespace if not a primitive
if (childSchemaObject &&
((childSchemaObject.$type && (childSchemaObject.$type.indexOf('xsd:') === -1)) ||
childSchemaObject.$ref || childSchemaObject.$name)) {
/*if the base name space of the children is not in the ingoredSchemaNamspaces we use it.
This is because in some services the child nodes do not need the baseNameSpace.
*/
var childNsPrefix = '';
var childName = '';
var childNsURI;
var childXmlnsAttrib = '';
var elementQName = childSchemaObject.$ref || childSchemaObject.$name;
if (elementQName) {
elementQName = splitQName(elementQName);
childName = elementQName.name;
if (elementQName.prefix === TNS_PREFIX) {
// Local element
childNsURI = childSchemaObject.$targetNamespace;
childNsPrefix = nsContext.registerNamespace(childNsURI);
for (i = 0, n = this.ignoredNamespaces.length; i < n; i++) {
if (this.ignoredNamespaces[i] === childNsPrefix) {
childNsPrefix = nsPrefix;
break;
}
}
} else {
childNsPrefix = elementQName.prefix;
for (i = 0, n = this.ignoredNamespaces.length; i < n; i++) {
if (this.ignoredNamespaces[i] === childNsPrefix) {
childNsPrefix = nsPrefix;
break;
}
}
childNsURI = schema.xmlns[childNsPrefix] || self.definitions.xmlns[childNsPrefix];
}
var unqualified = false;
// Check qualification form for local elements
if (childSchemaObject.$name && childSchemaObject.targetNamespace === undefined) {
if (childSchemaObject.$form === 'unqualified') {
unqualified = true;
} else if (childSchemaObject.$form === 'qualified') {
unqualified = false;
} else {
unqualified = schema.$elementFormDefault === 'unqualified';
}
}
if (unqualified) {
childNsPrefix = '';
}
if (childNsURI && childNsPrefix) {
if (nsContext.declareNamespace(childNsPrefix, childNsURI)) {
childXmlnsAttrib = ' xmlns:' + childNsPrefix + '="' + childNsURI + '"';
xmlnsAttrib += childXmlnsAttrib;
}
}
}
var resolvedChildSchemaObject;
if (childSchemaObject.$type) {
var typeQName = splitQName(childSchemaObject.$type);
var typePrefix = typeQName.prefix;
var typeURI = schema.xmlns[typePrefix] || self.definitions.xmlns[typePrefix];
childNsURI = typeURI;
if (typeURI !== 'http://www.w3.org/2001/XMLSchema') {
// Add the prefix/namespace mapping, but not declare it
nsContext.addNamespace(typeQName.prefix, typeURI);
}
resolvedChildSchemaObject =
self.findSchemaType(typeQName.name, typeURI) || childSchemaObject;
} else {
resolvedChildSchemaObject =
self.findSchemaObject(childNsURI, childName) || childSchemaObject;
}
if (childSchemaObject.$baseNameSpace && this.options.ignoreBaseNameSpaces) {
childNsPrefix = nsPrefix;
childNsURI = nsURI;
}
if (this.options.ignoreBaseNameSpaces) {
childNsPrefix = '';
childNsURI = '';
}
ns = childNsPrefix ? childNsPrefix + ':' : '';
if(Array.isArray(child)) {
//for arrays, we need to remember the current namespace
childNsPrefix = {
current: childNsPrefix,
parent: ns
};
}
value = self.objectToXML(child, name, childNsPrefix, childNsURI,
false, null, resolvedChildSchemaObject, nsContext);
} else if (obj[self.options.attributesKey] && obj[self.options.attributesKey].xsi_type) {
//if parent object has complex type defined and child not found in parent
var completeChildParamTypeObject = self.findChildSchemaObject(
obj[self.options.attributesKey].xsi_type.type,
obj[self.options.attributesKey].xsi_type.xmlns);
nonSubNameSpace = obj[self.options.attributesKey].xsi_type.prefix + ':';
nsContext.addNamespace(obj[self.options.attributesKey].xsi_type.prefix,
obj[self.options.attributesKey].xsi_type.xmlns);
value = self.objectToXML(child, name, obj[self.options.attributesKey].xsi_type.prefix,
obj[self.options.attributesKey].xsi_type.xmlns, false, null, null, nsContext);
} else {
if(Array.isArray(child)) {
name = nonSubNameSpace + name;
}
value = self.objectToXML(child, name, nsPrefix, nsURI, false, null, null, nsContext);
}
} else {
value = self.objectToXML(child, name, nsPrefix, nsURI, false, null, null, nsContext);
}
}
}
if (!Array.isArray(child)) {
parts.push(['<', emptyNonSubNameSpace ? '' : nonSubNameSpace || ns, name, attr, xmlnsAttrib,
(child === null ? ' xsi:nil="true"' : ''), '>'].join(''));
}
parts.push(value);
if (!Array.isArray(child)) {
parts.push(['</', emptyNonSubNameSpace ? '' : nonSubNameSpace || ns, name, '>'].join(''));
}
}
} else if (obj !== undefined) {
parts.push(xmlEscape(obj));
}
nsContext.popContext();
return parts.join('');
};
WSDL.prototype.processAttributes = function(child, nsContext) {
var attr = '';
if(child === null) {
child = [];
}
var attrObj = child[this.options.attributesKey];
if (attrObj && attrObj.xsi_type) {
var xsiType = attrObj.xsi_type;
var prefix = xsiType.prefix || xsiType.namespace;
// Generate a new namespace for complex extension if one not provided
if (!prefix) {
prefix = nsContext.registerNamespace(xsiType.xmlns);
} else {
nsContext.declareNamespace(prefix, xsiType.xmlns);
}
xsiType.prefix = prefix;
}
if (attrObj) {
for (var attrKey in attrObj) {
//handle complex extension separately
if (attrKey === 'xsi_type') {
var attrValue = attrObj[attrKey];
attr += ' xsi:type="' + attrValue.prefix + ':' + attrValue.type + '"';
attr += ' xmlns:' + attrValue.prefix + '="' + attrValue.xmlns + '"';
continue;
} else {
attr += ' ' + attrKey + '="' + xmlEscape(attrObj[attrKey]) + '"';
}
}
}
return attr;
};
/**
* Look up a schema type definition
* @param name
* @param nsURI
* @returns {*}
*/
WSDL.prototype.findSchemaType = function(name, nsURI) {
if (!this.definitions.schemas || !name || !nsURI) {
return null;
}
var schema = this.definitions.schemas[nsURI];
if (!schema || !schema.complexTypes) {
return null;
}
return schema.complexTypes[name];
};
WSDL.prototype.findChildSchemaObject = function(parameterTypeObj, childName) {
if (!parameterTypeObj || !childName) {
return null;
}
var found = null,
i = 0,
child,
ref;
if(Array.isArray(parameterTypeObj.$lookupTypes) && parameterTypeObj.$lookupTypes.length) {
var types = parameterTypeObj.$lookupTypes;
for(i = 0; i < types.length; i++) {
var typeObj = types[i];
if(typeObj.$name === childName) {
found = typeObj;
break;
}
}
}
var object = parameterTypeObj;
if (object.$name === childName && object.name === 'element') {
return object;
}
if (object.$ref) {
ref = splitQName(object.$ref);
if (ref.name === childName) {
return object;
}
}
var childNsURI;
if (object.$type) {
var typeInfo = splitQName(object.$type);
if (typeInfo.prefix === TNS_PREFIX) {
childNsURI = parameterTypeObj.$targetNamespace;
} else {
childNsURI = this.definitions.xmlns[typeInfo.prefix];
}
var typeDef = this.findSchemaType(typeInfo.name, childNsURI);
if (typeDef) {
return this.findChildSchemaObject(typeDef, childName);
}
}
if (object.children) {
for (i = 0, child; child = object.children[i]; i++) {
found = this.findChildSchemaObject(child, childName);
if (found) {
break;
}
if (child.$base) {
var baseQName = splitQName(child.$base);
var childNameSpace = baseQName.prefix === TNS_PREFIX ? '' : baseQName.prefix;
childNsURI = this.definitions.xmlns[baseQName.prefix];
var foundBase = this.findSchemaType(baseQName.name, childNsURI);
if (foundBase) {
found = this.findChildSchemaObject(foundBase, childName);
if (found) {
found.$baseNameSpace = childNameSpace;
found.$type = childNameSpace + ':' + childName;
break;
}
}
}
}
}
if (!found && object.$name === childName) {
return object;
}
return found;
};
WSDL.prototype._parse = function(xml) {
var self = this,
p = sax.parser(true),
stack = [],
root = null,
types = null,
schema = null,
options = self.options;
p.onopentag = function(node) {
var nsName = node.name;
var attrs = node.attributes;
var top = stack[stack.length - 1];
var name;
if (top) {
try {
top.startElement(stack, nsName, attrs, options);
} catch (e) {
if (self.options.strict) {
throw e;
} else {
stack.push(new Element(nsName, attrs, options));
}
}
} else {
name = splitQName(nsName).name;
if (name === 'definitions') {
root = new DefinitionsElement(nsName, attrs, options);
stack.push(root);
} else if (name === 'schema') {
// Shim a structure in here to allow the proper objects to be created when merging back.
root = new DefinitionsElement('definitions', {}, {});
types = new TypesElement('types', {}, {});
schema = new SchemaElement(nsName, attrs, options);
types.addChild(schema);
root.addChild(types);
stack.push(schema);
} else {
throw new Error('Unexpected root element of WSDL or include');
}
}
};
p.onclosetag = function(name) {
var top = stack[stack.length - 1];
assert(top, 'Unmatched close tag: ' + name);
top.endElement(stack, name);
};
p.write(xml).close();
return root;
};
WSDL.prototype._fromXML = function(xml) {
this.definitions = this._parse(xml);
this.definitions.descriptions = {
types:{}
};
this.xml = xml;
};
WSDL.prototype._fromServices = function(services) {
};
WSDL.prototype._xmlnsMap = function() {
var xmlns = this.definitions.xmlns;
var str = '';
for (var alias in xmlns) {
if (alias === '' || alias === TNS_PREFIX)
continue;
var ns = xmlns[alias];
switch (ns) {
case "http://xml.apache.org/xml-soap" : // apachesoap
case "http://schemas.xmlsoap.org/wsdl/" : // wsdl
case "http://schemas.xmlsoap.org/wsdl/soap/" : // wsdlsoap
case "http://schemas.xmlsoap.org/wsdl/soap12/": // wsdlsoap12
case "http://schemas.xmlsoap.org/soap/encoding/" : // soapenc
case "http://www.w3.org/2001/XMLSchema" : // xsd
continue;
}
if (~ns.indexOf('http://schemas.xmlsoap.org/'))
continue;
if (~ns.indexOf('http://www.w3.org/'))
continue;
if (~ns.indexOf('http://xml.apache.org/'))
continue;
str += ' xmlns:' + alias + '="' + ns + '"';
}
return str;
};
/*
* Have another function to load previous WSDLs as we
* don't want this to be invoked externally (expect for tests)
* This will attempt to fix circular dependencies with XSD files,
* Given
* - file.wsdl
* - xs:import namespace="A" schemaLocation: A.xsd
* - A.xsd
* - xs:import namespace="B" schemaLocation: B.xsd
* - B.xsd
* - xs:import namespace="A" schemaLocation: A.xsd
* file.wsdl will start loading, import A, then A will import B, which will then import A
* Because A has already started to load previously it will be returned right away and
* have an internal circular reference
* B would then complete loading, then A, then file.wsdl
* By the time file A starts processing its includes its definitions will be already loaded,
* this is the only thing that B will depend on when "opening" A
*/
function open_wsdl_recursive(uri, options, callback) {
var fromCache,
WSDL_CACHE;
if (typeof options === 'function') {
callback = options;
options = {};
}
WSDL_CACHE = options.WSDL_CACHE;
if (fromCache = WSDL_CACHE[ uri ]) {
return callback.call(fromCache, null, fromCache);
}
return open_wsdl(uri, options, callback);
}
function open_wsdl(uri, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
// initialize cache when calling open_wsdl directly
var WSDL_CACHE = options.WSDL_CACHE || {};
var request_headers = options.wsdl_headers;
var request_options = options.wsdl_options;
var wsdl;
if (!/^https?:/.test(uri)) {
debug('Reading file: %s', uri);
fs.readFile(uri, 'utf8', function(err, definition) {
if (err) {
callback(err);
}
else {
wsdl = new WSDL(definition, uri, options);
WSDL_CACHE[ uri ] = wsdl;
wsdl.WSDL_CACHE = WSDL_CACHE;
wsdl.onReady(callback);
}
});
}
else {
debug('Reading url: %s', uri);
var httpClient = options.httpClient || new HttpClient(options);
httpClient.request(uri, null /* options */, function(err, response, definition) {
if (err) {
callback(err);
} else if (response && response.statusCode === 200) {
wsdl = new WSDL(definition, uri, options);
WSDL_CACHE[ uri ] = wsdl;
wsdl.WSDL_CACHE = WSDL_CACHE;
wsdl.onReady(callback);
} else {
callback(new Error('Invalid WSDL URL: ' + uri + "\n\n\r Code: " + response.statusCode + "\n\n\r Response Body: " + response.body));
}
}, request_headers, request_options);
}
return wsdl;
}
exports.open_wsdl = open_wsdl;
exports.WSDL = WSDL;
| momchil-anachkov/su-translation-app | src/node/node_modules/soap/lib/wsdl.js | JavaScript | gpl-3.0 | 63,995 |
package com.gmail.mrphpfan.mccombatlevel;
import com.google.common.base.Enums;
import com.google.common.base.Optional;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
public class Effects {
public static Effects create(ConfigurationSection configSection) {
boolean lightning = configSection.getBoolean("lightning");
String effectType = configSection.getString("effect");
Effect particleEffect = null;
if (!effectType.isEmpty()) {
Optional<Effect> optionalEffect = Enums.getIfPresent(Effect.class, effectType.toUpperCase());
if (optionalEffect.isPresent()) {
particleEffect = optionalEffect.get();
}
}
ConfigurationSection soundSection = configSection.getConfigurationSection("sound");
String soundType = soundSection.getString("type");
Sound sound = null;
Optional<Sound> optionalSound = Enums.getIfPresent(Sound.class, soundType.toUpperCase());
if (optionalSound.isPresent()) {
sound = optionalSound.get();
}
float pitch = (float) soundSection.getDouble("pitch");
float volume = (float) soundSection.getDouble("volume");
return new Effects(lightning, particleEffect, sound, pitch, volume);
}
private final boolean lightning;
private final Effect particleEffect;
private final Sound sound;
private final float pitch;
private final float volume;
public Effects(boolean lightning, Effect particleEffect, Sound sound, float pitch, float volume) {
this.lightning = lightning;
this.particleEffect = particleEffect;
this.sound = sound;
this.pitch = pitch;
this.volume = volume;
}
public void playEffect(Player player) {
Location location = player.getLocation();
if (lightning) {
player.getWorld().strikeLightningEffect(location);
}
if (sound != null) {
player.playSound(location, sound, volume, pitch);
}
if (particleEffect != null) {
player.playEffect(location, particleEffect, particleEffect.getData());
}
}
}
| games647/McCombatLevel | src/main/java/com/gmail/mrphpfan/mccombatlevel/Effects.java | Java | gpl-3.0 | 2,293 |
/*
Aversive++
Copyright (C) 2014 Eirbot
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/>.
*/
#ifndef AVR_TASK_HPP
#define AVR_TASK_HPP
#include "../../common/system/task.hpp"
#endif//AVR_TASK_HPP
| astralien3000/aversive-- | include/avr/system/task.hpp | C++ | gpl-3.0 | 1,224 |
/*
* Copyright (C) 2019 Nethesis S.r.l.
* http://www.nethesis.it - nethserver@nethesis.it
*
* This script is part of NethServer.
*
* NethServer 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 any later version.
*
* NethServer 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 NethServer. If not, see COPYING.
*/
import Vue from "vue";
import VueI18n from "vue-i18n";
import Router from "vue-router";
import VueToggleButton from "vue-js-toggle-button";
import DocInfo from "./directives/DocInfo.vue";
import VueGoodTable from "vue-good-table";
import LiquorTree from "liquor-tree";
import App from "./App.vue";
import Dashboard from "./views/Dashboard.vue";
import Restore from "./views/Restore.vue";
import About from "./views/About.vue";
import UtilService from "./services/util";
Vue.mixin(UtilService);
import "./filters";
Vue.config.productionTip = false;
Vue.use(VueToggleButton);
Vue.component("doc-info", DocInfo);
Vue.use(VueGoodTable);
Vue.use(LiquorTree);
Vue.use(VueI18n);
const i18n = new VueI18n();
Vue.use(Router);
const router = new Router({
mode: "hash",
base: process.env.BASE_URL,
routes: [
{ path: "/", redirect: "/dashboard" },
{ path: "/dashboard", component: Dashboard },
{ path: "/restore", component: Restore },
{ path: "/about", name: "about", component: About }
]
});
router.replace("/dashboard");
var app = new Vue({
i18n,
router,
render: h => h(App)
});
nethserver.fetchTranslatedStrings(function(data) {
i18n.setLocaleMessage("cockpit", data);
i18n.locale = "cockpit";
app.$mount("#app"); // Start VueJS application
});
| NethServer/nethserver-restore-data | ui/src/main.js | JavaScript | gpl-3.0 | 2,022 |
import sys,time
from . import argparser
if sys.version < '3':
from threading import Semaphore
class Barrier:
def __init__(self, n):
self.n = n
self.count = 0
self.mutex = Semaphore(1)
self.barrier = Semaphore(0)
def wait(self):
self.mutex.acquire()
self.count = self.count + 1
self.mutex.release()
if self.count == self.n: self.barrier.release()
self.barrier.acquire()
self.barrier.release()
else:
from threading import Barrier
def print_verbose(*args):
if argparser.args.verbose:
print(args)
def die(msg=None):
if msg: print (msg)
sys.exit()
def print_service(svc):
print("Service Name: %s" % svc["name"])
print(" Host: %s" % svc["host"])
print(" Description: %s" % svc["description"])
print(" Provided By: %s" % svc["provider"])
print(" Protocol: %s" % svc["protocol"])
print(" channel/PSM: %s" % svc["port"])
print(" svc classes: %s "% svc["service-classes"])
print(" profiles: %s "% svc["profiles"])
print(" service id: %s "% svc["service-id"])
def inc_last_octet(addr):
return addr[:15] + hex((int(addr.split(':')[5], 16) + 1) & 0xff).replace('0x','').upper()
def RateLimited(maxPerSecond):
"""
Decorator for rate limiting a function
"""
minInterval = 1.0 / float(maxPerSecond)
def decorate(func):
lastTimeCalled = [0.0]
def rateLimitedFunction(*args,**kargs):
elapsed = time.clock() - lastTimeCalled[0]
leftToWait = minInterval - elapsed
if leftToWait>0:
time.sleep(leftToWait)
ret = func(*args,**kargs)
lastTimeCalled[0] = time.clock()
return ret
return rateLimitedFunction
return decorate
| intfrr/btproxy | libbtproxy/utils.py | Python | gpl-3.0 | 1,903 |
#region Copyright
/////////////////////////////////////////////////////////////////////////////
// Altaxo: a data processing and data plotting program
// Copyright (C) 2002-2011 Dr. Dirk Lellinger
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
/////////////////////////////////////////////////////////////////////////////
#endregion Copyright
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
#nullable enable
namespace Altaxo.Units
{
/// <summary>
/// Represents an SI prefix, such as nano, micro, Mega, Giga etc.
/// </summary>
public class SIPrefix : IUnit, IEquatable<SIPrefix>, IComparable<SIPrefix>
{
private string _name;
private string _shortCut;
private int _exponent;
private double _cachedFactor;
private double _cachedDivider;
private static List<SIPrefix> _instances;
/// <summary>List with all prefixes, including the prefix <see cref="None"/>.</summary>
private static SIPrefixList _allPrefixes;
/// <summary>List with only the prefix <see cref="None"/>.</summary>
private static SIPrefixList _nonePrefixList;
/// <summary>List with only the prefixes with an exponent as a multiple of 3..</summary>
private static SIPrefixList _multipleOf3Prefixes;
/// <summary>Dictionary of known prefixes, where the key is the exponent and the value is the known prefix.</summary>
private static Dictionary<int, SIPrefix> _prefixByExponent;
private static SIPrefix _prefix_yocto;
private static SIPrefix _prefix_zepto;
private static SIPrefix _prefix_atto;
private static SIPrefix _prefix_femto;
private static SIPrefix _prefix_pico;
private static SIPrefix _prefix_nano;
private static SIPrefix _prefix_micro;
private static SIPrefix _prefix_milli;
private static SIPrefix _prefix_centi;
private static SIPrefix _prefix_deci;
private static SIPrefix _prefix_none;
private static SIPrefix _prefix_deca;
private static SIPrefix _prefix_hecto;
private static SIPrefix _prefix_kilo;
private static SIPrefix _prefix_mega;
private static SIPrefix _prefix_giga;
private static SIPrefix _prefix_tera;
private static SIPrefix _prefix_peta;
private static SIPrefix _prefix_exa;
private static SIPrefix _prefix_zetta;
private static SIPrefix _prefix_yotta;
#region Serialization
[Altaxo.Serialization.Xml.XmlSerializationSurrogateFor(typeof(SIPrefix), 0)]
public class SerializationSurrogate0 : Altaxo.Serialization.Xml.IXmlSerializationSurrogate
{
public void Serialize(object obj, Altaxo.Serialization.Xml.IXmlSerializationInfo info)
{
var s = (SIPrefix)obj;
info.AddValue("Exponent", s.Exponent);
info.AddValue("Name", s.Name);
info.AddValue("Shortcut", s.ShortCut);
}
public object Deserialize(object? o, Altaxo.Serialization.Xml.IXmlDeserializationInfo info, object? parent)
{
var exponent = info.GetInt32("Exponent");
var name = info.GetString("Name");
var shortcut = info.GetString("Shortcut");
if (SIPrefix.TryGetPrefixFromExponent(exponent, out var prefix))
return prefix;
else
return new SIPrefix(name, shortcut, exponent);
}
}
#endregion
public static SIPrefix Yocto { get { return _prefix_yocto; } }
public static SIPrefix Zepto { get { return _prefix_zepto; } }
public static SIPrefix Atto { get { return _prefix_atto; } }
public static SIPrefix Femto { get { return _prefix_femto; } }
public static SIPrefix Pico { get { return _prefix_pico; } }
public static SIPrefix Nano { get { return _prefix_nano; } }
public static SIPrefix Micro { get { return _prefix_micro; } }
public static SIPrefix Milli { get { return _prefix_milli; } }
public static SIPrefix Centi { get { return _prefix_centi; } }
public static SIPrefix Deci { get { return _prefix_deci; } }
public static SIPrefix None { get { return _prefix_none; } }
public static SIPrefix Deca { get { return _prefix_deca; } }
public static SIPrefix Hecto { get { return _prefix_hecto; } }
public static SIPrefix Kilo { get { return _prefix_kilo; } }
public static SIPrefix Mega { get { return _prefix_mega; } }
public static SIPrefix Giga { get { return _prefix_giga; } }
public static SIPrefix Tera { get { return _prefix_tera; } }
public static SIPrefix Peta { get { return _prefix_peta; } }
public static SIPrefix Exa { get { return _prefix_exa; } }
public static SIPrefix Zetta { get { return _prefix_zetta; } }
public static SIPrefix Yotta { get { return _prefix_yotta; } }
/// <summary>
/// Gets the maximum length of the shortcuts of any of the known prefixes.
/// </summary>
/// <value>
/// The maximum length of of the shortcuts of any of the known prefixes.
/// </value>
public static int MaxShortCutLength { get { return 2; } }
/// <summary>
/// Gets the minimum length of the shortcuts of any of the known prefixes.
/// </summary>
/// <value>
/// The minimum length of of the shortcuts of any of the known prefixes.
/// </value>
public static int MinShortCutLength { get { return 1; } }
public static SIPrefix SmallestPrefix { get { return _prefix_yocto; } }
public static SIPrefix LargestPrefix { get { return _prefix_yotta; } }
static SIPrefix()
{
_instances = new List<SIPrefix>
{
(_prefix_yocto = new SIPrefix("yocto", "y", -24)),
(_prefix_zepto = new SIPrefix("zepto", "z", -21)),
(_prefix_atto = new SIPrefix("atto", "a", -18)),
(_prefix_femto = new SIPrefix("femto", "f", -15)),
(_prefix_pico = new SIPrefix("pico", "p", -12)),
(_prefix_nano = new SIPrefix("nano", "n", -9)),
(_prefix_micro = new SIPrefix("micro", "µ", -6)),
(_prefix_milli = new SIPrefix("milli", "m", -3)),
(_prefix_centi = new SIPrefix("centi", "c", -2)),
(_prefix_deci = new SIPrefix("deci", "d", -1)),
(_prefix_none = new SIPrefix("", "", 0)),
(_prefix_deca = new SIPrefix("deca", "da", 1)),
(_prefix_hecto = new SIPrefix("hecto", "h", 2)),
(_prefix_kilo = new SIPrefix("kilo", "k", 3)),
(_prefix_mega = new SIPrefix("mega", "M", 6)),
(_prefix_giga = new SIPrefix("giga", "G", 9)),
(_prefix_tera = new SIPrefix("tera", "T", 12)),
(_prefix_peta = new SIPrefix("peta", "P", 15)),
(_prefix_exa = new SIPrefix("exa", "E", 18)),
(_prefix_zetta = new SIPrefix("zetta", "Z", 21)),
(_prefix_yotta = new SIPrefix("yotta", "Y", 24))
};
_nonePrefixList = new SIPrefixList(new SIPrefix[] { _prefix_none });
_allPrefixes = new SIPrefixList(_instances);
_multipleOf3Prefixes = new SIPrefixList(new SIPrefix[] {
_prefix_yocto,
_prefix_zepto,
_prefix_atto,
_prefix_femto,
_prefix_pico,
_prefix_nano,
_prefix_micro,
_prefix_milli,
_prefix_none,
_prefix_kilo,
_prefix_mega,
_prefix_giga,
_prefix_tera,
_prefix_peta,
_prefix_exa,
_prefix_zetta,
_prefix_yotta
});
_prefixByExponent = new Dictionary<int, SIPrefix>();
foreach (var prefix in _instances)
_prefixByExponent.Add(prefix.Exponent, prefix);
}
/// <summary>
/// Returns a list with all known prefixes, including the prefix <see cref="None"/>.
/// </summary>
public static ISIPrefixList ListWithAllKnownPrefixes
{
get
{
return _allPrefixes;
}
}
/// <summary>
/// Returns a list with prefixes, for which the exponent is a multiple of 3, including the prefix <see cref="None"/>.
/// </summary>
public static ISIPrefixList LisOfPrefixesWithMultipleOf3Exponent
{
get
{
return _multipleOf3Prefixes;
}
}
/// <summary>
/// Returns a list that contains only the prefix <see cref="None"/>.
/// </summary>
public static ISIPrefixList ListWithNonePrefixOnly
{
get
{
return _nonePrefixList;
}
}
/// <summary>
/// Try the get a prefix given the prefix'es shortcut.
/// </summary>
/// <param name="shortcut">The shortcut of the prefix.</param>
/// <returns>The prefix to which the given shortcut belongs. Null if no such prefix could be found.</returns>
/// <exception cref="ArgumentNullException">shortcut</exception>
public static SIPrefix? TryGetPrefixFromShortcut(string shortcut)
{
if (string.IsNullOrEmpty(shortcut))
throw new ArgumentNullException(nameof(shortcut));
return _allPrefixes.TryGetPrefixFromShortCut(shortcut);
}
/// <summary>
/// Deserialization constructor. Initializes a new instance of the <see cref="SIPrefix"/> class. Do not use this constructor unless you don't find
/// the prefix in the list of known prefixes.
/// </summary>
/// <param name="name">The name of the prefix.</param>
/// <param name="shortCut">The short cut of the prefix.</param>
/// <param name="exponent">The exponent associated with the prefix.</param>
public SIPrefix(string name, string shortCut, int exponent)
{
if (name is null) // string.Empty is allowed here, in order to support SIPrefix.None
throw new ArgumentNullException(nameof(name));
if (shortCut is null) // string.Empty is allowed here, in order to support SIPrefix.None
throw new ArgumentNullException(nameof(shortCut));
_name = name;
_shortCut = shortCut;
_exponent = exponent;
_cachedFactor = Altaxo.Calc.RMath.Pow(10, exponent);
_cachedDivider = Altaxo.Calc.RMath.Pow(10, -exponent);
}
public static (SIPrefix prefix, double remainingFactor) FromMultiplication(SIPrefix p1, SIPrefix p2)
{
return _allPrefixes.GetPrefixFromExponent(p1._exponent + p2._exponent);
}
public static (SIPrefix prefix, double remainingFactor) FromDivision(SIPrefix p1, SIPrefix p2)
{
return _allPrefixes.GetPrefixFromExponent(p1._exponent - p2._exponent);
}
public string Name
{
get { return _name; }
}
public string ShortCut
{
get { return _shortCut; }
}
public int Exponent
{
get { return _exponent; }
}
/// <summary>
/// Try to get a known prefix with a given exponent.
/// </summary>
/// <param name="exponent">The exponent.</param>
/// <param name="prefix">If sucessfull, returns the prefix.</param>
/// <returns>True if a known prefix with the given exponent was found; otherwise, false.</returns>
public static bool TryGetPrefixFromExponent(int exponent, [MaybeNullWhen(false)] out SIPrefix prefix)
{
return _prefixByExponent.TryGetValue(exponent, out prefix);
}
public double ToSIUnit(double x)
{
return _cachedFactor >= 1 ? x * _cachedFactor : x / _cachedDivider;
}
public double FromSIUnit(double x)
{
return _cachedDivider >= 1 ? x * _cachedDivider : x / _cachedFactor;
}
public bool CanApplySIPrefix
{
get { return false; }
}
public bool Equals(SIPrefix? other)
{
return other is { } b ? _exponent == b._exponent : false;
}
public override bool Equals(object? obj)
{
return (obj is SIPrefix other) ? Equals(other) : false;
}
public override int GetHashCode()
{
return _exponent.GetHashCode();
}
public int CompareTo(SIPrefix? other)
{
if (other is null)
throw new ArgumentNullException(nameof(other));
return _exponent == other._exponent ? 0 : _exponent < other._exponent ? -1 : 1;
}
/// <summary>
/// Multiplies two prefixes. If the result is not
/// a known prefix, an <see cref="InvalidOperationException"/> is thrown.
/// Consider using <see cref="FromMultiplication(SIPrefix, SIPrefix)"/> instead.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns>
/// The result of the operator.
/// </returns>
/// <exception cref="InvalidOperationException">$"Result of multiplication of prefix {x} and {y} is not a known prefix!</exception>
public static SIPrefix operator *(SIPrefix x, SIPrefix y)
{
var exponent = x.Exponent + y.Exponent;
if (_prefixByExponent.TryGetValue(exponent, out var resultingPrefix))
return resultingPrefix;
else
throw new InvalidOperationException($"Result of multiplication of prefix {x} and {y} is not a known prefix!");
}
#region IUnit implementation
ISIPrefixList IUnit.Prefixes
{
get { return SIPrefix.ListWithNonePrefixOnly; }
}
SIUnit IUnit.SIUnit
{
get { return Units.Dimensionless.Unity.Instance; }
}
#endregion IUnit implementation
}
}
| Altaxo/Altaxo | Altaxo/Core/Units/SIPrefix.cs | C# | gpl-3.0 | 14,273 |
/**
* Genji Scrum Tool and Issue Tracker
* Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions
* <a href="http://www.trackplus.com">Genji Scrum Tool</a>
*
* 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/>.
*/
/* $Id:$ */
package com.aurel.track.admin.customize.lists;
/**
* Base class for a system or custom list option detail
* @author Tamas
*
*/
public class OptionDetailBaseTO extends DetailBaseTO {
private Integer optionID;
private String cssStyle;
public Integer getOptionID() {
return optionID;
}
public void setOptionID(Integer optionID) {
this.optionID = optionID;
}
public String getCssStyle() {
return cssStyle;
}
public void setCssStyle(String cssStyle) {
this.cssStyle = cssStyle;
}
}
| trackplus/Genji | src/main/java/com/aurel/track/admin/customize/lists/OptionDetailBaseTO.java | Java | gpl-3.0 | 1,349 |
Point.sJSLogin.connect(pointSlotLogin);
Point.sJSUpdateVertifyCode.connect(pointUpdateVertifyCode);
var spliterBtwData = "#..#";
var spliterEnd = "#.^_^.#";
var pointLoginCheckInterval;
var pointVertifyChangeIntervalId;
// login frame
$p_lf = $("#loginIframe").contents();
function pointSlotLogin(userName, pwd, vertifyCode)
{
$p_lf.find("#al_c").val(vertifyCode);
$p_lf.find("#al_u").val(userName);
$p_lf.find("#al_p").val(pwd);
$p_lf.find("#al_c").val(vertifyCode);
setTimeout(
function()
{
// debug
Point.justForJSTest("login");
$p_lf.find("#al_submit").get(0).click();
}, 500
);
}
var pointLoginCheckValid = true; // whether login check valid flag
pointLoginCheckInterval = setInterval("pointLoginCheckSlot()", 500);
// check login even (pwd incorrect, username not exist ...)
function pointLoginCheckSlot()
{
if($p_lf.find("#al_warn").css("display") === "block")
{
if(pointLoginCheckValid)
{
Point.loginError(1, $p_lf.find("#al_warn").html());
}
pointLoginCheckValid = false;
}
else
{
pointLoginCheckValid = true;
}
}
pointVertifyChangeIntervalId = setInterval("pointVertifyCodeCheckSlot()", 200);
var lastVc = ""
function pointVertifyCodeCheckSlot()
{
var vc = $p_lf.find("#al_c_img").attr("src")
if(vc !== lastVc)
{
Point.justForJSTest("pointVertifyCodeCheckSlot: " + vc)
Point.loginError(2, vc);
lastVc = vc;
}
}
function pointUpdateVertifyCode()
{
$p_lf.find("#al_c_img").click();
}
| PointTeam/PointDownload | PointDownload/resources/xware/xware_login.js | JavaScript | gpl-3.0 | 1,587 |
/*
MOBILE SELECT MENU
*/
(function($){
//variable for storing the menu count when no ID is present
var menuCount = 0;
//plugin code
$.fn.mobileMenu = function(options){
//plugin's default options
var settings = {
switchWidth: 767,
topOptionText: 'Filter by category',
indentString: ' '
};
//function to check if selector matches a list
function isList($this){
return $this.is('ul, ol');
}
//function to decide if mobile or not
function isMobile(){
return ($(window).width() < settings.switchWidth);
}
//check if dropdown exists for the current element
function menuExists($this){
//if the list has an ID, use it to give the menu an ID
if($this.attr('id')){
return ($('#mobileMenu_'+$this.attr('id')).length > 0);
}
//otherwise, give the list and select elements a generated ID
else {
menuCount++;
$this.attr('id', 'mm'+menuCount);
return ($('#mobileMenu_mm'+menuCount).length > 0);
}
}
//change page on mobile menu selection
function goToPage($this){
if($this.val() !== null){document.location.href = $this.val()}
}
//show the mobile menu
function showMenu($this){
$this.css('display', 'none');
$('#mobileMenu_'+$this.attr('id')).show();
}
//hide the mobile menu
function hideMenu($this){
$this.css('display', '');
$('#mobileMenu_'+$this.attr('id')).hide();
}
//create the mobile menu
function createMenu($this){
if(isList($this)){
//generate select element as a string to append via jQuery
//var selectString = '<div class="styled-select-cat"><select id="mobileMenu_'+$this.attr('id')+'" class="mobileMenu">';
var selectString = '';
//create first option (no value)
//selectString += '<option value="">'+settings.topOptionText+'</option>';
//loop through list items
$this.find('li').each(function(){
//when sub-item, indent
var levelStr = '';
var len = $(this).parents('ul, ol').length;
for(i=1;i<len;i++){levelStr += settings.indentString;}
//get url and text for option
var link = $(this).find('a:first-child').attr('href');
var text = levelStr + $(this).clone().children('ul, ol').remove().end().text();
//add option
//selectString += '<option value="'+link+'">'+text+'</option>';
});
//selectString += '</select></div>';
//append select element to ul/ol's container
$this.parent().append(selectString);
//add change event handler for mobile menu
$('#mobileMenu_'+$this.attr('id')).change(function(){
goToPage($(this));
});
//hide current menu, show mobile menu
showMenu($this);
} else {
alert('mobileMenu will only work with UL or OL elements!');
}
}
//plugin functionality
function run($this){
//menu doesn't exist
if(isMobile() && !menuExists($this)){
createMenu($this);
}
//menu already exists
else if(isMobile() && menuExists($this)){
showMenu($this);
}
//not mobile browser
else if(!isMobile() && menuExists($this)){
hideMenu($this);
}
}
//run plugin on each matched ul/ol
//maintain chainability by returning "this"
return this.each(function() {
//override the default settings if user provides some
if(options){$.extend(settings, options);}
//cache "this"
var $this = $(this);
//bind event to browser resize
$(window).resize(function(){run($this);});
//run plugin
run($this);
});
};
})(jQuery); | thepetronics/PetroFDS | Web/media/themes/local/menufiles/cat_nav_mobile.js | JavaScript | gpl-3.0 | 4,018 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-10 14:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='UserExtra',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email_confirmed', models.BooleanField(default=False)),
('activation_key', models.CharField(blank=True, max_length=40, verbose_name='activation key')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='userextra', to='accounts.User', verbose_name='user')),
],
),
]
| ravigadila/seemyhack | seemyhack/accounts/migrations/0002_userextra.py | Python | gpl-3.0 | 889 |
<?php
namespace HeadFirstDesignPatterns\Factory\AbstractFactory\Pizza\Ingredient\Dough;
use HeadFirstDesignPatterns\Factory\AbstractFactory\Pizza\Ingredient\Dough\Dough;
class ThickCrustDough implements Dough
{
public function toString()
{
return 'ThickCrust style extra thick crust dough';
}
} | nachosalvador/HeadFirstDesignPatterns | src/Factory/AbstractFactory/Pizza/Ingredient/Dough/ThickCrustDough.php | PHP | gpl-3.0 | 317 |
//
// main.cpp
// C++_MySQL
//
// Created by Mayur Jain on 2/12/17.
// Copyright © 2017 Mayur Jain. All rights reserved.
//
#include <iostream>
#include <mysql.h>
#include <string>
#include <vector>
#include <sstream>
MYSQL *connection,mysql;
MYSQL_RES *res;
MYSQL_ROW row;
int search_through(){
int search_num;
std::cout<<"Search Friend"<<std::endl;
std::cout<<"1. First Name"<<std::endl;
std::cout<<"2. Last Name"<<std::endl;
std::cout<<"3. College Name"<<std::endl;
std::cout<<"4. Field of Occupation"<<std::endl;
std::cout<<"5. Location"<<std::endl;
std::cin>>search_num;
return search_num;
}
int database_search(int var_searches){
int query_state;
std::string location;
switch(var_searches){
case 1:
{
std::string FName;
std::cout<<"Enter the First Name"<<std::endl;
std::cin>> FName;
std::string location_string = "SELECT * FROM Search WHERE FName ='"+FName+"'";
query_state = mysql_query(connection, location_string.c_str());
return query_state;
}
break;
case 2:
{
std::string LName;
std::cout<<"Enter the Last Name"<<std::endl;
std::cin>> LName;
std::string location_string = "SELECT * FROM Search WHERE LName ='"+LName+"'";
query_state = mysql_query(connection, location_string.c_str());
return query_state;
}
break;
case 3:
{
std::string CName;
std::cout<<"Enter the College Name"<<std::endl;
std::cin>> CName;
std::string location_string = "SELECT * FROM Search WHERE CName ='"+CName+"'";
query_state = mysql_query(connection, location_string.c_str());
return query_state;
}
break;
case 4:
{
std::string company;
std::cout<<"Enter the Comapany Name"<<std::endl;
std::cin>> company;
std::string location_string = "SELECT * FROM Search WHERE Company ='"+company+"'";
query_state = mysql_query(connection, location_string.c_str());
return query_state;
}
break;
case 5:
{
std::string local;
std::cout<<"Enter the Location Name"<<std::endl;
std::cin>> local;
std::string location_string = "SELECT * FROM Search WHERE Location ='"+local+"'";
query_state = mysql_query(connection, location_string.c_str());
return query_state;
}
break;
default:
{
std::cout<<"Kindly Adhere to Search Criteria Available"<<std::endl;
query_state = mysql_query(connection, "SHOW COLUMNS FROM Search");
return query_state;
}
}
}
int distinctSearches(){
int disSearch;
std::cout<<"Various Location , College and Company were your Friends : "<<std::endl;
std::cout<<"1. Distinct College Names available for Search"<<std::endl;
std::cout<<"2. Distinct Company Names available for search "<<std::endl;
std::cout<<"3. Distinct Location Names available for search"<<std::endl;
std::cout<<"Enter your Number"<<std::endl;
std::cin>>disSearch;
return disSearch;
}
int distinctValuesInEachColumn(int distinctVals){
int query_state;
std::string location;
switch(distinctVals){
case 1:
{
std::cout<<"Distinct Colleges Available for Search"<<std::endl;
query_state = mysql_query(connection,"SELECT DISTINCT CName FROM Search");
return query_state;
}
break;
case 2:
{
std::cout<<"Distinct Company Available for Search"<<std::endl;
query_state = mysql_query(connection,"SELECT DISTINCT company FROM Search");
return query_state;
}
break;
case 3:
{
std::cout<<"Distict Location Available for Search"<<std::endl;
query_state = mysql_query(connection,"SELECT DISTINCT Location FROM Search");
return query_state;
}
break;
default:
{
std::cout<<" These are distinct possible values our database holds currently ";
return 0;
}
}
}
int main(int argc, const char * argv[]) {
std::string option;
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,"localhost","mayurjain", "root","cplusplus", 0, 0, 0);
if(connection==NULL)
{
std::cout<<mysql_error(&mysql)<<std::endl;
}
std::cout<<"Do You want to Know Distinct values available for each Field"<<std::endl;
std::cout<<"Enter Yes or No"<<std::endl;
std::cin>>option;
if(option=="YES" || option=="yes" || option=="y"){
int distinctValue = distinctSearches();
int db_result = distinctValuesInEachColumn(distinctValue);
if(db_result!=0)
{
std::cout<<mysql_error(connection)<<std::endl<<std::endl;
return 1;
}
res=mysql_store_result(connection);
if(distinctValue<=3){
while((row=mysql_fetch_row(res))!=NULL)
{
if(row[0]==NULL)
break;
std::cout<<row[0]<<std::endl;
}
}
else{
std::cout<<"No other field is available"<<std::endl;
}
}
int var_searches = search_through();
int db_Result = database_search(var_searches);
if(db_Result!=0)
{
std::cout<<mysql_error(connection)<<std::endl<<std::endl;
return 1;
}
res=mysql_store_result(connection);
if(var_searches<=5){
std::cout<<"MySQL Tables in mysql database."<<std::endl<<std::endl;
while((row=mysql_fetch_row(res))!=NULL)
{
std::cout<<row[0]<<" "<<row[1]<<" "<<row[2]<<" "<<row[3]<<" "<<row[4]<<std::endl;
}
}
else{
const std::string searchFilters[] = {"First Name", "Last Name", "College Name", "Field of Work", "Location"};
int j=0;
while((row=mysql_fetch_row(res))!=NULL)
{
std::cout<<row[0]<<"->"<<searchFilters[j]<<std::endl;
j+=1;
}
}
mysql_free_result(res);
mysql_close(connection);
return 0;
}
//location_string << "select * from Search Where Location = '"<<location<<"'";
//std::cout<<location_string.str();
//std::string var = location_string.str();
//query_state = mysql_query(connection, location);
//std::ostringstream location_string;
| Mayurji/Understanding-Facebook-Filtering-Using-Cplusplus-MySQL | Facebook_Filtering.cpp | C++ | gpl-3.0 | 7,001 |
package l2s.gameserver.model.instances;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import l2s.commons.lang.reference.HardReference;
import l2s.commons.threading.RunnableImpl;
import l2s.gameserver.ThreadPoolManager;
import l2s.gameserver.data.xml.holder.NpcHolder;
import l2s.gameserver.data.xml.holder.SkillHolder;
import l2s.gameserver.model.Creature;
import l2s.gameserver.model.Player;
import l2s.gameserver.model.Skill;
import l2s.gameserver.network.l2.s2c.AutoAttackStartPacket;
import l2s.gameserver.network.l2.s2c.CIPacket;
import l2s.gameserver.network.l2.s2c.L2GameServerPacket;
import l2s.gameserver.templates.npc.NpcTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DecoyInstance extends MonsterInstance
{
private static final long serialVersionUID = 1L;
private static final Logger _log = LoggerFactory.getLogger(DecoyInstance.class);
private HardReference<Player> _playerRef;
private int _lifeTime, _timeRemaining;
private ScheduledFuture<?> _decoyLifeTask, _hateSpam;
public DecoyInstance(int objectId, NpcTemplate template, Player owner, int lifeTime)
{
super(objectId, template);
_playerRef = owner.getRef();
_lifeTime = lifeTime;
_timeRemaining = _lifeTime;
int skilllevel = getNpcId() < 13257 ? getNpcId() - 13070 : getNpcId() - 13250;
_decoyLifeTask = ThreadPoolManager.getInstance().scheduleAtFixedRate(new DecoyLifetime(), 1000, 1000);
_hateSpam = ThreadPoolManager.getInstance().scheduleAtFixedRate(new HateSpam(SkillHolder.getInstance().getSkill(5272, skilllevel)), 1000, 3000);
}
@Override
protected void onDeath(Creature killer)
{
super.onDeath(killer);
if(_hateSpam != null)
{
_hateSpam.cancel(false);
_hateSpam = null;
}
_lifeTime = 0;
}
class DecoyLifetime extends RunnableImpl
{
@Override
public void runImpl() throws Exception
{
try
{
double newTimeRemaining;
decTimeRemaining(1000);
newTimeRemaining = getTimeRemaining();
if(newTimeRemaining < 0)
unSummon();
}
catch(Exception e)
{
_log.error("", e);
}
}
}
class HateSpam extends RunnableImpl
{
private Skill _skill;
HateSpam(Skill skill)
{
_skill = skill;
}
@Override
public void runImpl() throws Exception
{
try
{
setTarget(DecoyInstance.this);
doCast(_skill, DecoyInstance.this, true);
}
catch(Exception e)
{
_log.error("", e);
}
}
}
public void unSummon()
{
if(_decoyLifeTask != null)
{
_decoyLifeTask.cancel(false);
_decoyLifeTask = null;
}
if(_hateSpam != null)
{
_hateSpam.cancel(false);
_hateSpam = null;
}
deleteMe();
}
public void decTimeRemaining(int value)
{
_timeRemaining -= value;
}
public int getTimeRemaining()
{
return _timeRemaining;
}
public int getLifeTime()
{
return _lifeTime;
}
@Override
public Player getPlayer()
{
return _playerRef.get();
}
@Override
public boolean isAutoAttackable(Creature attacker)
{
Player owner = getPlayer();
return owner != null && owner.isAutoAttackable(attacker);
}
@Override
public boolean isAttackable(Creature attacker)
{
Player owner = getPlayer();
return owner != null && owner.isAttackable(attacker);
}
@Override
protected void onDelete()
{
Player owner = getPlayer();
if(owner != null)
owner.removeDecoy(this);
super.onDelete();
}
@Override
public void onAction(Player player, boolean shift)
{
if(player.getTarget() != this)
player.setTarget(this);
else if(isAutoAttackable(player))
player.getAI().Attack(this, false, shift);
}
@Override
public double getCollisionRadius()
{
Player player = getPlayer();
if(player == null)
return 0;
return player.getCollisionRadius();
}
@Override
public double getCollisionHeight()
{
Player player = getPlayer();
if(player == null)
return 0;
return player.getCollisionHeight();
}
@Override
public List<L2GameServerPacket> addPacketList(Player forPlayer, Creature dropper)
{
if(!isInCombat())
return Collections.<L2GameServerPacket> singletonList(new CIPacket(this, forPlayer));
else
{
List<L2GameServerPacket> list = new ArrayList<L2GameServerPacket>(2);
list.add(new CIPacket(this, forPlayer));
list.add(new AutoAttackStartPacket(objectId));
return list;
}
}
@Override
public boolean isPeaceNpc()
{
return false;
}
} | pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/model/instances/DecoyInstance.java | Java | gpl-3.0 | 4,430 |
"""Power Supply Diag App."""
from ... import csdev as _csdev
from ...namesys import SiriusPVName as _PVName
from ...search import PSSearch as _PSSearch
class ETypes(_csdev.ETypes):
"""Local enumerate types."""
DIAG_STATUS_LABELS_AS = (
'PS Disconnected/Comm. Broken',
'PwrState-Sts Off',
'Current-(SP|Mon) are different',
'Interlocks',
'Alarms',
'OpMode-(Sel|Sts) are different',
'Reserved')
DIAG_STATUS_LABELS_LI = (
'PS Disconnected/Comm. Broken',
'PwrState-Sts Off',
'Current-(SP|Mon) are different',
'Interlocks',
'Reserved',
'Reserved',
'Reserved')
DIAG_STATUS_LABELS_BO = (
'PS Disconnected/Comm. Broken',
'PwrState-Sts Off',
'Current-(SP|Mon) are different',
'Interlocks',
'Alarms',
'OpMode-(Sel|Sts) are different',
'Wfm error exceeded tolerance')
_et = ETypes # syntactic sugar
def get_ps_diag_status_labels(psname):
"""Return Diag Status Labels enum."""
psname = _PVName(psname)
if psname.sec == 'BO':
return _et.DIAG_STATUS_LABELS_BO
if psname.sec == 'LI':
return _et.DIAG_STATUS_LABELS_LI
return _et.DIAG_STATUS_LABELS_AS
def get_ps_diag_propty_database(psname):
"""Return property database of diagnostics for power supplies."""
pstype = _PSSearch.conv_psname_2_pstype(psname)
splims = _PSSearch.conv_pstype_2_splims(pstype)
dtol = splims['DTOL_CUR']
enums = get_ps_diag_status_labels(psname)
dbase = {
'DiagVersion-Cte': {'type': 'str', 'value': 'UNDEF'},
'DiagCurrentDiff-Mon': {'type': 'float', 'value': 0.0,
'hilim': dtol, 'hihi': dtol, 'high': dtol,
'low': -dtol, 'lolo': -dtol, 'lolim': -dtol},
'DiagStatus-Mon': {'type': 'int', 'value': 0,
'hilim': 1, 'hihi': 1, 'high': 1,
'low': -1, 'lolo': -1, 'lolim': -1
},
'DiagStatusLabels-Cte': {'type': 'string', 'count': len(enums),
'value': enums}
}
dbase = _csdev.add_pvslist_cte(dbase, 'Diag')
return dbase
| lnls-sirius/dev-packages | siriuspy/siriuspy/diagsys/psdiag/csdev.py | Python | gpl-3.0 | 2,251 |
package com.laton95.runemysteries.world.gen.feature.structure.obelisk;
import com.laton95.runemysteries.config.Config;
import com.laton95.runemysteries.enums.EnumRuneType;
import com.laton95.runemysteries.world.gen.feature.structure.ModifiableRarityStructure;
import com.mojang.datafixers.Dynamic;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MutableBoundingBox;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.GenerationSettings;
import net.minecraft.world.gen.feature.NoFeatureConfig;
import net.minecraft.world.gen.feature.structure.Structure;
import net.minecraft.world.gen.feature.structure.StructureStart;
import net.minecraft.world.gen.feature.template.TemplateManager;
import javax.annotation.Nullable;
import java.util.function.Function;
public abstract class ObeliskStructure extends ModifiableRarityStructure {
private final EnumRuneType rune;
private final int seedModifier;
private final ResourceLocation obelisk;
public ObeliskStructure(Function<Dynamic<?>, ? extends NoFeatureConfig> function, int seedModifier, EnumRuneType rune, ResourceLocation obelisk) {
super(function);
this.rune = rune;
this.seedModifier = seedModifier;
this.obelisk = obelisk;
}
@Override
public String getStructureName() {
return "runemysteries:" + rune.name().toLowerCase() + "_obelisk";
}
@Override
public int getSize() {
return 1;
}
@Override
protected int getSeedModifier() {
return seedModifier;
}
protected abstract int getHeight(Biome biome);
@Nullable
@Override
public BlockPos findNearest(World worldIn, ChunkGenerator<? extends GenerationSettings> chunkGenerator, BlockPos pos, int radius, boolean p_211405_5_) {
return Config.generateObelisks ? super.findNearest(worldIn, chunkGenerator, pos, radius, p_211405_5_) : null;
}
@Override
public IStartFactory getStartFactory() {
return Start::new;
}
public class Start extends StructureStart {
public Start(Structure<?> structure, int chunkX, int chunkZ, MutableBoundingBox boundingBox, int reference, long seed) {
super(structure, chunkX, chunkZ, boundingBox, reference, seed);
}
public void init(ChunkGenerator<?> generator, TemplateManager templateManager, int chunkX, int chunkZ, Biome biome) {
int x = chunkX * 16;
int z = chunkZ * 16;
BlockPos pos = new BlockPos(x, 90, z);
ObeliskPieces.addPieces(templateManager, pos, this.components, obelisk, getHeight(biome));
this.recalculateStructureSize();
}
}
}
| Laton95/Rune-Mysteries | src/main/java/com/laton95/runemysteries/world/gen/feature/structure/obelisk/ObeliskStructure.java | Java | gpl-3.0 | 2,632 |
/* Webcamoid, webcam capture application.
* Copyright (C) 2017 Gonzalo Exequiel Pedone
*
* Webcamoid 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.
*
* Webcamoid 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 Webcamoid. If not, see <http://www.gnu.org/licenses/>.
*
* Web-Site: http://webcamoid.github.io/
*/
#include <QMap>
#include <QMutex>
#include <akfrac.h>
#include <akpacket.h>
#include <akaudiocaps.h>
#include <akaudiopacket.h>
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/opt.h>
#include <libavresample/avresample.h>
}
#include "convertaudioffmpegav.h"
using SampleFormatsMap = QMap<AkAudioCaps::SampleFormat, AVSampleFormat>;
using ChannelLayoutsMap = QMap<AkAudioCaps::ChannelLayout, int64_t>;
class ConvertAudioFFmpegAVPrivate
{
public:
AkAudioCaps m_caps;
AVAudioResampleContext *m_resampleContext {nullptr};
QMutex m_mutex;
bool m_contextIsOpen {false};
inline static const SampleFormatsMap &sampleFormats(bool planar)
{
static const SampleFormatsMap formats = {
{AkAudioCaps::SampleFormat_u8 , AV_SAMPLE_FMT_U8 },
{AkAudioCaps::SampleFormat_s16, AV_SAMPLE_FMT_S16},
{AkAudioCaps::SampleFormat_s32, AV_SAMPLE_FMT_S32},
{AkAudioCaps::SampleFormat_s64, AV_SAMPLE_FMT_S64 },
{AkAudioCaps::SampleFormat_flt, AV_SAMPLE_FMT_FLT},
{AkAudioCaps::SampleFormat_dbl, AV_SAMPLE_FMT_DBL},
};
static const SampleFormatsMap planarFormats = {
{AkAudioCaps::SampleFormat_u8 , AV_SAMPLE_FMT_U8P },
{AkAudioCaps::SampleFormat_s16, AV_SAMPLE_FMT_S16P},
{AkAudioCaps::SampleFormat_s32, AV_SAMPLE_FMT_S32P},
{AkAudioCaps::SampleFormat_s64, AV_SAMPLE_FMT_S64P},
{AkAudioCaps::SampleFormat_flt, AV_SAMPLE_FMT_FLTP},
{AkAudioCaps::SampleFormat_dbl, AV_SAMPLE_FMT_DBLP},
};
return planar? planarFormats: formats;
}
inline static const ChannelLayoutsMap &channelLayouts()
{
static const ChannelLayoutsMap channelLayouts = {
{AkAudioCaps::Layout_mono , AV_CH_LAYOUT_MONO },
{AkAudioCaps::Layout_stereo , AV_CH_LAYOUT_STEREO },
{AkAudioCaps::Layout_2p1 , AV_CH_LAYOUT_2POINT1 },
{AkAudioCaps::Layout_3p0 , AV_CH_LAYOUT_SURROUND },
{AkAudioCaps::Layout_3p0_back , AV_CH_LAYOUT_2_1 },
{AkAudioCaps::Layout_3p1 , AV_CH_LAYOUT_3POINT1 },
{AkAudioCaps::Layout_4p0 , AV_CH_LAYOUT_4POINT0 },
{AkAudioCaps::Layout_quad , AV_CH_LAYOUT_QUAD },
{AkAudioCaps::Layout_quad_side , AV_CH_LAYOUT_2_2 },
{AkAudioCaps::Layout_4p1 , AV_CH_LAYOUT_4POINT1 },
{AkAudioCaps::Layout_5p0 , AV_CH_LAYOUT_5POINT0_BACK },
{AkAudioCaps::Layout_5p0_side , AV_CH_LAYOUT_5POINT0 },
{AkAudioCaps::Layout_5p1 , AV_CH_LAYOUT_5POINT1_BACK },
{AkAudioCaps::Layout_5p1_side , AV_CH_LAYOUT_5POINT1 },
{AkAudioCaps::Layout_6p0 , AV_CH_LAYOUT_6POINT0 },
{AkAudioCaps::Layout_6p0_front , AV_CH_LAYOUT_6POINT0_FRONT },
{AkAudioCaps::Layout_hexagonal , AV_CH_LAYOUT_HEXAGONAL },
{AkAudioCaps::Layout_6p1 , AV_CH_LAYOUT_6POINT1 },
{AkAudioCaps::Layout_6p1_back , AV_CH_LAYOUT_6POINT1_BACK },
{AkAudioCaps::Layout_6p1_front , AV_CH_LAYOUT_6POINT1_FRONT },
{AkAudioCaps::Layout_7p0 , AV_CH_LAYOUT_7POINT0 },
{AkAudioCaps::Layout_7p0_front , AV_CH_LAYOUT_7POINT0_FRONT },
{AkAudioCaps::Layout_7p1 , AV_CH_LAYOUT_7POINT1 },
{AkAudioCaps::Layout_7p1_wide , AV_CH_LAYOUT_7POINT1_WIDE },
{AkAudioCaps::Layout_7p1_wide_back, AV_CH_LAYOUT_7POINT1_WIDE_BACK},
{AkAudioCaps::Layout_octagonal , AV_CH_LAYOUT_OCTAGONAL },
{AkAudioCaps::Layout_hexadecagonal, AV_CH_LAYOUT_HEXADECAGONAL },
{AkAudioCaps::Layout_downmix , AV_CH_LAYOUT_STEREO_DOWNMIX },
};
return channelLayouts;
}
};
ConvertAudioFFmpegAV::ConvertAudioFFmpegAV(QObject *parent):
ConvertAudio(parent)
{
this->d = new ConvertAudioFFmpegAVPrivate;
#ifndef QT_DEBUG
av_log_set_level(AV_LOG_QUIET);
#endif
}
ConvertAudioFFmpegAV::~ConvertAudioFFmpegAV()
{
this->uninit();
delete this->d;
}
bool ConvertAudioFFmpegAV::init(const AkAudioCaps &caps)
{
QMutexLocker mutexLocker(&this->d->m_mutex);
this->d->m_caps = caps;
this->d->m_resampleContext = avresample_alloc_context();
return true;
}
AkPacket ConvertAudioFFmpegAV::convert(const AkAudioPacket &packet)
{
QMutexLocker mutexLocker(&this->d->m_mutex);
if (!this->d->m_caps || packet.buffer().size() < 1)
return AkPacket();
uint64_t iSampleLayout =
ConvertAudioFFmpegAVPrivate::channelLayouts().value(packet.caps().layout(), 0);
AVSampleFormat iSampleFormat =
ConvertAudioFFmpegAVPrivate::sampleFormats(packet.caps().planar())
.value(packet.caps().format(), AV_SAMPLE_FMT_NONE);
int iSampleRate = packet.caps().rate();
int iNChannels = packet.caps().channels();
int iNSamples = packet.caps().samples();
uint64_t oSampleLayout =
ConvertAudioFFmpegAVPrivate::channelLayouts().value(this->d->m_caps.layout(),
AV_CH_LAYOUT_STEREO);
AVSampleFormat oSampleFormat =
av_get_sample_fmt(AkAudioCaps::sampleFormatToString(this->d->m_caps.format())
.toStdString().c_str());
int oSampleRate = this->d->m_caps.rate();
int oNChannels = this->d->m_caps.channels();
// Create input audio frame.
static AVFrame iFrame;
memset(&iFrame, 0, sizeof(AVFrame));
iFrame.format = iSampleFormat;
iFrame.channel_layout = uint64_t(iSampleLayout);
iFrame.sample_rate = iSampleRate;
iFrame.nb_samples = iNSamples;
iFrame.pts = packet.pts();
int iFrameSize = av_samples_get_buffer_size(iFrame.linesize,
iNChannels,
iFrame.nb_samples,
iSampleFormat,
1);
if (iFrameSize < 1)
return AkPacket();
auto tmpPacket = packet.realign(1);
if (avcodec_fill_audio_frame(&iFrame,
iNChannels,
iSampleFormat,
reinterpret_cast<const uint8_t *>(tmpPacket.buffer().constData()),
tmpPacket.buffer().size(),
1) < 0) {
return AkPacket();
}
// Fill output audio frame.
AVFrame oFrame;
memset(&oFrame, 0, sizeof(AVFrame));
oFrame.format = oSampleFormat;
oFrame.channel_layout = uint64_t(oSampleLayout);
oFrame.sample_rate = oSampleRate;
oFrame.nb_samples = int(avresample_get_delay(this->d->m_resampleContext))
+ iFrame.nb_samples
* oSampleRate
/ iSampleRate
+ 3;
oFrame.pts = iFrame.pts * oSampleRate / iSampleRate;
// Calculate the size of the audio buffer.
int oFrameSize = av_samples_get_buffer_size(oFrame.linesize,
oNChannels,
oFrame.nb_samples,
oSampleFormat,
1);
if (oFrameSize < 1)
return AkPacket();
QByteArray oBuffer(oFrameSize, 0);
if (avcodec_fill_audio_frame(&oFrame,
oNChannels,
oSampleFormat,
reinterpret_cast<const uint8_t *>(oBuffer.constData()),
oBuffer.size(),
1) < 0) {
return AkPacket();
}
// convert to destination format
if (!this->d->m_contextIsOpen) {
// Configure output context
av_opt_set_int(this->d->m_resampleContext,
"out_sample_fmt",
AVSampleFormat(oFrame.format),
0);
av_opt_set_int(this->d->m_resampleContext,
"out_channel_layout",
int64_t(oFrame.channel_layout),
0);
av_opt_set_int(this->d->m_resampleContext,
"out_sample_rate",
oFrame.sample_rate,
0);
// Configure input context
av_opt_set_int(this->d->m_resampleContext,
"in_sample_fmt",
AVSampleFormat(iFrame.format),
0);
av_opt_set_int(this->d->m_resampleContext,
"in_channel_layout",
int64_t(iFrame.channel_layout),
0);
av_opt_set_int(this->d->m_resampleContext,
"in_sample_rate",
iFrame.sample_rate,
0);
if (avresample_open(this->d->m_resampleContext) < 0)
return AkPacket();
this->d->m_contextIsOpen = true;
}
int oSamples = avresample_convert(this->d->m_resampleContext,
oFrame.data,
oFrameSize,
oFrame.nb_samples,
iFrame.data,
iFrameSize,
iFrame.nb_samples);
if (oSamples < 1)
return AkPacket();
oFrame.nb_samples = oSamples;
oFrameSize = av_samples_get_buffer_size(oFrame.linesize,
oNChannels,
oFrame.nb_samples,
oSampleFormat,
1);
oBuffer.resize(oFrameSize);
AkAudioPacket oAudioPacket;
oAudioPacket.caps() = this->d->m_caps;
oAudioPacket.caps().setSamples(oFrame.nb_samples);
oAudioPacket.buffer() = oBuffer;
oAudioPacket.pts() = oFrame.pts;
oAudioPacket.timeBase() = AkFrac(1, this->d->m_caps.rate());
oAudioPacket.index() = packet.index();
oAudioPacket.id() = packet.id();
return oAudioPacket;
}
void ConvertAudioFFmpegAV::uninit()
{
QMutexLocker mutexLocker(&this->d->m_mutex);
this->d->m_caps = AkAudioCaps();
if (this->d->m_resampleContext)
avresample_free(&this->d->m_resampleContext);
this->d->m_contextIsOpen = false;
}
#include "moc_convertaudioffmpegav.cpp"
| hipersayanX/webcamoid | libAvKys/Plugins/ACapsConvert/src/ffmpegav/src/convertaudioffmpegav.cpp | C++ | gpl-3.0 | 11,922 |
package com.cloudera.server.web.cmf.include;
import com.cloudera.cmf.model.DbRole;
import com.cloudera.server.web.common.Link;
import com.cloudera.server.web.common.include.LinkRenderer;
import java.io.IOException;
import java.io.Writer;
import org.jamon.AbstractTemplateImpl;
import org.jamon.TemplateManager;
public class RoleExternalLinkImpl extends AbstractTemplateImpl
implements RoleExternalLink.Intf
{
private final DbRole role;
private final String key;
private final String url;
private final String suffix;
protected static RoleExternalLink.ImplData __jamon_setOptionalArguments(RoleExternalLink.ImplData p_implData)
{
if (!p_implData.getUrl__IsNotDefault())
{
p_implData.setUrl(null);
}
if (!p_implData.getSuffix__IsNotDefault())
{
p_implData.setSuffix("");
}
return p_implData;
}
public RoleExternalLinkImpl(TemplateManager p_templateManager, RoleExternalLink.ImplData p_implData) {
super(p_templateManager, __jamon_setOptionalArguments(p_implData));
this.role = p_implData.getRole();
this.key = p_implData.getKey();
this.url = p_implData.getUrl();
this.suffix = p_implData.getSuffix();
}
public void renderNoFlush(Writer jamonWriter)
throws IOException
{
Link link = EntityLinkHelper.getRoleExternalLink(this.role, this.key, this.url, this.suffix);
if (link != null)
{
jamonWriter.write("\n");
LinkRenderer __jamon__var_589 = new LinkRenderer(getTemplateManager());
__jamon__var_589.setShowIcon(false);
__jamon__var_589.renderNoFlush(jamonWriter, link);
jamonWriter.write("\n");
}
jamonWriter.write("\n");
}
} | Mapleroid/cm-server | server-5.11.0.src/com/cloudera/server/web/cmf/include/RoleExternalLinkImpl.java | Java | gpl-3.0 | 1,728 |
var assert = require('assert');
var expect = require('chai').expect;
var usersMfaEnabled = require('./usersMfaEnabled')
const createCache = (users) => {
return {
iam: {
generateCredentialReport: {
'us-east-1': {
data: users
}
}
}
}
}
describe('usersMfaEnabled', function () {
describe('run', function () {
it('should FAIL when user has password and does not have MFA enabled', function (done) {
const cache = createCache(
[{
user: '<root_account>',
password_enabled: true,
mfa_active: false
},
{
user: 'UserAccount',
password_enabled: true,
mfa_active: false
}]
)
const callback = (err, results) => {
expect(results.length).to.equal(1)
expect(results[0].status).to.equal(2)
done()
}
usersMfaEnabled.run(cache, {}, callback)
})
it('should PASS when user has password and does not have MFA enabled', function (done) {
const cache = createCache(
[{
user: '<root_account>',
password_enabled: true,
mfa_active: false
},
{
user: 'UserAccount',
password_enabled: true,
mfa_active: true
}]
)
const callback = (err, results) => {
expect(results.length).to.equal(1)
expect(results[0].status).to.equal(0)
done()
}
usersMfaEnabled.run(cache, {}, callback)
})
})
})
| cloudsploit/scans | plugins/aws/iam/usersMfaEnabled.spec.js | JavaScript | gpl-3.0 | 1,884 |
/* Copyright (C) <2015> <XFactHD>
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 XFactHD.rfutilities.common.utils;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
public class ConfigHandler
{
public static Configuration configuration;
public static boolean floatingModels = false;
public static void init(File configFile)
{
if (configuration == null)
{
configuration = new Configuration(configFile);
loadConfiguration();
}
}
@SubscribeEvent
public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event)
{
if (event.modID.equalsIgnoreCase(Reference.MOD_ID))
{
loadConfiguration();
}
}
private static void loadConfiguration()
{
floatingModels = configuration.getBoolean("floatingModels", "General", false, "If set to true, the models won't be standing on solid plates, but instead float in the air.");
if (configuration.hasChanged())
{
configuration.save();
}
}
}
| XFactHD/RFUtilities | 1.7.10/src/main/java/XFactHD/rfutilities/common/utils/ConfigHandler.java | Java | gpl-3.0 | 1,825 |
<?php
/*********************************************************************************
* This file is part of Sentrifugo.
* Copyright (C) 2015 Sapplica
*
* Sentrifugo 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.
*
* Sentrifugo 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 Sentrifugo. If not, see <http://www.gnu.org/licenses/>.
*
* Sentrifugo Support <support@sentrifugo.com>
********************************************************************************/
class Default_CronjobController extends Zend_Controller_Action
{
private $options;
public function preDispatch()
{
}
public function init()
{
$this->_options= $this->getInvokeArg('bootstrap')->getOptions();
}
public function indexAction()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$date = new Zend_Date();
$email_model = new Default_Model_EmailLogs();
$cron_model = new Default_Model_Cronstatus();
// appraisal notifications
$this->checkperformanceduedate();
// feed forward notifications
// $this->checkffduedate();
$cron_status = $cron_model->getActiveCron('General');
if($cron_status == 'yes')
{
try
{
//updating cron status table to in-progress
$cron_data = array(
'cron_status' => 1,
'cron_type' => 'General',
'started_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, '');
if($cron_id != '')
{
$mail_data = $email_model->getNotSentMails();
if(count($mail_data) > 0)
{
foreach($mail_data as $mdata)
{
$options = array();
$options['header'] = $mdata['header'];
$options['message'] = $mdata['message'];
$options['subject'] = $mdata['emailsubject'];
$options['toEmail'] = $mdata['toEmail'];
$options['toName'] = $mdata['toName'];
if($mdata['cc'] != '')
$options['cc'] = $mdata['cc'];
if($mdata['bcc'] != '')
$options['bcc'] = $mdata['bcc'];
// to send email
$mail_status = sapp_Mail::_email($options);
$mail_where = array('id=?' => $mdata['id']);
$new_maildata['modifieddate'] = gmdate("Y-m-d H:i:s");
if($mail_status === true)
{
$new_maildata['is_sent'] = 1;
//to udpate email log table that mail is sent.
$id = $email_model->SaveorUpdateEmailData($new_maildata,$mail_where);
}
}//end of for loop
}//end of mails count if
//updating cron status table to completed.
$cron_data = array(
'cron_status' => 0,
'completed_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, "id = ".$cron_id);
}//end of cron status id if
}
catch(Exception $e)
{
}
}//end of cron status if
}//end of index action
/**
* This action is used to send mails to employees for passport expiry,and credit card expiry(personal details screen)
*/
public function empdocsexpiryAction()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$email_model = new Default_Model_EmailLogs();
$cron_model = new Default_Model_Cronstatus();
$cron_status = $cron_model->getActiveCron('Emp docs expiry');
if($cron_status == 'yes')
{
try
{
//updating cron status table to in-progress
$cron_data = array(
'cron_status' => 1,
'cron_type' => 'Emp docs expiry',
'started_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, '');
if($cron_id != '')
{
$calc_date = new DateTime(date('Y-m-d'));
$calc_date->add(new DateInterval('P1M'));
$print_date = $calc_date->format(DATEFORMAT_PHP);
$calc_date = $calc_date->format('Y-m-d');
$mail_data = $email_model->getEmpDocExpiryData($calc_date);
if(count($mail_data) > 0)
{
foreach($mail_data as $mdata)
{
$view = $this->getHelper('ViewRenderer')->view;
$this->view->emp_name = $mdata['name'];
$this->view->docs_arr = $mdata['docs'];
$this->view->expiry_date = $print_date;
$text = $view->render('mailtemplates/empdocsexpirycron.phtml');
$options['subject'] = APPLICATION_NAME.': Documents expiry';
$options['header'] = 'Greetings from '.APPLICATION_NAME;
$options['toEmail'] = $mdata['email'];
$options['toName'] = $mdata['name'];
$options['message'] = $text;
sapp_Global::_sendEmail($options);
}
}
$cron_data = array(
'cron_status' => 0,
'completed_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, "id = ".$cron_id);
}//end of cron status id if
}
catch(Exception $e)
{
}
}//end of cron status if
}//end of emp expiry action
/**
* This action is used to send mails to employees for passport expiry,and credit card expiry(visa and immigration screen)
*/
public function empexpiryAction()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$email_model = new Default_Model_EmailLogs();
$cron_model = new Default_Model_Cronstatus();
$cron_status = $cron_model->getActiveCron('Employee expiry');
$earr = array('i94' => 'I94','visa' => 'Visa' ,'passport' => 'Passport');
if($cron_status == 'yes')
{
try
{
//updating cron status table to in-progress
$cron_data = array(
'cron_status' => 1,
'cron_type' => 'Employee expiry',
'started_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, '');
if($cron_id != '')
{
$calc_date = new DateTime(date('Y-m-d'));
$calc_date->add(new DateInterval('P1M'));
$print_date = $calc_date->format(DATEFORMAT_PHP);
$calc_date = $calc_date->format('Y-m-d');
$mail_data = $email_model->getEmpExpiryData($calc_date);
if(count($mail_data) > 0)
{
foreach($mail_data as $mdata)
{
$base_url = 'http://'.$this->getRequest()->getHttpHost() . $this->getRequest()->getBaseUrl();
$view = $this->getHelper('ViewRenderer')->view;
$this->view->emp_name = $mdata['userfullname'];
$this->view->etype = $earr[$mdata['etype']];
$this->view->expiry_date = $print_date;
$text = $view->render('mailtemplates/empexpirycron.phtml');
$options['subject'] = APPLICATION_NAME.': '.$earr[$mdata['etype']].' renewal';
$options['header'] = 'Greetings from '.APPLICATION_NAME;
$options['toEmail'] = $mdata['emailaddress'];
$options['toName'] = $mdata['userfullname'];
$options['message'] = $text;
$options['cron'] = 'yes';
sapp_Global::_sendEmail($options);
}
}
$cron_data = array(
'cron_status' => 0,
'completed_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, "id = ".$cron_id);
}//end of cron status id if
}
catch(Exception $e)
{
}
}//end of cron status if
}//end of emp expiry action
/**
* This action is to remind managers to approve leaves of his team members before end of month.
*/
public function leaveapproveAction()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$email_model = new Default_Model_EmailLogs();
$cron_model = new Default_Model_Cronstatus();
$cron_status = $cron_model->getActiveCron('Approve leave');
if($cron_status == 'yes')
{
try
{
//updating cron status table to in-progress
$cron_data = array(
'cron_status' => 1,
'cron_type' => 'Approve leave',
'started_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, '');
if($cron_id != '')
{
$from_date = date('Y-m-01');
$to_date = date('Y-m-d');
$mail_data = $email_model->getLeaveApproveData($from_date,$to_date);
if(count($mail_data) > 0)
{
foreach($mail_data as $mdata)
{
$base_url = 'http://'.$this->getRequest()->getHttpHost() . $this->getRequest()->getBaseUrl();
$view = $this->getHelper('ViewRenderer')->view;
$this->view->emp_name = $mdata['mng_name'];
$this->view->team = $mdata['team'];
$text = $view->render('mailtemplates/leaveapprovecron.phtml');
$options['subject'] = APPLICATION_NAME.': Leave(s) pending for approval';
$options['header'] = 'Pending Leaves';
$options['toEmail'] = $mdata['mng_email'];
$options['toName'] = $mdata['mng_name'];
$options['message'] = $text;
$options['cron'] = 'yes';
sapp_Global::_sendEmail($options);
}
}
$cron_data = array(
'cron_status' => 0,
'completed_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, "id = ".$cron_id);
}//end of cron status id if
}
catch(Exception $e)
{
}
}//end of cron status if
}//end of leave approve action
/**
* This action is to remind managers to approve oncalls of his team members before end of month.
*/
public function oncallapproveAction()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$email_model = new Default_Model_EmailLogs();
$cron_model = new Default_Model_Cronstatus();
$cron_status = $cron_model->getActiveCron('Approve on call');
if($cron_status == 'yes')
{
try
{
//updating cron status table to in-progress
$cron_data = array(
'cron_status' => 1,
'cron_type' => 'Approve on call',
'started_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, '');
if($cron_id != '')
{
$from_date = date('Y-m-01');
$to_date = date('Y-m-d');
$mail_data = $email_model->getLeaveApproveData($from_date,$to_date);
if(count($mail_data) > 0)
{
foreach($mail_data as $mdata)
{
$base_url = 'http://'.$this->getRequest()->getHttpHost() . $this->getRequest()->getBaseUrl();
$view = $this->getHelper('ViewRenderer')->view;
$this->view->emp_name = $mdata['mng_name'];
$this->view->team = $mdata['team'];
$text = $view->render('mailtemplates/oncallapprovecron.phtml');
$options['subject'] = APPLICATION_NAME.': Leave(s) pending for approval';
$options['header'] = 'Pending Leaves';
$options['toEmail'] = $mdata['mng_email'];
$options['toName'] = $mdata['mng_name'];
$options['message'] = $text;
$options['cron'] = 'yes';
sapp_Global::_sendEmail($options);
}
}
$cron_data = array(
'cron_status' => 0,
'completed_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, "id = ".$cron_id);
}//end of cron status id if
}
catch(Exception $e)
{
}
}//end of cron status if
}//end of oncall approve action
/**
* This action is to send email to HR group when due date of requisition is completed.
*/
public function requisitionAction()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$email_model = new Default_Model_EmailLogs();
$cron_model = new Default_Model_Cronstatus();
$cron_status = $cron_model->getActiveCron('Requisition expiry');
if($cron_status == 'yes')
{
try
{
//updating cron status table to in-progress
$cron_data = array(
'cron_status' => 1,
'cron_type' => 'Requisition expiry',
'started_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, '');
if($cron_id != '')
{
$calc_date = new DateTime(date('Y-m-d'));
$calc_date->add(new DateInterval('P15D'));
$print_date = $calc_date->format(DATEFORMAT_PHP);
$calc_date = $calc_date->format('Y-m-d');
$mail_data = $email_model->getRequisitionData($calc_date);
if(count($mail_data) > 0)
{
foreach($mail_data as $did => $mdata)
{
if(defined("REQ_HR_".$did))
{
$base_url = 'http://'.$this->getRequest()->getHttpHost() . $this->getRequest()->getBaseUrl();
$view = $this->getHelper('ViewRenderer')->view;
$this->view->emp_name = "HR";
$this->view->print_date = $print_date;
$this->view->req = $mdata['req'];
$this->view->base_url = $base_url;
$text = $view->render('mailtemplates/requisitioncron.phtml');
$options['subject'] = APPLICATION_NAME.': Renew requisition expiry';
$options['header'] = 'Requisition Expiry';
$options['toEmail'] = constant("REQ_HR_".$did);
$options['toName'] = "HR";
$options['message'] = $text;
$options['cron'] = 'yes';
sapp_Global::_sendEmail($options);
}
}
}
$cron_data = array(
'cron_status' => 0,
'completed_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, "id = ".$cron_id);
}//end of cron status id if
}
catch(Exception $e)
{
}
}//end of cron status if
}//end of requisition action.
/**
* This action is used to send notification to inactive users.
*/
public function inactiveusersAction()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$email_model = new Default_Model_EmailLogs();
$cron_model = new Default_Model_Cronstatus();
$cron_status = $cron_model->getActiveCron('Inactive users');
if($cron_status == 'yes')
{
try
{
//updating cron status table to in-progress
$cron_data = array(
'cron_status' => 1,
'cron_type' => 'Inactive users',
'started_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, '');
if($cron_id != '')
{
$calc_date = new DateTime(date('Y-m-d'));
$calc_date->sub(new DateInterval('P3M'));
$print_date = $calc_date->format(DATEFORMAT_PHP);
$calc_date = $calc_date->format('Y-m-d');
$mail_data = $email_model->getInactiveusersData($calc_date);
if(count($mail_data) > 0)
{
foreach($mail_data as $did => $mdata)
{
$base_url = 'http://'.$this->getRequest()->getHttpHost() . $this->getRequest()->getBaseUrl();
$view = $this->getHelper('ViewRenderer')->view;
$this->view->emp_name = $mdata['userfullname'];
$this->view->print_date = $print_date;
$this->view->user_id = $mdata['employeeId'];
$this->view->base_url = $base_url;
$text = $view->render('mailtemplates/inactiveusercron.phtml');
$options['subject'] = APPLICATION_NAME.': Sentrifugo account inactivated';
$options['header'] = 'Employee inactivated';
$options['toEmail'] = $mdata['emailaddress'];
$options['toName'] = $mdata['userfullname'];
$options['message'] = $text;
$options['cron'] = 'yes';
sapp_Global::_sendEmail($options);
}
}
$cron_data = array(
'cron_status' => 0,
'completed_at' => gmdate("Y-m-d H:i:s"),
);
$cron_id = $cron_model->SaveorUpdateCronStatusData($cron_data, "id = ".$cron_id);
}//end of cron status id if
}
catch(Exception $e)
{
}
}//end of cron status if
}//end of inactiveusers action.
/**
* This action is used to save update json in logmanager(removes 30 days before content and saves in logmanagercron) .
*/
public function logcronAction(){
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$logmanager_model = new Default_Model_Logmanager();
$logmanagercron_model = new Default_Model_Logmanagercron();
$logData = $logmanager_model->getLogManagerData();
$i = 0;
if(count($logData) > 0){
foreach($logData as $record){
if(isset($record['log_details']) && !empty($record['log_details'])){
$id = $record['id'];
$menuId = $record['menuId'];
$actionflag = $record['user_action'];
$userid = $record['last_modifiedby'];
$keyflag = $record['key_flag'];
$date = $record['last_modifieddate'];
$jsondetails = '{"testjson":['.$record['log_details'].']}';
$jsonarr = @get_object_vars(json_decode($jsondetails));
$mainTableJson = '';
$cronTableJson = '';
if(!empty($jsonarr))
{
$mainJsonArrayCount = count($jsonarr['testjson']);
foreach($jsonarr['testjson'] as $key => $json){
$jsonVal = @get_object_vars($json);
if(!empty($jsonVal)){
$jsondate = explode(' ',$jsonVal['date']);
$datetime1 = new DateTime($jsondate[0]);
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
$interval = $interval->format('%a');
if($interval > 30){
if($cronTableJson == ''){
$cronTableJson .= json_encode($jsonVal);
}else{
$cronTableJson .= ','.json_encode($jsonVal);
}
if(isset($jsonVal['recordid']) && $jsonVal['recordid'] != ''){
$keyflag = $jsonVal['recordid'];
}
}else{
if($mainTableJson == ''){
$mainTableJson .= json_encode($jsonVal);
}else{
$mainTableJson .= ','.json_encode($jsonVal);
}
}
}
if(($mainJsonArrayCount-1) == $key){ // if all are greater than 30 days
if($mainTableJson == ''){
$mainTableJson .= json_encode($jsonVal);
}
}
}
try{
if($cronTableJson != '' && $mainTableJson != ''){
$result = $logmanager_model->UpdateLogManagerWhileCron($id,$mainTableJson);
if($result){
$InsertId = $logmanagercron_model->InsertLogManagerCron($menuId,$actionflag,$cronTableJson,$userid,$keyflag,$date);
}
$i++;
}
}catch(Exception $e){
echo $e->getMessage(); exit;
}
}
}
}
}
}
public function checkperformanceduedate()
{
$app_init_model = new Default_Model_Appraisalinit();
$app_ratings_model = new Default_Model_Appraisalemployeeratings();
$active_appraisal_Arr = $app_init_model->getActiveAppraisals();
$appraisalPrivMainModel = new Default_Model_Appraisalqsmain();
$app_manager_model = new Default_Model_Appraisalmanager();
$usersmodel = new Default_Model_Users();
$current_day = new DateTime('now');
$current_day->sub(new DateInterval('P1D'));
if(!empty($active_appraisal_Arr))
{
foreach($active_appraisal_Arr as $appval)
{
if($appval['managers_due_date'])
$manager_due_date = new DateTime($appval['managers_due_date']);
else
$manager_due_date = '';
if($appval['employees_due_date'])
$emp_due_date = new DateTime($appval['employees_due_date']);
else
$emp_due_date = '';
$due_date = ($appval['enable_step'] == 2)? $emp_due_date : $manager_due_date;
$interval = $current_day->diff($due_date);
$interval->format('%d');
$interval=$interval->days;
$appIdArr = array();
$appIdList = '';
if($interval<=2)
{
if($appval['enable_step'] == 2)
{
$employeeidArr = $app_ratings_model->getEmployeeIds($appval['id'],'cron');
if(!empty($employeeidArr))
{
$empIdArr = array();
$empIdList = '';
foreach($employeeidArr as $empval)
{
array_push($empIdArr,$empval['employee_id']);
}
if(!empty($empIdArr))
{
$empIdList = implode(',',$empIdArr);
$employeeDetailsArr = $app_manager_model->getUserDetailsByEmpID($empIdList); //Fetching employee details
if(!empty($employeeDetailsArr))
{
$empArr = array();
foreach($employeeDetailsArr as $emp)
{
array_push($empArr,$emp['emailaddress']); //preparing Bcc array
}
$optionArr = array('subject'=>'Self Appraisal Submission Pending',
'header'=>'Performance Appraisal',
'toemail'=>SUPERADMIN_EMAIL,
'toname'=>'Super Admin',
'bcc' => $empArr,
'message'=>"<div style='padding: 0; text-align: left; font-size:14px; font-family:Arial, Helvetica, sans-serif;'>
<span style='color:#3b3b3b;'>Hi, </span><br />
<div style='padding:20px 0 0 0;color:#3b3b3b;'>Self appraisal submission is pending.</div>
<div style='padding:20px 0 10px 0;'>Please <a href=".BASE_URL." target='_blank' style='color:#b3512f;'>click here</a> to login to your <b>".APPLICATION_NAME."</b> account to check the details.</div>
</div> ",
'cron'=>'yes');
sapp_PerformanceHelper::saveCronMail($optionArr);
}
}
}
}
else
{
$getLine1ManagerId = $appraisalPrivMainModel->getLine1ManagerIdMain($appval['id']);
if(!empty($getLine1ManagerId))
{
$empArr = array();
foreach($getLine1ManagerId as $val)
{
array_push($empArr,$val['emailaddress']); //preparing Bcc array
}
$optionArr = array('subject'=>'Manager Appraisal Submission Pending',
'header'=>'Performance Appraisal',
'toemail'=>SUPERADMIN_EMAIL,
'toname'=>'Super Admin',
'bcc' => $empArr,
'message'=>"<div style='padding: 0; text-align: left; font-size:14px; font-family:Arial, Helvetica, sans-serif;'>
<span style='color:#3b3b3b;'>Hi, </span><br />
<div style='padding:20px 0 0 0;color:#3b3b3b;'>Manager appraisal submission is pending.</div>
<div style='padding:20px 0 10px 0;'>Please <a href=".BASE_URL." target='_blank' style='color:#b3512f;'>click here</a> to login to your <b>".APPLICATION_NAME."</b> account to check the details.</div>
</div> ",
'cron'=>'yes');
sapp_PerformanceHelper::saveCronMail($optionArr);
}
}
}
}
}
}
public function checkffduedate()
{
$ffinitModel = new Default_Model_Feedforwardinit();
$ffEmpRatModel = new Default_Model_Feedforwardemployeeratings;
$ffDataArr = $ffinitModel->getFFbyBUDept('','yes');
$ffIdArr = array();
$ffIdList = '';
$current_day = new DateTime('now');
$current_day->sub(new DateInterval('P1D'));
if(!empty($ffDataArr))
{
foreach($ffDataArr as $ffval)
{
if($ffval['status'] == 1)
{
if($ffval['ff_due_date'])
$due_date = new DateTime($ffval['ff_due_date']);
else
$due_date = '';
$interval = $current_day->diff($due_date);
$interval->format('%d');
$interval=$interval->days;
if($interval<=2)
{
array_push($ffIdArr,$ffval['id']);
}
}
}
}
if(!empty($ffIdArr))
{
$ffIdList = implode(',',$ffIdArr);
}
if($ffIdList != '')
{
$ffEmpsStatusData = $ffEmpRatModel->getEmpsFFStatus($ffIdList,'cron');
if(!empty($ffEmpsStatusData))
{
$empIdArr = array();
foreach($ffEmpsStatusData as $empval)
{
array_push($empIdArr,$empval['emailaddress']);
}
$optionArr = array('subject'=>'Manager Feedforward submission pending',
'header'=>'Feedforward',
'toemail'=>SUPERADMIN_EMAIL,
'toname'=>'Super Admin',
'bcc' => $empIdArr,
'message'=>"<div style='padding: 0; text-align: left; font-size:14px; font-family:Arial, Helvetica, sans-serif;'>
<span style='color:#3b3b3b;'>Hi, </span><br />
<div style='padding:20px 0 0 0;color:#3b3b3b;'>Mangaer feedforward is pending.</div>
<div style='padding:20px 0 10px 0;'>Please <a href=".BASE_URL." target='_blank' style='color:#b3512f;'>click here</a> to login to your <b>".APPLICATION_NAME."</b> account to check the details.</div>
</div> ",
'cron'=>'yes');
sapp_PerformanceHelper::saveCronMail($optionArr);
}
}
}
}
| go-faustino/sentrifugo | application/modules/default/controllers/CronjobController.php | PHP | gpl-3.0 | 32,594 |
#!/usr/bin/env python
# coding=utf-8
#
# Copyright 2017 Ilya Zhivetiev <i.zhivetiev@gnss-lab.org>
#
# This file is part of tec-suite.
#
# tec-suite 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.
#
# tec-suite 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 tec-suite. If not, see <http://www.gnu.org/licenses/>.
"""
File: n.py
Description: GNSS RINEX observation data reader ver2.n
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import math
import re
from tecs.rinex.basic import ObservationData
from tecs.rinex.basic import RinexError
from tecs.rinex.common import validate_epoch
from tecs.rinex.header import RinexVersionType, ApproxPositionXYX, Interval, \
TimeOfFirstObs
NAME = 'tecs.rinex.v2.o'
LOGGER = logging.getLogger(NAME)
class Obs2(ObservationData):
"""Obs2(f_obj, filename, settings=None) -> instance
GPS observation data file ver.2.0
Parameters
----------
f_obj : file
file-like object
filename : str
a name of the file; we should use it because f_obj.name contains not
filename.
"""
VERSION = 2.0
REC_LEN = 16
OBS_TYPES = re.compile(r'\s{4}([LCPDT][12])')
RE_TOBS = re.compile(r'(.*)# / TYPES OF OBSERV')
RE_END_HEADER = re.compile(r'(.*)END OF HEADER')
RE_COMMENT = re.compile(r'(.*)COMMENT')
END_OF_HEADER = 'END OF HEADER'
def _get_val(self, rec, i, rlen):
"""get_val(rec, i, rlen) -> val, lli, sig_strength
parse the record rec to retrieve observation values: val, LLI
and signal strength.
Parameters
----------
rec : str
the whole record to parse
i : int
start of an observation data substring
rlen : int
length of the substring
"""
val = rec[i:i + rlen]
digs = '0123456789'
spaces = ' ' * len(val)
if val and val != spaces:
# observation
try:
obs = val[:14]
obs = float(obs)
except ValueError:
err = "wrong data string:\n%s" % rec
raise RinexError(self.filename, err)
val = val[14:]
# LLI
try:
lli = val[0]
if lli in digs:
lli = int(lli)
else:
lli = 0
except IndexError:
lli = 0
# Signal strength
try:
sig_strength = val[1]
if sig_strength in digs:
sig_strength = int(sig_strength)
else:
sig_strength = 0
except IndexError:
sig_strength = 0
else:
obs = None
lli = 0
sig_strength = 0
return obs, lli, sig_strength
def _get_prn(self, rec, i, cur_epoch):
"""get_prn(rec, i) -> prn"""
val = rec[i:i + 3]
if not val:
err = "can't extract satellite:\n%s <%s>" % (cur_epoch, rec)
raise RinexError(self.filename, err)
# system identifier
cur_sys = val[0].upper()
if cur_sys == ' ':
cur_sys = 'G'
# satellite number
cur_sat = None
try:
cur_sat = val[1:]
cur_sat = int(cur_sat)
except ValueError:
err = 'wrong PRN (%s) in epoch record:\n<%s>' % (
cur_sat, cur_epoch)
raise RinexError(self.filename, err)
cur_sat = "%02d" % cur_sat
# PRN
cur_prn = cur_sys + cur_sat
return cur_prn
def get_interval(self, n):
"""get_interval(n) -> interval
Get an observation interval using first n epochs of an observation file.
Parameters
----------
n : int
amount of epochs to read
Returns
-------
interval : float
observation interval, seconds
"""
epoch = None
epoch_count = 0
deltas = []
dt = None
records = self.read_records()
try:
while epoch_count < n:
rec = next(records)
if not epoch:
epoch = rec[0]
continue
elif epoch == rec[0]:
continue
dt = rec[0] - epoch
if dt:
deltas.append(dt.total_seconds())
epoch_count += 1
epoch = rec[0]
except RinexError as err:
msg = ("Can't find out obs interval: %s" % str(err))
raise RinexError(self.filename, msg)
except StopIteration as err:
if dt is None:
msg = ("Can't find out obs interval: %s" % str(err))
raise RinexError(self.filename, msg)
else:
pass
records.close()
del records
if len(set(deltas)) == 1:
interval = deltas[0]
else:
dt_dict = {}
for dt in deltas:
if dt not in dt_dict:
dt_dict[dt] = 1
else:
dt_dict[dt] += 1
tmp = list(dt_dict.keys())
tmp.sort(key=lambda k: dt_dict[k], reverse=True)
interval = tmp[0]
self._fobj.seek(0)
for rec in self._fobj:
rec = rec[60:].rstrip()
if rec == self.END_OF_HEADER:
break
return interval
def set_obs_num_types(self, header):
"""set_obs_num_types(header) -> None
Parameters
----------
header : list
check and set value of the self.properties['obs types']
"""
obs_types = []
def get_o_types(r, n, l):
"""get_o_types(r, n, l) -> obs_types
Parameters
----------
r : str
substring
n : int
amount of observations
l : int
len of the record
Returns
-------
obs_types : list
list of the observation types
"""
o_types = []
for i in range(0, n * l, l):
cur_o_type = r[i:i + l]
match = re.match(self.OBS_TYPES, cur_o_type)
if not match:
msg = "Unknown observation type: '%s'\n%s" % (
cur_o_type, r.rstrip())
self._logger.warning(msg)
cur_o_type = cur_o_type[-2:]
o_types.append(cur_o_type)
return o_types
for (idx, rec) in enumerate(header):
if not self.RE_TOBS.match(rec):
continue
try:
obs_num = rec[:6]
obs_num = int(obs_num)
except (IndexError, ValueError):
err = ('Can\'t read the number of the observation types:\n'
' <%s>') % rec.rstrip()
raise RinexError(self.filename, err)
if obs_num > 9:
obs_types = []
num_compl_lines = obs_num // 9
for cur_l in range(num_compl_lines):
obs_types_line = header[idx + cur_l]
obs_types += get_o_types(obs_types_line[6:60], 9, 6)
if obs_num % 9:
rest_num = obs_num - num_compl_lines * 9
obs_types_line = header[idx + num_compl_lines]
obs_types += get_o_types(obs_types_line[6:6 + rest_num * 6],
rest_num,
6)
else:
obs_types = get_o_types(rec[6:6 + obs_num * 6], obs_num, 6)
if obs_num != len(obs_types):
err = """Can't extract some observation types from:
'%s'""" % rec.rstrip()
raise RinexError(self.filename, err)
break
self.properties['obs types'] = tuple(obs_types)
def set_logger(self):
""" set_logger()
"""
self._logger = logging.getLogger(NAME + '.Obs2')
def read_epoch(self, epoch):
"""
read_epoch(epoch) -> epoch_components
parse epoch record.
Parameters
----------
epoch : str
epoch record
Returns
-------
epoch_components : tuple
(datetime, epoch-flag, num-of-satellites, rcvr-clock-offset, prns)
"""
# assume that the first element is an epoch
# 1. epoch flag
try:
epoch_flag = int(epoch[26:29])
except ValueError:
err = 'wrong epoch flag in epoch record\n%s' % epoch
raise RinexError(self.filename, err)
# set sat_num & return, need no date
if epoch_flag > 1:
msg = "epoch flag >1 (%s: %s)" % (self.filename, epoch)
self._logger.info(msg)
try:
sat_num = int(epoch[29:32])
return None, epoch_flag, sat_num, None, None
except ValueError:
err = "wrong event flag:\n%s" % epoch
raise RinexError(self.filename, err)
# 2. date
try:
d = []
for i in range(0, 13, 3):
val = epoch[i:i + 3]
val = int(val)
d.append(val)
sec = float(epoch[15:26])
microsec = (sec - int(sec)) * 1e+6
microsec = float("%.5f" % microsec)
d.append(int(sec))
d.append(int(microsec))
cur_epoch = validate_epoch(d)
except (IndexError, ValueError) as err:
msg = "wrong date in epoch record '%s': %s" % (epoch, str(err))
raise RinexError(self.filename, msg)
try:
receiver_offset = epoch[68:]
receiver_offset = float(receiver_offset)
except (IndexError, ValueError):
receiver_offset = 0.0
# 3. num of satellites
try:
sat_num = epoch[29:32]
sat_num = int(sat_num)
except ValueError:
err = 'wrong satellite number in epoch record:\n%s' % epoch
raise RinexError(self.filename, err)
# 4. list of PRNs (sat.num + sys identifier)
prev_epoch_line = ''
prns = []
# > 12
if sat_num > 12:
num_compl_lines = sat_num // 12
rest_sat_num = sat_num - num_compl_lines * 12
# read strings which contain 12 satellites
# - current row
for i in range(32, 66, 3):
cur_prn = self._get_prn(epoch, i, cur_epoch)
prns.append(cur_prn)
num_compl_lines -= 1
# - next rows (12 sat per row)
while num_compl_lines:
num_compl_lines -= 1
epoch = self._next_rec(self._fobj)
for i in range(32, 66, 3):
cur_prn = self._get_prn(epoch, i, cur_epoch)
prns.append(cur_prn)
# - the last one (if any)
if rest_sat_num:
epoch = self._next_rec(self._fobj)
r_stop = 32 + rest_sat_num * 3 - 2
for i in range(32, r_stop, 3):
cur_prn = self._get_prn(epoch, i, cur_epoch)
prns.append(cur_prn)
# < 12
else:
for i in range(32, 32 + 3 * sat_num - 2, 3):
cur_prn = self._get_prn(epoch, i, cur_epoch)
prns.append(cur_prn)
if sat_num != len(prns):
err = "can't extract all PRNs from epoch line:\n%s\n%s" % (
prev_epoch_line, epoch)
raise RinexError(self.filename, err)
return cur_epoch, epoch_flag, sat_num, receiver_offset, prns
def read_records(self):
"""read_records() -> generator
Returns
-------
dataset : tuple
(epoch, sat, data) with
data = { obs_1: val, obs_2: val, ... }
"""
for line in self._fobj:
(cur_epoch, epoch_flag,
sat_num, receiver_offset, prns) = self.read_epoch(line.rstrip())
# if the flag != 0
# 1. Power failure between previous and current epoch
if epoch_flag == 1:
msg = ('%s - power failure between previous and current '
'epoch %s.') % (self.filename, cur_epoch)
self._logger.info(msg)
# 3. New site occupation
elif epoch_flag == 3:
msg = "New site occupation: {} - {}."
msg = msg.format(cur_epoch, self.filename)
self._logger.info(msg)
header_slice = []
while sat_num > 0:
h_str = self._next_rec(self._fobj)
header_slice.append(h_str)
sat_num -= 1
self._parse_header(header_slice)
continue
# 4. Header information
elif epoch_flag == 4:
header_slice = []
while sat_num > 0:
sat_num -= 1
h_str = self._next_rec(self._fobj)
header_slice.append(h_str)
msg = "%s: %s." % (self.filename, h_str)
self._logger.debug(msg)
self._parse_header(header_slice)
continue
# n. Some other
elif epoch_flag > 1:
msg = 'epoch flag = %s; %s record(s) to follow: %s - %s.' % (
epoch_flag, sat_num, cur_epoch, self.filename)
self._logger.debug(msg)
while sat_num > 0:
msg = self._next_rec(self._fobj)
self._logger.debug(msg)
sat_num -= 1
continue
# FIXME should I?
if receiver_offset:
pass
# read the records
for cur_prn in prns:
data = []
for n in self.lines_per_rec:
rec = self._next_rec(self._fobj)
rend = n * self.REC_LEN - (self.REC_LEN - 1)
rstep = self.REC_LEN
for i in range(0, rend, rstep):
(val, lli, sig_strength) = (
self._get_val(rec, i, self.REC_LEN))
data.append((val, lli, sig_strength))
types_n_vals = {}
for i in range(len(data)):
o_type = self.properties['obs types'][i]
val = data[i]
types_n_vals[o_type] = val
# it could be epoch duplicate: just skip
if cur_epoch == self.preceding_epoch:
msg = "%s - duplicate dates: %s" % (
self.filename, str(cur_epoch))
self._logger.info(msg)
continue
yield (cur_epoch, cur_prn, types_n_vals)
self.preceding_epoch = cur_epoch
def __init__(self, f_obj, filename):
""" """
super(Obs2, self).__init__(f_obj, filename)
self._logger = None
self.set_logger()
# previous epoch to find duplicates
self.preceding_epoch = None
self.properties = {
'obs types': (None,),
}
self.lines_per_rec = []
file_header = []
for rec in self._fobj:
if self.RE_END_HEADER.match(rec):
break
file_header.append(rec)
self.set_obs_num_types(file_header)
self._det_lines_per_rec()
# header labels
self.ver_type = RinexVersionType(self.VERSION)
self.tofo = TimeOfFirstObs(self.VERSION)
self.xyz = ApproxPositionXYX(self.VERSION)
self.interval = Interval(self.VERSION)
self._parse_header(file_header)
dt = self.get_interval(10)
if self.interval.value != dt:
msg_wi = 'Wrong interval value in the header of {}: {}; ' \
'using {} instead.'
self._logger.warning(msg_wi.format(self.filename,
self.interval.value,
dt))
self.interval.value = '{:10.3f}'.format(dt)
def _det_lines_per_rec(self):
"""_det_lines_per_rec()
determine amount of the lines per record.
"""
obs_num = len(self.properties['obs types'])
s2flw = obs_num / 5.
s2flw = math.ceil(s2flw)
s2flw = int(s2flw)
lines_per_rec = []
n = obs_num
for s in range(s2flw):
n -= 5
if n < 0:
lines_per_rec.append(n + 5)
elif n >= 0:
lines_per_rec.append(5)
self.lines_per_rec = lines_per_rec
del lines_per_rec
del obs_num
def __del__(self):
self._fobj.close()
class Obs21(Obs2):
"""RINEX obs v2.11"""
VERSION = 2.1
# (F14.3,I1,I1)
REC_LEN = 16
OBS_TYPES = re.compile(r'\s{4}([LCPDTS][12])')
def set_logger(self):
self._logger = logging.getLogger(NAME + '.Obs21')
class Obs211(Obs21):
"""RINEX obs v2.11"""
VERSION = 2.11
# (F14.3,I1,I1)
REC_LEN = 16
OBS_TYPES = re.compile(r'\s{4}([LCPDS][125678])')
def set_logger(self):
self._logger = logging.getLogger(NAME + '.Obs211')
| gnss-lab/tec-suite | tecs/rinex/v2/o.py | Python | gpl-3.0 | 18,274 |
#!/usr/bin/env python
"""
Quick and dirty IRC notification script.
Any '{var}'-formatted environment variables names will be expanded
along with git "pretty" format placeholders (like "%H" for commit hash,
"%s" for commit message subject, and so on). Use commas to delineate
multiple messages.
Example:
python scripts/irc-notify.py chat.freenode.net:6697/#gridsync \[{branch}:%h\] {color}3$(python scripts/sha256sum.py dist/Gridsync.AppImage),:\)
"""
import os, random, socket, ssl, subprocess, sys, time
from subprocess import check_output as _co
color = "\x03"
branch = _co(["git", "rev-parse", "--abbrev-ref", "HEAD"]).decode().strip()
def _pf(s):
if "%" not in s:
return s
return _co(["git", "log", "-1", "--pretty={}".format(s)]).decode().strip()
protected_vars = vars().keys()
for key, value in os.environ.items():
if key.lower() not in protected_vars:
vars()[key.lower()] = value
messages = []
for msg in " ".join(sys.argv[2:]).split(","):
messages.append(_pf(msg.format(**vars())).strip())
_addr = sys.argv[1].split("/")[0]
_dest = sys.argv[1].split("/")[1]
_host = _addr.split(":")[0]
_port = _addr.split(":")[1]
_user = socket.gethostname().replace(".", "_")
try:
s = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
s.connect((socket.gethostbyname(_host), int(_port)))
s.send("NICK {0}\r\nUSER {0} * 0 :{0}\r\n".format(_user).encode())
f = s.makefile()
while f:
line = f.readline()
print(line.rstrip())
w = line.split()
if w[0] == "PING":
s.send("PONG {}\r\n".format(w[1]).encode())
elif w[1] == "433":
s.send(
"NICK {}-{}\r\n".format(
_user, str(random.randint(1, 9999))
).encode()
)
elif w[1] == "001":
time.sleep(5)
for msg in messages:
print("NOTICE {} :{}".format(_dest, msg))
s.send("NOTICE {} :{}\r\n".format(_dest, msg).encode())
time.sleep(5)
sys.exit()
except Exception as exc:
print("Error: {}".format(str(exc)))
sys.exit()
| gridsync/gridsync | scripts/irc-notify.py | Python | gpl-3.0 | 2,150 |
/*******************************************************************************
* Copyright (c) 2013 Nick Robinson All rights reserved. This program and the accompanying materials are made available under the terms of
* the GNU Public License v3.0 which accompanies this distribution, and is available at http://www.gnu.org/licenses/gpl.html
******************************************************************************/
package uk.co.nickthecoder.itchy.property;
import java.util.List;
public interface PropertySubject<S extends PropertySubject<S>>
{
public List<Property<S, ?>> getProperties();
}
| nickthecoder/itchy | src/main/java/uk/co/nickthecoder/itchy/property/PropertySubject.java | Java | gpl-3.0 | 610 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import gtk
import sqlalchemy
VOCABULARY_DB = "sqlite:///data/vocabulary.db"
class EntryDialog(gtk.MessageDialog):
def __init__(self, *args, **kwargs):
'''
Creates a new EntryDialog. Takes all the arguments of the usual
MessageDialog constructor plus one optional named argument
"default_value" to specify the initial contents of the entry.
'''
if 'default_value' in kwargs:
default_value = kwargs['default_value']
del kwargs['default_value']
else:
default_value = ''
super(EntryDialog, self).__init__(*args, **kwargs)
entry = gtk.Entry()
entry.set_text(str(default_value))
entry.connect("activate",
lambda ent, dlg, resp: dlg.response(resp),
self, gtk.RESPONSE_OK)
self.vbox.pack_end(entry, True, True, 0)
self.vbox.show_all()
self.entry = entry
def set_value(self, text):
self.entry.set_text(text)
def run(self):
result = super(EntryDialog, self).run()
if result == gtk.RESPONSE_OK:
text = self.entry.get_text()
else:
text = None
return text
class VocabularyWidget(gtk.VBox):
def __init__(self):
gtk.VBox.__init__(self)
# Setup DB
self.db = sqlalchemy.create_engine(VOCABULARY_DB)
self.tb_les = sqlalchemy.Table('lessons',
sqlalchemy.MetaData(self.db),
autoload=True)
self.tb_vocab = sqlalchemy.Table('vocabulary',
sqlalchemy.MetaData(self.db),
autoload=True)
# create toolbar
toolbar = gtk.Toolbar()
label = gtk.Label("Lesson: ")
toolbar.append_element(gtk.TOOLBAR_CHILD_WIDGET, label, None, None,
None, None, lambda : None, None)
self.lessons = gtk.ListStore(int, str)
self.cmb_lessons = gtk.ComboBox(self.lessons)
cell = gtk.CellRendererText()
self.cmb_lessons.pack_start(cell, True)
self.cmb_lessons.add_attribute(cell, 'text', 1)
self.cmb_lessons.connect("changed", self._on_lesson_changed)
toolbar.append_element(gtk.TOOLBAR_CHILD_WIDGET, self.cmb_lessons,
"Lesson", None, None, None, lambda : None, None)
icon = gtk.Image()
icon.set_from_stock(gtk.STOCK_ADD, 4)
toolbar.append_element(gtk.TOOLBAR_CHILD_BUTTON, None, None,
"Add a new lesson", None, icon,
self._on_add_clicked, None)
icon = gtk.Image()
icon.set_from_stock(gtk.STOCK_DELETE, 4)
toolbar.append_element(gtk.TOOLBAR_CHILD_BUTTON, None, None,
"Delete current lesson", None, icon,
self._on_delete_clicked, None)
toolbar.append_element(gtk.TOOLBAR_CHILD_SPACE, None, None, None,
None, None, lambda : None, None)
self.pack_start(toolbar, expand=False, fill=False)
# create vocabulary table
self.table = VocabularyTable(self.db)
self.pack_start(self.table)
# load data from database
self._load_lessons()
def _load_lessons(self):
res = self.tb_les.select().execute()
self.lessons.clear()
self.lessons.append([-1, "All"])
for r in res:
self.lessons.append([r[0], r[1]])
self.cmb_lessons.set_active(0)
def _on_add_clicked(self, widget):
dialog = EntryDialog(None, gtk.DIALOG_MODAL,
gtk.MESSAGE_INFO, gtk.BUTTONS_OK_CANCEL,
"Enter the name of the new lesson")
response = dialog.run()
dialog.destroy()
if response != None and response != '':
self.db.execute(self.tb_les.insert().values(name=response))
self._load_lessons()
def _on_delete_clicked(self, widget):
row = self.cmb_lessons.get_model()[self.cmb_lessons.get_active()]
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
gtk.BUTTONS_YES_NO,
"Are you sure you want to delete the '" + row[1] + "' lesson?"
+ "\nAll the lesson's vocabulary will be deleted too.")
response = dialog.run()
dialog.destroy()
if response == gtk.RESPONSE_YES:
q = self.tb_vocab.delete().where(self.tb_vocab.c.lesson == row[0])
self.db.execute(q)
q = self.tb_les.delete().where(self.tb_les.c.id == row[0])
self.db.execute(q)
self.lessons.remove(self.cmb_lessons.get_active_iter())
self.cmb_lessons.set_active(len(self.lessons)-1)
def _on_lesson_changed(self, widget):
it = widget.get_active_iter()
if it != None:
lesson_id = widget.get_model().get(it, 0)[0]
self.table.load(lesson_id)
class VocabularyTable(gtk.TreeView):
def __init__(self, db):
gtk.TreeView.__init__(self)
# Setup DB
self.db = db
self.tb_vocab = sqlalchemy.Table('vocabulary',
sqlalchemy.MetaData(self.db),
autoload=True)
self.model = gtk.ListStore(int, str, str, str, str, int)
self.set_model(self.model)
self.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
self.connect("key_press_event", self._on_key_press)
self.connect("button_press_event", self._on_click)
self.col_chars = gtk.TreeViewColumn('Characters')
self.col_reading = gtk.TreeViewColumn('Pinyin')
self.col_trans = gtk.TreeViewColumn('Translation')
self.append_column(self.col_chars)
self.append_column(self.col_reading)
self.append_column(self.col_trans)
self.cel_chars = gtk.CellRendererText()
self.cel_chars.set_property('editable', True)
self.cel_chars.connect("edited", self._on_cell_edited, 1)
self.cel_reading = gtk.CellRendererText()
self.cel_reading.set_property('editable', True)
self.cel_reading.connect("edited", self._on_cell_edited, 3)
self.cel_trans = gtk.CellRendererText()
self.cel_trans.set_property('editable', True)
self.cel_trans.connect("edited", self._on_cell_edited, 4)
self.col_chars.pack_start(self.cel_chars, False)
self.col_reading.pack_start(self.cel_reading, False)
self.col_trans.pack_start(self.cel_trans, False)
self.col_chars.set_attributes(self.cel_chars, text=1)
self.col_reading.set_attributes(self.cel_reading, text=3)
self.col_trans.set_attributes(self.cel_trans, text=4)
def load(self, lesson):
self.lesson = lesson
if lesson == -1:
query = self.tb_vocab.select()
else:
query = self.tb_vocab.select(self.tb_vocab.c.lesson == lesson)
res = query.execute()
self.model.clear()
for r in res:
self.model.append(r)
def _on_key_press(self, widget, event):
if event.keyval == gtk.keysyms.Delete:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL,
gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO,
"Are you sure you want to delete selected words?")
response = dialog.run()
dialog.destroy()
if response == gtk.RESPONSE_YES:
sel = self.get_selection()
model, pathlist = sel.get_selected_rows()
for path in pathlist:
self._delete_row(model.get_iter(path))
self._delete_commit()
def _on_click(self, widget, event):
if event.button == 3:
x = int(event.x)
y = int(event.y)
time = event.time
pthinfo = widget.get_path_at_pos(x, y)
if pthinfo is not None:
path, col, cellx, celly = pthinfo
widget.grab_focus()
widget.set_cursor( path, col, 0)
pmenu = gtk.Menu()
item = gtk.MenuItem("New")
item.connect("activate", self._on_popup_new_clicked)
pmenu.append(item)
item = gtk.MenuItem("Delete")
pmenu.append(item)
pmenu.show_all()
pmenu.popup( None, None, None, event.button, time)
return True
def _on_popup_new_clicked(self, widget):
ins = self.tb_vocab.insert()
new = ins.values(simplified='', traditional='', reading='',
translation='', lesson=self.lesson)
res = self.db.execute(new)
newid = res.last_inserted_ids()[0]
self.model.append([newid, '', '', '', '', self.lesson])
def _on_cell_edited(self, cell, path, new_text, col_id):
it = self.model.get_iter(path)
self.model[it][col_id] = new_text
self._update_row(it)
def _update_row(self, it):
row = self.model[it]
update = self.tb_vocab.update().where(
self.tb_vocab.c.id==row[0])
update_v = update.values(simplified=unicode(row[1]),
traditional=unicode(row[2]),
reading=unicode(row[3]),
translation=unicode(row[4]),
lesson=self.lesson)
self.db.execute(update_v)
def _delete_row(self, it):
i = self.model[it][0]
self.db.execute(self.tb_vocab.delete().where(self.tb_vocab.c.id == i))
self.model[it][0] = -2
def _delete_commit(self):
for it in self.model:
if it[0] == -2:
self.model.remove(it.iter)
| tomas-mazak/taipan | taipan/vocabulary.py | Python | gpl-3.0 | 9,999 |
package org.welsh.selenium.cluster;
import static org.junit.Assert.*;
import org.junit.Test;
import org.welsh.selenium.cluster.domain.SeleniumHub;
import org.welsh.selenium.cluster.exception.NoServerAvailableException;
import com.thoughtworks.selenium.Selenium;
/**
* Class to Test Using the SeleniumCluster to get
* the Selenium Instance and verify it functions when
* used.
*
* @author dwelsh
*
*/
public class SeleniumTest {
/**
* Base URL
*/
private static final String URL = "http://www.reddit.com/";
/**
* Browser to Use
*/
private static final String BROWSER = "*firefox";
/**
* Test to confirm that instance SeleniumCluster returns
* is a valid Selenium Object and works.
*
* @throws InterruptedException
*/
@Test
public void testSeleniumClusterOnSelenium() throws InterruptedException
{
try {
SeleniumCluster seleniumCluster = new SeleniumCluster(BROWSER, URL);
seleniumCluster.addSeleniumHub("localhost", 6444); // Unavailable Hub
seleniumCluster.addSeleniumHub(new SeleniumHub("localhost", 5444)); // Available Hub
Selenium selenium = seleniumCluster.getAvailableSelenium();
selenium.start();
selenium.open(URL);
selenium.windowMaximize();
assertTrue(selenium.isTextPresent("eddit is a website about everything"));
Thread.sleep(5000);
selenium.stop();
assertTrue(true);
} catch (NoServerAvailableException e) {
fail("No Hubs were Found Available. ");
}
}
}
| welsh/selenium-cluster | src/test/java/org/welsh/selenium/cluster/SeleniumTest.java | Java | gpl-3.0 | 1,470 |
<?php
session_start();
$userid=$_SESSION["userid"];
?>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Travaux écrits - serveur du Gymnase de Nyon</title>
<link rel="stylesheet" type="text/css" media="screen" href="mon_style.css">
</head>
<body>
<div class="main_page">
<div class="page_header floating_element">
<img src="logo_gymnase.png" alt="Logo du Gymnase de Nyon" class="floating_element" height="60px" />
<span class="floating_element_right">
Gymnase de Nyon<br>Travaux écrits de mathématiques
</span>
</div>
<div class="content_section floating_element">
<?php
$option = $_GET["option"];
if ($_SESSION["identification"] == true) {
switch($option) {
case(1):
$accueil = file_get_contents('accueil1.html');
break;
case(2):
$accueil = file_get_contents('accueil2.html');
break;
case(3):
$accueil = file_get_contents('accueil3.html');
break;
case(4):
$accueil = file_get_contents('accueil4.html');
break;
}
}
else {
$accueil = '';
include 'echec_identification.php';
}
echo $accueil;
?>
</div>
</div>
</body>
</html>
| Gauglhofer/exercices-latex-server | index2.php | PHP | gpl-3.0 | 1,571 |
<fieldset>
<legend>Your Address Information</legend>
<div class="form-group required">
<label for="ReservationOrgAddress" class="col-sm-4 col-xs-12 col-form-label text-right">Address</label>
<div class="col-sm-6 col-xs-12">
<input name="org_address" class="form-control" type="text" id="ReservationOrgAddress" required="required" value="{{ old('org_address') }}"/>
</div>
</div>
<div class="form-group required">
<label for="ReservationOrgCity" class="col-sm-4 col-xs-12 col-form-label text-right">City</label>
<div class="col-sm-6 col-xs-12">
<input name="org_city" class="form-control" type="text" id="ReservationOrgCity" required="required" value="{{ old('org_city') }}"/>
</div>
</div>
</fieldset>
| parsipixel/bl | resources/views/reservation/partials/form-field-sets/your-address.blade.php | PHP | gpl-3.0 | 796 |
// $Id: SubordinateStation.hh 2641 2007-09-02 21:31:02Z flaterco $
/* SubordinateStation Station with offsets.
Copyright (C) 1998 David Flater.
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/>.
*/
class SubordinateStation: public Station {
public:
// See HarmonicsFile::getStation.
SubordinateStation (const Dstr &name_,
const StationRef &stationRef,
const ConstituentSet &constituents,
const Dstr ¬e_,
CurrentBearing minCurrentBearing_,
CurrentBearing maxCurrentBearing_,
const MetaFieldVector &metadata,
const HairyOffsets &offsets);
// All these public methods are replacing virtual methods of
// Station. See Station.hh for descriptions.
Station * const clone() const;
const PredictionValue minLevel() const;
const PredictionValue maxLevel() const;
const PredictionValue predictTideLevel (Timestamp predictTime);
void predictTideEvents (Timestamp startTime,
Timestamp endTime,
TideEventsOrganizer &organizer,
TideEventsFilter filter = noFilter);
protected:
const HairyOffsets _offsets;
// predictTideLevel cached bracket. The code has gotten wordy
// enough already without renaming these all to
// uncorrectedLeftEventTime, etc.
Timestamp uncleftt, uncrightt, subleftt, subrightt;
PredictionValue uncleftp, uncrightp, subleftp, subrightp;
Units::PredictionUnits cacheUnits;
const bool isSubordinateStation();
const bool haveFloodBegins();
const bool haveEbbBegins();
// Wrapper for findSimpleMarkCrossing that does necessary
// compensations for substation interpolation. Like
// findSimpleMarkCrossing and findMarkCrossing_Dairiki, this method
// is insensitive to the relative ordering of tideEvent1 and
// tideEvent2.
const Timestamp findInterpolatedSubstationMarkCrossing (
const TideEvent &tideEvent1,
const TideEvent &tideEvent2,
PredictionValue marklev,
bool &isRising_out);
// Submethod of predictTideEvents.
void addInterpolatedSubstationMarkCrossingEvents (
Timestamp startTime,
Timestamp endTime,
TideEventsOrganizer &organizer);
// Given eventTime and eventType, fill in other fields and possibly
// apply corrections.
void finishTideEvent (TideEvent &te);
};
// Cleanup2006 Done
| shralpmeister/shralptide2 | XTide/SubordinateStation.hh | C++ | gpl-3.0 | 3,098 |
<?php
/**
* TastyIgniter
*
* An open source online ordering, reservation and management system for restaurants.
*
* @package TastyIgniter
* @author OrderDime
* @copyright TastyIgniter
* @link http://tastyigniter.com
* @license http://opensource.org/licenses/GPL-3.0 The GNU GENERAL PUBLIC LICENSE
* @since File available since Release 1.0
*/
defined('BASEPATH') OR exit('No direct script access allowed');
if ( ! function_exists('load_class'))
{
/**
* Class registry
*
* This function acts as a singleton. If the requested class does not
* exist it is instantiated and set to a static variable. If it has
* previously been instantiated the variable is returned.
*
* @param string the class name being requested
* @param string the directory where the class should be found
* @param string an optional argument to pass to the class constructor
* @return object
*/
function &load_class($class, $directory = 'libraries', $param = NULL)
{
static $_classes = array();
// Does the class exist? If so, we're done...
if (isset($_classes[$class]))
{
return $_classes[$class];
}
$name = FALSE;
// Look for the class first in the local application/libraries folder
// then in the native system/libraries folder
foreach (array(IGNITEPATH, BASEPATH) as $path)
{
if (file_exists($path.$directory.'/'.$class.'.php'))
{
$name = 'CI_'.$class;
if (class_exists($name, FALSE) === FALSE)
{
require_once($path.$directory.'/'.$class.'.php');
}
break;
}
}
// Is the request a class extension? If so we load it too
if (file_exists(IGNITEPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
{
$name = config_item('subclass_prefix').$class;
if (class_exists($name, FALSE) === FALSE)
{
require_once(IGNITEPATH.$directory.'/'.$name.'.php');
}
}
// Did we find the class?
if ($name === FALSE)
{
// Note: We use exit() rather than show_error() in order to avoid a
// self-referencing loop with the Exceptions class
set_status_header(503);
echo 'Unable to locate the specified class: '.$class.'.php';
exit(5); // EXIT_UNK_CLASS
}
// Keep track of what we just loaded
is_loaded($class);
$_classes[$class] = isset($param)
? new $name($param)
: new $name();
return $_classes[$class];
}
}
// --------------------------------------------------------------------
if ( ! function_exists('get_config'))
{
/**
* Loads the main config.php file
*
* This function lets us grab the config file even if the Config class
* hasn't been instantiated yet
*
* @param array
* @return array
*/
function &get_config(Array $replace = array())
{
static $config;
if (empty($config))
{
$file_path = IGNITEPATH.'config/config.php';
$found = FALSE;
if (file_exists($file_path))
{
$found = TRUE;
require($file_path);
}
// Is the config file in the environment folder?
if (file_exists($file_path = IGNITEPATH.'config/'.ENVIRONMENT.'/config.php'))
{
require($file_path);
}
elseif ( ! $found)
{
set_status_header(503);
echo 'The configuration file does not exist.';
exit(3); // EXIT_CONFIG
}
// Does the $config array exist in the file?
if ( ! isset($config) OR ! is_array($config))
{
set_status_header(503);
echo 'Your config file does not appear to be formatted correctly.';
exit(3); // EXIT_CONFIG
}
}
// Are any values being dynamically added or replaced?
foreach ($replace as $key => $val)
{
$config[$key] = $val;
}
return $config;
}
}
// ------------------------------------------------------------------------
if ( ! function_exists('get_mimes'))
{
/**
* Returns the MIME types array from config/mimes.php
*
* @return array
*/
function &get_mimes()
{
static $_mimes;
if (empty($_mimes))
{
if (file_exists(IGNITEPATH.'config/'.ENVIRONMENT.'/mimes.php'))
{
$_mimes = include(IGNITEPATH.'config/'.ENVIRONMENT.'/mimes.php');
}
elseif (file_exists(IGNITEPATH.'config/mimes.php'))
{
$_mimes = include(IGNITEPATH.'config/mimes.php');
}
else
{
$_mimes = array();
}
}
return $_mimes;
}
}
// ------------------------------------------------------------------------ | Delitex/test2 | system/tastyigniter/core/Common.php | PHP | gpl-3.0 | 5,221 |
package ummisco.gama.opengl;
import java.awt.Color;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import com.jogamp.common.nio.Buffers;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.util.gl2.GLUT;
import msi.gama.common.geometry.ICoordinates;
import msi.gama.common.geometry.Scaling3D;
import msi.gama.metamodel.shape.GamaPoint;
import msi.gama.metamodel.shape.IShape;
import msi.gama.outputs.LayeredDisplayData;
import msi.gama.util.GamaColor.NamedGamaColor;
import ummisco.gama.modernOpenGL.FrameBufferObject;
import ummisco.gama.modernOpenGL.shader.AbstractShader;
import ummisco.gama.modernOpenGL.shader.postprocessing.AbstractPostprocessingShader;
import ummisco.gama.modernOpenGL.shader.postprocessing.KeystoneShaderProgram;
import ummisco.gama.opengl.scene.OpenGL;
public class KeystoneDrawer implements IKeystoneState {
private FrameBufferObject fboScene;
private final JOGLRenderer renderer;
private GL2 gl;
private OpenGL openGL;
protected boolean drawKeystoneHelper = false;
protected int cornerSelected = -1, cornerHovered = -1;
private int uvMappingBufferIndex;
private int verticesBufferIndex;
private int indexBufferIndex;
private KeystoneShaderProgram shader;
private boolean worldCorners = false;
// private final Envelope3D[] cornersInPixels = new Envelope3D[] { new Envelope3D(0, 0, 0, 0, 0, 0),
// new Envelope3D(0, 0, 0, 0, 0, 0), new Envelope3D(0, 0, 0, 0, 0, 0), new Envelope3D(0, 0, 0, 0, 0, 0) };
private static final Color[] FILL_COLORS = new Color[] { NamedGamaColor.getNamed("gamared").withAlpha(0.5),
NamedGamaColor.getNamed("gamablue").withAlpha(0.5), NamedGamaColor.getNamed("black").withAlpha(0.5) };
final IntBuffer ibIdxBuff = Buffers.newDirectIntBuffer(new int[] { 0, 1, 2, 0, 2, 3 });
public KeystoneDrawer(final JOGLRenderer r) {
this.renderer = r;
}
public void setGLHelper(final OpenGL openGL) {
this.openGL = openGL;
this.gl = openGL.getGL();
}
@Override
public int getCornerSelected() {
return cornerSelected;
}
@Override
public GamaPoint[] getCoords() {
return renderer.data.getKeystone().toCoordinateArray();
}
@Override
public GamaPoint getKeystoneCoordinates(final int corner) {
return getCoords()[corner];
}
@Override
public boolean drawKeystoneHelper() {
return drawKeystoneHelper;
}
@Override
public void startDrawHelper() {
drawKeystoneHelper = true;
cornerSelected = -1;
}
@Override
public void stopDrawHelper() {
drawKeystoneHelper = false;
}
public void switchCorners() {
worldCorners = !renderer.data.KEYSTONE_IDENTITY.getEnvelope().covers(renderer.data.getKeystone().getEnvelope());
}
public void dispose() {
if (fboScene != null) {
fboScene.cleanUp();
}
gl.glDeleteBuffers(3, new int[] { indexBufferIndex, verticesBufferIndex, uvMappingBufferIndex }, 0);
}
public void beginRenderToTexture() {
gl.glClearColor(0, 0, 0, 1.0f);
gl.glClear(GL2.GL_STENCIL_BUFFER_BIT | GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
if (fboScene == null) {
fboScene = new FrameBufferObject(gl, renderer.getDisplayWidth(), renderer.getDisplayHeight());
}
// redirect the rendering to the fbo_scene (will be rendered later, as a texture)
fboScene.bindFrameBuffer();
}
private void drawSquare(final double[] center, final double side, final Color fill) {
drawRectangle(center, side, side, fill);
}
private void drawRectangle(final double[] center, final double width, final double height, final Color fill) {
openGL.pushMatrix();
openGL.translateBy(center);
openGL.setCurrentColor(fill);
openGL.scaleBy(Scaling3D.of(width, height, 1));
openGL.drawCachedGeometry(IShape.Type.SQUARE, null);
openGL.popMatrix();
}
private void drawKeystoneMarks() {
//
final int displayWidthInPixels = renderer.getViewWidth();
final int displayHeightInPixels = renderer.getViewHeight();
final double pixelWidthIn01 = 1d / displayWidthInPixels;
final double pixelHeightIn01 = 1d / displayHeightInPixels;
final double[] worldCoords = renderer.getPixelWidthAndHeightOfWorld();
final double worldWidthInPixels = worldCoords[0];
final double worldHeightInPixels = worldCoords[1];
final double widthRatio = worldWidthInPixels / displayWidthInPixels;
final double heightRatio = worldHeightInPixels / displayHeightInPixels;
final double xOffsetIn01 = 1 - widthRatio;
final double yOffsetIn01 = 1 - heightRatio;
final double labelHeightIn01 = pixelHeightIn01 * (18 + 20);
ICoordinates vertices;
if (!worldCorners) {
vertices = LayeredDisplayData.KEYSTONE_IDENTITY;
// 0, 0, 0 | 0, 1, 0 | 1, 1, 0 | 1, 0, 0
} else {
vertices = ICoordinates.ofLength(4);
vertices.at(0).setLocation(xOffsetIn01, yOffsetIn01, 0);
vertices.at(1).setLocation(xOffsetIn01, 1 - yOffsetIn01, 0);
vertices.at(2).setLocation(1 - xOffsetIn01, 1 - yOffsetIn01, 0);
vertices.at(3).setLocation(1 - xOffsetIn01, yOffsetIn01, 0);
}
openGL.pushIdentity(GL2.GL_PROJECTION);
gl.glOrtho(0, 1, 0, 1, 1, -1);
openGL.disableLighting();
vertices.visit((id, x, y, z) -> {
// cornersInPixels[id].setToNull();
openGL.pushIdentity(GL2.GL_MODELVIEW);
// Basic computations on text and color
final String text = floor4Digit(getCoords()[id].x) + "," + floor4Digit(getCoords()[id].y);
final int lengthOfTextInPixels = openGL.getGlut().glutBitmapLength(GLUT.BITMAP_HELVETICA_18, text);
final double labelWidthIn01 = pixelWidthIn01 * (lengthOfTextInPixels + 20);
final int fill = id == cornerSelected ? 0 : id == cornerHovered ? 1 : 2;
// Drawing the background of labels
final double xLabelIn01 = x + (id == 0 || id == 1 ? labelWidthIn01 / 2 : -labelWidthIn01 / 2);
final double yLabelIn01 = y + (id == 0 || id == 3 ? labelHeightIn01 / 2 : -labelHeightIn01 / 2);
drawRectangle(new double[] { xLabelIn01, yLabelIn01, z }, labelWidthIn01, labelHeightIn01,
FILL_COLORS[fill]);
// Writing back the envelope for user interaction
// cornersInPixels[id].setToZero();
// cornersInPixels[id].translate(xLabelIn01 * displayWidthInPixels, (1 - yLabelIn01) *
// displayHeightInPixels,
// 0);
// cornersInPixels[id].expandBy(labelWidthIn01 / 2 * displayWidthInPixels,
// labelHeightIn01 / 2 * displayHeightInPixels);
// Setting back the color to white and restoring the matrix
gl.glColor3d(1, 1, 1);
openGL.getGL().glLoadIdentity();
// Drawing the text itself
final double xPosIn01 = id == 0 || id == 1 ? 10 * pixelWidthIn01 + (worldCorners ? xOffsetIn01 : 0)
: 1 - labelWidthIn01 + 10 * pixelWidthIn01 - (worldCorners ? xOffsetIn01 : 0);
final double yPosIn01 = id == 0 || id == 3 ? 12 * pixelHeightIn01 + (worldCorners ? yOffsetIn01 : 0)
: 1 - labelHeightIn01 + 12 * pixelHeightIn01 - (worldCorners ? yOffsetIn01 : 0);
openGL.getGL().glRasterPos2d(xPosIn01, yPosIn01);
openGL.getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_18, text);
openGL.pop(GL2.GL_MODELVIEW);
}, 4, true);
openGL.pop(GL2.GL_MODELVIEW);
openGL.enableLighting();
openGL.pop(GL2.GL_PROJECTION);
}
private double floor4Digit(final double n) {
double number = n * 1000;
number = Math.round(number);
number /= 1000;
return number;
}
public void finishRenderToTexture() {
if (drawKeystoneHelper) {
drawKeystoneMarks();
}
// gl.glDisable(GL2.GL_DEPTH_TEST); // disables depth testing
final AbstractPostprocessingShader shader = getShader();
// unbind the last fbo
fboScene.unbindCurrentFrameBuffer();
// prepare shader
shader.start();
prepareShader(shader);
// build the surface
createScreenSurface();
// draw
gl.glDrawElements(GL2.GL_TRIANGLES, 6, GL2.GL_UNSIGNED_INT, 0);
shader.stop();
}
public KeystoneShaderProgram getShader() {
if (shader == null) {
shader = new KeystoneShaderProgram(gl, "keystoneVertexShader2", "keystoneFragmentShader2");
final int[] handles = new int[3];
gl.glGenBuffers(3, handles, 0);
uvMappingBufferIndex = handles[0];
verticesBufferIndex = handles[1];
indexBufferIndex = handles[2];
}
return shader;
}
private void prepareShader(final AbstractPostprocessingShader shaderProgram) {
shaderProgram.loadTexture(0);
shaderProgram.storeTextureID(fboScene.getFBOTexture());
}
public void createScreenSurface() {
// Keystoning computation (cf
// http://www.bitlush.com/posts/arbitrary-quadrilaterals-in-opengl-es-2-0)
// transform the coordinates [0,1] --> [-1,+1]
final ICoordinates coords = renderer.data.getKeystone();
final float[] p0 = new float[] { (float) coords.at(0).x * 2f - 1f, (float) (coords.at(0).y * 2f - 1f) }; // bottom-left
final float[] p1 = new float[] { (float) coords.at(1).x * 2f - 1f, (float) coords.at(1).y * 2f - 1f }; // top-left
final float[] p2 = new float[] { (float) coords.at(2).x * 2f - 1f, (float) coords.at(2).y * 2f - 1f }; // top-right
final float[] p3 = new float[] { (float) coords.at(3).x * 2f - 1f, (float) coords.at(3).y * 2f - 1f }; // bottom-right
final float ax = (p2[0] - p0[0]) / 2f;
final float ay = (p2[1] - p0[1]) / 2f;
final float bx = (p3[0] - p1[0]) / 2f;
final float by = (p3[1] - p1[1]) / 2f;
final float cross = ax * by - ay * bx;
if (cross != 0) {
final float cy = (p0[1] - p1[1]) / 2f;
final float cx = (p0[0] - p1[0]) / 2f;
final float s = (ax * cy - ay * cx) / cross;
final float t = (bx * cy - by * cx) / cross;
final float q0 = 1 / (1 - t);
final float q1 = 1 / (1 - s);
final float q2 = 1 / t;
final float q3 = 1 / s;
// I can now pass (u * q, v * q, q) to OpenGL
final float[] listVertices =
new float[] { p0[0], p0[1], 1f, p1[0], p1[1], 0f, p2[0], p2[1], 0f, p3[0], p3[1], 1f };
final float[] listUvMapping =
new float[] { 0f, 1f * q0, 0f, q0, 0f, 0f, 0f, q1, 1f * q2, 0f, 0f, q2, 1f * q3, 1f * q3, 0f, q3 };
// VERTICES POSITIONS BUFFER
storeAttributes(AbstractShader.POSITION_ATTRIBUTE_IDX, verticesBufferIndex, 3, listVertices);
// UV MAPPING (If a texture is defined)
storeAttributes(AbstractShader.UVMAPPING_ATTRIBUTE_IDX, uvMappingBufferIndex, 4, listUvMapping);
}
// gl.glActiveTexture(GL.GL_TEXTURE0);
gl.glBindTexture(GL.GL_TEXTURE_2D, fboScene.getFBOTexture());
// Select the VBO, GPU memory data, to use for colors
gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, indexBufferIndex);
gl.glBufferData(GL2.GL_ELEMENT_ARRAY_BUFFER, 24, ibIdxBuff, GL2.GL_STATIC_DRAW);
ibIdxBuff.rewind();
}
private void storeAttributes(final int shaderAttributeType, final int bufferIndex, final int size,
final float[] data) {
// Select the VBO, GPU memory data, to use for data
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, bufferIndex);
// Associate Vertex attribute with the last bound VBO
gl.glVertexAttribPointer(shaderAttributeType, size, GL2.GL_FLOAT, false, 0, 0 /* offset */);
// compute the total size of the buffer :
final int numBytes = data.length * 4;
gl.glBufferData(GL2.GL_ARRAY_BUFFER, numBytes, null, GL2.GL_STATIC_DRAW);
final FloatBuffer fbData = Buffers.newDirectFloatBuffer(data);
gl.glBufferSubData(GL2.GL_ARRAY_BUFFER, 0, numBytes, fbData);
gl.glEnableVertexAttribArray(shaderAttributeType);
}
@Override
public void setUpCoords() {}
@Override
public void setCornerSelected(final int cornerId) {
cornerSelected = cornerId;
}
@Override
public void resetCorner(final int cornerId) {
setKeystoneCoordinates(cornerId, LayeredDisplayData.KEYSTONE_IDENTITY.at(cornerId));
cornerSelected = -1;
cornerHovered = -1;
}
@Override
public int cornerSelected(final GamaPoint mouse) {
if (mouse.x < renderer.getViewWidth() / 2) {
if (mouse.y < renderer.getViewHeight() / 2) {
return 1;
} else {
return 0;
}
} else {
if (mouse.y < renderer.getViewHeight() / 2) {
return 2;
} else {
return 3;
}
}
}
@Override
public int cornerHovered(final GamaPoint mouse) {
if (mouse.x < renderer.getViewWidth() / 2) {
if (mouse.y < renderer.getViewHeight() / 2) {
return 1;
} else {
return 0;
}
} else {
if (mouse.y < renderer.getViewHeight() / 2) {
return 2;
} else {
return 3;
}
}
}
@Override
public void setCornerHovered(final int cornerId) {
cornerHovered = cornerId;
}
@Override
public void setKeystoneCoordinates(final int cornerId, final GamaPoint p) {
renderer.data.getKeystone().replaceWith(cornerId, p.x, p.y, p.z);
switchCorners();
renderer.data.setKeystone(renderer.data.getKeystone());
}
@Override
public boolean isKeystoneInAction() {
if (drawKeystoneHelper) {
return true;
}
if (!renderer.data.isKeystoneDefined()) {
return false;
}
return true;
}
public void reshape(final int width, final int height) {
if (fboScene != null) {
fboScene.setDisplayDimensions(width, height);
}
}
}
| hqnghi88/gamaClone | ummisco.gama.opengl/src/ummisco/gama/opengl/KeystoneDrawer.java | Java | gpl-3.0 | 12,787 |
using OpenTK;
using OpenTK.Graphics;
using micfort.GHL;
using micfort.GHL.Collections;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using CG_2IV05.Common;
namespace CG_2IV05.Visualize
{
public class VBOLoader
{
private ConcurrentPriorityQueue<NodeWithData, int> loadQueue;
public List<NodeWithData> VBOList { get; set; }
private micfort.GHL.ConsumerThread<NodeWithData> thread;
private OpenTK.Graphics.GraphicsContext context;
public VBOLoader(List<NodeWithData> vboList)
{
loadQueue = new ConcurrentPriorityQueue<NodeWithData, int>(new PriorityQueue<NodeWithData, int>());
this.VBOList = vboList;
thread = new ConsumerThread<NodeWithData>(loadQueue, Handler);
thread.ExceptionHandling = ExceptionHandling.ReportErrorContinue;
}
private void Handler(NodeWithData data)
{
if(context == null)
{
INativeWindow window = new NativeWindow();
context = new GraphicsContext(GraphicsMode.Default, window.WindowInfo);
context.MakeCurrent(window.WindowInfo);
}
data.LoadNodeFromDisc();
lock (VBOList)
{
VBOList.Add(data);
}
}
public void Start()
{
thread.Start();
}
public void Stop()
{
thread.Stop();
}
public void enqueueNode(NodeWithData node, int priority = 0)
{
loadQueue.Enqueue(node, priority);
}
}
}
| micfort/2IV05 | Visualize/VBOLoader.cs | C# | gpl-3.0 | 1,559 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="sv" version="2.0">
<context>
<name>AboutPage</name>
<message>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="43"/>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="156"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="45"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="158"/>
<source>About Tweetian</source>
<translation>Om Tweetian</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="59"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="61"/>
<source>Tweetian is a feature-rich Twitter app for smartphones, powered by Qt and QML. It has a simple, native and easy-to-use UI that will surely make you enjoy the Twitter experience on your smartphone. Tweetian is open source and licensed under GPL v3.</source>
<translation>Tweetian är en funktionsrik Twitter-applikation för smartphones, byggd med Qt och QML. Den har ett enkelt, nativt och lättanvänt gränssnitt som säkert kommer göra att du gillar Twitter-upplevelsen i din smartphone. Tweetian bygger på öppen källkod och är licensierat under GPL v3.</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="65"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="67"/>
<source>Version</source>
<translation>Version</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="85"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="87"/>
<source>Developed By</source>
<translation>Utvecklad av</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="93"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="95"/>
<source>Special Thanks</source>
<translation>Speciellt tack till</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="107"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="109"/>
<source>Powered By</source>
<translation>Drivs med</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="127"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="129"/>
<source>Legal</source>
<translation>Juridiskt</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="132"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="134"/>
<source>Twitter Privacy Policy</source>
<translation>Twitters sekretesspolicy</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AboutPage.qml" line="142"/>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="144"/>
<source>Twitter Terms of Service</source>
<translation>Twitters tjänstevillkor</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/AboutPage.qml" line="30"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
</context>
<context>
<name>AbstractUserPage</name>
<message>
<location filename="../qml/tweetian-symbian/UserPageCom/AbstractUserPage.qml" line="48"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
</context>
<context>
<name>AccountItem</name>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountItem.qml" line="53"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountItem.qml" line="53"/>
<source>Signed in</source>
<translation>Inloggad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountItem.qml" line="53"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountItem.qml" line="53"/>
<source>Not signed in</source>
<translation>Inte inloggad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountItem.qml" line="84"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountItem.qml" line="84"/>
<source>Sign Out</source>
<translation>Logga ut</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountItem.qml" line="84"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountItem.qml" line="84"/>
<source>Sign In</source>
<translation>Logga in</translation>
</message>
</context>
<context>
<name>AccountTab</name>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTab.qml" line="44"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTab.qml" line="44"/>
<source>About Pocket</source>
<translation>Om Pocket</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTab.qml" line="52"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTab.qml" line="52"/>
<source>About Instapaper</source>
<translation>Om Instapaper</translation>
</message>
</context>
<context>
<name>AccountTabScript</name>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="23"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="23"/>
<source>Signed in to Pocket successfully</source>
<translation>Inloggningen på Pocket lyckades</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="28"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="28"/>
<source>Error signing in to Pocket (%1)</source>
<translation>Fel vid inloggning på Pocket (%1)</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="35"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="35"/>
<source>Signed in to Instapaper successfully</source>
<translation>Inloggningen på Instapaper lyckades</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="40"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="40"/>
<source>Error signing in to Instapaper (%1)</source>
<translation>Fel vid inloggning på Instapaper (%1)</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="47"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="47"/>
<source>Sign in to Pocket</source>
<translation>Logga in på Pocket</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="56"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="56"/>
<source>Sign in to Instapaper</source>
<translation>Logga in på Instapaper</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="65"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="65"/>
<source>Do you want to sign out from your Twitter account? All other accounts will also automatically sign out. All settings will be reset.</source>
<translation>Vill du logga ut från ditt Twitter-konto? Alla andra konton kommer också att bli utloggade automatiskt. Alla inställningar återställs.</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="66"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="66"/>
<source>Twitter Sign Out</source>
<translation>Logga ut från Twitter</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="81"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="81"/>
<source>Do you want to sign out from your Pocket account?</source>
<translation>Vill du logga ut från ditt Pocket-konto?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="82"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="82"/>
<source>Pocket Sign Out</source>
<translation>Logga ut från Pocket</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="85"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="85"/>
<source>Signed out from your Pocket account successfully</source>
<translation>Utloggningen från Pocket-kontot lyckades</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="90"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="90"/>
<source>Do you want to sign out from your Instapaper account?</source>
<translation>Vill du logga ut från ditt Instapaper-konto?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="91"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="91"/>
<source>Instapaper Sign Out</source>
<translation>Logga ut från Instapaper</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/AccountTabScript.js" line="94"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/AccountTabScript.js" line="94"/>
<source>Signed out from your Instapaper account successfully</source>
<translation>Utloggningen från Instapaper-kontot lyckades</translation>
</message>
</context>
<context>
<name>AdvSearchPage</name>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="73"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="69"/>
<source>Search</source>
<translation>Sök</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="77"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="74"/>
<source>Cancel</source>
<translation>Avbryt</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="96"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="91"/>
<source>Words</source>
<translation>Ord</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="100"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="95"/>
<source>All of these words</source>
<translation>Alla dessa ord</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="102"/>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="109"/>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="116"/>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="123"/>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="170"/>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="177"/>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="184"/>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="210"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="97"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="104"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="111"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="118"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="165"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="172"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="179"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="205"/>
<source>eg. %1</source>
<translation>t. ex. %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="107"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="102"/>
<source>Exact phrase</source>
<translation>Exakt fras</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="114"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="109"/>
<source>Any of these words</source>
<translation>Något av dessa ord</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="121"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="116"/>
<source>None of these words</source>
<translation>Inget av dessa ord</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="140"/>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="246"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="137"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="242"/>
<source>Language</source>
<translation>Språk</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="164"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="159"/>
<source>Users</source>
<translation>Användare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="168"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="163"/>
<source>From any of these users</source>
<translation>Från någon av dessa användare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="175"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="170"/>
<source>To any of these users</source>
<translation>Till någon av dessa användare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="182"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="177"/>
<source>Mentioning any of these users</source>
<translation>Nämnandes någon av dessa användare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="187"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="182"/>
<source>Filters</source>
<translation>Filter</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="191"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="186"/>
<source>Contain links</source>
<translation>Innehåller länkar</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="196"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="191"/>
<source>Contain images</source>
<translation>Innehåller bilder</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="201"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="196"/>
<source>Contain videos</source>
<translation>Innehåller videoklipp</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="204"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="199"/>
<source>Other</source>
<translation>Övrigt</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="208"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="203"/>
<source>From any of these sources</source>
<translation>Från någon av dessa källor</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="215"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="210"/>
<source>Positive attitude :)</source>
<translation>Positiv attityd :)</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="220"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="215"/>
<source>Negative attitude :(</source>
<translation>Negativ attityd :(</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="225"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="220"/>
<source>Question ?</source>
<translation>Fråga ?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="230"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="225"/>
<source>Include retweets</source>
<translation>Inkludera retweets</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/AdvSearchPage.qml" line="240"/>
<location filename="../qml/tweetian-symbian/AdvSearchPage.qml" line="235"/>
<source>Advanced Search</source>
<translation>Avancerad sökning</translation>
</message>
</context>
<context>
<name>BrowseUsersPage</name>
<message>
<location filename="../qml/tweetian-symbian/BrowseUsersPage.qml" line="50"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
</context>
<context>
<name>Calculations</name>
<message>
<location filename="../qml/tweetian-harmattan/Utils/Calculations.js" line="28"/>
<location filename="../qml/tweetian-symbian/Utils/Calculations.js" line="28"/>
<source>~%1 per day</source>
<translation>~%1 per dag</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Utils/Calculations.js" line="29"/>
<location filename="../qml/tweetian-symbian/Utils/Calculations.js" line="29"/>
<source>~%1 per week</source>
<translation>~%1 per vecka</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Utils/Calculations.js" line="30"/>
<location filename="../qml/tweetian-symbian/Utils/Calculations.js" line="30"/>
<source>~%1 per month</source>
<translation>~%1 per månad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Utils/Calculations.js" line="31"/>
<location filename="../qml/tweetian-symbian/Utils/Calculations.js" line="31"/>
<source>< 1 per month</source>
<translation>< 1 per månad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Utils/Calculations.js" line="38"/>
<location filename="../qml/tweetian-symbian/Utils/Calculations.js" line="38"/>
<source>Now</source>
<translation>Nu</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Utils/Calculations.js" line="54"/>
<location filename="../qml/tweetian-symbian/Utils/Calculations.js" line="54"/>
<source>Yesterday %1</source>
<translation>Igår %1</translation>
</message>
<message numerus="yes">
<location filename="../qml/tweetian-harmattan/Utils/Calculations.js" line="50"/>
<location filename="../qml/tweetian-symbian/Utils/Calculations.js" line="50"/>
<source>%n hr(s)</source>
<translation><numerusform>%n tim</numerusform><numerusform>%n tim</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../qml/tweetian-harmattan/Utils/Calculations.js" line="46"/>
<location filename="../qml/tweetian-symbian/Utils/Calculations.js" line="46"/>
<source>%n min(s)</source>
<translation><numerusform>%n min</numerusform><numerusform>%n min</numerusform></translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Utils/Calculations.js" line="42"/>
<location filename="../qml/tweetian-symbian/Utils/Calculations.js" line="42"/>
<source>Just now</source>
<translation>Precis nu</translation>
</message>
</context>
<context>
<name>DMDialog</name>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/DMDialog.qml" line="34"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DMDialog.qml" line="38"/>
<source>Copy DM</source>
<translation>Kopiera DM</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/DMDialog.qml" line="38"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DMDialog.qml" line="42"/>
<source>DM copied to clipboard</source>
<translation>DM kopierat till urklipp</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/DMDialog.qml" line="42"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DMDialog.qml" line="47"/>
<source>Delete</source>
<translation>Radera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/DMDialog.qml" line="46"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DMDialog.qml" line="52"/>
<source>%1 Profile</source>
<translation>%1 profil</translation>
</message>
</context>
<context>
<name>DMThreadPage</name>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/DMThreadPage.qml" line="65"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DMThreadPage.qml" line="72"/>
<source>DM: %1</source>
<translation>DM: %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/DMThreadPage.qml" line="95"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DMThreadPage.qml" line="102"/>
<source>Direct message deleted successfully</source>
<translation>Direktmeddelande raderat framgångsrikt</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/DMThreadPage.qml" line="115"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DMThreadPage.qml" line="123"/>
<source>Do you want to delete this direct message?</source>
<translation>Vill du radera detta direktmeddelande?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/DMThreadPage.qml" line="116"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DMThreadPage.qml" line="124"/>
<source>Delete Message</source>
<translation>Radera meddelande</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MainPageCom/DMThreadPage.qml" line="41"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MainPageCom/DMThreadPage.qml" line="46"/>
<source>New DM</source>
<translation>Nytt DM</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MainPageCom/DMThreadPage.qml" line="52"/>
<source>Refresh</source>
<translation>Uppdatera</translation>
</message>
</context>
<context>
<name>DirectMessage</name>
<message numerus="yes">
<location filename="../qml/tweetian-harmattan/MainPageCom/DirectMessage.qml" line="196"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DirectMessage.qml" line="195"/>
<source>%n new message(s)</source>
<translation><numerusform>%n nytt meddelande</numerusform><numerusform>%n nya meddelanden</numerusform></translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/DirectMessage.qml" line="126"/>
<location filename="../qml/tweetian-symbian/MainPageCom/DirectMessage.qml" line="124"/>
<source>No message</source>
<translation>Inga meddelanden</translation>
</message>
</context>
<context>
<name>DynamicQueryDialog</name>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/DynamicQueryDialog.qml" line="27"/>
<location filename="../qml/tweetian-symbian/Dialog/DynamicQueryDialog.qml" line="28"/>
<source>Yes</source>
<translation>Ja</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/DynamicQueryDialog.qml" line="28"/>
<location filename="../qml/tweetian-symbian/Dialog/DynamicQueryDialog.qml" line="29"/>
<source>No</source>
<translation>Nej</translation>
</message>
</context>
<context>
<name>ExitDialog</name>
<message>
<location filename="../qml/tweetian-symbian/Dialog/ExitDialog.qml" line="28"/>
<source>Exit Tweetian</source>
<translation>Avsluta Tweetian</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/Dialog/ExitDialog.qml" line="29"/>
<source>Exit</source>
<translation>Avsluta</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/Dialog/ExitDialog.qml" line="29"/>
<source>Hide</source>
<translation>Dölj</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/Dialog/ExitDialog.qml" line="29"/>
<source>Cancel</source>
<translation>Avbryt</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/Dialog/ExitDialog.qml" line="32"/>
<source>Do you want to hide or exit Tweetian?</source>
<translation>Vill du dölja eller avsluta Tweetian?</translation>
</message>
</context>
<context>
<name>ImageUploader</name>
<message>
<location filename="../src/imageuploader.cpp" line="67"/>
<source>The file %1 does not exists</source>
<translation>Filen %1 existerar inte</translation>
</message>
<message>
<location filename="../src/imageuploader.cpp" line="85"/>
<source>Unable to open the file %1</source>
<translation>Kunde inte öppna filen %1</translation>
</message>
</context>
<context>
<name>ListDelegate</name>
<message>
<location filename="../qml/tweetian-harmattan/Delegate/ListDelegate.qml" line="46"/>
<location filename="../qml/tweetian-symbian/Delegate/ListDelegate.qml" line="46"/>
<source>By %1</source>
<translation>Av %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Delegate/ListDelegate.qml" line="64"/>
<location filename="../qml/tweetian-symbian/Delegate/ListDelegate.qml" line="64"/>
<source>%1 members | %2 subscribers</source>
<translation>%1 medlemmar | %2 prenumeranter</translation>
</message>
</context>
<context>
<name>ListInfo</name>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListInfo.qml" line="35"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListInfo.qml" line="35"/>
<source>List Name</source>
<translation>Listnamn</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListInfo.qml" line="36"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListInfo.qml" line="36"/>
<source>List Owner</source>
<translation>Listägare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListInfo.qml" line="38"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListInfo.qml" line="38"/>
<source>Description</source>
<translation>Beskrivning</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListInfo.qml" line="39"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListInfo.qml" line="39"/>
<source>Member</source>
<translation>Medlemmar</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListInfo.qml" line="40"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListInfo.qml" line="40"/>
<source>Subscriber</source>
<translation>Prenumeranter</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListInfo.qml" line="51"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListInfo.qml" line="51"/>
<source>List Info</source>
<translation>Listinformation</translation>
</message>
</context>
<context>
<name>ListMembers</name>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListMembers.qml" line="31"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListMembers.qml" line="31"/>
<source>Members (%1)</source>
<translation>Medlemmar (%1)</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListMembers.qml" line="32"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListMembers.qml" line="32"/>
<source>No member</source>
<translation>Inga medlemmar</translation>
</message>
</context>
<context>
<name>ListPage</name>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="46"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="47"/>
<source>Delete</source>
<translation>Radera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="47"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="48"/>
<source>Unsubscribe</source>
<translation>Sluta prenumerera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="47"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="48"/>
<source>Subscribe</source>
<translation>Prenumerera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="80"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="81"/>
<source>By %1</source>
<translation>Av %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="91"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="92"/>
<source>You have subscribed to the list %1 successfully</source>
<translation>Du prenumererar framgångsrikt på listan %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="97"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="98"/>
<source>You have unsubscribed from the list %1 successfully</source>
<translation>Du har framgångsrikt slutat prenumerera på listan %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="102"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="103"/>
<source>You have deleted the list %1 successfully</source>
<translation>Du har framgångsrikt raderat listan %1 </translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="114"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="115"/>
<source>Do you want to unsubscribe from the list %1?</source>
<translation>Vill du sluta prenumerera på listan %1?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="115"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="116"/>
<source>Do you want to subscribe to the list %1?</source>
<translation>Vill du prenumerera på listan %1?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="124"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="127"/>
<source>Do you want to delete the list %1?</source>
<translation>Vill du radera listan %1?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="113"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="114"/>
<source>Unsubscribe List</source>
<translation>Sluta prenumerera på lista</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="113"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="114"/>
<source>Subscribe List</source>
<translation>Prenumerera på lista</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPage.qml" line="125"/>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="128"/>
<source>Delete List</source>
<translation>Radera lista</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/ListPage.qml" line="43"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
</context>
<context>
<name>ListSubscribers</name>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListSubscribers.qml" line="31"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListSubscribers.qml" line="31"/>
<source>Subscribers (%1)</source>
<translation>Prenumeranter (%1)</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListSubscribers.qml" line="32"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListSubscribers.qml" line="32"/>
<source>No subscriber</source>
<translation>Inga prenumeranter</translation>
</message>
</context>
<context>
<name>ListTimeline</name>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListTimeline.qml" line="29"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListTimeline.qml" line="29"/>
<source>List Timeline</source>
<translation>Listans tidslinje</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/ListPageCom/ListTimeline.qml" line="30"/>
<location filename="../qml/tweetian-symbian/ListPageCom/ListTimeline.qml" line="30"/>
<source>No tweet</source>
<translation>Inga tweets</translation>
</message>
</context>
<context>
<name>LoadMoreButton</name>
<message>
<location filename="../qml/tweetian-harmattan/Component/LoadMoreButton.qml" line="41"/>
<location filename="../qml/tweetian-symbian/Component/LoadMoreButton.qml" line="41"/>
<source>Load more</source>
<translation>Ladda mer</translation>
</message>
</context>
<context>
<name>LongPressMenu</name>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/LongPressMenu.qml" line="41"/>
<location filename="../qml/tweetian-symbian/Dialog/LongPressMenu.qml" line="44"/>
<source>Reply</source>
<translation>Svara</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/LongPressMenu.qml" line="51"/>
<location filename="../qml/tweetian-symbian/Dialog/LongPressMenu.qml" line="55"/>
<source>Retweet</source>
<translation>Retweeta</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/LongPressMenu.qml" line="60"/>
<location filename="../qml/tweetian-harmattan/Dialog/LongPressMenu.qml" line="66"/>
<location filename="../qml/tweetian-symbian/Dialog/LongPressMenu.qml" line="65"/>
<location filename="../qml/tweetian-symbian/Dialog/LongPressMenu.qml" line="70"/>
<source>%1 Profile</source>
<translation>%1 profil</translation>
</message>
</context>
<context>
<name>MainPage</name>
<message>
<location filename="../qml/tweetian-harmattan/MainPage.qml" line="68"/>
<location filename="../qml/tweetian-symbian/MainPage.qml" line="75"/>
<source>Refresh cache</source>
<translation>Uppdatera cache</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPage.qml" line="73"/>
<location filename="../qml/tweetian-symbian/MainPage.qml" line="81"/>
<source>Settings</source>
<translation>Inställningar</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPage.qml" line="77"/>
<location filename="../qml/tweetian-symbian/MainPage.qml" line="86"/>
<source>About</source>
<translation>Om</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MainPage.qml" line="41"/>
<source>Exit</source>
<translation>Avsluta</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MainPage.qml" line="49"/>
<source>New Tweet</source>
<translation>Ny tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MainPage.qml" line="54"/>
<source>Trends & Search</source>
<translation>Trender & Sök</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MainPage.qml" line="59"/>
<source>My profile</source>
<translation>Min profil</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MainPage.qml" line="64"/>
<source>Menu</source>
<translation>Meny</translation>
</message>
</context>
<context>
<name>MapPage</name>
<message>
<location filename="../qml/tweetian-harmattan/MapPage.qml" line="51"/>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="55"/>
<source>Open in Nokia Maps</source>
<translation>Öppna i Nokia Maps</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MapPage.qml" line="47"/>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="50"/>
<source>View coordinates</source>
<translation>Visa koordinater</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MapPage.qml" line="183"/>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="194"/>
<source>Location Coordinates</source>
<translation>Platskoordinater</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MapPage.qml" line="185"/>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="196"/>
<source>Copy</source>
<translation>Kopiera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MapPage.qml" line="185"/>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="196"/>
<source>Close</source>
<translation>Stäng</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MapPage.qml" line="200"/>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="207"/>
<source>Degrees</source>
<translation>Grader</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MapPage.qml" line="217"/>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="227"/>
<source>Coordinates copied to clipboard</source>
<translation>Koordinater kopierade till urklipp</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MapPage.qml" line="204"/>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="212"/>
<source>Decimal</source>
<translation>Decimaler</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="34"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/MapPage.qml" line="39"/>
<source>Menu</source>
<translation>Meny</translation>
</message>
</context>
<context>
<name>MessageDialog</name>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/MessageDialog.qml" line="28"/>
<location filename="../qml/tweetian-symbian/Dialog/MessageDialog.qml" line="29"/>
<source>Close</source>
<translation>Stäng</translation>
</message>
</context>
<context>
<name>MuteTab</name>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/MuteTab.qml" line="35"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/MuteTab.qml" line="36"/>
<source>Example:
%1</source>
<translation>Exempel:⏎ %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/MuteTab.qml" line="48"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/MuteTab.qml" line="50"/>
<source>Help</source>
<translation>Hjälp</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/MuteTab.qml" line="49"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/MuteTab.qml" line="51"/>
<source>Mute</source>
<translation>Tysta</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/MuteTab.qml" line="58"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/MuteTab.qml" line="61"/>
<source>Save</source>
<translation>Spara</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/MuteTab.qml" line="71"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/MuteTab.qml" line="74"/>
<source>Changes will not be save until you press the save button</source>
<translation>Ändringarna sparas inte förrän du trycker på spara-knappen</translation>
</message>
</context>
<context>
<name>NearbyTweetsPage</name>
<message>
<location filename="../qml/tweetian-harmattan/NearbyTweetsPage.qml" line="52"/>
<location filename="../qml/tweetian-symbian/NearbyTweetsPage.qml" line="56"/>
<source>Refresh Cache & Location</source>
<translation>Uppdatera cache & plats</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NearbyTweetsPage.qml" line="88"/>
<location filename="../qml/tweetian-symbian/NearbyTweetsPage.qml" line="93"/>
<source>No tweet</source>
<translation>Inga tweets</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NearbyTweetsPage.qml" line="97"/>
<location filename="../qml/tweetian-symbian/NearbyTweetsPage.qml" line="102"/>
<source>Getting location...</source>
<translation>Hämtar plats...</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NearbyTweetsPage.qml" line="97"/>
<location filename="../qml/tweetian-symbian/NearbyTweetsPage.qml" line="102"/>
<source>Nearby Tweets</source>
<translation>Tweets i närheten</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/NearbyTweetsPage.qml" line="40"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/NearbyTweetsPage.qml" line="45"/>
<source>Menu</source>
<translation>Meny</translation>
</message>
</context>
<context>
<name>NewTweetPage</name>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="351"/>
<source>No music is playing currently or music player is not running</source>
<translation>Ingen musik spelas för tillfället eller så är inte musikspelaren igång</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="55"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="48"/>
<source>Tweet</source>
<translation>Tweeta</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="56"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="49"/>
<source>Reply</source>
<translation>Svara</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="57"/>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="281"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="50"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="269"/>
<source>Retweet</source>
<translation>Retweeta</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="58"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="51"/>
<source>DM</source>
<translation>DM</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="91"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="85"/>
<source>Cancel</source>
<translation>Avbryt</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="108"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="103"/>
<source>Tap to write...</source>
<translation>Peka för att skriva...</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="155"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="151"/>
<source>Tap to Edit</source>
<translation>Peka för att redigera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="216"/>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="251"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="213"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="248"/>
<source>Add</source>
<translation>Lägg till</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="223"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="221"/>
<source>Updating...</source>
<translation>Uppdaterar...</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="231"/>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="251"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="229"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="248"/>
<source>View/Remove</source>
<translation>Visa/Radera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="261"/>
<source>Quick Tweet</source>
<translation>Snabbtweet</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="267"/>
<source>Music Player: Now Playing</source>
<translation>Musikspelare: Spelar nu</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="276"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="264"/>
<source>Uploading...</source>
<translation>Laddar upp...</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="279"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="267"/>
<source>New Tweet</source>
<translation>Ny tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="280"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="268"/>
<source>Reply to %1</source>
<translation>Svara till %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="282"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="270"/>
<source>DM to %1</source>
<translation>DM till %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="295"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="288"/>
<source>View location</source>
<translation>Visa plats</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="302"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="296"/>
<source>Remove location</source>
<translation>Ta bort plats</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="320"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="323"/>
<source>View image</source>
<translation>Visa bild</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="324"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="328"/>
<source>Remove image</source>
<translation>Ta bort bild</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="455"/>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="472"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="452"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="469"/>
<source>Tweet sent successfully</source>
<translation>Tweet framgångsrikt skickad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="456"/>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="473"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="453"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="470"/>
<source>Reply sent successfully</source>
<translation>Svar framgångsrikt skickat</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="457"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="454"/>
<source>Direct message sent successfully</source>
<translation>Direktmeddelande framgångsrikt skickat</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="458"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="455"/>
<source>Retweet sent successfully</source>
<translation>Retweet framgångsrikt skickad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="484"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="481"/>
<source>Your tweet is more than 140 characters. Do you want to use TwitLonger to post your tweet?
Note: The tweet content will be publicly visible even if your tweet is private.</source>
<translation>Din tweet är mer än 140 tecken. Vill du använda TwitLonger för att skicka din tweet?⏎ Notera: Tweet-innehållet kommer att bli publikt även om din tweet är privat.</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/NewTweetPage.qml" line="487"/>
<location filename="../qml/tweetian-symbian/NewTweetPage.qml" line="483"/>
<source>Use TwitLonger?</source>
<translation>Använd TwitLonger?</translation>
</message>
</context>
<context>
<name>OpenLinkDialog</name>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/OpenLinkDialog.qml" line="49"/>
<location filename="../qml/tweetian-symbian/Dialog/OpenLinkDialog.qml" line="50"/>
<source>Open link in web browser</source>
<translation>Öppna länk i webbläsare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/OpenLinkDialog.qml" line="52"/>
<location filename="../qml/tweetian-symbian/Dialog/OpenLinkDialog.qml" line="54"/>
<source>Launching web browser...</source>
<translation>Startar webbläsare...</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/OpenLinkDialog.qml" line="56"/>
<source>Share link</source>
<translation>Dela länk</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/OpenLinkDialog.qml" line="61"/>
<location filename="../qml/tweetian-symbian/Dialog/OpenLinkDialog.qml" line="59"/>
<source>Copy link</source>
<translation>Kopiera länk</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/OpenLinkDialog.qml" line="64"/>
<location filename="../qml/tweetian-symbian/Dialog/OpenLinkDialog.qml" line="63"/>
<source>Link copied to clipboard</source>
<translation>Länk kopiera till urklipp</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/OpenLinkDialog.qml" line="71"/>
<location filename="../qml/tweetian-symbian/Dialog/OpenLinkDialog.qml" line="69"/>
<source>Send to Pocket</source>
<translation>Skicka till Pocket</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/OpenLinkDialog.qml" line="77"/>
<location filename="../qml/tweetian-symbian/Dialog/OpenLinkDialog.qml" line="75"/>
<source>Send to Instapaper</source>
<translation>Skicka till Instapaper</translation>
</message>
</context>
<context>
<name>PullToRefreshHeader</name>
<message>
<location filename="../qml/tweetian-harmattan/Component/PullToRefreshHeader.qml" line="54"/>
<location filename="../qml/tweetian-symbian/Component/PullToRefreshHeader.qml" line="54"/>
<source>Release to refresh</source>
<translation>Släpp för att uppdatera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Component/PullToRefreshHeader.qml" line="54"/>
<location filename="../qml/tweetian-symbian/Component/PullToRefreshHeader.qml" line="54"/>
<source>Pull down to refresh</source>
<translation>Dra ner för att uppdatera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Component/PullToRefreshHeader.qml" line="63"/>
<location filename="../qml/tweetian-symbian/Component/PullToRefreshHeader.qml" line="63"/>
<source>Last update: %1</source>
<translation>Senaste uppdatering: %1</translation>
</message>
</context>
<context>
<name>QSplashScreen</name>
<message>
<location filename="../main.cpp" line="81"/>
<source>Loading...</source>
<translation>Laddar...</translation>
</message>
</context>
<context>
<name>SearchPage</name>
<message>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="159"/>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="171"/>
<source>The search %1 is saved successfully</source>
<translation>Sökningen %1 framgångsrikt sparad </translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="177"/>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="189"/>
<source>The saved search %1 is removed successfully</source>
<translation>Den sparade sökningen %1 framgångsrikt raderad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="198"/>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="211"/>
<source>Do you want to save the search %1?</source>
<translation>Vill du spara sökningen %1?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="206"/>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="221"/>
<source>Do you want to remove the saved search %1?</source>
<translation>Vill du radera den sparade sökningen %1?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="155"/>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="187"/>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="167"/>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="199"/>
<source>Saved Searches</source>
<translation>Sparade sökningar</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="100"/>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="103"/>
<source>Search for tweets or users</source>
<translation>Sök efter tweets eller användare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="105"/>
<source>Search</source>
<translation>Sök</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="199"/>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="212"/>
<source>Save Search</source>
<translation>Spara sökning</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SearchPage.qml" line="207"/>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="222"/>
<source>Remove Saved Search</source>
<translation>Radera sparad sökning</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="41"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="46"/>
<source>Remove saved search</source>
<translation>Radera sparad sökning</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/SearchPage.qml" line="46"/>
<source>Add to saved search</source>
<translation>Lägg till som sparad sökning</translation>
</message>
</context>
<context>
<name>SelectImagePage</name>
<message>
<location filename="../qml/tweetian-harmattan/SelectImagePage.qml" line="35"/>
<location filename="../qml/tweetian-symbian/SelectImagePage.qml" line="36"/>
<source>Service</source>
<translation>Tjänst</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SelectImagePage.qml" line="49"/>
<location filename="../qml/tweetian-symbian/SelectImagePage.qml" line="52"/>
<source>Select image</source>
<translation>Välj bild</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SelectImagePage.qml" line="57"/>
<location filename="../qml/tweetian-symbian/SelectImagePage.qml" line="61"/>
<source>Preview</source>
<translation>Förhandsgranska</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SelectImagePage.qml" line="76"/>
<location filename="../qml/tweetian-symbian/SelectImagePage.qml" line="81"/>
<source>No image</source>
<translation>Ingen bild</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SelectImagePage.qml" line="84"/>
<location filename="../qml/tweetian-symbian/SelectImagePage.qml" line="92"/>
<source>Select Image</source>
<translation>Välj bild</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SelectImagePage.qml" line="102"/>
<location filename="../qml/tweetian-symbian/SelectImagePage.qml" line="113"/>
<source>Error loading image from gallery</source>
<translation>Fel vid laddning av bild från galleri</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SelectImagePage.qml" line="181"/>
<location filename="../qml/tweetian-symbian/SelectImagePage.qml" line="193"/>
<source>Image Upload Service</source>
<translation>Bilduppladdningstjänst</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/SelectImagePage.qml" line="31"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
</context>
<context>
<name>SettingGeneralTab</name>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="40"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="40"/>
<source>Theme</source>
<translation>Tema</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="51"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="52"/>
<source>Dark</source>
<translation>Mörkt</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="57"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="59"/>
<source>Light</source>
<translation>Ljust</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="66"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="68"/>
<source>Font size</source>
<translation>Teckenstorlek</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="77"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="80"/>
<source>Small</source>
<translation>Liten</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="83"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="87"/>
<source>Large</source>
<translation>Stor</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="89"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="93"/>
<source>Include #hashtags in reply</source>
<translation>Inkludera #hashtaggar i svar</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="96"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="100"/>
<source>Enable TwitLonger</source>
<translation>Aktivera TwitLonger</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="99"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="104"/>
<source>About TwitLonger</source>
<translation>Om TwitLonger</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="103"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="107"/>
<source>Translation</source>
<translation>Översättning</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="117"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingGeneralTab.qml" line="198"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="121"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingGeneralTab.qml" line="204"/>
<source>Translate to</source>
<translation>Översätt till</translation>
</message>
</context>
<context>
<name>SettingPage</name>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="43"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="48"/>
<source>Clear cache & database</source>
<translation>Rensa cache & databas</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="47"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="53"/>
<source>Clear thumbnails cache</source>
<translation>Rensa tumnagelcache</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="68"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="73"/>
<source>General</source>
<translation>Allmänt</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="69"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="74"/>
<source>Update</source>
<translation>Uppdatera</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="70"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="75"/>
<source>Account</source>
<translation>Konto</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="71"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="76"/>
<source>Mute</source>
<translation>Tysta</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="77"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="82"/>
<source>TwitLonger is a third-party service that allows you to post tweets longer than 140 characters.<br>More info about TwitLonger:<br><a href="http://www.twitlonger.com/about">www.twitlonger.com/about</a><br>By enabling this service, you agree to the TwitLonger privacy policy:<br><a href="http://www.twitlonger.com/privacy">www.twitlonger.com/privacy</a></source>
<translation>TwitLonger är en tredjepartstjänst som tillåter dig att skicka tweets som är längre än 140 tecken.<br>Mer info om TwitLonger:<br><a href="http://www.twitlonger.com/about">www.twitlonger.com/about</a><br>Genom att aktivera den här tjänsten godkänner du TwitLongers sekretesspolicy:<br><a href="http://www.twitlonger.com/privacy">www.twitlonger.com/privacy</a></translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="84"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="89"/>
<source>Pocket is a third-party service for saving web page links so you can read them later.<br>More about Pocket:<br><a href="http://getpocket.com/about">http://getpocket.com/about</a><br>By signing in, you agree to Pocket privacy policy:<br><a href="http://getpocket.com/privacy">http://getpocket.com/privacy</a></source>
<translation>Pocket är en tredjepartstjänst för att spara webbsidelänkar så att du kan läsa dem senare.<br>Mer info om Pocket:<br><a href="http://getpocket.com/about">http://getpocket.com/about</a><br>Genom att logga in godkänner du Pockets sekretesspolicy:<br><a href="http://getpocket.com/privacy">http://getpocket.com/privacy</a></translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="101"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="106"/>
<source>Streaming enables Tweetian to deliver real-time updates of timeline, mentions and direct messages without the needs of refreshing periodically. Auto refresh and manual refresh will be disabled when streaming is connected. It is not recommended to enable streaming when you are on a weak internet connection (eg. mobile data).</source>
<translation>Strömning möjliggör för Tweetian att leverera uppdateringar av tidslinjen, omnämnanden och direktmeddelanden i realtid utan att behöva göra regelbundna uppdateringar. Automatisk och manuell uppdatering inaktiveras när strömning är ansluten. Det rekommenderas inte att aktivera strömning när du använder en vek internetuppkoppling (t.ex. mobildata).</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="111"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="118"/>
<source>This action will clear the temporary cache and database. Twitter credential and app settings will not be reset. Continue?</source>
<translation>Denna åtgärd kommer att rensa den temporära cachen och databasen. Twitter-inloggningsuppgifter och programinställningar nollställs inte. Fortsätta?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="119"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="126"/>
<source>Cache and database cleared</source>
<translation>Cache och databas rensad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="127"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="136"/>
<source>%1 thumbnails deleted</source>
<translation>%1 tumnagelbilder raderade</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="91"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="96"/>
<source>More about Instapaper:<br><a href="http://www.instapaper.com/">http://www.instapaper.com/</a><br>By signing in, you agree to Instapaper privacy policy:<br><a href="http://www.instapaper.com/privacy-policy">http://www.instapaper.com/privacy-policy</a></source>
<translation>Mer information om Instapaper:<br><a href="http://www.instapaper.com/">http://www.instapaper.com/</a><br>Genom att logga in accepterar du Instapapers sekretesspolicy:<br><a href="http://www.instapaper.com/privacy-policy">http://www.instapaper.com/privacy-policy</a></translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="96"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="101"/>
<source>Mute allow you to mute tweets from your timeline with some specific keywords. Separate the keywords by space to mute tweet when ALL of the keywords are matched or separate by newline to mute tweet when ANY of the keywords are matched.
Keywords format: @user, #hashtag, source:Tweet_Button or plain words.</source>
<translation>Tysta (mute) tillåter dig att tysta tweets från din tidslinje med vissa specifika nyckelord. Separera nyckelorden med mellanslag för att tysta tweets där ALLA nyckelorden matchas eller separera dem med radbrytning för att tysta tweets där NÅGOT av nyckelorden matchas.⏎ Nyckelordsformat: @användare, #hashtagg, source:Tweet_Button eller ren text.</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="113"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="120"/>
<source>Clear Cache & Database</source>
<translation>Rensa cache & databas</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="124"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="133"/>
<source>Delete all cached thumbnails?</source>
<translation>Radera alla cachade tumnagelbilder?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingPage.qml" line="125"/>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="134"/>
<source>Clear Thumbnails Cache</source>
<translation>Rensa tumnagelcache</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="32"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/SettingPage.qml" line="37"/>
<source>Menu</source>
<translation>Meny</translation>
</message>
</context>
<context>
<name>SettingRefreshTab</name>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="35"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="43"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="35"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="43"/>
<source>Streaming</source>
<translation>Strömning</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="39"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="39"/>
<source>Enable streaming</source>
<translation>Aktivera strömning</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="46"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="46"/>
<source>Auto Refresh Frequency</source>
<translation>Autouppdateringsfrekvens</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="50"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="50"/>
<source>Timeline</source>
<translation>Tidslinje</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="51"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="61"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="71"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="51"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="61"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="71"/>
<source>Off</source>
<translation>Av</translation>
</message>
<message numerus="yes">
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="51"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="61"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="71"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="51"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="61"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="71"/>
<source>%n min(s)</source>
<translation><numerusform>%n min</numerusform><numerusform>%n min</numerusform></translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="51"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="61"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="71"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="51"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="61"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="71"/>
<source>Disabled</source>
<translation>Inaktiverad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="60"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="81"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="60"/>
<source>Mentions</source>
<translation>Omnämnanden</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="70"/>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="87"/>
<location filename="../qml/tweetian-symbian/SettingsPageCom/SettingRefreshTab.qml" line="70"/>
<source>Direct messages</source>
<translation>Direktmeddelanden</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SettingsPageCom/SettingRefreshTab.qml" line="78"/>
<source>Notifications</source>
<translation>Aviseringar</translation>
</message>
</context>
<context>
<name>SignInDialog</name>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/SignInDialog.qml" line="29"/>
<location filename="../qml/tweetian-harmattan/Dialog/SignInDialog.qml" line="63"/>
<location filename="../qml/tweetian-symbian/Dialog/SignInDialog.qml" line="30"/>
<source>Sign In</source>
<translation>Logga in</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/SignInDialog.qml" line="29"/>
<location filename="../qml/tweetian-symbian/Dialog/SignInDialog.qml" line="30"/>
<source>Cancel</source>
<translation>Avbryt</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/SignInDialog.qml" line="44"/>
<location filename="../qml/tweetian-symbian/Dialog/SignInDialog.qml" line="51"/>
<source>Username</source>
<translation>Användarnamn</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/SignInDialog.qml" line="49"/>
<source>Next</source>
<translation>Nästa</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/SignInDialog.qml" line="57"/>
<location filename="../qml/tweetian-symbian/Dialog/SignInDialog.qml" line="59"/>
<source>Password</source>
<translation>Lösenord</translation>
</message>
</context>
<context>
<name>SignInPage</name>
<message>
<location filename="../qml/tweetian-harmattan/SignInPage.qml" line="79"/>
<location filename="../qml/tweetian-symbian/SignInPage.qml" line="81"/>
<source>Sign In to Twitter</source>
<translation>Logga in på Twitter</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SignInPage.qml" line="96"/>
<location filename="../qml/tweetian-symbian/SignInPage.qml" line="98"/>
<source>Signed in successfully</source>
<translation>Inloggningen lyckades</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SignInPage.qml" line="103"/>
<location filename="../qml/tweetian-symbian/SignInPage.qml" line="105"/>
<source>Server or connection error. Click the refresh button to try again.</source>
<translation>Server- eller anslutningsfel. Klicka på Uppdatera-knappen och försök igen.</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/SignInPage.qml" line="105"/>
<location filename="../qml/tweetian-symbian/SignInPage.qml" line="107"/>
<source>Error: %1. Make sure the time/date of your phone is set correctly.</source>
<translation>Fel: %1. Försäkra dig om att din telefon har korrekt tid/datum inställt.</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/SignInPage.qml" line="34"/>
<source>Exit</source>
<translation>Avsluta</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/SignInPage.qml" line="39"/>
<source>Refresh</source>
<translation>Uppdatera</translation>
</message>
</context>
<context>
<name>StreamingHeader</name>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/StreamingHeader.qml" line="42"/>
<location filename="../qml/tweetian-symbian/MainPageCom/StreamingHeader.qml" line="42"/>
<source>Streaming...</source>
<translation>Strömmar...</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/StreamingHeader.qml" line="42"/>
<location filename="../qml/tweetian-symbian/MainPageCom/StreamingHeader.qml" line="42"/>
<source>Connecting to streaming</source>
<translation>Ansluter till strömning</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/MainPageCom/StreamingHeader.qml" line="43"/>
<location filename="../qml/tweetian-symbian/MainPageCom/StreamingHeader.qml" line="43"/>
<source>Offline</source>
<translation>Offline</translation>
</message>
</context>
<context>
<name>SuggestedUserPage</name>
<message>
<location filename="../qml/tweetian-harmattan/SuggestedUserPage.qml" line="52"/>
<location filename="../qml/tweetian-symbian/SuggestedUserPage.qml" line="53"/>
<source>Suggested Users</source>
<translation>Föreslagna användare</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/SuggestedUserPage.qml" line="36"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
</context>
<context>
<name>TextPage</name>
<message>
<location filename="../qml/tweetian-symbian/TextPage.qml" line="33"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
</context>
<context>
<name>TrendsLocationDialog</name>
<message>
<location filename="../qml/tweetian-harmattan/Dialog/TrendsLocationDialog.qml" line="27"/>
<location filename="../qml/tweetian-symbian/Dialog/TrendsLocationDialog.qml" line="28"/>
<source>Trends Location</source>
<translation>Plats för trender</translation>
</message>
</context>
<context>
<name>TrendsPage</name>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="59"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="64"/>
<source>Advanced search</source>
<translation>Avancerad sökning</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="63"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="69"/>
<source>Change trends location</source>
<translation>Ändra plats för trender</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="104"/>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="248"/>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="257"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="110"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="246"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="255"/>
<source>Saved Searches</source>
<translation>Sparade sökningar</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="136"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="145"/>
<source>Search for tweets or users</source>
<translation>Sök efter tweets eller användare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="183"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="183"/>
<source>Trends & Search</source>
<translation>Trender & Sök</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="228"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="226"/>
<source>Trends (%1)</source>
<translation>Trender (%1)</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="239"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="237"/>
<source>Unable to retrieve trends</source>
<translation>Kan inte hämta trender</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="239"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="237"/>
<source>Trends</source>
<translation>Trender</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="257"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="255"/>
<source>Unabled to retrieve saved search</source>
<translation>Kan inte hämta sparade sökningar</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="262"/>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="260"/>
<source>Worldwide</source>
<translation>Globalt</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="38"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TrendsPage.qml" line="140"/>
<source>Search</source>
<translation>Sök</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="43"/>
<source>Nearby tweets</source>
<translation>Närbelägna tweets</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="48"/>
<source>Suggested Users</source>
<translation>Föreslagna användare</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TrendsPage.qml" line="53"/>
<source>Menu</source>
<translation>Meny</translation>
</message>
</context>
<context>
<name>TweetDelegate</name>
<message>
<location filename="../qml/tweetian-harmattan/Delegate/TweetDelegate.qml" line="97"/>
<location filename="../qml/tweetian-symbian/Delegate/TweetDelegate.qml" line="94"/>
<source>Retweeted by %1</source>
<translation>Retweetad av %1</translation>
</message>
</context>
<context>
<name>TweetImage</name>
<message>
<location filename="../qml/tweetian-harmattan/TweetImage.qml" line="53"/>
<location filename="../qml/tweetian-symbian/TweetImage.qml" line="57"/>
<source>Image saved in %1</source>
<translation>Bild sparad i %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetImage.qml" line="54"/>
<location filename="../qml/tweetian-symbian/TweetImage.qml" line="58"/>
<source>Failed to save image</source>
<translation>Misslyckades med att spara bild</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetImage.qml" line="188"/>
<location filename="../qml/tweetian-symbian/TweetImage.qml" line="192"/>
<source>Loading image...%1</source>
<translation>Laddar bild...%1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetImage.qml" line="199"/>
<location filename="../qml/tweetian-symbian/TweetImage.qml" line="202"/>
<source>Error loading image</source>
<translation>Fel vid laddning av bild</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetImage.qml" line="32"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetImage.qml" line="38"/>
<source>Reset Zoom</source>
<translation>Återställ zoom</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetImage.qml" line="48"/>
<source>Open Link</source>
<translation>Öppna länk</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetImage.qml" line="53"/>
<source>Save Image</source>
<translation>Spara bild</translation>
</message>
</context>
<context>
<name>TweetListView</name>
<message numerus="yes">
<location filename="../qml/tweetian-harmattan/MainPageCom/TweetListView.qml" line="226"/>
<location filename="../qml/tweetian-symbian/MainPageCom/TweetListView.qml" line="221"/>
<source>%n new mention(s)</source>
<translation><numerusform>%n nytt omnämnande</numerusform><numerusform>%n nya omnämnanden</numerusform></translation>
</message>
</context>
<context>
<name>TweetPage</name>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="95"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="105"/>
<source>Copy tweet</source>
<translation>Kopiera tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="98"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="109"/>
<source>Tweet copied to clipboard</source>
<translation>Tweet kopierad till urklipp</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="102"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="113"/>
<source>Hide translated tweet</source>
<translation>Dölj översatt tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="102"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="113"/>
<source>Translate tweet</source>
<translation>Översätt tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="117"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="129"/>
<source>Tweet permalink</source>
<translation>Permalänk till tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="126"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="137"/>
<source>Delete tweet</source>
<translation>Radera tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="214"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="237"/>
<source>Retweeted by %1</source>
<translation>Retweetad av %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="278"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="300"/>
<source>Error opening link: %1</source>
<translation>Fel vid öppning av länk: %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="280"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="302"/>
<source>Streaming link is not available</source>
<translation>Strömningslänk inte tillgänglig</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="362"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="385"/>
<source>Tweet</source>
<translation>Tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="383"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="406"/>
<source>In-reply-to</source>
<translation>Som svar till</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="389"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="412"/>
<source>Reply</source>
<translation>Svara</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPage.qml" line="402"/>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="425"/>
<source>Translated Tweet</source>
<translation>Översatt tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="63"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="68"/>
<source>Reply All</source>
<translation>Svara alla</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="76"/>
<source>Retweet</source>
<translation>Retweeta</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="85"/>
<source>Unfavourite</source>
<translation>Radera favoritmarkering</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="85"/>
<source>Favourite</source>
<translation>Favoritmarkera</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/TweetPage.qml" line="94"/>
<source>Menu</source>
<translation>Meny</translation>
</message>
</context>
<context>
<name>TweetPageJS</name>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="301"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="301"/>
<source>Tweet deleted successfully</source>
<translation>Tweet framgångsrikt raderad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="309"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="309"/>
<source>Tweet favourited succesfully</source>
<translation>Tweet framgångrikt favoritmarkerad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="310"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="310"/>
<source>Tweet unfavourited successfully</source>
<translation>Favoritmarkering av tweet framgångsrikt raderad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="327"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="327"/>
<source>Unable to translate tweet</source>
<translation>Kan inte översätta tweet</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="346"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="346"/>
<source>Pocket - Not Signed In</source>
<translation>Pocket - Inte inloggad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="364"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="364"/>
<source>You are not sign in to your Instapaper account. Please sign in to your Instapaper account first under the "Account" tab in the Settings.</source>
<translation>Du är inte inloggad på ditt Instapaper-konto. Vänligen logga först in på ditt Instapaper-konto under "Konto"-fliken i Inställningar.</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="365"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="365"/>
<source>Instapaper - Not Signed In</source>
<translation>Instapaper - Inte inloggad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="354"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="354"/>
<source>The link has been sent to Pocket successfully</source>
<translation>Länk framgångsrikt skickad till Pocket</translation>
</message>
<message numerus="yes">
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="211"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="211"/>
<source>%n retweet(s)</source>
<translation><numerusform>%n retweet</numerusform><numerusform>%n retweets</numerusform></translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="212"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="212"/>
<source>Retweeters</source>
<translation>Retweetare</translation>
</message>
<message numerus="yes">
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="220"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="220"/>
<source>%n favourite(s)</source>
<translation><numerusform>%n favoritmarkering</numerusform><numerusform>%n favoritmarkeringar</numerusform></translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="221"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="221"/>
<source>Favouriters</source>
<translation>Favoritmarkerare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="329"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="329"/>
<source>Translation limit reached</source>
<translation>Översättningsgräns uppnådd</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="345"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="345"/>
<source>You are not signed in to your Pocket account. Please sign in to your Pocket account first under the "Account" tab in Settings.</source>
<translation>Du är inte inloggad på ditt Pocket-konto. Vänligen logga först in på ditt Pocket-konto under "Konto"-fliken i Inställningar.</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="357"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="357"/>
<source>Error sending link to Pocket (%1)</source>
<translation>Fel vid sändning av länk till Pocket (%1)</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="373"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="373"/>
<source>The link has been sent to Instapaper successfully</source>
<translation>Länk framgångsrikt skickad till Instapaper</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="376"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="376"/>
<source>Error sending link to Instapaper (%1)</source>
<translation>Fel vid sändning av länk till Instapaper (%1)</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="382"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="383"/>
<source>Do you want to delete this tweet?</source>
<translation>Vill du radera denna tweet?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/TweetPageJS.js" line="383"/>
<location filename="../qml/tweetian-symbian/TweetPageJS.js" line="384"/>
<source>Delete Tweet</source>
<translation>Radera tweet</translation>
</message>
</context>
<context>
<name>TweetSearchColumn</name>
<message>
<location filename="../qml/tweetian-harmattan/SearchPageCom/TweetSearchColumn.qml" line="84"/>
<location filename="../qml/tweetian-symbian/SearchPageCom/TweetSearchColumn.qml" line="84"/>
<source>No search result</source>
<translation>Inga sökresultat</translation>
</message>
</context>
<context>
<name>UserCategoryPage</name>
<message>
<location filename="../qml/tweetian-harmattan/UserCategoryPage.qml" line="49"/>
<location filename="../qml/tweetian-symbian/UserCategoryPage.qml" line="49"/>
<source>Suggested User Categories</source>
<translation>Kategorier med föreslagna användare</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/UserCategoryPage.qml" line="32"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
</context>
<context>
<name>UserDelegate</name>
<message>
<location filename="../qml/tweetian-harmattan/Delegate/UserDelegate.qml" line="80"/>
<location filename="../qml/tweetian-symbian/Delegate/UserDelegate.qml" line="80"/>
<source>%1 following | %2 followers</source>
<translation>%1 följer | %2 följare</translation>
</message>
</context>
<context>
<name>UserFavouritesPage</name>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserFavouritesPage.qml" line="27"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserFavouritesPage.qml" line="27"/>
<source>Favourites</source>
<translation>Favoriter</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserFavouritesPage.qml" line="29"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserFavouritesPage.qml" line="29"/>
<source>No favourite</source>
<translation>Inga favoriter</translation>
</message>
</context>
<context>
<name>UserFollowersPage</name>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserFollowersPage.qml" line="34"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserFollowersPage.qml" line="34"/>
<source>Followers</source>
<translation>Följare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserFollowersPage.qml" line="36"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserFollowersPage.qml" line="36"/>
<source>No follower</source>
<translation>Inga följare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserFollowersPage.qml" line="62"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserFollowersPage.qml" line="62"/>
<source>Error: No user to load?!</source>
<translation>Fel: Ingen användare att ladda?!</translation>
</message>
</context>
<context>
<name>UserFollowingPage</name>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserFollowingPage.qml" line="34"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserFollowingPage.qml" line="34"/>
<source>Following</source>
<translation>Följer</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserFollowingPage.qml" line="36"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserFollowingPage.qml" line="36"/>
<source>No following</source>
<translation>Följer inga</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserFollowingPage.qml" line="62"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserFollowingPage.qml" line="62"/>
<source>Error: No user to load?!</source>
<translation>Fel: Ingen användare att ladda?!</translation>
</message>
</context>
<context>
<name>UserListedPage</name>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserListedPage.qml" line="29"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserListedPage.qml" line="29"/>
<source>Listed</source>
<translation>Listad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserListedPage.qml" line="31"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserListedPage.qml" line="31"/>
<source>No list</source>
<translation>Inga listor</translation>
</message>
</context>
<context>
<name>UserPage</name>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="76"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="98"/>
<source>Unfollow %1</source>
<translation>Sluta följa %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="77"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="99"/>
<source>Follow %1</source>
<translation>Följ %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="82"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="105"/>
<source>Report user as spammer</source>
<translation>Rapportera användare som spammare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="282"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="308"/>
<source>Website</source>
<translation>Webbplats</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="283"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="309"/>
<source>Location</source>
<translation>Plats</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="284"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="310"/>
<source>Joined</source>
<translation>Gick med</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="285"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="311"/>
<source>Tweets</source>
<translation>Tweets</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="288"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="314"/>
<source>Following</source>
<translation>Följer</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="290"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="316"/>
<source>Followers</source>
<translation>Följare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="292"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="318"/>
<source>Favourites</source>
<translation>Favoriter</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="294"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="320"/>
<source>Subscribed List</source>
<translation>Listprenumerationer</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="296"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="322"/>
<source>Listed</source>
<translation>Listad i</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="310"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="336"/>
<source>The user %1 does not exist</source>
<translation>Användaren %1 existerar inte</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="317"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="343"/>
<source>Followed the user %1 successfully</source>
<translation>Följer framgångsrikt användaren %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="318"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="344"/>
<source>Unfollowed the user %1 successfully</source>
<translation>Slutade framgångsrikt följa användaren %1</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="328"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="354"/>
<source>Reported and blocked the user %1 successfully</source>
<translation>Användaren %1 framgångsrikt rapporterad och blockerad</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="338"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="364"/>
<source>Do you want to report and block the user %1?</source>
<translation>Vill du rapportera och blockera användaren %1?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="347"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="373"/>
<source>Do you want to unfollow the user %1?</source>
<translation>Vill du sluta följa användaren %1?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="348"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="374"/>
<source>Do you want to follow the user %1?</source>
<translation>Vill du följa användaren %1?</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="339"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="365"/>
<source>Report Spammer</source>
<translation>Rapporta spammare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="346"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="372"/>
<source>Unfollow user</source>
<translation>Sluta följa användare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPage.qml" line="346"/>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="372"/>
<source>Follow user</source>
<translation>Följ användare</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="64"/>
<source>Back</source>
<translation>Tillbaka</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="70"/>
<source>Mentions</source>
<translation>Omnämnanden</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="76"/>
<source>Direct Messages</source>
<translation>Direktmeddelanden</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="82"/>
<source>Refresh</source>
<translation>Uppdatera</translation>
</message>
<message>
<location filename="../qml/tweetian-symbian/UserPage.qml" line="87"/>
<source>Menu</source>
<translation>Meny</translation>
</message>
</context>
<context>
<name>UserSearchColumn</name>
<message>
<location filename="../qml/tweetian-harmattan/SearchPageCom/UserSearchColumn.qml" line="69"/>
<location filename="../qml/tweetian-symbian/SearchPageCom/UserSearchColumn.qml" line="69"/>
<source>No search result</source>
<translation>Inga sökresultat</translation>
</message>
</context>
<context>
<name>UserSubscribedListsPage</name>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserSubscribedListsPage.qml" line="27"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserSubscribedListsPage.qml" line="27"/>
<source>Subscribed Lists</source>
<translation>Listprenumerationer</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserSubscribedListsPage.qml" line="29"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserSubscribedListsPage.qml" line="29"/>
<source>No list</source>
<translation>Inga listor</translation>
</message>
</context>
<context>
<name>UserTweetsPage</name>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserTweetsPage.qml" line="27"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserTweetsPage.qml" line="27"/>
<source>Tweets</source>
<translation>Tweets</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/UserPageCom/UserTweetsPage.qml" line="29"/>
<location filename="../qml/tweetian-symbian/UserPageCom/UserTweetsPage.qml" line="29"/>
<source>No tweet</source>
<translation>Inga tweets</translation>
</message>
</context>
<context>
<name>main</name>
<message>
<location filename="../qml/tweetian-harmattan/main.qml" line="46"/>
<location filename="../qml/tweetian-symbian/main.qml" line="65"/>
<source>Server or connection error</source>
<translation>Server- eller anslutningsfel</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/main.qml" line="47"/>
<location filename="../qml/tweetian-symbian/main.qml" line="66"/>
<source>Rate limit reached, please try again later</source>
<translation>Frekvensgräns uppnådd, vänligen försök igen senare</translation>
</message>
<message>
<location filename="../qml/tweetian-harmattan/main.qml" line="48"/>
<location filename="../qml/tweetian-symbian/main.qml" line="67"/>
<source>Error: %1</source>
<translation>Fel: %1</translation>
</message>
</context>
</TS> | sailfishapps/Tweetian | i18n/tweetian_sv.ts | TypeScript | gpl-3.0 | 121,136 |
// Note: I had to change the name from [Aa]utocomplete to [Ss]elfcomplete
// in order to get this to work at the same time as JQuery-UI
/**
* Ajax Selfcomplete for jQuery, version 1.4.4
* (c) 2017 Tomas Kirda
*
* Ajax Selfcomplete for jQuery is freely distributable under the terms of an MIT-style license.
* For details, see the web site: https://github.com/devbridge/jQuery-Selfcomplete
*/
/*jslint browser: true, white: true, single: true, this: true, multivar: true */
/*global define, window, document, jQuery, exports, require */
// Expose plugin as an AMD module if AMD loader is present:
(function (factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object' && typeof require === 'function') {
// Browserify
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
'use strict';
var
utils = (function () {
return {
escapeRegExChars: function (value) {
return value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
},
createNode: function (containerClass) {
var div = document.createElement('div');
div.className = containerClass;
div.style.position = 'absolute';
div.style.display = 'none';
return div;
}
};
}()),
keys = {
ESC: 27,
TAB: 9,
RETURN: 13,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
},
noop = $.noop;
function Selfcomplete(el, options) {
var that = this;
// Shared variables:
that.element = el;
that.el = $(el);
that.suggestions = [];
that.badQueries = [];
that.selectedIndex = -1;
that.currentValue = that.element.value;
that.timeoutId = null;
that.cachedResponse = {};
that.onChangeTimeout = null;
that.onChange = null;
that.isLocal = false;
that.suggestionsContainer = null;
that.noSuggestionsContainer = null;
that.options = $.extend({}, Selfcomplete.defaults, options);
that.classes = {
selected: 'selfcomplete-selected',
suggestion: 'selfcomplete-suggestion'
};
that.hint = null;
that.hintValue = '';
that.selection = null;
// Initialize and set options:
that.initialize();
that.setOptions(options);
}
Selfcomplete.utils = utils;
$.Selfcomplete = Selfcomplete;
Selfcomplete.defaults = {
ajaxSettings: {},
autoSelectFirst: false,
appendTo: 'body',
serviceUrl: null,
lookup: null,
onSelect: null,
width: 'auto',
minChars: 1,
maxHeight: 300,
deferRequestBy: 0,
params: {},
formatResult: _formatResult,
formatGroup: _formatGroup,
delimiter: null,
zIndex: 9999,
type: 'GET',
noCache: false,
onSearchStart: noop,
onSearchComplete: noop,
onSearchError: noop,
preserveInput: false,
containerClass: 'selfcomplete-suggestions',
tabDisabled: false,
dataType: 'text',
currentRequest: null,
triggerSelectOnValidInput: true,
preventBadQueries: true,
lookupFilter: _lookupFilter,
paramName: 'query',
transformResult: _transformResult,
showNoSuggestionNotice: false,
noSuggestionNotice: 'No results',
orientation: 'bottom',
forceFixPosition: false
};
function _lookupFilter(suggestion, originalQuery, queryLowerCase) {
return suggestion.value.toLowerCase().startsWith(queryLowerCase) !== false;
};
function _transformResult(response) {
return typeof response === 'string' ? $.parseJSON(response) : response;
};
function _formatResult(suggestion, currentValue) {
// Do not replace anything if the current value is empty
if (!currentValue) {
return suggestion.value;
}
var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';
return suggestion.value
.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/<(\/?strong)>/g, '<$1>');
};
function _formatGroup(suggestion, category) {
return '<div class="selfcomplete-group">' + category + '</div>';
};
Selfcomplete.prototype = {
initialize: function () {
var that = this,
suggestionSelector = '.' + that.classes.suggestion,
selected = that.classes.selected,
options = that.options,
container;
// Remove selfcomplete attribute to prevent native suggestions:
that.element.setAttribute('selfcomplete', 'off');
// html() deals with many types: htmlString or Element or Array or jQuery
that.noSuggestionsContainer = $('<div class="selfcomplete-no-suggestion"></div>')
.html(this.options.noSuggestionNotice).get(0);
that.suggestionsContainer = Selfcomplete.utils.createNode(options.containerClass);
container = $(that.suggestionsContainer);
container.appendTo(options.appendTo || 'body');
// Only set width if it was provided:
if (options.width !== 'auto') {
container.css('width', options.width);
}
// Listen for mouse over event on suggestions list:
container.on('mouseover.selfcomplete', suggestionSelector, function () {
that.activate($(this).data('index'));
});
// Deselect active element when mouse leaves suggestions container:
container.on('mouseout.selfcomplete', function () {
that.selectedIndex = -1;
container.children('.' + selected).removeClass(selected);
});
// Listen for click event on suggestions list:
container.on('click.selfcomplete', suggestionSelector, function () {
that.select($(this).data('index'));
});
container.on('click.selfcomplete', function () {
clearTimeout(that.blurTimeoutId);
})
that.fixPositionCapture = function () {
if (that.visible) {
that.fixPosition();
}
};
$(window).on('resize.selfcomplete', that.fixPositionCapture);
that.el.on('keydown.selfcomplete', function (e) { that.onKeyPress(e); });
that.el.on('keyup.selfcomplete', function (e) { that.onKeyUp(e); });
that.el.on('blur.selfcomplete', function () { that.onBlur(); });
that.el.on('focus.selfcomplete', function () { that.onFocus(); });
that.el.on('change.selfcomplete', function (e) { that.onKeyUp(e); });
that.el.on('input.selfcomplete', function (e) { that.onKeyUp(e); });
},
onFocus: function () {
var that = this;
that.fixPosition();
if (that.el.val().length >= that.options.minChars) {
that.onValueChange();
}
},
onBlur: function () {
var that = this;
// If user clicked on a suggestion, hide() will
// be canceled, otherwise close suggestions
that.blurTimeoutId = setTimeout(function () {
that.hide();
}, 200);
},
abortAjax: function () {
var that = this;
if (that.currentRequest) {
that.currentRequest.abort();
that.currentRequest = null;
}
},
setOptions: function (suppliedOptions) {
var that = this,
options = $.extend({}, that.options, suppliedOptions);
that.isLocal = Array.isArray(options.lookup);
if (that.isLocal) {
options.lookup = that.verifySuggestionsFormat(options.lookup);
}
options.orientation = that.validateOrientation(options.orientation, 'bottom');
// Adjust height, width and z-index:
$(that.suggestionsContainer).css({
'max-height': options.maxHeight + 'px',
'width': options.width + 'px',
'z-index': options.zIndex
});
this.options = options;
},
clearCache: function () {
this.cachedResponse = {};
this.badQueries = [];
},
clear: function () {
this.clearCache();
this.currentValue = '';
this.suggestions = [];
},
disable: function () {
var that = this;
that.disabled = true;
clearTimeout(that.onChangeTimeout);
that.abortAjax();
},
enable: function () {
this.disabled = false;
},
fixPosition: function () {
// Use only when container has already its content
var that = this,
$container = $(that.suggestionsContainer),
containerParent = $container.parent().get(0);
// Fix position automatically when appended to body.
// In other cases force parameter must be given.
if (containerParent !== document.body && !that.options.forceFixPosition) {
return;
}
// Choose orientation
var orientation = that.options.orientation,
containerHeight = $container.outerHeight(),
height = that.el.outerHeight(),
offset = that.el.offset(),
styles = { 'top': offset.top, 'left': offset.left };
if (orientation === 'auto') {
var viewPortHeight = $(window).height(),
scrollTop = $(window).scrollTop(),
topOverflow = -scrollTop + offset.top - containerHeight,
bottomOverflow = scrollTop + viewPortHeight - (offset.top + height + containerHeight);
orientation = (Math.max(topOverflow, bottomOverflow) === topOverflow) ? 'top' : 'bottom';
}
if (orientation === 'top') {
styles.top += -containerHeight;
} else {
styles.top += height;
}
// If container is not positioned to body,
// correct its position using offset parent offset
if(containerParent !== document.body) {
var opacity = $container.css('opacity'),
parentOffsetDiff;
if (!that.visible){
$container.css('opacity', 0).show();
}
parentOffsetDiff = $container.offsetParent().offset();
styles.top -= parentOffsetDiff.top;
styles.left -= parentOffsetDiff.left;
if (!that.visible){
$container.css('opacity', opacity).hide();
}
}
if (that.options.width === 'auto') {
styles.width = that.el.outerWidth() + 'px';
}
$container.css(styles);
},
isCursorAtEnd: function () {
var that = this,
valLength = that.el.val().length,
selectionStart = that.element.selectionStart,
range;
if (typeof selectionStart === 'number') {
return selectionStart === valLength;
}
if (document.selection) {
range = document.selection.createRange();
range.moveStart('character', -valLength);
return valLength === range.text.length;
}
return true;
},
onKeyPress: function (e) {
var that = this;
// If suggestions are hidden and user presses arrow down, display suggestions:
if (!that.disabled && !that.visible && e.which === keys.DOWN && that.currentValue) {
that.suggest();
return;
}
if (that.disabled || !that.visible) {
return;
}
switch (e.which) {
case keys.ESC:
that.el.val(that.currentValue);
that.hide();
break;
case keys.RIGHT:
if (that.hint && that.options.onHint && that.isCursorAtEnd()) {
that.selectHint();
break;
}
return;
case keys.TAB:
if (that.hint && that.options.onHint) {
that.selectHint();
return;
}
if (that.selectedIndex === -1) {
that.hide();
return;
}
that.select(that.selectedIndex);
if (that.options.tabDisabled === false) {
return;
}
break;
case keys.RETURN:
if (that.selectedIndex === -1) {
that.hide();
return;
}
that.select(that.selectedIndex);
break;
case keys.UP:
that.moveUp();
break;
case keys.DOWN:
that.moveDown();
break;
default:
return;
}
// Cancel event if function did not return:
e.stopImmediatePropagation();
e.preventDefault();
},
onKeyUp: function (e) {
var that = this;
if (that.disabled) {
return;
}
switch (e.which) {
case keys.UP:
case keys.DOWN:
return;
}
clearTimeout(that.onChangeTimeout);
if (that.currentValue !== that.el.val()) {
that.findBestHint();
if (that.options.deferRequestBy > 0) {
// Defer lookup in case when value changes very quickly:
that.onChangeTimeout = setTimeout(function () {
that.onValueChange();
}, that.options.deferRequestBy);
} else {
that.onValueChange();
}
}
},
onValueChange: function () {
if (this.ignoreValueChange) {
this.ignoreValueChange = false;
return;
}
var that = this,
options = that.options,
value = that.el.val(),
query = that.getQuery(value);
if (that.selection && that.currentValue !== query) {
that.selection = null;
(options.onInvalidateSelection || $.noop).call(that.element);
}
clearTimeout(that.onChangeTimeout);
that.currentValue = value;
that.selectedIndex = -1;
// Check existing suggestion for the match before proceeding:
if (options.triggerSelectOnValidInput && that.isExactMatch(query)) {
that.select(0);
return;
}
if (query.length < options.minChars) {
that.hide();
} else {
that.getSuggestions(query);
}
},
isExactMatch: function (query) {
var suggestions = this.suggestions;
return (suggestions.length === 1 && suggestions[0].value.toLowerCase() === query.toLowerCase());
},
getQuery: function (value) {
var delimiter = this.options.delimiter,
parts;
if (!delimiter) {
return value;
}
parts = value.split(delimiter);
return $.trim(parts[parts.length - 1]);
},
getSuggestionsLocal: function (query) {
var that = this,
options = that.options,
queryLowerCase = query.toLowerCase(),
filter = options.lookupFilter,
limit = parseInt(options.lookupLimit, 10),
data;
data = {
suggestions: $.grep(options.lookup, function (suggestion) {
return filter(suggestion, query, queryLowerCase);
})
};
if (limit && data.suggestions.length > limit) {
data.suggestions = data.suggestions.slice(0, limit);
}
return data;
},
getSuggestions: function (q) {
var response,
that = this,
options = that.options,
serviceUrl = options.serviceUrl,
params,
cacheKey,
ajaxSettings;
options.params[options.paramName] = q;
if (options.onSearchStart.call(that.element, options.params) === false) {
return;
}
params = options.ignoreParams ? null : options.params;
if ($.isFunction(options.lookup)){
options.lookup(q, function (data) {
that.suggestions = data.suggestions;
that.suggest();
options.onSearchComplete.call(that.element, q, data.suggestions);
});
return;
}
if (that.isLocal) {
response = that.getSuggestionsLocal(q);
} else {
if ($.isFunction(serviceUrl)) {
serviceUrl = serviceUrl.call(that.element, q);
}
cacheKey = serviceUrl + '?' + $.param(params || {});
response = that.cachedResponse[cacheKey];
}
if (response && Array.isArray(response.suggestions)) {
that.suggestions = response.suggestions;
that.suggest();
options.onSearchComplete.call(that.element, q, response.suggestions);
} else if (!that.isBadQuery(q)) {
that.abortAjax();
ajaxSettings = {
url: serviceUrl,
data: params,
type: options.type,
dataType: options.dataType
};
$.extend(ajaxSettings, options.ajaxSettings);
that.currentRequest = $.ajax(ajaxSettings).done(function (data) {
var result;
that.currentRequest = null;
result = options.transformResult(data, q);
that.processResponse(result, q, cacheKey);
options.onSearchComplete.call(that.element, q, result.suggestions);
}).fail(function (jqXHR, textStatus, errorThrown) {
options.onSearchError.call(that.element, q, jqXHR, textStatus, errorThrown);
});
} else {
options.onSearchComplete.call(that.element, q, []);
}
},
isBadQuery: function (q) {
if (!this.options.preventBadQueries){
return false;
}
var badQueries = this.badQueries,
i = badQueries.length;
while (i--) {
if (q.indexOf(badQueries[i]) === 0) {
return true;
}
}
return false;
},
hide: function () {
var that = this,
container = $(that.suggestionsContainer);
if ($.isFunction(that.options.onHide) && that.visible) {
that.options.onHide.call(that.element, container);
}
that.visible = false;
that.selectedIndex = -1;
clearTimeout(that.onChangeTimeout);
$(that.suggestionsContainer).hide();
that.signalHint(null);
},
suggest: function () {
if (!this.suggestions.length) {
if (this.options.showNoSuggestionNotice) {
this.noSuggestions();
} else {
this.hide();
}
return;
}
var that = this,
options = that.options,
groupBy = options.groupBy,
formatResult = options.formatResult,
value = that.getQuery(that.currentValue),
className = that.classes.suggestion,
classSelected = that.classes.selected,
container = $(that.suggestionsContainer),
noSuggestionsContainer = $(that.noSuggestionsContainer),
beforeRender = options.beforeRender,
html = '',
category,
formatGroup = function (suggestion, index) {
var currentCategory = suggestion.data[groupBy];
if (category === currentCategory){
return '';
}
category = currentCategory;
return options.formatGroup(suggestion, category);
};
if (options.triggerSelectOnValidInput && that.isExactMatch(value)) {
that.select(0);
return;
}
// Build suggestions inner HTML:
$.each(that.suggestions, function (i, suggestion) {
if (groupBy){
html += formatGroup(suggestion, value, i);
}
html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value, i) + '</div>';
});
this.adjustContainerWidth();
noSuggestionsContainer.detach();
container.html(html);
if ($.isFunction(beforeRender)) {
beforeRender.call(that.element, container, that.suggestions);
}
that.fixPosition();
container.show();
// Select first value by default:
if (options.autoSelectFirst) {
that.selectedIndex = 0;
container.scrollTop(0);
container.children('.' + className).first().addClass(classSelected);
}
that.visible = true;
that.findBestHint();
},
noSuggestions: function() {
var that = this,
beforeRender = that.options.beforeRender,
container = $(that.suggestionsContainer),
noSuggestionsContainer = $(that.noSuggestionsContainer);
this.adjustContainerWidth();
// Some explicit steps. Be careful here as it easy to get
// noSuggestionsContainer removed from DOM if not detached properly.
noSuggestionsContainer.detach();
// clean suggestions if any
container.empty();
container.append(noSuggestionsContainer);
if ($.isFunction(beforeRender)) {
beforeRender.call(that.element, container, that.suggestions);
}
that.fixPosition();
container.show();
that.visible = true;
},
adjustContainerWidth: function() {
var that = this,
options = that.options,
width,
container = $(that.suggestionsContainer);
// If width is auto, adjust width before displaying suggestions,
// because if instance was created before input had width, it will be zero.
// Also it adjusts if input width has changed.
if (options.width === 'auto') {
width = that.el.outerWidth();
container.css('width', width > 0 ? width : 300);
} else if(options.width === 'flex') {
// Trust the source! Unset the width property so it will be the max length
// the containing elements.
container.css('width', '');
}
},
findBestHint: function () {
var that = this,
value = that.el.val().toLowerCase(),
bestMatch = null;
if (!value) {
return;
}
$.each(that.suggestions, function (i, suggestion) {
var foundMatch = suggestion.value.toLowerCase().indexOf(value) === 0;
if (foundMatch) {
bestMatch = suggestion;
}
return !foundMatch;
});
that.signalHint(bestMatch);
},
signalHint: function (suggestion) {
var hintValue = '',
that = this;
if (suggestion) {
hintValue = that.currentValue + suggestion.value.substr(that.currentValue.length);
}
if (that.hintValue !== hintValue) {
that.hintValue = hintValue;
that.hint = suggestion;
(this.options.onHint || $.noop)(hintValue);
}
},
verifySuggestionsFormat: function (suggestions) {
// If suggestions is string array, convert them to supported format:
if (suggestions.length && typeof suggestions[0] === 'string') {
return $.map(suggestions, function (value) {
return { value: value, data: null };
});
}
return suggestions;
},
validateOrientation: function(orientation, fallback) {
orientation = $.trim(orientation || '').toLowerCase();
if($.inArray(orientation, ['auto', 'bottom', 'top']) === -1){
orientation = fallback;
}
return orientation;
},
processResponse: function (result, originalQuery, cacheKey) {
var that = this,
options = that.options;
result.suggestions = that.verifySuggestionsFormat(result.suggestions);
// Cache results if cache is not disabled:
if (!options.noCache) {
that.cachedResponse[cacheKey] = result;
if (options.preventBadQueries && !result.suggestions.length) {
that.badQueries.push(originalQuery);
}
}
// Return if originalQuery is not matching current query:
if (originalQuery !== that.getQuery(that.currentValue)) {
return;
}
that.suggestions = result.suggestions;
that.suggest();
},
activate: function (index) {
var that = this,
activeItem,
selected = that.classes.selected,
container = $(that.suggestionsContainer),
children = container.find('.' + that.classes.suggestion);
container.find('.' + selected).removeClass(selected);
that.selectedIndex = index;
if (that.selectedIndex !== -1 && children.length > that.selectedIndex) {
activeItem = children.get(that.selectedIndex);
$(activeItem).addClass(selected);
return activeItem;
}
return null;
},
selectHint: function () {
var that = this,
i = $.inArray(that.hint, that.suggestions);
that.select(i);
},
select: function (i) {
var that = this;
that.hide();
that.onSelect(i);
},
moveUp: function () {
var that = this;
if (that.selectedIndex === -1) {
return;
}
if (that.selectedIndex === 0) {
$(that.suggestionsContainer).children().first().removeClass(that.classes.selected);
that.selectedIndex = -1;
that.ignoreValueChange = false;
that.el.val(that.currentValue);
that.findBestHint();
return;
}
that.adjustScroll(that.selectedIndex - 1);
},
moveDown: function () {
var that = this;
if (that.selectedIndex === (that.suggestions.length - 1)) {
return;
}
that.adjustScroll(that.selectedIndex + 1);
},
adjustScroll: function (index) {
var that = this,
activeItem = that.activate(index);
if (!activeItem) {
return;
}
var offsetTop,
upperBound,
lowerBound,
heightDelta = $(activeItem).outerHeight();
offsetTop = activeItem.offsetTop;
upperBound = $(that.suggestionsContainer).scrollTop();
lowerBound = upperBound + that.options.maxHeight - heightDelta;
if (offsetTop < upperBound) {
$(that.suggestionsContainer).scrollTop(offsetTop);
} else if (offsetTop > lowerBound) {
$(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta);
}
if (!that.options.preserveInput) {
// During onBlur event, browser will trigger "change" event,
// because value has changed, to avoid side effect ignore,
// that event, so that correct suggestion can be selected
// when clicking on suggestion with a mouse
that.ignoreValueChange = true;
that.el.val(that.getValue(that.suggestions[index].value));
}
that.signalHint(null);
},
onSelect: function (index) {
var that = this,
onSelectCallback = that.options.onSelect,
suggestion = that.suggestions[index];
that.currentValue = that.getValue(suggestion.value);
if (that.currentValue !== that.el.val() && !that.options.preserveInput) {
that.el.val(that.currentValue);
}
that.signalHint(null);
that.suggestions = [];
that.selection = suggestion;
if ($.isFunction(onSelectCallback)) {
onSelectCallback.call(that.element, suggestion);
}
},
getValue: function (value) {
var that = this,
delimiter = that.options.delimiter,
currentValue,
parts;
if (!delimiter) {
return value;
}
currentValue = that.currentValue;
parts = currentValue.split(delimiter);
if (parts.length === 1) {
return value;
}
return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
},
dispose: function () {
var that = this;
that.el.off('.selfcomplete').removeData('selfcomplete');
$(window).off('resize.selfcomplete', that.fixPositionCapture);
$(that.suggestionsContainer).remove();
}
};
// Create chainable jQuery plugin:
$.fn.devbridgeSelfcomplete = function (options, args) {
var dataKey = 'selfcomplete';
// If function invoked without argument return
// instance of the first matched element:
if (!arguments.length) {
return this.first().data(dataKey);
}
return this.each(function () {
var inputElement = $(this),
instance = inputElement.data(dataKey);
if (typeof options === 'string') {
if (instance && typeof instance[options] === 'function') {
instance[options](args);
}
} else {
// If instance already exists, destroy it:
if (instance && instance.dispose) {
instance.dispose();
}
instance = new Selfcomplete(this, options);
inputElement.data(dataKey, instance);
}
});
};
// Don't overwrite if it already exists
if (!$.fn.selfcomplete) {
$.fn.selfcomplete = $.fn.devbridgeSelfcomplete;
}
}));
| maryszmary/ud-annotatrix | standalone/lib/ext/jquery.autocomplete.js | JavaScript | gpl-3.0 | 33,367 |
// Doctor personal info edit section functions
$(function()
{
retrievePersonalInfo(); // Retrieves personal info
var passFields = $('#third_step input[type=password]');
passFields.each(function()
{ // Erases password values
$(this).val("");
});
////// First form //////
$('form').submit(function(){ return false; });
$('#submit_edit_first').click(function()
{
$('#submit_edit_first').removeClass('error').removeClass('valid'); // Removes submit error class and adds valid class
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // E-mail pattern will be used to check mail validity
var fields = $('#first_step input[type=text]');
var error = 0;
fields.each(function() // Loop passes through all text input fields of the first form
{
var value = $(this).val();
var phone = $('#phone').val();
var cellPhone = $('#cellPhone').val();
var value = $(this).val();
var field_id = $(this).attr('id');
if( field_id !='phone' && field_id !='cellPhone' && // If current input is NOT phone, cell phone or postcode
field_id !='postCode' && value=="" ) // and the input value is the same as the default value
{
apply_error_events(this,'formError5'); // Error classes messages and animations
error++; // (msg: Invalid value)
}
else if (value.length<3 &&value!= '') // If input is smaller than 3 characters
{
apply_error_events(this,'formError8'); // Error classes messages and animations
error++; // (msg: Enter value with more than 3 characters)
}
else if((field_id =='phone'|| field_id =='cellPhone') // If no phone number has inserted
&& phone=="" && cellPhone=="" )
{
apply_error_events(this,'formError10'); // Error classes messages and animations
error++; // (msg: Insert at least 1 phone number)
}
else if((value!="" && field_id =='postCode' && // Cases of non-numeric input where numeric
(isNaN( $('#postCode').val() ) ) ) || ( value!="" && // is required
field_id =='phone' && (isNaN( $('#phone').val()))) ||
( value!="" && field_id =='cellPhone' &&
(isNaN( $('#cellPhone').val() ) ) ) )
{
apply_error_events(this,'formError11'); // Error classes messages and animations
error++; // (msg: Invalid value)
}
else if( field_id =='email' && !emailPattern.test(value) ) // Checks e-mail validity
{
apply_error_events(this,'formError11'); // Error classes messages and animations
error++; // (msg: Invalid value)
}
else
{
$(this).addClass('valid'); // If none of the above occurs, adds class "valid"
$("label[for='"+field_id+"']").fadeTo('slow', 0); // Removes all error messages) if appeared before
}
});
if(!error) // If all inputs are valid
{
$('.error_p').fadeTo('fast', 0); // Remove error messages if exist
$('#form_msg1 h1').fadeTo('fast', 0); // Remove regular labels
$('#form_loading_p_doc').fadeTo('slow', 1); // Visualize waiting animation during the delay..
sendData(1); // Procceed to the data registration
}
});
////// Second form //////
$('#submit_edit_second').click(function()
{
$('#second_step input').removeClass('error').removeClass('valid'); // Removes submit error class and adds valid class
var fields = $('#second_step input[type=text]');
var error = 0;
if(!error) // If all inputs are valid
{
$('.error_p').fadeTo('fast', 0); // Remove error messages if exist
$('#form_msg2 h1').fadeTo('fast', 0); // Remove regular labels
$('#form_loading_p2_doc').fadeTo('slow', 1); // Visualize waiting animation during the delay..
sendData(2); // Procceed to the data registration
}
});
////// Third form //////
$('#submit_edit_third').click(function()
{
$('#third_step input').removeClass('error').removeClass('valid'); // Removes submit error class and adds valid class
//ckeck if inputs aren't empty
var fields = $('#third_step input[type=password]');
var error = 0;
fields.each(function()
{
var value = $(this).val();
var field_id = $(this).attr('id');
if( value=="" )
{
apply_error_events(this,'formError5'); // Error classes messages and animations
error++;
}
else if ( (field_id =='oldPassword' && value.length<5) ||
(field_id =='newPassword' && value.length<5) ||
(field_id =='passwordConf' && value.length<5) )
{
apply_error_events(this,'formError3'); // Error classes messages and animations
error++;
}
else if ($('#newPassword').val() != $('#passwordConf').val())
{
apply_error_events(this,'formError14'); // Error classes messages and animations
error++;
} else {
$(this).addClass('valid'); // If none of the above occurs, adds class "valid"
$("label[for='"+field_id+"']").fadeTo('slow', 0); // Removes all error messages) if appeared before
}
});
if(!error) // If all inputs are valid
{
$('.error_p').fadeTo('fast', 0); // Remove error messages if exist
$('#form_msg3 h1, #form_msg3 p').fadeTo('fast', 0); // Remove regular labels
$('#form_loading_p3_doc').fadeTo('slow', 1); // Visualize waiting animation during the delay..
sendData(3); // Procceed to the data registration
}
});
//////Switch buttons //////
$('.choice_buttons tr #communication_upd').click(function()
{
$('.content').animate({
height: 840
}, 800, function(){
$('#first_step').slideDown(); // Switches the form contents
$('#second_step').slideUp();
$('#third_step').slideUp();
}
);
});
$('.choice_buttons tr #biog_upd').click(function()
{
$('#first_step').slideUp();
$('#third_step').slideUp();
$('.content').animate({
height: 475
}, 800, function(){ // Switches the form contents
$('#first_step').slideUp();
$('#second_step').slideDown();
$('#third_step').slideUp();
}
);
});
$('.choice_buttons tr #password_upd').click(function()
{
$('.content').animate({
height: 535
}, 800, function(){ // Switches the form contents
$('#first_step').slideUp();
$('#second_step').slideUp();
$('#third_step').slideDown();
}
);
});
////// Retrieves patients data and puts them to the input fields //////
function retrievePersonalInfo()
{
$.ajax({
type: "POST",
url: "server_processes/doctor_functions/staff_data.php",
dataType: "json",
success: function(response)
{
$('#address').val(response.Address);
$('#city').val(response.City);
$('#postCode').val(response.Postal_code);
$('#phone').val(response.Home_phone);
$('#cellPhone').val(response.Mobile_phone);
$('#email').val(response.Email);
$('#biog').val(response.Resume);
}
});
}
////// Sends data to server //////
function sendData(step)
{
$.ajax({
type: "POST",
url: "server_processes/doctor_functions/edit_staff.php",
data:{
step: step,
address: $('#address').val(),
city: $('#city').val(),
postCode: $('#postCode').val(),
phone: $('#phone').val(),
cellPhone: $('#cellPhone').val(),
email: $('#email').val(),
biog: $('#biog').val(),
password: $('#newPassword').val(),
oldpass: $('#oldPassword').val()
},
success: function(response)
{
if(response == "EXPIRED") // If the server respons that session has expired
{
session_expired(); // Calls function to alert the user and logout
}
else if(response == "DONE") // If all data is succesfully inserted
{
if(step == 1) // If data is from the first form
{
$('#form_loading_p_doc').fadeTo('slow', 0); // Hide loading animation
$('h1.succ').html(langPack['editSuccess']).fadeTo('slow', 1); // Show success message
}
else if(step == 2) // If data is from the second form
{
$('#form_loading_p2_doc').fadeTo('slow', 0); // Hide loading animation
$('h1.succ2').html(langPack['editSuccess']).fadeTo('slow', 1); // Show success message
}
else if(step == 3) // If data is from the third form
{
$('#form_loading_p3_doc').fadeTo('slow', 0); // Hide loading animation
$('h1.succ3').html(langPack['editSuccess']).fadeTo('slow', 1); // Show success message
$('p.succ3').html(langPack['editSuccess']).fadeTo('slow', 1);
}
}
else if(response =="WRONG PASS") // If password is invalid
{
$('#form_loading_p3_doc').fadeTo('slow', 0); // Hide loading animation
$('#form_msg3 h1.error_p').html(langPack['wrongPass']).fadeTo('slow', 1); // Show error message
$('#form_msg3 p.error_p').html(langPack['wrongPass']).fadeTo('slow', 1);
}
else{ // Else (if something went wrong)
if(step == 1) // If data is from the first form
{
$('#form_loading_p_doc').fadeTo('slow', 0); // Hide loading animation
$('#form_msg1 h1.error_p').html(langPack['regFailed']).fadeTo('slow', 1); // Show error message
$('#form_msg1 p.error_p').html(langPack['regSubFaied']).fadeTo('slow', 1);
}
else if(step == 2) // If data is from the second form
{
$('#form_loading_p2_doc').fadeTo('slow', 0); // Hide loading animation
$('#form_msg2 h1.error_p').html(langPack['regFailed']).fadeTo('slow', 1); // Show error message
$('#form_msg2 p.error_p').html(langPack['regSubFaied']).fadeTo('slow', 1);
}
else if(step == 3) // If data is from the t form
{
$('#form_loading_p3_doc').fadeTo('slow', 0); // Hide loading animation
$('#form_msg3 h1.error_p').html(langPack['regFailed']).fadeTo('slow', 1); // Show error message
$('#form_msg3 p.error_p').html(langPack['regSubFaied']).fadeTo('slow', 1);
}
}
}
});
}
}); | labrosb/Hospital-Management-System | client_processes/doctor_functions/edit_staff_profile.js | JavaScript | gpl-3.0 | 10,568 |
/*
* Copyright © 2010 Martin Riedel
*
* This file is part of DirectLister.
*
* DirectLister 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.
*
* DirectLister 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 DirectLister. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sourceforge.directlister.model.filters;
import java.io.File;
/**
* TODO doc
*
* @author Martin Riedel
*
*/
public class FileNameContainsFilter implements Filter {
/*
* MEMBERS
*/
/**
* TODO doc
*/
private final String containedString;
/*
* CONSTRUCTORS
*/
/**
* TODO doc
*
*/
FileNameContainsFilter(final String containedString) {
this.containedString = containedString;
}
/*
* METHODS
*/
/**
* {@inheritDoc}
*/
@Override
public boolean apply(final File operand) {
return operand.getName().toLowerCase().contains(this.containedString.toLowerCase());
}
}
| mriedel/DirectLister | src/net/sourceforge/directlister/model/filters/FileNameContainsFilter.java | Java | gpl-3.0 | 1,375 |
#include "Arpschuino.h"
#include <avr/io.h>
#include <util/crc16.h>
#include <avr/eeprom.h>
#include <avr/sleep.h>
#if ARDUINO >= 100
#include <Arduino.h> // Arduino 1.0
#else
#include <WProgram.h> // Arduino 0022
#endif
| AntonLanghoff/Arpschuino | Core/Arpschuino-1.0/libraries/Arpschuino/Arpschuino.cpp | C++ | gpl-3.0 | 223 |
//
///////////////////////////////////////////////////////////////////////////////////////////////////
//
#include <utility/configuration.hpp>
#include <memory/mapped.hpp>
#include <transport/mcd.hpp>
#include <behaviour/event_republish.hpp>
#include <node/processor.hpp>
#include <fstream>
#include <iostream>
#include <cstddef>
//
///////////////////////////////////////////////////////////////////////////////////////////////////
//
using event_type = uint64_t;
using transport_memory_type = memory::mapped;
using transport_type = transport::mcd< event_type >;
using behaviour_memory_type = memory::mapped;
using behaviour_type = behaviour::event_republish< event_type >;
using node_type = node::processor< transport_type, behaviour_type >;
//
///////////////////////////////////////////////////////////////////////////////////////////////////
//
int main(
int argc,
char *argv[]
)
{
utility::configuration cfg( argc, argv );
std::cout << toString( cfg ) << std::endl;
transport_memory_type transport_memory(
cfg.get< std::string >( "transport.memory.file" ),
cfg.get< std::size_t >( "transport.memory.base" ),
cfg.get< std::size_t >( "transport.memory.size" )
);
transport_type transport(
transport_memory.data(
cfg.get< std::size_t >( "transport.memory.offset" )
),
cfg.get< transport_type::node_id_type >( "transport.id" ),
cfg.get< transport_type::follow_list_type >( "transport.follow" )
);
behaviour_memory_type behaviour_memory(
cfg.get< std::string >( "behaviour.memory.file" ),
cfg.get< std::size_t >( "behaviour.memory.base" ),
cfg.get< std::size_t >( "behaviour.memory.size" )
);
behaviour_type behaviour(
behaviour_memory.data(
cfg.get< std::size_t >( "behaviour.memory.offset" )
),
cfg.get< int >( "behaviour.loops" )
);
node_type node(
transport,
behaviour
);
node();
return 0;
}
//
///////////////////////////////////////////////////////////////////////////////////////////////////
//
| shauncroton/quix | src/base_mcd_processor_message_republish.cpp | C++ | gpl-3.0 | 2,042 |
Bitrix 17.0.9 Business Demo = 4fd706f3d8f7df0f1dbed42768e58c13
| gohdan/DFC | known_files/hashes/bitrix/modules/im/lang/ru/js_window.php | PHP | gpl-3.0 | 63 |
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2018 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cmd
import (
"fmt"
"path/filepath"
"sort"
"strings"
"github.com/snapcore/snapd/client"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/progress"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/systemd"
)
func ClientSnapFromSnapInfo(snapInfo *snap.Info) (*client.Snap, error) {
var publisher *snap.StoreAccount
if snapInfo.Publisher.Username != "" {
publisher = &snapInfo.Publisher
}
confinement := snapInfo.Confinement
if confinement == "" {
confinement = snap.StrictConfinement
}
snapapps := make([]*snap.AppInfo, 0, len(snapInfo.Apps))
for _, app := range snapInfo.Apps {
snapapps = append(snapapps, app)
}
sort.Sort(BySnapApp(snapapps))
apps, err := ClientAppInfosFromSnapAppInfos(snapapps)
result := &client.Snap{
Description: snapInfo.Description(),
Developer: snapInfo.Publisher.Username,
Publisher: publisher,
Icon: snapInfo.Media.IconURL(),
ID: snapInfo.SnapID,
InstallDate: snapInfo.InstallDate(),
Name: snapInfo.InstanceName(),
Revision: snapInfo.Revision,
Summary: snapInfo.Summary(),
Type: string(snapInfo.GetType()),
Base: snapInfo.Base,
Version: snapInfo.Version,
Channel: snapInfo.Channel,
Private: snapInfo.Private,
Confinement: string(confinement),
Apps: apps,
Broken: snapInfo.Broken,
Contact: snapInfo.Contact,
Title: snapInfo.Title(),
License: snapInfo.License,
Screenshots: snapInfo.Media.Screenshots(),
Media: snapInfo.Media,
Prices: snapInfo.Prices,
Channels: snapInfo.Channels,
Tracks: snapInfo.Tracks,
CommonIDs: snapInfo.CommonIDs,
}
return result, err
}
func ClientAppInfoNotes(app *client.AppInfo) string {
if !app.IsService() {
return "-"
}
var notes = make([]string, 0, 2)
var seenTimer, seenSocket bool
for _, act := range app.Activators {
switch act.Type {
case "timer":
seenTimer = true
case "socket":
seenSocket = true
}
}
if seenTimer {
notes = append(notes, "timer-activated")
}
if seenSocket {
notes = append(notes, "socket-activated")
}
if len(notes) == 0 {
return "-"
}
return strings.Join(notes, ",")
}
// BySnapApp sorts apps by (snap name, app name)
type BySnapApp []*snap.AppInfo
func (a BySnapApp) Len() int { return len(a) }
func (a BySnapApp) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a BySnapApp) Less(i, j int) bool {
iName := a[i].Snap.InstanceName()
jName := a[j].Snap.InstanceName()
if iName == jName {
return a[i].Name < a[j].Name
}
return iName < jName
}
func ClientAppInfosFromSnapAppInfos(apps []*snap.AppInfo) ([]client.AppInfo, error) {
// TODO: pass in an actual notifier here instead of null
// (Status doesn't _need_ it, but benefits from it)
sysd := systemd.New(dirs.GlobalRootDir, systemd.SystemMode, progress.Null)
out := make([]client.AppInfo, 0, len(apps))
for _, app := range apps {
appInfo := client.AppInfo{
Snap: app.Snap.InstanceName(),
Name: app.Name,
CommonID: app.CommonID,
}
if fn := app.DesktopFile(); osutil.FileExists(fn) {
appInfo.DesktopFile = fn
}
appInfo.Daemon = app.Daemon
if !app.IsService() || !app.Snap.IsActive() {
out = append(out, appInfo)
continue
}
// collect all services for a single call to systemctl
serviceNames := make([]string, 0, 1+len(app.Sockets)+1)
serviceNames = append(serviceNames, app.ServiceName())
sockSvcFileToName := make(map[string]string, len(app.Sockets))
for _, sock := range app.Sockets {
sockUnit := filepath.Base(sock.File())
sockSvcFileToName[sockUnit] = sock.Name
serviceNames = append(serviceNames, sockUnit)
}
if app.Timer != nil {
timerUnit := filepath.Base(app.Timer.File())
serviceNames = append(serviceNames, timerUnit)
}
// sysd.Status() makes sure that we get only the units we asked
// for and raises an error otherwise
sts, err := sysd.Status(serviceNames...)
if err != nil {
return nil, fmt.Errorf("cannot get status of services of app %q: %v", app.Name, err)
}
if len(sts) != len(serviceNames) {
return nil, fmt.Errorf("cannot get status of services of app %q: expected %v results, got %v", app.Name, len(serviceNames), len(sts))
}
for _, st := range sts {
switch filepath.Ext(st.UnitName) {
case ".service":
appInfo.Enabled = st.Enabled
appInfo.Active = st.Active
case ".timer":
appInfo.Activators = append(appInfo.Activators, client.AppActivator{
Name: app.Name,
Enabled: st.Enabled,
Active: st.Active,
Type: "timer",
})
case ".socket":
appInfo.Activators = append(appInfo.Activators, client.AppActivator{
Name: sockSvcFileToName[st.UnitName],
Enabled: st.Enabled,
Active: st.Active,
Type: "socket",
})
}
}
out = append(out, appInfo)
}
return out, nil
}
| ubuntu-core/snappy | cmd/snapinfo.go | GO | gpl-3.0 | 5,591 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace CarRental.WebApp.Areas.AdminPanel.Models
{
public class EquipmentViewModel
{
public EquipmentViewModel()
{
IsEnabled = true;
}
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
[Display(Name = "Enabled")]
public bool IsEnabled { get; set; }
}
} | wojtas233/carrental | CarRental.WebApp/Areas/AdminPanel/Models/EquipmentViewModel.cs | C# | gpl-3.0 | 523 |
#include <iostream>
#include "game.hpp"
using namespace std;
int main(int argc, char *argv[]) {
Game game;
if (argc >= 2) {
game.setLanguage(argv[1]);
} else {
game.setLanguage("");
}
game.init();
game.loop();
game.shutdown();
return 0;
}
| ProjectTecPro-2016-1/jtj | src/main.cpp | C++ | gpl-3.0 | 288 |
/**
* Too Many Tools
* TMT
*
* @author dogking190
* @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
*
*/
package dogking190.tmt.Tools;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import dogking190.lib.Modinfo;
import dogking190.lib.Names;
import dogking190.tmt.tmt;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.item.EnumToolMaterial;
import net.minecraft.item.ItemPickaxe;
public class PickaxeTin extends ItemPickaxe
{
public PickaxeTin(int par1, EnumToolMaterial par2EnumToolMaterial)
{
super(par1, par2EnumToolMaterial);
this.setCreativeTab(tmt.tabTooManytools);
this.setUnlocalizedName(Names.pickaxeTin_UnlocalizedName);
}
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister icon)
{
itemIcon = icon.registerIcon(Modinfo.ID.toLowerCase() + ":" + Names.pickaxeTin_UnlocalizedName);
}
}
| dogking190/TooManyTools | common/dogking190/tmt/Tools/PickaxeTin.java | Java | gpl-3.0 | 1,012 |
import logging
from ..exports import ObjectCollectorMixin, ListCollector
#: Event name used to signal members to perform one-time initialization
INITIALIZE = 'initialize'
class Hooks(ObjectCollectorMixin, ListCollector):
"""
This class collects event hooks that should be installed during supervisor
start-up.
"""
export_key = 'hooks'
def install_member(self, hook):
hook_name = getattr(hook, 'hook', None)
if not hook_name:
logging.error('Missing hook name for {}'.format(hook))
return
# Initialize hook must be executed in-place, as soon as the component
# loads. Currently it's hard-wired here, because anywhere else seemed
# already too late to fire it, though a better alternative is welcome.
if hook_name == INITIALIZE:
hook(self.supervisor)
else:
self.events.subscribe(hook_name, hook)
| Outernet-Project/librarian | librarian/core/collectors/hooks.py | Python | gpl-3.0 | 927 |
/*
* Copyright (c) 2015. Kelewan Technologies Ltd
*/
package com.kloudtek.kloudmake.java;
import com.kloudtek.kloudmake.KMContextImpl;
import com.kloudtek.kloudmake.Resource;
import com.kloudtek.kloudmake.exception.InvalidResourceDefinitionException;
import com.kloudtek.kloudmake.exception.KMRuntimeException;
import com.kloudtek.kloudmake.util.ReflectionHelper;
import java.lang.reflect.Method;
/**
* Use to enforce customer OnlyIf annotations (on a method).
*/
public class EnforceOnlyIfCustom extends EnforceOnlyIf {
private Method method;
private final Class<?> clazz;
public EnforceOnlyIfCustom(Method method, Class<?> clazz) throws InvalidResourceDefinitionException {
this.method = method;
this.clazz = clazz;
Class<?> returnType = method.getReturnType();
if (!returnType.equals(boolean.class)) {
throw new InvalidResourceDefinitionException("Method annotated with @OnlyIf must return a boolean value");
}
}
@Override
public boolean execAllowed(KMContextImpl context, Resource resource) throws KMRuntimeException {
return (boolean) ReflectionHelper.invoke(method, clazz, resource);
}
}
| Kloudtek/kloudmake | core/src/main/java/com/kloudtek/kloudmake/java/EnforceOnlyIfCustom.java | Java | gpl-3.0 | 1,192 |
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
#define TASK "countpaths"
ifstream cin(TASK ".in");
ofstream cout(TASK ".out");
vector <int> mem;
vector <vector <int> > g;
int dp(int v) {
if (mem[v] != -1)
return mem[v];
if (v == (int)g.size() - 1)
return 1;
int res = 0;
for (int i = 0; i < (int)g[v].size(); i++) {
int to = g[v][i];
res += dp(to);
}
return mem[v] = res;
}
int main() {
int n, m;
cin >> n >> m;
g.resize(n);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
g[--u].push_back(--v);
}
mem.assign(n, -1);
cout << dp(0) << endl;
}
| zakharvoit/discrete-math-labs | Season1/DynamicProgramming/CountPaths/main.cpp | C++ | gpl-3.0 | 705 |
#include <ert/util/test_util.hpp>
#include <ert/util/rng.h>
#include <ert/res_util/es_testdata.hpp>
#include <ert/analysis/std_enkf.hpp>
#include <ert/analysis/ies/ies_enkf_state.hpp>
#include <ert/analysis/ies/ies_enkf.hpp>
void init_stdA(const res::es_testdata &testdata, matrix_type *A2) {
rng_type *rng = rng_alloc(MZRAN, INIT_DEFAULT);
std_enkf_data_type *std_data =
static_cast<std_enkf_data_type *>(std_enkf_data_alloc());
std_enkf_set_truncation(std_data, 1.00);
matrix_type *X =
matrix_alloc(testdata.active_ens_size, testdata.active_ens_size);
std_enkf_initX(std_data, X, nullptr, testdata.S, testdata.R, testdata.dObs,
testdata.E, testdata.D, rng);
matrix_inplace_matmul(A2, X);
std_enkf_data_free(std_data);
rng_free(rng);
}
/*
This function will run the forward model again and update the matrices in the
testdata structure - with A1 as prior.
*/
void forward_model(res::es_testdata &testdata, const matrix_type *A1) {
int nrens = matrix_get_columns(A1);
int ndim = matrix_get_rows(A1);
int nrobs = matrix_get_rows(testdata.S);
/* Model prediction gives new S given prior S=func(A) */
for (int iens = 0; iens < nrens; iens++) {
for (int i = 0; i < nrobs; i++) {
double coeffa = matrix_iget(A1, 0, iens);
double coeffb = matrix_iget(A1, 1, iens);
double coeffc = matrix_iget(A1, 2, iens);
double y = coeffa * i * i + coeffb * i + coeffc;
matrix_iset(testdata.S, i, iens, y);
}
}
/* Updating D according to new S: D=dObs+E-S*/
for (int i = 0; i < nrens; i++)
matrix_copy_column(testdata.D, testdata.dObs, i, 0);
matrix_inplace_add(testdata.D, testdata.E);
matrix_inplace_sub(testdata.D, testdata.S);
}
void cmp_std_ies(res::es_testdata &testdata) {
int num_iter = 100;
bool verbose = false;
rng_type *rng = rng_alloc(MZRAN, INIT_DEFAULT);
matrix_type *A1 = testdata.alloc_state("prior");
matrix_type *A2 = testdata.alloc_state("prior");
ies_enkf_state_type *ies_data =
static_cast<ies_enkf_state_type *>(ies_enkf_state_alloc());
ies_enkf_config_type *ies_config = ies_enkf_state_get_config(ies_data);
forward_model(testdata, A1);
ies_enkf_config_set_truncation(ies_config, 1.0);
ies_enkf_config_set_ies_max_steplength(ies_config, 0.6);
ies_enkf_config_set_ies_min_steplength(ies_config, 0.6);
ies_enkf_config_set_ies_inversion(ies_config, IES_INVERSION_EXACT);
ies_enkf_config_set_ies_aaprojection(ies_config, false);
/* ES solution */
init_stdA(testdata, A2);
for (int iter = 0; iter < num_iter; iter++) {
forward_model(testdata, A1);
ies_enkf_init_update(ies_data, testdata.ens_mask, testdata.obs_mask,
testdata.S, testdata.R, testdata.dObs, testdata.E,
testdata.D, rng);
ies_enkf_updateA(ies_data, A1, testdata.S, testdata.R, testdata.dObs,
testdata.E, testdata.D, rng);
if (verbose) {
fprintf(stdout, "IES iteration = %d %d\n", iter,
bool_vector_count_equal(testdata.ens_mask, true));
matrix_pretty_fprint(A1, "Aies", "%11.5f", stdout);
matrix_pretty_fprint(A2, "Astdenkf", "%11.5f", stdout);
}
test_assert_int_equal(ies_enkf_state_get_iteration_nr(ies_data),
iter + 1);
if (matrix_similar(A1, A2, 1e-5))
break;
}
test_assert_true(matrix_similar(A1, A2, 1e-5));
matrix_free(A1);
matrix_free(A2);
ies_enkf_state_free(ies_data);
rng_free(rng);
}
void cmp_std_ies_delrel(res::es_testdata &testdata) {
int num_iter = 100;
bool verbose = true;
rng_type *rng = rng_alloc(MZRAN, INIT_DEFAULT);
matrix_type *A1 = testdata.alloc_state("prior");
matrix_type *A2 = testdata.alloc_state("prior");
matrix_type *A1c = matrix_alloc_copy(A1);
matrix_type *A2c = matrix_alloc_copy(A2);
ies_enkf_state_type *ies_data =
static_cast<ies_enkf_state_type *>(ies_enkf_state_alloc());
ies_enkf_config_type *ies_config = ies_enkf_state_get_config(ies_data);
forward_model(testdata, A1);
ies_enkf_config_set_truncation(ies_config, 1.0);
ies_enkf_config_set_ies_min_steplength(ies_config, 0.6);
ies_enkf_config_set_ies_max_steplength(ies_config, 0.6);
ies_enkf_config_set_ies_inversion(ies_config, IES_INVERSION_EXACT);
ies_enkf_config_set_ies_aaprojection(ies_config, false);
int iens_deact = testdata.active_ens_size / 2;
if (verbose) {
fprintf(stdout, "ES and IES original priors\n");
matrix_pretty_fprint(A1, "A1 ", "%11.5f", stdout);
matrix_pretty_fprint(A2, "A2 ", "%11.5f", stdout);
}
/* IES solution after with one realization is inactivated */
for (int iter = 0; iter < num_iter; iter++) {
forward_model(testdata, A1);
// Removing the realization
if (iter == 6) {
testdata.deactivate_realization(iens_deact);
A1c =
matrix_alloc(matrix_get_rows(A1),
bool_vector_count_equal(testdata.ens_mask, true));
int iens_active = 0;
for (int iens = 0; iens < matrix_get_columns(A1); iens++) {
if (bool_vector_iget(testdata.ens_mask, iens)) {
matrix_copy_column(A1c, A1, iens_active, iens);
iens_active += 1;
}
}
matrix_realloc_copy(A1, A1c);
}
ies_enkf_init_update(ies_data, testdata.ens_mask, testdata.obs_mask,
testdata.S, testdata.R, testdata.dObs, testdata.E,
testdata.D, rng);
ies_enkf_updateA(ies_data, A1, testdata.S, testdata.R, testdata.dObs,
testdata.E, testdata.D, rng);
if (verbose) {
fprintf(stdout, "IES iteration = %d active realizations= %d\n",
iter, bool_vector_count_equal(testdata.ens_mask, true));
matrix_pretty_fprint(A1, "Aies", "%11.5f", stdout);
}
}
fprintf(stdout, "IES solution with %d active realizations\n",
bool_vector_count_equal(testdata.ens_mask, true));
matrix_pretty_fprint(A1, "A1 ", "%11.5f", stdout);
/* ES update with one realization removed*/
{
A2c = matrix_alloc(matrix_get_rows(A2),
bool_vector_count_equal(testdata.ens_mask, true));
int iens_active = 0;
for (int iens = 0; iens < matrix_get_columns(A2); iens++) {
if (bool_vector_iget(testdata.ens_mask, iens)) {
matrix_copy_column(A2c, A2, iens_active, iens);
iens_active += 1;
}
}
matrix_realloc_copy(A2, A2c);
}
forward_model(testdata, A2);
if (verbose) {
fprintf(stdout, "\n\n\nES prior with one realization removed\n");
matrix_pretty_fprint(A2, "A2 ", "%11.5f", stdout);
}
init_stdA(testdata, A2);
if (verbose) {
fprintf(stdout, "ES solution with one realization removed\n");
matrix_pretty_fprint(A2, "A2 ", "%11.5f", stdout);
}
test_assert_true(matrix_similar(A1, A2, 1e-5));
matrix_free(A1c);
matrix_free(A2c);
matrix_free(A1);
matrix_free(A2);
ies_enkf_state_free(ies_data);
rng_free(rng);
}
matrix_type *swap_matrix(matrix_type *old_matrix, matrix_type *new_matrix) {
matrix_free(old_matrix);
return new_matrix;
}
/*
This test verifies that the update iteration do not crash hard when
realizations and observations are deactived between iterations.
The function is testing reactivation as well. It is a bit tricky since there is no
reactivation function. What is done is to start with identical copies, testdata and
testdata2. In the first iteration, one observation is removed in testdata2 and before
computing the update. In the subsequent iterations, testdata is used which includes
the datapoint initially removed from testdata2.
*/
void test_deactivate_observations_and_realizations(const char *testdata_file) {
res::es_testdata testdata(testdata_file);
res::es_testdata testdata2(testdata_file);
int num_iter = 10;
rng_type *rng = rng_alloc(MZRAN, INIT_DEFAULT);
ies_enkf_state_type *ies_data =
static_cast<ies_enkf_state_type *>(ies_enkf_state_alloc());
ies_enkf_config_type *ies_config = ies_enkf_state_get_config(ies_data);
matrix_type *A0 = testdata.alloc_state("prior");
matrix_type *A = matrix_alloc_copy(A0);
ies_enkf_config_set_truncation(ies_config, 1.00);
ies_enkf_config_set_ies_max_steplength(ies_config, 0.50);
ies_enkf_config_set_ies_min_steplength(ies_config, 0.50);
ies_enkf_config_set_ies_inversion(ies_config,
IES_INVERSION_SUBSPACE_EXACT_R);
ies_enkf_config_set_ies_aaprojection(ies_config, false);
for (int iter = 0; iter < 1; iter++) {
printf("test_deactivate_observations_and_realizations: iter= %d\n",
iter);
// deactivate an observation initially to test reactivation in the following iteration
testdata2.deactivate_obs(2);
ies_enkf_init_update(ies_data, testdata2.ens_mask, testdata2.obs_mask,
testdata2.S, testdata2.R, testdata2.dObs,
testdata2.E, testdata2.D, rng);
ies_enkf_updateA(ies_data, A, testdata2.S, testdata2.R, testdata2.dObs,
testdata2.E, testdata2.D, rng);
}
for (int iter = 1; iter < num_iter; iter++) {
printf("test_deactivate_observations_and_realizations: iter= %d\n",
iter);
// Deactivate a realization
if (iter == 3) {
int iens = testdata.active_ens_size / 2;
testdata.deactivate_realization(iens);
A = matrix_alloc(matrix_get_rows(A0),
bool_vector_count_equal(testdata.ens_mask, true));
int iens_active = 0;
for (int iens = 0; iens < matrix_get_columns(A0); iens++) {
if (bool_vector_iget(testdata.ens_mask, iens)) {
matrix_copy_column(A, A0, iens_active, iens);
iens_active += 1;
}
}
}
// Now deactivate a previously active observation
if (iter == 7)
testdata.deactivate_obs(testdata.active_obs_size / 2);
ies_enkf_init_update(ies_data, testdata.ens_mask, testdata.obs_mask,
testdata.S, testdata.R, testdata.dObs, testdata.E,
testdata.D, rng);
ies_enkf_updateA(ies_data, A, testdata.S, testdata.R, testdata.dObs,
testdata.E, testdata.D, rng);
}
matrix_free(A);
matrix_free(A0);
ies_enkf_state_free(ies_data);
rng_free(rng);
}
int main(int argc, char **argv) {
res::es_testdata testdata(argv[1]);
cmp_std_ies(testdata);
cmp_std_ies_delrel(testdata);
test_deactivate_observations_and_realizations(argv[1]);
}
| joakim-hove/ert | libres/old_tests/analysis/ies/test_ies_iteration.cpp | C++ | gpl-3.0 | 11,225 |
/*
* Name: Sebastian Lloret
* Recitation TA: Brennan Mcconnell
* Assignment #: 4
*/
#include <iostream>
using namespace std;
//strings are 340 characters
const string humanDNA = "CGCAAATTTGCCGGATTTCCTTTGCTGTTCCTGCATGTAGTTTAAACGAGATTGCCAGCACCGGGTATCATTCACCATTTTTCTTTTCGTTAACTTGCCGTCAGCCTTTTCTTTGACCTCTTCTTTCTGTTCATGTGTATTTGCTGTCTCTTAGCCCAGACTTCCCGTGTCCTTTCCACCGGGCCTTTGAGAGGTCACAGGGTCTTGATGCTGTGGTCTTCATCTGCAGGTGTCTGACTTCCAGCAACTGCTGGCCTGTGCCAGGGTGCAGCTGAGCACTGGAGTGGAGTTTTCCTGTGGAGAGGAGCCATGCCTAGAGTGGGATGGGCCATTGTTCATG";
const string mouseDNA = "CGCAATTTTTACTTAATTCTTTTTCTTTTAATTCATATATTTTTAATATGTTTACTATTAATGGTTATCATTCACCATTTAACTATTTGTTATTTTGACGTCATTTTTTTCTATTTCCTCTTTTTTCAATTCATGTTTATTTTCTGTATTTTTGTTAAGTTTTCACAAGTCTAATATAATTGTCCTTTGAGAGGTTATTTGGTCTATATTTTTTTTTCTTCATCTGTATTTTTATGATTTCATTTAATTGATTTTCATTGACAGGGTTCTGCTGTGTTCTGGATTGTATTTTTCTTGTGGAGAGGAACTATTTCTTGAGTGGGATGTACCTTTGTTCTTG";
const string unknownDNA = "CGCATTTTTGCCGGTTTTCCTTTGCTGTTTATTCATTTATTTTAAACGATATTTATATCATCGGGTTTCATTCACTATTTTTCTTTTCGATAAATTTTTGTCAGCATTTTCTTTTACCTCTTCTTTCTGTTTATGTTAATTTTCTGTTTCTTAACCCAGTCTTCTCGATTCTTATCTACCGGACCTATTATAGGTCACAGGGTCTTGATGCTTTGGTTTTCATCTGCAAGAGTCTGACTTCCTGCTAATGCTGTTCTGTGTCAGGGTGCATCTGAGCACTGATGTGGAGTTTTCTTGTGGATATGAGCCATTCATAGTGTGGGATGTGCCATAGTTCATG";
//function to find the hamming distance between two DNA strings
void calculateSimilarity (double *similarity, string DNA1, string DNA2){
double hammingDistance = 0;
for(int i = 0; i < DNA1.length(); i++) { //find non-matching characters and count them up
if (DNA1[i] != DNA2[i]) {
hammingDistance++;
}
}
*similarity = (DNA1.length() - hammingDistance) / DNA1.length(); //calculate the similarity score and store it in a pointer to pass between functions
}
//use a user-inputted substring and find the best match in the mouse DNA string
void calculateBestMatch(double *distance, int *index, string DNA1, string substr){
int bestIndex;
int smallestHamming = -1;
for (int i = 0; i < DNA1.length(); i++) {
double hammingDistance = 0;
string DNASubstring = DNA1.substr(i, substr.length());
for (int k = 0; k < DNASubstring.length(); k++) {
if (DNASubstring[k] != substr[k]) {
hammingDistance++;
}
}
if (hammingDistance < smallestHamming or smallestHamming == -1) {
smallestHamming = hammingDistance;
bestIndex = i;
}
}
*distance = smallestHamming;
*index = bestIndex;
string sequence = DNA1.substr(bestIndex, substr.length());
int matchingCharacters = substr.length() - smallestHamming;
if (matchingCharacters <= 1) {
cout << "Match not found.\n";
return;
}
cout << "Best match: " << sequence << endl;
cout << "Best match score: " << (substr.length() - smallestHamming) << endl;
}
//determine whether the unknown DNA string is more similar to mouse or human DNA, and then prompt the user for a substring to compare to the mouse DNA
int main(){
double similarityScore;
double *similarity = &similarityScore;
calculateSimilarity(similarity, humanDNA, unknownDNA);
double humanSimilarity = similarityScore;
calculateSimilarity(similarity, mouseDNA, unknownDNA);
double mouseSimilarity = similarityScore;
if (humanSimilarity > mouseSimilarity) {
cout << "Human\n";
}
else if (mouseSimilarity > humanSimilarity) {
cout << "Mouse\n";
}
else {
cout << "Identity cannot be determined.\n";
}
string substr;
double hammingDistance;
double *distancePointer = &hammingDistance;
int index;
int *indexPointer = &index;
cout<< "Enter a substring: ";
cin >> substr;
cin.ignore();
calculateBestMatch(distancePointer, indexPointer, mouseDNA, substr);
}
| SebastianLloret/CSCI-1310 | Assignments/Assignment4_Lloret.cpp | C++ | gpl-3.0 | 4,232 |
/*
* Sweeper - Duplicate file cleaner
* Copyright (C) 2012 Bogdan Ciprian Pistol
*
* 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 gg.pistol.sweeper.core;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Before;
import org.junit.Test;
public class HashFunctionTest {
private HashFunction hash;
private InputStream inputStream;
private OperationTrackingListener listener;
private AtomicBoolean abortFlag;
@Before
public void setUp() throws Exception {
hash = new HashFunction();
inputStream = new ByteArrayInputStream("foo".getBytes("UTF-8"));
listener = mock(OperationTrackingListener.class);
abortFlag = new AtomicBoolean();
}
@Test
public void testCompute() throws Exception {
assertEquals("0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33", hash.compute(inputStream, listener, abortFlag));
inputStream = new ByteArrayInputStream("".getBytes("UTF-8"));
assertEquals("da39a3ee5e6b4b0d3255bfef95601890afd80709", hash.compute(inputStream, listener, abortFlag));
inputStream = new ByteArrayInputStream(new byte[6 * (1 << 20)]); // 6 MB
hash.compute(inputStream, listener, abortFlag);
verify(listener).incrementTargetProgress(anyLong());
}
@Test
public void testComputeException() throws Exception {
try {
hash.compute(null, listener, abortFlag);
fail();
} catch (NullPointerException e) {
// expected
}
try {
hash.compute(inputStream, null, abortFlag);
fail();
} catch (NullPointerException e) {
// expected
}
try {
hash.compute(inputStream, listener, null);
fail();
} catch (NullPointerException e) {
// expected
}
try {
hash.compute(inputStream, listener, new AtomicBoolean(true));
fail();
} catch (SweeperAbortException e) {
// expected
}
}
}
| bogdanu/sweeper | src/test/java/gg/pistol/sweeper/core/HashFunctionTest.java | Java | gpl-3.0 | 2,789 |
// Navigation active state on click or section scrolled
var sections = $('section'), nav = $('.desktop-navigation'), nav_height = nav.outerHeight();
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
sections.each(function() {
var top = $(this).offset().top - nav_height -1,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
});
});
nav.find('a').on('click', function () {
var $el = $(this), id = $el.attr('href');
// $(this).addClass('active');
$('html, body').animate({
scrollTop: $(id).offset().top - nav_height
}, 500);
return false;
}); | blueocto/code-snippets | jquery-javascript/sticky-nav-active-state-while-scrolling.js | JavaScript | gpl-3.0 | 823 |
<!DOCTYPE html>
<html>
<?php include_once('../head.php'); ?>
<body>
<?php include_once('../header.php'); ?>
<div id='tos'>
<?php include_once('design.php'); ?>
<div id='content'>
<div id='index'>
<p><a href=<?php echo ($configuration['site_dir'] . 'others/images'); ?>><img src=<?php echo ($configuration['site_dir'] . 'images/win9x/win9x_images.gif'); ?> /><br /><?php echo ($lang['IMAGES']); ?></a></p>
<p><a href=<?php echo ($configuration['site_dir'] . 'others/updates'); ?>><img src=<?php echo ($configuration['site_dir'] . 'images/win9x/wininstall.gif'); ?> /><br /><?php echo ($lang['GAMES']); ?></a></p>
<p><a href=<?php echo ($configuration['site_dir'] . 'others/drivers'); ?>><img src=<?php echo ($configuration['site_dir'] . 'images/win9x/win9x_drivers.gif'); ?> /><br /><?php echo ($lang['DRIVERS']); ?></a></p>
<p><a href=<?php echo ($configuration['site_dir'] . 'others/softwares'); ?>><img src=<?php echo ($configuration['site_dir'] . 'images/win9x/win9x_softwares.gif'); ?> /><br /><?php echo ($lang['SOFTWARES']); ?></a></p>
<p><a href=<?php echo ($configuration['site_dir'] . 'others/games'); ?>><img src=<?php echo ($configuration['site_dir'] . 'images/win9x/win9x_games.gif'); ?> width="32" height="32" /><br /><?php echo ($lang['GAMES']); ?></a></p>
</div>
</div>
</div>
<?php include_once('../footer.php'); ?>
</body>
</html> | Cryonid/rcnet-downloadcenter | others/index.php | PHP | gpl-3.0 | 1,471 |
//
// TransportRead.cs
//
// Author:
// Benito Palacios Sánchez <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez
//
// 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 EaTopic.Topics;
namespace EaTopic.Transports
{
public delegate void ReceivedDataEventHandler(DataFormatter data);
/// <summary>
/// Transport read / receive layer.
/// </summary>
public interface TransportReceiver
{
/// <summary>
/// Close this instance.
/// </summary>
void Close();
int Port { get; }
event ReceivedDataEventHandler ReceivedData;
void StartReceive(DataFormatter formatter);
}
}
| pleonex/eaTopic | eaTopic/Transports/TransportReceiver.cs | C# | gpl-3.0 | 1,250 |
package com.college17summer.android.fleeting;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | College17Summer/Fleeting | app/src/test/java/com/college17summer/android/fleeting/ExampleUnitTest.java | Java | gpl-3.0 | 414 |
package com.github.joe42.splitter.vtf;
import java.io.File;
import java.util.*;
import fuse.FuseFtype;
import fuse.compat.FuseDirEnt;
public class VirtualFileContainer {
List<VirtualFile> vtf = new ArrayList<VirtualFile>();
public synchronized void add(VirtualFile virtualFile) {
vtf.add(virtualFile);
}
public synchronized void remove(VirtualFile virtualFile) {
vtf.remove(virtualFile);
}
public synchronized void remove(String path) {
VirtualFile fileToRemove = null;
for(VirtualFile file: vtf){
if(file.getPath().equals(path)){
fileToRemove = file;
break;
}
}
if(fileToRemove != null){
vtf.remove(fileToRemove);
}
}
public synchronized boolean containsFile(String path){
for(VirtualFile file: vtf){
if(file.getPath().equals(path)){
return true;
}
}
return false;
}
public synchronized List<String> getDirNames(){
/**@return All directory names of this container*/
List<String> ret = new ArrayList<String>();
String dir;
for(VirtualFile file: vtf){
dir = file.getDir();
while(dir != null){
ret.add(dir);
dir = new File(dir).getParent();
}
}
return ret;
}
public synchronized List<String> getDirNames(String path){
/**@return All directory names in path*/
List<String> ret = new ArrayList<String>();
String parent;
File file;
for(String dir: getDirNames()){
file = new File(dir);
parent = file.getParent();
if(path.equals(parent)){
ret.add(file.getName());
}
}
ret.add(".");
ret.add("..");
return ret;
}
public synchronized List<String> getFileNames(String path){
/**@return All file names in path*/
List<String> ret = new ArrayList<String>();
for(VirtualFile file: vtf){
if(file.getDir().equals(path)){
ret.add(file.getName());
}
}
return ret;
}
public boolean containsDir(String path){
return getDirNames().contains(path);
}
public FuseDirEnt[] getDir(String path) {
List<FuseDirEnt> ret = new ArrayList<FuseDirEnt>();
for (String file : getFileNames(path)) {
FuseDirEnt entity = new FuseDirEnt();
entity.name = file;
entity.mode = FuseFtype.TYPE_FILE | 0664;
ret.add(entity);
}
for (String dir : getDirNames(path)) {
FuseDirEnt entity = new FuseDirEnt();
entity.name = dir;
entity.mode = FuseFtype.TYPE_DIR | 0755;
ret.add(entity);
}
return ret.toArray(new FuseDirEnt[0]);
}
public synchronized VirtualFile get(String path){
/**
* @return the first virtual File with the path path or null if it does not exist
*/
for(VirtualFile file: vtf){
if(file.getPath().equals(path)){
return file;
}
}
return null;
}
}
| joe42/nubisave | splitter/src/com/github/joe42/splitter/vtf/VirtualFileContainer.java | Java | gpl-3.0 | 2,642 |
<?php
/**
* This file is part of Joshua Project API.
*
* Joshua Project API 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.
*
* Joshua Project API 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/>.
*
* @author Johnathan Pulos <johnathan@missionaldigerati.org>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/**
* This requires PDO MySQL Support.
*
* @author Johnathan Pulos
*/
/**
* Set the timezone
*/
date_default_timezone_set('America/Denver');
/**
* Set whether to use Memcached for caching the queries. Most queries are cached for 1 day.
*
* @var boolean
* @author Johnathan Pulos
*/
$useCaching = false;
$googleDocTitle = '';
$DS = DIRECTORY_SEPARATOR;
$DOMAIN_ADDRESS = $_SERVER['SERVER_NAME'];
if ((substr_compare($DOMAIN_ADDRESS, "http://", 0, 7)) !== 0) {
$DOMAIN_ADDRESS = "http://" . $DOMAIN_ADDRESS;
}
if (strpos($DOMAIN_ADDRESS, 'joshua.api.local') !== false) {
$GOOGLE_TRACKING_ID = 'UA-49359140-2';
} elseif (strpos($DOMAIN_ADDRESS, 'jpapi.codingstudio.org') !== false) {
$GOOGLE_TRACKING_ID = 'UA-49359140-1';
} else {
$GOOGLE_TRACKING_ID = '';
}
/**
* Set the Public directory path
*
* @var string
* @author Johnathan Pulos
*/
$PUBLIC_DIRECTORY = dirname(__FILE__);
/**
* Lets get the version of the API based on the URL (
* http://joshua.api.local/v12/people_groups/daily_unreached.json?api_key=37e24112caae
* ) It will default to the latest API. You must provide an API Version if you are accessing the data. The default is
* only for static pages
*
* @author Johnathan Pulos
*/
$pattern = '/([v]+[1-9]+)/';
preg_match($pattern, $_SERVER['REQUEST_URI'], $matches);
if (empty($matches)) {
$API_VERSION = "v1";
} else {
$API_VERSION = $matches[0];
}
$bypassExtTest = false;
if ($useCaching === true) {
$cache = new Memcached();
$cache->addServer('localhost', 11211) or die('Memcached not found');
} else {
$cache = '';
}
/**
* Set the Template View directory path
*
* @var string
* @author Johnathan Pulos
*/
$VIEW_DIRECTORY = $PUBLIC_DIRECTORY . "/../App/" . $API_VERSION . "/Views/";
/**
* Load up the Composer AutoLoader
*
* @author Johnathan Pulos
*/
$vendorDirectory = __DIR__ . $DS . ".." . $DS . "Vendor" . $DS;
require $vendorDirectory . 'autoload.php';
$app = new \Slim\Slim(array('templates.path' => $VIEW_DIRECTORY));
$settings = new JPAPI\DatabaseSettings();
$pdoDb = \PHPToolbox\PDODatabase\PDODatabaseConnect::getInstance();
$pdoDb->setDatabaseSettings(new \JPAPI\DatabaseSettings);
$db = $pdoDb->getDatabaseInstance();
/**
* Get the current request to determine which PHP file to load. Do not load all files, because it can take longer to
* load.
*
* @author Johnathan Pulos
*/
$appRequest = $app->request();
$requestedUrl = $appRequest->getResourceUri();
/**
* Include common functions
*
* @author Johnathan Pulos
*/
require(__DIR__."/../App/" . $API_VERSION . "/Includes/CommonFunctions.php");
/**
* Are we on a static page?
*
* @author Johnathan Pulos
*/
$staticPages = array("/", "/get_my_api_key", "/resend_activation_links", "/getting_started");
if (in_array($requestedUrl, $staticPages)) {
require(__DIR__."/../App/" . $API_VERSION . "/Resources/StaticPages.php");
$bypassExtTest = true;
$googleDocTitle = "Requesting a Static Page";
}
/**
* Are we on a documentation page?
*
* @author Johnathan Pulos
*/
if (strpos($requestedUrl, '/docs') !== false) {
require(__DIR__."/../App/" . $API_VERSION . "/Resources/Docs.php");
$bypassExtTest = true;
$googleDocTitle = "Requesting Documentation";
}
/**
* Are we on a API Key page?
*
* @author Johnathan Pulos
*/
if (strpos($requestedUrl, '/api_keys') !== false) {
/**
* We need to lock out all PUT and GET requests for api_keys. These are the admin users.
*
* @author Johnathan Pulos
**/
if (($appRequest->isGet()) || ($appRequest->isPut())) {
$adminSettings = new \JPAPI\AdminSettings;
$app->add(
new Slim\Extras\Middleware\HttpBasicAuth(
$adminSettings->default['username'],
$adminSettings->default['password']
)
);
}
require(__DIR__."/../App/" . $API_VERSION . "/Resources/APIKeys.php");
$bypassExtTest = true;
$googleDocTitle = "Requesting Admin Area";
}
/**
* We must be on an API Request. Make sure they only supply supported formats.
*
* @author Johnathan Pulos
*/
$extArray = explode('.', $requestedUrl);
$ext = end($extArray);
if (($bypassExtTest === false) && (!in_array($ext, array('json', 'xml')))) {
$app->render("/errors/400.xml.php");
exit;
}
/**
* Check if they have a valid API key, else send a 401 error
*
* @author Johnathan Pulos
**/
if ($bypassExtTest === false) {
$APIKey = strip_tags($appRequest->get('api_key'));
if ((!isset($APIKey)) || ($APIKey == "")) {
$app->render("/errors/401." . $ext . ".php");
exit;
}
/**
* Find the API Key in the database, and validate it
*
* @author Johnathan Pulos
* @todo put a try block here
**/
$query = "SELECT * FROM md_api_keys where api_key = :api_key LIMIT 1";
$statement = $db->prepare($query);
$statement->execute(array('api_key' => $APIKey));
$apiKeyData = $statement->fetchAll(PDO::FETCH_ASSOC);
if (empty($apiKeyData)) {
$app->render("/errors/401." . $ext . ".php");
exit;
}
if ($apiKeyData[0]['status'] == 0 || $apiKeyData[0]['status'] == 2) {
/**
* Pending (0) or Suspended (2)
*
* @author Johnathan Pulos
*/
$app->render("/errors/401." . $ext . ".php");
exit;
}
}
/**
* Are we searching API for People Groups?
*
* @author Johnathan Pulos
*/
if (strpos($requestedUrl, 'people_groups') !== false) {
/**
* Load the Query Generator for People Groups, ProfileText, and Resources
*
* @author Johnathan Pulos
*/
require(__DIR__."/../App/" . $API_VERSION . "/Resources/PeopleGroups.php");
$googleDocTitle = "API Request for People Group Data.";
}
/**
* Are we searching API for Countries?
*
* @author Johnathan Pulos
*/
if (strpos($requestedUrl, 'countries') !== false) {
/**
* Load the Query Generator for People Groups
*
* @author Johnathan Pulos
*/
require(__DIR__."/../App/" . $API_VERSION . "/Resources/Countries.php");
$googleDocTitle = "API Request for Country Data.";
}
/**
* Are we searching API for Languages?
*
* @author Johnathan Pulos
*/
if (strpos($requestedUrl, 'languages') !== false) {
/**
* Load the Query Generator for Languages
*
* @author Johnathan Pulos
*/
require(__DIR__."/../App/" . $API_VERSION . "/Resources/Languages.php");
$googleDocTitle = "API Request for Language Data.";
}
/**
* Are we searching API for Continents?
*
* @author Johnathan Pulos
*/
if (strpos($requestedUrl, 'continents') !== false) {
/**
* Load the Query Generator for Continents
*
* @author Johnathan Pulos
*/
require(__DIR__."/../App/" . $API_VERSION . "/Resources/Continents.php");
$googleDocTitle = "API Request for Continent Data.";
}
/**
* Are we searching API for Regions?
*
* @author Johnathan Pulos
*/
if (strpos($requestedUrl, 'regions') !== false) {
/**
* Load the Query Generator for Regions
*
* @author Johnathan Pulos
*/
require(__DIR__."/../App/" . $API_VERSION . "/Resources/Regions.php");
$googleDocTitle = "API Request for Continent Data.";
}
/**
* Send the request to Google Analytics
*
* @author Johnathan Pulos
*/
/**
* Autoload the Google Analytics Class
*
* @author Johnathan Pulos
*/
if ($GOOGLE_TRACKING_ID != '') {
$googleAnalytics = new \PHPToolbox\GoogleAnalytics\GoogleAnalytics($GOOGLE_TRACKING_ID);
/**
* Construct the Payload
*/
if (isset($_SERVER['REQUEST_URI'])) {
$dp = $_SERVER['REQUEST_URI'];
} else {
$dp = '';
}
if ((isset($APIKey)) && ($APIKey != '')) {
$cid = $APIKey;
} else {
$cid = 'Site Visitor';
}
$payload = array(
'cid' => $cid,
't' => 'pageview',
'dh' => $DOMAIN_ADDRESS,
'dp' => $dp,
'dt' => $googleDocTitle
);
/**
* Send the payload
*/
$googleAnalytics->save($payload);
}
/**
* Now run the Slim Framework rendering
*
* @author Johnathan Pulos
*/
$app->run();
| MissionalDigerati/joshua_project_api | Public/index.php | PHP | gpl-3.0 | 8,989 |
/*****************************************************************************
* Copyright (C) 2004-2013 The PaGMO development team, *
* Advanced Concepts Team (ACT), European Space Agency (ESA) *
* http://apps.sourceforge.net/mediawiki/pagmo *
* http://apps.sourceforge.net/mediawiki/pagmo/index.php?title=Developers *
* http://apps.sourceforge.net/mediawiki/pagmo/index.php?title=Credits *
* act@esa.int *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
*****************************************************************************/
#include "hv4d.h"
namespace pagmo { namespace util { namespace hv_algorithm {
/// Compute hypervolume
/**
* @param[in] points vector of points containing the D-dimensional points for which we compute the hypervolume
* @param[in] r_point reference point for the points
*
* @return hypervolume.
*/
double hv4d::compute(std::vector<fitness_vector> &points, const fitness_vector &r_point) const
{
// Prepare the initial data to suit the original code
double* data = new double[points.size() * 4];
double refpoint[4];
for (unsigned int d_idx = 0 ; d_idx < 4 ; ++d_idx) {
refpoint[d_idx] = r_point[d_idx];
}
unsigned int data_idx = 0;
for (unsigned int p_idx = 0 ; p_idx < points.size() ; ++p_idx) {
for (unsigned int d_idx = 0 ; d_idx < 4 ; ++d_idx) {
data[data_idx++] = points[p_idx][d_idx];
}
}
double hv = guerreiro_hv4d(data, points.size(), refpoint);
delete[] data;
return hv;
}
/// Verify before compute
/**
* Verifies whether given algorithm suits the requested data.
*
* @param[in] points vector of points containing the 4-dimensional points for which we compute the hypervolume
* @param[in] r_point reference point for the vector of points
*
* @throws value_error when trying to compute the hypervolume for the non-maximal reference point
*/
void hv4d::verify_before_compute(const std::vector<fitness_vector> &points, const fitness_vector &r_point) const
{
if (r_point.size() != 4) {
pagmo_throw(value_error, "Algorithm HV4D works only for 4-dimensional cases");
}
base::assert_minimisation(points, r_point);
}
/// Clone method.
base_ptr hv4d::clone() const
{
return base_ptr(new hv4d(*this));
}
/// Algorithm name
std::string hv4d::get_name() const
{
return "Four-dimensional hypervolume by Andreia P. Guerreiro";
}
} } }
BOOST_CLASS_EXPORT_IMPLEMENT(pagmo::util::hv_algorithm::hv4d)
| jdiez17/pagmo | src/util/hv_algorithm/hv4d.cpp | C++ | gpl-3.0 | 3,656 |
// Dapplo - building blocks for desktop applications
// Copyright (C) 2016-2018 Dapplo
//
// For more information see: http://dapplo.net/
// Dapplo repositories are hosted on GitHub: https://github.com/dapplo
//
// This file is part of Dapplo.Dopy
//
// Dapplo.Dopy 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.
//
// Dapplo.Dopy 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 a copy of the GNU Lesser General Public License
// along with Dapplo.Dopy. If not, see <http://www.gnu.org/licenses/lgpl.txt>.
using Autofac;
using Dapplo.Addons;
using Dapplo.Dopy.Sharing.Services;
namespace Dapplo.Dopy.Sharing
{
/// <inheritdoc />
public class SharingAddonModule : AddonModule
{
/// <inheritdoc />
protected override void Load(ContainerBuilder builder)
{
builder
.RegisterType<ShareServer>()
.As<IService>()
.SingleInstance();
base.Load(builder);
}
}
}
| dapplo/Dapplo.Dopy | src/Dapplo.Dopy.Addon.Sharing/SharingAddonModule.cs | C# | gpl-3.0 | 1,448 |
"""Sis_legajos URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from Alumnos import views
from django.contrib.auth.views import login, logout
#from Alumnos.views import (
# ListaUsuarios,
# DetalleUsuario,
# CrearUsuario,
# ActualizarUsuario,
# EliminarUsuario,
# ListaMovimientos,
#)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^home/', views.home, name='Home'),
url(r'^home2/', views.home2, name='Home2'),
url(r'^busqueda_dni/$', views.busqueda_dni),
url(r'^busqueda_apellido/$', views.busqueda_apellido),
url(r'^busqueda_legajo/$', views.busqueda_legajo),
url(r'^legajo/([0-9]+)/$', views.alumno, name='vista_alumno'),
url(r'^nuevo_alumno/$', views.nuevo_alumno),
url(r'^editar_alumno/([0-9]+)$', views.editar_alumno),
url(r'^borrar_alumno/([0-9]+)/$', views.borrar_alumno,name="borrar_alumno"),
#url(r'^almacenar/$', views.almacenar),
url(r'^login/$',login,{'template_name':'login.html'}),
url(r'^logout/$',logout,{'template_name':'logout.html'}),
#seleccionar un alumno para poder moverlo
url(r'^seleccionar_alumno/$', views.seleccionar_alumno),
url(r'^mover_legajo_lugar/([0-9]+)/$', views.mover_legajo_lugar,name="mover_legajo_lugar"),
url(r'^mover_legajo_archivo/([0-9]+)/$', views.mover_legajo_archivo),
url(r'^mover_legajo_cajon/([0-9]+)/$', views.mover_legajo_cajon),
url(r'^confirmar_mover/([0-9]+)/([0-9]+)/([0-9]+)/$', views.confirmar_mover, name="confirmar_mover"),
#URLS Lugar
url(r'^nuevo_lugar/$', views.nuevo_lugar),
url(r'^lugar_borrar/([0-9]+)/$', views.borrar_lugar,name="borrar_lugar"),
#URLS Archivo
url(r'^nuevo_archivo/$', views.nuevo_archivo),
url(r'^archivo_borrar/([0-9]+)/$', views.borrar_archivo,name="borrar_archivo"),
#URLS par almacenar un legajo
url(r'^almacenar_legajo_lugar/([0-9]+)/$', views.almacenar_legajo_lugar,name="almacenar_legajo_lugar"),
url(r'^almacenar_legajo_archivo/([0-9]+)/$', views.almacenar_legajo_archivo),
url(r'^almacenar_legajo_cajon/([0-9]+)/$', views.almacenar_legajo_cajon),
url(r'^confirmar_almacenar/([0-9]+)/([0-9]+)/$', views.confirmar_almacenar, name="confirmar_almacenar"),
#url(r'^ver_movimientos/$', views.ver_movimientos),
#usuarios
# url(r'^usuarios/$', ListaUsuarios.as_view(), name='lista'),
# url(r'^usuarios/(?P<pk>\d+)$', DetalleUsuario.as_view(), name='detalle'),
# url(r'^usuarios/nuevo$', CrearUsuario.as_view(), name='nuevo'),
# url(r'^usuarios/editar/(?P<pk>\d+)$', ActualizarUsuario.as_view(),name='editar'),
# url(r'^usuarios/borrar/(?P<pk>\d+)$', EliminarUsuario.as_view(),name='borrar')
#corrección usuarios
#url(r'^$', ListaUsuarios.as_view(), name='lista'),
#url(r'^(?P<pk>\d+)$', DetalleUsuario.as_view(), name='detalle'),
#url(r'^nuevo$', CrearUsuario.as_view(), name='nuevo'),
#url(r'^editar/(?P<pk>\d+)$', ActualizarUsuario.as_view(),name='editar'),
#url(r'^borrar/(?P<pk>\d+)$', EliminarUsuario.as_view(),name='borrar')
#tercer intento
#url(r'^usuarios/', include('usuarios.urls', namespace='usuarios'))
url(r'^movimientos/$', views.ver_movimientos),
#ver mov viejo url(r'ver_movimientos/^$', ListaMovimientos.as_view(), name='listamovimientos')
url(r'^cursos/', include('courses.urls', namespace='courses'))
]
| Informatorio/Sis_LegajosV2 | Sis_legajos/urls.py | Python | gpl-3.0 | 3,985 |
/*
* Copyright (c) 2008, SQL Power Group Inc.
*
* This file is part of DQguru
*
* DQguru 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.
*
* DQguru 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 ca.sqlpower.matchmaker;
import java.math.BigDecimal;
import java.sql.Types;
import java.util.Date;
/**
* A class that contains a mapping of java.sql data types to Java class types that the
* MatchMaker munge steps support. At this point, the munge steps support BigDecimal,
* Date, Boolean, and String. This simplification of the datatypes is to greatly reduce
* the number of cases we need to handle in the munge process, and at this point, we do
* not feel such fine grained type handling is necessary.
*/
public class TypeMap {
/**
* Returns the Java class associated with the given SQL type code.
*
* @param type
* The type ID number. See {@link Types} for the official list.
* @return The class for the given type. Defaults to java.lang.String if the
* type code is unknown, since almost every SQL type can be
* represented as a string if necessary.
*/
public static Class<?> typeClass(int type) {
switch (type) {
case Types.VARCHAR:
case Types.VARBINARY:
case Types.STRUCT:
case Types.REF:
case Types.OTHER:
case Types.NULL:
case Types.LONGVARCHAR:
case Types.LONGVARBINARY:
case Types.JAVA_OBJECT:
case Types.DISTINCT:
case Types.DATALINK:
case Types.CLOB:
case Types.CHAR:
case Types.BLOB:
case Types.BINARY:
case Types.ARRAY:
default:
return String.class;
case Types.TINYINT:
case Types.SMALLINT:
case Types.REAL:
case Types.NUMERIC:
case Types.INTEGER:
case Types.FLOAT:
case Types.DOUBLE:
case Types.DECIMAL:
case Types.BIGINT:
return BigDecimal.class;
case Types.BIT:
case Types.BOOLEAN:
return Boolean.class;
case Types.TIMESTAMP:
case Types.TIME:
case Types.DATE:
return Date.class;
}
}
}
| SQLPower/power-matchmaker | src/ca/sqlpower/matchmaker/TypeMap.java | Java | gpl-3.0 | 2,747 |
using System;
using System.Globalization;
using System.Text;
namespace WolvenKit.Scaleform
{
/// <summary>
/// Class containing static text conversion functions.
/// </summary>
public sealed class ByteConversion
{
/// <summary>
/// Codepage value for Shift JIS (Jp)
/// </summary>
public const int CodePageJapan = 932;
/// <summary>
/// Codepage value for Cyrillic (US)
/// </summary>
public const int CodePageUnitedStates = 1251;
/// <summary>
/// Codepage value for OEM DOS
/// </summary>
public const int CodePageOEM = 437;
private ByteConversion() { }
/// <summary>
/// Get string from bytes.
/// </summary>
/// <param name="pBytes">Bytes to convert to a string.</param>
/// <param name="codePage">Codepage to use in converting bytes.</param>
/// <returns>String encoding using the input Codepage.</returns>
public static string GetEncodedText(byte[] value, int codePage)
{
//return Encoding.Unicode.GetString(value);
return System.Text.Encoding.GetEncoding(codePage).GetString(value);
}
/// <summary>
/// Get text encoded in Shift JIS
/// </summary>
/// <param name="pBytes">Bytes to decode.</param>
/// <returns>String encoded using the Shift JIS codepage.</returns>
public static string GetJapaneseEncodedText(byte[] value)
{
return GetEncodedText(value, CodePageJapan);
}
/// <summary>
/// Get text encoded in Cyrillic
/// </summary>
/// <param name="pBytes">Bytes to decode.</param>
/// <returns>String encoded using the Cyrillic codepage.</returns>
public static string GetUnitedStatesEncodedText(byte[] value)
{
return GetEncodedText(value, CodePageUnitedStates);
}
/// <summary>
/// Get text encoded in ASCII
/// </summary>
/// <param name="pBytes">Bytes to decode.</param>
/// <returns>String encoded using ASCII.</returns>
public static string GetAsciiText(byte[] value)
{
System.Text.Encoding ascii = System.Text.Encoding.ASCII;
return ascii.GetString(value);
}
/// <summary>
/// Get text encoded in ASCII, stops at null.
/// </summary>
/// <param name="pBytes">Bytes to decode.</param>
/// <param name="offset">Offet within byte array of string.</param>
/// <returns>String encoded using ASCII.</returns>
public static string GetAsciiText(byte[] value, long offset)
{
StringBuilder sb = new StringBuilder();
System.Text.Encoding ascii = System.Text.Encoding.ASCII;
for (long i = offset; i < value.Length; i++)
{
if (value[i] == 0)
{
break;
}
else
{
sb.Append((char)value[i]);
}
}
return sb.ToString();
}
public static string GetUtf16LeText(byte[] value)
{
System.Text.Encoding encoding = System.Text.Encoding.Unicode;
return encoding.GetString(value);
}
/// <summary>
/// Convert input string to a long. Works for Decimal and Hexidecimal (use 0x prefix).
/// </summary>
/// <param name="pStringNumber">String containing a Decimal and Hexidecimal number.</param>
/// <returns>Long representing the input string.</returns>
public static long GetLongValueFromString(string value)
{
long ret;
bool isNegative = false;
string parseValue;
if (value.StartsWith("-"))
{
parseValue = value.Substring(1);
isNegative = true;
}
else
{
parseValue = value;
}
if (parseValue.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase))
{
parseValue = parseValue.Substring(2);
ret = long.Parse(parseValue, System.Globalization.NumberStyles.HexNumber, null);
}
else
{
ret = long.Parse(parseValue, System.Globalization.NumberStyles.Integer, null);
}
if (isNegative)
{
ret *= -1;
}
return ret;
}
/// <summary>
/// Get the UInt32 Value of the Incoming Byte Array, which is in Big Endian order.
/// </summary>
/// <param name="pBytes">Bytes to convert.</param>
/// <returns>The UInt32 Value of the Incoming Byte Array.</returns>
public static UInt32 GetUInt32BigEndian(byte[] value)
{
byte[] workingArray = new byte[value.Length];
Array.Copy(value, 0, workingArray, 0, value.Length);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(workingArray);
}
return BitConverter.ToUInt32(workingArray, 0);
}
/// <summary>
/// Get the UInt16 Value of the Incoming Byte Array, which is in Big Endian order.
/// </summary>
/// <param name="pBytes">Bytes to convert.</param>
/// <returns>The UInt16 Value of the Incoming Byte Array.</returns>
public static UInt16 GetUInt16BigEndian(byte[] value)
{
byte[] workingArray = new byte[value.Length];
Array.Copy(value, 0, workingArray, 0, value.Length);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(workingArray);
}
return BitConverter.ToUInt16(workingArray, 0);
}
/// <summary>
/// Predicts Code Page between Cyrillic and Shift-JIS based on whether high ASCII is included or not.
/// </summary>
/// <param name="tagBytes">Bytes containing the tags in an unknown language.</param>
/// <returns>Integer representing the predicted code page.</returns>
public static int GetPredictedCodePageForTags(byte[] tagBytes)
{
int predictedCodePage = CodePageUnitedStates;
foreach (byte b in tagBytes)
{
if ((int)b > 0x7F)
{
predictedCodePage = CodePageJapan;
break;
}
}
return predictedCodePage;
}
public static byte GetHighNibble(byte value)
{
return (byte)(((value) >> 4) & 0x0F);
}
public static byte GetLowNibble(byte value)
{
return (byte)((value) & 0x0F); ;
}
public static byte[] GetBytesFromHexString(string hexValue)
{
int j = 0;
byte[] bytes = new byte[hexValue.Length / 2];
// convert the string to bytes
for (int i = 0; i < hexValue.Length; i += 2)
{
bytes[j] = BitConverter.GetBytes(Int16.Parse(hexValue.Substring(i, 2), System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture))[0];
j++;
}
return bytes;
}
public static byte[] GetBytesBigEndian(uint value)
{
byte[] ret = BitConverter.GetBytes(value);
Array.Reverse(ret);
return ret;
}
public static DateTime GetDateTimeFromFAT32Date(int value)
{
short xDate = (short)(value >> 0x10);
short xTime = (short)(value & 0xFFFF);
if (xDate == 0 && xTime == 0)
{
return DateTime.Now;
}
else
{
return new DateTime(
(((xDate & 0xFE00) >> 9) + 0x7BC),
((xDate & 0x1E0) >> 5),
(xDate & 0x1F),
((xTime & 0xF800) >> 0xB),
((xTime & 0x7E0) >> 5),
((xTime & 0x1F) * 2));
}
}
}
}
| DellCliff/Wolven-kit | W3Edit.Scaleform/ByteConversion.cs | C# | gpl-3.0 | 8,262 |
/*
LBSim: a fluid dynamics simulator using the lattice Boltzmann method
Copyright (C) 2013 Fabio Sussumu Komori - NDS/GNMD/LME/PSI/EP/USP
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
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shared.h"
#include "../../model/latticeboltzmann/gridconfig.h"
#include <QDebug>
Shared* Shared::newShared = 0;
Shared::Shared() {
}
Shared* Shared::instance() {
if (!newShared) {
newShared = new Shared();
}
return newShared;
}
GridConfig* Shared::getGridConfig() {
return gridConfig;
}
void Shared::setGridConfig(GridConfig *gridConfig) {
this->gridConfig = gridConfig;
}
| fabioskomori/lbsim | model/util/shared.cpp | C++ | gpl-3.0 | 1,202 |
/**
* Copyright 2020 The Pennsylvania State University
* @license Apache-2.0, see License.md for full text.
*/
import{LitElement as e,html as t,css as r}from"../../../lit/index.js";import{FutureTerminalTextLiteSuper as a}from"./FutureTerminalTextSuper.js";class FutureTerminalTextLite extends(a(e)){static get styles(){let e=r``;return super.styles&&(e=super.styles),[e,r`
:host {
font-weight: bold;
display: inline-flex;
--flicker-easing: cubic-bezier(0.32, 0.32, 0, 0.92);
--flicker-duration: 300ms;
--fade-in-duration: 500ms;
}
span {
color: #5fa4a5;
text-shadow: 0 0 4px #5fa4a5;
animation: flicker var(--flicker-duration) var(--flicker-easing);
}
:host([red]) span {
color: #b35b5a;
text-shadow: 0 0 4px #b35b5a;
}
:host([fadein]) span {
animation: fade-in var(--fade-in-duration),
flicker 300ms var(--flicker-easing)
calc(var(--fade-in-duration) * 0.8);
transform: translate(0, 0);
opacity: 1;
}
@keyframes flicker {
0% {
opacity: 0.75;
}
50% {
opacity: 0.45;
}
100% {
opacity: 1;
}
}
@keyframes fade-in {
from {
transform: translate(-30px, 0px);
opacity: 0;
}
}
`]}updated(e){super.updated&&super.updated(e),e.forEach(((e,t)=>{"glitch"===t&&this[t]&&this._doGlitch()}))}render(){return t`<span><slot></slot></span>`}static get properties(){return{...super.properties,glitch:{type:Boolean},red:{type:Boolean,reflect:!0},fadein:{type:Boolean,reflect:!0},glitchMax:{type:Number,attribute:"glitch-max"},glitchDuration:{type:Number,attribute:"glitch-duration"}}}static get tag(){return"future-terminal-text-lite"}}customElements.define(FutureTerminalTextLite.tag,FutureTerminalTextLite);export{FutureTerminalTextLite}; | elmsln/elmsln | core/dslmcode/cores/haxcms-1/build/es6/node_modules/@lrnwebcomponents/future-terminal-text/lib/future-terminal-text-lite.js | JavaScript | gpl-3.0 | 2,021 |
/* bender-tags: clipboard,pastefromword */
/* jshint ignore:start */
/* bender-ckeditor-plugins: pastefromword,ajax,basicstyles,bidi,font,link,toolbar,colorbutton,image */
/* bender-ckeditor-plugins: list,liststyle,sourcearea,format,justify,table,tableresize,tabletools,indent,indentblock,div,dialog */
/* jshint ignore:end */
/* bender-include: _lib/q.js,_helpers/promisePasteEvent.js,_lib/q.js,_helpers/assertWordFilter.js,_helpers/createTestCase.js,_helpers/pfwTools.js */
/* global createTestCase,pfwTools */
( function() {
'use strict';
pfwTools.defaultConfig.disallowedContent = 'span[lang,dir]';
bender.editor = {
config: pfwTools.defaultConfig
};
var browsers = [
'chrome',
'firefox',
'ie8',
'ie11'
],
wordVersion = 'word2013',
ticketTests = {
'7661Multilevel_lists': [ 'word2013' ],
'7696empty_table': [ 'word2013' ],
'7797fonts': [ 'word2013' ],
'7843Multi_level_Numbered_list': [ 'word2013' ],
'7857pasting_RTL_lists_from_word_defect': [ 'word2013' ],
'7872lists': [ 'word2013' ],
'7918Numbering': [ 'word2013' ],
'7950Sample_word_doc': [ 'word2013' ],
'8437WORD_ABC': [ 'word2013' ],
'8501FromWord': [ 'word2013' ],
'8665Tartalom': [ 'word2013' ],
'8734list_test2': [ 'word2013' ],
'8734list_test': [ 'word2013' ],
'8780ckeditor_tablebug_document': [ 'word2013' ],
'9144test': [ 'word2013' ],
'9274CKEditor_formating_issue': [ 'word2013' ],
'9330Sample_Anchor_Document': [ 'word2013' ],
'9331ckBugWord1': [ 'word2013' ],
'9340test_ckeditor': [ 'word2013' ],
'9422for_cke': [ 'word2013' ],
'9426CK_Sample_word_document': [ 'word2013' ],
'9456Stuff_to_get': [ 'word2013' ],
'9456text-with-bullet-list-example': [ 'word2013' ],
'9475list2003': [ 'word2013' ],
'9475List2010': [ 'word2013' ],
'9616word_table': [ 'word2013' ],
'9685ckeditor_tablebug_document': [ 'word2013' ],
'9685testResumeTest': [ 'word2013' ]
},
testData = {
_should: {
ignore: {}
}
},
ticketKeys = CKEDITOR.tools.objectKeys( ticketTests ),
i, k;
for ( i = 0; i < ticketKeys.length; i++ ) {
for ( k = 0; k < browsers.length; k++ ) {
if ( ticketTests[ ticketKeys[ i ] ] === true || CKEDITOR.tools.indexOf( ticketTests[ ticketKeys[ i ] ], wordVersion ) !== -1 ) {
var testName = [ 'test', ticketKeys[ i ], wordVersion, browsers[ k ] ].join( ' ' );
if ( CKEDITOR.env.ie && CKEDITOR.env.version <= 11 ) {
testData._should.ignore[ testName ] = true;
}
testData[ testName ] = createTestCase( ticketKeys[ i ], wordVersion, browsers[ k ], true );
}
}
}
bender.test( testData );
} )();
| Mediawiki-wysiwyg/WYSIWYG-CKeditor | WYSIWYG/ckeditor_source/tests/plugins/pastefromword/generated/tickets4.js | JavaScript | gpl-3.0 | 2,627 |
package fluddokt.opsu.fake;
import java.net.URL;
public class MultiClip extends Clip{
public MultiClip(String path) {
super(path);
}
public MultiClip(URL url, boolean isMP3, LineListener listener) {
super(url, isMP3, listener);
}
public static void destroyExtraClips() {
// TODO Auto-generated method stub
}
}
| fluddokt/opsu | src/fluddokt/opsu/fake/MultiClip.java | Java | gpl-3.0 | 353 |
#include "Logger.h"
#include <sys/time.h>
#include <unistd.h>
// Global static pointer used to ensure a single instance of the class.
Logger* Logger::m_pInstance = NULL;
pthread_mutex_t Logger::mMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t Logger::mWriteMutex = PTHREAD_MUTEX_INITIALIZER;
Logger::GC Logger::gc;
/** This function is called to create an instance of the class.
Calling the constructor publicly is not allowed. The constructor
is private and is only called by this Instance function.
*/
Logger& Logger::Instance()
{
if (NULL == m_pInstance) // Only allow one instance of class to be generated.
{
pthread_mutex_lock(&mMutex);
if (!m_pInstance) // Only allow one instance of class to be generated.
{
m_pInstance = new Logger();
}
pthread_mutex_unlock(&mMutex);
}
return *m_pInstance;
}
Logger::Logger()
{
std::cout << "Logger::Logger" << std::endl;
mConsumeThread = new ConsumeThread(mQueue, mConfiger);
mConsumeThread->start();
}
void Logger::loadConfigFile(const std::string &_ConfigFilePath)
{
mConfiger.LoadFile(_ConfigFilePath.c_str());
int fmMaxLogFileCount = mConfiger.GetLongValue("Logger", "MaxLogFileCount", 10);
long fmMaxLogFileSize = mConfiger.GetLongValue("Logger", "MaxLogFileSize", 100);
std::cout << "Logger::Logger: fmMaxLogFileCount: " << fmMaxLogFileCount << std::endl;
std::cout << "Logger::Logger: fmMaxLogFileSize: " << fmMaxLogFileSize << std::endl;
mConfiger.setMaxLogFileSize(fmMaxLogFileSize);
mConfiger.setMaxLogFileCount(fmMaxLogFileCount);
}
void Logger::setMaxLogFileSize(long _Size)
{
mConfiger.setMaxLogFileSize(_Size);
}
void Logger::setMaxLogFileCount(int _Count)
{
mConfiger.setMaxLogFileCount(_Count);
}
void Logger::dumpConfiger()
{
mConfiger.dumpConfiger();
}
void Logger::addLogID(const std::string &_LogID, const std::string &_LogFileName)
{
mConfiger.addLogID(_LogID, _LogFileName);
}
Logger& Logger::operator <<(Logger& (*pfunc)(Logger &_Logger))
{
return pfunc(*this);
}
void Logger::writeLogToFile()
{
unsigned long tmpThreadID = pthread_self();
std::string tmpLoggerContect = mLSList[tmpThreadID]->toString()+"\n";
mQueue.add(tmpLoggerContect);
mLSList[tmpThreadID]->clear();
}
//convert: 2014-7-31 17:26:57>>[CRITICAL] Test critical logger!!! >> Test critical logger!!!
std::string Logger::getTime()
{
std::stringstream date_stream;
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
struct tm *ti = localtime(&tv.tv_sec);;
char timeBuf[50];
strftime(timeBuf, sizeof(timeBuf)/sizeof(timeBuf[0]), "%Y-%m-%d/%H:%M:%S", ti);
int musec = tv.tv_usec/1000;
char millisecBuf[5];
sprintf(millisecBuf, "%03d", musec);
date_stream << timeBuf << "." << millisecBuf;
return date_stream.str();
}
std::string Logger::getLevelMarker(LEVEL level)
{
std::string tmp_marker;
switch(level)
{
case Logger::critical:
return MARKER_CRITICAL;
break;
case Logger::information:
return MARKER_INFORMATION;
break;
case Logger::warnning:
return MARKER_WARNNING;
break;
case Logger::error:
return MARKER_ERROR;
break;
case Logger::debug:
return MARKER_DEBUG;
case Logger::nolevel:
return MARKER_NOLEVEL;
break;
default:
break;
}
return tmp_marker;
}
void Logger::makeLogHeader(LEVEL _Level)
{
*this << SEPARATOR;
*this << getTime();
*this << SEPARATOR;
*this << getLevelMarker(_Level);
*this << SEPARATOR;
}
std::string Logger::getString()
{
return mLSList[pthread_self()]->toString();
}
//flags
Logger& INFO(Logger& _Logger)
{
_Logger.makeLogHeader(Logger::information);
return _Logger;
}
Logger& WARNNING(Logger& _Logger)
{
_Logger.makeLogHeader(Logger::warnning);
return _Logger;
}
Logger& ERROR(Logger& _Logger)
{
_Logger.makeLogHeader(Logger::error);
return _Logger;
}
Logger& CRITICAL(Logger& _Logger)
{
_Logger.makeLogHeader(Logger::critical);
return _Logger;
}
Logger& DEBUG(Logger& _Logger)
{
_Logger.makeLogHeader(Logger::debug);
return _Logger;
}
Logger& NOLEVEL(Logger& _Logger)
{
_Logger.makeLogHeader(Logger::nolevel);
return _Logger;
}
Logger& END_LOGGER(Logger& _Logger)
{
_Logger.writeLogToFile();
return _Logger;
}
Logger& SETID(Logger& _Logger)
{
return _Logger;
}
Logger::~Logger()
{
std::map<unsigned long, LogStream *>::iterator it = mLSList.begin();
for(; it != mLSList.end(); it++)
{
if(it->second != NULL)
{
std::cout << "*********delete thread id: " << it->first << std::endl;
delete it->second;
//mLSList.erase(it->first);
}
}
if(mConsumeThread!= NULL)
{
delete mConsumeThread;
}
pthread_mutex_destroy(&mMutex);
pthread_mutex_destroy(&mWriteMutex);
}
| freeman0508/jlogger | libsrc/Logger.cpp | C++ | gpl-3.0 | 4,964 |
/**
* OSGi/JEE Sample.
*
* Copyright (C) 2014 Goulwen Le Fur
*
* 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.
* 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 osgi.jee.samples.jpa.db.derby.internal.datasource;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.XADataSource;
import org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource40;
import org.apache.derby.jdbc.EmbeddedDataSource40;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.apache.derby.jdbc.EmbeddedXADataSource;
import org.apache.derby.jdbc.ReferenceableDataSource;
import org.osgi.service.jdbc.DataSourceFactory;
/**
* @author <a href="mailto:goulwen.lefur@gmail.com">Goulwen Le Fur</a>.
*
*/
public class DerbyDataSourceFactory implements DataSourceFactory {
/**
* {@inheritDoc}
* @see org.osgi.service.jdbc.DataSourceFactory#createDataSource(java.util.Properties)
*/
public DataSource createDataSource(Properties props) throws SQLException {
EmbeddedDataSource40 ds = new EmbeddedDataSource40();
if (props.get("url") != null && ((String)props.get("url")).endsWith(";create=true")) {
ds.setCreateDatabase("create");
}
setProperties(ds, props);
return ds;
}
/**
* {@inheritDoc}
* @see org.osgi.service.jdbc.DataSourceFactory#createConnectionPoolDataSource(java.util.Properties)
*/
public ConnectionPoolDataSource createConnectionPoolDataSource(Properties props) throws SQLException {
EmbeddedConnectionPoolDataSource40 ds = new EmbeddedConnectionPoolDataSource40();
setProperties(ds, props);
return ds;
}
/**
* {@inheritDoc}
* @see org.osgi.service.jdbc.DataSourceFactory#createXADataSource(java.util.Properties)
*/
public XADataSource createXADataSource(Properties props) throws SQLException {
EmbeddedXADataSource ds = new EmbeddedXADataSource();
setProperties(ds, props);
return ds;
}
/**
* {@inheritDoc}
* @see org.osgi.service.jdbc.DataSourceFactory#createDriver(java.util.Properties)
*/
public Driver createDriver(Properties props) throws SQLException {
EmbeddedDriver driver = new EmbeddedDriver();
return driver;
}
private void setProperties(ReferenceableDataSource ds, Properties properties) throws SQLException {
Properties props = (Properties) properties.clone();
String databaseName = (String) props.remove(DataSourceFactory.JDBC_DATABASE_NAME);
if (databaseName == null) {
String url = (String) props.remove("url");
databaseName = extractDBNameFromUrl(url);
}
ds.setDatabaseName(databaseName);
String password = (String) props.remove(DataSourceFactory.JDBC_PASSWORD);
ds.setPassword(password);
String user = (String) props.remove(DataSourceFactory.JDBC_USER);
ds.setUser(user);
if (!props.isEmpty()) {
throw new SQLException("cannot set properties " + props.keySet());
}
}
private String extractDBNameFromUrl(String url) {
if (url != null && !url.isEmpty()) {
String derbyURL = url;
if (derbyURL.endsWith(";create=true")) {
derbyURL = derbyURL.substring("jdbc:derby:".length(), derbyURL.length() - ";create=true".length());
} else {
derbyURL = derbyURL.substring("jdbc:derby:".length());
}
return derbyURL;
}
return "memory:default";
}
}
| glefur/osgi-jee | jpa/bundles/osgi.jee.samples.jpa.db.derby/src/main/java/osgi/jee/samples/jpa/db/derby/internal/datasource/DerbyDataSourceFactory.java | Java | gpl-3.0 | 3,811 |
namespace phoenix {
struct pHorizontalSlider : public pWidget {
HorizontalSlider& horizontalSlider;
unsigned position();
void setLength(unsigned length);
void setPosition(unsigned position);
pHorizontalSlider(HorizontalSlider& horizontalSlider) : pWidget(horizontalSlider), horizontalSlider(horizontalSlider) {}
void constructor();
void destructor();
};
}
| ChoccyHobNob/DiCE | phoenix/reference/widget/horizontal-slider.hpp | C++ | gpl-3.0 | 374 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2016 Evan Debenham
*
* Lovecraft Pixel Dungeon
* Copyright (C) 2016-2017 Leon Horn
*
* Plugin Pixel Dungeon
* Copyright (C) 2017 Leon Horn
*
* 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 eben the implied warranty of
* GNU General Public License for more details.
*
* You should have have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses>
*/
package com.pluginpixel.pluginpixeldungeon.actors.mobs.npcs;
import com.pluginpixel.pluginpixeldungeon.Dungeon;
import com.pluginpixel.pluginpixeldungeon.effects.CellEmitter;
import com.pluginpixel.pluginpixeldungeon.effects.Speck;
import com.pluginpixel.pluginpixeldungeon.effects.particles.ElmoParticle;
import com.pluginpixel.pluginpixeldungeon.items.Heap;
import com.pluginpixel.pluginpixeldungeon.messages.Messages;
import com.pluginpixel.pluginpixeldungeon.sprites.ImpSprite;
public class ImpShopkeeper extends Shopkeeper {
{
spriteClass = ImpSprite.class;
}
private boolean seenBefore = false;
@Override
protected boolean act() {
if (!seenBefore && Dungeon.visible[pos]) {
yell( Messages.get(this, "greetings", Dungeon.hero.givenName() ) );
seenBefore = true;
}
return super.act();
}
@Override
public void flee() {
for (Heap heap: Dungeon.level.heaps.values()) {
if (heap.type == Heap.Type.FOR_SALE) {
CellEmitter.get( heap.pos ).burst( ElmoParticle.FACTORY, 4 );
heap.destroy();
}
}
destroy();
sprite.emitter().burst( Speck.factory( Speck.WOOL ), 15 );
sprite.killAndErase();
}
}
| TypedScroll/PluginPixelDungeon | core/src/main/java/com/pluginpixel/pluginpixeldungeon/actors/mobs/npcs/ImpShopkeeper.java | Java | gpl-3.0 | 2,001 |
package ru.log_inil.mc.minedonate.gui;
import net.minecraft.util.ResourceLocation;
public class GuiStaticVariables {
public static final ResourceLocation buttonTextures = new ResourceLocation ( "textures/gui/widgets.png" ) ;
public static final ResourceLocation scrollTextures = new ResourceLocation ( "textures/gui/options_background.png" ) ;
public static int guiGradientTextField_GradientStartColor = 1761673473 ;
public static int guiGradientTextField_GradientEndColor = 0 ;
public static int guiGradientTextField_BgRectColor0 = -6250336 ;
public static int guiGradientTextField_BgRectColor1 = -16777216 ;
public static int guiGradientTextField_HolderColor = 14737632 ;
}
| Pishka/MineDonate | forge 1.7.10/src/main/java/ru/log_inil/mc/minedonate/gui/GuiStaticVariables.java | Java | gpl-3.0 | 705 |
package ru.isalnikov.bmw;
import java.util.HashSet;
import java.util.Set;
import static java.util.stream.Collectors.toList;
import java.util.stream.Stream;
/**
* if we give two strings ? could yoe determine if they share a common substring?
* Don't foget that a substring may be as small as one character. For example the worlds "a" , "and" "art" share the common substring "a"
*
The words "be" and "cat" do not share a substring/
* Ready ti work out the answer ?
*
* @author Igor Salnikov isalnikov.com
*/
public class NewMain {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Stream.of("hello".split("")).forEach(System.out::println);
}
public static String twoStrings(String s1, String s2) {
Set<Character> set1 = new HashSet(s1.chars().mapToObj(c -> (char) c).collect(toList()));
char[] chars = s2.toCharArray();
for (char aChar : chars) {
if (set1.contains(aChar)) {
return "YES";
}
}
return "NO";
// Set<Character> set1 = new HashSet(s1.chars().mapToObj(c -> (char) c).collect(toList()));
// Set<Character> set2 = new HashSet(s2.chars().mapToObj(c -> (char) c).collect(toList()));
// TODO ???
// if (set1.retainAll(set2)) {
// return "YES";
// }
//
// return "NO";
//
// }
}
}
| isalnikov/ACMP | src/main/java/ru/isalnikov/bmw/NewMain.java | Java | gpl-3.0 | 1,500 |
<?php
/**
* Copyright (c) 2017 JD Williams
*
* This file is part of Unify, a PHP testing framework built by JD Williams. Unify 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.
*
* Unify is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You should have received a copy of the GNU General Public License along with Unify. If not, see
* <http://www.gnu.org/licenses/>.
*/
namespace JDWil\Unify\Exception;
class XdebugException extends UnifyException {}
| jdwil/unify | src/Exception/XdebugException.php | PHP | gpl-3.0 | 972 |
<?php
namespace CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* CoreBundle\Entity\GeneradorEolico
*
* @ORM\Entity
* @ORM\Table(name="Aerogenerador")
*
*/
class Aerogenerador
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $marca
*
* @ORM\Column(name="marca", type="string", length=100)
* @Assert\NotBlank(
* message="Este campo es obligatorio!"
* )
*/
private $marca;
/**
* @var integer $potenciaUnitaria
*
* @ORM\Column(name="potenciaUnitaria", type="decimal", precision=10, scale=2)
* @Assert\NotBlank(
* message="Este campo es obligatorio!"
* )
* @Assert\Type(
* type="numeric",
* message="El valor no es válido!"
* )
* @Assert\GreaterThan(
* value = 0,
* message="El valor debe ser mayor a 0!"
* )
*/
private $potenciaUnitaria;
/**
* @var integer $cantidad
*
* @ORM\Column(name="cantidad", type="integer")
* @Assert\NotBlank(
* message="Este campo es obligatorio!"
* )
* @Assert\Type(
* type="integer",
* message="El valor no es válido!"
* )
* @Assert\GreaterThan(
* value = 0
* )
*/
private $cantidad;
/**
* @var integer $eficiencia
*
* @ORM\Column(name="eficiencia", type="decimal", precision=10, scale=2)
* @Assert\NotBlank(
* message="Este campo es obligatorio!"
* )
* @Assert\Type(
* type="integer",
* message="El valor no es válido!"
* )
* @Assert\GreaterThan(
* value = 0
* )
*/
private $eficiencia;
/**
* @ORM\ManyToOne(targetEntity="Eolica", inversedBy="aerogeneradores")
* @ORM\JoinColumn(name="tecnologia", referencedColumnName="id", onDelete="CASCADE")
*/
private $tecnologia;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set marca
*
* @param string $marca
*
* @return GeneradorEolico
*/
public function setMarca($marca)
{
$this->marca = $marca;
return $this;
}
/**
* Get marca
*
* @return string
*/
public function getMarca()
{
return $this->marca;
}
/**
* Set potenciaUnitaria
*
* @param integer $potenciaUnitaria
*
* @return GeneradorEolico
*/
public function setPotenciaUnitaria($potenciaUnitaria)
{
$this->potenciaUnitaria = $potenciaUnitaria;
return $this;
}
/**
* Get potenciaUnitaria
*
* @return integer
*/
public function getPotenciaUnitaria()
{
return $this->potenciaUnitaria;
}
/**
* Set cantidad
*
* @param integer $cantidad
*
* @return GeneradorEolico
*/
public function setCantidad($cantidad)
{
$this->cantidad = $cantidad;
return $this;
}
/**
* Get cantidad
*
* @return integer
*/
public function getCantidad()
{
return $this->cantidad;
}
/**
* Set eficiencia
*
* @param integer $eficiencia
*
* @return GeneradorEolico
*/
public function setEficiencia($eficiencia)
{
$this->eficiencia = $eficiencia;
return $this;
}
/**
* Get eficiencia
*
* @return integer
*/
public function getEficiencia()
{
return $this->eficiencia;
}
/**
* Set tecnologia
*
* @param \CoreBundle\Entity\Eolica $tecnologia
*
* @return GeneradorEolico
*/
public function setTecnologia(\CoreBundle\Entity\Eolica $tecnologia = null)
{
$this->tecnologia = $tecnologia;
return $this;
}
/**
* Get tecnologia
*
* @return \CoreBundle\Entity\Eolica
*/
public function getTecnologia()
{
return $this->tecnologia;
}
}
| gmqz/proinged | src/CoreBundle/Entity/Aerogenerador.php | PHP | gpl-3.0 | 4,288 |
<?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/>.
/**
* Subplugin info class.
*
* @package mod_sharedresource
* @copyright 2014 Valery Fremaux (valery.Fremaux@gmail.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace mod_sharedresource\plugininfo;
use core\plugininfo\base, core_plugin_manager, moodle_url;
defined('MOODLE_INTERNAL') || die();
class sharedmetadata extends base {
/**
* Finds all enabled plugins, the result may include missing plugins.
* @return array|null of enabled plugins $pluginname=>$pluginname, null means unknown
*/
public static function get_enabled_plugins() {
global $DB;
$plugins = core_plugin_manager::instance()->get_installed_plugins('sharedmetadata');
if (!$plugins) {
return array();
}
$installed = array();
foreach ($plugins as $plugin => $version) {
$installed[] = 'sharedmetadata_'.$plugin;
}
list($installed, $params) = $DB->get_in_or_equal($installed, SQL_PARAMS_NAMED);
$disabled = $DB->get_records_select('config_plugins', "plugin $installed AND name = 'disabled'", $params, 'plugin ASC');
foreach ($disabled as $conf) {
if (empty($conf->value)) {
continue;
}
list($type, $name) = explode('_', $conf->plugin, 2);
unset($plugins[$name]);
}
$enabled = array();
foreach ($plugins as $plugin => $version) {
$enabled[$plugin] = $plugin;
}
return $enabled;
}
public function is_uninstall_allowed() {
return true;
}
/**
* Pre-uninstall hook.
* @private
*/
public function uninstall_cleanup() {
global $DB;
parent::uninstall_cleanup();
}
public function get_settings_section_name() {
return $this->type . '_' . $this->name;
}
/**
* Loads plugin settings to the settings tree
*
* This function usually includes settings.php file in plugins folder.
* Alternatively it can create a link to some settings page (instance of admin_externalpage)
*
* @param \part_of_admin_tree $adminroot
* @param string $parentnodename
* @param bool $hassiteconfig whether the current user has moodle/site:config capability
*/
public function load_settings(\part_of_admin_tree $adminroot, $parentnodename, $hassiteconfig) {
global $CFG, $USER, $DB, $OUTPUT, $PAGE; // In case settings.php wants to refer to them.
$ADMIN = $adminroot; // May be used in settings.php.
$plugininfo = $this; // Also can be used inside settings.php.
if (!$this->is_installed_and_upgraded()) {
return;
}
if (!$hassiteconfig or !file_exists($this->full_path('settings.php'))) {
return;
}
$section = $this->get_settings_section_name();
$settings = new \admin_settingpage($section, $this->displayname, 'moodle/site:config', $this->is_enabled() === false);
if ($adminroot->fulltree) {
$shortsubtype = $this->type;
include($this->full_path('settings.php'));
}
$adminroot->add($this->type . 'plugins', $settings);
}
}
| nitro2010/moodle | mod/sharedresource/classes/plugininfo/sharedmetadata.php | PHP | gpl-3.0 | 3,924 |
using CMS.Code;
using CMS.Data.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
namespace CMS.Data
{
public class SqlServerRepositoryBase : IRepositoryBase, IDisposable
{
private SqlServerCMSDbContext dbcontext = new SqlServerCMSDbContext();
private DbTransaction dbTransaction { get; set; }
public IRepositoryBase BeginTrans()
{
DbConnection dbConnection = ((IObjectContextAdapter)dbcontext).ObjectContext.Connection;
if (dbConnection.State == ConnectionState.Closed)
{
dbConnection.Open();
}
dbTransaction = dbConnection.BeginTransaction();
return this;
}
public int Commit()
{
try
{
var returnValue = dbcontext.SaveChanges();
if (dbTransaction != null)
{
dbTransaction.Commit();
}
return returnValue;
}
catch (Exception)
{
if (dbTransaction != null)
{
this.dbTransaction.Rollback();
}
throw;
}
finally
{
this.Dispose();
}
}
public void Dispose()
{
if (dbTransaction != null)
{
this.dbTransaction.Dispose();
}
this.dbcontext.Dispose();
}
public int Insert<TEntity>(TEntity entity) where TEntity : class
{
VerifyExtension.Verity(entity);
dbcontext.Entry<TEntity>(entity).State = EntityState.Added;
return dbTransaction == null ? this.Commit() : 0;
}
public int Insert<TEntity>(List<TEntity> entitys) where TEntity : class
{
foreach (var entity in entitys)
{
VerifyExtension.Verity(entity);
dbcontext.Entry<TEntity>(entity).State = EntityState.Added;
}
return dbTransaction == null ? this.Commit() : 0;
}
public int Update<TEntity>(TEntity entity) where TEntity : class
{
VerifyExtension.Verity(entity);
dbcontext.Set<TEntity>().Attach(entity);
PropertyInfo[] props = entity.GetType().GetProperties();
foreach (PropertyInfo prop in props)
{
NotMappedAttribute notMapped = Attribute.GetCustomAttribute(prop, typeof(NotMappedAttribute)) as NotMappedAttribute;
if (notMapped == null)
{
if (prop.GetValue(entity, null) != null)
{
if (prop.GetValue(entity, null).ToString() == " ")
dbcontext.Entry(entity).Property(prop.Name).CurrentValue = null;
dbcontext.Entry(entity).Property(prop.Name).IsModified = true;
}
}
}
return dbTransaction == null ? this.Commit() : 0;
}
public int Delete<TEntity>(TEntity entity) where TEntity : class
{
dbcontext.Set<TEntity>().Attach(entity);
dbcontext.Entry<TEntity>(entity).State = EntityState.Deleted;
return dbTransaction == null ? this.Commit() : 0;
}
public int Delete<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
var entitys = dbcontext.Set<TEntity>().Where(predicate).ToList();
entitys.ForEach(m => dbcontext.Entry<TEntity>(m).State = EntityState.Deleted);
return dbTransaction == null ? this.Commit() : 0;
}
public int DeleteById<TEntity>(TEntity entity) where TEntity : class
{
RemoveHoldingEntityInContext(entity);
//var entity = this as IDeleteAudited;
dbcontext.Set<TEntity>().Attach(entity);
PropertyInfo[] props = entity.GetType().GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.Name.ToLower() == "DeleteMark".ToLower())
{
dbcontext.Entry(entity).Property(prop.Name).CurrentValue = true;
dbcontext.Entry(entity).Property(prop.Name).IsModified = true;
}
if (prop.Name.ToLower() == "DeleteUserId".ToLower())
{
var LoginInfo = SysLoginObjHelp.sysLoginObjHelp.GetOperator();
if (LoginInfo != null)
{
dbcontext.Entry(entity).Property(prop.Name).CurrentValue = LoginInfo.UserId;
dbcontext.Entry(entity).Property(prop.Name).IsModified = true;
}
}
if (prop.Name.ToLower() == "DeleteTime".ToLower())
{
dbcontext.Entry(entity).Property(prop.Name).CurrentValue = DateTime.Now;
dbcontext.Entry(entity).Property(prop.Name).IsModified = true;
}
}
return dbTransaction == null ? this.Commit() : 0;
}
public int DeleteById<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
var entitys = dbcontext.Set<TEntity>().Where(predicate).ToList();
for (int i = 0; i < entitys.Count; i++)
{
RemoveHoldingEntityInContext(entitys[i]);
dbcontext.Set<TEntity>().Attach(entitys[i]);
PropertyInfo[] props = entitys[i].GetType().GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.Name.ToLower() == "DeleteMark".ToLower())
{
dbcontext.Entry(entitys[i]).Property(prop.Name).CurrentValue = true;
dbcontext.Entry(entitys[i]).Property(prop.Name).IsModified = true;
}
if (prop.Name.ToLower() == "DeleteUserId".ToLower())
{
//var LoginInfo = OperatorProvider.Provider.GetCurrent();
var LoginInfo = SysLoginObjHelp.sysLoginObjHelp.GetOperator();
if (LoginInfo != null)
{
dbcontext.Entry(entitys[i]).Property(prop.Name).CurrentValue = LoginInfo.UserId;
dbcontext.Entry(entitys[i]).Property(prop.Name).IsModified = true;
}
}
if (prop.Name.ToLower() == "DeleteTime".ToLower())
{
dbcontext.Entry(entitys[i]).Property(prop.Name).CurrentValue = DateTime.Now;
dbcontext.Entry(entitys[i]).Property(prop.Name).IsModified = true;
}
}
}
return dbTransaction == null ? this.Commit() : 0;
}
public TEntity FindEntity<TEntity>(object keyValue) where TEntity : class
{
return dbcontext.Set<TEntity>().Find(keyValue);
}
public TEntity FindEntity<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
return dbcontext.Set<TEntity>().FirstOrDefault(predicate);
}
public IQueryable<TEntity> IQueryable<TEntity>() where TEntity : class
{
return dbcontext.Set<TEntity>();
}
public IQueryable<TEntity> IQueryable<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
return dbcontext.Set<TEntity>().Where(predicate);
}
public List<TEntity> FindList<TEntity>(string strSql) where TEntity : class
{
return dbcontext.Database.SqlQuery<TEntity>(strSql).ToList<TEntity>();
}
public List<TEntity> FindList<TEntity>(string strSql, DbParameter[] dbParameter) where TEntity : class
{
return dbcontext.Database.SqlQuery<TEntity>(strSql, dbParameter).ToList<TEntity>();
}
public List<TEntity> FindList<TEntity>(Pagination pagination) where TEntity : class,new()
{
bool isAsc = pagination.sord.ToLower() == "asc" ? true : false;
string[] _order = pagination.sidx.Split(',');
MethodCallExpression resultExp = null;
var tempData = dbcontext.Set<TEntity>().AsQueryable();
foreach (string item in _order)
{
string _orderPart = item;
_orderPart = Regex.Replace(_orderPart, @"\s+", " ");
string[] _orderArry = _orderPart.Split(' ');
string _orderField = _orderArry[0];
bool sort = isAsc;
if (_orderArry.Length == 2)
{
isAsc = _orderArry[1].ToUpper() == "ASC" ? true : false;
}
var parameter = Expression.Parameter(typeof(TEntity), "t");
var property = typeof(TEntity).GetProperty(_orderField);
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
resultExp = Expression.Call(typeof(Queryable), isAsc ? "OrderBy" : "OrderByDescending", new Type[] { typeof(TEntity), property.PropertyType }, tempData.Expression, Expression.Quote(orderByExp));
}
tempData = tempData.Provider.CreateQuery<TEntity>(resultExp);
pagination.records = tempData.Count();
tempData = tempData.Skip<TEntity>(pagination.rows * (pagination.page - 1)).Take<TEntity>(pagination.rows).AsQueryable();
return tempData.ToList();
}
public List<TEntity> FindList<TEntity>(Expression<Func<TEntity, bool>> predicate, Pagination pagination) where TEntity : class,new()
{
bool isAsc = pagination.sord.ToLower() == "asc" ? true : false;
string[] _order = pagination.sidx.Split(',');
MethodCallExpression resultExp = null;
var tempData = dbcontext.Set<TEntity>().Where(predicate);
foreach (string item in _order)
{
string _orderPart = item;
_orderPart = Regex.Replace(_orderPart, @"\s+", " ");
string[] _orderArry = _orderPart.Split(' ');
string _orderField = _orderArry[0];
bool sort = isAsc;
if (_orderArry.Length == 2)
{
isAsc = _orderArry[1].ToUpper() == "ASC" ? true : false;
}
var parameter = Expression.Parameter(typeof(TEntity), "t");
var property = typeof(TEntity).GetProperty(_orderField);
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
resultExp = Expression.Call(typeof(Queryable), isAsc ? "OrderBy" : "OrderByDescending", new Type[] { typeof(TEntity), property.PropertyType }, tempData.Expression, Expression.Quote(orderByExp));
}
tempData = tempData.Provider.CreateQuery<TEntity>(resultExp);
pagination.records = tempData.Count();
tempData = tempData.Skip<TEntity>(pagination.rows * (pagination.page - 1)).Take<TEntity>(pagination.rows).AsQueryable();
return tempData.ToList();
}
//用于监测Context中的Entity是否存在,如果存在,将其Detach,防止出现问题。
private Boolean RemoveHoldingEntityInContext<TEntity>(TEntity entity) where TEntity : class
{
var objContext = ((IObjectContextAdapter)dbcontext).ObjectContext;
var objSet = objContext.CreateObjectSet<TEntity>();
var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, entity);
Object foundEntity;
var exists = objContext.TryGetObjectByKey(entityKey, out foundEntity);
if (exists)
{
objContext.Detach(foundEntity);
}
return (exists);
}
}
}
| gongthub/CMS | Code/CMS/CMS.Data/Repository/SqlServerRepositoryBase.cs | C# | gpl-3.0 | 12,588 |
Ext.define('Surveyportal.view.reportui.datachart.chart.ChartController', {
extend : 'Ext.app.ViewController',
alias : 'controller.chartController',
reportView : null,
reportViewController : null,
reportJSON : null,
defaultIncHeight:100,
init : function() {
this.control({
"button": {
click:this.filterdaterangedata,
},
});
},
initObject : function() {
this.reportViewController = this.reportView.controller;
this.reportJSON = this.reportView.reportJSON;
var clayout=this.getView().down("#chartcolumnlayout");
if(this.reportJSON != undefined && this.reportJSON.defaultCColumn!=undefined && this.reportJSON.defaultCColumn.toString().length>0){
clayout.value=this.reportJSON.defaultCColumn;
clayout.minLength=this.reportJSON.defaultCColumn;
}
},
afterRender:function(){
if(this.numberofcharts <= 1){
if(this.getView().down("#chartcolumnlayout")!= null){
this.getView().down("#chartcolumnlayout").hide();
}
}
},
loadCharts : function(charts) {
this.initObject();
this.getView().removeAll();
this.numberofcharts=charts.length;
if(charts.length <= 1){
if(this.getView().down("#chartcolumnlayout")!= null){
this.getView().down("#chartcolumnlayout").hide();
}
}
var fusionchart;
// var charts= this.chartDatas
if(charts.length > 0)
{
for (var x = 0; x < charts.length; x++) {
if(charts[x].hasOwnProperty("group") && charts[x].group == true){
this.loadGroupCharts(charts[x].groupCharts,charts[x]);
}else{
panel = this.getView().add({
xtype : "panel",
title:charts[x].chartTitle,
height : charts[x].height * 1 +this.defaultIncHeight,
group:false,
margin : '5 5 0 0',
chartJSON : charts[x],
listeners : {
afterrender : 'loadfusionchart'
}
});
}
}
}
else
{
this.getView().hide();
}
this.getView().doLayout();
this.resizeCharts(this.getView().down("#chartcolumnlayout"));
},
loadGroupCharts:function(groupcharts,chart){
var charts=[]
for (var x = 0; x < groupcharts.length; x++) {
charts.push({
xtype : "panel",
height : groupcharts[x].height * 1,
scope:this,
margin : '5 5 0 0',
chartwidth:this.getView().getWidth()/groupcharts.length,
chartJSON : groupcharts[x],
listeners : {
afterrender :function(panel){
panel.chartJSON.width=panel.chartwidth;
var fusionchart = new FusionCharts(panel.chartJSON);
fusionchart.render(panel.body.id);
}
}
});
}
this.getView().add({
xtype : "panel",
margin : '5 5 0 0',
title:chart.chartTitle,
bodyStyle : 'background:#D8D8D8',
group:true,
scope:this,
width:"100%",
layout:{
type : 'table',
columns : charts.length
},
items : charts
});
this.resizeCharts(this.getView().down("#chartcolumnlayout"));
},
loadfusionchart : function(panel) {
var clayout=this.getView().down("#chartcolumnlayout");
var newColumns =clayout==null?1:parseInt(clayout.value);
var chartwidth=this.getView().getWidth()/newColumns;
panel.chartJSON.width=chartwidth;
var fusionchart = new FusionCharts(panel.chartJSON);
fusionchart.render(panel.body.id);
// this.resizeCharts(this.getView().down("#chartcolumnlayout"));
},
resizeCharts : function(comp, newValue, oldValue, eOpts) {
var Value = comp.value;
mainPanel = comp.up().up();
mainPanel.getLayout().columns = parseInt(Value);
newColumns = parseInt(Value);
totalWidth = (mainPanel.getWidth())
for (var i = 0; i < mainPanel.items.length; i++) {
var currentPanel = mainPanel.items.items[i];
if(currentPanel.hasOwnProperty("group") && currentPanel.group == false){
currentPanel.setWidth(((totalWidth - 2) / newColumns));
}
}
for ( var k in FusionCharts.items) {
debugger;
fusionObj = FusionCharts.items[k];
if(fusionObj.args.hasOwnProperty("group") && fusionObj.args.group == true){
}else{
var panelbodyId = fusionObj.options.containerElementId;
if (this.getView().down(
'#'
+ panelbodyId.substring(0, panelbodyId
.indexOf('-body'))) != null) {
fusionObj.resizeTo(((totalWidth) / newColumns));
}
}
}
mainPanel.setWidth(totalWidth);
},
filterdaterangedata:function(btn){
debugger;
if(btn.hasOwnProperty("daterangevalue") ){
var defaultDate=this.reportView.down("#defaultsDate");
if(defaultDate!=null){
defaultDate.setValue(btn.daterangevalue);
this.reportView.controller.datachart.controller.filterData();
}
}
},
onPanelResize:function(me, width, height, oldWidth, oldHeight, eOpts )
{
debugger;
newColumns=parseInt(me.down("ratingField").value);
for (var i = 0; i < me.items.length; i++) {
var currentPanel = me.items.items[i];
if(currentPanel.hasOwnProperty("group") && currentPanel.group == false){
currentPanel.setWidth(((width - 2) / newColumns));
}
}
for ( var k in FusionCharts.items) {
debugger;
fusionObj = FusionCharts.items[k];
if(fusionObj.args.hasOwnProperty("group") && fusionObj.args.group == true){
}else{
var panelbodyId = fusionObj.options.containerElementId;
if (me.down(
'#'
+ panelbodyId.substring(0, panelbodyId
.indexOf('-body'))) != null) {
fusionObj.resizeTo(((width) / newColumns));
}
}
}
//alert("Panel Resize Called>>>>>>>>>");
}
}); | applifireAlgo/appDemoApps201115 | surveyportal/src/main/webapp/app/view/reportui/datachart/chart/ChartController.js | JavaScript | gpl-3.0 | 5,406 |
package com.bensler.decaf.swing.table;
import java.sql.Ref;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
/**
*/
public class ColumnModel<E> extends DefaultTableColumnModel {
private final Map<TablePropertyView, Column> allPropertiesColumnMap_;
private final Map<TablePropertyView, Column> propertyColumnMap_;
private Column pressedColumn_;
private Column sortedColumn_;
private Sorting sorting_;
private int[] prefSizes_;
ColumnModel() {
super();
allPropertiesColumnMap_ = new HashMap<TablePropertyView, Column>();
propertyColumnMap_ = new HashMap<TablePropertyView, Column>();
pressedColumn_ = null;
sortedColumn_ = null;
sorting_ = Sorting.NONE;
prefSizes_ = null;
}
void init() {
allPropertiesColumnMap_.putAll(propertyColumnMap_);
}
Set<TablePropertyView> getShownProperties() {
return new HashSet<TablePropertyView>(propertyColumnMap_.keySet());
}
List<String> getPropertyKeyList() {
final List<String> returnValue = new ArrayList<String>(tableColumns.size());
for (int i = 0; i < tableColumns.size(); i++) {
final TablePropertyView view = ((Column)tableColumns.get(i)).getView();
returnValue.add(view.getId());
}
return returnValue;
}
List<String> getSizeList() {
final List<String> returnValue = new ArrayList<String>(tableColumns.size());
for (int i = 0; i < tableColumns.size(); i++) {
returnValue.add(Integer.toString(((Column)tableColumns.get(i)).getWidth()));
}
return returnValue;
}
void setPrefSizes(int[] sizes) {
prefSizes_ = sizes;
}
void setPrefSize(int size, int columnIndex) {
prefSizes_[columnIndex] = size;
}
int getPrefWidth() {
int prefSizeSum = 0;
for (int i = 0; i < prefSizes_.length; i++) {
prefSizeSum += prefSizes_[i];
}
return prefSizeSum;
}
void updatePrefSizes() {
prefSizes_ = new int[getColumnCount()];
for (int i = 0; i < prefSizes_.length; i++) {
prefSizes_[i] = getColumn(i).getWidth();
}
}
void updateColPrefSizes(int size) {
if (prefSizes_ == null) {
updatePrefSizes();
} else {
final int prefWidth = getPrefWidth();
if ((size > 0) && (prefWidth > 0)) {
final float ratio = ((float)size) / prefWidth;
if (prefSizes_.length == getColumnCount()) {
for (int i = 0; i < prefSizes_.length; i++) {
final Column col = getColumn(i);
col.setPreferredWidth(Math.round(prefSizes_[i] * ratio));
}
}
}
}
}
// int[] getPrefSizes() {
// if (prefSizes_ == null) {
// updatePrefSizes();
// }
// return (int[])ArrayUtil.createCopy(prefSizes_);
// }
//
// Column getSortedColumn() {
// return sortedColumn_;
// }
void setProperties(List<TablePropertyView> properties) {
if (!properties.isEmpty()) {
setShownProperties(new HashSet<TablePropertyView>(0));
for (int i = 0; i < properties.size(); i++) {
addColumn(allPropertiesColumnMap_.get(properties.get(i)));
}
}
}
void setSorting(Column column, Sorting sorting) {
for (int i = 0; i < getColumnCount(); i++) {
if (getColumn(i) == column) {
sortedColumn_ = column;
sorting_ = sorting;
break;
}
}
}
void setShownProperties(Collection<TablePropertyView> newProperties) {
final Set<TablePropertyView> shownProperties = getShownProperties();
final Set<TablePropertyView> toRemove = new HashSet<TablePropertyView>(shownProperties);
final Set<TablePropertyView> toAdd = new HashSet<TablePropertyView>(newProperties);
toRemove.removeAll(newProperties);
toAdd.removeAll(shownProperties);
for (TablePropertyView view : toRemove) {
hideColumn(view);
}
updatePrefSizes();
if (!toAdd.isEmpty()) {
int i = 0;
int prefSizeSum = 0;
final int[] newPrefSizes = new int[prefSizes_.length + toAdd.size()];
final int avgSize;
for (i = 0; i < prefSizes_.length; i++) {
prefSizeSum += prefSizes_[i];
newPrefSizes[i] = prefSizes_[i];
}
avgSize = Math.round(((float)prefSizeSum) / newPrefSizes.length);
for (TablePropertyView view : toAdd) {
showColumn(view);
newPrefSizes[i] = avgSize;
}
prefSizes_ = newPrefSizes;
}
}
private void showColumn(TablePropertyView view) {
final Column column = allPropertiesColumnMap_.get(view);
if (column != null) {
final int viewIndex = getColumnCount();
column.setViewIndex(viewIndex);
addColumn(column);
}
}
void hideColumn(TablePropertyView view) {
final Column column = allPropertiesColumnMap_.get(view);
if (column != null) {
column.setViewIndex(tableColumns.indexOf(column));
removeColumn(column);
}
}
@Override
public void addColumn(TableColumn aColumn) {
final Column column = (Column)aColumn;
final TablePropertyView property = column.getView();
if (!propertyColumnMap_.containsKey(property)) {
propertyColumnMap_.put(property, column);
super.addColumn(column);
}
}
@Override
public void removeColumn(TableColumn column) {
propertyColumnMap_.remove(((Column)column).getView());
if (column == pressedColumn_) {
pressedColumn_ = null;
}
if (column == sortedColumn_) {
sortedColumn_ = null;
}
super.removeColumn(column);
}
void setPressedColumn(Column column) {
if (tableColumns.contains(column)) {
pressedColumn_ = column;
}
}
void resetPressedColumn() {
pressedColumn_ = null;
}
boolean isColumnPressed(int col) {
return (pressedColumn_ == tableColumns.get(col));
}
@Override
public Column getColumn(int columnIndex) {
return (Column)super.getColumn(columnIndex);
}
Sorting getSorting(int columnIndex) {
return (
(tableColumns.get(columnIndex) == sortedColumn_)
? sorting_ : Sorting.NONE
);
}
public Column resolveColumn(Ref tablePropertyViewRef) {
for (TableColumn column : tableColumns) {
if (((Column)column).getView().equals(tablePropertyViewRef)) {
return (Column)column;
}
}
return null;
}
}
| bensler/Decaf | decaf-swing/src/main/java/com/bensler/decaf/swing/table/ColumnModel.java | Java | gpl-3.0 | 6,712 |
/*
* PatientView
*
* Copyright (c) Worth Solutions Limited 2004-2013
*
* This file is part of PatientView.
*
* PatientView 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.
* PatientView 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 PatientView in a file
* titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @package PatientView
* @link http://www.patientview.org
* @author PatientView <info@patientview.org>
* @copyright Copyright (c) 2004-2013, Worth Solutions Limited
* @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
*/
package org.patientview.radar.service;
import org.patientview.radar.model.Phenotype;
import org.patientview.radar.model.sequenced.ClinicalData;
import java.util.List;
public interface ClinicalDataManager {
void saveClinicalDate(ClinicalData clinicalData);
ClinicalData getClinicalData(long id);
List<ClinicalData> getClinicalDataByRadarNumber(long radarNumber);
ClinicalData getFirstClinicalDataByRadarNumber(long radarNumber);
Phenotype getPhenotype(long id);
List<Phenotype> getPhenotypes();
}
| robworth/patientview | patientview-parent/radar/src/main/java/org/patientview/radar/service/ClinicalDataManager.java | Java | gpl-3.0 | 1,565 |
// Copyright (C) 2015 Frode Roxrud Gill
// See LICENSE file for GPLv3 license
#include "PowerManager.h"
#include "../BackertrapAdaApp.h"
void PowerManagerTimerCallback(TimerManager::TimerId id, void* calling_object, U8 param)
{
static_cast<PowerManager*>(calling_object)->OnTimerEvent(id, param);
}
PowerManager::PowerManager()
{
}
PowerManager::~PowerManager()
{
}
void PowerManager::OnTimerEvent(TimerManager::TimerId id, U8 UNUSED_PARAM(param>))
{
switch(id)
{
case TimerManager::BACKLIGHT_TIMEOUT: APP()->GetDisplayManager()->GetDisplay()->SetBacklightStatus(Display::OFF); break;
default: break;
}
}
void PowerManager::RegisterActivity()
{
APP()->GetTimerManager()->ResetTimeout(TimerManager::BACKLIGHT_TIMEOUT, 20, TimerManager::SECOND, ::PowerManagerTimerCallback, this, 0); //ToDo: Load from settings
}
void PowerManager::SleepIDLE() const
{
sleep_set_mode(SLEEP_SMODE_IDLE_gc);
sleep_enable();
sleep_enter();
sleep_disable();
}
| frodegill/backertrap-ada | managers/PowerManager.cpp | C++ | gpl-3.0 | 961 |
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* 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.implementations;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.plot.flag.types.BooleanFlag;
import org.checkerframework.checker.nullness.qual.NonNull;
public class KelpGrowFlag extends BooleanFlag<KelpGrowFlag> {
public static final KelpGrowFlag KELP_GROW_TRUE = new KelpGrowFlag(true);
public static final KelpGrowFlag KELP_GROW_FALSE = new KelpGrowFlag(false);
private KelpGrowFlag(boolean value) {
super(value, TranslatableCaption.miniMessage("flags.flag_description_kelp_grow"));
}
@Override
protected KelpGrowFlag flagOf(@NonNull Boolean value) {
return value ? KELP_GROW_TRUE : KELP_GROW_FALSE;
}
}
| IntellectualCrafters/PlotSquared | Core/src/main/java/com/plotsquared/core/plot/flag/implementations/KelpGrowFlag.java | Java | gpl-3.0 | 2,061 |
angular.module('CarpentryApp.Index', ['CarpentryApp.Common']).controller(
'IndexController',
function ($rootScope, $scope, $state, $http, $cookies, hotkeys, notify) {
var limit = 720;
var counter = 0;
$rootScope.resetPollers();
$rootScope.indexPoller = setInterval(function(){
counter++;
if (counter > 720) {
clearInterval($rootScope.indexPoller);
}
$rootScope.refresh();
}, 1000);
$rootScope.refresh();
});
| gabrielfalcao/carpentry | carpentry/static/js/app.2.index.js | JavaScript | gpl-3.0 | 529 |
package eu.siacs.conversations.services;
public abstract class AbstractQuickConversationsService {
protected final XmppConnectionService service;
public AbstractQuickConversationsService(XmppConnectionService service) {
this.service = service;
}
public abstract void considerSync();
public static boolean isQuicksy() {
return true;
}
public static boolean isConversations() {
return true;
}
public abstract void signalAccountStateChange();
public abstract boolean isSynchronizing();
public abstract void considerSyncBackground(boolean force);
} | kriztan/Pix-Art-Messenger | src/main/java/eu/siacs/conversations/services/AbstractQuickConversationsService.java | Java | gpl-3.0 | 621 |
<?php
require("phpsqlinfo_dbinfo.php");
// Gets data from URL parameters.
$name = $_GET['name'];
$address = $_GET['address'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$type = $_GET['type'];
// Opens a connection to a MySQL server.
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Sets the active MySQL database.
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Inserts new row with place data.
$query = sprintf("INSERT INTO markers " .
" (id, name, address, lat, lng, type ) " .
" VALUES (NULL, '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($name),
mysql_real_escape_string($address),
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($type));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
| n7wwk/WebIMS-Test | maps/phpsqlinfo_addrow.php | PHP | gpl-3.0 | 1,058 |
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source
// & Institut Laue - Langevin
// SPDX - License - Identifier: GPL - 3.0 +
#include "MantidCrystal/SortHKL.h"
#include "MantidAPI/AnalysisDataService.h"
#include "MantidAPI/FileProperty.h"
#include "MantidAPI/Sample.h"
#include "MantidAPI/TextAxis.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidDataObjects/Peak.h"
#include "MantidDataObjects/PeaksWorkspace.h"
#include "MantidDataObjects/Workspace2D.h"
#include "MantidGeometry/Crystal/OrientedLattice.h"
#include "MantidGeometry/Crystal/PointGroupFactory.h"
#include "MantidGeometry/Instrument/RectangularDetector.h"
#include "MantidKernel/ListValidator.h"
#include "MantidKernel/UnitFactory.h"
#include "MantidKernel/Utils.h"
#include <cmath>
#include <fstream>
#include <numeric>
using namespace Mantid::Geometry;
using namespace Mantid::DataObjects;
using namespace Mantid::Kernel;
using namespace Mantid::API;
using namespace Mantid::Crystal::PeakStatisticsTools;
namespace Mantid {
namespace Crystal {
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(SortHKL)
SortHKL::SortHKL() {
m_pointGroups = getAllPointGroups();
m_refConds = getAllReflectionConditions();
}
SortHKL::~SortHKL() = default;
void SortHKL::init() {
declareProperty(make_unique<WorkspaceProperty<PeaksWorkspace>>(
"InputWorkspace", "", Direction::Input),
"An input PeaksWorkspace with an instrument.");
/* TODO: These two properties with string lists keep appearing -
* Probably there should be a dedicated Property type or validator. */
std::vector<std::string> pgOptions;
pgOptions.reserve(2 * m_pointGroups.size() + 5);
std::transform(m_pointGroups.cbegin(), m_pointGroups.cend(),
std::back_inserter(pgOptions),
[](const auto &group) { return group->getSymbol(); });
std::transform(m_pointGroups.cbegin(), m_pointGroups.cend(),
std::back_inserter(pgOptions),
[](const auto &group) { return group->getName(); });
// Scripts may have Orthorhombic misspelled from past bug in PointGroupFactory
pgOptions.push_back("222 (Orthorombic)");
pgOptions.push_back("mm2 (Orthorombic)");
pgOptions.push_back("2mm (Orthorombic)");
pgOptions.push_back("m2m (Orthorombic)");
pgOptions.push_back("mmm (Orthorombic)");
declareProperty("PointGroup", pgOptions[0],
boost::make_shared<StringListValidator>(pgOptions),
"Which point group applies to this crystal?");
std::vector<std::string> centeringOptions;
centeringOptions.reserve(2 * m_refConds.size());
std::transform(m_refConds.cbegin(), m_refConds.cend(),
std::back_inserter(centeringOptions),
[](const auto &condition) { return condition->getSymbol(); });
std::transform(m_refConds.cbegin(), m_refConds.cend(),
std::back_inserter(centeringOptions),
[](const auto &condition) { return condition->getName(); });
declareProperty("LatticeCentering", centeringOptions[0],
boost::make_shared<StringListValidator>(centeringOptions),
"Appropriate lattice centering for the peaks.");
declareProperty(make_unique<WorkspaceProperty<PeaksWorkspace>>(
"OutputWorkspace", "", Direction::Output),
"Output PeaksWorkspace");
declareProperty("OutputChi2", 0.0, "Chi-square is available as output",
Direction::Output);
declareProperty(make_unique<WorkspaceProperty<ITableWorkspace>>(
"StatisticsTable", "StatisticsTable", Direction::Output),
"An output table workspace for the statistics of the peaks.");
declareProperty(make_unique<PropertyWithValue<std::string>>(
"RowName", "Overall", Direction::Input),
"name of row");
declareProperty("Append", false,
"Append to output table workspace if true.\n"
"If false, new output table workspace (default).");
const std::vector<std::string> equivTypes{"Mean", "Median"};
declareProperty("EquivalentIntensities", equivTypes.front(),
boost::make_shared<StringListValidator>(equivTypes),
"Replace intensities by mean(default), "
"or median.");
declareProperty(Kernel::make_unique<PropertyWithValue<double>>(
"SigmaCritical", 3.0, Direction::Input),
"Removes peaks whose intensity deviates more than "
"SigmaCritical from the mean (or median).");
declareProperty(
make_unique<WorkspaceProperty<MatrixWorkspace>>(
"EquivalentsWorkspace", "EquivalentIntensities", Direction::Output),
"Output Equivalent Intensities");
declareProperty("WeightedZScore", false,
"Use weighted ZScore if true.\n"
"If false, standard ZScore (default).");
}
void SortHKL::exec() {
PeaksWorkspace_sptr inputPeaksWorkspace = getProperty("InputWorkspace");
const std::vector<Peak> &inputPeaks = inputPeaksWorkspace->getPeaks();
std::vector<Peak> peaks = getNonZeroPeaks(inputPeaks);
if (peaks.empty()) {
g_log.error() << "Number of peaks should not be 0 for SortHKL.\n";
return;
}
UnitCell cell = inputPeaksWorkspace->sample().getOrientedLattice();
UniqueReflectionCollection uniqueReflections =
getUniqueReflections(peaks, cell);
std::string equivalentIntensities = getPropertyValue("EquivalentIntensities");
double sigmaCritical = getProperty("SigmaCritical");
bool weightedZ = getProperty("WeightedZScore");
MatrixWorkspace_sptr UniqWksp =
Mantid::API::WorkspaceFactory::Instance().create(
"Workspace2D", uniqueReflections.getReflections().size(), 20, 20);
int counter = 0;
size_t maxPeaks = 0;
auto taxis = new TextAxis(uniqueReflections.getReflections().size());
UniqWksp->getAxis(0)->unit() = UnitFactory::Instance().create("Wavelength");
for (const auto &unique : uniqueReflections.getReflections()) {
/* Since all possible unique reflections are explored
* there may be 0 observations for some of them.
* In that case, nothing can be done.*/
if (unique.second.count() > 2) {
taxis->setLabel(counter, " " + unique.second.getHKL().toString());
auto &UniqX = UniqWksp->mutableX(counter);
auto &UniqY = UniqWksp->mutableY(counter);
auto &UniqE = UniqWksp->mutableE(counter);
counter++;
auto wavelengths = unique.second.getWavelengths();
auto intensities = unique.second.getIntensities();
g_log.debug() << "HKL " << unique.second.getHKL() << "\n";
g_log.debug() << "Intensities ";
for (const auto &e : intensities)
g_log.debug() << e << " ";
g_log.debug() << "\n";
std::vector<double> zScores;
if (!weightedZ) {
zScores = Kernel::getZscore(intensities);
} else {
auto sigmas = unique.second.getSigmas();
zScores = Kernel::getWeightedZscore(intensities, sigmas);
}
if (zScores.size() > maxPeaks)
maxPeaks = zScores.size();
// Possibly remove outliers.
auto outliersRemoved =
unique.second.removeOutliers(sigmaCritical, weightedZ);
auto intensityStatistics =
Kernel::getStatistics(outliersRemoved.getIntensities(),
StatOptions::Mean | StatOptions::Median);
g_log.debug() << "Mean = " << intensityStatistics.mean
<< " Median = " << intensityStatistics.median << "\n";
// sort wavelengths & intensities
for (size_t i = 0; i < wavelengths.size(); i++) {
size_t i0 = i;
for (size_t j = i + 1; j < wavelengths.size(); j++) {
if (wavelengths[j] < wavelengths[i0]) // Change was here!
{
i0 = j;
}
}
double temp = wavelengths[i0];
wavelengths[i0] = wavelengths[i];
wavelengths[i] = temp;
temp = intensities[i0];
intensities[i0] = intensities[i];
intensities[i] = temp;
}
g_log.debug() << "Zscores ";
for (size_t i = 0; i < std::min(zScores.size(), static_cast<size_t>(20));
++i) {
UniqX[i] = wavelengths[i];
UniqY[i] = intensities[i];
if (zScores[i] > sigmaCritical)
UniqE[i] = intensities[i];
else if (equivalentIntensities == "Mean")
UniqE[i] = intensityStatistics.mean - intensities[i];
else
UniqE[i] = intensityStatistics.median - intensities[i];
g_log.debug() << zScores[i] << " ";
}
for (size_t i = zScores.size(); i < 20; ++i) {
UniqX[i] = wavelengths[zScores.size() - 1];
UniqY[i] = intensities[zScores.size() - 1];
UniqE[i] = 0.0;
}
g_log.debug() << "\n";
}
}
if (counter > 0) {
MatrixWorkspace_sptr UniqWksp2 =
Mantid::API::WorkspaceFactory::Instance().create("Workspace2D", counter,
maxPeaks, maxPeaks);
for (int64_t i = 0; i < counter; ++i) {
auto &outSpec = UniqWksp2->getSpectrum(i);
const auto &inSpec = UniqWksp->getSpectrum(i);
outSpec.setHistogram(inSpec.histogram());
// Copy the spectrum number/detector IDs
outSpec.copyInfoFrom(inSpec);
}
UniqWksp2->replaceAxis(1, taxis);
setProperty("EquivalentsWorkspace", UniqWksp2);
} else {
setProperty("EquivalentsWorkspace", UniqWksp);
}
PeaksStatistics peaksStatistics(uniqueReflections, equivalentIntensities,
sigmaCritical, weightedZ);
// Store the statistics for output.
const std::string tableName = getProperty("StatisticsTable");
ITableWorkspace_sptr statisticsTable = getStatisticsTable(tableName);
insertStatisticsIntoTable(statisticsTable, peaksStatistics);
// Store all peaks that were used to calculate statistics.
PeaksWorkspace_sptr outputPeaksWorkspace =
getOutputPeaksWorkspace(inputPeaksWorkspace);
std::vector<Peak> &originalOutputPeaks = outputPeaksWorkspace->getPeaks();
originalOutputPeaks.swap(peaksStatistics.m_peaks);
sortOutputPeaksByHKL(outputPeaksWorkspace);
setProperty("OutputWorkspace", outputPeaksWorkspace);
setProperty("OutputChi2", peaksStatistics.m_chiSquared);
setProperty("StatisticsTable", statisticsTable);
AnalysisDataService::Instance().addOrReplace(tableName, statisticsTable);
}
/// Returns a vector which contains only peaks with I > 0, sigma > 0 and valid
/// HKL.
std::vector<Peak>
SortHKL::getNonZeroPeaks(const std::vector<Peak> &inputPeaks) const {
std::vector<Peak> peaks;
peaks.reserve(inputPeaks.size());
std::remove_copy_if(inputPeaks.begin(), inputPeaks.end(),
std::back_inserter(peaks), [](const Peak &peak) {
return peak.getIntensity() <= 0.0 ||
peak.getSigmaIntensity() <= 0.0 ||
peak.getHKL() == V3D(0, 0, 0);
});
return peaks;
}
/**
* @brief SortHKL::getUniqueReflections
*
* This method returns a map that contains a UniqueReflection-
* object with 0 to n Peaks each. The key of the map is the
* reflection index all peaks are equivalent to.
*
* @param peaks :: Vector of peaks to assign.
* @param cell :: UnitCell to use for calculation of possible reflections.
* @return Map of unique reflections.
*/
UniqueReflectionCollection
SortHKL::getUniqueReflections(const std::vector<Peak> &peaks,
const UnitCell &cell) const {
ReflectionCondition_sptr centering = getCentering();
PointGroup_sptr pointGroup = getPointgroup();
std::pair<double, double> dLimits = getDLimits(peaks, cell);
UniqueReflectionCollection reflections(cell, dLimits, pointGroup, centering);
reflections.addObservations(peaks);
return reflections;
}
/// Returns the centering extracted from the user-supplied property.
ReflectionCondition_sptr SortHKL::getCentering() const {
ReflectionCondition_sptr centering =
boost::make_shared<ReflectionConditionPrimitive>();
const std::string refCondName = getPropertyValue("LatticeCentering");
const auto found = std::find_if(m_refConds.crbegin(), m_refConds.crend(),
[refCondName](const auto &condition) {
return condition->getName() == refCondName;
});
if (found != m_refConds.crend()) {
centering = *found;
}
return centering;
}
/// Returns the PointGroup-object constructed from the property supplied by the
/// user.
PointGroup_sptr SortHKL::getPointgroup() const {
PointGroup_sptr pointGroup =
PointGroupFactory::Instance().createPointGroup("-1");
std::string pointGroupName = getPropertyValue("PointGroup");
size_t pos = pointGroupName.find("Orthorombic");
if (pos != std::string::npos) {
g_log.warning() << "Orthorhomic is misspelled in your script.\n";
pointGroupName.replace(pos, 11, "Orthorhombic");
g_log.warning() << "Please correct to " << pointGroupName << ".\n";
}
const auto found =
std::find_if(m_pointGroups.crbegin(), m_pointGroups.crend(),
[&pointGroupName](const auto &group) {
return group->getName() == pointGroupName;
});
if (found != m_pointGroups.crend()) {
pointGroup = *found;
}
return pointGroup;
}
/// Returns the lowest and highest d-Value in the list. Uses UnitCell and HKL
/// for calculation to prevent problems with potentially inconsistent d-Values
/// in Peak.
std::pair<double, double> SortHKL::getDLimits(const std::vector<Peak> &peaks,
const UnitCell &cell) const {
auto dLimitIterators = std::minmax_element(
peaks.begin(), peaks.end(), [cell](const Peak &lhs, const Peak &rhs) {
return cell.d(lhs.getHKL()) < cell.d(rhs.getHKL());
});
return std::make_pair(cell.d((*dLimitIterators.first).getHKL()),
cell.d((*dLimitIterators.second).getHKL()));
}
/// Create a TableWorkspace for the statistics with appropriate columns or get
/// one from the ADS.
ITableWorkspace_sptr
SortHKL::getStatisticsTable(const std::string &name) const {
TableWorkspace_sptr tablews;
// Init or append to a table workspace
bool append = getProperty("Append");
if (append && AnalysisDataService::Instance().doesExist(name)) {
tablews = AnalysisDataService::Instance().retrieveWS<TableWorkspace>(name);
} else {
tablews = boost::make_shared<TableWorkspace>();
tablews->addColumn("str", "Resolution Shell");
tablews->addColumn("int", "No. of Unique Reflections");
tablews->addColumn("double", "Resolution Min");
tablews->addColumn("double", "Resolution Max");
tablews->addColumn("double", "Multiplicity");
tablews->addColumn("double", "Mean ((I)/sd(I))");
tablews->addColumn("double", "Rmerge");
tablews->addColumn("double", "Rpim");
tablews->addColumn("double", "Data Completeness");
}
return tablews;
}
/// Inserts statistics the supplied PeaksStatistics-objects into the supplied
/// TableWorkspace.
void SortHKL::insertStatisticsIntoTable(
const ITableWorkspace_sptr &table,
const PeaksStatistics &statistics) const {
if (!table) {
throw std::runtime_error("Can't store statistics into Null-table.");
}
std::string name = getProperty("RowName");
double completeness = 0.0;
if (name.substr(0, 4) != "bank") {
completeness = static_cast<double>(statistics.m_completeness);
}
// append to the table workspace
API::TableRow newrow = table->appendRow();
newrow << name << statistics.m_uniqueReflections << statistics.m_dspacingMin
<< statistics.m_dspacingMax << statistics.m_redundancy
<< statistics.m_meanIOverSigma << 100.0 * statistics.m_rMerge
<< 100.0 * statistics.m_rPim << 100.0 * completeness;
}
/// Returns a PeaksWorkspace which is either the input workspace or a clone.
PeaksWorkspace_sptr SortHKL::getOutputPeaksWorkspace(
const PeaksWorkspace_sptr &inputPeaksWorkspace) const {
PeaksWorkspace_sptr outputPeaksWorkspace = getProperty("OutputWorkspace");
if (outputPeaksWorkspace != inputPeaksWorkspace) {
outputPeaksWorkspace = inputPeaksWorkspace->clone();
}
return outputPeaksWorkspace;
}
/// Sorts the peaks in the workspace by H, K and L.
void SortHKL::sortOutputPeaksByHKL(IPeaksWorkspace_sptr outputPeaksWorkspace) {
// Sort by HKL
std::vector<std::pair<std::string, bool>> criteria{
{"H", true}, {"K", true}, {"L", true}};
outputPeaksWorkspace->sort(criteria);
}
} // namespace Crystal
} // namespace Mantid
| mganeva/mantid | Framework/Crystal/src/SortHKL.cpp | C++ | gpl-3.0 | 16,928 |
/*****************************************************************************************
==========================================================================================
____ ____ ___
U | __")u U | __")u / " \
\| _ \/ \| _ \/ | |"| |
| |_) | | |_) | /| |_| |\
|____/ |____/ U \__\_\u
_|| \\_ _|| \\_ \\//
(__) (__) (__) (__) (_(__)
-- The Fermion Grill --
==========================================================================================
*****************************************************************************************/
//**************************************************************************************//
// Copyright (C) 2014 Malik Kirchner "malik.kirchner@gmx.net" //
// //
// This program is free software: you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation, either version 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/>. //
// //
// Dieses Programm ist Freie Software: Sie können es unter den Bedingungen //
// der GNU General Public License, wie von der Free Software Foundation, //
// Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren //
// veröffentlichten Version, weiterverbreiten und/oder modifizieren. //
// //
// Dieses Programm wird in der Hoffnung, dass es nützlich sein wird, aber //
// OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite //
// Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. //
// Siehe die GNU General Public License für weitere Details. //
// //
// Sie sollten eine Kopie der GNU General Public License zusammen mit diesem //
// Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. //
// //
//**************************************************************************************//
#pragma once
template <typename T> constexpr void safe_delete(T& ptr) {
if (ptr) delete ptr;
ptr = nullptr;
}
template <typename T> constexpr void safe_array_delete(T& ptr) {
if (ptr) delete[] ptr;
ptr = nullptr;
}
| malikkirchner/bbq | src/util/memory.hpp | C++ | gpl-3.0 | 3,792 |
/**
* Database.java
* (C) 2011 Florian Staudacher, Christian Wurst
*
* This file is part of AutoDJ.
*
* AutoDJ 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.
*
* AutoDJ 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 AutoDJ. If not, see <http://www.gnu.org/licenses/>.
*/
package AutoDJ.firstrun;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import AutoDJ.prefs.Settings;
import AutoDJ.wizard.WizardPanel;
/**
* @author Florian Staudacher
*
* This wizard panel asks the user for his database preference
* and (if necessary) the needed credentials
*
*/
public class Database extends WizardPanel implements ActionListener, FocusListener {
/**
* inherited from JPanel
*/
private static final long serialVersionUID = 1L;
/**
* gui components
*/
JComboBox dbTypeDropdown;
JPanel dbOptions;
JLabel sqlitePathLbl;
JFileChooser fileChooser;
JButton fileChooserBtn;
CardLayout cardLayout;
JPanel sqliteOptions;
JPanel mysqlOptions;
HashMap<String, JTextField> mysqlCredentials;
/**
* values
*/
String dbType;
String sqlitePath;
/**
* initialize panel
*/
public Database() {
super();
setTitle("Music Library");
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
initDbOptions();
}
/**
* build the gui components and form
*/
public void initComponents() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// add explanatory text to layout
JLabel explanationText = new JLabel("<html>Enter the database you want to use.</html");
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 4;
panel.add(explanationText, c);
c.gridwidth = 1; // reset
// db type dropdown
dbType = Settings.get("dbType", "...");
Vector<String> dbTypes = new Vector<String>();
dbTypes.add("...");
dbTypes.add("sqlite");
dbTypes.add("mysql");
int selIndex = dbTypes.indexOf(dbType);
dbTypeDropdown = new JComboBox(dbTypes);
dbTypeDropdown.setSelectedIndex(selIndex);
dbTypeDropdown.addActionListener(this);
c.gridy = 2;
c.insets = new Insets(30, 0, 40, 20);
c.anchor = GridBagConstraints.FIRST_LINE_START;
panel.add(dbTypeDropdown, c);
// additional db option panel
dbOptions = new JPanel();
dbOptions.setLayout(new FlowLayout(FlowLayout.LEADING));
c.gridx = 2;
c.insets = new Insets(30, 0, 10, 0);
panel.add(dbOptions, c);
// add final text to layout
JLabel continueText = new JLabel("<html>When you are done, click 'finish' to start AutoDJ.</html>");
c.gridx = 1;
c.gridy = 4;
c.gridwidth = 4;
panel.add(continueText, c);
setContent(panel);
}
/**
* save the selected db type in the settings
*/
@Override
public void actionPerformed(ActionEvent evt) {
if( evt.getSource().equals(dbTypeDropdown)) {
dbType = dbTypeDropdown.getSelectedItem().toString();
Settings.set("dbType", dbType);
showDbOptions();
}
if( evt.getSource().equals(fileChooserBtn)) {
int retVal = fileChooser.showOpenDialog(this);
if (retVal == JFileChooser.APPROVE_OPTION) {
sqlitePath = fileChooser.getSelectedFile().getPath();
sqlitePathLbl.setText(sqlitePath);
Settings.set("dbPath", sqlitePath);
}
}
}
/**
* populate panels with additional db options
*
* @param String type
*/
private void initDbOptions() {
Vector<JPanel> panels = new Vector<JPanel>();
panels.add(initSqliteDbOptions());
panels.add(initMysqlDbOptions());
Dimension dim = dbOptions.getSize();
Iterator<JPanel> itr = panels.iterator();
while(itr.hasNext()) {
JPanel p = itr.next();
Dimension d = p.getPreferredSize();
if( d.height > dim.height ) dim.height = d.height + 10;
if( d.width > dim.width ) dim.width = d.width + 10;
}
dbOptions.setPreferredSize(dim);
showDbOptions();
}
/**
* inizialize the sqlite option pane
*/
private JPanel initSqliteDbOptions() {
sqliteOptions = new JPanel();
sqliteOptions.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// add explanation
JLabel sqliteLbl = new JLabel("<html>Specify the desired location of the database file</html>");
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 4;
c.anchor = GridBagConstraints.FIRST_LINE_START;
sqliteOptions.add(sqliteLbl, c);
c.gridwidth = 1; // reset
// add label for file path to layout
sqlitePath = Settings.get("dbPath", "[nothing selected]");
sqlitePathLbl = new JLabel(sqlitePath);
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(10, 0, 10, 20);
sqliteOptions.add(sqlitePathLbl, c);
// add "select" button to layout
fileChooserBtn = new JButton("Select");
fileChooserBtn.addActionListener(this);
c.gridx = 3;
c.insets = new Insets(10, 0, 10, 0);
sqliteOptions.add(fileChooserBtn, c);
return sqliteOptions;
}
/**
* initialize the mysql option pane
*/
private JPanel initMysqlDbOptions() {
mysqlCredentials = new HashMap<String, JTextField>();
mysqlOptions = new JPanel();
mysqlOptions.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// add explanation
JLabel sqliteLbl = new JLabel("<html>Specify the credentials of your database</html>");
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 4;
c.anchor = GridBagConstraints.FIRST_LINE_START;
mysqlOptions.add(sqliteLbl, c);
c.gridwidth = 1; // reset
// add input fields for credentials
String[] fields = { "Host", "Name", "User", "Pass" }; // these strings must be the same as the
// names of the db settings without 'db'
for( int i = 0; i < fields.length; i++ ) {
JLabel l = new JLabel(fields[i], JLabel.TRAILING);
c.gridx = 1;
c.gridy++;
c.insets = new Insets(8, 0, 0, 6);
mysqlOptions.add(l, c);
JTextField t = new JTextField(10);
t.setText(Settings.get("db"+fields[i], ""));
t.addFocusListener(this);
l.setLabelFor(t);
c.gridx = 2;
mysqlOptions.add(t, c);
mysqlCredentials.put(fields[i], t);
}
return mysqlOptions;
}
/**
* show the option panel for the selected db type
*/
private void showDbOptions() {
dbOptions.removeAll();
if( dbType.equals("sqlite")) {
showSqliteOptions();
} else if( dbType.equals("mysql")) {
showMysqlOptions();
}
// re-layout the container
validate();
repaint();
}
/**
* show the sqlite option pane
*/
private void showSqliteOptions() {
dbOptions.add(sqliteOptions);
}
/**
* show the mysql option pane
*/
private void showMysqlOptions() {
dbOptions.add(mysqlOptions);
}
@Override
public void focusGained(FocusEvent evt) {
// ignore
}
/**
* if a mysql credential field loses focus, save the entered value
*/
@Override
public void focusLost(FocusEvent evt) {
Set<Map.Entry<String, JTextField>> set = mysqlCredentials.entrySet();
// determine which text field just lost focus
for (Map.Entry<String, JTextField> me : set) {
if( me.getValue().equals( ((JTextField)evt.getSource()) ) ) {
Settings.set("db"+me.getKey(), me.getValue().getText());
break;
}
}
}
}
| Raven24/AutoDJ | src/AutoDJ/firstrun/Database.java | Java | gpl-3.0 | 8,252 |
<?php
include 'config/db.php';
include 'libraries/events.php';
$rackid = mysqli_real_escape_string($conn, $_POST['rackid']);
$rack_name = mysqli_real_escape_string($conn, $_POST['rack_name']);
$rack_size = mysqli_real_escape_string($conn, $_POST['rack_size']);
$rack_city = mysqli_real_escape_string($conn, $_POST['rack_city']);
$rack_country = mysqli_real_escape_string($conn, $_POST['rack_country']);
if(isset($rackid, $rack_name, $rack_size, $rack_city, $rack_country)) {
$sql = "UPDATE `rackspace` SET `rack_name`='$rack_name' WHERE `rackid`='$rackid'";
$conn->query($sql);
$sql = "UPDATE `rackspace` SET `rack_size`='$rack_size' WHERE `rackid`='$rackid'";
$conn->query($sql);
$sql = "UPDATE `rackspace` SET `rack_city`='$rack_city' WHERE `rackid`='$rackid'";
echo $conn->query($sql);
$sql = "UPDATE `rackspace` SET `rack_country`='$rack_country' WHERE `rackid`='$rackid'";
$conn->query($sql);
$event_type = "Rackspace Modified";
$event_message = "Rackspace $rack_name was updated";
$event_status = "Complete";
add_event($event_type, $event_message, $event_status);
$_SESSION['success'] = "Success, Rackspace modified.";
header('Location: manage_rackspace.php');
$conn->close();
}
if(empty($rack_name)) {
$_SESSION['error'] = "Error, Rack Name not set.";
header('Location: manage_rackspace.php');
}
if(empty($rack_size)) {
$_SESSION['error'] = "Error, Rack Size not set.";
header('Location: manage_rackspace.php');
}
if(empty($rack_city)) {
$_SESSION['error'] = "Error, Rack City not set.";
header('Location: manage_rackspace.php');
}
if(empty($rack_country)) {
$_SESSION['error'] = "Error, Rack Country not set.";
header('Location: manage_rackspace.php');
}
?> | Wayno/DCIMStack | views/rackspace/modify_rackspace_db.php | PHP | gpl-3.0 | 1,740 |
# coding: utf-8
import os
import re
import hashlib
import time
from string import strip
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
from flask import current_app, request, flash, render_template, session, redirect, url_for
from lac.data_modelz import *
from lac.helperz import *
from lac.formz import SizeQuotaForm, InodeQuotaForm
__author__ = "Nicolas CHATELAIN"
__copyright__ = "Copyright 2014, Nicolas CHATELAIN @ CINES"
__license__ = "GPL"
class Engine(object):
def __init__(self, app=None):
if app is not None:
self.app = app
self.init_app(self.app)
else:
self.app = None
def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['engine'] = self
self.cache = app.extensions['cache']
self.ldap = app.extensions['ldap']
self.converter = app.extensions['converter']
self.fm = app.extensions['form_manager']
self.ldap_search_base = app.config['LDAP_SEARCH_BASE']
self.ldap_admin = app.config['LDAP_DEFAULT_ADMIN']
def is_ccc_group(self, member):
return 'ccc' == self.cache.get_group_from_member_uid(member)
def is_cines_group(self, uid):
return 'cines' == self.cache.get_group_from_member_uid(uid)
def is_principal_group(self, member, group):
return self.cache.get_posix_group_cn_by_gid(member['gidNumber'][0]) == group
def disable_account(self, user):
user_attr = user.get_attributes()
mod_attr = [('pwdAccountLockedTime', "000001010000Z")]
user_uid = user_attr['uid'][0]
if self.cache.get_group_from_member_uid(user_uid) == 'ccc':
new_shadow_expire_datetime = datetime.now() - timedelta(days=1)
new_shadow_expire = str(
self.converter.datetime_to_days_number(
new_shadow_expire_datetime)
)
mod_attr.append(('shadowExpire', new_shadow_expire))
self.ldap.update_uid_attribute(
user_uid,
mod_attr
)
flash(u'Compte {0} désactivé'.format(user_uid))
print(u'{0} : Compte {1} désactivé'.format(
session['uid'],
user_uid).encode('utf-8')
)
def enable_account(self, user):
user_uid = user.get_attributes()['uid'][0]
if self.cache.get_group_from_member_uid(user_uid) == 'ccc':
new_shadow_expire_datetime = self.converter.days_number_to_datetime(
user.get_attributes()['cinesdaterenew'][0]
) + relativedelta(
months = +self.app.config['SHADOW_DURATION']
)
new_shadow_expire = str(
self.converter.datetime_to_days_number(new_shadow_expire_datetime))
self.ldap.update_uid_attribute(user_uid,
[('shadowExpire', new_shadow_expire)]
)
self.ldap.remove_uid_attribute(user_uid,
[('pwdAccountLockedTime', None)])
print(u'{0} : Compte {1} activé'.format(
session['uid'],
user_uid).encode('utf-8')
)
def get_search_user_fieldz(self):
page = Page.query.filter_by(label = "search_user").first()
page_attributez = Field.query.filter_by(page_id = page.id).all()
return page_attributez
def get_search_user_attributez(self):
search_attributez = [attr.label.encode('utf-8')
for attr in self.get_search_user_fieldz()]
return search_attributez
def get_resultz_from_search_user_form(self, form):
filter_list =[]
if form.uid_number.data != "" :
filter_list.append("(uidNumber={0})".format(
strip(form.uid_number.data)
))
if form.sn.data != "" :
filter_list.append("(sn=*{0}*)".format(
strip(form.sn.data)
))
if form.uid.data != "" :
filter_list.append("(uid=*{0}*)".format(
strip(form.uid.data)
))
if form.mail.data != "":
filter_list.append("(mail=*{0}*)".format(
strip(form.mail.data)
))
if form.user_disabled.data :
filter_list.append("(shadowExpire=0)")
if form.ip.data :
filter_list.append("(cinesIpClient={0})".format(
strip(form.ip.data)
))
if form.nationality.data :
filter_list.append("(cinesNationality={0})".format(
strip(form.nationality.data)
))
if form.user_type.data == "":
base_dn = "ou=people,{0}".format(self.ldap_search_base)
else:
base_dn = "ou={0},ou=people,{1}".format(form.user_type.data,
self.ldap_search_base)
if filter_list != [] :
ldap_filter = "(&(objectClass=posixAccount){0})".format("".join(
filter_list
))
else:
ldap_filter = "(objectClass=posixAccount)"
search_resultz = self.ldap.search(
ldap_filter=ldap_filter,
attributes=self.get_search_user_attributez(),
base_dn=base_dn)
return search_resultz
def get_search_group_fieldz(self):
page = Page.query.filter_by(label = "search_group").first()
page_attributez = Field.query.filter_by(page_id = page.id, display=True).all()
return page_attributez
def get_search_group_attributez(self):
search_attributez = [attr.label.encode('utf-8')
for attr in self.get_search_group_fieldz()]
return search_attributez
def get_resultz_from_search_group_form(self, form):
filter_list =[]
if form.gid_number.data != "" :
filter_list.append("(gidNumber={0})".format(
strip(form.gid_number.data)
))
if form.cn.data != "" :
filter_list.append("(cn=*{0}*)".format(
strip(form.cn.data)
))
if form.description.data :
filter_list.append(
"(description=*{0}*)".format(
strip(form.description.data)
)
)
if form.group_type.data == "":
base_dn = "ou=groupePosix,{0}".format(self.ldap_search_base)
else:
base_dn = "ou={0},ou=groupePosix,{1}".format(
strip(form.group_type.data),
self.ldap_search_base)
if filter_list != [] :
ldap_filter = "(&(objectClass=posixGroup){0})".format("".join(
filter_list
))
else:
ldap_filter = "(objectClass=posixGroup)"
search_resultz = self.ldap.search(
ldap_filter=ldap_filter,
attributes=self.get_search_group_attributez(),
base_dn=base_dn)
return search_resultz
def update_group_memberz_cines_c4(self, branch, group, comite):
memberz_uid = self.ldap.get_posix_group_memberz(branch, group)
if len(memberz_uid)>1:
ldap_filter = '(&(objectClass=posixAccount)(|{0}))'.format(
''.join(['(uid={0})'.format(uid) for uid in memberz_uid]))
elif len(memberz_uid)==1:
ldap_filter = '(&(objectClass=posixAccount)(uid={0}))'.format(
memberz_uid[0])
else:
return
memberz = self.ldap.search(
ldap_filter=ldap_filter,
attributes=['cinesC4', 'dn', 'uid', 'gidNumber']
)
for member in memberz:
self.update_user_cines_c4(member, group, comite)
def update_user_cines_c4(self, user, group, comite):
user_attrz = user.get_attributes()
user_uid = user_attrz['uid'][0]
if (
self.is_ccc_group(user_uid)
and (
'cinesC4' not in user_attrz
or user_attrz['cinesC4'][0] != comite
)
):
if not comite and 'cinesC4' in user_attrz:
old_comite = user_attrz['cinesC4'][0]
self.ldap.remove_uid_attribute(
user_uid,
[('cinesC4', None)]
)
self.rem_user_from_container(user_uid, old_comite)
elif comite:
if "cinesC4" in user_attrz:
old_comite = user_attrz['cinesC4'][0]
self.rem_user_from_container(user_uid, old_comite)
self.add_user_to_container(user_uid, comite)
self.ldap.update_uid_attribute(
user_uid,
[('cinesC4', comite.encode('utf-8'))])
print(u'{0} : Nouveau comité pour {1} -> {2}'.format(
session['uid'],
user_uid,
comite).encode('utf-8')
)
def add_user_to_container(self, user_uid, container_cn):
container_dn = "cn={0},ou=grConteneur,ou=groupePosix,{1}".format(
container_cn,
self.ldap_search_base
)
pre_modlist = []
pre_modlist.append(('memberUid', [user_uid.encode('utf-8')]))
self.ldap.add_dn_attribute(container_dn, pre_modlist)
def rem_user_from_container(self, user_uid, container_cn):
container_dn = "cn={0},ou=grConteneur,ou=groupePosix,{1}".format(
container_cn,
self.ldap_search_base
)
pre_modlist = []
pre_modlist.append(('memberUid', [user_uid.encode('utf-8')]))
self.ldap.remove_dn_attribute(container_dn, pre_modlist)
def update_password_from_form(self, form, uid):
pre_modlist = []
if self.cache.get_group_from_member_uid(uid) == 'cines':
nt_hash = hashlib.new(
'md4',
strip(form.new_pass.data).encode('utf-16le')
).hexdigest().upper()
pre_modlist = [('sambaPwdLastSet', str(int(time.time()))),
('sambaNTPassword', nt_hash)]
if uid != session['uid']:
pre_modlist.append(('userPassword',
strip(form.new_pass.data).encode('utf-8')))
if self.cache.get_group_from_member_uid(uid) not in ['autre', 'soft']:
pre_modlist.append(('pwdReset', 'TRUE'))
if self.ldap.update_uid_attribute(uid, pre_modlist):
flash(u'Mot de passe pour {0} mis à jour avec succès.'.format(uid))
print(u'{0} : Mise à jour du mot de passe pour {1}'.format(
session['uid'],
uid).encode('utf-8')
)
return redirect(url_for('show_user',
page= self.cache.get_group_from_member_uid(uid),
uid=uid))
else:
if self.ldap.change_passwd(
uid,
session['password'],
strip(form.new_pass.data)
):
flash(
u'Votre mot de passe a été mis à jour avec succès.'.format(uid)
)
print(u'{0} : Mise à jour du mot de passe pour {1}'.format(
session['uid'],
uid).encode('utf-8')
)
if pre_modlist:
self.ldap.update_uid_attribute(uid, pre_modlist)
return redirect(url_for('home'))
def update_page_from_form(self, page, raw_form):
form = raw_form['form']
page_oc_id_list = raw_form['page_oc_id_list']
page_unic_attr_id_list = raw_form['page_unic_attr_id_list']
attr_label_list = raw_form['attr_label_list']
if attr_label_list is not None:
self.update_fields_from_edit_page_admin_form(form, attr_label_list, page)
if form.oc_form.selected_oc.data is not None:
# On traite les ObjectClass ajoutées
for oc_id in form.oc_form.selected_oc.data :
if oc_id not in page_oc_id_list:
print("Creation de l'Object Class id {0}".format(oc_id))
page_oc = PageObjectClass(page.id, oc_id)
db.session.add(page_oc)
# On traite les ObjectClass supprimées
# et les fieldz associés en cascade
for oc_id in page_oc_id_list:
if oc_id not in form.oc_form.selected_oc.data:
print("Suppression de l'Object Class id {0}".format(oc_id))
PageObjectClass.query.filter_by(page_id=page.id,
ldapobjectclass_id= oc_id
).delete()
attr_to_del_list = [
attr.id for attr in get_attr_from_oc_id_list([oc_id])
]
print("Attributs à supprimer {0}".format(attr_to_del_list))
Field.query.filter(Field.page_id==page.id,
Field.ldapattribute_id.in_(
attr_to_del_list
)
).delete(synchronize_session='fetch')
if form.attr_form.selected_attr.data is not None:
# On traite les Attributes ajoutées
for attr_id in form.attr_form.selected_attr.data :
if attr_id not in page_unic_attr_id_list:
print("Creation de l'attribut id {0}".format(attr_id))
attr = LDAPAttribute.query.filter_by(id = attr_id).first()
self.create_default_field(attr, page)
if page_unic_attr_id_list is not None:
# On traite les Attributes supprimées
for attr_id in page_unic_attr_id_list:
if attr_id not in form.attr_form.selected_attr.data:
print("Suppression de l'attribut id {0}".format(attr_id))
Field.query.filter_by(
id=attr_id
).delete()
db.session.commit()
print(u'{0} : Page {1} mise à jour'.format(
session['uid'],
page.label).encode('utf-8')
)
def update_lac_admin_from_form(self, form):
group_dn = "cn=lacadmin,ou=system,{0}".format(self.ldap_search_base)
memberz = [ get_uid_from_dn(dn)
for dn in self.ldap.get_lac_admin_memberz() ]
if form.selected_memberz.data is not None:
memberz_to_add = []
for member in form.selected_memberz.data:
if member not in memberz:
memberz_to_add.append(self.ldap.get_full_dn_from_uid(member))
if memberz_to_add:
self.ldap.add_dn_attribute(group_dn,
[('member', member.encode('utf8'))
for member in memberz_to_add]
)
if memberz is not None:
memberz_to_del = []
for member in memberz:
if member not in form.selected_memberz.data:
memberz_to_del.append(self.ldap.get_full_dn_from_uid(member))
if memberz_to_del:
self.ldap.remove_dn_attribute(group_dn,
[('member', member.encode('utf8'))
for member in memberz_to_del]
)
self.fm.populate_ldap_admin_choices(form)
print(u'{0} : Update des admin lac : {1}'.format(
session['uid'],
form.selected_memberz.data
if form.selected_memberz.data is not None
else "vide").encode('utf-8')
)
def update_ldap_admin_from_form(self, form):
group_dn = "cn=ldapadmin,ou=system,{0}".format(self.ldap_search_base)
memberz = [ get_uid_from_dn(dn)
for dn in self.ldap.get_ldap_admin_memberz() ]
if form.selected_memberz.data is not None:
memberz_to_add = []
for member in form.selected_memberz.data:
if member not in memberz:
memberz_to_add.append(self.ldap.get_full_dn_from_uid(member))
if memberz_to_add:
self.ldap.add_dn_attribute(group_dn,
[('member', member.encode('utf8'))
for member in memberz_to_add]
)
if memberz is not None:
memberz_to_del = []
for member in memberz:
if member not in form.selected_memberz.data:
memberz_to_del.append(self.ldap.get_full_dn_from_uid(member))
if memberz_to_del:
self.ldap.remove_dn_attribute(group_dn,
[('member', member.encode('utf8'))
for member in memberz_to_del]
)
self.fm.populate_ldap_admin_choices(form)
print(u'{0} : Update des admin ldap : {1}'.format(
session['uid'],
form.selected_memberz.data
if form.selected_memberz.data is not None
else "vide").encode('utf-8')
)
def get_last_used_id(self, ldap_ot):
attributes=['gidNumber'] if ldap_ot.apply_to == 'group' else ['uidNumber']
if ldap_ot.apply_to == 'group':
ldap_filter = '(objectClass=posixGroup)'
else:
ldap_filter = '(objectClass=posixAccount)'
base_dn='ou={0},ou={1},{2}'.format(
ldap_ot.label,
'groupePosix' if ldap_ot.apply_to == 'group' else 'people',
self.ldap_search_base
)
resultz = self.ldap.search(base_dn,ldap_filter,attributes)
if not resultz:
return 0
max_id= 0
for result in resultz:
result_id = int(result.get_attributes()[attributes[0]][0])
if result_id > max_id:
max_id = result_id
return str(max_id)
def is_active(self, user):
user_attrz = user.get_attributes()
if ('shadowExpire' in user_attrz and datetime.now()> self.converter.days_number_to_datetime(
user_attrz['shadowExpire'][0]
)) or ('pwdAccountLockedTime' in user_attrz):
return False
else:
return True
def create_default_quota(self, form):
cn = strip(form.common_name.data).encode('utf-8')
dn = 'cn={0},ou=quota,ou=system,{1}'.format(cn, self.ldap_search_base)
cinesQuotaSizeHard = self.fm.get_quota_value_from_form(
form,
'cinesQuotaSizeHard')
cinesQuotaSizeSoft = self.fm.get_quota_value_from_form(
form,
'cinesQuotaSizeSoft')
cinesQuotaInodeHard = self.fm.get_quota_value_from_form(
form,
'cinesQuotaInodeHard')
cinesQuotaInodeSoft = self.fm.get_quota_value_from_form(
form,
'cinesQuotaInodeSoft')
pre_modlist = [
('cn', cn),
('objectClass', ['top', 'cinesQuota']),
('cinesQuotaSizeHard', cinesQuotaSizeHard),
('cinesQuotaSizeSoft', cinesQuotaSizeSoft),
('cinesQuotaInodeHard', cinesQuotaInodeHard),
('cinesQuotaInodeSoft', cinesQuotaInodeSoft)]
self.ldap.add(dn, pre_modlist)
print(u'{0} : Quota par défaut {1} créé'.format(
session['uid'],
cn).encode('utf-8')
)
def update_default_quota(self, storage_cn, form):
storage_dn = "cn={0},ou=quota,ou=system,{1}".format(
storage_cn,
self.ldap_search_base
)
cinesQuotaSizeHard = self.fm.get_quota_value_from_form(
form,
'cinesQuotaSizeHard')
cinesQuotaSizeSoft = self.fm.get_quota_value_from_form(
form,
'cinesQuotaSizeSoft')
cinesQuotaInodeHard = self.fm.get_quota_value_from_form(
form,
'cinesQuotaInodeHard')
cinesQuotaInodeSoft = self.fm.get_quota_value_from_form(
form,
'cinesQuotaInodeSoft')
pre_modlist = [('cinesQuotaSizeHard', cinesQuotaSizeHard),
('cinesQuotaSizeSoft', cinesQuotaSizeSoft),
('cinesQuotaInodeHard', cinesQuotaInodeHard),
('cinesQuotaInodeSoft', cinesQuotaInodeSoft)]
self.ldap.update_dn_attribute(storage_dn, pre_modlist)
print(u'{0} : Quota par défaut {1} mis à jour'.format(
session['uid'],
storage_cn).encode('utf-8')
)
def update_quota(self, storage, form):
storage_cn = storage['cn'][0]
default_storage_cn, group_id = storage_cn.split('.G.')
default_storage = self.ldap.get_default_storage(default_storage_cn).get_attributes()
storage_dn = "cn={0},cn={1},ou={2},ou=groupePosix,{3}".format(
storage_cn,
self.cache.get_posix_group_cn_by_gid(group_id),
self.ldap.get_branch_from_posix_group_gidnumber(group_id),
self.ldap_search_base
)
pre_modlist = []
for field_name in self.app.config['QUOTA_FIELDZ']:
form_value = self.fm.get_quota_value_from_form(
form,
field_name)
default_field = self.app.config['QUOTA_FIELDZ'][field_name]['default']
if (
form_value != default_storage[default_field][0]
and (field_name not in storage
or form_value != storage[field_name][0])
):
pre_modlist.append((field_name, form_value))
if form.cinesQuotaSizeTempExpire.data:
cinesQuotaSizeTempExpire = self.converter.datetime_to_timestamp(
form.cinesQuotaSizeTempExpire.data
).encode('utf-8')
if (form.cinesQuotaSizeTempExpire.data is not None
and (
'cinesQuotaSizeTempExpire' not in storage
or cinesQuotaSizeTempExpire != storage[
'cinesQuotaSizeTempExpire'
]
)
):
pre_modlist.append(('cinesQuotaSizeTempExpire',
cinesQuotaSizeTempExpire))
if form.cinesQuotaInodeTempExpire.data:
cinesQuotaInodeTempExpire = self.converter.datetime_to_timestamp(
form.cinesQuotaInodeTempExpire.data
).encode('utf-8')
if (form.cinesQuotaInodeTempExpire.data is not None
and (
'cinesQuotaInodeTempExpire' not in storage
or cinesQuotaInodeTempExpire != storage[
'cinesQuotaInodeTempExpire'
]
)
):
pre_modlist.append(('cinesQuotaInodeTempExpire',
cinesQuotaInodeTempExpire))
self.ldap.update_dn_attribute(storage_dn, pre_modlist)
print(u'{0} : Quota par spécifique {1} mis à jour'.format(
session['uid'],
storage_cn).encode('utf-8')
)
def populate_last_used_idz(self):
ignore_ot_list = ['reserved', 'grLight', 'grPrace']
ldap_otz = LDAPObjectType.query.all()
for ldap_ot in ldap_otz:
if ldap_ot.label not in ignore_ot_list:
last_used_id = self.get_last_used_id(ldap_ot)
id_range = self.get_range_list_from_string(ldap_ot.ranges)
if int(last_used_id) not in id_range:
last_used_id = id_range[0]
ldap_ot.last_used_id = last_used_id
db.session.add(ldap_ot)
db.session.commit()
def create_ldapattr_if_not_exists(self, label):
db_attr = LDAPAttribute.query.filter_by(
label = label
).first()
if db_attr is None:
db_attr = LDAPAttribute(label=label)
return db_attr
def create_ldap_object_from_add_group_form(self, form, page_label):
ot = LDAPObjectType.query.filter_by(label = page_label).first()
cn = strip(form.cn.data).encode('utf-8')
description = strip(form.description.data).encode('utf-8')
id_number = str(self.get_next_id_from_ldap_ot(ot))
object_classes = [oc_ot.ldapobjectclass.label.encode('utf-8')
for oc_ot in LDAPObjectTypeObjectClass.query.filter_by(
ldapobjecttype_id = ot.id).all()]
if not object_classes:
flash(u'ObjectClasss manquants pour ce type d\'objet')
return 0
full_dn = "cn={0},ou={1},ou=groupePosix,{2}".format(
cn,
ot.label,
self.ldap_search_base)
add_record = [('cn', [cn]),
('gidNumber', [id_number]),
('objectClass', object_classes)]
if page_label != 'grProjet':
add_record.append(('fileSystem', [form.filesystem.data.encode('utf-8')]))
if description and description != '':
add_record.append(('description', [description]))
if hasattr(form, 'responsable'):
add_record.append(('cinesProjResp', [form.responsable.data.encode('utf-8')]))
if 'sambaGroupMapping' in object_classes:
add_record.extend([
('sambaSID', "{0}-{1}".format(self.ldap.get_sambasid_prefix(),
id_number)),
('sambaGroupType', ['2'])
])
if self.ldap.add(full_dn, add_record):
ot.last_used_id= id_number
db.session.add(ot)
db.session.commit()
self.cache.populate_grouplist()
self.cache.populate_people_group()
flash(u'Groupe créé')
print(u'{0} : Groupe posix {1} créé'.format(
session['uid'],
cn).encode('utf-8')
)
return 1
def create_ldap_object_from_add_workgroup_form(self, form):
ot = LDAPObjectType.query.filter_by(label = 'grTravail').first()
cn = strip(form.cn.data).encode('utf-8')
description = strip(form.description.data).encode('utf-8')
object_classes = [oc_ot.ldapobjectclass.label.encode('utf-8')
for oc_ot in LDAPObjectTypeObjectClass.query.filter_by(
ldapobjecttype_id = ot.id).all()]
if not object_classes:
flash(u'ObjectClasss manquants pour ce type d\'objet')
return 0
full_dn = "cn={0},ou=grTravail,{1}".format(
cn,
self.ldap_search_base)
add_record = [('cn', [cn]),
('cinesGrWorkType', [
getattr(form, 'cinesGrWorkType').data.encode('utf-8')
]),
('uniqueMember', [self.ldap_admin]),
('objectClass', object_classes)]
if description and description != '':
add_record.append(('description', [description]))
if self.ldap.add(full_dn, add_record):
db.session.add(ot)
db.session.commit()
self.cache.populate_work_group()
flash(u'Groupe créé')
print(u'{0} : Groupe de travail {1} créé'.format(
session['uid'],
cn).encode('utf-8')
)
return 1
def create_ldap_object_from_add_container_form(self, form):
ot = LDAPObjectType.query.filter_by(label = 'grConteneur').first()
cn = strip(form.cn.data).encode('utf-8')
description = strip(form.description.data).encode('utf-8')
object_classes = [oc_ot.ldapobjectclass.label.encode('utf-8')
for oc_ot in LDAPObjectTypeObjectClass.query.filter_by(
ldapobjecttype_id = ot.id).all()]
id_number = str(self.get_next_id_from_ldap_ot(ot))
if not object_classes:
flash(u'ObjectClasss manquants pour ce type d\'objet')
return 0
full_dn = "cn={0},ou=grConteneur,ou=groupePosix,{1}".format(
cn,
self.ldap_search_base)
add_record = [('cn', [cn]),
('gidNumber', [id_number]),
('objectClass', object_classes)]
if description and description != '':
add_record.append(('description', [description]))
if self.ldap.add(full_dn, add_record):
ot.last_used_id= id_number
db.session.add(ot)
db.session.commit()
self.cache.populate_work_group()
flash(u'Groupe créé')
print(u'{0} : Conteneur {1} créé'.format(
session['uid'],
cn).encode('utf-8')
)
return 1
def create_ldap_object_from_add_user_form(self, form, fieldz, page):
ldap_ot = LDAPObjectType.query.filter_by(
label=page.label
).first()
ldap_ot_ocz = LDAPObjectTypeObjectClass.query.filter_by(
ldapobjecttype_id = ldap_ot.id
).all()
ot_oc_list = [oc.ldapobjectclass.label.encode('utf-8')
for oc in ldap_ot_ocz]
form_attributez = []
uid = form.uid.data
for field in fieldz:
form_field_values = [
strip(
self.converter.from_display_mode(
entry.data,
field.fieldtype.type
)
)
for entry in getattr(form, field.label).entries
]
if field.label == 'cinesdaterenew' :
now_days_number = self.converter.datetime_to_days_number(datetime.now())
if form_field_values[0] == now_days_number :
form_field_values = []
if (field.label not in ['cinesUserToPurge', 'cn', 'cinesIpClient']
and form_field_values != [''] ):
form_attributez.append((field.label, form_field_values))
if (field.label == 'cinesIpClient' and form_field_values != ['']):
form_attributez.append((field.label, ';'.join(form_field_values)))
if field.label == 'gidNumber':
gid_number = form_field_values[0]
self.cache.add_to_people_group_if_not_member(
self.cache.get_posix_group_cn_by_gid(gid_number),
[uid.encode('utf-8')])
uid_number = self.get_next_id_from_ldap_ot(ldap_ot)
add_record = [('uid', [uid.encode('utf-8')]),
('cn', [uid.encode('utf-8')]),
('uidNumber', [str(uid_number).encode('utf-8')]),
('objectClass', ot_oc_list)]
add_record.extend(form_attributez)
add_record.append(
('homeDirectory', "/home/{0}".format(uid).encode('utf-8')))
add_record.append(
('shadowlastchange',
[str(self.converter.datetime_to_days_number(datetime.now()))]
)
)
if 'cinesusr' in ot_oc_list:
add_record.append(
('cinesSoumission', [self.ldap.get_initial_submission()])
)
if 'sambaSamAccount' in ot_oc_list:
add_record.append(
('sambaSID', "{0}-{1}".format(self.ldap.get_sambasid_prefix(),
uid_number))
)
if page.label == 'ccc' and gid_number:
group_cn = self.cache.get_posix_group_cn_by_gid(gid_number)
ressource = C4Ressource.query.filter_by(
code_projet = group_cn).first()
if ressource:
comite = ressource.comite.ct
else:
comite = ''
if comite != '':
add_record.append(
('cinesC4', comite.encode('utf-8'))
)
self.add_user_to_container(uid, comite)
if ldap_ot.ppolicy != '':
add_record.append(
('pwdPolicySubentry',
'cn={0},ou=policies,ou=system,{1}'.format(
ldap_ot.ppolicy,
self.ldap_search_base)
)
)
parent_dn = self.ldap.get_people_dn_from_ou(ldap_ot.label)
full_dn = "uid={0};{1}".format(uid,parent_dn)
if self.ldap.add(full_dn, add_record):
ldap_ot.last_used_id= uid_number
db.session.add(ldap_ot)
db.session.commit()
self.cache.populate_grouplist()
self.cache.populate_people_group()
print(u'{0} : Utilisateur {1} créé'.format(
session['uid'],
uid).encode('utf-8')
)
else:
flash(u'L\'utilisateur n\'a pas été créé')
return True
def create_ldap_object_from_add_object_type_form(self,
form,
ldap_object_type ):
selected_oc_choices = self.fm.get_ot_oc_choices(ldap_object_type)
ot_oc_id_list = [oc[0] for oc in selected_oc_choices]
ldap_object_type.label = strip(form.label.data)
ldap_object_type.description = strip(form.description.data)
ldap_object_type.ranges = strip(form.ranges.data)
ldap_object_type.apply_to = strip(form.apply_to.data)
ldap_object_type.ppolicy = form.ppolicy.data
db.session.add(ldap_object_type)
if form.object_classes.selected_oc.data is not None:
# On traite les ObjectClass ajoutées
for oc_id in form.object_classes.selected_oc.data :
if oc_id not in ot_oc_id_list:
print("Creation de l'Object Class id {0}".format(oc_id))
ot_oc = LDAPObjectTypeObjectClass(
ldap_object_type.id, oc_id)
db.session.add(ot_oc)
# On traite les ObjectClass supprimées
# et les fieldz associés en cascade
for oc_id in ot_oc_id_list:
if oc_id not in form.object_classes.selected_oc.data:
print("Suppression de l'Object Class id {0}".format(oc_id))
LDAPObjectTypeObjectClass.query.filter_by(
ldapobjecttype_id=ldap_object_type.id,
ldapobjectclass_id= oc_id
).delete()
db.session.commit()
if form.set_ppolicy.data :
self.ldap.set_group_ppolicy(ldap_object_type.label,
ldap_object_type.ppolicy)
flash(u'{0} mis à jour'.format(ldap_object_type.description))
print(u'{0} : Type d\'objet {1} créé'.format(
session['uid'],
ldap_object_type.label).encode('utf-8')
)
def create_ldap_quota(self, storage, group_id):
niou_cn = '{0}.G.{1}'.format(
storage,
group_id)
default_storage = self.ldap.get_default_storage(
storage).get_attributes()
add_record = [
('cn', [niou_cn]),
('objectClass', ['top', 'cinesQuota']),
('cinesQuotaSizeHard', default_storage['cinesQuotaSizeHard']),
('cinesQuotaSizeSoft', default_storage['cinesQuotaSizeSoft']),
('cinesQuotaInodeHard', default_storage['cinesQuotaInodeHard']),
('cinesQuotaInodeSoft', default_storage['cinesQuotaInodeSoft'])
]
group_full_dn = self.ldap.get_full_dn_from_cn(
self.cache.get_posix_group_cn_by_gid(group_id))
full_dn = 'cn={0},{1}'.format(niou_cn,group_full_dn)
self.ldap.add(full_dn, add_record)
flash(u'Quota initialisé')
print(u'{0} : Quota spécifique {1} créé'.format(
session['uid'],
niou_cn).encode('utf-8')
)
def update_users_by_file(self, edit_form, attrz_list):
fieldz = Field.query.filter(Field.id.in_(attrz_list)).all()
pre_modlist = []
for field in fieldz:
pre_modlist.append(
(field.label,
strip(getattr(edit_form, field.label).data).encode('utf-8'))
)
if edit_form.action.data == '0':
for uid in userz:
ldap.add_uid_attribute(uid, pre_modlist)
elif edit_form.action.data == '1':
for uid in userz:
ldap.update_uid_attribute(uid, pre_modlist)
flash(u'Les utilisateurs ont été mis à jour')
def generate_backup_file(self, userz, attributez):
userz = [strip(user).encode('utf-8') for user in userz.split(',')]
attributez = [strip(attribute).encode('utf-8')
for attribute in attributez.split(',')]
file_name = "backup_{0}.txt".format(
datetime.now().strftime("%d%b%HH%M_%Ss"))
file_content = " ".join(attributez)
for user in userz:
user_attr = ldap.search(
ldap_filter="(uid={0})".format(user),
attributes=attributez)[0].get_attributes()
line = ",".join(["{0}={1}".format(key, value)
for key, value in user_attr.iteritems()])
line = ",".join(["uid={0}".format(user),line])
file_content = "\n".join([file_content, line])
response = make_response(file_content)
response.headers[
'Content-Disposition'
] = 'attachment; filename={0}'.format(file_name)
return response
def get_next_id_from_ldap_ot(self, ldap_ot):
id_range = self.get_range_list_from_string(ldap_ot.ranges)
next_index = id_range.index(ldap_ot.last_used_id)+1
if ldap_ot.apply_to == 'group':
id_type = 'gidNumber'
else:
id_type = 'uidNumber'
while 1:
test_id = id_range[next_index]
ldap_filter = '({0}={1})'.format(id_type, test_id)
result = self.ldap.search(ldap_filter=ldap_filter,
attributes = [id_type])
if not result:
return test_id
next_index += 1
def get_storagez_labelz(self):
storagez = self.ldap.get_group_quota_list()
storagez_labelz = [storage.get_attributes()['cn'][0]
for storage in storagez]
return storagez_labelz
def get_range_list_from_string(self, rangez_string):
rangez = rangez_string.split(';')
rangez_lst = []
for range_string in rangez:
if range_string != '':
range_split = range_string.split('-')
rangez_lst.extend(range(
int(range_split[0]),
int(range_split[1])+1))
return sorted(set(rangez_lst))
def update_ldap_object_from_edit_ppolicy_form(self, form, attributes, cn):
dn = "cn={0},ou=policies,ou=system,{1}".format(
cn,
self.ldap_search_base)
ppolicy_attrz = self.ldap.get_ppolicy(cn).get_attributes()
pre_modlist = []
for attr in attributes:
field_value = strip(getattr(form, attr).data).encode('utf-8')
if attr not in ppolicy_attrz or ppolicy_attrz[attr][0] != field_value:
# if attr == 'pwdMustChange':
# pre_modlist.append((attr, [True if field_value else False]))
# else:
pre_modlist.append((attr, [field_value]))
self.ldap.update_dn_attribute(dn, pre_modlist)
print(u'{0} : Ppolicy {1} créée'.format(
session['uid'],
cn).encode('utf-8')
)
def update_ldap_object_from_edit_user_form(self, form, fieldz, uid, page):
user = self.ldap.get_uid_detailz(uid)
uid_attributez = user.get_attributes()
pre_modlist = []
for field in fieldz:
form_values = [
strip(
self.converter.from_display_mode(
entry.data,
field.fieldtype.type
)
)
for entry in getattr(form, field.label).entries
]
if field.label == 'cinesIpClient':
form_values = [';'.join(form_values)]
if (field.label not in uid_attributez
or uid_attributez[field.label] != form_values):
if form_values == [''] or (field.label == 'cinesUserToPurge'
and True not in form_values):
form_values = None
if (
field.label == 'cinesUserToPurge'
and form_values
and True in form_values
):
form_values = ['1']
pre_modlist.append((field.label, form_values))
if page.label == 'ccc' and field.label == 'gidNumber':
group_cn = self.cache.get_posix_group_cn_by_gid(form_values[0])
ressource = C4Ressource.query.filter_by(
code_projet = group_cn).first()
if ressource:
comite = ressource.comite.ct
else:
comite = ''
if (
comite != ''
and "cinesC4" in uid_attributez
and uid_attributez['cinesC4'] != comite
):
pre_modlist.append(
('cinesC4', comite.encode('utf-8'))
)
self.update_user_cines_c4(user, group_cn, comite)
self.ldap.update_uid_attribute(uid, pre_modlist)
self.cache.populate_people_group()
print(u'{0} : Mise à jour de l\'utilisteur {1}'.format(
session['uid'],
uid).encode('utf-8')
)
def upsert_otrs_user(self, uid):
user_attrz = self.ldap.get_uid_detailz(uid).get_attributes()
otrs_user = OTRSCustomerUser.query.filter_by(login = uid).first()
if not otrs_user:
otrs_user = OTRSCustomerUser(login = uid)
if 'telephoneNumber' in user_attrz:
telephone_number = ';'.join(
[phone for phone in user_attrz['telephoneNumber']])
else:
telephone_number = ''
user_type = LDAPObjectType.query.filter_by(
label = self.cache.get_group_from_member_uid(uid)
).first().description
first_gr_name = self.cache.get_posix_group_cn_by_gid(user_attrz['gidNumber'][0])
otrs_user.email = user_attrz['mail'][0]
otrs_user.customer_id = user_attrz['uidNumber'][0]
otrs_user.first_name = user_attrz['givenName'][0]
otrs_user.last_name = user_attrz['sn'][0]
otrs_user.phone = telephone_number
otrs_user.comments = '{0}; {1}'.format(user_type, first_gr_name)
otrs_user.valid_id = 1
otrs_user.create_time = datetime.now()
db.session.add(otrs_user)
db.session.commit()
def delete_otrs_user(self, uid):
date = datetime.now().strftime("%Y%m%d%H%M")
disabled_login = "".join(['ZDEL', date, "_", uid])
# print(disabled_login)
otrs_user = OTRSCustomerUser.query.filter_by(login = uid).first()
if otrs_user:
otrs_user.login = disabled_login
otrs_user.valid_id = 2
db.session.add(otrs_user)
otrs_ticketz = OTRSTicket.query.filter_by(customer_user_id = uid).all()
for ticket in otrs_ticketz:
ticket.customer_user_id = disabled_login
db.session.add(ticket)
if self.is_cines_group(uid):
OTRSUser.query.filter_by(login=uid).update(
{
'valid_id': 2,
'login': disabled_login,
'change_time': datetime.now()
}, synchronize_session=False
)
db.session.commit()
def update_user_table_on_deletion(self, uid):
ldap_user = self.ldap.get_uid_detailz(uid).get_attributes()
db_user = db.session.query(User).filter_by(uid=uid).first()
# Create user if doesn't already exists
if not db_user:
db_user = User(uid=uid)
db.session.add(db_user)
db_user.uid_number = ldap_user['uidNumber'][0].decode('utf-8')
db_user.firstname = ldap_user['givenName'][0].decode('utf-8')
db_user.lastname = ldap_user['sn'][0].decode('utf-8')
db_user.deletion_timestamp = datetime.now()
if 'mail' in ldap_user:
db_user.email = ldap_user['mail'][0].decode('utf-8')
if 'telephoneNumber' in ldap_user:
db_user.phone_number = ldap_user['telephoneNumber'][0].decode('utf-8')
db.session.commit()
def remove_user_from_all_groupz(self, uid, posix_groupz, work_groupz):
user_dn = self.ldap.get_full_dn_from_uid(uid)
for group_cn in work_groupz:
group_dn = 'cn={0},ou=grTravail,{1}'.format(
group_cn,
self.ldap_search_base
)
pre_modlist = [('uniqueMember', user_dn.encode('utf-8'))]
self.ldap.remove_dn_attribute(group_dn,pre_modlist)
for (group_cn, group_branch) in posix_groupz:
group_dn = self.ldap.get_group_full_dn(group_branch, group_cn)
pre_modlist = [('memberUid', uid.encode('utf-8'))]
self.ldap.remove_dn_attribute(group_dn,pre_modlist)
def set_user_submissionz(self, uid, formz):
for group in self.ldap.get_submission_groupz_list():
form = getattr(formz, group)
is_submission = form.submission.data
is_member = form.member.data
if is_submission and is_member:
self.cache.add_to_work_group_if_not_member(group, [uid])
self.ldap.set_submission(uid, group, '1')
elif is_member and not is_submission:
self.cache.add_to_work_group_if_not_member(group, [uid])
self.ldap.set_submission(uid, group, '0')
elif not is_member:
self.cache.rem_from_workgroup_if_member(group, [uid])
self.ldap.set_submission(uid, group, '0')
def update_user_submission(self, uid, form):
wrk_group = strip(form.wrk_group.data)
is_submission = form.submission.data
is_member = form.member.data
if is_submission and is_member:
self.cache.add_to_work_group_if_not_member(wrk_group, [uid])
self.ldap.set_submission(uid, wrk_group, '1')
elif is_member and not is_submission:
self.cache.add_to_work_group_if_not_member(wrk_group, [uid])
self.ldap.set_submission(uid, wrk_group, '0')
elif not is_member:
self.cache.rem_from_workgroup_if_member(wrk_group, [uid])
self.ldap.set_submission(uid, wrk_group, '0')
def update_group_submission(self, form):
groupz_id = form.group_form.selected_groupz.data
groupz_infoz = [
(self.ldap.get_branch_from_posix_group_gidnumber(id),
self.cache.get_posix_group_cn_by_gid(id))
for id in groupz_id
]
groupz_memberz = self.ldap.get_posix_groupz_memberz(groupz_infoz)
wrk_group = form.submission_form.wrk_group.data
is_submission = form.submission_form.submission.data
is_member = form.submission_form.member.data
if is_submission and is_member:
self.cache.add_to_work_group_if_not_member(
wrk_group,
groupz_memberz_uid)
for uid in groupz_memberz_uid:
self.ldap.set_submission(uid, wrk_group, '1')
elif is_member and not is_submission:
self.cache.add_to_work_group_if_not_member(
wrk_group,
groupz_memberz_uid)
for uid in groupz_memberz_uid:
self.ldap.set_submission(uid, wrk_group, '0')
elif not is_member:
self.cache.rem_from_workgroup_if_member(wrk_group, groupz_memberz_uid)
for uid in groupz_memberz_uid:
self.ldap.set_submission(uid, wrk_group, '0')
def update_ldap_object_from_edit_group_form(self, form, page, group_cn):
ldap_filter='(&(cn={0})(objectClass=posixGroup))'.format(group_cn)
attributes=['*','+']
group_attributez = self.ldap.search(
ldap_filter=ldap_filter,
attributes=attributes)[0].get_attributes()
pagefieldz = Field.query.filter_by(page_id = page.id,
edit = True).all()
pre_modlist = []
for field in pagefieldz:
form_field_values = [strip(entry.data).encode('utf-8')
for entry in getattr(form, field.label).entries]
if form_field_values == ['']:
form_field_values = None
if ((field.label not in group_attributez)
or (field.label in group_attributez
and group_attributez[field.label] != form_field_values)):
pre_modlist.append((field.label, form_field_values))
pre_modlist.append(
('memberuid',
[
member.encode('utf-8') for member in
form.memberz.selected_memberz.data
])
)
group_dn="cn={0},ou={1},ou=groupePosix,{2}".format(
group_cn,
page.label,
self.ldap_search_base)
self.ldap.update_dn_attribute(group_dn, pre_modlist)
print(u'{0} : Groupe posix {1} mis à jour'.format(
session['uid'],
group_cn).encode('utf-8')
)
def update_ldap_object_from_edit_workgroup_form(self, form, page, group_cn):
dn="cn={0},ou=grTravail,{1}".format(
group_cn,
self.ldap_search_base)
ldap_filter='(&(cn={0})(objectClass=cinesGrWork))'.format(group_cn)
attributes=['*','+']
group_attributez = self.ldap.search(
ldap_filter=ldap_filter,
attributes=attributes)[0].get_attributes()
pagefieldz = Field.query.filter_by(page_id = page.id,
edit = True).all()
pre_modlist = []
for field in pagefieldz:
form_field_values = [strip(entry.data).encode('utf-8')
for entry in
getattr(form, field.label).entries]
if form_field_values == ['']:
form_field_values = None
if ((field.label not in group_attributez)
or (field.label in group_attributez
and group_attributez[field.label] != form_field_values)):
pre_modlist.append((field.label, form_field_values))
old_memberz = group_attributez['uniqueMember']
new_memberz = [
self.ldap.get_full_dn_from_uid(member).encode('utf-8')
for member in form.memberz.selected_memberz.data
if self.ldap.get_full_dn_from_uid(member) is not None
]
for member in old_memberz:
if (member not in new_memberz
and self.cache.get_group_from_member_uid(
get_uid_from_dn(member)) == "cines"):
self.ldap.set_submission( get_uid_from_dn(member), group_cn, '0')
pre_modlist.append(
('uniqueMember',
new_memberz
)
)
self.cache.populate_work_group()
self.ldap.update_dn_attribute(dn, pre_modlist)
print(u'{0} : Groupe de travail {1} mis à jour'.format(
session['uid'],
group_cn).encode('utf-8')
)
def update_fields_from_edit_page_admin_form(self, form, attributes, page):
Field.query.filter(Field.page_id == page.id,
~Field.label.in_(attributes)
).delete(synchronize_session='fetch')
for attribute in attributes:
attribute_field = getattr(form, attribute)
self.upsert_field(attribute, attribute_field, page)
def create_default_field(self, attribute, page):
print("Create default {0} for {1}".format(attribute, page.label))
field_type = FieldType.query.filter_by(type='Text').first()
page_attr = Field(label = attribute.label,
page = page,
ldapattribute = attribute,
fieldtype=field_type)
db.session.add(page_attr)
db.session.commit()
return page_attr
def upsert_field(self, attr_label, form_field, page):
attribute = LDAPAttribute.query.filter_by(label = attr_label).first()
field_type = FieldType.query.filter_by(
id=form_field.display_mode.data
).first()
existing_field = Field.query.filter_by(page_id=page.id,
label=attribute.label,
ldapattribute_id=attribute.id
).first()
if existing_field is not None:
existing_field.display = form_field.display.data
existing_field.edit = form_field.edit.data
existing_field.restrict = form_field.restrict.data
existing_field.fieldtype = field_type
existing_field.description = strip(form_field.desc.data)
existing_field.multivalue = form_field.multivalue.data
existing_field.mandatory = form_field.mandatory.data
existing_field.priority = form_field.priority.data
existing_field.block = strip(form_field.block.data)
else:
new_field = Field(label=attribute.label,
page=page,
ldapattribute=attribute,
display=form_field.display.data,
edit=form_field.edit.data,
restrict=form_field.restrict.data,
fieldtype=field_type,
description=form_field.desc.data,
multivalue=form_field.multivalue.data,
mandatory=form_field.mandatory.data,
priority=form_field.priority.data,
block=form_field.block.data)
db.session.add(new_field)
def get_dict_from_raw_log_valuez(self, raw_valuez):
valuez = {}
for raw_value in raw_valuez:
# print(raw_value)
raw_value_split = raw_value.split(":")
attr_name = raw_value_split[0]
attr_operation = raw_value_split[1][:1]
attr_value = raw_value_split[1][1:]
if attr_name in [
'userPassword',
'sambaNTPassword',
'pwdHistory'
]:
attr_value = '<PASSWORD_HASH>'
elif attr_name in [
'pwdChangedTime',
'modifyTimestamp',
'pwdFailureTime',
]:
if attr_value != "":
attr_value = self.converter.generalized_time_to_datetime(
attr_value.strip())
if attr_name not in [
'entryCSN',
'modifiersName',
'modifyTimestamp',
'uidNumber'
]:
if attr_name in valuez:
valuez[attr_name].append(
(attr_value ,
attr_operation)
)
else:
valuez[attr_name] = [(attr_value, attr_operation)]
return valuez
def allowed_file(self, filename):
print("filename : {0}".format(filename))
print(filename.rsplit('.', 1)[1])
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
def get_cinesdaterenew_from_uid(self, uid):
page = Page.query.filter_by(label='ccc').first()
field = Field.query.filter_by(
page_id = page.id,
label = 'cinesdaterenew').first()
ldap_filter='(uid={0})'.format(uid)
attributes=['cinesdaterenew']
base_dn='ou=people,{0}'.format(self.ldap_search_base)
uid_attrz= self.ldap.search(base_dn,ldap_filter,attributes)[0].get_attributes()
if 'cinesdaterenew' in uid_attrz:
date_renew = self.converter.to_display_mode(
uid_attrz['cinesdaterenew'][0], field.fieldtype.type
)
else:
date_renew = ''
return date_renew
def add_ppolicy(self, cn):
dn = "cn={0},ou=policies,ou=system,{1}".format(
cn,
self.ldap_search_base)
add_record=[('cn',[cn]),
('pwdAttribute', ['userPassword']),
('objectClass', ['device', 'pwdPolicy'])]
if self.ldap.add(dn, add_record):
flash(u'PPolicy {0} ajoutée'.format(cn))
print(u'{0} : PPolicy {1} créé'.format(
session['uid'],
cn).encode('utf-8')
)
| T3h-N1k0/LAC | lac/engine.py | Python | gpl-3.0 | 57,871 |
/*
* Created on 10-abr-2006
*
* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibáñez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* dac@iver.es
*/
/* CVS MESSAGES:
*
* $Id:
* $Log:
*/
package com.iver.cit.gvsig.drivers;
import java.awt.geom.Rectangle2D;
import java.sql.Types;
import org.gvsig.topology.ITopologyErrorContainer;
import org.gvsig.topology.Messages;
import org.gvsig.topology.TopologyError;
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
import com.hardcode.gdbms.driver.exceptions.ReloadDriverException;
import com.hardcode.gdbms.driver.exceptions.WriteDriverException;
import com.hardcode.gdbms.engine.data.DataSourceFactory;
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
import com.hardcode.gdbms.engine.data.edition.DataWare;
import com.hardcode.gdbms.engine.values.Value;
import com.hardcode.gdbms.engine.values.ValueFactory;
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
import com.iver.cit.gvsig.fmap.core.FShape;
import com.iver.cit.gvsig.fmap.core.IFeature;
import com.iver.cit.gvsig.fmap.core.IGeometry;
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
public class TopologyErrorMemoryDriver implements VectorialDriver,
ObjectDriver,
BoundedShapes {
public static final Rectangle2D EMPTY_FULL_EXTENT = new Rectangle2D.Double();
public static final String LEGEND_FIELD = Messages.getText("Rule_type");
/**
* Number of fields to show
* */
private static final int NUMBER_OF_FIELDS = 7;
private static final int DEFAULT_FIELD_LENGTH = 20;
private DriverAttributes attr = new DriverAttributes();
/**
* Name of the data source of this driver
*/
String name;
ITopologyErrorContainer errorContainer;
/**
* Full extent of all features
*/
Rectangle2D fullExtent;
/**
* Constructor
* @param name descriptive name of the data source
* @param features collection of features in memory
* @param definition definition of the layer of these features
*/
public TopologyErrorMemoryDriver(String name,
ITopologyErrorContainer errorContainer){
this.name = name;
this.errorContainer = errorContainer;
attr.setLoadedInMemory(true);
computeFullExtent();
}
public int getShapeType() {
return FShape.MULTI;
}
public String getName() {
return name;
}
public int getShapeCount() throws ReadDriverException {
return errorContainer.getNumberOfErrors();
}
public Rectangle2D getFullExtent() throws ReadDriverException, ExpansionFileReadException {
if(fullExtent == null){
//collection is empty
return EMPTY_FULL_EXTENT;
}
return fullExtent;
}
public IGeometry getShape(int index) throws ReadDriverException {
if(index < errorContainer.getNumberOfErrors())
return errorContainer.getTopologyError(index).getGeometry();
else
return null;
}
public void reload() throws ReloadDriverException {
}
public DriverAttributes getDriverAttributes() {
return attr;
}
public boolean isWritable() {
return false;
}
public int[] getPrimaryKeys() throws ReadDriverException {
return null;
}
public void write(DataWare dataWare) throws WriteDriverException, ReadDriverException {
}
public void setDataSourceFactory(DataSourceFactory dsf) {
}
public Value getFieldValue(long rowIndex, int fieldId) throws ReadDriverException {
TopologyError feature = errorContainer.getTopologyError((int) rowIndex);
Value solution = null;
switch(fieldId){
case 0:
solution = ValueFactory.createValue(feature.getViolatedRule().getName());
break;
case 1:
solution = ValueFactory.createValue(feature.getOriginLayer().getName());
break;
case 2:
FLyrVect destinationLyr = feature.getDestinationLayer();
if(destinationLyr != null)
solution = ValueFactory.createValue(feature.getDestinationLayer().getName());
else
solution = ValueFactory.createNullValue();
break;
case 3:
solution = ValueFactory.createValue(feature.getShapeTypeAsText());
break;
case 4://TODO Algunos errores tienen el feature1 y el feature2 a null
IFeature feature1 = feature.getFeature1();
if(feature1 != null)
solution = ValueFactory.createValue(feature1.getID());
else
solution = ValueFactory.createNullValue();
break;
case 5:
IFeature feature2 = feature.getFeature2();
if(feature2 != null)
solution = ValueFactory.createValue(feature2.getID());
else
solution = ValueFactory.createNullValue();
break;
case 6:
solution = ValueFactory.createValue(feature.isException());
break;
}
return solution;
}
public int getFieldCount() throws ReadDriverException {
return NUMBER_OF_FIELDS;
}
public String getFieldName(int fieldId) throws ReadDriverException {
String solution = "";
switch(fieldId){
case 0:
solution = Messages.getText("Rule_type");
break;
case 1:
solution = Messages.getText("Layer_1");
break;
case 2:
solution = Messages.getText("Layer_2");
break;
case 3:
solution = Messages.getText("Shape_Type");
break;
case 4:
solution = Messages.getText("Feature_1");
break;
case 5:
solution = Messages.getText("Feature_2");
break;
case 6:
solution = Messages.getText("Exception");
break;
}
return solution;
}
public long getRowCount() throws ReadDriverException {
return getShapeCount();
}
public int getFieldType(int i) throws ReadDriverException {
int fieldType = -1;
switch(i){
case 0:
case 1:
case 2:
case 3:
fieldType = Types.VARCHAR;
case 4:
case 5:
fieldType = Types.NUMERIC;
case 6:
fieldType = Types.BOOLEAN;
}
return fieldType;
}
public int getFieldWidth(int i) throws ReadDriverException {
return DEFAULT_FIELD_LENGTH;
}
public Rectangle2D getShapeBounds(int index) throws ReadDriverException, ExpansionFileReadException {
IGeometry geometry = getShape(index);
return geometry.getBounds2D();
}
public int getShapeType(int index) throws ReadDriverException {
IGeometry geometry = getShape(index);
return geometry.getGeometryType();
}
private void computeFullExtent() {
for(int i = 0; i < errorContainer.getNumberOfErrors(); i++){
IFeature feature = errorContainer.getTopologyError(i);
Rectangle2D rAux = feature.getGeometry().getBounds2D();
if(fullExtent == null)
fullExtent = rAux;
else
fullExtent.add(rAux);
}
}
}
| iCarto/siga | libTopology/src/com/iver/cit/gvsig/drivers/TopologyErrorMemoryDriver.java | Java | gpl-3.0 | 7,665 |
require 'pathname'
require 'listen/adapter'
require 'listen/change'
require 'listen/record'
require 'listen/silencer'
module Listen
class Listener
attr_accessor :options, :directories, :paused, :changes, :block, :thread
attr_accessor :registry, :supervisor
RELATIVE_PATHS_WITH_MULTIPLE_DIRECTORIES_WARNING_MESSAGE = "The relative_paths option doesn't work when listening to multiple diretories."
# Initializes the directories listener.
#
# @param [String] directory the directories to listen to
# @param [Hash] options the listen options (see Listen::Listener::Options)
#
# @yield [modified, added, removed] the changed files
# @yieldparam [Array<String>] modified the list of modified files
# @yieldparam [Array<String>] added the list of added files
# @yieldparam [Array<String>] removed the list of removed files
#
def initialize(*args, &block)
@options = _init_options(args.last.is_a?(Hash) ? args.pop : {})
@directories = args.flatten.map { |path| Pathname.new(path).realpath }
@changes = []
@block = block
@registry = Celluloid::Registry.new
@supervisor = Celluloid::SupervisionGroup.run!(@registry)
_init_debug
end
# Starts the listener by initializing the adapter and building
# the directory record concurrently, then it starts the adapter to watch
# for changes. The current thread is not blocked after starting.
#
def start
_signals_trap
_init_actors
unpause
registry[:adapter].async.start
@thread = Thread.new { _wait_for_changes }
end
# Terminates all Listen actors and kill the adapter.
#
def stop
@stopping = true
thread.join
end
# Pauses listening callback (adapter still running)
#
def pause
@paused = true
end
# Unpauses listening callback
#
def unpause
registry[:record].build
@paused = false
end
# Returns true if Listener is paused
#
# @return [Boolean]
#
def paused?
@paused == true
end
# Returns true if Listener is not paused
#
# @return [Boolean]
#
def listen?
@paused == false
end
# Adds ignore patterns to the existing one (See DEFAULT_IGNORED_DIRECTORIES and DEFAULT_IGNORED_EXTENSIONS in Listen::Silencer)
#
# @param [Regexp, Array<Regexp>] new ignoring patterns.
#
def ignore(regexps)
@options[:ignore] = [options[:ignore], regexps]
registry[:silencer] = Silencer.new(self)
end
# Overwrites ignore patterns (See DEFAULT_IGNORED_DIRECTORIES and DEFAULT_IGNORED_EXTENSIONS in Listen::Silencer)
#
# @param [Regexp, Array<Regexp>] new ignoring patterns.
#
def ignore!(regexps)
@options.delete(:ignore)
@options[:ignore!] = regexps
registry[:silencer] = Silencer.new(self)
end
# Sets only patterns, to listen only to specific regexps
#
# @param [Regexp, Array<Regexp>] new ignoring patterns.
#
def only(regexps)
@options[:only] = regexps
registry[:silencer] = Silencer.new(self)
end
private
def _init_options(options = {})
{ debug: false,
latency: nil,
wait_for_delay: 0.1,
force_polling: false,
polling_fallback_message: nil }.merge(options)
end
def _init_debug
if options[:debug]
Celluloid.logger.level = Logger::INFO
else
Celluloid.logger = nil
end
end
def _init_actors
supervisor.add(Silencer, as: :silencer, args: self)
supervisor.add(Record, as: :record, args: self)
supervisor.pool(Change, as: :change_pool, args: self)
adapter_class = Adapter.select(options)
supervisor.add(adapter_class, as: :adapter, args: self)
end
def _signals_trap
return if defined?(JRUBY_VERSION)
if Signal.list.keys.include?('INT')
Signal.trap('INT') { stop }
end
end
def _wait_for_changes
loop do
break if @stopping || Listen.stopping
changes = _pop_changes
unless changes.all? { |_,v| v.empty? }
block.call(changes[:modified], changes[:added], changes[:removed])
end
sleep options[:wait_for_delay]
end
supervisor.finalize
rescue => ex
Kernel.warn "[Listen warning]: Change block raised an exception: #{$!}"
Kernel.warn "Backtrace:\n\t#{ex.backtrace.join("\n\t")}"
end
def _pop_changes
changes = { modified: [], added: [], removed: [] }
until @changes.empty?
change = @changes.pop
change.each { |k, v| changes[k] << v.to_s }
end
changes.each { |_, v| v.uniq! }
end
end
end
| ruibarreira/linuxtrail | usr/lib/ruby/vendor_ruby/listen/listener.rb | Ruby | gpl-3.0 | 4,738 |
<?php
/*
NAME: Daily mail
ABOUT: Sends an email each morning with general information about the day
DEPENDENCIES: Location module; Weather module; Email module; Clothes module; News module;
INSTALL: None;
CONFIG: Edit the dailyEmail.tpl file in inc/templates folder to your liking.
*/
$dailyEmail = false;
/*if (date('Hi') == '0700' && ((date('N') == '2') || (date('N') == '4')) ) $dailyEmail = true; // TTh @ 7
elseif (date('Hi') == '1100' && ((date('N') == '1') || (date('N') == '3') || (date('N') == '5')) ) $dailyEmail = true; // MWF @ 11
elseif (date('Hi') == '1200' && ((date('N') == '6') || (date('N') == '7')) ) $dailyEmail = true; //SS @ noon*/
if (date('Hi') == '0700') $dailyEmail = true;
if ($dailyEmail)
{
$arrayNews = alice_news(4);
foreach($arrayNews as $newsItem)
{
$news .= "<a href='{$newsItem->link}'>{$newsItem->title}</a> - {$newsItem->description}<br />";
}
$history = explode("|", file_get_contents("http://jacroe.com/projects/today/api.php")); // This is another project of mine that lists things about today.
$smarty->assign("date", date('l, F j, Y '));
$smarty->assign("city", $l['city']);
$smarty->assign("state", $l['state']);
$smarty->assign("weather", $w);
$smarty->assign("clothes", alice_clothes($w));
$smarty->assign("news", $news);
$smarty->assign("history", $history);
$rawBody = $smarty->fetch('dailyEmail.tpl');
$lines = explode("\n", $rawBody);
$subject = trim(array_shift($lines));
$body = join("\n", $lines);
alice_email_send(NAME, EMAIL, $subject, $body);
sleep(30);
}
?>
| jacroe/alice | recipes/daily-email.php | PHP | gpl-3.0 | 1,567 |
#include "elevador.h"
#include <iostream>
using namespace std;
int main(void){
elevador e1;
e1.inicializa(10,8);
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.sai();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.entra();
cout <<"nro pessoas no elevador" << e1.getNroPessoas () <<endl;
e1.sobe();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.sobe();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.sobe();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.sobe();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.sobe();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.sobe();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.sobe();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.sobe();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.sobe();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.desce();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.desce();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.desce();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.desce();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.desce();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.desce();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.desce();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
e1.desce();
if(e1.getAndarAtual())
cout << "Elevador no " << e1.getAndarAtual() << "o andar " << endl;
else cout << "Elevador no terreo" <<endl;
return 0;
}
| nedisonn/LAPROII | elevador/main.cpp | C++ | gpl-3.0 | 3,690 |
/*
###############################
# Copyright (C) 2012 Jon Schang
#
# This file is part of jSchangLib, released under the LGPLv3
#
# jSchangLib 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.
#
# jSchangLib 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 jSchangLib. If not, see <http://www.gnu.org/licenses/>.
###############################
*/
package com.jonschang.investing.trading;
import com.jonschang.investing.*;
public class PlatformException extends InvestingException {
public PlatformException() {super();}
public PlatformException(String mesg) {super(mesg);}
public PlatformException(String mesg, Throwable cause) {super(mesg,cause);}
public PlatformException(Throwable cause) {super(cause);}
}
| jschang/jSchangLib | investing/src/main/java/com/jonschang/investing/trading/PlatformException.java | Java | gpl-3.0 | 1,214 |
# -*- 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 ulakbus.models import User
from .general import fake
__author__ = 'Ali Riza Keles'
def new_user(username=None, password=None, superuser=False):
user = User(
username=username or fake.user_name(),
password=password or fake.password(),
superuser=superuser
)
user.save()
return user
| yetercatikkas/ulakbus | tests/fake/user.py | Python | gpl-3.0 | 515 |
package hunternif.mc.dota2items;
import hunternif.mc.dota2items.client.RenderTickHandler;
import hunternif.mc.dota2items.client.SwingTickHandler;
import hunternif.mc.dota2items.client.gui.FontRendererContourShadow;
import hunternif.mc.dota2items.client.gui.FontRendererWithIcons;
import hunternif.mc.dota2items.client.gui.GuiDotaStats;
import hunternif.mc.dota2items.client.gui.GuiGold;
import hunternif.mc.dota2items.client.gui.GuiHealthAndMana;
import hunternif.mc.dota2items.client.gui.GuiManaBar;
import hunternif.mc.dota2items.client.gui.IconInText;
import hunternif.mc.dota2items.client.render.CooldownItemRenderer;
import hunternif.mc.dota2items.client.render.DummyRenderer;
import hunternif.mc.dota2items.client.render.RenderClarityEffect;
import hunternif.mc.dota2items.client.render.RenderDagonBolt;
import hunternif.mc.dota2items.client.render.RenderMidasEffect;
import hunternif.mc.dota2items.client.render.RenderShopkeeper;
import hunternif.mc.dota2items.config.CfgInfo;
import hunternif.mc.dota2items.config.Config;
import hunternif.mc.dota2items.config.DescriptionBuilder;
import hunternif.mc.dota2items.effect.EffectClarity;
import hunternif.mc.dota2items.effect.EntityDagonBolt;
import hunternif.mc.dota2items.effect.EntityMidasEffect;
import hunternif.mc.dota2items.entity.EntityShopkeeper;
import hunternif.mc.dota2items.entity.EntityWrapper;
import hunternif.mc.dota2items.item.ActiveItem;
import hunternif.mc.dota2items.item.Dota2Item;
import java.lang.reflect.Field;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.ReloadableResourceManager;
import net.minecraft.client.resources.SimpleReloadableResourceManager;
import net.minecraft.client.resources.data.MetadataSerializer;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.client.event.sound.SoundLoadEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.ForgeSubscribe;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
public class ClientProxy extends CommonProxy {
public static final CooldownItemRenderer cooldownItemRenderer = new CooldownItemRenderer();
public static final ReloadableResourceManager resourceManager = new SimpleReloadableResourceManager(new MetadataSerializer());
public static final FontRendererWithIcons fontRWithIcons = new FontRendererWithIcons(
Minecraft.getMinecraft().gameSettings, new ResourceLocation("textures/font/ascii.png"), Minecraft.getMinecraft().renderEngine, false);
public static final FontRendererContourShadow fontRContourShadow = new FontRendererContourShadow(
Minecraft.getMinecraft().gameSettings, new ResourceLocation("textures/font/ascii.png"), Minecraft.getMinecraft().renderEngine, false);
public static final IconInText ICON_GOLD = new IconInText("$gold$", 12, 12, Dota2Items.ID+":textures/gui/gold_coins.png", -1, -3, 2);
public static final IconInText ICON_COOLDOWN = new IconInText("$cd$", 7, 7, Dota2Items.ID+":textures/gui/cooldown.png", 0, 0, 3);
public static final IconInText ICON_MANACOST = new IconInText("$manacost$", 7, 7, Dota2Items.ID+":textures/gui/manacost.png", 0, 0, 3);
private final RenderTickHandler hudTickHandler = new RenderTickHandler();
private final SwingTickHandler swingTickHandler = new SwingTickHandler();
@Override
public void registerRenderers() {
// Build item description
try {
Field[] fields = Config.class.getFields();
for (Field field : fields) {
if (field.getType().equals(CfgInfo.class)) {
CfgInfo<?> info = (CfgInfo)field.get(null);
if (info.instance instanceof Dota2Item) {
DescriptionBuilder.build((CfgInfo<? extends Dota2Item>)info);
}
}
}
} catch (Exception e) {
Dota2Items.logger.warning("Failed to build item description: " + e.toString());
}
resourceManager.registerReloadListener(fontRWithIcons);
resourceManager.registerReloadListener(fontRContourShadow);
fontRWithIcons.registerIcon(ICON_GOLD);
fontRWithIcons.registerIcon(ICON_COOLDOWN);
fontRWithIcons.registerIcon(ICON_MANACOST);
Minecraft mc = Minecraft.getMinecraft();
MinecraftForge.EVENT_BUS.register(cooldownItemRenderer);
MinecraftForge.EVENT_BUS.register(new GuiManaBar(mc));
MinecraftForge.EVENT_BUS.register(new GuiHealthAndMana(mc));
hudTickHandler.registerHUD(new GuiGold(mc));
hudTickHandler.registerHUD(new GuiDotaStats(mc));
for (Item item : Dota2Items.itemList) {
if (item instanceof ActiveItem) {
MinecraftForgeClient.registerItemRenderer(item.itemID, cooldownItemRenderer);
}
}
RenderingRegistry.registerEntityRenderingHandler(EntityShopkeeper.class, new RenderShopkeeper());
RenderingRegistry.registerEntityRenderingHandler(EntityDagonBolt.class, new RenderDagonBolt());
RenderingRegistry.registerEntityRenderingHandler(EntityWrapper.class, new DummyRenderer());
RenderingRegistry.registerEntityRenderingHandler(EffectClarity.class, new RenderClarityEffect());
RenderingRegistry.registerEntityRenderingHandler(EntityMidasEffect.class, new RenderMidasEffect());
}
@Override
public void registerSounds() {
MinecraftForge.EVENT_BUS.register(this);
}
@Override
public void registerTickHandlers() {
super.registerTickHandlers();
TickRegistry.registerTickHandler(hudTickHandler, Side.CLIENT);
TickRegistry.registerTickHandler(swingTickHandler, Side.CLIENT);
}
@ForgeSubscribe
public void onSound(SoundLoadEvent event) {
try {
for (Sound sound : Sound.values()) {
if (!sound.isRandom()) {
event.manager.soundPoolSounds.addSound(sound.getName()+".ogg");
} else {
for (int i = 1; i <= sound.randomVariants; i++) {
event.manager.soundPoolSounds.addSound(sound.getName()+i+".ogg");
}
}
}
}
catch (Exception e) {
Dota2Items.logger.warning("Failed to register one or more sounds.");
}
}
} | Hunternif/Dota2Items | src/hunternif/mc/dota2items/ClientProxy.java | Java | gpl-3.0 | 6,221 |
#include <iostream>
#include "plugins-base/mapping/slide.h"
static const bool VERBOSE = false;
using namespace tempi;
bool check_slide()
{
plugins_base::Slide slide = plugins_base::Slide();
slide.setSlide(1.0);
if (VERBOSE)
std::cout << "slide = " << slide.getSlide() << std::endl;
double factor = 1.0;
for (int i = 0; i < 100; ++i)
{
double result = slide.slide(i * factor);
if (VERBOSE)
std::cout << "" << i << " = " << result << std::endl;
}
return true;
}
int main(int argc, char *argv[])
{
if (! check_slide())
return 1;
return 0;
}
| aalex/tempi | plugins-base/tests/check_slide.cpp | C++ | gpl-3.0 | 627 |
<?php
/*
* AlcedisMED
* Copyright (C) 2010-2016 Alcedis GmbH
*
* 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/>.
*/
if (isset($_REQUEST['convertdoc']) == true) {
$smarty->assign('convertdoc', $_REQUEST['convertdoc']);
}
switch ($pageName) {
case 'convert':
case 'convert_exec':
case 'customcss':
//Zugriff auf Cache immer gestatten
$verified = true;
$permissionGranted = true;
$featureRequest = true;
break;
}
?> | Alcedis/AlcedisMED | application/med4/feature/convert/loader.php | PHP | gpl-3.0 | 1,120 |
/*====================================================================*\
GridDialog.java
Grid dialog box class.
\*====================================================================*/
// PACKAGE
package uk.blankaspect.crosswordeditor;
//----------------------------------------------------------------------
// IMPORTS
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import uk.blankaspect.common.swing.action.KeyAction;
import uk.blankaspect.common.swing.button.FButton;
import uk.blankaspect.common.swing.checkbox.FCheckBox;
import uk.blankaspect.common.swing.combobox.FComboBox;
import uk.blankaspect.common.swing.label.FLabel;
import uk.blankaspect.common.swing.menu.FMenuItem;
import uk.blankaspect.common.swing.misc.GuiUtils;
import uk.blankaspect.common.swing.text.TextRendering;
//----------------------------------------------------------------------
// GRID DIALOG BOX CLASS
class GridDialog
extends JDialog
implements ActionListener, ChangeListener, MouseListener
{
////////////////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////////////////
private static final String TITLE_STR = "Grid";
private static final String SYMMETRY_STR = "Symmetry";
private static final String FULLY_INTERSECTING_STR = "Highlight fully intersecting fields";
private static final String UNDO_STR = "Undo";
private static final String REDO_STR = "Redo";
// Commands
private interface Command
{
String SELECT_SYMMETRY = "selectSymmetry";
String TOGGLE_HIGHLIGHT_FULLY_INTERSECTING = "toggleHighlightFullyIntersecting";
String UNDO = "undo";
String REDO = "redo";
String SHOW_CONTEXT_MENU = "showContextMenu";
String ACCEPT = "accept";
String CLOSE = "close";
}
private static final Map<String, CommandAction> COMMANDS;
private static final KeyAction.KeyCommandPair[] KEY_COMMANDS =
{
new KeyAction.KeyCommandPair
(
KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_DOWN_MASK),
Command.UNDO
),
new KeyAction.KeyCommandPair
(
KeyStroke.getKeyStroke(KeyEvent.VK_Y, KeyEvent.CTRL_DOWN_MASK),
Command.REDO
),
new KeyAction.KeyCommandPair
(
KeyStroke.getKeyStroke(KeyEvent.VK_CONTEXT_MENU, 0),
Command.SHOW_CONTEXT_MENU
),
new KeyAction.KeyCommandPair
(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
Command.CLOSE
)
};
////////////////////////////////////////////////////////////////////////
// Member classes : non-inner classes
////////////////////////////////////////////////////////////////////////
// NUMBER FIELD CLASS
private static class NumberField
extends JComponent
{
////////////////////////////////////////////////////////////////////
// Constants
////////////////////////////////////////////////////////////////////
private static final int VERTICAL_MARGIN = 2;
private static final int HORIZONTAL_MARGIN = 6;
private static final Color TEXT_COLOUR = Color.BLACK;
private static final Color BACKGROUND_COLOUR = new Color(236, 244, 236);
private static final Color BORDER_COLOUR = new Color(192, 196, 192);
private static final String PROTOTYPE_STR = "000";
////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////
private NumberField()
{
// Set font
AppFont.TEXT_FIELD.apply(this);
// Initialise instance variables
numFields = -1;
// Set preferred size
FontMetrics fontMetrics = getFontMetrics(getFont());
int width = 2 * HORIZONTAL_MARGIN + fontMetrics.stringWidth(PROTOTYPE_STR);
int height = 2 * VERTICAL_MARGIN + fontMetrics.getAscent() + fontMetrics.getDescent();
setPreferredSize(new Dimension(width, height));
// Set attributes
setEnabled(false);
setOpaque(true);
setFocusable(false);
}
//--------------------------------------------------------------
////////////////////////////////////////////////////////////////////
// Instance methods : overriding methods
////////////////////////////////////////////////////////////////////
@Override
protected void paintComponent(Graphics gr)
{
// Create copy of graphics context
gr = gr.create();
// Get dimensions
int width = getWidth();
int height = getHeight();
// Draw background
gr.setColor(BACKGROUND_COLOUR);
gr.fillRect(0, 0, width, height);
// Draw text
if (numFields >= 0)
{
// Set rendering hints for text antialiasing and fractional metrics
TextRendering.setHints((Graphics2D)gr);
// Draw text
String text = Integer.toString(numFields);
FontMetrics fontMetrics = gr.getFontMetrics();
int x = width - HORIZONTAL_MARGIN - fontMetrics.stringWidth(text);
gr.setColor(TEXT_COLOUR);
gr.drawString(text, x, VERTICAL_MARGIN + fontMetrics.getAscent());
}
// Draw border
gr.setColor(BORDER_COLOUR);
gr.drawRect(0, 0, width - 1, height - 1);
}
//--------------------------------------------------------------
////////////////////////////////////////////////////////////////////
// Instance methods
////////////////////////////////////////////////////////////////////
private void setNumFields(int numFields)
{
if (this.numFields != numFields)
{
this.numFields = numFields;
repaint();
}
}
//--------------------------------------------------------------
////////////////////////////////////////////////////////////////////
// Instance variables
////////////////////////////////////////////////////////////////////
private int numFields;
}
//==================================================================
////////////////////////////////////////////////////////////////////////
// Member classes : inner classes
////////////////////////////////////////////////////////////////////////
// COMMAND ACTION CLASS
private static class CommandAction
extends AbstractAction
{
////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////
private CommandAction(String command,
String text)
{
// Call superclass constructor
super(text);
// Set action properties
putValue(Action.ACTION_COMMAND_KEY, command);
}
//--------------------------------------------------------------
////////////////////////////////////////////////////////////////////
// Instance methods : ActionListener interface
////////////////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent event)
{
listener.actionPerformed(event);
}
//--------------------------------------------------------------
////////////////////////////////////////////////////////////////////
// Instance variables
////////////////////////////////////////////////////////////////////
private ActionListener listener;
}
//==================================================================
////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////
private GridDialog(Window owner,
Grid grid)
{
// Call superclass constructor
super(owner, TITLE_STR, Dialog.ModalityType.APPLICATION_MODAL);
// Set icons
setIconImages(owner.getIconImages());
// Set action listener in commands
for (String commandKey : COMMANDS.keySet())
COMMANDS.get(commandKey).listener = this;
//---- Control panel
GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
JPanel controlPanel = new JPanel(gridBag);
GuiUtils.setPaddedLineBorder(controlPanel);
int gridY = 0;
// Label: symmetry
JLabel symmetryLabel = new FLabel(SYMMETRY_STR);
gbc.gridx = 0;
gbc.gridy = gridY;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = AppConstants.COMPONENT_INSETS;
gridBag.setConstraints(symmetryLabel, gbc);
controlPanel.add(symmetryLabel);
// Combo box: symmetry
symmetryComboBox = new FComboBox<>();
for (Grid.Symmetry symmetry : Grid.Symmetry.values())
{
if (symmetry.supportsDimensions(grid.getNumColumns(), grid.getNumRows()))
symmetryComboBox.addItem(symmetry);
}
symmetryComboBox.setSelectedValue(grid.getSymmetry());
symmetryComboBox.setActionCommand(Command.SELECT_SYMMETRY);
symmetryComboBox.addActionListener(this);
gbc.gridx = 1;
gbc.gridy = gridY++;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = AppConstants.COMPONENT_INSETS;
gridBag.setConstraints(symmetryComboBox, gbc);
controlPanel.add(symmetryComboBox);
// Check box: highlight fully intersecting fields
highlightFullyIntersectingCheckBox = new FCheckBox(FULLY_INTERSECTING_STR);
highlightFullyIntersectingCheckBox.setSelected(highlightFullyIntersecting);
highlightFullyIntersectingCheckBox.setActionCommand(Command.TOGGLE_HIGHLIGHT_FULLY_INTERSECTING);
highlightFullyIntersectingCheckBox.addActionListener(this);
gbc.gridx = 1;
gbc.gridy = gridY++;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = AppConstants.COMPONENT_INSETS;
gridBag.setConstraints(highlightFullyIntersectingCheckBox, gbc);
controlPanel.add(highlightFullyIntersectingCheckBox);
//---- Grid panel
JPanel gridOuterPanel = new JPanel(gridBag);
GuiUtils.setPaddedLineBorder(gridOuterPanel);
gridPanel = grid.getSeparator().createGridPanel(grid);
gridPanel.addChangeListener(this);
gridPanel.addMouseListener(this);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 0, 0, 0);
gridBag.setConstraints(gridPanel, gbc);
gridOuterPanel.add(gridPanel);
//---- Number of fields panel
JPanel numFieldsPanel = new JPanel(gridBag);
GuiUtils.setPaddedLineBorder(numFieldsPanel);
numFieldsFields = new EnumMap<>(Direction.class);
int gridX = 0;
for (Direction direction : Direction.DEFINED_DIRECTIONS)
{
// Label: direction
JLabel directionLabel = new FLabel(direction.toString());
gbc.gridx = gridX++;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(0, (gridX == 0) ? 0 : 16, 0, 0);
gridBag.setConstraints(directionLabel, gbc);
numFieldsPanel.add(directionLabel);
// Field: number of fields
NumberField field = new NumberField();
numFieldsFields.put(direction, field);
gbc.gridx = gridX++;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(0, 6, 0, 0);
gridBag.setConstraints(field, gbc);
numFieldsPanel.add(field);
}
updateHighlighting();
updateNumFields();
//---- Button panel
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 8, 0));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(3, 12, 3, 12));
// Button: OK
JButton okButton = new FButton(AppConstants.OK_STR);
okButton.setActionCommand(Command.ACCEPT);
okButton.addActionListener(this);
buttonPanel.add(okButton);
// Button: cancel
JButton cancelButton = new FButton(AppConstants.CANCEL_STR);
cancelButton.setActionCommand(Command.CLOSE);
cancelButton.addActionListener(this);
buttonPanel.add(cancelButton);
//---- Main panel
JPanel mainPanel = new JPanel(gridBag);
mainPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
mainPanel.addMouseListener(this);
gridY = 0;
gbc.gridx = 0;
gbc.gridy = gridY++;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 0, 0, 0);
gridBag.setConstraints(controlPanel, gbc);
mainPanel.add(controlPanel);
gbc.gridx = 0;
gbc.gridy = gridY++;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(3, 0, 0, 0);
gridBag.setConstraints(gridOuterPanel, gbc);
mainPanel.add(gridOuterPanel);
gbc.gridx = 0;
gbc.gridy = gridY++;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(3, 0, 0, 0);
gridBag.setConstraints(numFieldsPanel, gbc);
mainPanel.add(numFieldsPanel);
gbc.gridx = 0;
gbc.gridy = gridY++;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(3, 0, 0, 0);
gridBag.setConstraints(buttonPanel, gbc);
mainPanel.add(buttonPanel);
// Add commands to action map
KeyAction.create(mainPanel, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, this, KEY_COMMANDS);
//---- Window
// Set content pane
setContentPane(mainPanel);
// Dispose of window explicitly
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
// Handle window closing
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent event)
{
onClose();
}
});
// Prevent dialog from being resized
setResizable(false);
// Resize dialog to its preferred size
pack();
// Set location of dialog box
if (location == null)
location = GuiUtils.getComponentLocation(this, owner);
setLocation(location);
// Set default button
getRootPane().setDefaultButton(okButton);
// Show dialog
setVisible(true);
}
//------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////
// Class methods
////////////////////////////////////////////////////////////////////////
public static Grid showDialog(Component parent,
CrosswordDocument document)
{
return new GridDialog(GuiUtils.getWindow(parent), document.getGrid()).getGrid();
}
//------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////
// Instance methods : ActionListener interface
////////////////////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (command.equals(Command.SELECT_SYMMETRY))
onSelectSymmetry();
else if (command.equals(Command.TOGGLE_HIGHLIGHT_FULLY_INTERSECTING))
onToggleHighlightFullyIntersecting();
else if (command.equals(Command.UNDO))
onUndo();
else if (command.equals(Command.REDO))
onRedo();
else if (command.equals(Command.SHOW_CONTEXT_MENU))
onShowContextMenu();
else if (command.equals(Command.ACCEPT))
onAccept();
else if (command.equals(Command.CLOSE))
onClose();
}
//------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////
// Instance methods : ChangeListener interface
////////////////////////////////////////////////////////////////////////
public void stateChanged(ChangeEvent event)
{
symmetryComboBox.setSelectedValue(gridPanel.getGrid().getSymmetry());
}
//------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////
// Instance methods : MouseListener interface
////////////////////////////////////////////////////////////////////////
public void mouseClicked(MouseEvent event)
{
// do nothing
}
//------------------------------------------------------------------
public void mouseEntered(MouseEvent event)
{
// do nothing
}
//------------------------------------------------------------------
public void mouseExited(MouseEvent event)
{
// do nothing
}
//------------------------------------------------------------------
public void mousePressed(MouseEvent event)
{
showContextMenu(event);
}
//------------------------------------------------------------------
public void mouseReleased(MouseEvent event)
{
showContextMenu(event);
}
//------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////
// Instance methods
////////////////////////////////////////////////////////////////////////
private Grid getGrid()
{
return (accepted ? gridPanel.getGrid() : null);
}
//------------------------------------------------------------------
private void updateNumFields()
{
for (Direction direction : numFieldsFields.keySet())
numFieldsFields.get(direction).setNumFields(gridPanel.getNumFields(direction));
}
//------------------------------------------------------------------
private void updateHighlighting()
{
gridPanel.setHighlightFullyIntersecting(highlightFullyIntersectingCheckBox.isSelected());
}
//------------------------------------------------------------------
private void showContextMenu(MouseEvent event)
{
if ((event == null) || event.isPopupTrigger())
{
// Create context menu
if (contextMenu == null)
{
contextMenu = new JPopupMenu();
contextMenu.add(new FMenuItem(COMMANDS.get(Command.UNDO)));
contextMenu.add(new FMenuItem(COMMANDS.get(Command.REDO)));
}
// Update commands
Grid grid = gridPanel.getGrid();
COMMANDS.get(Command.UNDO).setEnabled(grid.canUndoEdit());
COMMANDS.get(Command.REDO).setEnabled(grid.canRedoEdit());
// Display menu
if (event == null)
contextMenu.show(getContentPane(), 0, 0);
else
contextMenu.show(event.getComponent(), event.getX(), event.getY());
}
}
//------------------------------------------------------------------
private void onSelectSymmetry()
{
gridPanel.setSymmetry(symmetryComboBox.getSelectedValue());
updateNumFields();
}
//------------------------------------------------------------------
private void onToggleHighlightFullyIntersecting()
{
updateHighlighting();
}
//------------------------------------------------------------------
private void onUndo()
{
gridPanel.undoEdit();
}
//------------------------------------------------------------------
private void onRedo()
{
gridPanel.redoEdit();
}
//------------------------------------------------------------------
private void onShowContextMenu()
{
showContextMenu(null);
}
//------------------------------------------------------------------
private void onAccept()
{
accepted = true;
onClose();
}
//------------------------------------------------------------------
private void onClose()
{
highlightFullyIntersecting = highlightFullyIntersectingCheckBox.isSelected();
location = getLocation();
setVisible(false);
dispose();
}
//------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////
// Class variables
////////////////////////////////////////////////////////////////////////
private static boolean highlightFullyIntersecting;
private static Point location;
////////////////////////////////////////////////////////////////////////
// Static initialiser
////////////////////////////////////////////////////////////////////////
static
{
COMMANDS = new HashMap<>();
COMMANDS.put(Command.UNDO, new CommandAction(Command.UNDO, UNDO_STR));
COMMANDS.put(Command.REDO, new CommandAction(Command.REDO, REDO_STR));
}
////////////////////////////////////////////////////////////////////////
// Instance variables
////////////////////////////////////////////////////////////////////////
private boolean accepted;
private FComboBox<Grid.Symmetry> symmetryComboBox;
private JCheckBox highlightFullyIntersectingCheckBox;
private GridPanel gridPanel;
private Map<Direction, NumberField> numFieldsFields;
private JPopupMenu contextMenu;
}
//----------------------------------------------------------------------
| blankaspect/crosswordEditor | src/main/java/uk/blankaspect/crosswordeditor/GridDialog.java | Java | gpl-3.0 | 21,789 |