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
/* * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com) * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "platform/graphics/BitmapImage.h" #include "platform/PlatformInstrumentation.h" #include "platform/Timer.h" #include "platform/geometry/FloatRect.h" #include "platform/graphics/BitmapImageMetrics.h" #include "platform/graphics/DeferredImageDecoder.h" #include "platform/graphics/ImageObserver.h" #include "platform/graphics/StaticBitmapImage.h" #include "platform/graphics/skia/SkiaUtils.h" #include "platform/tracing/TraceEvent.h" #include "third_party/skia/include/core/SkCanvas.h" #include "wtf/PassRefPtr.h" #include "wtf/PtrUtil.h" #include "wtf/text/WTFString.h" namespace blink { PassRefPtr<BitmapImage> BitmapImage::createWithOrientationForTesting( const SkBitmap& bitmap, ImageOrientation orientation) { if (bitmap.isNull()) { return BitmapImage::create(); } RefPtr<BitmapImage> result = adoptRef(new BitmapImage(bitmap)); result->m_frames[0].m_orientation = orientation; if (orientation.usesWidthAsHeight()) result->m_sizeRespectingOrientation = result->m_size.transposedSize(); return result.release(); } BitmapImage::BitmapImage(ImageObserver* observer) : Image(observer), m_currentFrame(0), m_cachedFrameIndex(0), m_repetitionCount(cAnimationNone), m_repetitionCountStatus(Unknown), m_repetitionsComplete(0), m_desiredFrameStartTime(0), m_frameCount(0), m_animationPolicy(ImageAnimationPolicyAllowed), m_animationFinished(false), m_allDataReceived(false), m_haveSize(false), m_sizeAvailable(false), m_haveFrameCount(false) {} BitmapImage::BitmapImage(const SkBitmap& bitmap, ImageObserver* observer) : Image(observer), m_size(bitmap.width(), bitmap.height()), m_currentFrame(0), m_cachedFrame(SkImage::MakeFromBitmap(bitmap)), m_cachedFrameIndex(0), m_repetitionCount(cAnimationNone), m_repetitionCountStatus(Unknown), m_repetitionsComplete(0), m_frameCount(1), m_animationPolicy(ImageAnimationPolicyAllowed), m_animationFinished(true), m_allDataReceived(true), m_haveSize(true), m_sizeAvailable(true), m_haveFrameCount(true) { // Since we don't have a decoder, we can't figure out the image orientation. // Set m_sizeRespectingOrientation to be the same as m_size so it's not 0x0. m_sizeRespectingOrientation = m_size; m_frames.grow(1); m_frames[0].m_hasAlpha = !bitmap.isOpaque(); m_frames[0].m_haveMetadata = true; } BitmapImage::~BitmapImage() { stopAnimation(); } bool BitmapImage::currentFrameHasSingleSecurityOrigin() const { return true; } void BitmapImage::destroyDecodedData() { m_cachedFrame.reset(); for (size_t i = 0; i < m_frames.size(); ++i) m_frames[i].clear(true); m_source.clearCacheExceptFrame(kNotFound); notifyMemoryChanged(); } PassRefPtr<SharedBuffer> BitmapImage::data() { return m_source.data(); } void BitmapImage::notifyMemoryChanged() { if (getImageObserver()) getImageObserver()->decodedSizeChangedTo(this, totalFrameBytes()); } size_t BitmapImage::totalFrameBytes() { const size_t numFrames = frameCount(); size_t totalBytes = 0; for (size_t i = 0; i < numFrames; ++i) totalBytes += m_source.frameBytesAtIndex(i); return totalBytes; } sk_sp<SkImage> BitmapImage::decodeAndCacheFrame(size_t index) { size_t numFrames = frameCount(); if (m_frames.size() < numFrames) m_frames.grow(numFrames); // We are caching frame snapshots. This is OK even for partially decoded // frames, as they are cleared by dataChanged() when new data arrives. sk_sp<SkImage> image = m_source.createFrameAtIndex(index); m_cachedFrame = image; m_cachedFrameIndex = index; m_frames[index].m_orientation = m_source.orientationAtIndex(index); m_frames[index].m_haveMetadata = true; m_frames[index].m_isComplete = m_source.frameIsCompleteAtIndex(index); if (repetitionCount(false) != cAnimationNone) m_frames[index].m_duration = m_source.frameDurationAtIndex(index); m_frames[index].m_hasAlpha = m_source.frameHasAlphaAtIndex(index); m_frames[index].m_frameBytes = m_source.frameBytesAtIndex(index); notifyMemoryChanged(); return image; } void BitmapImage::updateSize() const { if (!m_sizeAvailable || m_haveSize) return; m_size = m_source.size(); m_sizeRespectingOrientation = m_source.size(RespectImageOrientation); m_haveSize = true; } IntSize BitmapImage::size() const { updateSize(); return m_size; } IntSize BitmapImage::sizeRespectingOrientation() const { updateSize(); return m_sizeRespectingOrientation; } bool BitmapImage::getHotSpot(IntPoint& hotSpot) const { return m_source.getHotSpot(hotSpot); } Image::SizeAvailability BitmapImage::setData(PassRefPtr<SharedBuffer> data, bool allDataReceived) { if (!data.get()) return SizeAvailable; int length = data->size(); if (!length) return SizeAvailable; // If ImageSource::setData() fails, we know that this is a decode error. // Report size available so that it gets registered as such in ImageResource. if (!m_source.setData(std::move(data), allDataReceived)) return SizeAvailable; return dataChanged(allDataReceived); } Image::SizeAvailability BitmapImage::dataChanged(bool allDataReceived) { TRACE_EVENT0("blink", "BitmapImage::dataChanged"); // Clear all partially-decoded frames. For most image formats, there is only // one frame, but at least GIF and ICO can have more. With GIFs, the frames // come in order and we ask to decode them in order, waiting to request a // subsequent frame until the prior one is complete. Given that we clear // incomplete frames here, this means there is at most one incomplete frame // (even if we use destroyDecodedData() -- since it doesn't reset the // metadata), and it is after all the complete frames. // // With ICOs, on the other hand, we may ask for arbitrary frames at // different times (e.g. because we're displaying a higher-resolution image // in the content area and using a lower-resolution one for the favicon), // and the frames aren't even guaranteed to appear in the file in the same // order as in the directory, so an arbitrary number of the frames might be // incomplete (if we ask for frames for which we've not yet reached the // start of the frame data), and any or none of them might be the particular // frame affected by appending new data here. Thus we have to clear all the // incomplete frames to be safe. for (size_t i = 0; i < m_frames.size(); ++i) { // NOTE: Don't call frameIsCompleteAtIndex() here, that will try to // decode any uncached (i.e. never-decoded or // cleared-on-a-previous-pass) frames! if (m_frames[i].m_haveMetadata && !m_frames[i].m_isComplete) { m_frames[i].clear(true); if (i == m_cachedFrameIndex) m_cachedFrame.reset(); } } // Feed all the data we've seen so far to the image decoder. m_allDataReceived = allDataReceived; m_haveFrameCount = false; return isSizeAvailable() ? SizeAvailable : SizeUnavailable; } bool BitmapImage::hasColorProfile() const { return m_source.hasColorProfile(); } String BitmapImage::filenameExtension() const { return m_source.filenameExtension(); } void BitmapImage::draw( SkCanvas* canvas, const SkPaint& paint, const FloatRect& dstRect, const FloatRect& srcRect, RespectImageOrientationEnum shouldRespectImageOrientation, ImageClampingMode clampMode) { TRACE_EVENT0("skia", "BitmapImage::draw"); sk_sp<SkImage> image = imageForCurrentFrame(); if (!image) return; // It's too early and we don't have an image yet. FloatRect adjustedSrcRect = srcRect; adjustedSrcRect.intersect(SkRect::Make(image->bounds())); if (adjustedSrcRect.isEmpty() || dstRect.isEmpty()) return; // Nothing to draw. ImageOrientation orientation = DefaultImageOrientation; if (shouldRespectImageOrientation == RespectImageOrientation) orientation = frameOrientationAtIndex(m_currentFrame); SkAutoCanvasRestore autoRestore(canvas, false); FloatRect adjustedDstRect = dstRect; if (orientation != DefaultImageOrientation) { canvas->save(); // ImageOrientation expects the origin to be at (0, 0) canvas->translate(adjustedDstRect.x(), adjustedDstRect.y()); adjustedDstRect.setLocation(FloatPoint()); canvas->concat(affineTransformToSkMatrix( orientation.transformFromDefault(adjustedDstRect.size()))); if (orientation.usesWidthAsHeight()) { // The destination rect will have its width and height already reversed // for the orientation of the image, as it was needed for page layout, so // we need to reverse it back here. adjustedDstRect = FloatRect(adjustedDstRect.x(), adjustedDstRect.y(), adjustedDstRect.height(), adjustedDstRect.width()); } } canvas->drawImageRect(image.get(), adjustedSrcRect, adjustedDstRect, &paint, WebCoreClampingModeToSkiaRectConstraint(clampMode)); if (image->isLazyGenerated()) PlatformInstrumentation::didDrawLazyPixelRef(image->uniqueID()); if (ImageObserver* observer = getImageObserver()) observer->didDraw(this); startAnimation(); } size_t BitmapImage::frameCount() { if (!m_haveFrameCount) { m_frameCount = m_source.frameCount(); // If decoder is not initialized yet, m_source.frameCount() returns 0. if (m_frameCount) m_haveFrameCount = true; } return m_frameCount; } static inline bool hasVisibleImageSize(IntSize size) { return (size.width() > 1 || size.height() > 1); } bool BitmapImage::isSizeAvailable() { if (m_sizeAvailable) return true; m_sizeAvailable = m_source.isSizeAvailable(); if (m_sizeAvailable && hasVisibleImageSize(size())) { BitmapImageMetrics::countDecodedImageType(m_source.filenameExtension()); if (m_source.filenameExtension() == "jpg") BitmapImageMetrics::countImageOrientation( m_source.orientationAtIndex(0).orientation()); } return m_sizeAvailable; } sk_sp<SkImage> BitmapImage::frameAtIndex(size_t index) { if (index >= frameCount()) return nullptr; if (index == m_cachedFrameIndex && m_cachedFrame) return m_cachedFrame; return decodeAndCacheFrame(index); } bool BitmapImage::frameIsCompleteAtIndex(size_t index) const { if (index < m_frames.size() && m_frames[index].m_haveMetadata && m_frames[index].m_isComplete) return true; return m_source.frameIsCompleteAtIndex(index); } float BitmapImage::frameDurationAtIndex(size_t index) const { if (index < m_frames.size() && m_frames[index].m_haveMetadata) return m_frames[index].m_duration; return m_source.frameDurationAtIndex(index); } sk_sp<SkImage> BitmapImage::imageForCurrentFrame() { return frameAtIndex(currentFrame()); } PassRefPtr<Image> BitmapImage::imageForDefaultFrame() { if (frameCount() > 1) { sk_sp<SkImage> firstFrame = frameAtIndex(0); if (firstFrame) return StaticBitmapImage::create(std::move(firstFrame)); } return Image::imageForDefaultFrame(); } bool BitmapImage::frameHasAlphaAtIndex(size_t index) { if (m_frames.size() <= index) return true; if (m_frames[index].m_haveMetadata && !m_frames[index].m_hasAlpha) return false; // m_hasAlpha may change after m_haveMetadata is set to true, so always ask // ImageSource for the value if the cached value is the default value. bool hasAlpha = m_source.frameHasAlphaAtIndex(index); if (m_frames[index].m_haveMetadata) m_frames[index].m_hasAlpha = hasAlpha; return hasAlpha; } bool BitmapImage::currentFrameKnownToBeOpaque(MetadataMode metadataMode) { if (metadataMode == PreCacheMetadata) { // frameHasAlphaAtIndex() conservatively returns false for uncached frames. // To increase the chance of an accurate answer, pre-cache the current frame // metadata. frameAtIndex(currentFrame()); } return !frameHasAlphaAtIndex(currentFrame()); } bool BitmapImage::currentFrameIsComplete() { return frameIsCompleteAtIndex(currentFrame()); } bool BitmapImage::currentFrameIsLazyDecoded() { sk_sp<SkImage> image = frameAtIndex(currentFrame()); return image && image->isLazyGenerated(); } ImageOrientation BitmapImage::currentFrameOrientation() { return frameOrientationAtIndex(currentFrame()); } ImageOrientation BitmapImage::frameOrientationAtIndex(size_t index) { if (m_frames.size() <= index) return DefaultImageOrientation; if (m_frames[index].m_haveMetadata) return m_frames[index].m_orientation; return m_source.orientationAtIndex(index); } int BitmapImage::repetitionCount(bool imageKnownToBeComplete) { if ((m_repetitionCountStatus == Unknown) || ((m_repetitionCountStatus == Uncertain) && imageKnownToBeComplete)) { // Snag the repetition count. If |imageKnownToBeComplete| is false, the // repetition count may not be accurate yet for GIFs; in this case the // decoder will default to cAnimationLoopOnce, and we'll try and read // the count again once the whole image is decoded. m_repetitionCount = m_source.repetitionCount(); m_repetitionCountStatus = (imageKnownToBeComplete || m_repetitionCount == cAnimationNone) ? Certain : Uncertain; } return m_repetitionCount; } bool BitmapImage::shouldAnimate() { bool animated = repetitionCount(false) != cAnimationNone && !m_animationFinished && getImageObserver(); if (animated && m_animationPolicy == ImageAnimationPolicyNoAnimation) animated = false; return animated; } void BitmapImage::startAnimation(CatchUpAnimation catchUpIfNecessary) { if (m_frameTimer || !shouldAnimate() || frameCount() <= 1) return; // If we aren't already animating, set now as the animation start time. const double time = monotonicallyIncreasingTime(); if (!m_desiredFrameStartTime) m_desiredFrameStartTime = time; // Don't advance the animation to an incomplete frame. size_t nextFrame = (m_currentFrame + 1) % frameCount(); if (!m_allDataReceived && !frameIsCompleteAtIndex(nextFrame)) return; // Don't advance past the last frame if we haven't decoded the whole image // yet and our repetition count is potentially unset. The repetition count // in a GIF can potentially come after all the rest of the image data, so // wait on it. if (!m_allDataReceived && (repetitionCount(false) == cAnimationLoopOnce || m_animationPolicy == ImageAnimationPolicyAnimateOnce) && m_currentFrame >= (frameCount() - 1)) return; // Determine time for next frame to start. By ignoring paint and timer lag // in this calculation, we make the animation appear to run at its desired // rate regardless of how fast it's being repainted. const double currentDuration = frameDurationAtIndex(m_currentFrame); m_desiredFrameStartTime += currentDuration; // When an animated image is more than five minutes out of date, the // user probably doesn't care about resyncing and we could burn a lot of // time looping through frames below. Just reset the timings. const double cAnimationResyncCutoff = 5 * 60; if ((time - m_desiredFrameStartTime) > cAnimationResyncCutoff) m_desiredFrameStartTime = time + currentDuration; // The image may load more slowly than it's supposed to animate, so that by // the time we reach the end of the first repetition, we're well behind. // Clamp the desired frame start time in this case, so that we don't skip // frames (or whole iterations) trying to "catch up". This is a tradeoff: // It guarantees users see the whole animation the second time through and // don't miss any repetitions, and is closer to what other browsers do; on // the other hand, it makes animations "less accurate" for pages that try to // sync an image and some other resource (e.g. audio), especially if users // switch tabs (and thus stop drawing the animation, which will pause it) // during that initial loop, then switch back later. if (nextFrame == 0 && m_repetitionsComplete == 0 && m_desiredFrameStartTime < time) m_desiredFrameStartTime = time; if (catchUpIfNecessary == DoNotCatchUp || time < m_desiredFrameStartTime) { // Haven't yet reached time for next frame to start; delay until then. m_frameTimer = wrapUnique( new Timer<BitmapImage>(this, &BitmapImage::advanceAnimation)); m_frameTimer->startOneShot(std::max(m_desiredFrameStartTime - time, 0.), BLINK_FROM_HERE); } else { // We've already reached or passed the time for the next frame to start. // See if we've also passed the time for frames after that to start, in // case we need to skip some frames entirely. Remember not to advance // to an incomplete frame. for (size_t frameAfterNext = (nextFrame + 1) % frameCount(); frameIsCompleteAtIndex(frameAfterNext); frameAfterNext = (nextFrame + 1) % frameCount()) { // Should we skip the next frame? double frameAfterNextStartTime = m_desiredFrameStartTime + frameDurationAtIndex(nextFrame); if (time < frameAfterNextStartTime) break; // Skip the next frame by advancing the animation forward one frame. if (!internalAdvanceAnimation(SkipFramesToCatchUp)) { DCHECK(m_animationFinished); return; } m_desiredFrameStartTime = frameAfterNextStartTime; nextFrame = frameAfterNext; } // Post a task to advance the frame immediately. m_desiredFrameStartTime // may be in the past, meaning the next time through this function we'll // kick off the next advancement sooner than this frame's duration would // suggest. m_frameTimer = wrapUnique(new Timer<BitmapImage>( this, &BitmapImage::advanceAnimationWithoutCatchUp)); m_frameTimer->startOneShot(0, BLINK_FROM_HERE); } } void BitmapImage::stopAnimation() { // This timer is used to animate all occurrences of this image. Don't // invalidate the timer unless all renderers have stopped drawing. m_frameTimer.reset(); } void BitmapImage::resetAnimation() { stopAnimation(); m_currentFrame = 0; m_repetitionsComplete = 0; m_desiredFrameStartTime = 0; m_animationFinished = false; m_cachedFrame.reset(); } bool BitmapImage::maybeAnimated() { if (m_animationFinished) return false; if (frameCount() > 1) return true; return m_source.repetitionCount() != cAnimationNone; } void BitmapImage::advanceTime(double deltaTimeInSeconds) { if (m_desiredFrameStartTime) m_desiredFrameStartTime -= deltaTimeInSeconds; else m_desiredFrameStartTime = monotonicallyIncreasingTime() - deltaTimeInSeconds; } void BitmapImage::advanceAnimation(TimerBase*) { internalAdvanceAnimation(); // At this point the image region has been marked dirty, and if it's // onscreen, we'll soon make a call to draw(), which will call // startAnimation() again to keep the animation moving. } void BitmapImage::advanceAnimationWithoutCatchUp(TimerBase*) { if (internalAdvanceAnimation()) startAnimation(DoNotCatchUp); } bool BitmapImage::internalAdvanceAnimation(AnimationAdvancement advancement) { // Stop the animation. stopAnimation(); // See if anyone is still paying attention to this animation. If not, we // don't advance, and will remain suspended at the current frame until the // animation is resumed. if (advancement != SkipFramesToCatchUp && getImageObserver()->shouldPauseAnimation(this)) return false; if (m_currentFrame + 1 < frameCount()) { m_currentFrame++; } else { m_repetitionsComplete++; // Get the repetition count again. If we weren't able to get a // repetition count before, we should have decoded the whole image by // now, so it should now be available. // We don't need to special-case cAnimationLoopOnce here because it is // 0 (see comments on its declaration in ImageAnimation.h). if ((repetitionCount(true) != cAnimationLoopInfinite && m_repetitionsComplete > m_repetitionCount) || m_animationPolicy == ImageAnimationPolicyAnimateOnce) { m_animationFinished = true; m_desiredFrameStartTime = 0; // We skipped to the last frame and cannot advance further. The // observer will not receive animationAdvanced notifications while // skipping but we still need to notify the observer to draw the // last frame. Skipping frames occurs while painting so we do not // synchronously notify the observer which could cause a layout. if (advancement == SkipFramesToCatchUp) { m_frameTimer = wrapUnique(new Timer<BitmapImage>( this, &BitmapImage::notifyObserversOfAnimationAdvance)); m_frameTimer->startOneShot(0, BLINK_FROM_HERE); } return false; } // Loop the animation back to the first frame. m_currentFrame = 0; } // We need to draw this frame if we advanced to it while not skipping. if (advancement != SkipFramesToCatchUp) getImageObserver()->animationAdvanced(this); return true; } void BitmapImage::notifyObserversOfAnimationAdvance(TimerBase*) { getImageObserver()->animationAdvanced(this); } } // namespace blink
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Source/platform/graphics/BitmapImage.cpp
C++
gpl-3.0
22,704
<?php function generate_items_from_query() { $items = array(); $content; if (!isset($_GET["eq"])) $content = ";;;;;;;;;;;"; else $content = $_GET["eq"]; try { $values = split(';', $content); for ($i=0; $i < count($values); $i++) { $val = $values[$i]; if ($val == "") { $it = new Item("en_US"); array_push($items, $it); } else { $val = sql_sanitize($val); $req = Item::get_standard_query("en_US") . " AND wow_native_id = $val"; $res = db_ask($req); if (is_array($res) == false || count($res) <= 0) { $it = new Item("en_US"); array_push($items, $it); } else { $it = Item::get_from_array($res[0]); array_push($items, $it); } } } if (count($items) < 11) return generate_default_items(); else return $items; } catch (Exception $e) { return generate_default_items(); } } function generate_default_items() { $items = array(); $i = new Item("en_US"); array_push($items, $i); array_push($items, $i); array_push($items, $i); array_push($items, $i); array_push($items, $i); array_push($items, $i); array_push($items, $i); array_push($items, $i); array_push($items, $i); array_push($items, $i); array_push($items, $i); array_push($items, $i); return $items; } function generate_item_present($item, $slot) { $slotName = slot_name($slot); if ($item->id == -1) { $content = "<img class=\"item-icon\" src=\"images/unknown-item.jpg\"/>"; $content .= "<strong>$slotName</strong><span class=\"item-name item-none\">(Click to equip an item)</span>"; return $content; } else { $content = "<img class=\"item-icon\" src=\"http://media.blizzard.com/wow/icons/56/" . $item->icon . ".jpg\"/>"; $content .= "<strong>$slotName</strong><span class=\"item-name " . $item->generate_color_class_object() . "\">" . $item->name . "</span>"; return $content; } } ?>
doubotis/transmogrify
_code/utils/utils-parser.php
PHP
gpl-3.0
2,382
/* * Copyright (c) 2017, Miguel Gamboa * * 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/>. */ import org.junit.Test; import util.Countify; import util.FileRequest; import util.ICounter; import weather.WeatherService; import weather.data.WeatherWebApi; import weather.model.Location; import weather.model.WeatherInfo; import java.time.LocalDate; import static java.lang.System.out; import static java.time.LocalDate.of; import static org.junit.Assert.assertEquals; import static util.queries.LazyQueries.count; import static util.queries.LazyQueries.distinct; import static util.queries.LazyQueries.filter; import static util.queries.LazyQueries.map; import static util.queries.LazyQueries.skip; /** * @author Miguel Gamboa * created on 29-03-2017 */ public class WeatherDomainTest { @Test public void testWeatherService(){ /** * Arrange WeatherService --> WeatherWebApi --> Countify --> FileRequest */ ICounter<String, Iterable<String>> req = Countify.of(new FileRequest()::getContent); WeatherService api = new WeatherService(new WeatherWebApi(req::apply)); /** * Act and Assert * Counts 0 request while iterator() is not consumed */ Iterable<Location> locals = api.search("Porto"); assertEquals(0, req.getCount()); locals = filter(locals, l -> l.getLatitude() > 0 ); assertEquals(0, req.getCount()); /** * Counts 1 request when iterate to get the first Location */ Location loc = locals.iterator().next(); assertEquals(1, req.getCount()); Iterable<WeatherInfo> infos = api.pastWeather(loc.getLatitude(), loc.getLongitude(), of(2017,02,01), of(2017,02,28)); assertEquals(1, req.getCount()); infos = filter(infos, info -> info.getDescription().toLowerCase().contains("sun")); assertEquals(1, req.getCount()); Iterable<Integer> temps = map(infos, WeatherInfo::getTempC); assertEquals(1, req.getCount()); temps = distinct(temps); assertEquals(1, req.getCount()); /** * When we iterate over the pastWeather then we make one more request */ assertEquals(5, count(temps)); // iterates all items assertEquals(2, req.getCount()); assertEquals((long) 21, (long) skip(temps, 2).iterator().next()); // another iterator assertEquals(3, req.getCount()); temps.forEach(System.out::println); // iterates all items assertEquals(4, req.getCount()); } }
isel-leic-mpd/mpd-2017-i41d
aula13-json/src/test/java/WeatherDomainTest.java
Java
gpl-3.0
3,152
#要注意 javascript 轉 python 語法差異 #document.getElementById -> doc[] #module Math -> math #Math.PI -> math.pi #abs -> fabs #array 可用 list代替 import math import time from browser import doc import browser.timer # 點類別 class Point(object): # 起始方法 def __init__(self, x, y): self.x = x self.y = y # 繪製方法 def drawMe(self, g, r): self.g = g self.r = r self.g.save() self.g.moveTo(self.x,self.y) self.g.beginPath() # 根據 r 半徑繪製一個圓代表點的所在位置 self.g.arc(self.x, self.y, self.r, 0, 2*math.pi, true) self.g.moveTo(self.x,self.y) self.g.lineTo(self.x+self.r, self.y) self.g.moveTo(self.x, self.y) self.g.lineTo(self.x-self.r, self.y) self.g.moveTo(self.x, self.y) self.g.lineTo(self.x, self.y+self.r) self.g.moveTo(self.x, self.y) self.g.lineTo(self.x, self.y-self.r) self.g.restore() self.g.stroke() # 加入 Eq 方法 def Eq(self, pt): self.x = pt.x self.y = pt.y # 加入 setPoint 方法 def setPoint(self, px, py): self.x = px self.y = py # 加上 distance(pt) 方法, 計算點到 pt 的距離 def distance(self, pt): self.pt = pt x = self.x - self.pt.x y = self.y - self.pt.y return math.sqrt(x * x + y * y) # 利用文字標示點的座標位置 def tag(self, g): self.g = g self.g.beginPath() self.g.fillText("%d, %d"%(self.x, self.y),self.x, self.y) self.g.stroke() # Line 類別物件 class Line(object): # 起始方法 def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 # 直線的第一點, 設為線尾 self.Tail = self.p1 # 直線組成的第二點, 設為線頭 self.Head = self.p2 # 直線的長度屬性 self.length = math.sqrt(math.pow(self.p2.x-self.p1.x, 2)+math.pow(self.p2.y-self.p1.y,2)) # setPP 以指定頭尾座標點來定義直線 def setPP(self, p1, p2): self.p1 = p1 self.p2 = p2 self.Tail = self.p1 self.Head = self.p2 self.length = math.sqrt(math.pow(self.p2.x-self.p1.x, 2)+math.pow(self.p2.y-self.p1.y,2)) # setRT 方法 for Line, 應該已經確定 Tail 點, 然後以 r, t 作為設定 Head 的參考 def setRT(self, r, t): self.r = r self.t = t x = self.r * math.cos(self.t) y = self.r * math.sin(self.t) self.Tail.Eq(self.p1) self.Head.setPoint(self.Tail.x + x,self.Tail.y + y) # getR 方法 for Line def getR(self): # x 分量與 y 分量 x = self.p1.x - self.p2.x y = self.p1.y - self.p2.y return math.sqrt(x * x + y * y) # 根據定義 atan2(y,x), 表示 (x,y) 與 正 x 軸之間的夾角, 介於 pi 與 -pi 間 def getT(self): x = self.p2.x - self.p1.x y = self.p2.y - self.p1.y if (math.fabs(x) < math.pow(10,-100)): if(y < 0.0): return (-math.pi/2) else: return (math.pi/2) else: return math.atan2(y, x) # setTail 方法 for Line def setTail(self, pt): self.pt = pt self.Tail.Eq(pt) self.Head.setPoint(self.pt.x + self.x, self.pt.y + self.y) # getHead 方法 for Line def getHead(self): return self.Head def getTail(self): return self.Tail def drawMe(self, g): self.g = g self.g.beginPath() self.g.moveTo(self.p1.x,self.p1.y) self.g.lineTo(self.p2.x,self.p2.y) self.g.stroke() def test(self): return ("this is pure test to Inherit") class Link(Line): def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 self.length = math.sqrt(math.pow((self.p2.x - self.p1.x), 2) + math.pow((self.p2.y - self.p1.y), 2)) #g context def drawMe(self, g): self.g = g hole = 5 radius = 10 length = self.getR() # alert(length) # 儲存先前的繪圖狀態 self.g.save() self.g.translate(self.p1.x,self.p1.y) #alert(str(self.p1.x)+","+str(self.p1.y)) #self.g.rotate(-((math.pi/2)-self.getT())) self.g.rotate(-math.pi*0.5 + self.getT()) #alert(str(self.getT())) #self.g.rotate(10*math.pi/180) #this.g.rotate(-(Math.PI/2-this.getT())); # 必須配合畫在 y 軸上的 Link, 進行座標轉換, 也可以改為畫在 x 軸上... self.g.beginPath() self.g.moveTo(0,0) self.g.arc(0, 0, hole, 0, 2*math.pi, true) self.g.stroke() self.g.moveTo(0,length) self.g.beginPath() self.g.arc(0,length, hole, 0, 2*math.pi, true) self.g.stroke() self.g.moveTo(0,0) self.g.beginPath() self.g.arc(0,0, radius, 0, math.pi, true) self.g.moveTo(0+radius,0) self.g.lineTo(0+radius,0+length) self.g.stroke() self.g.moveTo(0,0+length) self.g.beginPath() self.g.arc(0, 0+length, radius, math.pi, 0, true) self.g.moveTo(0-radius,0+length) self.g.lineTo(0-radius,0) self.g.stroke() self.g.restore() self.g.beginPath() self.g.fillStyle = "red" self.g.font = "bold 18px sans-serif" self.g.fillText("%d, %d"%(self.p2.x, self.p2.y),self.p2.x, self.p2.y) self.g.stroke() self.g.restore() class Triangle(object): def __init__(self, p1, p2, p3): self.p1 = p1 self.p2 = p2 self.p3 = p3 def getLenp3(self): p1 = self.p1 ret = p1.distance(self.p2) return ret def getLenp1(self): p2 = self.p2 ret = p2.distance(self.p3) return ret def getLenp2(self): p1 = self.p1 ret = p1.distance(self.p3) return ret # 角度 def getAp1(self): ret = math.acos(((self.getLenp2() * self.getLenp2() + self.getLenp3() * self.getLenp3()) - self.getLenp1() * self.getLenp1()) / (2* self.getLenp2() * self.getLenp3())) return ret # def getAp2(self): ret =math.acos(((self.getLenp1() * self.getLenp1() + self.getLenp3() * self.getLenp3()) - self.getLenp2() * self.getLenp2()) / (2* self.getLenp1() * self.getLenp3())) return ret def getAp3(self): ret = math.acos(((self.getLenp1() * self.getLenp1() + self.getLenp2() * self.getLenp2()) - self.getLenp3() * self.getLenp3()) / (2* self.getLenp1() * self.getLenp2())) return ret def drawMe(self, g): self.g = g r = 5 # 繪出三個頂點 self.p1.drawMe(self.g,r) self.p2.drawMe(self.g,r) self.p3.drawMe(self.g,r) line1 = Line(self.p1,self.p2) line2 = Line(self.p1,self.p3) line3 = Line(self.p2,self.p3) # 繪出三邊線 line1.drawMe(self.g) line2.drawMe(self.g) line3.drawMe(self.g) # ends Triangle def # 透過三個邊長定義三角形 def setSSS(self, lenp3, lenp1, lenp2): self.lenp3 = lenp3 self.lenp1 = lenp1 self.lenp2 = lenp2 self.ap1 = math.acos(((self.lenp2 * self.lenp2 + self.lenp3 * self.lenp3) - self.lenp1 * self.lenp1) / (2* self.lenp2 * self.lenp3)) self.ap2 = math.acos(((self.lenp1 * self.lenp1 + self.lenp3 * self.lenp3) - self.lenp2 * self.lenp2) / (2* self.lenp1 * self.lenp3)) self.ap3 = math.acos(((self.lenp1 * self.lenp1 + self.lenp2 * self.lenp2) - self.lenp3 * self.lenp3) / (2* self.lenp1 * self.lenp2)) # 透過兩個邊長與夾角定義三角形 def setSAS(self, lenp3, ap2, lenp1): self.lenp3 = lenp3 self.ap2 = ap2 self.lenp1 = lenp1 self.lenp2 = math.sqrt((self.lenp3 * self.lenp3 + self.lenp1 * self.lenp1) - 2* self.lenp3 * self.lenp1 * math.cos(self.ap2)) #等於 SSS(AB, BC, CA) def setSaSS(self, lenp2, lenp3, lenp1): self.lenp2 = lenp2 self.lenp3 = lenp3 self.lenp1 = lenp1 if(self.lenp1 > (self.lenp2 + self.lenp3)): #<CAB 夾角為 180 度, 三點共線且 A 介於 BC 之間 ret = math.pi else : # <CAB 夾角為 0, 三點共線且 A 不在 BC 之間 if((self.lenp1 < (self.lenp2 - self.lenp3)) or (self.lenp1 < (self.lenp3 - self.lenp2))): ret = 0.0 else : # 透過餘絃定理求出夾角 <CAB ret = math.acos(((self.lenp2 * self.lenp2 + self.lenp3 * self.lenp3) - self.lenp1 * self.lenp1) / (2 * self.lenp2 * self.lenp3)) return ret # 取得三角形的三個邊長值 def getSSS(self): temp = [] temp.append( self.getLenp1() ) temp.append( self.getLenp2() ) temp.append( self.getLenp3() ) return temp # 取得三角形的三個角度值 def getAAA(self): temp = [] temp.append( self.getAp1() ) temp.append( self.getAp2() ) temp.append( self.getAp3() ) return temp # 取得三角形的三個角度與三個邊長 def getASASAS(self): temp = [] temp.append(self.getAp1()) temp.append(self.getLenp1()) temp.append(self.getAp2()) temp.append(self.getLenp2()) temp.append(self.getAp3()) temp.append(self.getLenp3()) return temp #2P 2L return mid P def setPPSS(self, p1, p3, lenp1, lenp3): temp = [] self.p1 = p1 self.p3 = p3 self.lenp1 = lenp1 self.lenp3 = lenp3 #bp3 is the angle beside p3 point, cp3 is the angle for line23, p2 is the output line31 = Line(p3, p1) self.lenp2 = line31.getR() #self.lenp2 = self.p3.distance(self.p1) #這裡是求角3 ap3 = math.acos(((self.lenp1 * self.lenp1 + self.lenp2 * self.lenp2) - self.lenp3 * self.lenp3) / (2 * self.lenp1 * self.lenp2)) #ap3 = math.acos(((self.lenp1 * self.lenp1 + self.lenp3 * self.lenp3) - self.lenp2 * self.lenp2) / (2 * self.lenp1 * self.lenp3)) bp3 = line31.getT() cp3 = bp3 - ap3 temp.append(p3.x + self.lenp1*math.cos(cp3))#p2.x temp.append(p3.y + self.lenp1*math.sin(cp3))#p2.y return temp def tag(g, p): None # 執行繪圖流程, 注意 x, y 為 global variables def draw(): global theta context.clearRect(0, 0, canvas.width, canvas.height) line1.drawMe(context) line2.drawMe(context) line3.drawMe(context) #triangle1.drawMe(context) #triangle2.drawMe(context) theta += dx p2.x = p1.x + line1.length*math.cos(theta*degree) p2.y = p1.y - line1.length*math.sin(theta*degree) p3.x, p3.y = triangle2.setPPSS(p2,p4,link2_len,link3_len) p1.tag(context) # 以上為相關函式物件的定義區 # 全域變數 # 幾何位置輸入變數 x=10 y=10 r=10 # 畫布與繪圖內容 # 其他輸入變數 theta = 0 degree = math.pi/180.0 dx = 2 dy = 4 #set p1.p2.p3.p4 position p1 = Point(150,100) p2 = Point(150,200) p3 = Point(300,300) p4 = Point(350,100) #accord position create link line1 = Link(p1,p2) line2 = Link(p2,p3) line3 = Link(p3,p4) line4 = Link(p1,p4) line5 = Link(p2,p4) link2_len = p2.distance(p3) link3_len = p3.distance(p4) #link2_len = line1.getR() #link3_len = line3.getR() #alert(str(link2_len)+','+str(link3_len)) triangle1 = Triangle(p1,p2,p4) triangle2 = Triangle(p2,p3,p4) # 視窗載入時執行內容 # 繪圖畫布設定 canvas = doc["plotarea"] context = canvas.getContext("2d") # 座標轉換, 移動 canvas.height 並且 y 座標變號, 也就是將原點座標移到畫面左下角 context.translate(0,canvas.height) context.scale(1,-1) #以間隔 10 micro seconds 重複呼叫 draw() #time.set_interval(draw,20) browser.timer.set_interval(draw,10)
2014c2g5/2014cadp
wsgi/local_data/brython_programs/brython_fourbar1.py
Python
gpl-3.0
11,960
/* * #%L * episodesmanager-services * * $Id$ * $HeadURL$ * %% * Copyright (C) 2009 - 2010 Jean Couteau * %% * 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/gpl-3.0.html>. * #L% */ package org.kootox.episodesmanager.services.importExport; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kootox.episodesmanager.entities.Episode; import org.kootox.episodesmanager.entities.Season; import org.kootox.episodesmanager.entities.Show; import org.kootox.episodesmanager.services.EpisodesManagerService; import org.kootox.episodesmanager.services.ServiceContext; import org.kootox.episodesmanager.services.shows.EpisodesService; import org.kootox.episodesmanager.services.shows.SeasonsService; import org.kootox.episodesmanager.services.shows.ShowsService; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.List; /** * * Class that can export different elements of database into XML * * User: couteau * Date: 12 mars 2010 */ public class XMLWriter implements EpisodesManagerService { private static Log log = LogFactory.getLog(XMLWriter.class); protected ServiceContext serviceContext; public XMLWriter(ServiceContext serviceContext) { this.serviceContext = serviceContext; } public void setServiceContext(ServiceContext serviceContext) { this.serviceContext = serviceContext; } /** * Export an episode into XML * * @param episode the episode to export into XML * @return the episode XML code */ private String exportEpisode(Episode episode) { StringBuilder builder = new StringBuilder(); builder.append(" <episode>\n"); //title builder.append(" <title>"); builder.append(escape(episode.getTitle())); builder.append("</title>\n"); //airing date builder.append(" <airdate>"); builder.append(episode.getAiringDate()); builder.append("</airdate>\n"); //acquired builder.append(" <acquired>"); builder.append(episode.getAcquired()); builder.append("</acquired>\n"); //viewed builder.append(" <watched>"); builder.append(episode.getViewed()); builder.append("</watched>\n"); //number builder.append(" <number>"); builder.append(episode.getNumber()); builder.append("</number>\n"); //summary builder.append(" <summary>"); builder.append(escape(episode.getSummary())); builder.append("</summary>\n"); builder.append(" </episode>\n"); return builder.toString() ; } private String exportSeason(Season season){ EpisodesService episodesService = serviceContext.newService(EpisodesService.class); StringBuilder builder = new StringBuilder(); builder.append(" <season>\n"); //number builder.append(" <number>"); builder.append(season.getNumber()); builder.append("</number>\n"); builder.append(" <episodes>\n"); List<Episode> episodes = episodesService.getAllEpisodes(season); for(Episode episode:episodes){ builder.append(exportEpisode(episode)); } builder.append(" </episodes>\n"); builder.append(" </season>\n"); return builder.toString(); } private String exportShow(Show show){ SeasonsService service = serviceContext.newService(SeasonsService.class); StringBuilder builder = new StringBuilder(); builder.append("<show>\n"); //title builder.append(" <name>"); builder.append(escape(show.getTitle())); builder.append("</name>\n"); //tvrage id builder.append(" <tvrageID>"); builder.append(show.getTvrageId()); builder.append("</tvrageID>\n"); //over builder.append(" <status>"); builder.append(show.getOver()); builder.append("</status>\n"); //origin country builder.append(" <origin_country>"); builder.append(escape(show.getOriginCountry())); builder.append("</origin_country>\n"); //runtime builder.append(" <runtime>"); builder.append(show.getRuntime()); builder.append("</runtime>\n"); //network builder.append(" <network>"); builder.append(escape(show.getNetwork())); builder.append("</network>\n"); //airtime builder.append(" <airtime>"); builder.append(show.getAirtime()); builder.append("</airtime>\n"); //timezone builder.append(" <timezone>"); builder.append(escape(show.getTimeZone())); builder.append("</timezone>\n"); builder.append(" <seasons>\n"); List<Season> seasons = service.getAllSeasons(show); for(Season season:seasons){ builder.append(exportSeason(season)); } builder.append(" </seasons>\n"); builder.append("</show>\n"); return builder.toString(); } public void exportToXML(File file) { ShowsService service = serviceContext.newService(ShowsService.class); OutputStreamWriter xmlFile = null; try { xmlFile = new FileWriter(file); List<Show> shows = service.getAllShows(); StringBuilder builder = new StringBuilder(); builder.append("<?xml version=\"1.0\"?>\n<shows>\n"); for(Show show:shows) { builder.append(exportShow(show)); } builder.append("</shows>\n"); xmlFile.write(builder.toString()); xmlFile.close(); } catch (Exception ex) { log.error("an error occurred", ex); } finally { try { xmlFile.close(); } catch (IOException eee) { log.error("Error trying to close file"); } catch (NullPointerException eee) { log.debug("Stream was not existing"); } } } private String escape(String toEscape){ return StringEscapeUtils.escapeXml(toEscape); } }
kootox/episodes-manager
episodesmanager-services/src/main/java/org/kootox/episodesmanager/services/importExport/XMLWriter.java
Java
gpl-3.0
7,089
#include "simulation/Elements.h" //#TPT-Directive ElementClass Element_PRTO PT_PRTO 110 Element_PRTO::Element_PRTO() { Identifier = "DEFAULT_PT_PRTO"; Name = "PRTO"; Colour = PIXPACK(0x0020EB); MenuVisible = 1; MenuSection = SC_SPECIAL; Enabled = 1; Advection = 0.0f; AirDrag = 0.00f * CFDS; AirLoss = 0.90f; Loss = 0.00f; Collision = 0.0f; Gravity = 0.0f; Diffusion = 0.00f; HotAir = 0.005f * CFDS; Falldown = 0; Flammable = 0; Explosive = 0; Meltable = 0; Hardness = 0; Weight = 100; Temperature = R_TEMP+0.0f +273.15f; HeatConduct = 0; Description = "Portal OUT. Things come out here, now with channels (same as WIFI)"; State = ST_SOLID; Properties = TYPE_SOLID; LowPressure = IPL; LowPressureTransition = NT; HighPressure = IPH; HighPressureTransition = NT; LowTemperature = ITL; LowTemperatureTransition = NT; HighTemperature = ITH; HighTemperatureTransition = NT; Update = &Element_PRTO::update; Graphics = &Element_PRTO::graphics; } /*these are the count values of where the particle gets stored, depending on where it came from 0 1 2 7 . 3 6 5 4 PRTO does (count+4)%8, so that it will come out at the opposite place to where it came in PRTO does +/-1 to the count, so it doesn't jam as easily */ //#TPT-Directive ElementHeader Element_PRTO static int update(UPDATE_FUNC_ARGS) int Element_PRTO::update(UPDATE_FUNC_ARGS) { int r, nnx, rx, ry, np, fe = 0; int count = 0; parts[i].tmp = (int)((parts[i].temp-73.15f)/100+1); if (parts[i].tmp>=CHANNELS) parts[i].tmp = CHANNELS-1; else if (parts[i].tmp<0) parts[i].tmp = 0; for (count=0; count<8; count++) { rx = sim->portal_rx[count]; ry = sim->portal_ry[count]; if (x+rx>=0 && y+ry>0 && x+rx<XRES && y+ry<YRES && (rx || ry)) { r = pmap[y+ry][x+rx]; if (!r) fe = 1; if (r) continue; if (!r) { for ( nnx =0 ; nnx<80; nnx++) { int randomness = (count + rand()%3-1 + 4)%8;//add -1,0,or 1 to count if (sim->portalp[parts[i].tmp][randomness][nnx].type==PT_SPRK)// TODO: make it look better, spark creation { sim->create_part(-1,x+1,y,PT_SPRK); sim->create_part(-1,x+1,y+1,PT_SPRK); sim->create_part(-1,x+1,y-1,PT_SPRK); sim->create_part(-1,x,y-1,PT_SPRK); sim->create_part(-1,x,y+1,PT_SPRK); sim->create_part(-1,x-1,y+1,PT_SPRK); sim->create_part(-1,x-1,y,PT_SPRK); sim->create_part(-1,x-1,y-1,PT_SPRK); sim->portalp[parts[i].tmp][randomness][nnx] = sim->emptyparticle; break; } else if (sim->portalp[parts[i].tmp][randomness][nnx].type) { if (sim->portalp[parts[i].tmp][randomness][nnx].type==PT_STKM) sim->player.spwn = 0; if (sim->portalp[parts[i].tmp][randomness][nnx].type==PT_STKM2) sim->player2.spwn = 0; if (sim->portalp[parts[i].tmp][randomness][nnx].type==PT_FIGH) { sim->fighcount--; sim->fighters[(unsigned char)sim->portalp[parts[i].tmp][randomness][nnx].tmp].spwn = 0; } np = sim->create_part(-1, x+rx, y+ry, sim->portalp[parts[i].tmp][randomness][nnx].type); if (np<0) { if (sim->portalp[parts[i].tmp][randomness][nnx].type==PT_STKM) sim->player.spwn = 1; if (sim->portalp[parts[i].tmp][randomness][nnx].type==PT_STKM2) sim->player2.spwn = 1; if (sim->portalp[parts[i].tmp][randomness][nnx].type==PT_FIGH) { sim->fighcount++; sim->fighters[(unsigned char)sim->portalp[parts[i].tmp][randomness][nnx].tmp].spwn = 1; } continue; } if (parts[np].type==PT_FIGH) { // Release the fighters[] element allocated by create_part, the one reserved when the fighter went into the portal will be used sim->fighters[(unsigned char)parts[np].tmp].spwn = 0; sim->fighters[(unsigned char)sim->portalp[parts[i].tmp][randomness][nnx].tmp].spwn = 1; } if (sim->portalp[parts[i].tmp][randomness][nnx].vx == 0.0f && sim->portalp[parts[i].tmp][randomness][nnx].vy == 0.0f) { // particles that have passed from PIPE into PRTI have lost their velocity, so use the velocity of the newly created particle if the particle in the portal has no velocity float tmp_vx = parts[np].vx; float tmp_vy = parts[np].vy; parts[np] = sim->portalp[parts[i].tmp][randomness][nnx]; parts[np].vx = tmp_vx; parts[np].vy = tmp_vy; } else parts[np] = sim->portalp[parts[i].tmp][randomness][nnx]; parts[np].x = x+rx; parts[np].y = y+ry; sim->portalp[parts[i].tmp][randomness][nnx] = sim->emptyparticle; break; } } } } } if (fe) { int orbd[4] = {0, 0, 0, 0}; //Orbital distances int orbl[4] = {0, 0, 0, 0}; //Orbital locations if (!sim->parts[i].life) parts[i].life = rand()*rand()*rand(); if (!sim->parts[i].ctype) parts[i].ctype = rand()*rand()*rand(); sim->orbitalparts_get(parts[i].life, parts[i].ctype, orbd, orbl); for (r = 0; r < 4; r++) { if (orbd[r]<254) { orbd[r] += 16; if (orbd[r]>254) { orbd[r] = 0; orbl[r] = rand()%255; } else { orbl[r] += 1; orbl[r] = orbl[r]%255; } //orbl[r] += 1; //orbl[r] = orbl[r]%255; } else { orbd[r] = 0; orbl[r] = rand()%255; } } sim->orbitalparts_set(&parts[i].life, &parts[i].ctype, orbd, orbl); } else { parts[i].life = 0; parts[i].ctype = 0; } return 0; } //#TPT-Directive ElementHeader Element_PRTO static int graphics(GRAPHICS_FUNC_ARGS) int Element_PRTO::graphics(GRAPHICS_FUNC_ARGS) { *firea = 8; *firer = 0; *fireg = 0; *fireb = 255; *pixel_mode |= EFFECT_DBGLINES; *pixel_mode |= EFFECT_GRAVOUT; *pixel_mode &= ~PMODE; *pixel_mode |= PMODE_ADD; return 1; } Element_PRTO::~Element_PRTO() {}
jacksonmj/Powder-Toy-Mods
src/simulation/elements/PRTO.cpp
C++
gpl-3.0
5,973
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package basicintast.util; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.misc.ParseCancellationException; /** * * @author wellington */ public class ThrowingErrorListener extends BaseErrorListener { public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException { throw new ParseCancellationException("Error on line " + line + " character " + charPositionInLine + " " + msg); } }
wellingtondellamura/compilers-codes-samples
parsers/antlr/BasicIntAST/src/basicintast/util/ThrowingErrorListener.java
Java
gpl-3.0
1,023
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Управление общими сведениями о сборке осуществляется с помощью // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("lexical")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("lexical")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми // для COM-компонентов. Если требуется обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("a1f308d1-a37a-4415-b36c-46ed5052c828")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер построения // Редакция // // Можно задать все значения или принять номер построения и номер редакции по умолчанию, // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
palexisru/pl2_rus
v01/pl2/lexical/lexical/Properties/AssemblyInfo.cs
C#
gpl-3.0
2,024
package net.diecode.killermoney.events; import net.diecode.killermoney.objects.CCommand; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class KMCCommandExecutionEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private CCommand cCommand; private Player killer; private LivingEntity victim; private boolean cancelled; public KMCCommandExecutionEvent(CCommand cCommand, Player killer, LivingEntity victim) { this.cCommand = cCommand; this.killer = killer; this.victim = victim; } public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } public CCommand getCCommand() { return cCommand; } public Player getKiller() { return killer; } public LivingEntity getVictim() { return victim; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } }
diecode/KillerMoney
src/net/diecode/killermoney/events/KMCCommandExecutionEvent.java
Java
gpl-3.0
1,271
/** Copyright: 2015/2016 Benjamin Aigner developer.google.com This file is part of AustrianPublicStream. AustrianPublicStream 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. AustrianPublicStream 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 AustrianPublicStream. If not, see <http://www.gnu.org/licenses/>. **/ package systems.byteswap.publicstream; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceActivity; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatDelegate; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; /** * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls * to be used with AppCompat. */ public abstract class AppCompatPreferenceActivity extends PreferenceActivity { private AppCompatDelegate mDelegate; @Override protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getDelegate().onPostCreate(savedInstanceState); } public ActionBar getSupportActionBar() { return getDelegate().getSupportActionBar(); } @NonNull @Override public MenuInflater getMenuInflater() { return getDelegate().getMenuInflater(); } @Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override public void setContentView(View view) { getDelegate().setContentView(view); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { getDelegate().setContentView(view, params); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { getDelegate().addContentView(view, params); } @Override protected void onPostResume() { super.onPostResume(); getDelegate().onPostResume(); } @Override protected void onTitleChanged(CharSequence title, int color) { super.onTitleChanged(title, color); getDelegate().setTitle(title); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getDelegate().onConfigurationChanged(newConfig); } @Override protected void onStop() { super.onStop(); getDelegate().onStop(); } @Override protected void onDestroy() { super.onDestroy(); getDelegate().onDestroy(); } public void invalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } private AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, null); } return mDelegate; } }
benjaminaigner/AustrianPublicStream
app/src/main/java/systems/byteswap/publicstream/AppCompatPreferenceActivity.java
Java
gpl-3.0
3,612
#include "AsyncHTTPClient.h" #include "../httprequest.h" #include "../GlobalFuncs.h" #include <comutil.h> #include <winhttp.h> AsyncHTTPClient::AsyncHTTPClient() : m_url(""), m_currentStatus(AsyncHTTPClient::HTTP_READY), m_response(""), m_responseCode(0) {} AsyncHTTPClient::~AsyncHTTPClient() { } void AsyncHTTPClient::addArgument(const std::string & argName, const std::string & content) { m_args.emplace_back(argName, content); } void AsyncHTTPClient::asyncSendWorker() { // To prevent the destructor from beeing executed. std::shared_ptr<AsyncHTTPClient> lock = shared_from_this(); // FIXME: Only apply arg list in URL for GET, otherwise pass as data. std::string fullArgList = ""; for (const std::pair<std::string, std::string>& argPack : m_args) { fullArgList += argPack.first + "=" + url_encode(argPack.second) + "&"; } if (fullArgList.length() > 0) { fullArgList = fullArgList.substr(0, fullArgList.length() - 1); // To remove the extra "&" } std::string method = ""; switch (m_method) { case HTTP_POST: method = "POST"; break; case HTTP_GET: default: method = "GET"; break; } HRESULT hr; CLSID clsid; IWinHttpRequest *pIWinHttpRequest = NULL; _variant_t varFalse(false); _variant_t varData(fullArgList.c_str()); _variant_t varContent(""); if (m_method == HTTP_POST) varContent = fullArgList.c_str(); hr = CLSIDFromProgID(L"WinHttp.WinHttpRequest.5.1", &clsid); if (SUCCEEDED(hr)) { hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, IID_IWinHttpRequest, (void **)&pIWinHttpRequest); } if (SUCCEEDED(hr)) { hr = pIWinHttpRequest->SetTimeouts(1000, 1000, 2000, 1000); } if (SUCCEEDED(hr)) { _bstr_t method(method.c_str()); _bstr_t url; if (m_method == HTTP_GET) { url = ((m_url + (fullArgList.empty() ? "" : "?") + fullArgList).c_str()); } else { url = m_url.c_str(); } hr = pIWinHttpRequest->Open(method, url, varFalse); } if (m_method == HTTP_POST) { if (SUCCEEDED(hr)) { hr = pIWinHttpRequest->SetRequestHeader(bstr_t("Content-Type"), bstr_t("application/x-www-form-urlencoded")); } } if (SUCCEEDED(hr)) { hr = pIWinHttpRequest->Send(varContent); if ((hr & 0xFFFF) == ERROR_WINHTTP_TIMEOUT) m_responseCode = 408; // If timeout then set the HTTP response code. } if (SUCCEEDED(hr)) { LONG statusCode = 0; hr = pIWinHttpRequest->get_Status(&statusCode); m_responseCode = statusCode; } _variant_t responseRaw(""); if (SUCCEEDED(hr)) { if (m_responseCode == 200) { hr = pIWinHttpRequest->get_ResponseBody(&responseRaw); } else { hr = E_FAIL; } } if (SUCCEEDED(hr)) { // body long upperBounds; long lowerBounds; byte* buff; if (responseRaw.vt == (VT_ARRAY | VT_UI1)) { long dims = SafeArrayGetDim(responseRaw.parray); if (dims == 1) { SafeArrayGetLBound(responseRaw.parray, 1, &lowerBounds); SafeArrayGetUBound(responseRaw.parray, 1, &upperBounds); upperBounds++; SafeArrayAccessData(responseRaw.parray, (void**)&buff); m_response = std::string(reinterpret_cast<const char *>(buff), upperBounds-lowerBounds); SafeArrayUnaccessData(responseRaw.parray); } } } m_currentStatus.store(HTTP_FINISHED, std::memory_order_relaxed); m_asyncSendWorkerThread.detach(); // To be absolutely safe pIWinHttpRequest->Release(); m_finishNotifier.notify_all(); } void AsyncHTTPClient::asynSend() { if (getStatus() != HTTP_READY) return; m_currentStatus.store(HTTP_PROCESSING, std::memory_order_relaxed); m_asyncSendWorkerThread = std::thread([this]() { asyncSendWorker(); }); } std::string AsyncHTTPClient::getResponseData() const { if (getStatus() != HTTP_FINISHED) return ""; return m_response; } AsyncHTTPClient::AsyncHTTPStatus AsyncHTTPClient::getStatus() const { return m_currentStatus.load(std::memory_order_relaxed); } void AsyncHTTPClient::setUrl(const std::string& url) { if (getStatus() != HTTP_READY) return; m_url = url; } std::string AsyncHTTPClient::getUrl() const { if (getStatus() != HTTP_READY) return ""; return m_url; } int AsyncHTTPClient::getStatusCode() const { if (getStatus() != HTTP_FINISHED) return 0; return m_responseCode; } void AsyncHTTPClient::waitUntilResponse() { if (getStatus() != HTTP_PROCESSING) return; std::unique_lock<std::mutex> lock(m_asyncSendMutex); m_finishNotifier.wait(lock); }
zeriyoshi/LunaDLL
LunaDll/Misc/AsyncHTTPClient.cpp
C++
gpl-3.0
4,828
/* * lemonjuice - Java Template Engine. * Copyright (C) 2009-2012 Manuel Tomis manuel@codegremlins.com * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ package com.codegremlins.lemonjuice.engine; import com.codegremlins.lemonjuice.TemplateContext; import com.codegremlins.lemonjuice.util.Functions; class EqualElement extends Element { private Element left; private Element right; private boolean condition; public EqualElement(boolean condition, Element left, Element right) { this.condition = condition; this.left = left; this.right = right; } @Override public Object evaluate(TemplateContext model) throws Exception { Object lvalue = left.evaluate(model); Object rvalue = right.evaluate(model); return condition == Functions.compareEqual(lvalue, rvalue); } }
mtomis/lemonjuice
src/com/codegremlins/lemonjuice/engine/EqualElement.java
Java
gpl-3.0
1,485
package br.net.ubre.lang.keyword.binary.relational; import br.net.ubre.data.container.DataContainer; import br.net.ubre.lang.data.literal.FalseStatement; import br.net.ubre.lang.data.literal.TrueStatement; import br.net.ubre.lang.statement.Statement; /** * COmpara se os valores das partes (esquerda e direita) são iguais. * * @author Douglas Siviotti (073.116.317-69) * @version 24/03/2015 * */ public class EqualsOperator extends RelationalKeyword { public EqualsOperator(String token) { super(token); } public Statement perform(DataContainer container) { Object leftResult = left.result(container); Object rightResult = right.result(container); if (leftResult != null) { return (leftResult.equals(rightResult)) ? TrueStatement.INSTANCE : FalseStatement.INSTANCE; } return (rightResult == null) ? TrueStatement.INSTANCE : FalseStatement.INSTANCE; } }
siviotti/ubre
ubre-core/src/main/java/br/net/ubre/lang/keyword/binary/relational/EqualsOperator.java
Java
gpl-3.0
895
/* PostMonster, universal HTTP automation tool * Copyright (C) 2015 by Paul Artsishevsky <polter.rnd@gmail.com> * * This file is part of PostMonster. * * PostMonster 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. * * PostMonster 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 PostMonster. If not, see <http://www.gnu.org/licenses/>. */ #include "pluginregistry.h" #include <QSettings> #include <QPluginLoader> #include <QDir> PluginRegistry &PluginRegistry::instance() { static PluginRegistry m_instance; return m_instance; } void PluginRegistry::loadPlugins(const PostMonster::APIFunctions &api) { QDir pluginsDir = QDir::current(); pluginsDir.cd("plugins"); QSettings settings; int size = settings.beginReadArray("Plugins"); // Load static plugins QHash<QObject *, QPair<QJsonObject, QPluginLoader *> > plugins; foreach (const QStaticPlugin &plugin, QPluginLoader::staticPlugins()) { QObject *pluginInstance = plugin.instance(); plugins[pluginInstance] = QPair<QJsonObject, QPluginLoader *>(plugin.metaData(), nullptr); } // Load dynamic plugins for (int i = 0; i < size; ++i) { settings.setArrayIndex(i); QPluginLoader *loader = new QPluginLoader(pluginsDir.absoluteFilePath( settings.value("filename").toString())); QObject *pluginInstance = loader->instance(); plugins[pluginInstance] = QPair<QJsonObject, QPluginLoader *>(loader->metaData(), loader); } // Activate plugins QHashIterator<QObject *, QPair<QJsonObject, QPluginLoader *>> i(plugins); while (i.hasNext()) { i.next(); QObject *instance = i.key(); QJsonObject metaData = i.value().first["MetaData"].toObject(); QPluginLoader *loader = i.value().second; PostMonster::ToolPluginInterface *tool = qobject_cast<PostMonster::ToolPluginInterface *>(instance); if (tool) { PluginData *pluginData = new PluginData; pluginData->type = PostMonster::Tool; pluginData->instance = tool; pluginData->loader = loader; pluginData->info = metaData; //TODO Check for existent plugins with the same id m_plugins[metaData["id"].toString()] = pluginData; m_info[tool] = &pluginData->info; // Add tool plugins to toolbar tool->load(api); emit toolPluginLoaded(instance); } } } PostMonster::ToolPluginInterface *PluginRegistry::tool(const QString &name) { if (m_plugins.contains(name) && m_plugins[name]->type == PostMonster::Tool) { return dynamic_cast<PostMonster::ToolPluginInterface *>(m_plugins[name]->instance); } return nullptr; } const QJsonObject &PluginRegistry::info(const PostMonster::PluginInterface *plugin) { return *m_info[plugin]; } const QList<PluginRegistry::PluginData *> PluginRegistry::plugins(PostMonster::PluginType type) { QList<PluginData *> result; foreach (PluginData *plugin, m_plugins.values()) { if (plugin->type & type) result << plugin; } return result; } PluginRegistry::~PluginRegistry() { qDeleteAll(m_plugins.values()); }
PostMonster/postmonster
src/pluginregistry.cpp
C++
gpl-3.0
3,715
/* * A Command & Conquer: Renegade SSGM Plugin, containing all the single player mission scripts * Copyright(C) 2017 Neijwiert * * This program is free software : you can redistribute it and / or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program.If not, see <http://www.gnu.org/licenses/>. */ #include "General.h" #include "M01_Nod_GuardTower_Tailgun_JDG.h" // This script is never used void M01_Nod_GuardTower_Tailgun_JDG::Created(GameObject *obj) { ActionParamsStruct params; params.Set_Basic(this, 100.0f, 17); Vector3 pos = Commands->Get_Position(obj); GameObject *starObj = Commands->Get_A_Star(pos); params.Set_Attack(starObj, 30.0f, 1.0f, true); Commands->Action_Attack(obj, params); } ScriptRegistrant<M01_Nod_GuardTower_Tailgun_JDG> M01_Nod_GuardTower_Tailgun_JDGRegistrant("M01_Nod_GuardTower_Tailgun_JDG", "");
Neijwiert/C-C-Renegade-Mission-Scripts
Source/Single Player Scripts/M01_Nod_GuardTower_Tailgun_JDG.cpp
C++
gpl-3.0
1,307
//: move/Nap.java package pokepon.move; import pokepon.enums.*; import pokepon.pony.Pony; import pokepon.battle.*; /** * Heal 50% of user's HP. * * @author silverweed */ public class Nap extends Move { public Nap() { super("Nap"); type = Type.NIGHT; moveType = Move.MoveType.STATUS; maxpp = pp = 10; accuracy = -1; priority = 0; briefDesc = "User sleeps 2 turns to refill HP and cure status."; healUser = 1f; healUserStatus = 1f; } public Nap(Pony p) { this(); pony = p; } @Override public BattleEvent[] getBattleEvents() { return new BattleEvent[] { new BattleEvent(1, name) { @Override public void afterMoveUsage(final BattleEngine be) { if(be.getAttacker() == pony && !pony.isFainted()) { pony.setAsleep(true); if(be.getBattleTask() != null) { be.getBattleTask().sendB("|battle|"+pony.getNickname()+" takes a nap and becomes healthy!"); be.getBattleTask().sendB(be.getConnection(be.getSide(pony)),"|addstatus|ally|slp"); be.getBattleTask().sendB(be.getConnection(be.getOppositeSide(pony)),"|addstatus|opp|slp"); } pony.sleepCounter = 3; count = 0; } } } }; } }
silverweed/pokepon
move/Nap.java
Java
gpl-3.0
1,192
package l2s.gameserver.ai; import l2s.gameserver.model.Creature; import l2s.gameserver.model.instances.NpcInstance; import l2s.gameserver.model.instances.MonsterInstance; /** * @author Bonux **/ public class SpecialTautiMonsters extends Fighter { public SpecialTautiMonsters(NpcInstance actor) { super(actor); } @Override protected void onEvtAttacked(Creature attacker, int damage) { NpcInstance actor = getActor(); if(!canAttack(actor.getNpcId(), attacker)) return; super.onEvtAttacked(attacker, damage); } @Override public boolean canAttackCharacter(Creature target) { NpcInstance actor = getActor(); return canAttack(actor.getNpcId(), target); } @Override public int getMaxAttackTimeout() { return 0; } private boolean canAttack(int selfId, Creature target) { if(selfId == 33680 || selfId == 33679) //peace { if(target.isPlayable()) return false; else return target.isMonster(); } else //not peace { if(target.isMonster()) { MonsterInstance monster = (MonsterInstance) target; if(monster.getNpcId() == 19262 || monster.getNpcId() == 19263 || monster.getNpcId() == 19264 || monster.getNpcId() == 19265 || monster.getNpcId() == 19266) return false; else return true; } else return !target.isNpc(); } } }
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/ai/SpecialTautiMonsters.java
Java
gpl-3.0
1,320
#!/usr/bin/env python # -*- coding: utf-8 -*- import time timeformat='%H:%M:%S' def begin_banner(): print '' print '[*] swarm starting at '+time.strftime(timeformat,time.localtime()) print '' def end_banner(): print '' print '[*] swarm shutting down at '+time.strftime(timeformat,time.localtime()) print ''
Arvin-X/swarm
lib/utils/banner.py
Python
gpl-3.0
334
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MinecraftUSkinEditor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MinecraftUSkinEditor")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0acaaede-93f5-4b5d-b8d7-a0c43359c0d6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Nobledez/MineKampf
MinecraftUSkinEditor/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,452
package com.healthcare.db.client; import com.healthcare.db.model.Itemmapping; import com.healthcare.db.model.ItemmappingExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface ItemmappingMapper { /** * This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping * @mbggenerated Mon Jul 27 06:41:29 ICT 2015 */ int countByExample(ItemmappingExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping * @mbggenerated Mon Jul 27 06:41:29 ICT 2015 */ int deleteByExample(ItemmappingExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping * @mbggenerated Mon Jul 27 06:41:29 ICT 2015 */ int insert(Itemmapping record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping * @mbggenerated Mon Jul 27 06:41:29 ICT 2015 */ int insertSelective(Itemmapping record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping * @mbggenerated Mon Jul 27 06:41:29 ICT 2015 */ List<Itemmapping> selectByExample(ItemmappingExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping * @mbggenerated Mon Jul 27 06:41:29 ICT 2015 */ int updateByExampleSelective(@Param("record") Itemmapping record, @Param("example") ItemmappingExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping * @mbggenerated Mon Jul 27 06:41:29 ICT 2015 */ int updateByExample(@Param("record") Itemmapping record, @Param("example") ItemmappingExample example); }
punyararj/his-interface-core
HISIF_CORE/src/com/healthcare/db/client/ItemmappingMapper.java
Java
gpl-3.0
1,934
<?php namespace Cms\Dao\Import; use Cms\Dao\Import as Dao; use Cms\Dao\Doctrine as DoctrineBase; /** * Doctrine Dao für den Import * * @package Cms * @subpackage Dao */ class Doctrine extends DoctrineBase implements Dao { }
rukzuk/rukzuk
app/server/library/Cms/Dao/Import/Doctrine.php
PHP
gpl-3.0
242
// GoSquared var GoSquared = {}; GoSquared.acct = "GSN-064561-T"; (function(w){ function gs(){ w._gstc_lt = +new Date; var d = document, g = d.createElement("script"); g.type = "text/javascript"; g.src = "//d1l6p2sc9645hc.cloudfront.net/tracker.js"; var s = d.getElementsByTagName("script")[0]; s.parentNode.insertBefore(g, s); } w.addEventListener ? w.addEventListener("load", gs, false) : w.attachEvent("onload", gs); })(window); // Google Analytics var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-40084408-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
Moussa/Wiki-Fi
static/js/analytics.js
JavaScript
gpl-3.0
905
/* * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EconomicSDK { /// <summary> /// Providers view options for pagination. /// </summary> public class ViewOptions { #region === constructor === /// <summary> /// /// </summary> public ViewOptions() : this(20,0) { } /// <summary> /// /// </summary> /// <param name="pageSize"></param> /// <param name="skipPages"></param> public ViewOptions(int pageSize, int skipPages) { if (PageSize > 1000) throw new ArgumentOutOfRangeException("Maximum page size of 1.000."); this.PageSize = pageSize; this.SkipPages = skipPages; } #endregion #region === public properties === /// <summary> /// Gets or sets the page size of the pagination. /// </summary> public int PageSize { get; set; } /// <summary> /// Gets or sets the number of pages to skip. /// </summary> public int SkipPages { get; set; } #endregion #region === public methods === /// <summary> /// Append to the url. /// </summary> /// <param name="url">Url of the request.</param> public void AppendTo(ref string url) { if (!url.Contains("?")) { url += "?"; } else { url += "&"; } url += string.Format("skippages={1}&pagesize={0}", this.PageSize, this.SkipPages); } #endregion } }
cloudfy/economicsdk
ViewOptions.cs
C#
gpl-3.0
2,382
/** * @file FESpace_imp.hpp * @brief Implementation of the functional space class methods * @author Carlo Marcati * @date 2013-09-08 */ /* 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 __FESPACE_IMP_HPP__ #define __FESPACE_IMP_HPP__ 1 namespace Tspeed{ template<int N, typename Q, typename S> FESpace<N,Q,S>::FESpace(Mesh_ptr m):M_mesh(m),M_quad(),M_sh(),M_nln((N+1)*(N+2)/2),M_nqn2d(Q::nqn2d),M_ne(M_mesh->ne()) { for(int i=0; i<M_nln; ++i) { M_B.col(i) = M_sh.phi(i,M_quad.int_nodes().col(0), M_quad.int_nodes().col(1)); M_G[i].row(0) = M_sh.grad(i,M_quad.int_nodes().col(0), M_quad.int_nodes().col(1)).col(0).transpose(); M_G[i].row(1) = M_sh.grad(i,M_quad.int_nodes().col(0), M_quad.int_nodes().col(1)).col(1).transpose(); M_vert_basis(i,0) = M_sh.phi(i,0.2,0.2); M_vert_basis(i,1) = M_sh.phi(i,0.8,0.2); M_vert_basis(i,2) = M_sh.phi(i,0.2,0.8); M_vert_basis(i,3) = M_sh.phi(i,0.5,0.5); for(int iedg=0; iedg<3; ++iedg) { M_Bedge[iedg].col(i) = M_sh.phi (i, M_quad.edge_nodes(iedg).col(0), M_quad.edge_nodes(iedg).col(1)); M_Gedge[i*3+iedg].row(0) = M_sh.grad(i, M_quad.edge_nodes(iedg).col(0), M_quad.edge_nodes(iedg).col(1)).col(0); M_Gedge[i*3+iedg].row(1) = M_sh.grad(i, M_quad.edge_nodes(iedg).col(0), M_quad.edge_nodes(iedg).col(1)).col(1); } } base_mass_and_inv(); std::cout << "FESpace :: " << (N+1)*(N+2)/2*M_mesh->ne() << " dof per component." << std::endl; }; template<int N, typename Q, typename S> void FESpace<N,Q,S>::base_mass_and_inv() { if(S::is_orthonormal) { M_base_mass = Eigen::MatrixXd::Identity(S::gdl, S::gdl); } else { M_base_mass = Eigen::MatrixXd::Zero(S::gdl, S::gdl); for(int i=0; i<S::gdl ; ++i) { for (int j = 0; j<S::gdl ; ++j) { for(int k = 0; k<Q::nqn2d ; ++k) M_base_mass(i,j) += M_B(k,i)*M_B(k,j)*M_quad.iweight(k); } } } M_base_invmass = M_base_mass.inverse(); }; template<int N, typename Q, typename S> void FESpace<N,Q,S>::points_out(std::string const &fname)const { std::ofstream outf(fname); Geo::Point p0(0.2,0.2),p1(0.8,0.2),p2(0.2,0.8),p3(0.5,0.5); for(auto ie: M_mesh->elements()) { outf << ie.map(p0).x() << " " << ie.map(p0).y() << std::endl; outf << ie.map(p1).x() << " " << ie.map(p1).y() << std::endl; outf << ie.map(p2).x() << " " << ie.map(p2).y() << std::endl; outf << ie.map(p3).x() << " " << ie.map(p3).y() << std::endl; } outf.close(); } template<int N, typename Q, typename S> void FESpace<N,Q,S>::field_out(std::string const &fname, Eigen::VectorXd const &uh, unsigned int step)const { //std::ofstream outf_s1(fname+"u_x_"+std::to_string(step)+".field"); //std::ofstream outf_s2(fname+"u_y_"+std::to_string(step)+".field"); std::ofstream outf_v(fname+"u_"+std::to_string(step)+".field"); double valx, valy; for(auto ie: M_mesh->elements()) { for(int i = 0; i<4 ; ++i) { valx = M_vert_basis.col(i).dot(uh.segment(ie.id()*M_nln,M_nln)); valy = M_vert_basis.col(i).dot(uh.segment(ie.id()*M_nln+M_ne*M_nln,M_nln)); //outf_s1 << valx << std::endl; //outf_s2 << valy << std::endl; outf_v << valx << " " << valy << std::endl; } } //outf_s1.close(); //outf_s2.close(); outf_v.close(); } template<int N, typename Q, typename S> double FESpace<N,Q,S>::L2error(std::function<std::array<double,2>(double,double)> const & uex, Eigen::VectorXd const & uh)const { Eigen::MatrixXd local_exact = Eigen::MatrixXd::Zero(M_nqn2d,2); Eigen::MatrixXd local_aprox = Eigen::MatrixXd::Zero(M_nqn2d,2); std::array<double,2 > F; Geo::Point p; double error = 0; double error_loc = 0; for(auto ie: M_mesh->elements()) { error_loc = 0; local_aprox.col(0) = M_B*uh.segment(ie.id()*M_nln, M_nln); local_aprox.col(1) = M_B*uh.segment(M_nln*M_ne+ie.id()*M_nln, M_nln); for(int i=0; i<M_nqn2d; ++i) { p = ie.map(M_quad.inode(i)); F = uex(p.x(), p.y()); //local_exact(i,0) = F[0]; //local_exact(i,1) = F[1]; error_loc += ((local_aprox(i,0) - F[0])*(local_aprox(i,0)-F[0])+(local_aprox(i,1) - F[1])*(local_aprox(i,1)-F[1]))*M_quad.iweight(i); } //std::cout << "********" << error_loc << std::endl; error += error_loc*ie.detJ(); } return std::sqrt(error); }; template<int N, typename Q, typename S> Eigen::VectorXd FESpace<N,Q,S>::transform(std::function<std::array<double,2>(double,double)> const & fun)const { Eigen::VectorXd uh(2*M_ne*M_nln); unsigned int startIndex; unsigned int size = M_nln; Eigen::VectorXd rhs(M_nln); for(auto ie: M_mesh->elements()) { startIndex = ie.id()*M_nln; rhs = M_loc_rhs(ie,fun); //std::cout << ie.id() << ": " << std::endl; //std::cout << ie.Jac() << std::endl << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << std::endl; //std::cout << rhs << std::endl; //std::cout << std::endl; //invM = 1./ie.detJ()*Eigen::MatrixXd::Identity(M_nln,M_nln); uh.segment(startIndex, size) = 1./ie.detJ()*M_base_invmass * rhs.segment(0, size); uh.segment(startIndex + M_ne*M_nln, size) = 1./ie.detJ()*M_base_invmass * rhs.segment(M_nln, size); } return uh; } template<int N, typename Q, typename S> Eigen::VectorXd FESpace<N,Q,S>::M_loc_rhs(Geo::Triangle const & ie , std::function<std::array<double,2>(double,double)> const & fun)const { double dx; Geo::Point p; std::array<double,2> F; Eigen::VectorXd out(2*M_nln); out = Eigen::VectorXd::Zero(2*M_nln); for(unsigned int i=0; i<Q::nqn2d; ++i) { dx = std::abs(ie.detJ())*M_quad.iweight(i); p = ie.map(M_quad.inode(i)); F = fun(p.x(),p.y()); out.segment(0,M_nln) += F[0]*dx*M_B.row(i); out.segment(M_nln,M_nln) += F[1]*dx*M_B.row(i); } //std::cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" <<std::endl; //std::cout << *out << std::endl; //std::cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" <<std::endl; return out; } } #endif
carlomr/tspeed
lib/include/FESpace_imp.hpp
C++
gpl-3.0
6,726
#!/usr/bin/python -Wall # -*- coding: utf-8 -*- """ <div id="content"> <div style="text-align:center;" class="print"><img src="images/print_page_logo.png" alt="projecteuler.net" style="border:none;" /></div> <h2>Number letter counts</h2><div id="problem_info" class="info"><h3>Problem 17</h3><span>Published on Friday, 17th May 2002, 06:00 pm; Solved by 88413; Difficulty rating: 5%</span></div> <div class="problem_content" role="problem"> <p>If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.</p> <p>If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? </p> <br /> <p class="note"><b>NOTE:</b> Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.</p> </div><br /> <br /></div> """ s={0:"",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",10:"ten",11:"eleven",12:"twelve",13:"thirteen",14:"fourteen",15:"fifteen",16:"sixteen",17:"seventeen",18:"eighteen",19:"nineteen",20:"twenty",30:"thirty",40:"forty",50:"fifty",60:"sixty",70:"seventy",80:"eighty",90:"ninety"} for i in range(1,1000): if(not i in s.keys()): if(i<100): s[i]=s[i/10*10]+s[i%10] else: s[i]=s[i/100]+"hundred" if(i%100): s[i]+="and"+s[i%100] s[1000]="onethousand" total=0; for i in s.values(): total+=len(i) print total
beyoungwoo/C_glibc_Sample
_Algorithm/ProjectEuler_python/euler_17.py
Python
gpl-3.0
1,631
/******************************************************************************* * Copyright (c) 2013 Christian Wiwie. * 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 * * Contributors: * Christian Wiwie - initial API and implementation ******************************************************************************/ /** * */ package de.clusteval.data.goldstandard.format; // TODO: Auto-generated Javadoc /** * The Class GoldStandardFormat. * * @author Christian Wiwie */ public class GoldStandardFormat { /** * Instantiates a new gold standard format. * */ public GoldStandardFormat() { super(); } }
deric/clusteval-parent
clusteval-backend/src/main/java/de/clusteval/data/goldstandard/format/GoldStandardFormat.java
Java
gpl-3.0
821
puts "Multiplying string 'abc' for 5 times ('abc' * 5)" puts 'abc' * 5 puts "Compare strings ('x' > 'y')" puts 'x' > 'y' puts "Comparing strings ('y' > 'x')" puts 'y' > 'x'
darshand/beginner-ruby-from-novice-to-professional
chapter_3/string_expressions.rb
Ruby
gpl-3.0
175
namespace BreadPlayer.Core.Models { public class Query { public string QueryWord { get; set; } } }
theweavrs/BreadPlayer
BreadPlayer.Core/Models/Query.cs
C#
gpl-3.0
121
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code 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. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) $Revision: 5122 $ (Revision of last commit) $Date: 2011-12-11 19:47:31 +0000 (Sun, 11 Dec 2011) $ (Date of last commit) $Author: greebo $ (Author of last commit) ******************************************************************************/ #include "../../idlib/precompiled.h" #pragma hdrstop void EditorPrintConsole(const char *msg) { }
Extant-1/ThieVR
sys/stub/util_stub.cpp
C++
gpl-3.0
948
<?php namespace SuperUtils\Image\Driver; /* * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * :: * :: GIFEncoder Version 2.0 by László Zsidi, http://gifs.hu * :: * :: This class is a rewritten 'GifMerge.class.php' version. * :: * :: Modification: * :: - Simplified and easy code, * :: - Ultra fast encoding, * :: - Built-in errors, * :: - Stable working * :: * :: * :: Updated at 2007. 02. 13. '00.05.AM' * :: * :: * :: * :: Try on-line GIFBuilder Form demo based on GIFEncoder. * :: * :: http://gifs.hu/phpclasses/demos/GifBuilder/ * :: * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */ class GIFEncoder { private $GIF = "GIF89a"; /* GIF header 6 bytes */ private $VER = "GIFEncoder V2.05"; /* Encoder version */ private $BUF = []; private $LOP = 0; private $DIS = 2; private $COL = - 1; private $IMG = - 1; private $ERR = [ 'ERR00' => "Does not supported function for only one image!", 'ERR01' => "Source is not a GIF image!", 'ERR02' => "Unintelligible flag ", 'ERR03' => "Does not make animation from animated GIF source" ]; /* * ::::::::::::::::::::::::::::::::::::::::::::::::::: * :: * :: GIFEncoder... * :: */ public function __construct($GIF_src, $GIF_dly, $GIF_lop, $GIF_dis, $GIF_red, $GIF_grn, $GIF_blu, $GIF_mod) { if (! is_array($GIF_src) && ! is_array($GIF_dly)) { printf("%s: %s", $this->VER, $this->ERR['ERR00']); exit(0); } $this->LOP = ($GIF_lop > - 1) ? $GIF_lop : 0; $this->DIS = ($GIF_dis > - 1) ? (($GIF_dis < 3) ? $GIF_dis : 3) : 2; $this->COL = ($GIF_red > - 1 && $GIF_grn > - 1 && $GIF_blu > - 1) ? ($GIF_red | ($GIF_grn << 8) | ($GIF_blu << 16)) : - 1; for($i = 0; $i < count($GIF_src); $i ++) { if (strToLower($GIF_mod) == "url") { $this->BUF[] = fread(fopen($GIF_src[$i], "rb"), filesize($GIF_src[$i])); } else if (strToLower($GIF_mod) == "bin") { $this->BUF[] = $GIF_src[$i]; } else { printf("%s: %s ( %s )!", $this->VER, $this->ERR['ERR02'], $GIF_mod); exit(0); } if (substr($this->BUF[$i], 0, 6) != "GIF87a" && substr($this->BUF[$i], 0, 6) != "GIF89a") { printf("%s: %d %s", $this->VER, $i, $this->ERR['ERR01']); exit(0); } for($j = (13 + 3 * (2 << (ord($this->BUF[$i]{10}) & 0x07))), $k = TRUE; $k; $j ++) { switch ($this->BUF[$i]{$j}) { case "!" : if ((substr($this->BUF[$i], ($j + 3), 8)) == "NETSCAPE") { printf("%s: %s ( %s source )!", $this->VER, $this->ERR['ERR03'], ($i + 1)); exit(0); } break; case ";" : $k = FALSE; break; } } } $this->GIFAddHeader(); for($i = 0; $i < count($this->BUF); $i ++) { $this->GIFAddFrames($i, $GIF_dly[$i]); } $this->GIFAddFooter(); } /* * ::::::::::::::::::::::::::::::::::::::::::::::::::: * :: * :: GIFAddHeader... * :: */ private function GIFAddHeader() { $cmap = 0; if (ord($this->BUF[0]{10}) & 0x80) { $cmap = 3 * (2 << (ord($this->BUF[0]{10}) & 0x07)); $this->GIF .= substr($this->BUF[0], 6, 7); $this->GIF .= substr($this->BUF[0], 13, $cmap); $this->GIF .= "!\377\13NETSCAPE2.0\3\1" . $this->GIFWord($this->LOP) . "\0"; } } /* * ::::::::::::::::::::::::::::::::::::::::::::::::::: * :: * :: GIFAddFrames... * :: */ private function GIFAddFrames($i, $d) { $Locals_str = 13 + 3 * (2 << (ord($this->BUF[$i]{10}) & 0x07)); $Locals_end = strlen($this->BUF[$i]) - $Locals_str - 1; $Locals_tmp = substr($this->BUF[$i], $Locals_str, $Locals_end); $Global_len = 2 << (ord($this->BUF[0]{10}) & 0x07); $Locals_len = 2 << (ord($this->BUF[$i]{10}) & 0x07); $Global_rgb = substr($this->BUF[0], 13, 3 * (2 << (ord($this->BUF[0]{10}) & 0x07))); $Locals_rgb = substr($this->BUF[$i], 13, 3 * (2 << (ord($this->BUF[$i]{10}) & 0x07))); $Locals_ext = "!\xF9\x04" . chr(($this->DIS << 2) + 0) . chr(($d >> 0) & 0xFF) . chr(($d >> 8) & 0xFF) . "\x0\x0"; if ($this->COL > - 1 && ord($this->BUF[$i]{10}) & 0x80) { for($j = 0; $j < (2 << (ord($this->BUF[$i]{10}) & 0x07)); $j ++) { if (ord($Locals_rgb{3 * $j + 0}) == (($this->COL >> 16) & 0xFF) && ord($Locals_rgb{3 * $j + 1}) == (($this->COL >> 8) & 0xFF) && ord($Locals_rgb{3 * $j + 2}) == (($this->COL >> 0) & 0xFF)) { $Locals_ext = "!\xF9\x04" . chr(($this->DIS << 2) + 1) . chr(($d >> 0) & 0xFF) . chr(($d >> 8) & 0xFF) . chr($j) . "\x0"; break; } } } switch ($Locals_tmp{0}) { case "!" : $Locals_img = substr($Locals_tmp, 8, 10); $Locals_tmp = substr($Locals_tmp, 18, strlen($Locals_tmp) - 18); break; case "," : $Locals_img = substr($Locals_tmp, 0, 10); $Locals_tmp = substr($Locals_tmp, 10, strlen($Locals_tmp) - 10); break; } if (ord($this->BUF[$i]{10}) & 0x80 && $this->IMG > - 1) { if ($Global_len == $Locals_len) { if ($this->GIFBlockCompare($Global_rgb, $Locals_rgb, $Global_len)) { $this->GIF .= ($Locals_ext . $Locals_img . $Locals_tmp); } else { $byte = ord($Locals_img{9}); $byte |= 0x80; $byte &= 0xF8; $byte |= (ord($this->BUF[0]{10}) & 0x07); $Locals_img{9} = chr($byte); $this->GIF .= ($Locals_ext . $Locals_img . $Locals_rgb . $Locals_tmp); } } else { $byte = ord($Locals_img{9}); $byte |= 0x80; $byte &= 0xF8; $byte |= (ord($this->BUF[$i]{10}) & 0x07); $Locals_img{9} = chr($byte); $this->GIF .= ($Locals_ext . $Locals_img . $Locals_rgb . $Locals_tmp); } } else { $this->GIF .= ($Locals_ext . $Locals_img . $Locals_tmp); } $this->IMG = 1; } /* * ::::::::::::::::::::::::::::::::::::::::::::::::::: * :: * :: GIFAddFooter... * :: */ private function GIFAddFooter() { $this->GIF .= ";"; } /* * ::::::::::::::::::::::::::::::::::::::::::::::::::: * :: * :: GIFBlockCompare... * :: */ private function GIFBlockCompare($GlobalBlock, $LocalBlock, $Len) { for($i = 0; $i < $Len; $i ++) { if ($GlobalBlock{3 * $i + 0} != $LocalBlock{3 * $i + 0} || $GlobalBlock{3 * $i + 1} != $LocalBlock{3 * $i + 1} || $GlobalBlock{3 * $i + 2} != $LocalBlock{3 * $i + 2}) { return (0); } } return (1); } /* * ::::::::::::::::::::::::::::::::::::::::::::::::::: * :: * :: GIFWord... * :: */ private function GIFWord($int) { return (chr($int & 0xFF) . chr(($int >> 8) & 0xFF)); } /* * ::::::::::::::::::::::::::::::::::::::::::::::::::: * :: * :: GetAnimation... * :: */ public function GetAnimation() { return ($this->GIF); } }
winerQin/SuperUtils
src/Image/Driver/GIFEncoder.php
PHP
gpl-3.0
7,735
package easyrec.poc.client.entity; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="success") @XmlAccessorType(XmlAccessType.FIELD) public class ResponseCode { @XmlAttribute(name="code") private Integer code; @XmlAttribute(name="message") private String message; public Integer getCode() { return code; } public String getMessage() { return message; } }
customertimes/easyrec-PoC
easyrec-client/src/main/java/easyrec/poc/client/entity/ResponseCode.java
Java
gpl-3.0
536
#region License /* Copyright 2014 - 2015 Nikita Bernthaler Summoners.cs is part of SFXKillSteal. SFXKillSteal 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. SFXKillSteal 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 SFXKillSteal. If not, see <http://www.gnu.org/licenses/>. */ #endregion License #region using System; using System.Collections.Generic; using System.Linq; using LeagueSharp; using LeagueSharp.Common; using SFXKillSteal.Library.Extensions.NET; using SFXKillSteal.Library.Logger; using SharpDX; #endregion namespace SFXKillSteal.Data { internal class SummonerSpell { private SpellSlot? _slot; public string Name { get; set; } public float Range { get; set; } public SpellSlot Slot { get { return (SpellSlot) (_slot ?? (_slot = ObjectManager.Player.GetSpellSlot(Name))); } } } internal static class Summoners { public static SummonerSpell BlueSmite; public static SummonerSpell RedSmite; public static SummonerSpell Ignite; public static SummonerSpell Smite; public static List<SummonerSpell> SummonerSpells; static Summoners() { try { // ReSharper disable once StringLiteralTypo BlueSmite = new SummonerSpell { Name = "s5_summonersmiteplayerganker", Range = 750f }; RedSmite = new SummonerSpell { Name = "s5_summonersmiteduel", Range = 750f }; Ignite = new SummonerSpell { Name = "SummonerDot", Range = 600f }; Smite = new SummonerSpell { Name = "SummonerSmite", Range = 750f }; SummonerSpells = new List<SummonerSpell> { Ignite, Smite, BlueSmite, RedSmite }; } catch (Exception ex) { SummonerSpells = new List<SummonerSpell>(); Global.Logger.AddItem(new LogItem(ex)); } } public static bool IsReady(this SummonerSpell spell) { return spell.Slot != SpellSlot.Unknown && spell.Slot.IsReady(); } public static List<SummonerSpell> AvailableSummoners() { return SummonerSpells.Where(ss => ss.Exists()).ToList(); } public static bool Exists(this SummonerSpell spell) { return spell.Slot != SpellSlot.Unknown; } public static void Cast(this SummonerSpell spell) { ObjectManager.Player.Spellbook.CastSpell(spell.Slot); } public static void Cast(this SummonerSpell spell, Obj_AI_Hero target) { ObjectManager.Player.Spellbook.CastSpell(spell.Slot, target); } public static void Cast(this SummonerSpell spell, Vector3 position) { ObjectManager.Player.Spellbook.CastSpell(spell.Slot, position); } public static float CalculateBlueSmiteDamage() { return 20 + ObjectManager.Player.Level * 8; } public static float CalculateRedSmiteDamage() { return 54 + ObjectManager.Player.Level * 6; } public static float CalculateComboDamage(Obj_AI_Hero target, bool ignite, bool smite) { try { var damage = 0f; if (ignite && Ignite.Exists() && Ignite.IsReady() && target.Position.Distance(ObjectManager.Player.Position) <= Ignite.Range) { damage += (float) ObjectManager.Player.GetSummonerSpellDamage(target, Damage.SummonerSpell.Ignite); } if (smite) { if (BlueSmite.Exists() && BlueSmite.IsReady() && target.Position.Distance(ObjectManager.Player.Position) <= BlueSmite.Range) { damage += CalculateBlueSmiteDamage(); } else if (RedSmite.Exists() && RedSmite.IsReady() && target.Position.Distance(ObjectManager.Player.Position) <= RedSmite.Range) { damage += CalculateRedSmiteDamage(); } } return damage; } catch (Exception ex) { Global.Logger.AddItem(new LogItem(ex)); } return 0f; } public static void UseComboSummoners(Obj_AI_Hero target, bool ignite, bool smite) { try { if (ignite && Ignite.Exists() && Ignite.IsReady() && target.Position.Distance(ObjectManager.Player.Position) <= Ignite.Range) { Ignite.Cast(target); } if (smite) { if (BlueSmite.Exists() && BlueSmite.IsReady() && target.Position.Distance(ObjectManager.Player.Position) <= BlueSmite.Range) { BlueSmite.Cast(target); } else if (RedSmite.Exists() && RedSmite.IsReady() && target.Position.Distance(ObjectManager.Player.Position) <= RedSmite.Range) { RedSmite.Cast(target); } } } catch (Exception ex) { Global.Logger.AddItem(new LogItem(ex)); } } public static string FixName(string name) { try { return name.Contains("Smite", StringComparison.OrdinalIgnoreCase) ? "summonersmite" : (name.Contains("Teleport", StringComparison.OrdinalIgnoreCase) ? "summonerteleport" : name.ToLower()); } catch (Exception ex) { Global.Logger.AddItem(new LogItem(ex)); } return name; } } }
Lizzaran/LeagueSharp-Standalones
SFXUtility/SFXKillSteal/Data/Summoners.cs
C#
gpl-3.0
6,544
package com.integreight.onesheeld.shields.controller; import android.app.Activity; import com.integreight.firmatabluetooth.ShieldFrame; import com.integreight.onesheeld.enums.UIShield; import com.integreight.onesheeld.shields.ControllerParent; import com.integreight.onesheeld.utils.Log; public class LcdShield extends ControllerParent<LcdShield> { private LcdEventHandler eventHandler; // private Activity activity; public int rows = 2; public int columns = 16; public char[] chars; public int currIndx = 0; // Method ids private static final byte PRINT = (byte) 0x11; private static final byte BEGIN = (byte) 0x01; private static final byte CLEAR = (byte) 0x02; private static final byte HOME = (byte) 0x03; // private static final byte NO_DISPLAY = (byte) 0x05; // private static final byte DISPLAY = (byte) 0x06; private static final byte NO_BLINK = (byte) 0x04; private static final byte BLINK = (byte) 0x05; private static final byte NO_CURSOR = (byte) 0x06; private static final byte CURSOR = (byte) 0x07; private static final byte SCROLL_DISPLAY_LEFT = (byte) 0x08; private static final byte SCROLL_DISPLAY_RIGHT = (byte) 0x09; private static final byte LEFT_TO_RIGHT = (byte) 0x0A; private static final byte RIGHT_TO_LEFT = (byte) 0x0B; // private static final byte CREATE_CHAR = (byte) 0x0F; private static final byte SET_CURSOR = (byte) 0x0E; private static final byte WRITE = (byte) 0x0F; private static final byte AUTO_SCROLL = (byte) 0x0C; private static final byte NO_AUTO_SCROLL = (byte) 0x0D; public int lastScrollLeft = 0; public boolean isBlinking = false, isCursoring = false; private boolean isAutoScroll = false; private boolean isLeftToRight = true; public LcdShield() { super(); } public LcdShield(Activity activity, String tag) { super(activity, tag); setChars(new char[rows * columns]); } @Override public ControllerParent<LcdShield> init(String tag) { setChars(new char[columns * rows]); return super.init(tag); } public void setLcdEventHandler(LcdEventHandler eventHandler) { this.eventHandler = eventHandler; } public void write(char ch) { if (currIndx > -1 && currIndx < chars.length) { // if (isLeftToRight) { if (!isAutoScroll) { chars[currIndx] = ch; changeCursor(isLeftToRight ? currIndx + 1 : currIndx - 1); } else { final char[] tmp = chars; for (int i = 0; i < currIndx; i++) { if (i + 1 < tmp.length && i + 1 > -1) chars[i] = tmp[i + 1]; } if (currIndx - 1 > -1 && currIndx - 1 < chars.length) chars[currIndx - 1] = ch; } } } public void changeCursor(int indx) { if (!isAutoScroll && indx > -1 && indx < rows * columns) { if (eventHandler != null) { eventHandler.noBlink(); eventHandler.noCursor(); } currIndx = indx; } } public synchronized void scrollDisplayLeft() { lastScrollLeft = 1; char[] tmp = new char[chars.length]; for (int i = 0; i < tmp.length; i++) { if (i + lastScrollLeft > -1 && i + lastScrollLeft < chars.length) { tmp[i] = chars[i + lastScrollLeft]; } } if (eventHandler != null) eventHandler.noBlink(); changeCursor(currIndx - 1); chars = tmp; if (eventHandler != null) { eventHandler.updateLCD(chars); if (isBlinking) eventHandler.blink(); } Log.d("LCD", (">>>>>>> Left " + lastScrollLeft)); } public synchronized void scrollDisplayRight() { lastScrollLeft = -1; char[] tmp = new char[chars.length]; for (int i = 0; i < tmp.length; i++) { if (i + lastScrollLeft > -1 && i + lastScrollLeft < chars.length) { tmp[i] = chars[i + lastScrollLeft]; } } if (eventHandler != null) eventHandler.noBlink(); changeCursor(currIndx + 1); chars = tmp; if (eventHandler != null) { eventHandler.updateLCD(chars); if (isBlinking) eventHandler.blink(); } Log.d("LCD", (">>>>>>> Right " + lastScrollLeft)); } public static interface LcdEventHandler { public void updateLCD(char[] arrayToUpdate); public void blink(); public void noBlink(); public void cursor(); public void noCursor(); } private void processInput(ShieldFrame frame) { switch (frame.getFunctionId()) { case CLEAR: if (eventHandler != null) { eventHandler.noBlink(); eventHandler.noCursor(); } lastScrollLeft = 0; chars = new char[columns * rows]; if (eventHandler != null) eventHandler.updateLCD(chars); changeCursor(0); if (isBlinking && eventHandler != null) eventHandler.blink(); if (isCursoring && eventHandler != null) eventHandler.cursor(); break; case HOME: if (eventHandler != null) eventHandler.noBlink(); if (eventHandler != null) eventHandler.noCursor(); changeCursor(0); if (isBlinking && eventHandler != null) eventHandler.blink(); if (isCursoring && eventHandler != null) eventHandler.cursor(); break; case BLINK: if (eventHandler != null) eventHandler.blink(); isBlinking = true; break; case NO_BLINK: if (eventHandler != null) eventHandler.noBlink(); isBlinking = false; break; case SCROLL_DISPLAY_LEFT: scrollDisplayLeft(); break; case SCROLL_DISPLAY_RIGHT: scrollDisplayRight(); break; case BEGIN: break; case SET_CURSOR: if (eventHandler != null) { eventHandler.noBlink(); eventHandler.noCursor(); } int row = (int) frame.getArgument(0)[0]; int col = (int) frame.getArgument(1)[0]; changeCursor((row * columns) + col); if (isBlinking && eventHandler != null) eventHandler.blink(); if (isCursoring && eventHandler != null) eventHandler.cursor(); break; case WRITE: write(frame.getArgumentAsString(0).charAt(0)); if (eventHandler != null) { eventHandler.updateLCD(chars); if (isBlinking) eventHandler.blink(); if (isCursoring) eventHandler.cursor(); } break; case PRINT: lastScrollLeft = 0; if (eventHandler != null) { eventHandler.noBlink(); eventHandler.noCursor(); } lastScrollLeft = 0; String txt = frame.getArgumentAsString(0); for (int i = 0; i < txt.length(); i++) { write(txt.charAt(i)); } if (eventHandler != null) { eventHandler.updateLCD(chars); if (isBlinking) eventHandler.blink(); if (isCursoring) eventHandler.cursor(); } break; case CURSOR: if (eventHandler != null) eventHandler.cursor(); isCursoring = true; break; case NO_CURSOR: if (eventHandler != null) eventHandler.noCursor(); isCursoring = false; break; case AUTO_SCROLL: isAutoScroll = true; break; case NO_AUTO_SCROLL: isAutoScroll = false; break; case LEFT_TO_RIGHT: isLeftToRight = true; break; case RIGHT_TO_LEFT: isLeftToRight = false; break; default: break; } } @Override public void onNewShieldFrameReceived(ShieldFrame frame) { if (frame.getShieldId() == UIShield.LCD_SHIELD.getId()) processInput(frame); } @Override public void reset() { // TODO Auto-generated method stub } public void setChars(char[] chars) { this.chars = chars; } }
donaldhwong/1Sheeld
oneSheeld/src/main/java/com/integreight/onesheeld/shields/controller/LcdShield.java
Java
gpl-3.0
9,331
Bitrix 16.5 Business Demo = 0a7f69738fccb3e80fcda38b38fdde03
gohdan/DFC
known_files/hashes/bitrix/modules/bizproc/install/components/bitrix/bizproc.wizards.log/templates/.default/lang/en/template.php
PHP
gpl-3.0
61
package com.touchableheroes.drafts.app.sensors; /** * Created by asiebert on 06.12.14. */ public class ISensorListener { }
drdrej/android-drafts-app
app/src/main/java/com/touchableheroes/drafts/app/sensors/ISensorListener.java
Java
gpl-3.0
127
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace BBD.DSP.Models.IEEE11073 { public class DataPacket { public APDU APDU; public byte[] RawData; public DataAPDU Data; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct APDU { public UInt16 Choice; public UInt16 Length; public override string ToString() { return $"0x{((int)Choice).ToString("X4")} ({Length} bytes)"; } } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct DataAPDU { public UInt16 DataLength; public UInt16 InvokeID; public UInt16 Choice; public UInt16 Length; public override string ToString() { return $"0x{((int)Choice).ToString("X4")} ({Length} bytes)"; } } public static class Tools { public enum Endianness { BigEndian, LittleEndian } public static T GetBigEndian<T>(byte[] data) { byte[] dataLE = Tools.MaybeAdjustEndianness(typeof(T), data, Tools.Endianness.BigEndian); GCHandle handle = GCHandle.Alloc(dataLE, GCHandleType.Pinned); T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); return result; } private static byte[] MaybeAdjustEndianness(Type type, byte[] data, Endianness endianness, int startOffset = 0) { if ((BitConverter.IsLittleEndian) == (endianness == Endianness.LittleEndian)) { // nothing to change => return return data; } foreach (var field in type.GetFields()) { var fieldType = field.FieldType; if (field.IsStatic) // don't process static fields continue; if (fieldType == typeof(string)) // don't swap bytes for strings continue; var offset = Marshal.OffsetOf(type, field.Name).ToInt32(); // handle enums if (fieldType.IsEnum) fieldType = Enum.GetUnderlyingType(fieldType); // check for sub-fields to recurse if necessary var subFields = fieldType.GetFields().Where(subField => subField.IsStatic == false).ToArray(); var effectiveOffset = startOffset + offset; if (effectiveOffset >= data.Length) continue; if (subFields.Length == 0) { Array.Reverse(data, effectiveOffset, Marshal.SizeOf(fieldType)); } else { // recurse MaybeAdjustEndianness(fieldType, data, endianness, effectiveOffset); } } return data; } internal static T BytesToStruct<T>(byte[] rawData, Endianness endianness) where T : struct { T result = default(T); MaybeAdjustEndianness(typeof(T), rawData, endianness); GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned); try { IntPtr rawDataPtr = handle.AddrOfPinnedObject(); result = (T)Marshal.PtrToStructure(rawDataPtr, typeof(T)); } finally { handle.Free(); } return result; } internal static byte[] StructToBytes<T>(T data, Endianness endianness) where T : struct { byte[] rawData = new byte[Marshal.SizeOf(data)]; GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned); try { IntPtr rawDataPtr = handle.AddrOfPinnedObject(); Marshal.StructureToPtr(data, rawDataPtr, false); } finally { handle.Free(); } MaybeAdjustEndianness(typeof(T), rawData, endianness); return rawData; } } }
andrasfuchs/BioBalanceDetector
Software/Source/BBDCommon/BBD.DSP/Models/IEEE11073/APDUs.cs
C#
gpl-3.0
4,298
#! /usr/bin/env python # ========================================================================== # This scripts performs unit tests for the csiactobs script # # Copyright (C) 2016-2018 Juergen Knoedlseder # # 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/>. # # ========================================================================== import gammalib import cscripts from testing import test # =============================== # # Test class for csiactobs script # # =============================== # class Test(test): """ Test class for csiactobs script This test class makes unit tests for the csiactobs script by using it from the command line and from Python. """ # Constructor def __init__(self): """ Constructor """ # Call base class constructor test.__init__(self) # Set data members self._datapath = self._datadir + '/iactdata' self._runlist = self._datadir + '/iact_runlist.dat' # Return return # Set test functions def set(self): """ Set all test functions """ # Set test name self.name('csiactobs') # Append tests self.append(self._test_cmd, 'Test csiactobs on command line') self.append(self._test_python, 'Test csiactobs from Python') # Return return # Test csiactobs on command line def _test_cmd(self): """ Test csiactobs on the command line """ # Set script name csiactobs = self._script('csiactobs') # Setup csiactobs command cmd = csiactobs+' datapath="'+self._datapath+'"'+ \ ' prodname="unit-test"'+ \ ' infile="'+self._runlist+'"'+ \ ' bkgpars=1'+\ ' outobs="csiactobs_obs_cmd1.xml"'+ \ ' outmodel="csiactobs_bgd_cmd1.xml"'+ \ ' logfile="csiactobs_cmd1.log" chatter=1' # Check if execution was successful self.test_assert(self._execute(cmd) == 0, 'Check successful execution from command line') # Check observation definition XML file self._check_obsdef('csiactobs_obs_cmd1.xml', 6) # Check model definition XML file self._check_moddef('csiactobs_bgd_cmd1.xml', 6) # Setup csiactobs command cmd = csiactobs+' datapath="data_path_that_does_not_exist"'+ \ ' prodname="unit-test"'+ \ ' infile="'+self._runlist+'"'+ \ ' bkgpars=1'+\ ' outobs="csiactobs_obs_cmd2.xml"'+ \ ' outmodel="csiactobs_bgd_cmd2.xml"'+ \ ' logfile="csiactobs_cmd2.log" debug=yes debug=yes'+ \ ' chatter=1' # Check if execution failed self.test_assert(self._execute(cmd, success=False) != 0, 'Check invalid input datapath when executed from command line') # Setup csiactobs command cmd = csiactobs+' datapath="'+self._datapath+'"'+ \ ' prodname="unit-test-doesnt-exist"'+ \ ' infile="'+self._runlist+'"'+ \ ' bkgpars=1'+\ ' outobs="csiactobs_obs_cmd3.xml"'+ \ ' outmodel="csiactobs_bgd_cmd3.xml"'+ \ ' logfile="csiactobs_cmd3.log" debug=yes debug=yes'+ \ ' chatter=1' # Check if execution failed self.test_assert(self._execute(cmd, success=False) != 0, 'Check invalid input prodname when executed from command line') # Check csiactobs --help self._check_help(csiactobs) # Return return # Test csiactobs from Python def _test_python(self): """ Test csiactobs from Python """ # Allocate empty csiactobs script iactobs = cscripts.csiactobs() # Check that empty csiactobs sciript has an empty observation container # and energy boundaries self.test_value(iactobs.obs().size(), 0, 'Check that empty csiactobs has an empty observation container') self.test_value(iactobs.ebounds().size(), 0, 'Check that empty csiactobs has empty energy bins') # Check that saving saves an empty model definition file iactobs['outobs'] = 'csiactobs_obs_py0.xml' iactobs['outmodel'] = 'csiactobs_bgd_py0.xml' iactobs['logfile'] = 'csiactobs_py0.log' iactobs.logFileOpen() iactobs.save() # Check empty observation definition XML file self._check_obsdef('csiactobs_obs_py0.xml', 0) # Check empty model definition XML file self._check_moddef('csiactobs_bgd_py0.xml', 0) # Check that clearing does not lead to an exception or segfault #iactobs.clear() # Set-up csiactobs iactobs = cscripts.csiactobs() iactobs['datapath'] = self._datapath iactobs['prodname'] = 'unit-test' iactobs['infile'] = self._runlist iactobs['bkgpars'] = 1 iactobs['outobs'] = 'csiactobs_obs_py1.xml' iactobs['outmodel'] = 'csiactobs_bgd_py1.xml' iactobs['logfile'] = 'csiactobs_py1.log' iactobs['chatter'] = 2 # Run csiactobs script and save run list iactobs.logFileOpen() # Make sure we get a log file iactobs.run() iactobs.save() # Check observation definition XML file self._check_obsdef('csiactobs_obs_py1.xml', 6) # Check model definition XML file self._check_moddef('csiactobs_bgd_py1.xml', 6) # Create test runlist runlist = ['15000','15001'] # Set-up csiactobs using a runlist with 2 background parameters iactobs = cscripts.csiactobs() iactobs['datapath'] = self._datapath iactobs['prodname'] = 'unit-test' iactobs['bkgpars'] = 2 iactobs['outobs'] = 'csiactobs_obs_py2.xml' iactobs['outmodel'] = 'csiactobs_bgd_py2.xml' iactobs['logfile'] = 'csiactobs_py2.log' iactobs['chatter'] = 3 iactobs.runlist(runlist) # Run csiactobs script and save run list iactobs.logFileOpen() # Make sure we get a log file iactobs.run() iactobs.save() # Test return functions self.test_value(iactobs.obs().size(), 2, 'Check number of observations in container') self.test_value(iactobs.ebounds().size(), 0, 'Check number of energy boundaries') # Check observation definition XML file self._check_obsdef('csiactobs_obs_py2.xml',2) # Check model definition XML file self._check_moddef('csiactobs_bgd_py2.xml',2) # Set-up csiactobs with a large number of free parameters and "aeff" # background iactobs = cscripts.csiactobs() iactobs['datapath'] = self._datapath iactobs['prodname'] = 'unit-test' iactobs['infile'] = self._runlist iactobs['bkgpars'] = 8 iactobs['bkg_mod_hiera'] = 'aeff' iactobs['outobs'] = 'csiactobs_obs_py3.xml' iactobs['outmodel'] = 'csiactobs_bgd_py3.xml' iactobs['logfile'] = 'csiactobs_py3.log' iactobs['chatter'] = 4 # Execute csiactobs script iactobs.execute() # Check observation definition XML file self._check_obsdef('csiactobs_obs_py3.xml',6) # Check model definition XML file self._check_moddef('csiactobs_bgd_py3.xml',6) # Set-up csiactobs with a "gauss" background and "inmodel" parameter iactobs = cscripts.csiactobs() iactobs['datapath'] = self._datapath iactobs['inmodel'] = self._model iactobs['prodname'] = 'unit-test' iactobs['infile'] = self._runlist iactobs['bkgpars'] = 1 iactobs['bkg_mod_hiera'] = 'gauss' iactobs['outobs'] = 'NONE' iactobs['outmodel'] = 'NONE' iactobs['logfile'] = 'csiactobs_py4.log' iactobs['chatter'] = 4 # Run csiactobs script iactobs.logFileOpen() # Make sure we get a log file iactobs.run() # Check number of observations self.test_value(iactobs.obs().size(), 6, 'Check number of observations in container') # Check number of models self.test_value(iactobs.obs().models().size(), 8, 'Check number of models in container') # Set-up csiactobs with a "gauss" background and "inmodel" parameter iactobs = cscripts.csiactobs() iactobs['datapath'] = self._datapath iactobs['inmodel'] = self._model iactobs['prodname'] = 'unit-test' iactobs['infile'] = self._runlist iactobs['bkgpars'] = 1 iactobs['bkg_mod_hiera'] = 'irf' iactobs['outobs'] = 'NONE' iactobs['outmodel'] = 'NONE' iactobs['logfile'] = 'csiactobs_py4.log' iactobs['chatter'] = 4 # Run csiactobs script iactobs.logFileOpen() # Make sure we get a log file iactobs.run() # Check number of observations self.test_value(iactobs.obs().size(), 5, 'Check number of observations in container') # Check number of models self.test_value(iactobs.obs().models().size(), 7, 'Check number of models in container') # Return return # Check observation definition XML file def _check_obsdef(self, filename, obs_expected): """ Check observation definition XML file """ # Load observation definition XML file obs = gammalib.GObservations(filename) # Check number of observations self.test_value(obs.size(), obs_expected, 'Check for '+str(obs_expected)+' observations in XML file') # If there are observations in the XML file then check their content if obs_expected > 0: # Get response rsp = obs[0].response() # Test response self.test_value(obs[0].eventfile().file(), 'events_0.fits.gz', 'Check event file name') self.test_value(obs[0].eventfile().extname(), 'EVENTS', 'Check event extension name') self.test_value(rsp.aeff().filename().file(), 'irf_file.fits.gz', 'Check effective area file name') self.test_value(rsp.aeff().filename().extname(), 'EFFECTIVE AREA', 'Check effective area extension name') self.test_value(rsp.psf().filename().file(), 'irf_file.fits.gz', 'Check point spread function file name') self.test_value(rsp.psf().filename().extname(), 'POINT SPREAD FUNCTION', 'Check point spread function extension name') self.test_value(rsp.edisp().filename().file(), 'irf_file.fits.gz', 'Check energy dispersion file name') self.test_value(rsp.edisp().filename().extname(), 'ENERGY DISPERSION', 'Check energy dispersion extension name') self.test_value(rsp.background().filename().file(), 'irf_file.fits.gz', 'Check background file name') self.test_value(rsp.background().filename().extname(), 'BACKGROUND', 'Check background extension name') # Return return # Check model XML file def _check_moddef(self, filename, models_expected): """ Check model definition XML file """ # Load model definition XML file models = gammalib.GModels(filename) # Check number of models self.test_value(models.size(), models_expected, 'Check for '+str(models_expected)+' models in XML file') # Return return
ctools/ctools
test/test_csiactobs.py
Python
gpl-3.0
13,064
/******************************************************************* Part of the Fritzing project - http://fritzing.org Copyright (c) 2007-2014 Fachhochschule Potsdam - http://fh-potsdam.de Fritzing 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. Fritzing 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 Fritzing. If not, see <http://www.gnu.org/licenses/>. ******************************************************************** $Revision: 6980 $: $Author: irascibl@gmail.com $: $Date: 2013-04-22 01:45:43 +0200 (Mo, 22. Apr 2013) $ ********************************************************************/ #include "note.h" #include "../debugdialog.h" #include "../sketch/infographicsview.h" #include "../model/modelpart.h" #include "../utils/resizehandle.h" #include "../utils/textutils.h" #include "../utils/graphicsutils.h" #include "../fsvgrenderer.h" #include <QTextFrame> #include <QTextLayout> #include <QTextFrameFormat> #include <QApplication> #include <QTextDocumentFragment> #include <QTimer> #include <QFormLayout> #include <QGroupBox> #include <QLineEdit> #include <QDialogButtonBox> #include <QPushButton> // TODO: // ** search for ModelPart:: and fix up // check which menu items don't apply // ** selection // ** delete // ** move // ** undo delete + text // ** resize // ** undo resize // anchor // ** undo change text // ** undo selection // ** undo move // ** layers and z order // ** hide and show layer // ** save and load // format: bold, italic, size (small normal large huge), color?, // undo format // heads-up controls // copy/paste // ** z-order manipulation // hover // ** multiple selection // ** icon in taskbar (why does it show up as text until you update it?) const int Note::emptyMinWidth = 40; const int Note::emptyMinHeight = 25; const int Note::initialMinWidth = 140; const int Note::initialMinHeight = 45; const int borderWidth = 7; const int TriangleOffset = 7; const double InactiveOpacity = 0.5; QString Note::initialTextString; QRegExp UrlTag("<a.*href=[\"']([^\"]+[.\\s]*)[\"'].*>"); /////////////////////////////////////// void findA(QDomElement element, QList<QDomElement> & aElements) { if (element.tagName().compare("a", Qt::CaseInsensitive) == 0) { aElements.append(element); return; } QDomElement c = element.firstChildElement(); while (!c.isNull()) { findA(c, aElements); c = c.nextSiblingElement(); } } QString addText(const QString & text, bool inUrl) { if (text.isEmpty()) return ""; return QString("<tspan fill='%1' >%2</tspan>\n") .arg(inUrl ? "#0000ff" : "#000000") .arg(TextUtils::convertExtendedChars(TextUtils::escapeAnd(text))) ; } /////////////////////////////////////// class NoteGraphicsTextItem : public QGraphicsTextItem { public: NoteGraphicsTextItem(QGraphicsItem * parent = NULL); protected: void focusInEvent(QFocusEvent *); void focusOutEvent(QFocusEvent *); }; NoteGraphicsTextItem::NoteGraphicsTextItem(QGraphicsItem * parent) : QGraphicsTextItem(parent) { const QTextFrameFormat format = document()->rootFrame()->frameFormat(); QTextFrameFormat altFormat(format); altFormat.setMargin(0); // so document never thinks a mouse click is a move event document()->rootFrame()->setFrameFormat(altFormat); } void NoteGraphicsTextItem::focusInEvent(QFocusEvent * event) { InfoGraphicsView * igv = InfoGraphicsView::getInfoGraphicsView(this); if (igv != NULL) { igv->setNoteFocus(this, true); } QApplication::instance()->installEventFilter((Note *) this->parentItem()); QGraphicsTextItem::focusInEvent(event); DebugDialog::debug("note focus in"); } void NoteGraphicsTextItem::focusOutEvent(QFocusEvent * event) { InfoGraphicsView * igv = InfoGraphicsView::getInfoGraphicsView(this); if (igv != NULL) { igv->setNoteFocus(this, false); } QApplication::instance()->removeEventFilter((Note *) this->parentItem()); QGraphicsTextItem::focusOutEvent(event); DebugDialog::debug("note focus out"); } ////////////////////////////////////////// LinkDialog::LinkDialog(QWidget *parent) : QDialog(parent) { this->setWindowTitle(QObject::tr("Edit link")); QVBoxLayout * vLayout = new QVBoxLayout(this); QGroupBox * formGroupBox = new QGroupBox(this); QFormLayout * formLayout = new QFormLayout(); m_urlEdit = new QLineEdit(this); m_urlEdit->setFixedHeight(25); m_urlEdit->setFixedWidth(200); formLayout->addRow(tr("url:"), m_urlEdit ); m_textEdit = new QLineEdit(this); m_textEdit->setFixedHeight(25); m_textEdit->setFixedWidth(200); formLayout->addRow(tr("text:"), m_textEdit ); formGroupBox->setLayout(formLayout); vLayout->addWidget(formGroupBox); QDialogButtonBox * buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); vLayout->addWidget(buttonBox); this->setLayout(vLayout); } LinkDialog::~LinkDialog() { } void LinkDialog::setText(const QString & text) { m_textEdit->setText(text); } void LinkDialog::setUrl(const QString & url) { m_urlEdit->setText(url); } QString LinkDialog::text() { return m_textEdit->text(); } QString LinkDialog::url() { return m_urlEdit->text(); } ///////////////////////////////////////////// Note::Note( ModelPart * modelPart, ViewLayer::ViewID viewID, const ViewGeometry & viewGeometry, long id, QMenu* itemMenu) : ItemBase(modelPart, viewID, viewGeometry, id, itemMenu) { m_charsAdded = 0; if (initialTextString.isEmpty()) { initialTextString = tr("[write your note here]"); } m_inResize = NULL; this->setCursor(Qt::ArrowCursor); setFlag(QGraphicsItem::ItemIsSelectable, true); if (viewGeometry.rect().width() == 0 || viewGeometry.rect().height() == 0) { m_rect.setRect(0, 0, Note::initialMinWidth, Note::initialMinHeight); } else { m_rect.setRect(0, 0, viewGeometry.rect().width(), viewGeometry.rect().height()); } m_pen.setWidth(borderWidth); m_pen.setCosmetic(false); m_pen.setBrush(QColor(0xfa, 0xbc, 0x4f)); m_brush.setColor(QColor(0xff, 0xe9, 0xc8)); m_brush.setStyle(Qt::SolidPattern); setPos(m_viewGeometry.loc()); QPixmap pixmap(":/resources/images/icons/noteResizeGrip.png"); m_resizeGrip = new ResizeHandle(pixmap, Qt::SizeFDiagCursor, false, this); connect(m_resizeGrip, SIGNAL(mousePressSignal(QGraphicsSceneMouseEvent *, ResizeHandle *)), this, SLOT(handleMousePressSlot(QGraphicsSceneMouseEvent *, ResizeHandle *))); connect(m_resizeGrip, SIGNAL(mouseMoveSignal(QGraphicsSceneMouseEvent *, ResizeHandle *)), this, SLOT(handleMouseMoveSlot(QGraphicsSceneMouseEvent *, ResizeHandle *))); connect(m_resizeGrip, SIGNAL(mouseReleaseSignal(QGraphicsSceneMouseEvent *, ResizeHandle *)), this, SLOT(handleMouseReleaseSlot(QGraphicsSceneMouseEvent *, ResizeHandle *))); //connect(m_resizeGrip, SIGNAL(zoomChangedSignal(double)), this, SLOT(handleZoomChangedSlot(double))); m_graphicsTextItem = new NoteGraphicsTextItem(); QFont font("Droid Sans", 9, QFont::Normal); m_graphicsTextItem->setFont(font); m_graphicsTextItem->document()->setDefaultFont(font); m_graphicsTextItem->setParentItem(this); m_graphicsTextItem->setVisible(true); m_graphicsTextItem->setPlainText(initialTextString); m_graphicsTextItem->setTextInteractionFlags(Qt::TextEditorInteraction | Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); m_graphicsTextItem->setCursor(Qt::IBeamCursor); m_graphicsTextItem->setOpenExternalLinks(true); connectSlots(); positionGrip(); setAcceptHoverEvents(true); } void Note::saveGeometry() { m_viewGeometry.setRect(boundingRect()); m_viewGeometry.setLoc(this->pos()); m_viewGeometry.setSelected(this->isSelected()); m_viewGeometry.setZ(this->zValue()); } bool Note::itemMoved() { return (this->pos() != m_viewGeometry.loc()); } void Note::saveInstanceLocation(QXmlStreamWriter & streamWriter) { QRectF rect = m_viewGeometry.rect(); QPointF loc = m_viewGeometry.loc(); streamWriter.writeAttribute("x", QString::number(loc.x())); streamWriter.writeAttribute("y", QString::number(loc.y())); streamWriter.writeAttribute("width", QString::number(rect.width())); streamWriter.writeAttribute("height", QString::number(rect.height())); } void Note::moveItem(ViewGeometry & viewGeometry) { this->setPos(viewGeometry.loc()); } void Note::findConnectorsUnder() { } void Note::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); if (m_hidden) return; if (m_inactive) { painter->save(); painter->setOpacity(InactiveOpacity); } painter->setPen(Qt::NoPen); painter->setBrush(m_brush); QPolygonF poly; poly.append(m_rect.topLeft()); poly.append(m_rect.topRight() + QPointF(-TriangleOffset, 0)); poly.append(m_rect.topRight() + QPointF(0, TriangleOffset)); poly.append(m_rect.bottomRight()); poly.append(m_rect.bottomLeft()); painter->drawPolygon(poly); painter->setBrush(m_pen.brush()); poly.clear(); poly.append(m_rect.topRight() + QPointF(-TriangleOffset, 0)); poly.append(m_rect.topRight() + QPointF(0, TriangleOffset)); poly.append(m_rect.topRight() + QPointF(-TriangleOffset, TriangleOffset)); painter->drawPolygon(poly); painter->setPen(m_pen); poly.clear(); poly.append(QPointF(0, m_rect.bottom() - borderWidth / 2.0)); poly.append(QPointF(m_rect.right(), m_rect.bottom() - borderWidth / 2.0)); painter->drawPolygon(poly); if (option->state & QStyle::State_Selected) { GraphicsUtils::qt_graphicsItem_highlightSelected(painter, option, boundingRect(), QPainterPath()); } if (m_inactive) { painter->restore(); } } QRectF Note::boundingRect() const { return m_rect; } QPainterPath Note::shape() const { QPainterPath path; path.addRect(boundingRect()); return path; } void Note::positionGrip() { QSizeF gripSize = m_resizeGrip->boundingRect().size(); QSizeF sz = this->boundingRect().size(); QPointF p(sz.width() - gripSize.width(), sz.height() - gripSize.height()); m_resizeGrip->setPos(p); m_graphicsTextItem->setPos(TriangleOffset / 2, TriangleOffset / 2); m_graphicsTextItem->setTextWidth(sz.width() - TriangleOffset); } void Note::mousePressEvent(QGraphicsSceneMouseEvent * event) { InfoGraphicsView *infographics = InfoGraphicsView::getInfoGraphicsView(this); if (infographics != NULL && infographics->spaceBarIsPressed()) { m_spaceBarWasPressed = true; event->ignore(); return; } m_spaceBarWasPressed = false; m_inResize = NULL; ItemBase::mousePressEvent(event); } void Note::mouseMoveEvent(QGraphicsSceneMouseEvent * event) { if (m_spaceBarWasPressed) { event->ignore(); return; } ItemBase::mouseMoveEvent(event); } void Note::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { if (m_spaceBarWasPressed) { event->ignore(); return; } ItemBase::mouseReleaseEvent(event); } void Note::contentsChangeSlot(int position, int charsRemoved, int charsAdded) { Q_UNUSED(charsRemoved); m_charsAdded = charsAdded; m_charsPosition = position; } void Note::forceFormat(int position, int charsAdded) { disconnectSlots(); QTextCursor textCursor = m_graphicsTextItem->textCursor(); QTextCharFormat f; QFont font("Droid Sans", 9, QFont::Normal); f.setFont(font); f.setFontFamily("Droid Sans"); f.setFontPointSize(9); int cc = m_graphicsTextItem->document()->characterCount(); textCursor.setPosition(position, QTextCursor::MoveAnchor); if (position + charsAdded >= cc) { charsAdded--; } textCursor.setPosition(position + charsAdded, QTextCursor::KeepAnchor); //textCursor.setCharFormat(f); textCursor.mergeCharFormat(f); //DebugDialog::debug(QString("setting font tc:%1,%2 params:%3,%4") //.arg(textCursor.anchor()).arg(textCursor.position()) //.arg(position).arg(position + charsAdded)); /* textCursor = m_graphicsTextItem->textCursor(); for (int i = 0; i < charsAdded; i++) { textCursor.setPosition(position + i, QTextCursor::MoveAnchor); f = textCursor.charFormat(); DebugDialog::debug(QString("1format %1 %2 %3").arg(f.fontPointSize()).arg(f.fontFamily()).arg(f.fontWeight())); //f.setFont(font); //f.setFontPointSize(9); //f.setFontWeight(QFont::Normal); //textCursor.setCharFormat(f); //QTextCharFormat g = textCursor.charFormat(); //DebugDialog::debug(QString("2format %1 %2 %3").arg(g.fontPointSize()).arg(g.fontFamily()).arg(g.fontWeight())); } */ connectSlots(); } void Note::contentsChangedSlot() { //DebugDialog::debug(QString("contents changed ") + m_graphicsTextItem->document()->toPlainText()); if (m_charsAdded > 0) { forceFormat(m_charsPosition, m_charsAdded); } InfoGraphicsView *infoGraphicsView = InfoGraphicsView::getInfoGraphicsView(this); if (infoGraphicsView != NULL) { QString oldText; if (m_modelPart) { oldText = m_modelPart->instanceText(); } QSizeF oldSize = m_rect.size(); QSizeF newSize = oldSize; checkSize(newSize); infoGraphicsView->noteChanged(this, oldText, m_graphicsTextItem->document()->toHtml(), oldSize, newSize); } if (m_modelPart) { m_modelPart->setInstanceText(m_graphicsTextItem->document()->toHtml()); } } void Note::checkSize(QSizeF & newSize) { QSizeF gripSize = m_resizeGrip->boundingRect().size(); QSizeF size = m_graphicsTextItem->document()->size(); if (size.height() + gripSize.height() + gripSize.height() > m_rect.height()) { prepareGeometryChange(); m_rect.setHeight(size.height() + gripSize.height() + gripSize.height()); newSize.setHeight(m_rect.height()); positionGrip(); this->update(); } } void Note::disconnectSlots() { disconnect(m_graphicsTextItem->document(), SIGNAL(contentsChanged()), this, SLOT(contentsChangedSlot())); disconnect(m_graphicsTextItem->document(), SIGNAL(contentsChange(int, int, int)), this, SLOT(contentsChangeSlot(int, int, int))); } void Note::connectSlots() { connect(m_graphicsTextItem->document(), SIGNAL(contentsChanged()), this, SLOT(contentsChangedSlot()), Qt::DirectConnection); connect(m_graphicsTextItem->document(), SIGNAL(contentsChange(int, int, int)), this, SLOT(contentsChangeSlot(int, int, int)), Qt::DirectConnection); } void Note::setText(const QString & text, bool check) { // disconnect the signal so it doesn't fire recursively disconnectSlots(); QString oldText = text; m_graphicsTextItem->document()->setHtml(text); connectSlots(); if (check) { QSizeF newSize; checkSize(newSize); forceFormat(0, m_graphicsTextItem->document()->characterCount()); } } QString Note::text() { return m_graphicsTextItem->document()->toHtml(); } void Note::setSize(const QSizeF & size) { prepareGeometryChange(); m_rect.setWidth(size.width()); m_rect.setHeight(size.height()); positionGrip(); } void Note::setHidden(bool hide) { ItemBase::setHidden(hide); m_graphicsTextItem->setVisible(!hide); m_resizeGrip->setVisible(!hide); } void Note::setInactive(bool inactivate) { ItemBase::setInactive(inactivate); } bool Note::eventFilter(QObject * object, QEvent * event) { if (event->type() == QEvent::Shortcut || event->type() == QEvent::ShortcutOverride) { if (!object->inherits("QGraphicsView")) { event->accept(); return true; } } if (event->type() == QEvent::KeyPress) { QKeyEvent * kevent = static_cast<QKeyEvent *>(event); if (kevent->matches(QKeySequence::Bold)) { QTextCursor textCursor = m_graphicsTextItem->textCursor(); QTextCharFormat cf = textCursor.charFormat(); bool isBold = cf.fontWeight() == QFont::Bold; QTextCharFormat textCharFormat; textCharFormat.setFontWeight(isBold ? QFont::Normal : QFont::Bold); textCursor.mergeCharFormat(textCharFormat); event->accept(); return true; } if (kevent->matches(QKeySequence::Italic)) { QTextCursor textCursor = m_graphicsTextItem->textCursor(); QTextCharFormat cf = textCursor.charFormat(); QTextCharFormat textCharFormat; textCharFormat.setFontItalic(!cf.fontItalic()); textCursor.mergeCharFormat(textCharFormat); event->accept(); return true; } if ((kevent->key() == Qt::Key_L) && (kevent->modifiers() & Qt::ControlModifier)) { QTimer::singleShot(75, this, SLOT(linkDialog())); event->accept(); return true; } } return false; } void Note::linkDialog() { QTextCursor textCursor = m_graphicsTextItem->textCursor(); bool gotUrl = false; if (textCursor.anchor() == textCursor.selectionStart()) { // the selection returns empty since we're between characters // so select one character forward or one character backward // to see whether we're in a url int wasAnchor = textCursor.anchor(); bool atEnd = textCursor.atEnd(); bool atStart = textCursor.atStart(); if (!atStart) { textCursor.setPosition(wasAnchor - 1, QTextCursor::KeepAnchor); QString html = textCursor.selection().toHtml(); if (UrlTag.indexIn(html) >= 0) { gotUrl = true; } } if (!gotUrl && !atEnd) { textCursor.setPosition(wasAnchor + 1, QTextCursor::KeepAnchor); QString html = textCursor.selection().toHtml(); if (UrlTag.indexIn(html) >= 0) { gotUrl = true; } } textCursor.setPosition(wasAnchor, QTextCursor::MoveAnchor); } else { QString html = textCursor.selection().toHtml(); DebugDialog::debug(html); if (UrlTag.indexIn(html) >= 0) { gotUrl = true; } } LinkDialog ld; QString originalText; QString originalUrl; if (gotUrl) { originalUrl = UrlTag.cap(1); ld.setUrl(originalUrl); QString html = m_graphicsTextItem->toHtml(); // assumes html is in xml form QString errorStr; int errorLine; int errorColumn; QDomDocument domDocument; if (!domDocument.setContent(html, &errorStr, &errorLine, &errorColumn)) { return; } QDomElement root = domDocument.documentElement(); if (root.isNull()) { return; } if (root.tagName() != "html") { return; } DebugDialog::debug(html); QList<QDomElement> aElements; findA(root, aElements); foreach (QDomElement a, aElements) { // TODO: if multiple hrefs point to the same url this will only find the first one QString href = a.attribute("href"); if (href.isEmpty()) { href = a.attribute("HREF"); } if (href.compare(originalUrl) == 0) { QString text; if (TextUtils::findText(a, text)) { ld.setText(text); break; } else { return; } } } } int result = ld.exec(); if (result == QDialog::Accepted) { if (gotUrl) { int from = 0; while (true) { QTextCursor cursor = m_graphicsTextItem->document()->find(originalText, from); if (cursor.isNull()) { // TODO: tell the user return; } QString html = cursor.selection().toHtml(); if (html.contains(originalUrl)) { cursor.insertHtml(QString("<a href=\"%1\">%2</a>").arg(ld.url()).arg(ld.text())); break; } from = cursor.selectionEnd(); } } else { textCursor.insertHtml(QString("<a href=\"%1\">%2</a>").arg(ld.url()).arg(ld.text())); } } } void Note::handleZoomChangedSlot(double scale) { Q_UNUSED(scale); positionGrip(); } void Note::handleMousePressSlot(QGraphicsSceneMouseEvent * event, ResizeHandle * resizeHandle) { if (m_spaceBarWasPressed) return; saveGeometry(); QSizeF sz = this->boundingRect().size(); resizeHandle->setResizeOffset(this->pos() + QPointF(sz.width(), sz.height()) - event->scenePos()); m_inResize = resizeHandle; } void Note::handleMouseMoveSlot(QGraphicsSceneMouseEvent * event, ResizeHandle * resizeHandle) { Q_UNUSED(resizeHandle); if (!m_inResize) return; double minWidth = emptyMinWidth; double minHeight = emptyMinHeight; QSizeF gripSize = m_resizeGrip->boundingRect().size(); QSizeF minSize = m_graphicsTextItem->document()->size() + gripSize + gripSize; if (minSize.height() > minHeight) minHeight = minSize.height(); QRectF rect = boundingRect(); rect.moveTopLeft(this->pos()); double oldX1 = rect.x(); double oldY1 = rect.y(); double newX = event->scenePos().x() + m_inResize->resizeOffset().x(); double newY = event->scenePos().y() + m_inResize->resizeOffset().y(); QRectF newR; if (newX - oldX1 < minWidth) { newX = oldX1 + minWidth; } if (newY - oldY1 < minHeight) { newY = oldY1 + minHeight; } newR.setRect(0, 0, newX - oldX1, newY - oldY1); prepareGeometryChange(); m_rect = newR; positionGrip(); } void Note::handleMouseReleaseSlot(QGraphicsSceneMouseEvent * event, ResizeHandle * resizeHandle) { Q_UNUSED(resizeHandle); Q_UNUSED(event); if (!m_inResize) return; m_inResize = NULL; InfoGraphicsView *infoGraphicsView = InfoGraphicsView::getInfoGraphicsView(this); if (infoGraphicsView != NULL) { infoGraphicsView->noteSizeChanged(this, m_viewGeometry.rect().size(), m_rect.size()); } } bool Note::hasPartLabel() { return false; } bool Note::stickyEnabled() { return false; } bool Note::hasPartNumberProperty() { return false; } bool Note::rotationAllowed() { return false; } bool Note::rotation45Allowed() { return false; } QString Note::retrieveSvg(ViewLayer::ViewLayerID viewLayerID, QHash<QString, QString> & svgHash, bool blackOnly, double dpi, double & factor) { Q_UNUSED(svgHash); factor = 1; switch (viewLayerID) { case ViewLayer::BreadboardNote: if (viewID() != ViewLayer::BreadboardView) return ""; break; case ViewLayer::PcbNote: if (viewID() != ViewLayer::PCBView) return ""; break; case ViewLayer::SchematicNote: if (viewID() != ViewLayer::SchematicView) return ""; break; default: return ""; } QString svg = "<g>"; QString penColor = blackOnly ? "#000000" : m_pen.color().name(); double penWidth = m_pen.widthF() * dpi / GraphicsUtils::SVGDPI; QString brushColor = blackOnly ? "none" : m_brush.color().name(); svg += QString("<rect x='%1' y='%2' width='%3' height='%4' fill='%5' stroke='%6' stroke-width='%7' />") .arg(penWidth / 2) .arg(penWidth / 2) .arg((m_rect.width() * dpi / GraphicsUtils::SVGDPI) - penWidth) .arg((m_rect.height() * dpi / GraphicsUtils::SVGDPI) - penWidth) .arg(brushColor) .arg(penColor) .arg(penWidth) ; QTextCursor textCursor = m_graphicsTextItem->textCursor(); QSizeF gripSize = m_resizeGrip->boundingRect().size(); double docLeft = gripSize.width(); double docTop = gripSize.height(); for (QTextBlock block = m_graphicsTextItem->document()->begin(); block.isValid(); block = block.next()) { QTextLayout * layout = block.layout(); double left = block.blockFormat().leftMargin() + docLeft + layout->position().x(); double top = block.blockFormat().topMargin() + docTop + layout->position().y(); for (int i = 0; i < layout->lineCount(); i++) { QTextLine line = layout->lineAt(i); QRectF r = line.rect(); int start = line.textStart(); int count = line.textLength(); QString soFar; svg += QString("<text x='%1' y='%2' font-family='%3' stroke='none' fill='#000000' text-anchor='left' font-size='%4' >\n") .arg((left + r.left()) * dpi / GraphicsUtils::SVGDPI) .arg((top + r.top() + line.ascent()) * dpi / GraphicsUtils::SVGDPI) .arg("Droid Sans") .arg(line.ascent() * dpi / GraphicsUtils::SVGDPI) ; bool inUrl = false; for (int i = 0; i < count; i++) { textCursor.setPosition(i + start + block.position(), QTextCursor::MoveAnchor); textCursor.setPosition(i + start + block.position() + 1, QTextCursor::KeepAnchor); QString html = textCursor.selection().toHtml(); if (UrlTag.indexIn(html) >= 0) { if (inUrl) { soFar += block.text().mid(start + i, 1); continue; } svg += addText(soFar, false); soFar = block.text().mid(start + i, 1); inUrl = true; } else { if (!inUrl) { soFar += block.text().mid(start + i, 1); continue; } svg += addText(soFar, !blackOnly); soFar = block.text().mid(start + i, 1); inUrl = false; } } svg += addText(soFar, inUrl && !blackOnly); svg += "</text>"; } } svg += "</g>"; return svg; } ViewLayer::ViewID Note::useViewIDForPixmap(ViewLayer::ViewID, bool) { return ViewLayer::IconView; } void Note::addedToScene(bool temporary) { positionGrip(); return ItemBase::addedToScene(temporary); }
sirdel/fritzing
src/items/note.cpp
C++
gpl-3.0
24,662
/*! * jQuery UI Effects Transfer 1.10.1 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/transfer-effect/ * * Depends: * jquery.ui.effect.js */ (function( $, undefined ) { $.effects.effect.transfer = function( o, done ) { var elem = $( this ), target = $( o.to ), targetFixed = target.css( "position" ) === "fixed", body = $("body"), fixTop = targetFixed ? body.scrollTop() : 0, fixLeft = targetFixed ? body.scrollLeft() : 0, endPosition = target.offset(), animation = { top: endPosition.top - fixTop , left: endPosition.left - fixLeft , height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $( "<div class='ui-effects-transfer'></div>" ) .appendTo( document.body ) .addClass( o.className ) .css({ top: startPosition.top - fixTop , left: startPosition.left - fixLeft , height: elem.innerHeight(), width: elem.innerWidth(), position: targetFixed ? "fixed" : "absolute" }) .animate( animation, o.duration, o.easing, function() { transfer.remove(); done(); }); }; })(jQuery);
Tinchosan/wingpanel
admin/js/jquery-ui/development-bundle/ui/jquery.ui.effect-transfer.js
JavaScript
gpl-3.0
1,284
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code 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. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../../idlib/precompiled.h" #include "../../sound/snd_local.h" #include "../posix/posix_public.h" #include "sound.h" #include <dlfcn.h> static idCVar s_alsa_pcm( "s_alsa_pcm", "default", CVAR_SYSTEM | CVAR_ARCHIVE, "which alsa pcm device to use. default, hwplug, hw.. see alsa docs" ); static idCVar s_alsa_lib( "s_alsa_lib", "libasound.so.2", CVAR_SYSTEM | CVAR_ARCHIVE, "alsa client sound library" ); /* =============== idAudioHardwareALSA::DLOpen =============== */ bool idAudioHardwareALSA::DLOpen() { const char* version; if( m_handle ) { return true; } common->Printf( "dlopen(%s)\n", s_alsa_lib.GetString() ); if( !( m_handle = dlopen( s_alsa_lib.GetString(), RTLD_NOW | RTLD_GLOBAL ) ) ) { common->Printf( "dlopen(%s) failed: %s\n", s_alsa_lib.GetString(), dlerror() ); return false; } // print the version if available id_snd_asoundlib_version = ( pfn_snd_asoundlib_version )dlsym( m_handle, "snd_asoundlib_version" ); if( !id_snd_asoundlib_version ) { common->Printf( "dlsym(\"snd_asoundlib_version\") failed: %s\n", dlerror() ); common->Warning( "please consider upgrading alsa to a more recent version." ); } else { version = id_snd_asoundlib_version(); common->Printf( "asoundlib version: %s\n", version ); } // dlsym the symbols ALSA_DLSYM( snd_pcm_avail_update ); ALSA_DLSYM( snd_pcm_close ); ALSA_DLSYM( snd_pcm_hw_params ); ALSA_DLSYM( snd_pcm_hw_params_any ); ALSA_DLSYM( snd_pcm_hw_params_get_buffer_size ); ALSA_DLSYM( snd_pcm_hw_params_set_access ); ALSA_DLSYM( snd_pcm_hw_params_set_buffer_size_min ); ALSA_DLSYM( snd_pcm_hw_params_set_channels ); ALSA_DLSYM( snd_pcm_hw_params_set_format ); ALSA_DLSYM( snd_pcm_hw_params_set_rate ); ALSA_DLSYM( snd_pcm_hw_params_sizeof ); ALSA_DLSYM( snd_pcm_open ); ALSA_DLSYM( snd_pcm_prepare ); ALSA_DLSYM( snd_pcm_state ); ALSA_DLSYM( snd_pcm_writei ); ALSA_DLSYM( snd_strerror ); return true; } /* =============== idAudioHardwareALSA::Release =============== */ void idAudioHardwareALSA::Release() { if( m_pcm_handle ) { common->Printf( "close pcm\n" ); id_snd_pcm_close( m_pcm_handle ); m_pcm_handle = NULL; } if( m_buffer ) { free( m_buffer ); m_buffer = NULL; } if( m_handle ) { common->Printf( "dlclose\n" ); dlclose( m_handle ); m_handle = NULL; } } /* ================= idAudioHardwareALSA::InitFailed ================= */ void idAudioHardwareALSA::InitFailed() { Release(); cvarSystem->SetCVarBool( "s_noSound", true ); common->Warning( "sound subsystem disabled\n" ); common->Printf( "--------------------------------------\n" ); } /* ===================== idAudioHardwareALSA::Initialize ===================== */ bool idAudioHardwareALSA::Initialize() { int err; common->Printf( "------ Alsa Sound Initialization -----\n" ); if( !DLOpen() ) { InitFailed(); return false; } if( ( err = id_snd_pcm_open( &m_pcm_handle, s_alsa_pcm.GetString(), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK ) ) < 0 ) { common->Printf( "snd_pcm_open SND_PCM_STREAM_PLAYBACK '%s' failed: %s\n", s_alsa_pcm.GetString(), id_snd_strerror( err ) ); InitFailed(); return false; } common->Printf( "opened Alsa PCM device %s for playback\n", s_alsa_pcm.GetString() ); // set hardware parameters ---------------------------------------------------------------------- // init hwparams with the full configuration space snd_pcm_hw_params_t* hwparams; // this one is a define id_snd_pcm_hw_params_alloca( &hwparams ); if( ( err = id_snd_pcm_hw_params_any( m_pcm_handle, hwparams ) ) < 0 ) { common->Printf( "cannot configure the PCM device: %s\n", id_snd_strerror( err ) ); InitFailed(); return false; } if( ( err = id_snd_pcm_hw_params_set_access( m_pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED ) ) < 0 ) { common->Printf( "SND_PCM_ACCESS_RW_INTERLEAVED failed: %s\n", id_snd_strerror( err ) ); InitFailed(); return false; } if( ( err = id_snd_pcm_hw_params_set_format( m_pcm_handle, hwparams, SND_PCM_FORMAT_S16_LE ) ) < 0 ) { common->Printf( "SND_PCM_FORMAT_S16_LE failed: %s\n", id_snd_strerror( err ) ); InitFailed(); return false; } // channels // sanity over number of speakers if( idSoundSystemLocal::s_numberOfSpeakers.GetInteger() != 6 && idSoundSystemLocal::s_numberOfSpeakers.GetInteger() != 2 ) { common->Warning( "invalid value for s_numberOfSpeakers. Use either 2 or 6" ); idSoundSystemLocal::s_numberOfSpeakers.SetInteger( 2 ); } m_channels = idSoundSystemLocal::s_numberOfSpeakers.GetInteger(); if( ( err = id_snd_pcm_hw_params_set_channels( m_pcm_handle, hwparams, m_channels ) ) < 0 ) { common->Printf( "error setting %d channels: %s\n", m_channels, id_snd_strerror( err ) ); if( idSoundSystemLocal::s_numberOfSpeakers.GetInteger() != 2 ) { // fallback to stereo if that works m_channels = 2; if( ( err = id_snd_pcm_hw_params_set_channels( m_pcm_handle, hwparams, m_channels ) ) < 0 ) { common->Printf( "fallback to stereo failed: %s\n", id_snd_strerror( err ) ); InitFailed(); return false; } else { common->Printf( "fallback to stereo\n" ); idSoundSystemLocal::s_numberOfSpeakers.SetInteger( 2 ); } } else { InitFailed(); return false; } } // set sample rate (frequency) if( ( err = id_snd_pcm_hw_params_set_rate( m_pcm_handle, hwparams, PRIMARYFREQ, 0 ) ) < 0 ) { common->Printf( "failed to set 44.1KHz rate: %s - try ( +set s_alsa_pcm plughw:0 ? )\n", id_snd_strerror( err ) ); InitFailed(); return false; } // have enough space in the input buffer for our MIXBUFFER_SAMPLE feedings and async ticks snd_pcm_uframes_t frames; frames = MIXBUFFER_SAMPLES + MIXBUFFER_SAMPLES / 3; if( ( err = id_snd_pcm_hw_params_set_buffer_size_min( m_pcm_handle, hwparams, &frames ) ) < 0 ) { common->Printf( "buffer size select failed: %s\n", id_snd_strerror( err ) ); InitFailed(); return false; } // apply parameters if( ( err = id_snd_pcm_hw_params( m_pcm_handle, hwparams ) ) < 0 ) { common->Printf( "snd_pcm_hw_params failed: %s\n", id_snd_strerror( err ) ); InitFailed(); return false; } // check the buffer size if( ( err = id_snd_pcm_hw_params_get_buffer_size( hwparams, &frames ) ) < 0 ) { common->Printf( "snd_pcm_hw_params_get_buffer_size failed: %s\n", id_snd_strerror( err ) ); } else { common->Printf( "device buffer size: %lu frames ( %lu bytes )\n", ( long unsigned int )frames, frames * m_channels * 2 ); } // TODO: can use swparams to setup the device so it doesn't underrun but rather loops over // snd_pcm_sw_params_set_stop_threshold // To get alsa to just loop on underruns. set the swparam stop_threshold to equal buffer size. The sound buffer will just loop and never throw an xrun. // allocate the final mix buffer m_buffer_size = MIXBUFFER_SAMPLES * m_channels * 2; m_buffer = malloc( m_buffer_size ); common->Printf( "allocated a mix buffer of %d bytes\n", m_buffer_size ); #ifdef _DEBUG // verbose the state snd_pcm_state_t curstate = id_snd_pcm_state( m_pcm_handle ); assert( curstate == SND_PCM_STATE_PREPARED ); #endif common->Printf( "--------------------------------------\n" ); return true; } /* =============== idAudioHardwareALSA::~idAudioHardwareALSA =============== */ idAudioHardwareALSA::~idAudioHardwareALSA() { common->Printf( "----------- Alsa Shutdown ------------\n" ); Release(); common->Printf( "--------------------------------------\n" ); } /* ================= idAudioHardwareALSA::GetMixBufferSize ================= */ int idAudioHardwareALSA::GetMixBufferSize() { return m_buffer_size; } /* ================= idAudioHardwareALSA::GetMixBuffer ================= */ short* idAudioHardwareALSA::GetMixBuffer() { return ( short* )m_buffer; } /* =============== idAudioHardwareALSA::Flush =============== */ bool idAudioHardwareALSA::Flush() { int ret; snd_pcm_state_t state; state = id_snd_pcm_state( m_pcm_handle ); if( state != SND_PCM_STATE_RUNNING && state != SND_PCM_STATE_PREPARED ) { if( ( ret = id_snd_pcm_prepare( m_pcm_handle ) ) < 0 ) { Sys_Printf( "failed to recover from SND_PCM_STATE_XRUN: %s\n", id_snd_strerror( ret ) ); cvarSystem->SetCVarBool( "s_noSound", true ); return false; } Sys_Printf( "preparing audio device for output\n" ); } Write( true ); } /* =============== idAudioHardwareALSA::Write rely on m_freeWriteChunks which has been set in Flush() before engine did the mixing for this MIXBUFFER_SAMPLE =============== */ void idAudioHardwareALSA::Write( bool flushing ) { if( !flushing && m_remainingFrames ) { // if we write after a new mixing loop, we should have m_writeChunk == 0 // otherwise that last remaining chunk that was never flushed out to the audio device has just been overwritten Sys_Printf( "idAudioHardwareALSA::Write: %d frames overflowed and dropped\n", m_remainingFrames ); } if( !flushing ) { // if running after the mix loop, then we have a full buffer to write out m_remainingFrames = MIXBUFFER_SAMPLES; } if( m_remainingFrames == 0 ) { return; } // write the max frames you can in one shot - we need to write it all out in Flush() calls before the next Write() happens int pos = ( int )m_buffer + ( MIXBUFFER_SAMPLES - m_remainingFrames ) * m_channels * 2; snd_pcm_sframes_t frames = id_snd_pcm_writei( m_pcm_handle, ( void* )pos, m_remainingFrames ); if( frames < 0 ) { if( frames != -EAGAIN ) { Sys_Printf( "snd_pcm_writei %d frames failed: %s\n", m_remainingFrames, id_snd_strerror( frames ) ); } return; } m_remainingFrames -= frames; }
RobertBeckebans/Sikkpin-Feedback
neo/sys/linux/sound_alsa.cpp
C++
gpl-3.0
11,042
#include "TerrainNoise.h" TerrainNoise::TerrainNoise() { } #undef CLASSNAME #define CLASSNAME TerrainNoise void TerrainNoise::bind_methods() { REG_CSTR(0); }
Merg3D/Titan-Designer
src/world/TerrainNoise.cpp
C++
gpl-3.0
168
using UnityEngine; using System.Collections; public class DocumentSwitchTrigger : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerStay2D(Collider2D col) { if (GameObject.Find("GameManager").GetComponent<GameManager>().chosenQuickObject == this.gameObject) { if (col.tag == "SwitchTrigger") { SwitchTriggerScript swg = col.GetComponent<SwitchTriggerScript>(); /* if (swg.isPivot == true) { if (swg.id == this.GetComponent<CarMainScript>().triggerIdx) { } else { Vector2 mousePosition = Input.mousePosition; mousePosition = Camera.main.ScreenToWorldPoint(mousePosition); if (this.gameObject.GetComponent<CarMainScript>().triggerIdx < swg.id) { if (mousePosition.x > swg.transform.position.x) this.GetComponent<CarMainScript>().canMove = false; if (mousePosition.x < swg.transform.position.x) { this.GetComponent<CarMainScript>().canMove = true; } } else { if (mousePosition.x < swg.transform.position.x) this.GetComponent<CarMainScript>().canMove = false; if (mousePosition.x < swg.transform.position.x) { this.GetComponent<CarMainScript>().canMove = true; } } } } */ } } } }
rancex/sort-machine
Assets/Code/DocumentSwitchTrigger.cs
C#
gpl-3.0
1,761
class Issuer < ActiveRecord::Base extend FriendlyId friendly_id :name default_scope order(:name) belongs_to :institution validates_presence_of :name, :abbreviation, :institution validates_length_of :abbreviation, :is => 2 validates_uniqueness_of :name, :abbreviation has_many :regulation_types, :dependent => :destroy has_many :types, :through => :regulation_types before_validation :capitalize_abbr def capitalize_abbr self.abbreviation.upcase! end def display_name [name,institution.name].join " " end end
alfrenovsky/Digesto
app/models/issuer.rb
Ruby
gpl-3.0
550
class BudgetDatatable < AjaxDatatablesRails::Base # http://bobfly.blogspot.de/2015/05/rails-4-datatables-foundation.html AjaxDatatablesRails::Extensions::Kaminari def sortable_columns # Declare strings in this format: ModelName.column_name @sortable_columns ||= %w(Budget.title Budget.promise Budget.start_date Budget.end_date Member.last_name Donation.name) end def searchable_columns # Declare strings in this format: ModelName.column_name @searchable_columns ||= %w(Budget.title Budget.promise Budget.start_date Budget.end_date Member.last_name Member.first_name Donation.name) end private def data records.map do |record| [ record.title, number_to_currency(record.promise, locale: :de), I18n.l(record.start_date, format: :long), I18n.l(record.end_date, format: :long), link_to(record.member.full_name, v.member_path(record.member_id)), link_to(record.donation.name, v.donation_path(record.donation_id)), link_to(v.budget_path(record.id), class: "" ) do content_tag(:span, "", class: "glyphicon glyphicon-search", title: I18n.t('table.show')) end, link_to(v.edit_budget_path(record.id), class: "" ) do content_tag(:span, "", class: "glyphicon glyphicon-edit", title: I18n.t('table.edit')) end, link_to(v.budget_path(record.id), method: :delete, data: {confirm: 'Are you sure?'}) do content_tag(:span, "", class: "glyphicon glyphicon-trash color-red", title: I18n.t('table.delete') ) end, 'DT_RowClass': "danger", "DT_RowId": record.id ] end end def get_raw_records # insert query here Budget.includes(:member, :donation).joins(:member, :donation).all end # ==== Insert 'presenter'-like methods below if necessary def_delegator :@view, :link_to def_delegator :@view, :html_safe def_delegator :@view, :content_tag def_delegator :@view, :number_to_currency def v @view end end
iNeedCode/Maalify
app/datatables/budget_datatable.rb
Ruby
gpl-3.0
2,044
# Copyright 2015 Matthew J. Aburn # # 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. See <http://www.gnu.org/licenses/>. r""" Simulation of standard multiple stochastic integrals, both Ito and Stratonovich I_{ij}(t) = \int_{0}^{t}\int_{0}^{s} dW_i(u) dW_j(s) (Ito) J_{ij}(t) = \int_{0}^{t}\int_{0}^{s} \circ dW_i(u) \circ dW_j(s) (Stratonovich) These multiple integrals I and J are important building blocks that will be used by most of the higher-order algorithms that integrate multi-dimensional SODEs. We first implement the method of Kloeden, Platen and Wright (1992) to approximate the integrals by the first n terms from the series expansion of a Brownian bridge process. By default using n=5. Finally we implement the method of Wiktorsson (2001) which improves on the previous method by also approximating the tail-sum distribution by a multivariate normal distribution. References: P. Kloeden, E. Platen and I. Wright (1992) The approximation of multiple stochastic integrals M. Wiktorsson (2001) Joint Characteristic Function and Simultaneous Simulation of Iterated Ito Integrals for Multiple Independent Brownian Motions """ import numpy as np numpy_version = list(map(int, np.version.short_version.split('.'))) if numpy_version >= [1,10,0]: broadcast_to = np.broadcast_to else: from ._broadcast import broadcast_to def deltaW(N, m, h): """Generate sequence of Wiener increments for m independent Wiener processes W_j(t) j=0..m-1 for each of N time intervals of length h. Returns: dW (array of shape (N, m)): The [n, j] element has the value W_j((n+1)*h) - W_j(n*h) """ return np.random.normal(0.0, np.sqrt(h), (N, m)) def _t(a): """transpose the last two axes of a three axis array""" return a.transpose((0, 2, 1)) def _dot(a, b): r""" for rank 3 arrays a and b, return \sum_k a_ij^k . b_ik^l (no sum on i) i.e. This is just normal matrix multiplication at each point on first axis """ return np.einsum('ijk,ikl->ijl', a, b) def _Aterm(N, h, m, k, dW): """kth term in the sum of Wiktorsson2001 equation (2.2)""" sqrt2h = np.sqrt(2.0/h) Xk = np.random.normal(0.0, 1.0, (N, m, 1)) Yk = np.random.normal(0.0, 1.0, (N, m, 1)) term1 = _dot(Xk, _t(Yk + sqrt2h*dW)) term2 = _dot(Yk + sqrt2h*dW, _t(Xk)) return (term1 - term2)/k def Ikpw(dW, h, n=5): """matrix I approximating repeated Ito integrals for each of N time intervals, based on the method of Kloeden, Platen and Wright (1992). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size n (int, optional): how many terms to take in the series expansion Returns: (A, I) where A: array of shape (N, m, m) giving the Levy areas that were used. I: array of shape (N, m, m) giving an m x m matrix of repeated Ito integral values for each of the N time intervals. """ N = dW.shape[0] m = dW.shape[1] if dW.ndim < 3: dW = dW.reshape((N, -1, 1)) # change to array of shape (N, m, 1) if dW.shape[2] != 1 or dW.ndim > 3: raise(ValueError) A = _Aterm(N, h, m, 1, dW) for k in range(2, n+1): A += _Aterm(N, h, m, k, dW) A = (h/(2.0*np.pi))*A I = 0.5*(_dot(dW, _t(dW)) - np.diag(h*np.ones(m))) + A dW = dW.reshape((N, -1)) # change back to shape (N, m) return (A, I) def Jkpw(dW, h, n=5): """matrix J approximating repeated Stratonovich integrals for each of N time intervals, based on the method of Kloeden, Platen and Wright (1992). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size n (int, optional): how many terms to take in the series expansion Returns: (A, J) where A: array of shape (N, m, m) giving the Levy areas that were used. J: array of shape (N, m, m) giving an m x m matrix of repeated Stratonovich integral values for each of the N time intervals. """ m = dW.shape[1] A, I = Ikpw(dW, h, n) J = I + 0.5*h*np.eye(m).reshape((1, m, m)) return (A, J) # The code below this point implements the method of Wiktorsson2001. def _vec(A): """ Linear operator _vec() from Wiktorsson2001 p478 Args: A: a rank 3 array of shape N x m x n, giving a matrix A[j] for each interval of time j in 0..N-1 Returns: array of shape N x mn x 1, made by stacking the columns of matrix A[j] on top of each other, for each j in 0..N-1 """ N, m, n = A.shape return A.reshape((N, m*n, 1), order='F') def _unvec(vecA, m=None): """inverse of _vec() operator""" N = vecA.shape[0] if m is None: m = np.sqrt(vecA.shape[1] + 0.25).astype(np.int64) return vecA.reshape((N, m, -1), order='F') def _kp(a, b): """Special case Kronecker tensor product of a[i] and b[i] at each time interval i for i = 0 .. N-1 It is specialized for the case where both a and b are shape N x m x 1 """ if a.shape != b.shape or a.shape[-1] != 1: raise(ValueError) N = a.shape[0] # take the outer product over the last two axes, then reshape: return np.einsum('ijk,ilk->ijkl', a, b).reshape(N, -1, 1) def _kp2(A, B): """Special case Kronecker tensor product of A[i] and B[i] at each time interval i for i = 0 .. N-1 Specialized for the case A and B rank 3 with A.shape[0]==B.shape[0] """ N = A.shape[0] if B.shape[0] != N: raise(ValueError) newshape1 = A.shape[1]*B.shape[1] return np.einsum('ijk,ilm->ijlkm', A, B).reshape(N, newshape1, -1) def _P(m): """Returns m^2 x m^2 permutation matrix that swaps rows i and j where j = 1 + m((i - 1) mod m) + (i - 1) div m, for i = 1 .. m^2 """ P = np.zeros((m**2,m**2), dtype=np.int64) for i in range(1, m**2 + 1): j = 1 + m*((i - 1) % m) + (i - 1)//m P[i-1, j-1] = 1 return P def _K(m): """ matrix K_m from Wiktorsson2001 """ M = m*(m - 1)//2 K = np.zeros((M, m**2), dtype=np.int64) row = 0 for j in range(1, m): col = (j - 1)*m + j s = m - j K[row:(row+s), col:(col+s)] = np.eye(s) row += s return K def _AtildeTerm(N, h, m, k, dW, Km0, Pm0): """kth term in the sum for Atilde (Wiktorsson2001 p481, 1st eqn)""" M = m*(m-1)//2 Xk = np.random.normal(0.0, 1.0, (N, m, 1)) Yk = np.random.normal(0.0, 1.0, (N, m, 1)) factor1 = np.dot(Km0, Pm0 - np.eye(m**2)) factor1 = broadcast_to(factor1, (N, M, m**2)) factor2 = _kp(Yk + np.sqrt(2.0/h)*dW, Xk) return _dot(factor1, factor2)/k def _sigmainf(N, h, m, dW, Km0, Pm0): r"""Asymptotic covariance matrix \Sigma_\infty Wiktorsson2001 eqn (4.5)""" M = m*(m-1)//2 Im = broadcast_to(np.eye(m), (N, m, m)) IM = broadcast_to(np.eye(M), (N, M, M)) Ims0 = np.eye(m**2) factor1 = broadcast_to((2.0/h)*np.dot(Km0, Ims0 - Pm0), (N, M, m**2)) factor2 = _kp2(Im, _dot(dW, _t(dW))) factor3 = broadcast_to(np.dot(Ims0 - Pm0, Km0.T), (N, m**2, M)) return 2*IM + _dot(_dot(factor1, factor2), factor3) def _a(n): r""" \sum_{n+1}^\infty 1/k^2 """ return np.pi**2/6.0 - sum(1.0/k**2 for k in range(1, n+1)) def Iwik(dW, h, n=5): """matrix I approximating repeated Ito integrals for each of N time intervals, using the method of Wiktorsson (2001). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size n (int, optional): how many terms to take in the series expansion Returns: (Atilde, I) where Atilde: array of shape (N,m(m-1)//2,1) giving the area integrals used. I: array of shape (N, m, m) giving an m x m matrix of repeated Ito integral values for each of the N time intervals. """ N = dW.shape[0] m = dW.shape[1] if dW.ndim < 3: dW = dW.reshape((N, -1, 1)) # change to array of shape (N, m, 1) if dW.shape[2] != 1 or dW.ndim > 3: raise(ValueError) if m == 1: return (np.zeros((N, 1, 1)), (dW*dW - h)/2.0) Pm0 = _P(m) Km0 = _K(m) M = m*(m-1)//2 Atilde_n = _AtildeTerm(N, h, m, 1, dW, Km0, Pm0) for k in range(2, n+1): Atilde_n += _AtildeTerm(N, h, m, k, dW, Km0, Pm0) Atilde_n = (h/(2.0*np.pi))*Atilde_n # approximation after n terms S = _sigmainf(N, h, m, dW, Km0, Pm0) normdW2 = np.sum(np.abs(dW)**2, axis=1) radical = np.sqrt(1.0 + normdW2/h).reshape((N, 1, 1)) IM = broadcast_to(np.eye(M), (N, M, M)) Im = broadcast_to(np.eye(m), (N, m, m)) Ims0 = np.eye(m**2) sqrtS = (S + 2.0*radical*IM)/(np.sqrt(2.0)*(1.0 + radical)) G = np.random.normal(0.0, 1.0, (N, M, 1)) tailsum = h/(2.0*np.pi)*_a(n)**0.5*_dot(sqrtS, G) Atilde = Atilde_n + tailsum # our final approximation of the areas factor3 = broadcast_to(np.dot(Ims0 - Pm0, Km0.T), (N, m**2, M)) vecI = 0.5*(_kp(dW, dW) - _vec(h*Im)) + _dot(factor3, Atilde) I = _unvec(vecI) dW = dW.reshape((N, -1)) # change back to shape (N, m) return (Atilde, I) def Jwik(dW, h, n=5): """matrix J approximating repeated Stratonovich integrals for each of N time intervals, using the method of Wiktorsson (2001). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size n (int, optional): how many terms to take in the series expansion Returns: (Atilde, J) where Atilde: array of shape (N,m(m-1)//2,1) giving the area integrals used. J: array of shape (N, m, m) giving an m x m matrix of repeated Stratonovich integral values for each of the N time intervals. """ m = dW.shape[1] Atilde, I = Iwik(dW, h, n) J = I + 0.5*h*np.eye(m).reshape((1, m, m)) return (Atilde, J)
mattja/sdeint
sdeint/wiener.py
Python
gpl-3.0
10,384
#!/usr/bin/python # -*- coding: utf-8 -*- #-------------------------------------------------------------------- # Copyright (c) 2014 Eren Inan Canpolat # Author: Eren Inan Canpolat <eren.canpolat@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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/>. #-------------------------------------------------------------------- content_template = """<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> </body> </html>""" toc_ncx = u"""<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN" "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd"> <ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1"> <head> <meta name="dtb:uid" content="{book.uuid}" /> <meta name="dtb:depth" content="{book.toc_root.maxlevel}" /> <meta name="dtb:totalPageCount" content="0" /> <meta name="dtb:maxPageNumber" content="0" /> </head> <docTitle> <text>{book.title}</text> </docTitle> {navmap} </ncx>""" container_xml = """<?xml version="1.0" encoding="UTF-8" standalone="no"?> <container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"> <rootfiles> <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/> </rootfiles> </container> """
canpolat/bookbinder
bookbinder/templates.py
Python
gpl-3.0
2,011
package company; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; public class StringChains { private int longestChain(String[] words) { if (words == null || words.length == 0) return 0; int chainLength = 0; Arrays.sort(words, new Comparator<String>() { public int compare(String first, String second) { return first.length() - second.length(); } }); Map<String, Integer> wordMap = new HashMap<>(); for (int i = 0; i < words.length; i++) { if (wordMap.containsKey(words[i])) continue; wordMap.put(words[i], 1); for (int j = 0; j < words[i].length(); j++) { String temp = words[i].substring(0, j) + words[i].substring(j + 1); if (wordMap.containsKey(temp) && wordMap.get(temp) + 1 > wordMap.get(words[i])) { wordMap.put(words[i], wordMap.get(temp) + 1); } } if (wordMap.get(words[i]) > chainLength) chainLength = wordMap.get(words[i]); } return chainLength; } public static void main(String[] args) { StringChains sc = new StringChains(); System.out.println(sc.longestChain(new String[] { "a", "b", "ba", "bca", "bda", "bdca" })); System.out.println(sc.longestChain(new String[] {})); System.out.println(sc.longestChain(null)); System.out.println(sc.longestChain(new String[] { "bc", "abc" })); } }
Sriee/epi
Interview/src/company/StringChains.java
Java
gpl-3.0
1,592
<!DOCTYPE html> <html> <head> <title>添加邀请注册</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="<?php echo $this->rootUrl; ?>/css/bootstrap-3.2.0.min.css"> <link rel="stylesheet" href="<?php echo $this->rootUrl; ?>/css/bootstrap-theme-3.2.0.min.css"> <link rel="stylesheet" href="<?php echo $this->rootUrl; ?>/css/bootstrap-switch-3.2.1.min.css"> <link rel="stylesheet" href="<?php echo $this->rootUrl; ?>/css/jquery-ui.min.css"> <link rel="stylesheet" href="<?php echo $this->rootUrl; ?>/css/activity/tuiguang.css"> <script src="<?php echo $this->rootUrl; ?>/js/jquery-2.0.3.min.js"></script> <script src="<?php echo $this->rootUrl; ?>/js/bootstrap-3.2.0.min.js"></script> <script src="<?php echo $this->rootUrl; ?>/js/jquery-ui-1.11.2.min.js"></script> <script src="<?php echo $this->rootUrl; ?>/js/bootstrap-switch-3.2.1.min.js"></script> </head> <style type="text/css"> .tips { font-weight: bold; } </style> <body> <div class="reward-edit"> <div class="panel panel-default"> <div class="panel-heading"><b></b></div> <div class="panel-body"> <form class="form-horizontal" id="form" action ="<?php echo Yii::app()->createAbsoluteUrl('admin/uidiy/editconfig', array('id' => $config['id'])) ?>" method="post" enctype="multipart/form-data". > <div class="form-group"> <label for="" class="col-sm-2 control-label">模块名称:</label> <div class="col-sm-10"> <input type="text" class="form-control" name="name" id="name" required autofocus autocomplete="off" value="<?PHP echo WebUtils::u($config['name']) ?>"> <span id="helpBlock" class="help-block"><small>模块名称 必填</small></span> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">Icon:</label> <div class="col-sm-10"> <a id="tip_upload" href="javascript:;" class="tips"onclick="nxxupload();">上传文件</a> <a id="tip_text" href="javascript:;" onclick="nxxtext();">填写URL</a> <input type="text" class="form-control" name="icon_text" style="display: none" id="icon_text" value="<?php echo $config['icon'] ?>" > <input type="file" class="form-control" name="icon_file" style="display:done" id="icon_file"> <span id="helpBlock" class="help-block"><small>大小180*180 Jpg/Png文件</small></span> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">当前图标:</label> <div class="col-sm-10"> <img src="<?php echo $config['icon'] ?>" class="img-thumbnail" style="width: 70px;height: 70px;"> </div> </div> <?php if (!empty($config['id'])) { ?> <div class="form-group"> <label for="" class="col-sm-2 control-label">是否启用:</label> <div class="col-sm-10"> <select name="status" class="form-control" > <option value="1" <?php if ($config['status'] != '2') { ?>selected=""<?php } ?>>是</option> <option value="2" <?php if ($config['status'] == '2') { ?>selected=""<?php } ?> >否</option> </select> <span id="helpBlock" class="help-block"><small>默认开启。如果关闭将不会在APP中显示</small></span> </div> </div> <?php } ?> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit"class="btn btn-primary">提 交</button> </div> </div> </form> </div> <div class="panel-footer"></div> </div> </div> </body> <script> function nxxupload() { document.getElementById("tip_text").className = ''; document.getElementById("tip_upload").className = 'tips'; document.getElementById("icon_text").style.display = 'none'; document.getElementById("icon_file").style.display = ''; } function nxxtext() { document.getElementById("tip_upload").className = ''; document.getElementById("tip_text").className = 'tips'; document.getElementById("icon_text").style.display = ''; document.getElementById("icon_file").style.display = 'none'; } </script>
goyoo-php/mobcent
app/modules/admin/views/uidiy/configedit.php
PHP
gpl-3.0
5,489
using System; using System.IO; using System.IO.Compression; using System.Linq; using Nancy; using Nancy.Bootstrapper; using NLog; using NzbDrone.Common.EnvironmentInfo; namespace Lidarr.Http.Extensions.Pipelines { public class GzipCompressionPipeline : IRegisterNancyPipeline { private readonly Logger _logger; public int Order => 0; private readonly Action<Action<Stream>, Stream> _writeGZipStream; public GzipCompressionPipeline(Logger logger) { _logger = logger; // On Mono GZipStream/DeflateStream leaks memory if an exception is thrown, use an intermediate buffer in that case. _writeGZipStream = PlatformInfo.IsMono ? WriteGZipStreamMono : (Action<Action<Stream>, Stream>)WriteGZipStream; } public void Register(IPipelines pipelines) { pipelines.AfterRequest.AddItemToEndOfPipeline(CompressResponse); } private void CompressResponse(NancyContext context) { var request = context.Request; var response = context.Response; try { if ( response.Contents != Response.NoBody && !response.ContentType.Contains("image") && !response.ContentType.Contains("font") && request.Headers.AcceptEncoding.Any(x => x.Contains("gzip")) && !AlreadyGzipEncoded(response) && !ContentLengthIsTooSmall(response)) { var contents = response.Contents; response.Headers["Content-Encoding"] = "gzip"; response.Contents = responseStream => _writeGZipStream(contents, responseStream); } } catch (Exception ex) { _logger.Error(ex, "Unable to gzip response"); throw; } } private static void WriteGZipStreamMono(Action<Stream> innerContent, Stream targetStream) { using (var membuffer = new MemoryStream()) { WriteGZipStream(innerContent, membuffer); membuffer.Position = 0; membuffer.CopyTo(targetStream); } } private static void WriteGZipStream(Action<Stream> innerContent, Stream targetStream) { using (var gzip = new GZipStream(targetStream, CompressionMode.Compress, true)) using (var buffered = new BufferedStream(gzip, 8192)) { innerContent.Invoke(buffered); } } private static bool ContentLengthIsTooSmall(Response response) { var contentLength = response.Headers.TryGetValue("Content-Length", out var value) ? value : null; if (contentLength != null && long.Parse(contentLength) < 1024) { return true; } return false; } private static bool AlreadyGzipEncoded(Response response) { var contentEncoding = response.Headers.TryGetValue("Content-Encoding", out var value) ? value : null; if (contentEncoding == "gzip") { return true; } return false; } } }
lidarr/Lidarr
src/Lidarr.Http/Extensions/Pipelines/GZipPipeline.cs
C#
gpl-3.0
3,335
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda. //This file is part of SIAT. SIAT is licensed under the terms //of the GNU General Public License, version 3. //See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt> package ar.gov.rosario.siat.rec.view.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import ar.gov.rosario.siat.base.view.struts.BaseDispatchAction; import ar.gov.rosario.siat.base.view.util.BaseConstants; import ar.gov.rosario.siat.base.view.util.UserSession; import ar.gov.rosario.siat.gde.iface.model.NovedadRSAdapter; import ar.gov.rosario.siat.rec.iface.model.NovedadRSVO; import ar.gov.rosario.siat.rec.iface.service.RecServiceLocator; import ar.gov.rosario.siat.rec.iface.util.RecError; import ar.gov.rosario.siat.rec.iface.util.RecSecurityConstants; import ar.gov.rosario.siat.rec.view.util.RecConstants; import coop.tecso.demoda.iface.helper.DemodaUtil; import coop.tecso.demoda.iface.model.CommonKey; import coop.tecso.demoda.iface.model.NavModel; public final class AdministrarNovedadRSDAction extends BaseDispatchAction { private Log log = LogFactory.getLog(AdministrarNovedadRSDAction.class); public ActionForward inicializar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); String act = getCurrentAct(request); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); UserSession userSession = canAccess(request, mapping, RecSecurityConstants.ABM_NOVEDADRS, act); if (userSession == null) return forwardErrorSession(request); NavModel navModel = userSession.getNavModel(); NovedadRSAdapter novedadRSAdapterVO = null; String stringServicio = ""; ActionForward actionForward = null; try { CommonKey commonKey = new CommonKey(navModel.getSelectedId()); if (navModel.getAct().equals(BaseConstants.ACT_VER)) { stringServicio = "getNovedadRSAdapterForView(userSession, commonKey)"; novedadRSAdapterVO = RecServiceLocator.getDreiService().getNovedadRSAdapterForView(userSession, commonKey); actionForward = mapping.findForward(RecConstants.FWD_NOVEDADRS_VIEW_ADAPTER); } if (navModel.getAct().equals(BaseConstants.ACT_APLICAR)) { stringServicio = "getNovedadRSAdapterForUpdate(userSession, commonKey)"; novedadRSAdapterVO = RecServiceLocator.getDreiService().getNovedadRSAdapterForSimular(userSession, commonKey); novedadRSAdapterVO.addMessage(RecError.NOVEDADRS_MSG_APLICAR); actionForward = mapping.findForward(RecConstants.FWD_NOVEDADRS_EDIT_ADAPTER); } if (navModel.getAct().equals(RecConstants.ACT_APLICAR_MASIVO_NOVEDADRS)) { stringServicio = "getNovedadRSAdapterForMasivo(userSession)"; novedadRSAdapterVO = RecServiceLocator.getDreiService().getNovedadRSAdapterForMasivo(userSession); novedadRSAdapterVO.addMessage(RecError.NOVEDADRS_MSG_APLICAR_MASIVO); actionForward = mapping.findForward(RecConstants.FWD_NOVEDADRS_VIEW_ADAPTER); } if (log.isDebugEnabled()) log.debug(funcName + " salimos de servicio: " + stringServicio ); // Nunca Tiene errores recuperables // Tiene errores no recuperables if (novedadRSAdapterVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": servicio: " + stringServicio + ": " + novedadRSAdapterVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, NovedadRSAdapter.NAME, novedadRSAdapterVO); } // Seteo los valores de navegacion en el adapter novedadRSAdapterVO.setValuesFromNavModel(navModel); if (log.isDebugEnabled()) log.debug(funcName + ": " + NovedadRSAdapter.NAME + ": " + novedadRSAdapterVO.infoString()); // Envio el VO al request request.setAttribute(NovedadRSAdapter.NAME, novedadRSAdapterVO); // Subo el apdater al userSession userSession.put(NovedadRSAdapter.NAME, novedadRSAdapterVO); saveDemodaMessages(request, novedadRSAdapterVO); return actionForward; } catch (Exception exception) { return baseException(mapping, request, funcName, exception, NovedadRSAdapter.NAME); } } public ActionForward aplicar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); UserSession userSession = canAccess(request, mapping, RecSecurityConstants.ABM_NOVEDADRS, RecSecurityConstants.MTD_APLICAR); if (userSession==null) return forwardErrorSession(request); try { // Bajo el adapter del userSession NovedadRSAdapter novedadRSAdapterVO = (NovedadRSAdapter) userSession.get(NovedadRSAdapter.NAME); // Si es nulo no se puede continuar if (novedadRSAdapterVO == null) { log.error("error en: " + funcName + ": " + NovedadRSAdapter.NAME + " IS NULL. No se pudo obtener de la sesion"); return forwardErrorSessionNullObject(mapping, request, funcName, NovedadRSAdapter.NAME); } // llamada al servicio NovedadRSVO novedadRSVO = RecServiceLocator.getDreiService().aplicarNovedadRS(userSession, novedadRSAdapterVO.getNovedadRS()); // Tiene errores recuperables if (novedadRSVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + novedadRSAdapterVO.infoString()); saveDemodaErrors(request, novedadRSVO); return forwardErrorRecoverable(mapping, request, userSession, NovedadRSAdapter.NAME, novedadRSAdapterVO); } // Tiene errores no recuperables if (novedadRSVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": " + novedadRSAdapterVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, NovedadRSAdapter.NAME, novedadRSAdapterVO); } // Fue Exitoso return forwardConfirmarOk(mapping, request, funcName, NovedadRSAdapter.NAME); } catch (Exception exception) { return baseException(mapping, request, funcName, exception, NovedadRSAdapter.NAME); } } public ActionForward aplicarMasivo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); UserSession userSession = canAccess(request, mapping, RecSecurityConstants.ABM_NOVEDADRS, RecSecurityConstants.MTD_APLICARMASIVO); if (userSession==null) return forwardErrorSession(request); try { // Bajo el adapter del userSession NovedadRSAdapter novedadRSAdapterVO = (NovedadRSAdapter) userSession.get(NovedadRSAdapter.NAME); // Si es nulo no se puede continuar if (novedadRSAdapterVO == null) { log.error("error en: " + funcName + ": " + NovedadRSAdapter.NAME + " IS NULL. No se pudo obtener de la sesion"); return forwardErrorSessionNullObject(mapping, request, funcName, NovedadRSAdapter.NAME); } // Recuperamos datos del form en el vo DemodaUtil.populateVO(novedadRSAdapterVO, request); // Tiene errores recuperables if (novedadRSAdapterVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + novedadRSAdapterVO.infoString()); saveDemodaErrors(request, novedadRSAdapterVO); return forwardErrorRecoverable(mapping, request, userSession, NovedadRSAdapter.NAME, novedadRSAdapterVO); } // llamada al servicio novedadRSAdapterVO = RecServiceLocator.getDreiService().aplicarMasivoNovedadRS(userSession,novedadRSAdapterVO); // Tiene errores recuperables if (novedadRSAdapterVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + novedadRSAdapterVO.infoString()); saveDemodaErrors(request, novedadRSAdapterVO); return forwardErrorRecoverable(mapping, request, userSession, NovedadRSAdapter.NAME, novedadRSAdapterVO, RecConstants.FWD_NOVEDADRS_VIEW_ADAPTER); } // Tiene errores no recuperables if (novedadRSAdapterVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": " + novedadRSAdapterVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, NovedadRSAdapter.NAME, novedadRSAdapterVO); } // Fue Exitoso return forwardConfirmarOk(mapping, request, funcName, NovedadRSAdapter.NAME); } catch (Exception exception) { return baseException(mapping, request, funcName, exception, NovedadRSAdapter.NAME); } } public ActionForward volver(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return baseVolver(mapping, form, request, response, NovedadRSAdapter.NAME); } public ActionForward refill(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); return baseRefill(mapping, form, request, response, funcName, NovedadRSAdapter.NAME); } }
avdata99/SIAT
siat-1.0-SOURCE/src/view/src/WEB-INF/src/ar/gov/rosario/siat/rec/view/struts/AdministrarNovedadRSDAction.java
Java
gpl-3.0
9,557
<?php $L['Lightsquid_Description'] = 'Web proxy statistieken'; $L['Lightsquid_Tags'] = 'Grafische analyse statistiek Squid Web Proxy'; $L['Lightsquid_Title'] = 'Web Proxy Statistiek'; $L['Settings_title'] = 'Instellingen'; $L['Settings_label'] = 'Instellingen'; $L['Lang_label'] = 'Taal'; $L['BigFileLimit_label'] = 'Rapporteer bestanden groter dan (MB)'; $L['PerUserTrafficLimit_label'] = 'Rapporteer als gebruiker over zijn dag limiet zit (MB)';
NethServer/nethserver-lang
locale/nl/server-manager/NethServer_Module_Lightsquid.php
PHP
gpl-3.0
451
var xForRefIcon = 0; var yForRefIcon = 0; var xForSubDiagramIcon = 0; var yForSubDiagramIcon = 0; var xForTransIcon = 0; var yForTransIcon = 0; var fileLinks = []; var folderLinks = []; var urlLinks = []; var diagramLinks = []; var shapeLinks = []; var subdiagramLinks = []; var fromTransitorLinks = []; var toTransitorLinks = []; // vplink var vpLinkProjectLink; var vpLinkPageUrl; var vpLinkProjectLinkWithName; var vpLinkPageUrlWithName; function showDefaultReferenceIcon(imageId, modelValues, objectId) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeX = xyValueArray[0]*1; var shapeY = xyValueArray[1]*1; var x = shapeX + xOffset*1; var y = shapeY + yOffset*1 - 13; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var referenceIconLayer = document.getElementById(objectId); N = (document.all) ? 0 : 1; if (N) { referenceIconLayer.style.left = x - 3; referenceIconLayer.style.top = y + h; } else { referenceIconLayer.style.posLeft = x - 3; referenceIconLayer.style.posTop = y + h; } referenceIconLayer.style.visibility="visible" // } } } function showReferenceIcon(imageId, modelValues) { if (modelValues != '') { var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeX = xyValueArray[0]*1; var shapeY = xyValueArray[1]*1; var x = shapeX + xOffset*1; var y = shapeY + yOffset*1 - 13; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var referenceIconLayer = document.getElementById("referenceIconLayer"); N = (document.all) ? 0 : 1; if (N) { referenceIconLayer.style.left = x - 3; referenceIconLayer.style.top = y + h; } else { referenceIconLayer.style.posLeft = x - 3; referenceIconLayer.style.posTop = y + h; } referenceIconLayer.style.visibility="visible" // } } } function hideReferenceIcon() { var referenceIconLayer = document.getElementById("referenceIconLayer"); if (referenceIconLayer != null) { referenceIconLayer.style.visibility="hidden" } } function showDefaultSubdiagramIcon(imageId, modelValues, objectId) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeRightX = xyValueArray[2]*1; var shapeRightY = xyValueArray[1]*1; var x = shapeRightX + xOffset*1 - 10; var y = shapeRightY + yOffset*1 - 13; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var subdiagramIconLayer = document.getElementById(objectId); N = (document.all) ? 0 : 1; if (N) { subdiagramIconLayer.style.left = x - 3; subdiagramIconLayer.style.top = y + h; } else { subdiagramIconLayer.style.posLeft = x - 3; subdiagramIconLayer.style.posTop = y + h; } subdiagramIconLayer.style.visibility="visible" // } } } function showSubdiagramIcon(imageId, modelValues) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeRightX = xyValueArray[2]*1; var shapeRightY = xyValueArray[1]*1; var x = shapeRightX + xOffset*1 - 10; var y = shapeRightY + yOffset*1 - 13; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var subdiagramIconLayer = document.getElementById("subdiagramIconLayer"); N = (document.all) ? 0 : 1; if (N) { subdiagramIconLayer.style.left = x - 3; subdiagramIconLayer.style.top = y + h; } else { subdiagramIconLayer.style.posLeft = x - 3; subdiagramIconLayer.style.posTop = y + h; } subdiagramIconLayer.style.visibility="visible" // } } } function hideSubdiagramIcon() { var subdiagramIconLayer = document.getElementById("subdiagramIconLayer"); if (subdiagramIconLayer != null) { subdiagramIconLayer.style.visibility="hidden" } } function showDefaultTransitorIcon(imageId, modelValues, objectId) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeRightX = xyValueArray[2]*1; var shapeRightY = xyValueArray[1]*1; var x = shapeRightX + xOffset*1 - 10; var y = shapeRightY + yOffset*1; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var transitorIconLayer = document.getElementById(objectId); N = (document.all) ? 0 : 1; if (N) { transitorIconLayer.style.left = x - 3; transitorIconLayer.style.top = y + h; } else { transitorIconLayer.style.posLeft = x - 3; transitorIconLayer.style.posTop = y + h; } transitorIconLayer.style.visibility="visible" // } } } function showTransitorIcon(imageId, modelValues) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeRightX = xyValueArray[2]*1; var shapeRightY = xyValueArray[1]*1; var x = shapeRightX + xOffset*1 - 10; var y = shapeRightY + yOffset*1; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var transitorIconLayer = document.getElementById("transitorIconLayer"); N = (document.all) ? 0 : 1; if (N) { transitorIconLayer.style.left = x - 3; transitorIconLayer.style.top = y + h; } else { transitorIconLayer.style.posLeft = x - 3; transitorIconLayer.style.posTop = y + h; } transitorIconLayer.style.visibility="visible" // } } } function hideTransitorIcon() { var transitorIconLayer = document.getElementById("transitorIconLayer"); if (transitorIconLayer != null) { transitorIconLayer.style.visibility="hidden" } } function showDefaultDocumentationIcon(imageId, modelValues, objectId) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeX = xyValueArray[0]*1; var shapeY = xyValueArray[1]*1; var x = shapeX + xOffset*1; var y = shapeY + yOffset*1; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var documentationIconLayer = document.getElementById(objectId); N = (document.all) ? 0 : 1; if (N) { documentationIconLayer.style.left = x - 3; documentationIconLayer.style.top = y + h; } else { documentationIconLayer.style.posLeft = x - 3; documentationIconLayer.style.posTop = y + h; } documentationIconLayer.style.visibility="visible" // } } } function storeReferenceAndSubdiagramInfos(imageId, coords, fileRefs, folderRefs, urlRefs, diagramRefs, shapeRefs, subdiagrams, modelElementRefs, fromTransitors, toTransitors) { if (coords != ''){ var xyValueArray = coords.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ fileLinks = []; folderLinks = []; urlLinks = []; diagramLinks = []; shapeLinks = []; subdiagramLinks = []; modelElementLinks = []; fromTransitorLinks = []; toTransitorLinks = []; var popup = document.getElementById("linkPopupMenuTable"); popup.width = 250; // reset to 250 first (forZachman may changed it to 500) for (i = 0 ; i < fileRefs.length ; i++) { fileLinks[i] = fileRefs[i]; } for (i = 0 ; i < folderRefs.length ; i++) { folderLinks[i] = folderRefs[i]; } for (i = 0 ; i < urlRefs.length ; i++) { urlLinks[i] = urlRefs[i]; } for (j = 0 ; j < diagramRefs.length ; j++) { diagramLinks[j] = diagramRefs[j] } for (j = 0 ; j < shapeRefs.length ; j++) { shapeLinks[j] = shapeRefs[j] } for (j = 0 ; j < subdiagrams.length ; j++) { subdiagramLinks[j] = subdiagrams[j] } for (j = 0 ; j < modelElementRefs.length ; j++) { modelElementLinks[j] = modelElementRefs[j] } for (j = 0 ; j < fromTransitors.length ; j++) { fromTransitorLinks[j] = fromTransitors[j] } for (j = 0 ; j < toTransitors.length ; j++) { toTransitorLinks[j] = toTransitors[j] } var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeX = xyValueArray[0]*1; var shapeY = xyValueArray[1]*1; var x = shapeX + xOffset*1; var y = shapeY + yOffset*1 + 2; var w = xyValueArray[2]*1 - xyValueArray[0]*1; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; xForRefIcon = x; yForRefIcon = y + h; shapeX = xyValueArray[2]*1; shapeY = xyValueArray[1]*1; x = shapeX + xOffset*1 - 12; y = shapeY + yOffset*1 + 2; w = xyValueArray[2]*1 - xyValueArray[0]*1; h = xyValueArray[3]*1 - xyValueArray[1]*1; url = xyValueArray[4]; xForSubDiagramIcon = x; yForSubDiagramIcon = y + h; xForTransIcon = x; yForTransIcon = y + h + 12; // } } } function resetPopupForReference() { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); // file references for (i = 0 ; i < fileLinks.length ; i++) { var fileNameUrl = fileLinks[i].split("*"); var name = fileNameUrl[0]; var url = fileNameUrl[1]; // may be null var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/FileReference.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/FileReference.png'); background-repeat: no-repeat;\"></div>&nbsp;"+name; imgPopupCell.valign="middle"; if (url == null) { imgPopupCell.className="PopupMenuRowNonSelectable"; } else { imgPopupCell.destination=url; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination);hideLinkPopup(); }; } } // folder reference for (i = 0 ; i < folderLinks.length ; i++) { var folderNameUrl = folderLinks[i].split("*"); var name = folderNameUrl[0]; var url = folderNameUrl[1]; // may be null var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/FolderReference.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/FolderReference.png'); background-repeat: no-repeat;\"></div>&nbsp;"+name; imgPopupCell.valign="middle"; if (url == null) { imgPopupCell.className="PopupMenuRowNonSelectable"; } else if (url != null) { imgPopupCell.destination=url; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination);hideLinkPopup(); }; } } // url reference for (i = 0 ; i < urlLinks.length ; i++) { var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); var destination = urlLinks[i][0]; var name = urlLinks[i][1]; if (name == null || name == '') { name = destination; } imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/UrlReference.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/UrlReference.png'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=destination; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination);hideLinkPopup(); }; } // diagram reference for (j = 0 ; j < diagramLinks.length ; j++) { var diagramUrlNameType = diagramLinks[j].split("/"); var url = diagramUrlNameType[0]; var name = diagramUrlNameType[1]; var type = diagramUrlNameType[2]; var imgSrc = '../images/icons/'+type+'.png'; var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (url == 'vplink') { imgPopupCell.destination= diagramUrlNameType[3].replace('@','/'); imgPopupCell.vpLinkWithName= diagramUrlNameType[4].replace('@','/'); imgPopupCell.onclick= function onclick(event) { showVpLink(this.destination, this.vpLinkWithName, null, this) }; } else { imgPopupCell.destination=url if (url != null && url != '') { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } // shape reference for (j = 0 ; j < shapeLinks.length ; j++) { var shapeUrlNameType = shapeLinks[j].split("/"); var url = shapeUrlNameType[0]; var name = shapeUrlNameType[1]; var iconFileName = shapeUrlNameType[2]; var imgSrc = '../images/icons/'+iconFileName+'.png'; var row = popup.insertRow(popup.rows.length) var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=url imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (iconFileName.length > 0){ imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } // model element reference for (j = 0 ; j < modelElementLinks.length ; j++) { var modelElementUrlNameType = modelElementLinks[j].split("/"); var url = modelElementUrlNameType[0]; var name = modelElementUrlNameType[1]; var iconFileName = modelElementUrlNameType[2]; var imgSrc = '../images/icons/'+iconFileName+'.png'; var row = popup.insertRow(popup.rows.length) var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=url imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (iconFileName.length > 0) { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } function resetPopupForSubdiagram() { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); // subdiagram for (j = 0 ; j < subdiagramLinks.length ; j++) { var diagramUrlNameType = subdiagramLinks[j].split("/"); var url = diagramUrlNameType[0]; var name = diagramUrlNameType[1]; var type = diagramUrlNameType[2]; var imgSrc = '../images/icons/'+type+'.png'; var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=url imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (url != null && url != '') { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } function movePopupPositionToReferenceIconPosition() { movePopupPositionToSpecificPosition(xForRefIcon, yForRefIcon); } function movePopupPositionToSubdiagramIconPosition() { movePopupPositionToSpecificPosition(xForSubDiagramIcon, yForSubDiagramIcon); } function movePopupPositionToCursorPosition(imageId, event) { var diagram = document.getElementById(imageId); var xOffset = 0; var yOffset = 0; var e = (window.event) ? window.event : event; xOffset = e.clientX; yOffset = e.clientY; if (document.all) { if (!document.documentElement.scrollLeft) xOffset += document.body.scrollLeft; else xOffset += document.documentElement.scrollLeft; if (!document.documentElement.scrollTop) yOffset += document.body.scrollTop; else yOffset += document.documentElement.scrollTop; }else{ xOffset += window.pageXOffset; yOffset += window.pageYOffset; } var nX = xOffset*1; var nY = yOffset*1; movePopupPositionToSpecificPosition(nX, nY); } function movePopupPositionToSpecificPosition(x, y) { var popupLayer = document.getElementById("linkPopupMenuLayer"); N = (document.all) ? 0 : 1; if (N) { popupLayer.style.left = x; popupLayer.style.top = y; } else { popupLayer.style.posLeft = x; popupLayer.style.posTop = y; } } function switchPopupShowHideStatus(){ var popup = document.getElementById("linkPopupMenuTable"); if (popup.style.visibility=="visible") { hideLinkPopup(); }else{ showLinkPopup(); } } function switchPopupShowHideStatusForZachman(aForZachmanKind) { var popup = document.getElementById("linkPopupMenuTable"); if (popup.style.visibility=="visible") { if (aForZachmanKind == popup.forZachmanKind) { popup.forZachmanKind = null; hideLinkPopup(); } else { // keep popup shown, just need change its forZachmanKind popup.forZachmanKind = aForZachmanKind; } }else{ popup.forZachmanKind = aForZachmanKind; showLinkPopup(); } } function adjustPopupPositionForSpotLightTable() { movePopupPositionToSpecificPosition(cursorX,cursorY); } function showLinkPopup(){ hideVpLink(); hideReferencedBys(); var popup = document.getElementById("linkPopupMenuTable"); popup.style.visibility="visible" document.getElementById("linkPopupMenuLayer").style.visibility="visible"; } function hideLinkPopup(){ var popup = document.getElementById("linkPopupMenuTable"); if (popup != null) { popup.style.visibility="hidden" document.getElementById("linkPopupMenuLayer").style.visibility="hidden"; } } function clearLinkPopupContent(){ var popup = document.getElementById("linkPopupMenuTable"); for (i = popup.rows.length ; i >0 ; i--) { popup.deleteRow(0); } } function movePopupPositionToTransitorIconPosition() { movePopupPositionToSpecificPosition(xForTransIcon, yForTransIcon); } function resetPopupForTransitor() { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); // transitor var row = popup.insertRow(popup.rows.length); var popupCell = row.insertCell(0); popupCell.innerHTML="<div style=\"font-size:11px\">From:</div>"; for (j = 0 ; j < fromTransitorLinks.length ; j++) { var shapeUrlNameType = fromTransitorLinks[j].split("/"); addPopupItem(popup, shapeUrlNameType); } row = popup.insertRow(popup.rows.length); popupCell = row.insertCell(0); popupCell.innerHTML="<div style=\"font-size:11px\">To:</div>"; for (j = 0 ; j < toTransitorLinks.length ; j++) { var shapeUrlNameType = toTransitorLinks[j].split("/"); addPopupItem(popup, shapeUrlNameType); } } // for From/To Transitor function addPopupItem(popup, shapeUrlNameType) { var url = shapeUrlNameType[0]; var name = shapeUrlNameType[1]; var iconFileName = shapeUrlNameType[2]; var imgSrc = '../images/icons/'+iconFileName+'.png'; var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle"; imgPopupCell.destination=url; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } // for Zachman // @param format: url/name/type, url/name/type, ... function resetPopupForZachmanCellDiagrams(lCellId, lValues) { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); popup.style.width = 250; var lZachmanCell = document.getElementById(lCellId); var lZachmanCellX = findPosX(lZachmanCell); var lZachmanCellY = findPosY(lZachmanCell); if (lZachmanCellX > 250) { // show on left movePopupPositionToSpecificPosition(lZachmanCellX+lZachmanCell.offsetWidth-popup.offsetWidth-5, lZachmanCellY+lZachmanCell.offsetHeight-5); } else { // show on right // x+5 & y-5 to let the popup overlap with current cell movePopupPositionToSpecificPosition(lZachmanCellX+5, lZachmanCellY+lZachmanCell.offsetHeight-5); } // ZachmanCell.diagrams for (j = 0 ; j < lValues.length ; j++) { var diagramUrlNameType = lValues[j].split("/"); var url = diagramUrlNameType[0]; var name = diagramUrlNameType[1]; var type = diagramUrlNameType[2]; var imgSrc = '../images/icons/'+type+'.png'; var row = popup.insertRow(popup.rows.length); var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name; imgPopupCell.valign="middle"; imgPopupCell.destination=url; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (url != null && url != '') { imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } else { imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowNonSelectable"; }; } } } // @param format: url/name/aliases/labels/documentation, url/name/aliases/labels/documentation, ... function resetPopupForZachmanCellTerms(lCellId, lValues) { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); popup.style.width = 500; var lZachmanCell = document.getElementById(lCellId); var lZachmanCellX = findPosX(lZachmanCell); var lZachmanCellY = findPosY(lZachmanCell); if (lZachmanCellX > 500) { // show on left movePopupPositionToSpecificPosition(lZachmanCellX+lZachmanCell.offsetWidth-popup.offsetWidth-5, lZachmanCellY+lZachmanCell.offsetHeight-5); } else { // show on right // x+5 & y-5 to let the popup overlap with current cell movePopupPositionToSpecificPosition(lZachmanCellX+5, lZachmanCellY+lZachmanCell.offsetHeight-5); } // ZachmanCell.terms { var row = popup.insertRow(popup.rows.length); row.className="PopupMenuHeaderRow"; { var lPopupCell = row.insertCell(0); lPopupCell.innerHTML="Name"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(1); lPopupCell.innerHTML="Aliases"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(2); lPopupCell.innerHTML="Labels"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(3); lPopupCell.innerHTML="Documentation"; lPopupCell.valign="middle"; } } for (j = 0 ; j < lValues.length ; j++) { var lValue = lValues[j].split("/"); var url = lValue[0]; var name = lValue[1]; var aliases = lValue[2]; var labels = lValue[3]; var documentation = lValue[4]; var row = popup.insertRow(popup.rows.length); for (lCellIndex = 1; lCellIndex < lValue.length; lCellIndex++) { var lPopupCell = row.insertCell(lCellIndex-1); lPopupCell.id="cell"+j+","+lCellIndex-1; lPopupCell.innerHTML=lValue[lCellIndex]; lPopupCell.valign="middle"; } if (url != null && url != '') { row.destination=url; row.className="PopupMenuRowDeselected"; row.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; row.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; row.onclick= function onclick(event) { window.open(this.destination,'_self') }; } else { row.className="PopupMenuRowNonSelectable"; } } } // @param format: url/id/name/ruleText, url/id/name/ruleText, ... function resetPopupForZachmanCellRules(lCellId, lValues) { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); popup.style.width = 500; var lZachmanCell = document.getElementById(lCellId); var lZachmanCellX = findPosX(lZachmanCell); var lZachmanCellY = findPosY(lZachmanCell); if (lZachmanCellX > 500) { // show on left movePopupPositionToSpecificPosition(lZachmanCellX+lZachmanCell.offsetWidth-popup.offsetWidth-5, lZachmanCellY+lZachmanCell.offsetHeight-5); } else { // show on right // x+5 & y-5 to let the popup overlap with current cell movePopupPositionToSpecificPosition(lZachmanCellX+5, lZachmanCellY+lZachmanCell.offsetHeight-5); } // ZachmanCell.rules { var row = popup.insertRow(popup.rows.length); row.className="PopupMenuHeaderRow"; { var lPopupCell = row.insertCell(0); lPopupCell.innerHTML="ID"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(1); lPopupCell.innerHTML="Name"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(2); lPopupCell.innerHTML="Rule"; lPopupCell.valign="middle"; } } for (j = 0 ; j < lValues.length ; j++) { var lValue = lValues[j].split("/"); var url = lValue[0]; var id = lValue[1]; var name = lValue[2]; var ruleText = lValue[3]; var row = popup.insertRow(popup.rows.length); for (lCellIndex = 1; lCellIndex < lValue.length; lCellIndex++) { var lPopupCell = row.insertCell(lCellIndex-1); lPopupCell.id="cell"+j+","+lCellIndex-1; lPopupCell.innerHTML=lValue[lCellIndex]; lPopupCell.valign="middle"; } if (url != null && url != '') { row.destination=url; row.className="PopupMenuRowDeselected"; row.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; row.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; row.onclick= function onclick(event) { window.open(this.destination,'_self') }; } else { row.className="PopupMenuRowNonSelectable"; } } } function showVpLink(link, linkWithName, pageUrlElementName, linkElem) { // getting absolute location in page var lLeft = 0; var lTop = 0; var lParent = linkElem; while (lParent != null) { lLeft += lParent.offsetLeft; lTop += lParent.offsetTop; lParent = lParent.offsetParent; } showVpLinkAt(link, linkWithName, pageUrlElementName, lLeft, lTop + linkElem.offsetHeight); } function showVpLinkAtDiagram(link, linkWithName, pageUrlElementName, aLeft, aTop) { var lLeft = 0; var lTop = 0; var diagramElem = document.getElementById('diagram'); var lParent = diagramElem; while (lParent != null) { lLeft += lParent.offsetLeft; lTop += lParent.offsetTop; lParent = lParent.offsetParent; } showVpLinkAt(link, linkWithName, pageUrlElementName, lLeft + aLeft, lTop + aTop); } function showVpLinkAt(link, linkWithName, pageUrlElementName, aLeft, aTop) { var popup = document.getElementById("vplink"); if (popup.style.visibility == "visible") { popup.style.visibility="hidden"; } else { var linktext = document.getElementById("vplink-text"); var withName = document.getElementById("vplink-checkbox"); var lLinkType = document.getElementById("vplink-linkType") // read from cookies (https://earth.space/#issueId=81262) var lWithNameValue = getCookie("vpProjectPublisher_vpLink_withName"); if (lWithNameValue != null) { if (lWithNameValue == "true") { withName.checked = true; } else { withName.checked = false; } } var lLinkTypeValue = getCookie("vpProjectPublisher_vpLink_type"); if (lLinkTypeValue != null) { if (lLinkTypeValue == "Page URL") { lLinkType.selectedIndex = 1; // 1 should be "Page URL" } else { lLinkType.selectedIndex = 0; // 0 should be "Project Link" } } vpLinkProjectLink = link; vpLinkProjectLinkWithName = linkWithName; if (pageUrlElementName != null) { vpLinkPageUrl = document.location.href; vpLinkPageUrlWithName = pageUrlElementName+"\n"+vpLinkPageUrl; lLinkType.disabled = false; } else { vpLinkPageUrl = null; vpLinkPageUrlWithName = null; lLinkType.selectedIndex = 0; // 0 should be "Project Link" lLinkType.disabled = true; } if (withName.checked) { if (lLinkType.disabled == false && lLinkType.options[lLinkType.selectedIndex].value == "Page URL") { // Page URL linktext.value = vpLinkPageUrlWithName; } else { // Project Link linktext.value = vpLinkProjectLinkWithName; } } else { if (lLinkType.disabled == false && lLinkType.options[lLinkType.selectedIndex].value == "Page URL") { // Page URL linktext.value = vpLinkPageUrl; } else { // Project Link linktext.value = vpLinkProjectLink; } } N = (document.all) ? 0 : 1; if (N) { popup.style.left = aLeft; popup.style.top = aTop; } else { popup.style.posLeft = aLeft; popup.style.posTop = aTop; } hideLinkPopup(); hideReferencedBys(); popup.style.visibility="visible" linktext.focus(); linktext.select(); } } function hideVpLink() { var popupLayer = document.getElementById("vplink"); if (popupLayer != null && popupLayer.style.visibility == "visible") { popupLayer.style.visibility="hidden"; } } function vpLinkToggleName() { var linktext = document.getElementById("vplink-text"); var withName = document.getElementById("vplink-checkbox"); var lLinkType = document.getElementById("vplink-linkType") // write to cookies (https://earth.space/#issueId=81262) setCookie("vpProjectPublisher_vpLink_withName", withName.checked); setCookie("vpProjectPublisher_vpLink_type", lLinkType.options[lLinkType.selectedIndex].value); if (withName.checked) { if (lLinkType.disabled == false && lLinkType.options[lLinkType.selectedIndex].value == "Page URL") { // Page URL linktext.value = vpLinkPageUrlWithName; } else { // Project Link linktext.value = vpLinkProjectLinkWithName; } } else { if (lLinkType.disabled == false && lLinkType.options[lLinkType.selectedIndex].value == "Page URL") { // Page URL linktext.value = vpLinkPageUrl; } else { // Project Link linktext.value = vpLinkProjectLink; } } linktext.focus(); linktext.select(); } function showReferencedBys(invokerId, refByDiagrams, refByModels) { var popupLayer = document.getElementById("referencedBys"); if (popupLayer.style.visibility == "visible") { popupLayer.style.visibility="hidden"; } else { var popup = document.getElementById("referencedBysTable"); for (i = popup.rows.length ; i >0 ; i--) { popup.deleteRow(0); } var refByDiagramLinks = []; var refByModelLinks = []; { popup.width = 250; // reset to 250 first (forZachman may changed it to 500) for (i = 0 ; i < refByDiagrams.length ; i++) { refByDiagramLinks[i] = refByDiagrams[i]; } for (i = 0 ; i < refByModels.length ; i++) { refByModelLinks[i] = refByModels[i]; } } { // ref by diagrams for (j = 0 ; j < refByDiagramLinks.length ; j++) { var diagramUrlNameType = refByDiagramLinks[j].split("/"); var url = diagramUrlNameType[0]; var name = diagramUrlNameType[1]; var type = diagramUrlNameType[2]; var imgSrc = '../images/icons/'+type+'.png'; var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (url == 'vplink') { imgPopupCell.destination= diagramUrlNameType[3].replace('@','/'); imgPopupCell.vpLinkWithName= diagramUrlNameType[4].replace('@','/'); imgPopupCell.onclick= function onclick(event) { showVpLink(this.destination, this.vpLinkWithName, null, this) }; } else { imgPopupCell.destination=url if (url != null && url != '') { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } // ref by models for (j = 0 ; j < refByModelLinks.length ; j++) { var modelElementUrlNameType = refByModelLinks[j].split("/"); var url = modelElementUrlNameType[0]; var name = modelElementUrlNameType[1]; var iconFileName = modelElementUrlNameType[2]; var imgSrc = '../images/icons/'+iconFileName+'.png'; var row = popup.insertRow(popup.rows.length) var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=url imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (iconFileName.length > 0) { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } var invoker = document.getElementById(invokerId); var xOffset = findPosX(invoker); var yOffset = findPosY(invoker); yOffset = yOffset+18; N = (document.all) ? 0 : 1; if (N) { popupLayer.style.left = xOffset; popupLayer.style.top = yOffset; } else { popupLayer.style.posLeft = xOffset; popupLayer.style.posTop = yOffset; } hideLinkPopup(); hideVpLink(); popupLayer.style.visibility = "visible"; } } function hideReferencedBys() { var popupLayer = document.getElementById("referencedBys"); if (popupLayer != null && popupLayer.style.visibility == "visible") { popupLayer.style.visibility="hidden"; } } function setCookie(c_name, value) { var c_value = escape(value); document.cookie = c_name + "=" + c_value; } function getCookie(c_name) { var c_value = document.cookie; var c_start = c_value.indexOf(" " + c_name + "="); if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); } if (c_start == -1) { c_value = null; } else { c_start = c_value.indexOf("=", c_start)+1; var c_end = c_value.indexOf(";", c_start); if (c_end == -1) { c_end = c_value.length; } c_value = unescape(c_value.substring(c_start, c_end)); } return c_value; }
EdwardWuYiHsuan/Student-Course-System
poseitech-java-assignments/docs/content/link_popup.js
JavaScript
gpl-3.0
39,618
/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @date 2017 * Unit tests for interface/StandardCompiler.h. */ #include <string> #include <boost/test/unit_test.hpp> #include <libsolidity/interface/StandardCompiler.h> #include <libsolidity/interface/Version.h> #include <libsolutil/JSON.h> #include <test/Metadata.h> using namespace std; using namespace solidity::evmasm; namespace solidity::frontend::test { namespace { /// Helper to match a specific error type and message bool containsError(Json::Value const& _compilerResult, string const& _type, string const& _message) { if (!_compilerResult.isMember("errors")) return false; for (auto const& error: _compilerResult["errors"]) { BOOST_REQUIRE(error.isObject()); BOOST_REQUIRE(error["type"].isString()); BOOST_REQUIRE(error["message"].isString()); if ((error["type"].asString() == _type) && (error["message"].asString() == _message)) return true; } return false; } bool containsAtMostWarnings(Json::Value const& _compilerResult) { if (!_compilerResult.isMember("errors")) return true; for (auto const& error: _compilerResult["errors"]) { BOOST_REQUIRE(error.isObject()); BOOST_REQUIRE(error["severity"].isString()); if (error["severity"].asString() != "warning") return false; } return true; } Json::Value getContractResult(Json::Value const& _compilerResult, string const& _file, string const& _name) { if ( !_compilerResult["contracts"].isObject() || !_compilerResult["contracts"][_file].isObject() || !_compilerResult["contracts"][_file][_name].isObject() ) return Json::Value(); return _compilerResult["contracts"][_file][_name]; } Json::Value compile(string _input) { StandardCompiler compiler; string output = compiler.compile(std::move(_input)); Json::Value ret; BOOST_REQUIRE(util::jsonParseStrict(output, ret)); return ret; } } // end anonymous namespace BOOST_AUTO_TEST_SUITE(StandardCompiler) BOOST_AUTO_TEST_CASE(assume_object_input) { Json::Value result; /// Use the native JSON interface of StandardCompiler to trigger these frontend::StandardCompiler compiler; result = compiler.compile(Json::Value()); BOOST_CHECK(containsError(result, "JSONError", "Input is not a JSON object.")); result = compiler.compile(Json::Value("INVALID")); BOOST_CHECK(containsError(result, "JSONError", "Input is not a JSON object.")); /// Use the string interface of StandardCompiler to trigger these result = compile(""); BOOST_CHECK(containsError(result, "JSONError", "* Line 1, Column 1\n Syntax error: value, object or array expected.\n* Line 1, Column 1\n A valid JSON document must be either an array or an object value.\n")); result = compile("invalid"); BOOST_CHECK(containsError(result, "JSONError", "* Line 1, Column 1\n Syntax error: value, object or array expected.\n* Line 1, Column 2\n Extra non-whitespace after JSON value.\n")); result = compile("\"invalid\""); BOOST_CHECK(containsError(result, "JSONError", "* Line 1, Column 1\n A valid JSON document must be either an array or an object value.\n")); BOOST_CHECK(!containsError(result, "JSONError", "* Line 1, Column 1\n Syntax error: value, object or array expected.\n")); result = compile("{}"); BOOST_CHECK(!containsError(result, "JSONError", "* Line 1, Column 1\n Syntax error: value, object or array expected.\n")); BOOST_CHECK(!containsAtMostWarnings(result)); } BOOST_AUTO_TEST_CASE(invalid_language) { char const* input = R"( { "language": "INVALID", "sources": { "name": { "content": "abc" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "Only \"Solidity\" or \"Yul\" is supported as a language.")); } BOOST_AUTO_TEST_CASE(valid_language) { char const* input = R"( { "language": "Solidity" } )"; Json::Value result = compile(input); BOOST_CHECK(!containsError(result, "JSONError", "Only \"Solidity\" or \"Yul\" is supported as a language.")); } BOOST_AUTO_TEST_CASE(no_sources) { char const* input = R"( { "language": "Solidity" } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "No input sources specified.")); } BOOST_AUTO_TEST_CASE(no_sources_empty_object) { char const* input = R"( { "language": "Solidity", "sources": {} } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "No input sources specified.")); } BOOST_AUTO_TEST_CASE(no_sources_empty_array) { char const* input = R"( { "language": "Solidity", "sources": [] } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "\"sources\" is not a JSON object.")); } BOOST_AUTO_TEST_CASE(sources_is_array) { char const* input = R"( { "language": "Solidity", "sources": ["aa", "bb"] } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "\"sources\" is not a JSON object.")); } BOOST_AUTO_TEST_CASE(unexpected_trailing_test) { char const* input = R"( { "language": "Solidity", "sources": { "A": { "content": "contract A { function f() {} }" } } } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "* Line 10, Column 2\n Extra non-whitespace after JSON value.\n")); } BOOST_AUTO_TEST_CASE(smoke_test) { char const* input = R"( { "language": "Solidity", "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); } BOOST_AUTO_TEST_CASE(error_recovery_field) { auto input = R"( { "language": "Solidity", "settings": { "parserErrorRecovery": "1" }, "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "\"settings.parserErrorRecovery\" must be a Boolean.")); input = R"( { "language": "Solidity", "settings": { "parserErrorRecovery": true }, "sources": { "empty": { "content": "" } } } )"; result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); } BOOST_AUTO_TEST_CASE(optimizer_enabled_not_boolean) { char const* input = R"( { "language": "Solidity", "settings": { "optimizer": { "enabled": "wrong" } }, "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "The \"enabled\" setting must be a Boolean.")); } BOOST_AUTO_TEST_CASE(optimizer_runs_not_a_number) { char const* input = R"( { "language": "Solidity", "settings": { "optimizer": { "enabled": true, "runs": "not a number" } }, "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "The \"runs\" setting must be an unsigned number.")); } BOOST_AUTO_TEST_CASE(optimizer_runs_not_an_unsigned_number) { char const* input = R"( { "language": "Solidity", "settings": { "optimizer": { "enabled": true, "runs": -1 } }, "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "The \"runs\" setting must be an unsigned number.")); } BOOST_AUTO_TEST_CASE(basic_compilation) { char const* input = R"( { "language": "Solidity", "sources": { "fileA": { "content": "contract A { }" } }, "settings": { "outputSelection": { "fileA": { "A": [ "abi", "devdoc", "userdoc", "evm.bytecode", "evm.assembly", "evm.gasEstimates", "evm.legacyAssembly", "metadata" ], "": [ "legacyAST" ] } } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["abi"].isArray()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]"); BOOST_CHECK(contract["devdoc"].isObject()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["devdoc"]), "{\"methods\":{}}"); BOOST_CHECK(contract["userdoc"].isObject()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["userdoc"]), "{\"methods\":{}}"); BOOST_CHECK(contract["evm"].isObject()); /// @TODO check evm.methodIdentifiers, legacyAssembly, bytecode, deployedBytecode BOOST_CHECK(contract["evm"]["bytecode"].isObject()); BOOST_CHECK(contract["evm"]["bytecode"]["object"].isString()); BOOST_CHECK_EQUAL( solidity::test::bytecodeSansMetadata(contract["evm"]["bytecode"]["object"].asString()), string("6080604052348015600f57600080fd5b5060") + (VersionIsRelease ? "3f" : util::toHex(bytes{uint8_t(61 + VersionStringStrict.size())})) + "80601d6000396000f3fe6080604052600080fdfe" ); BOOST_CHECK(contract["evm"]["assembly"].isString()); BOOST_CHECK(contract["evm"]["assembly"].asString().find( " /* \"fileA\":0:14 contract A { } */\n mstore(0x40, 0x80)\n " "callvalue\n /* \"--CODEGEN--\":8:17 */\n dup1\n " "/* \"--CODEGEN--\":5:7 */\n iszero\n tag_1\n jumpi\n " "/* \"--CODEGEN--\":30:31 */\n 0x00\n /* \"--CODEGEN--\":27:28 */\n " "dup1\n /* \"--CODEGEN--\":20:32 */\n revert\n /* \"--CODEGEN--\":5:7 */\n" "tag_1:\n /* \"fileA\":0:14 contract A { } */\n pop\n dataSize(sub_0)\n dup1\n " "dataOffset(sub_0)\n 0x00\n codecopy\n 0x00\n return\nstop\n\nsub_0: assembly {\n " "/* \"fileA\":0:14 contract A { } */\n mstore(0x40, 0x80)\n 0x00\n " "dup1\n revert\n\n auxdata: 0xa26469706673582212" ) == 0); BOOST_CHECK(contract["evm"]["gasEstimates"].isObject()); BOOST_CHECK_EQUAL(contract["evm"]["gasEstimates"].size(), 1); BOOST_CHECK(contract["evm"]["gasEstimates"]["creation"].isObject()); BOOST_CHECK_EQUAL(contract["evm"]["gasEstimates"]["creation"].size(), 3); BOOST_CHECK(contract["evm"]["gasEstimates"]["creation"]["codeDepositCost"].isString()); BOOST_CHECK(contract["evm"]["gasEstimates"]["creation"]["executionCost"].isString()); BOOST_CHECK(contract["evm"]["gasEstimates"]["creation"]["totalCost"].isString()); BOOST_CHECK_EQUAL( u256(contract["evm"]["gasEstimates"]["creation"]["codeDepositCost"].asString()) + u256(contract["evm"]["gasEstimates"]["creation"]["executionCost"].asString()), u256(contract["evm"]["gasEstimates"]["creation"]["totalCost"].asString()) ); // Lets take the top level `.code` section (the "deployer code"), that should expose most of the features of // the assembly JSON. What we want to check here is Operation, Push, PushTag, PushSub, PushSubSize and Tag. BOOST_CHECK(contract["evm"]["legacyAssembly"].isObject()); BOOST_CHECK(contract["evm"]["legacyAssembly"][".code"].isArray()); BOOST_CHECK_EQUAL( util::jsonCompactPrint(contract["evm"]["legacyAssembly"][".code"]), "[{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"value\":\"80\"}," "{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"value\":\"40\"}," "{\"begin\":0,\"end\":14,\"name\":\"MSTORE\"}," "{\"begin\":0,\"end\":14,\"name\":\"CALLVALUE\"}," "{\"begin\":8,\"end\":17,\"name\":\"DUP1\"}," "{\"begin\":5,\"end\":7,\"name\":\"ISZERO\"}," "{\"begin\":5,\"end\":7,\"name\":\"PUSH [tag]\",\"value\":\"1\"}," "{\"begin\":5,\"end\":7,\"name\":\"JUMPI\"}," "{\"begin\":30,\"end\":31,\"name\":\"PUSH\",\"value\":\"0\"}," "{\"begin\":27,\"end\":28,\"name\":\"DUP1\"}," "{\"begin\":20,\"end\":32,\"name\":\"REVERT\"}," "{\"begin\":5,\"end\":7,\"name\":\"tag\",\"value\":\"1\"}," "{\"begin\":5,\"end\":7,\"name\":\"JUMPDEST\"}," "{\"begin\":0,\"end\":14,\"name\":\"POP\"}," "{\"begin\":0,\"end\":14,\"name\":\"PUSH #[$]\",\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"}," "{\"begin\":0,\"end\":14,\"name\":\"DUP1\"}," "{\"begin\":0,\"end\":14,\"name\":\"PUSH [$]\",\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"}," "{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"value\":\"0\"}," "{\"begin\":0,\"end\":14,\"name\":\"CODECOPY\"}," "{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"value\":\"0\"}," "{\"begin\":0,\"end\":14,\"name\":\"RETURN\"}]" ); BOOST_CHECK(contract["metadata"].isString()); BOOST_CHECK(solidity::test::isValidMetadata(contract["metadata"].asString())); BOOST_CHECK(result["sources"].isObject()); BOOST_CHECK(result["sources"]["fileA"].isObject()); BOOST_CHECK(result["sources"]["fileA"]["legacyAST"].isObject()); BOOST_CHECK_EQUAL( util::jsonCompactPrint(result["sources"]["fileA"]["legacyAST"]), "{\"attributes\":{\"absolutePath\":\"fileA\",\"exportedSymbols\":{\"A\":[1]}},\"children\":" "[{\"attributes\":{\"abstract\":false,\"baseContracts\":[null],\"contractDependencies\":[null],\"contractKind\":\"contract\"," "\"documentation\":null,\"fullyImplemented\":true,\"linearizedBaseContracts\":[1],\"name\":\"A\",\"nodes\":[null],\"scope\":2}," "\"id\":1,\"name\":\"ContractDefinition\",\"src\":\"0:14:0\"}],\"id\":2,\"name\":\"SourceUnit\",\"src\":\"0:14:0\"}" ); } BOOST_AUTO_TEST_CASE(compilation_error) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "fileA": { "A": [ "abi" ] } } }, "sources": { "fileA": { "content": "contract A { function }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(result.isMember("errors")); BOOST_CHECK(result["errors"].size() >= 1); for (auto const& error: result["errors"]) { BOOST_REQUIRE(error.isObject()); BOOST_REQUIRE(error["message"].isString()); if (error["message"].asString().find("pre-release compiler") == string::npos) { BOOST_CHECK_EQUAL( util::jsonCompactPrint(error), "{\"component\":\"general\",\"formattedMessage\":\"fileA:1:23: ParserError: Expected identifier but got '}'\\n" "contract A { function }\\n ^\\n\",\"message\":\"Expected identifier but got '}'\"," "\"severity\":\"error\",\"sourceLocation\":{\"end\":23,\"file\":\"fileA\",\"start\":22},\"type\":\"ParserError\"}" ); } } } BOOST_AUTO_TEST_CASE(output_selection_explicit) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "fileA": { "A": [ "abi" ] } } }, "sources": { "fileA": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["abi"].isArray()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]"); } BOOST_AUTO_TEST_CASE(output_selection_all_contracts) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "fileA": { "*": [ "abi" ] } } }, "sources": { "fileA": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["abi"].isArray()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]"); } BOOST_AUTO_TEST_CASE(output_selection_all_files_single_contract) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "*": { "A": [ "abi" ] } } }, "sources": { "fileA": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["abi"].isArray()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]"); } BOOST_AUTO_TEST_CASE(output_selection_all_files_all_contracts) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "*": { "*": [ "abi" ] } } }, "sources": { "fileA": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["abi"].isArray()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]"); } BOOST_AUTO_TEST_CASE(output_selection_dependent_contract) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "*": { "A": [ "abi" ] } } }, "sources": { "fileA": { "content": "contract B { } contract A { function f() public { new B(); } }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["abi"].isArray()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[{\"inputs\":[],\"name\":\"f\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"); } BOOST_AUTO_TEST_CASE(output_selection_dependent_contract_with_import) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "*": { "A": [ "abi" ] } } }, "sources": { "fileA": { "content": "import \"fileB\"; contract A { function f() public { new B(); } }" }, "fileB": { "content": "contract B { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["abi"].isArray()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[{\"inputs\":[],\"name\":\"f\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"); } BOOST_AUTO_TEST_CASE(filename_with_colon) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "http://github.com/ethereum/solidity/std/StandardToken.sol": { "A": [ "abi" ] } } }, "sources": { "http://github.com/ethereum/solidity/std/StandardToken.sol": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "http://github.com/ethereum/solidity/std/StandardToken.sol", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["abi"].isArray()); BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]"); } BOOST_AUTO_TEST_CASE(library_filename_with_colon) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "fileA": { "A": [ "evm.bytecode" ] } } }, "sources": { "fileA": { "content": "import \"git:library.sol\"; contract A { function f() public returns (uint) { return L.g(); } }" }, "git:library.sol": { "content": "library L { function g() public returns (uint) { return 1; } }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["evm"]["bytecode"].isObject()); BOOST_CHECK(contract["evm"]["bytecode"]["linkReferences"].isObject()); BOOST_CHECK(contract["evm"]["bytecode"]["linkReferences"]["git:library.sol"].isObject()); BOOST_CHECK(contract["evm"]["bytecode"]["linkReferences"]["git:library.sol"]["L"].isArray()); BOOST_CHECK(contract["evm"]["bytecode"]["linkReferences"]["git:library.sol"]["L"][0].isObject()); } BOOST_AUTO_TEST_CASE(libraries_invalid_top_level) { char const* input = R"( { "language": "Solidity", "settings": { "libraries": "42" }, "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "\"libraries\" is not a JSON object.")); } BOOST_AUTO_TEST_CASE(libraries_invalid_entry) { char const* input = R"( { "language": "Solidity", "settings": { "libraries": { "L": "42" } }, "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "Library entry is not a JSON object.")); } BOOST_AUTO_TEST_CASE(libraries_invalid_hex) { char const* input = R"( { "language": "Solidity", "settings": { "libraries": { "library.sol": { "L": "0x4200000000000000000000000000000000000xx1" } } }, "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "Invalid library address (\"0x4200000000000000000000000000000000000xx1\") supplied.")); } BOOST_AUTO_TEST_CASE(libraries_invalid_length) { char const* input = R"( { "language": "Solidity", "settings": { "libraries": { "library.sol": { "L1": "0x42", "L2": "0x4200000000000000000000000000000000000001ff" } } }, "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "Library address is of invalid length.")); } BOOST_AUTO_TEST_CASE(libraries_missing_hex_prefix) { char const* input = R"( { "language": "Solidity", "settings": { "libraries": { "library.sol": { "L": "4200000000000000000000000000000000000001" } } }, "sources": { "empty": { "content": "" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsError(result, "JSONError", "Library address is not prefixed with \"0x\".")); } BOOST_AUTO_TEST_CASE(library_linking) { char const* input = R"( { "language": "Solidity", "settings": { "libraries": { "library.sol": { "L": "0x4200000000000000000000000000000000000001" } }, "outputSelection": { "fileA": { "A": [ "evm.bytecode" ] } } }, "sources": { "fileA": { "content": "import \"library.sol\"; import \"library2.sol\"; contract A { function f() public returns (uint) { L2.g(); return L.g(); } }" }, "library.sol": { "content": "library L { function g() public returns (uint) { return 1; } }" }, "library2.sol": { "content": "library L2 { function g() public { } }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["evm"]["bytecode"].isObject()); BOOST_CHECK(contract["evm"]["bytecode"]["linkReferences"].isObject()); BOOST_CHECK(!contract["evm"]["bytecode"]["linkReferences"]["library.sol"].isObject()); BOOST_CHECK(contract["evm"]["bytecode"]["linkReferences"]["library2.sol"].isObject()); BOOST_CHECK(contract["evm"]["bytecode"]["linkReferences"]["library2.sol"]["L2"].isArray()); BOOST_CHECK(contract["evm"]["bytecode"]["linkReferences"]["library2.sol"]["L2"][0].isObject()); } BOOST_AUTO_TEST_CASE(evm_version) { auto inputForVersion = [](string const& _version) { return R"( { "language": "Solidity", "sources": { "fileA": { "content": "contract A { }" } }, "settings": { )" + _version + R"( "outputSelection": { "fileA": { "A": [ "metadata" ] } } } } )"; }; Json::Value result; result = compile(inputForVersion("\"evmVersion\": \"homestead\",")); BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].asString().find("\"evmVersion\":\"homestead\"") != string::npos); result = compile(inputForVersion("\"evmVersion\": \"tangerineWhistle\",")); BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].asString().find("\"evmVersion\":\"tangerineWhistle\"") != string::npos); result = compile(inputForVersion("\"evmVersion\": \"spuriousDragon\",")); BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].asString().find("\"evmVersion\":\"spuriousDragon\"") != string::npos); result = compile(inputForVersion("\"evmVersion\": \"byzantium\",")); BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].asString().find("\"evmVersion\":\"byzantium\"") != string::npos); result = compile(inputForVersion("\"evmVersion\": \"constantinople\",")); BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].asString().find("\"evmVersion\":\"constantinople\"") != string::npos); result = compile(inputForVersion("\"evmVersion\": \"petersburg\",")); BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].asString().find("\"evmVersion\":\"petersburg\"") != string::npos); result = compile(inputForVersion("\"evmVersion\": \"istanbul\",")); BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].asString().find("\"evmVersion\":\"istanbul\"") != string::npos); // test default result = compile(inputForVersion("")); BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].asString().find("\"evmVersion\":\"istanbul\"") != string::npos); // test invalid result = compile(inputForVersion("\"evmVersion\": \"invalid\",")); BOOST_CHECK(result["errors"][0]["message"].asString() == "Invalid EVM version requested."); } BOOST_AUTO_TEST_CASE(optimizer_settings_default_disabled) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "fileA": { "A": [ "metadata" ] } } }, "sources": { "fileA": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["metadata"].isString()); Json::Value metadata; BOOST_CHECK(util::jsonParseStrict(contract["metadata"].asString(), metadata)); Json::Value const& optimizer = metadata["settings"]["optimizer"]; BOOST_CHECK(optimizer.isMember("enabled")); BOOST_CHECK(optimizer["enabled"].asBool() == false); BOOST_CHECK(!optimizer.isMember("details")); BOOST_CHECK(optimizer["runs"].asUInt() == 200); } BOOST_AUTO_TEST_CASE(optimizer_settings_default_enabled) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "fileA": { "A": [ "metadata" ] } }, "optimizer": { "enabled": true } }, "sources": { "fileA": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["metadata"].isString()); Json::Value metadata; BOOST_CHECK(util::jsonParseStrict(contract["metadata"].asString(), metadata)); Json::Value const& optimizer = metadata["settings"]["optimizer"]; BOOST_CHECK(optimizer.isMember("enabled")); BOOST_CHECK(optimizer["enabled"].asBool() == true); BOOST_CHECK(!optimizer.isMember("details")); BOOST_CHECK(optimizer["runs"].asUInt() == 200); } BOOST_AUTO_TEST_CASE(optimizer_settings_details_exactly_as_default_disabled) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "fileA": { "A": [ "metadata" ] } }, "optimizer": { "details": { "constantOptimizer" : false, "cse" : false, "deduplicate" : false, "jumpdestRemover" : true, "orderLiterals" : false, "peephole" : true } } }, "sources": { "fileA": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["metadata"].isString()); Json::Value metadata; BOOST_CHECK(util::jsonParseStrict(contract["metadata"].asString(), metadata)); Json::Value const& optimizer = metadata["settings"]["optimizer"]; BOOST_CHECK(optimizer.isMember("enabled")); // enabled is switched to false instead! BOOST_CHECK(optimizer["enabled"].asBool() == false); BOOST_CHECK(!optimizer.isMember("details")); BOOST_CHECK(optimizer["runs"].asUInt() == 200); } BOOST_AUTO_TEST_CASE(optimizer_settings_details_different) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "fileA": { "A": [ "metadata" ] } }, "optimizer": { "runs": 600, "details": { "constantOptimizer" : true, "cse" : false, "deduplicate" : true, "jumpdestRemover" : true, "orderLiterals" : false, "peephole" : true, "yul": true } } }, "sources": { "fileA": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["metadata"].isString()); Json::Value metadata; BOOST_CHECK(util::jsonParseStrict(contract["metadata"].asString(), metadata)); Json::Value const& optimizer = metadata["settings"]["optimizer"]; BOOST_CHECK(!optimizer.isMember("enabled")); BOOST_CHECK(optimizer.isMember("details")); BOOST_CHECK(optimizer["details"]["constantOptimizer"].asBool() == true); BOOST_CHECK(optimizer["details"]["cse"].asBool() == false); BOOST_CHECK(optimizer["details"]["deduplicate"].asBool() == true); BOOST_CHECK(optimizer["details"]["jumpdestRemover"].asBool() == true); BOOST_CHECK(optimizer["details"]["orderLiterals"].asBool() == false); BOOST_CHECK(optimizer["details"]["peephole"].asBool() == true); BOOST_CHECK(optimizer["details"]["yul"].asBool() == true); BOOST_CHECK(optimizer["details"]["yulDetails"].isObject()); BOOST_CHECK(optimizer["details"]["yulDetails"].getMemberNames() == vector<string>{"stackAllocation"}); BOOST_CHECK(optimizer["details"]["yulDetails"]["stackAllocation"].asBool() == true); BOOST_CHECK_EQUAL(optimizer["details"].getMemberNames().size(), 8); BOOST_CHECK(optimizer["runs"].asUInt() == 600); } BOOST_AUTO_TEST_CASE(metadata_without_compilation) { // NOTE: the contract code here should fail to compile due to "out of stack" // If the metadata is successfully returned, that means no compilation was attempted. char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "fileA": { "A": [ "metadata" ] } } }, "sources": { "fileA": { "content": "contract A { function x(uint a, uint b, uint c, uint d, uint e, uint f, uint g, uint h, uint i, uint j, uint k, uint l, uint m, uint n, uint o, uint p) pure public {} function y() pure public { uint a; uint b; uint c; uint d; uint e; uint f; uint g; uint h; uint i; uint j; uint k; uint l; uint m; uint n; uint o; uint p; x(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p); } }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["metadata"].isString()); BOOST_CHECK(solidity::test::isValidMetadata(contract["metadata"].asString())); } BOOST_AUTO_TEST_CASE(common_pattern) { char const* input = R"( { "language": "Solidity", "settings": { "outputSelection": { "*": { "*": [ "evm.bytecode.object", "metadata" ] } } }, "sources": { "fileA": { "content": "contract A { function f() pure public {} }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["metadata"].isString()); BOOST_CHECK(solidity::test::isValidMetadata(contract["metadata"].asString())); BOOST_CHECK(contract["evm"]["bytecode"].isObject()); BOOST_CHECK(contract["evm"]["bytecode"]["object"].isString()); } BOOST_AUTO_TEST_CASE(use_stack_optimization) { // NOTE: the contract code here should fail to compile due to "out of stack" // If we enable stack optimization, though, it will compile. char const* input = R"( { "language": "Solidity", "settings": { "optimizer": { "enabled": true, "details": { "yul": true } }, "outputSelection": { "fileA": { "A": [ "evm.bytecode.object" ] } } }, "sources": { "fileA": { "content": "contract A { function y() public { assembly { function fun() -> a3, b3, c3, d3, e3, f3, g3, h3, i3, j3, k3, l3, m3, n3, o3, p3 { let a := 1 let b := 1 let z3 := 1 sstore(a, b) sstore(add(a, 1), b) sstore(add(a, 2), b) sstore(add(a, 3), b) sstore(add(a, 4), b) sstore(add(a, 5), b) sstore(add(a, 6), b) sstore(add(a, 7), b) sstore(add(a, 8), b) sstore(add(a, 9), b) sstore(add(a, 10), b) sstore(add(a, 11), b) sstore(add(a, 12), b) } let a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1, o1, p1 := fun() let a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2, p2 := fun() sstore(a1, a2) } } }" } } } )"; Json::Value parsedInput; BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput)); solidity::frontend::StandardCompiler compiler; Json::Value result = compiler.compile(parsedInput); BOOST_CHECK(containsAtMostWarnings(result)); Json::Value contract = getContractResult(result, "fileA", "A"); BOOST_REQUIRE(contract.isObject()); BOOST_REQUIRE(contract["evm"]["bytecode"]["object"].isString()); BOOST_CHECK(contract["evm"]["bytecode"]["object"].asString().length() > 20); // Now disable stack optimizations // results in "stack too deep" parsedInput["settings"]["optimizer"]["details"]["yulDetails"]["stackAllocation"] = false; result = compiler.compile(parsedInput); BOOST_REQUIRE(result["errors"].isArray()); BOOST_CHECK(result["errors"][0]["severity"] == "error"); BOOST_REQUIRE(result["errors"][0]["message"].isString()); BOOST_CHECK(result["errors"][0]["message"].asString().find("Stack too deep when compiling inline assembly") != std::string::npos); BOOST_CHECK(result["errors"][0]["type"] == "YulException"); } BOOST_AUTO_TEST_CASE(standard_output_selection_wildcard) { char const* input = R"( { "language": "Solidity", "sources": { "A": { "content": "pragma solidity >=0.0; contract C { function f() public pure {} }" } }, "settings": { "outputSelection": { "*": { "C": ["evm.bytecode"] } } } } )"; Json::Value parsedInput; BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput)); solidity::frontend::StandardCompiler compiler; Json::Value result = compiler.compile(parsedInput); BOOST_REQUIRE(result["contracts"].isObject()); BOOST_REQUIRE(result["contracts"].size() == 1); BOOST_REQUIRE(result["contracts"]["A"].isObject()); BOOST_REQUIRE(result["contracts"]["A"].size() == 1); BOOST_REQUIRE(result["contracts"]["A"]["C"].isObject()); BOOST_REQUIRE(result["contracts"]["A"]["C"]["evm"].isObject()); BOOST_REQUIRE(result["contracts"]["A"]["C"]["evm"]["bytecode"].isObject()); BOOST_REQUIRE(result["sources"].isObject()); BOOST_REQUIRE(result["sources"].size() == 1); BOOST_REQUIRE(result["sources"]["A"].isObject()); } BOOST_AUTO_TEST_CASE(standard_output_selection_wildcard_colon_source) { char const* input = R"( { "language": "Solidity", "sources": { ":A": { "content": "pragma solidity >=0.0; contract C { function f() public pure {} }" } }, "settings": { "outputSelection": { "*": { "C": ["evm.bytecode"] } } } } )"; Json::Value parsedInput; BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput)); solidity::frontend::StandardCompiler compiler; Json::Value result = compiler.compile(parsedInput); BOOST_REQUIRE(result["contracts"].isObject()); BOOST_REQUIRE(result["contracts"].size() == 1); BOOST_REQUIRE(result["contracts"][":A"].isObject()); BOOST_REQUIRE(result["contracts"][":A"].size() == 1); BOOST_REQUIRE(result["contracts"][":A"]["C"].isObject()); BOOST_REQUIRE(result["contracts"][":A"]["C"]["evm"].isObject()); BOOST_REQUIRE(result["contracts"][":A"]["C"]["evm"]["bytecode"].isObject()); BOOST_REQUIRE(result["sources"].isObject()); BOOST_REQUIRE(result["sources"].size() == 1); BOOST_REQUIRE(result["sources"][":A"].isObject()); } BOOST_AUTO_TEST_CASE(standard_output_selection_wildcard_empty_source) { char const* input = R"( { "language": "Solidity", "sources": { "": { "content": "pragma solidity >=0.0; contract C { function f() public pure {} }" } }, "settings": { "outputSelection": { "*": { "C": ["evm.bytecode"] } } } } )"; Json::Value parsedInput; BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput)); solidity::frontend::StandardCompiler compiler; Json::Value result = compiler.compile(parsedInput); BOOST_REQUIRE(result["contracts"].isObject()); BOOST_REQUIRE(result["contracts"].size() == 1); BOOST_REQUIRE(result["contracts"][""].isObject()); BOOST_REQUIRE(result["contracts"][""].size() == 1); BOOST_REQUIRE(result["contracts"][""]["C"].isObject()); BOOST_REQUIRE(result["contracts"][""]["C"]["evm"].isObject()); BOOST_REQUIRE(result["contracts"][""]["C"]["evm"]["bytecode"].isObject()); BOOST_REQUIRE(result["sources"].isObject()); BOOST_REQUIRE(result["sources"].size() == 1); BOOST_REQUIRE(result["sources"][""].isObject()); } BOOST_AUTO_TEST_CASE(standard_output_selection_wildcard_multiple_sources) { char const* input = R"( { "language": "Solidity", "sources": { "A": { "content": "pragma solidity >=0.0; contract C { function f() public pure {} }" }, "B": { "content": "pragma solidity >=0.0; contract D { function f() public pure {} }" } }, "settings": { "outputSelection": { "*": { "D": ["evm.bytecode"] } } } } )"; Json::Value parsedInput; BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput)); solidity::frontend::StandardCompiler compiler; Json::Value result = compiler.compile(parsedInput); BOOST_REQUIRE(result["contracts"].isObject()); BOOST_REQUIRE(result["contracts"].size() == 1); BOOST_REQUIRE(result["contracts"]["B"].isObject()); BOOST_REQUIRE(result["contracts"]["B"].size() == 1); BOOST_REQUIRE(result["contracts"]["B"]["D"].isObject()); BOOST_REQUIRE(result["contracts"]["B"]["D"]["evm"].isObject()); BOOST_REQUIRE(result["contracts"]["B"]["D"]["evm"]["bytecode"].isObject()); BOOST_REQUIRE(result["sources"].isObject()); BOOST_REQUIRE(result["sources"].size() == 2); BOOST_REQUIRE(result["sources"]["A"].isObject()); BOOST_REQUIRE(result["sources"]["B"].isObject()); } BOOST_AUTO_TEST_SUITE_END() } // end namespaces
bobsummerwill/solidity
test/libsolidity/StandardCompiler.cpp
C++
gpl-3.0
39,368
var request = require('request'); var cheerio = require('cheerio'); var admin = require("firebase-admin"); //var serviceAccount = require("tehillim-17559-firebase-adminsdk-gx90v-b712a63ab5.json"); admin.initializeApp({ credential: admin.credential.cert("tehillim-17559-firebase-adminsdk-gx90v-b712a63ab5.json"), databaseURL: "https://tehillim-17559.firebaseio.com" }); // As an admin, the app has access to read and write all data, regardless of Security Rules var db = admin.database(); // Attach an asynchronous callback to read the data at our posts reference //ref.on("value", function (snapshot) { // console.log(snapshot.val()); //}, function (errorObject) { // console.log("The read failed: " + errorObject.code); //}); var psalmId = 1; var stripeHtml = function (text) { return text.replace(/<i><\/i>/g, ''); }; var removeLeadingVerseIndex = function (text) { return text.replace(/\d{1,2}/g, ''); }; var runEnHeRequest = function (id) { request('http://www.sefaria.org/api/texts/Psalms.' + id + '?commentary=0&context=1&pad=0', function (error, response, html) { if (!error && response.statusCode == 200) { console.log("Psalm: " + id + " OK"); var objHtml = JSON.parse(html); var enArray = []; objHtml.text.forEach(function (item) { enArray.push(stripeHtml(item)); }); var newObj = { id: id, name: "Psalm " + id, en: enArray, he: objHtml.he } var path = "psalms/" + (id-1).toString(); var ref = db.ref(path); ref.update(newObj, function (error) { if (error) { console.log("Data could not be saved." + error); } else { console.log("Psalm " + id + " saved successfully."); } }); } if (error) { console.log(response); } }); } var runPhonetiqueFrRequest = function (id) { request('http://tehilim-online.com/les-psaumes-de-David/Tehilim-' + id, function (error, response, html) { if (!error && response.statusCode == 200) { console.log("Psalm: " + id + " OK"); var $ = cheerio.load(html); var ph = $('#phonetiqueBlock span').text().split("\n"); var frNotFormatted = $('#traductionBlock p').text().split("\n"); var fr = []; frNotFormatted.forEach(function (item) { fr.push(removeLeadingVerseIndex(item)); }); var newObj = { ph: ph, fr: fr } // console.log(newObj); var path = "psalms/" + (id - 1).toString(); var ref = db.ref(path); ref.update(newObj, function (error) { if (error) { console.log("Data could not be saved." + error); } else { console.log("Psalm " + id + " saved successfully."); } }); } if (error) { console.log(response); } }); } while(psalmId <= 150) { var psalmTextArray = []; //runEnHeRequest(psalmId); runPhonetiqueFrRequest(psalmId); psalmId++; }
miroo93/TehillimForAll
TehillimForAll/srv/scrape.js
JavaScript
gpl-3.0
3,344
import { FormsEpidemiologia } from '../modules/forms/forms-epidemiologia/forms-epidemiologia-schema'; async function run(done) { const fichas = FormsEpidemiologia.find({ active: { $exists: false } }).cursor(); for await (const ficha of fichas) { const _id = ficha.id; const $set = { active: true }; await FormsEpidemiologia.update({ _id }, { $set }); } done(); } export = run;
andes/api
scripts/EP-167.ts
TypeScript
gpl-3.0
419
/* Copyright (C) 2013 by Claudio Zopfi, Zurich, Suisse, z@x21.ch This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QDebug> #include "layoutmodel.h" LayoutModel::LayoutModel() { width=200; height=200; nrows=2; nsegs=12; nseg = new int[nrows]; nseg[0] = 5; nseg[1] = 7; rowheight = new int[nrows]; rowheightpx = new int[nrows]; rowheight[0] = 4; rowheight[1] = 4; rowheightmax=8; segwidth = new int[nsegs]; segwidthpx = new int[nsegs]; setAll(nsegs,segwidth,1); segwidthmax=new int[nrows]; segwidthmax[0]= 5; segwidthmax[1]= 7; note = new int[nsegs]; note[0]=50; note[1]=51; note[2]=52; note[3]=53; note[4]=54; note[5]=55; note[6]=56; note[7]=57; note[8]=58; note[9]=59; note[10]=60; note[11]=61; ctlx=new int[nsegs]; setAll(nsegs,ctlx,0); ctly=new int[nsegs]; setAll(nsegs,ctly,0); chan=new int[nsegs]; setAll(nsegs,chan,0); pressed=new int[nsegs]; setAll(nsegs,pressed,0); calcGeo(200,200); } void LayoutModel::calcGeo(int w, int h) { // qDebug() << "Cacl geo " << w << " " << h; width=w; height=h; int i=0; int rowheightsum=0; for(int y=0;y<nrows;y++) { rowheightpx[y]=height*rowheight[y]/rowheightmax; rowheightsum+=rowheightpx[y]; // additional pixels may occur due to rounding differences // -> add additional pixels to last row if(y==nrows-1 && rowheightsum<height) { rowheightpx[y]+=rowheightsum-height; } int segwidthsum=0; for(int x=0;x<nseg[y];x++) { segwidthpx[i]=width*segwidth[i]/segwidthmax[y]; segwidthsum+=segwidthpx[i]; // -> add additional pixels to last segment if(x==nseg[y]-1 && segwidthsum<width) { segwidthpx[i]+=width-segwidthsum; } i++; } } } int LayoutModel::getHeight() const { return height; } int LayoutModel::getWidth() const { return width; } int LayoutModel::getNrows() const { return nrows; } int LayoutModel::getRowheightpx(int i) const { return rowheightpx[i]; } int LayoutModel::getNseg(int i) const { return nseg[i]; } void LayoutModel::setAll(int n, int *d, int v) { for(int i=0;i<n;i++) { d[i]=v; } } int LayoutModel::getSegwidth(int i) const { return segwidth[i]; } int LayoutModel::getCtly(int i) const { return ctly[i]; } int LayoutModel::getChan(int i) const { return chan[i]; } int LayoutModel::getCtlx(int i) const { return ctlx[i]; } int LayoutModel::getNote(int i) const { return note[i]; } int LayoutModel::getSegwidthpx(int i) const { return segwidthpx[i]; } int LayoutModel::getSegwidthmax(int i) const { return segwidthmax[i]; } int LayoutModel::getPressed(int i) const { return pressed[i]; } void LayoutModel::incPressed(int i) { pressed[i]++; } void LayoutModel::decPressed(int i) { if(pressed[i]>0) { pressed[i]--; } }
x21/rc1
rc1/conf/layoutmodel.cpp
C++
gpl-3.0
3,628
// // input_properties_py.hpp // blockscipy // // Created by Malte Moeser on 8/26/19. // #ifndef input_properties_py_h #define input_properties_py_h #include "method_tags.hpp" #include <blocksci/chain/block.hpp> struct AddInputMethods { template <typename FuncApplication> void operator()(FuncApplication func) { using namespace blocksci; func(property_tag, "value", &Input::getValue, "The value in base currency attached to this input"); func(property_tag, "address_type", &Input::getType, "The address type of the input"); func(property_tag, "sequence_num", &Input::sequenceNumber, "The sequence number of the input"); func(property_tag, "spent_tx_index", &Input::spentTxIndex, "The index of the transaction that this input spent"); func(property_tag, "spent_tx", &Input::getSpentTx, "The transaction that this input spent"); func(property_tag, "spent_output", &Input::getSpentOutput, "The output that this input spent"); func(property_tag, "age", &Input::age, "The number of blocks between the spent output and this input"); func(property_tag, "tx", &Input::transaction, "The transaction that contains this input"); func(property_tag, "block", &Input::block, "The block that contains this input"); func(property_tag, "index", &Input::inputIndex, "The index inside this transaction's inputs"); func(property_tag, "tx_index", &Input::txIndex, "The tx index of this input's transaction"); ; } }; #endif /* input_properties_py_h */
citp/BlockSci
blockscipy/src/chain/input/input_properties_py.hpp
C++
gpl-3.0
1,555
var _ = require('lodash'); var doFacesIntersect = require('./face-intersection').doFacesIntersect; function flatMeshIntersects(mesh){ var numFaces = mesh.faces.length; for (var i = 0; i < numFaces; ++i) { var firstFace = _.map(mesh.faces[i].vertices, function(vertexIndex){ return mesh.vertices[vertexIndex]; }); for (var j = i + 1; j < numFaces; ++j) { var secondFace = _.map(mesh.faces[j].vertices, function(vertexIndex){ return mesh.vertices[vertexIndex]; }); if (doFacesIntersect(firstFace, secondFace)) { return true; } } } return false; } exports.flatMeshIntersects = flatMeshIntersects;
mjleehh/paper-model
lib/algorithms/flat-mesh-intersection.js
JavaScript
gpl-3.0
737
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Prasatec.Cu2Com.Data { public sealed class UserResetCollection : Raden.ICollection<UserReset> { private const int DEFAULT_LIMIT = 25; public UserResetCollection() : this(new Raden.QueryBuilder<UserReset>().Build()) { } public UserResetCollection(Raden.IQuery Query) { this.baseQuery = Query; } private int i_PageIndex, i_RecordsPerPage; private Raden.IQuery baseQuery; public event EventHandler ListRefreshed; public void Refresh() { this.ListRefreshed?.Invoke(this, EventArgs.Empty); throw new NotImplementedException(); } public string[] Columns { get; private set; } public UserReset[] Records { get; private set; } public int PageCount { get; private set; } public int PageIndex { get { return this.i_PageIndex; } set { if (value > this.PageCount) { value = PageCount; } if (value < 1) { value = 1; } this.Refresh(); } } public int RecordsPerPage { get { return this.i_RecordsPerPage; } set { this.i_RecordsPerPage = value; this.i_PageIndex = 1; this.Refresh(); } } public bool Next() { if (this.PageIndex != this.PageCount) { this.PageIndex++; return true; } return false; } public bool Previous() { if (this.PageIndex != 1) { this.PageIndex--; return true; } return false; } public void FirstPage() { if (this.PageIndex != 1) { this.PageIndex = 1; } } public void LastPage() { if (this.PageIndex != this.PageCount) { this.PageIndex = this.PageCount; } } public void Reload() { this.i_PageIndex = 1; this.i_RecordsPerPage = DEFAULT_LIMIT; this.Refresh(); } } }
PrasatecDevelopment/curve
alpha/0.1.230.0/Prasatec.Cu2Com/Data/UserResetCollection.cs
C#
gpl-3.0
2,630
// (C) Copyright 2009, Chong Wang, David Blei and Li Fei-Fei // written by Chong Wang, chongw@cs.princeton.edu // This file is part of slda. // slda 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. // slda 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 <stdio.h> #include <string.h> #include "corpus.h" #include "utils.h" #include "maslda.h" void help( void ) { printf("usage: maslda [est] [data] [answers] [settings] [alpha] [tau] [k] [random/seeded/model_path] [seed] [directory]\n"); printf(" maslda [estinf] [data] [answers] [settings] [alpha] [tau] [k] [random/seeded/model_path] [seed] [directory]\n"); printf(" maslda [inf] [data] [label] [settings] [model] [directory]\n"); } int main(int argc, char* argv[]) { if (argc < 2) { help(); return 0; } if (strcmp(argv[1], "est") == 0) { corpus c; char * data_filename = argv[2]; char * answers_filename = argv[3]; settings setting; char * setting_filename = argv[4]; printf("setting_filename %s\n", setting_filename); if(!setting.read_settings(setting_filename)) return 0; int labels_file = c.read_data(data_filename, answers_filename, 1, setting.LABELS_TRN_FILE); double alpha = atof(argv[5]); printf("alpha %lf\n", alpha); double tau = atof(argv[6]); printf("tau %lf\n", tau); int num_topics = atoi(argv[7]); printf("number of topics is %d\n", num_topics); char * init_method = argv[8]; double init_seed = atof(argv[9]); char * directory = argv[10]; printf("models will be saved in %s\n", directory); make_directory(directory); slda model; model.init(alpha, tau, num_topics, &c, &setting, init_seed, labels_file); model.v_em(&c, init_method, directory, &setting); } if (strcmp(argv[1], "estinf") == 0) { corpus c; char * data_filename = argv[2]; char * answers_filename = argv[3]; settings setting; char * setting_filename = argv[4]; printf("setting_filename %s\n", setting_filename); if(!setting.read_settings(setting_filename)) return 0; int labels_file = c.read_data(data_filename, answers_filename, 2, setting.LABELS_TRN_FILE); double alpha = atof(argv[5]); printf("alpha %lf\n", alpha); double tau = atof(argv[6]); printf("tau %lf\n", tau); int num_topics = atoi(argv[7]); printf("number of topics is %d\n", num_topics); char * init_method = argv[8]; double init_seed = atof(argv[9]); char * directory = argv[10]; printf("models will be saved in %s\n", directory); make_directory(directory); slda model; model.init(alpha, tau, num_topics, &c, &setting, init_seed, labels_file); model.v_em(&c, init_method, directory, &setting); model.infer_only(&c, directory); } if (strcmp(argv[1], "inf") == 0) { corpus c; char * data_filename = argv[2]; char * answers_filename = argv[3]; c.read_data(data_filename, answers_filename, 0, NULL); settings setting; char * setting_filename = argv[4]; setting.read_settings(setting_filename); char * model_filename = argv[5]; char * directory = argv[6]; printf("\nresults will be saved in %s\n", directory); make_directory(directory); slda model; model.load_model(model_filename, &setting); model.infer_only(&c, directory); } return 0; }
fmpr/MA-sLDAr
MA-sLDAr (smooth)/main.cpp
C++
gpl-3.0
4,275
/** * MegaMek - Copyright (C) 2004,2005 Ben Mazur (bmazur@sev.org) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package megamek.common.weapons; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Vector; import megamek.common.Aero; import megamek.common.AmmoType; import megamek.common.BattleArmor; import megamek.common.Building; import megamek.common.Compute; import megamek.common.Coords; import megamek.common.Entity; import megamek.common.EquipmentMode; import megamek.common.EquipmentType; import megamek.common.HitData; import megamek.common.IAimingModes; import megamek.common.IGame; import megamek.common.ITerrain; import megamek.common.Infantry; import megamek.common.LosEffects; import megamek.common.Mech; import megamek.common.Mounted; import megamek.common.RangeType; import megamek.common.Report; import megamek.common.TagInfo; import megamek.common.TargetRoll; import megamek.common.Targetable; import megamek.common.Terrains; import megamek.common.ToHitData; import megamek.common.WeaponType; import megamek.common.actions.WeaponAttackAction; import megamek.common.options.OptionsConstants; import megamek.server.Server; import megamek.server.Server.DamageType; import megamek.server.SmokeCloud; /** * @author Andrew Hunter A basic, simple attack handler. May or may not work for * any particular weapon; must be overloaded to support special rules. */ public class WeaponHandler implements AttackHandler, Serializable { private static final long serialVersionUID = 7137408139594693559L; public ToHitData toHit; protected HitData hit; public WeaponAttackAction waa; public int roll; protected boolean isJammed = false; protected IGame game; protected transient Server server; // must not save the server protected boolean bMissed; protected boolean bSalvo = false; protected boolean bGlancing = false; protected boolean bDirect = false; protected boolean nukeS2S = false; protected WeaponType wtype; protected String typeName; protected Mounted weapon; protected Entity ae; protected Targetable target; protected int subjectId; protected int nRange; protected int nDamPerHit; protected int attackValue; protected boolean throughFront; protected boolean underWater; protected boolean announcedEntityFiring = false; protected boolean missed = false; protected DamageType damageType; protected int generalDamageType = HitData.DAMAGE_NONE; protected Vector<Integer> insertedAttacks = new Vector<Integer>(); protected int nweapons; // for capital fighters/fighter squadrons protected int nweaponsHit; // for capital fighters/fighter squadrons protected boolean secondShot = false; protected int numRapidFireHits; protected String sSalvoType = " shot(s) "; protected int nSalvoBonus = 0; /** * Keeps track of whether we are processing the first hit in a series of * hits (like for cluster weapons) */ protected boolean firstHit = true; /** * Boolean flag that determines whether or not this attack is part of a * strafing run. */ protected boolean isStrafing = false; /** * Boolean flag that determiens if this shot was the first one by a * particular weapon in a strafing run. Used to ensure that heat is only * added once. */ protected boolean isStrafingFirstShot = false; /** * return the <code>int</code> Id of the attacking <code>Entity</code> */ public int getAttackerId() { return ae.getId(); } /** * Do we care about the specified phase? */ public boolean cares(IGame.Phase phase) { if (phase == IGame.Phase.PHASE_FIRING) { return true; } return false; } /** * @param vPhaseReport * - A <code>Vector</code> containing the phasereport. * @return a <code>boolean</code> value indicating wether or not the attack * misses because of a failed check. */ protected boolean doChecks(Vector<Report> vPhaseReport) { return false; } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); server = Server.getServerInstance(); } /** * @return a <code>boolean</code> value indicating wether or not this attack * needs further calculating, like a missed shot hitting a building, * or an AMS only shooting down some missiles. */ protected boolean handleSpecialMiss(Entity entityTarget, boolean targetInBuilding, Building bldg, Vector<Report> vPhaseReport) { // Shots that miss an entity can set fires. // Buildings can't be accidentally ignited, // and some weapons can't ignite fires. if ((entityTarget != null) && ((bldg == null) && (wtype.getFireTN() != TargetRoll.IMPOSSIBLE))) { server.tryIgniteHex(target.getPosition(), subjectId, false, false, new TargetRoll(wtype.getFireTN(), wtype.getName()), 3, vPhaseReport); } // shots that miss an entity can also potential cause explosions in a // heavy industrial hex server.checkExplodeIndustrialZone(target.getPosition(), vPhaseReport); // BMRr, pg. 51: "All shots that were aimed at a target inside // a building and miss do full damage to the building instead." if (!targetInBuilding || (toHit.getValue() == TargetRoll.AUTOMATIC_FAIL)) { return false; } return true; } /** * Calculate the number of hits * * @param vPhaseReport * - the <code>Vector</code> containing the phase report. * @return an <code>int</code> containing the number of hits. */ protected int calcHits(Vector<Report> vPhaseReport) { // normal BA attacks (non-swarm, non single-trooper weapons) // do more than 1 hit if ((ae instanceof BattleArmor) && (weapon.getLocation() == BattleArmor.LOC_SQUAD) && !(weapon.isSquadSupportWeapon()) && !(ae.getSwarmTargetId() == target.getTargetId())) { bSalvo = true; int toReturn = allShotsHit() ? ((BattleArmor) ae) .getShootingStrength() : Compute .missilesHit(((BattleArmor) ae).getShootingStrength()); Report r = new Report(3325); r.newlines = 0; r.subject = subjectId; r.add(toReturn); r.add(" troopers "); r.add(toHit.getTableDesc()); vPhaseReport.add(r); return toReturn; } return 1; } /** * Calculate the clustering of the hits * * @return a <code>int</code> value saying how much hits are in each cluster * of damage. */ protected int calcnCluster() { return 1; } protected int calcnClusterAero(Entity entityTarget) { if (usesClusterTable() && !ae.isCapitalFighter() && (entityTarget != null) && !entityTarget.isCapitalScale()) { return 5; } else { return 1; } } protected int[] calcAeroDamage(Entity entityTarget, Vector<Report> vPhaseReport) { // Now I need to adjust this for attacks on aeros because they use // attack values and different rules // this will work differently for cluster and non-cluster // weapons, and differently for capital fighter/fighter // squadrons if (game.getOptions().booleanOption("aero_sanity")) { // everything will use the normal hits and clusters for hits weapon // unless // we have a squadron or capital scale entity int reportSize = vPhaseReport.size(); int hits = calcHits(vPhaseReport); int nCluster = calcnCluster(); if (ae.isCapitalFighter()) { Vector<Report> throwAwayReport = new Vector<Report>(); // for capital scale fighters, each non-cluster weapon hits a // different location bSalvo = true; hits = 1; if (nweapons > 1) { if (allShotsHit()) { nweaponsHit = nweapons; } else { nweaponsHit = Compute.missilesHit(nweapons, ((Aero) ae).getClusterMods()); } if (usesClusterTable()) { // remove the last reports because they showed the // number of shots that hit while (vPhaseReport.size() > reportSize) { vPhaseReport.remove(vPhaseReport.size() - 1); } // nDamPerHit = 1; hits = 0; for (int i = 0; i < nweaponsHit; i++) { hits += calcHits(throwAwayReport); } Report r = new Report(3325); r.subject = subjectId; r.add(hits); r.add(sSalvoType); r.add(toHit.getTableDesc()); r.newlines = 0; vPhaseReport.add(r); } else { nCluster = 1; Report r = new Report(3325); r.subject = subjectId; r.add(nweaponsHit); r.add(" weapon(s) "); r.add(" "); r.newlines = 0; hits = nweaponsHit; vPhaseReport.add(r); } } } int[] results = new int[2]; results[0] = hits; results[1] = nCluster; return results; } else { int hits = 1; int nCluster = calcnClusterAero(entityTarget); if (ae.isCapitalFighter()) { bSalvo = false; if (nweapons > 1) { nweaponsHit = Compute.missilesHit(nweapons, ((Aero) ae).getClusterMods()); Report r = new Report(3325); r.subject = subjectId; r.add(nweaponsHit); r.add(" weapon(s) "); r.add(" "); r.newlines = 0; vPhaseReport.add(r); } nDamPerHit = attackValue * nweaponsHit; hits = 1; nCluster = 1; } else if (nCluster > 1) { bSalvo = true; nDamPerHit = 1; hits = attackValue; } else { bSalvo = false; nDamPerHit = attackValue; hits = 1; nCluster = 1; } int[] results = new int[2]; results[0] = hits; results[1] = nCluster; return results; } } /** * handle this weapons firing * * @return a <code>boolean</code> value indicating whether this should be * kept or not */ public boolean handle(IGame.Phase phase, Vector<Report> vPhaseReport) { if (!cares(phase)) { return true; } boolean heatAdded = false; int numAttacks = 1; if (game.getOptions().booleanOption("uac_tworolls") && ((wtype.getAmmoType() == AmmoType.T_AC_ULTRA) || (wtype .getAmmoType() == AmmoType.T_AC_ULTRA_THB)) && !weapon.curMode().equals("Single")) { numAttacks = 2; } insertAttacks(phase, vPhaseReport); Entity entityTarget = (target.getTargetType() == Targetable.TYPE_ENTITY) ? (Entity) target : null; final boolean targetInBuilding = Compute.isInBuilding(game, entityTarget); if (entityTarget != null) { ae.setLastTarget(entityTarget.getId()); ae.setLastTargetDisplayName(entityTarget.getDisplayName()); } // Which building takes the damage? Building bldg = game.getBoard().getBuildingAt(target.getPosition()); String number = nweapons > 1 ? " (" + nweapons + ")" : ""; for (int i = numAttacks; i > 0; i--) { // Report weapon attack and its to-hit value. Report r = new Report(3115); r.indent(); r.newlines = 0; r.subject = subjectId; r.add(wtype.getName() + number); if (entityTarget != null) { if ((wtype.getAmmoType() != AmmoType.T_NA) && (weapon.getLinked() != null) && (weapon.getLinked().getType() instanceof AmmoType)) { AmmoType atype = (AmmoType) weapon.getLinked().getType(); if (atype.getMunitionType() != AmmoType.M_STANDARD) { r.messageId = 3116; r.add(atype.getSubMunitionName()); } } r.addDesc(entityTarget); } else { r.messageId = 3120; r.add(target.getDisplayName(), true); } vPhaseReport.addElement(r); if (toHit.getValue() == TargetRoll.IMPOSSIBLE) { r = new Report(3135); r.subject = subjectId; r.add(toHit.getDesc()); vPhaseReport.addElement(r); return false; } else if (toHit.getValue() == TargetRoll.AUTOMATIC_FAIL) { r = new Report(3140); r.newlines = 0; r.subject = subjectId; r.add(toHit.getDesc()); vPhaseReport.addElement(r); } else if (toHit.getValue() == TargetRoll.AUTOMATIC_SUCCESS) { r = new Report(3145); r.newlines = 0; r.subject = subjectId; r.add(toHit.getDesc()); vPhaseReport.addElement(r); } else { // roll to hit r = new Report(3150); r.newlines = 0; r.subject = subjectId; r.add(toHit.getValue()); vPhaseReport.addElement(r); } // dice have been rolled, thanks r = new Report(3155); r.newlines = 0; r.subject = subjectId; r.add(roll); vPhaseReport.addElement(r); // do we hit? bMissed = roll < toHit.getValue(); // are we a glancing hit? if (game.getOptions().booleanOption("tacops_glancing_blows")) { if (roll == toHit.getValue()) { bGlancing = true; r = new Report(3186); r.subject = ae.getId(); r.newlines = 0; vPhaseReport.addElement(r); } else { bGlancing = false; } } else { bGlancing = false; } // Set Margin of Success/Failure. toHit.setMoS(roll - Math.max(2, toHit.getValue())); bDirect = game.getOptions().booleanOption("tacops_direct_blow") && ((toHit.getMoS() / 3) >= 1) && (entityTarget != null); if (bDirect) { r = new Report(3189); r.subject = ae.getId(); r.newlines = 0; vPhaseReport.addElement(r); } // Do this stuff first, because some weapon's miss report reference // the // amount of shots fired and stuff. nDamPerHit = calcDamagePerHit(); if (!heatAdded) { addHeat(); heatAdded = true; } attackValue = calcAttackValue(); // Any necessary PSRs, jam checks, etc. // If this boolean is true, don't report // the miss later, as we already reported // it in doChecks boolean missReported = doChecks(vPhaseReport); if (missReported) { bMissed = true; } // Do we need some sort of special resolution (minefields, // artillery, if (specialResolution(vPhaseReport, entityTarget) && (i < 2)) { return false; } if (bMissed && !missReported) { if (game.getOptions().booleanOption("uac_tworolls") && ((wtype.getAmmoType() == AmmoType.T_AC_ULTRA) || (wtype .getAmmoType() == AmmoType.T_AC_ULTRA_THB)) && (i == 2)) { reportMiss(vPhaseReport, true); } else { reportMiss(vPhaseReport); } // Works out fire setting, AMS shots, and whether continuation // is // necessary. if (!handleSpecialMiss(entityTarget, targetInBuilding, bldg, vPhaseReport) && (i < 2)) { return false; } } // yeech. handle damage. . different weapons do this in very // different // ways int nCluster = calcnCluster(); int id = vPhaseReport.size(); int hits = calcHits(vPhaseReport); if (target.isAirborne() || game.getBoard().inSpace()) { // if we added a line to the phase report for calc hits, remove // it now while (vPhaseReport.size() > id) { vPhaseReport.removeElementAt(vPhaseReport.size() - 1); } int[] aeroResults = calcAeroDamage(entityTarget, vPhaseReport); hits = aeroResults[0]; nCluster = aeroResults[1]; } // We have to adjust the reports on a miss, so they line up if (bMissed && id != vPhaseReport.size()) { vPhaseReport.get(id - 1).newlines--; vPhaseReport.get(id).indent(2); vPhaseReport.get(vPhaseReport.size() - 1).newlines++; } if (!bMissed) { // The building shields all units from a certain amount of // damage. // The amount is based upon the building's CF at the phase's // start. int bldgAbsorbs = 0; if (targetInBuilding && (bldg != null)) { bldgAbsorbs = bldg.getAbsorbtion(target.getPosition()); } // Make sure the player knows when his attack causes no damage. if (hits == 0) { r = new Report(3365); r.subject = subjectId; vPhaseReport.addElement(r); } // for each cluster of hits, do a chunk of damage while (hits > 0) { int nDamage; if ((target.getTargetType() == Targetable.TYPE_HEX_TAG) || (target.getTargetType() == Targetable.TYPE_BLDG_TAG)) { int priority = 1; EquipmentMode mode = (weapon.curMode()); if (mode != null) { if (mode.getName() == "1-shot") { priority = 1; } else if (mode.getName() == "2-shot") { priority = 2; } else if (mode.getName() == "3-shot") { priority = 3; } else if (mode.getName() == "4-shot") { priority = 4; } } TagInfo info = new TagInfo(ae.getId(), target.getTargetType(), target, priority, false); game.addTagInfo(info); r = new Report(3390); r.subject = subjectId; vPhaseReport.addElement(r); hits = 0; } // targeting a hex for igniting if ((target.getTargetType() == Targetable.TYPE_HEX_IGNITE) || (target.getTargetType() == Targetable.TYPE_BLDG_IGNITE)) { handleIgnitionDamage(vPhaseReport, bldg, hits); hits = 0; } // targeting a hex for clearing if (target.getTargetType() == Targetable.TYPE_HEX_CLEAR) { nDamage = nDamPerHit * hits; handleClearDamage(vPhaseReport, bldg, nDamage); hits = 0; } // Targeting a building. if (target.getTargetType() == Targetable.TYPE_BUILDING) { // The building takes the full brunt of the attack. nDamage = nDamPerHit * hits; handleBuildingDamage(vPhaseReport, bldg, nDamage, target.getPosition()); hits = 0; } if (entityTarget != null) { handleEntityDamage(entityTarget, vPhaseReport, bldg, hits, nCluster, bldgAbsorbs); server.creditKill(entityTarget, ae); hits -= nCluster; firstHit = false; } } // Handle the next cluster. } else { // We missed, but need to handle special miss cases // When shooting at a non-infantry unit in a building and the // shot misses, the building is damaged instead, TW pg 171 int dist = ae.getPosition().distance(target.getPosition()); if (targetInBuilding && !(entityTarget instanceof Infantry) && dist == 1) { r = new Report(6429); r.indent(2); r.subject = ae.getId(); r.newlines--; vPhaseReport.add(r); int nDamage = nDamPerHit * hits; // We want to set bSalvo to true to prevent // handleBuildingDamage from reporting a hit boolean savedSalvo = bSalvo; bSalvo = true; handleBuildingDamage(vPhaseReport, bldg, nDamage, target.getPosition()); bSalvo = savedSalvo; hits = 0; } } if (game.getOptions().booleanOption("uac_tworolls") && ((wtype.getAmmoType() == AmmoType.T_AC_ULTRA) || (wtype .getAmmoType() == AmmoType.T_AC_ULTRA_THB)) && (i == 2)) { // Jammed weapon doesn't get 2nd shot... if (isJammed) { r = new Report(9905); r.indent(); r.subject = ae.getId(); vPhaseReport.addElement(r); i--; } else { // If not jammed, it gets the second shot... r = new Report(9900); r.indent(); r.subject = ae.getId(); vPhaseReport.addElement(r); if (null != ae.getCrew()) { roll = ae.getCrew().rollGunnerySkill(); } else { roll = Compute.d6(2); } } } } Report.addNewline(vPhaseReport); return false; } /** * Calculate the damage per hit. * * @return an <code>int</code> representing the damage dealt per hit. */ protected int calcDamagePerHit() { double toReturn = wtype.getDamage(nRange); // Check for BA vs BA weapon effectiveness, if option is on if (game.getOptions().booleanOption("tacops_ba_vs_ba") && (target instanceof BattleArmor)) { // We don't check to make sure the attacker is BA, as most weapons // will return their normal damage. toReturn = Compute.directBlowBADamage(toReturn, wtype.getBADamageClass(), (BattleArmor) target); } // we default to direct fire weapons for anti-infantry damage if ((target instanceof Infantry) && !(target instanceof BattleArmor)) { toReturn = Compute.directBlowInfantryDamage(toReturn, bDirect ? toHit.getMoS() / 3 : 0, wtype.getInfantryDamageClass(), ((Infantry) target).isMechanized()); } else if (bDirect) { toReturn = Math.min(toReturn + (toHit.getMoS() / 3), toReturn * 2); } if (bGlancing) { // Round up glancing blows against conventional infantry if ((target instanceof Infantry) && !(target instanceof BattleArmor)) { toReturn = (int) Math.ceil(toReturn / 2.0); } else { toReturn = (int) Math.floor(toReturn / 2.0); } } if (game.getOptions().booleanOption(OptionsConstants.AC_TAC_OPS_RANGE) && (nRange > wtype.getRanges(weapon)[RangeType.RANGE_LONG])) { toReturn = (int) Math.floor(toReturn * .75); } if (game.getOptions().booleanOption( OptionsConstants.AC_TAC_OPS_LOS_RANGE) && (nRange > wtype.getRanges(weapon)[RangeType.RANGE_EXTREME])) { toReturn = (int) Math.floor(toReturn * .5); } return (int) toReturn; } /** * Calculate the attack value based on range * * @return an <code>int</code> representing the attack value at that range. */ protected int calcAttackValue() { int av = 0; // if we have a ground firing unit, then AV should not be determined by // aero range brackets if (!ae.isAirborne() || game.getOptions().booleanOption("uac_tworolls")) { if (usesClusterTable()) { // for cluster weapons just use the short range AV av = wtype.getRoundShortAV(); } else { // otherwise just use the full weapon damage by range av = wtype.getDamage(nRange); } } else { // we have an airborne attacker, so we need to use aero range // brackets int range = RangeType.rangeBracket(nRange, wtype.getATRanges(), true, false); if (range == WeaponType.RANGE_SHORT) { av = wtype.getRoundShortAV(); } else if (range == WeaponType.RANGE_MED) { av = wtype.getRoundMedAV(); } else if (range == WeaponType.RANGE_LONG) { av = wtype.getRoundLongAV(); } else if (range == WeaponType.RANGE_EXT) { av = wtype.getRoundExtAV(); } } if (bDirect) { av = Math.min(av + (toHit.getMoS() / 3), av * 2); } if (bGlancing) { av = (int) Math.floor(av / 2.0); } av = (int) Math.floor(getBracketingMultiplier() * av); return av; } /** * * adjustment factor on attack value for fighter squadrons */ protected double getBracketingMultiplier() { double mult = 1.0; if (wtype.hasModes() && weapon.curMode().equals("Bracket 80%")) { mult = 0.8; } if (wtype.hasModes() && weapon.curMode().equals("Bracket 60%")) { mult = 0.6; } if (wtype.hasModes() && weapon.curMode().equals("Bracket 40%")) { mult = 0.4; } return mult; } /* * Return the capital missile target for criticals. Zero if not a capital * missile */ protected int getCapMisMod() { return 0; } /** * Handles potential damage to partial cover that absorbs a shot. The * <code>ToHitData</code> is checked to what if there is any damagable cover * to be hit, and if so which cover gets hit (there are two possibilities in * some cases, such as 75% partial cover). The method then takes care of * assigning damage to the cover. Buildings are damaged directly, while * dropships call the <code>handleEntityDamage</code> method. * * @param entityTarget * The target Entity * @param vPhaseReport * @param pcHit * @param bldg * @param hits * @param nCluster * @param bldgAbsorbs */ protected void handlePartialCoverHit(Entity entityTarget, Vector<Report> vPhaseReport, HitData pcHit, Building bldg, int hits, int nCluster, int bldgAbsorbs) { // Report the hit and table description, if this isn't part of a salvo Report r; if (!bSalvo) { r = new Report(3405); r.subject = subjectId; r.add(toHit.getTableDesc()); r.add(entityTarget.getLocationAbbr(pcHit)); vPhaseReport.addElement(r); if (weapon.isRapidfire()) { r.newlines = 0; r = new Report(3225); r.subject = subjectId; r.add(numRapidFireHits * 3); vPhaseReport.add(r); } } else { // Keep spacing consistent Report.addNewline(vPhaseReport); } r = new Report(3460); r.subject = subjectId; r.add(entityTarget.getShortName()); r.add(entityTarget.getLocationAbbr(pcHit)); r.indent(2); vPhaseReport.addElement(r); int damagableCoverType = LosEffects.DAMAGABLE_COVER_NONE; Building coverBuilding = null; Entity coverDropship = null; Coords coverLoc = null; // Determine if there is primary and secondary cover, // and then determine which one gets hit if ((toHit.getCover() == LosEffects.COVER_75RIGHT || toHit.getCover() == LosEffects.COVER_75LEFT) || // 75% cover has a primary and secondary (toHit.getCover() == LosEffects.COVER_HORIZONTAL && toHit .getDamagableCoverTypeSecondary() != LosEffects.DAMAGABLE_COVER_NONE)) { // Horiztonal cover provided by two 25%'s, so primary and secondary int hitLoc = pcHit.getLocation(); // Primary stores the left side, from the perspective of the // attacker if (hitLoc == Mech.LOC_RLEG || hitLoc == Mech.LOC_RT || hitLoc == Mech.LOC_RARM) { // Left side is primary damagableCoverType = toHit.getDamagableCoverTypePrimary(); coverBuilding = toHit.getCoverBuildingPrimary(); coverDropship = toHit.getCoverDropshipPrimary(); coverLoc = toHit.getCoverLocPrimary(); } else { // If not left side, then right side, which is secondary damagableCoverType = toHit.getDamagableCoverTypeSecondary(); coverBuilding = toHit.getCoverBuildingSecondary(); coverDropship = toHit.getCoverDropshipSecondary(); coverLoc = toHit.getCoverLocSecondary(); } } else { // Only primary cover exists damagableCoverType = toHit.getDamagableCoverTypePrimary(); coverBuilding = toHit.getCoverBuildingPrimary(); coverDropship = toHit.getCoverDropshipPrimary(); coverLoc = toHit.getCoverLocPrimary(); } // Check if we need to damage the cover that absorbed the hit. if (damagableCoverType == LosEffects.DAMAGABLE_COVER_DROPSHIP) { // We need to adjust some state and then restore it later // This allows us to make a call to handleEntityDamage ToHitData savedToHit = toHit; int savedAimingMode = waa.getAimingMode(); waa.setAimingMode(IAimingModes.AIM_MODE_NONE); int savedAimedLocation = waa.getAimedLocation(); waa.setAimedLocation(Entity.LOC_NONE); boolean savedSalvo = bSalvo; bSalvo = true; // Create new toHitData toHit = new ToHitData(0, "", ToHitData.HIT_NORMAL, Compute.targetSideTable(ae, coverDropship)); // Report cover was damaged int sizeBefore = vPhaseReport.size(); r = new Report(3465); r.subject = subjectId; r.add(coverDropship.getShortName()); vPhaseReport.add(r); // Damage the dropship handleEntityDamage(coverDropship, vPhaseReport, bldg, hits, nCluster, bldgAbsorbs); // Remove a blank line in the report list if (vPhaseReport.elementAt(sizeBefore).newlines > 0) vPhaseReport.elementAt(sizeBefore).newlines--; // Indent reports related to the damage absorption while (sizeBefore < vPhaseReport.size()) { vPhaseReport.elementAt(sizeBefore).indent(3); sizeBefore++; } // Restore state toHit = savedToHit; waa.setAimingMode(savedAimingMode); waa.setAimedLocation(savedAimedLocation); bSalvo = savedSalvo; // Damage a building that blocked a shot } else if (damagableCoverType == LosEffects.DAMAGABLE_COVER_BUILDING) { // Normal damage int nDamage = nDamPerHit * Math.min(nCluster, hits); Vector<Report> buildingReport = server.damageBuilding( coverBuilding, nDamage, " blocks the shot and takes ", coverLoc); for (Report report : buildingReport) { report.subject = subjectId; report.indent(); } vPhaseReport.addAll(buildingReport); // Damage any infantry in the building. Vector<Report> infantryReport = server.damageInfantryIn( coverBuilding, nDamage, coverLoc, wtype.getInfantryDamageClass()); for (Report report : infantryReport) { report.indent(2); } vPhaseReport.addAll(infantryReport); } missed = true; } /** * Handle damage against an entity, called once per hit by default. * * @param entityTarget * @param vPhaseReport * @param bldg * @param hits * @param nCluster * @param bldgAbsorbs */ protected void handleEntityDamage(Entity entityTarget, Vector<Report> vPhaseReport, Building bldg, int hits, int nCluster, int bldgAbsorbs) { int nDamage; missed = false; hit = entityTarget.rollHitLocation(toHit.getHitTable(), toHit.getSideTable(), waa.getAimedLocation(), waa.getAimingMode(), toHit.getCover()); hit.setGeneralDamageType(generalDamageType); hit.setCapital(wtype.isCapital()); hit.setBoxCars(roll == 12); hit.setCapMisCritMod(getCapMisMod()); hit.setFirstHit(firstHit); hit.setAttackerId(getAttackerId()); if (weapon.isWeaponGroup()) { hit.setSingleAV(attackValue); } boolean isIndirect = wtype.hasModes() && weapon.curMode().equals("Indirect"); if (!isIndirect && entityTarget.removePartialCoverHits(hit.getLocation(), toHit .getCover(), Compute.targetSideTable(ae, entityTarget, weapon.getCalledShot().getCall()))) { // Weapon strikes Partial Cover. handlePartialCoverHit(entityTarget, vPhaseReport, hit, bldg, hits, nCluster, bldgAbsorbs); return; } if (!bSalvo) { // Each hit in the salvo get's its own hit location. Report r = new Report(3405); r.subject = subjectId; r.add(toHit.getTableDesc()); r.add(entityTarget.getLocationAbbr(hit)); vPhaseReport.addElement(r); if (weapon.isRapidfire()) { r.newlines = 0; r = new Report(3225); r.subject = subjectId; r.add(numRapidFireHits * 3); vPhaseReport.add(r); } } else { Report.addNewline(vPhaseReport); } // for non-salvo shots, report that the aimed shot was successfull // before applying damage if (hit.hitAimedLocation() && !bSalvo) { Report r = new Report(3410); r.subject = subjectId; vPhaseReport.lastElement().newlines = 0; vPhaseReport.addElement(r); } // Resolve damage normally. nDamage = nDamPerHit * Math.min(nCluster, hits); if (bDirect) { hit.makeDirectBlow(toHit.getMoS() / 3); } // A building may be damaged, even if the squad is not. if (bldgAbsorbs > 0) { int toBldg = Math.min(bldgAbsorbs, nDamage); nDamage -= toBldg; Report.addNewline(vPhaseReport); Vector<Report> buildingReport = server.damageBuilding(bldg, toBldg, entityTarget.getPosition()); for (Report report : buildingReport) { report.subject = subjectId; } vPhaseReport.addAll(buildingReport); } nDamage = checkTerrain(nDamage, entityTarget, vPhaseReport); nDamage = checkLI(nDamage, entityTarget, vPhaseReport); // some buildings scale remaining damage that is not absorbed // TODO: this isn't quite right for castles brian if (null != bldg) { nDamage = (int) Math.floor(bldg.getDamageToScale() * nDamage); } // A building may absorb the entire shot. if (nDamage == 0) { Report r = new Report(3415); r.subject = subjectId; r.indent(2); r.addDesc(entityTarget); vPhaseReport.addElement(r); missed = true; } else { if (bGlancing) { hit.makeGlancingBlow(); } vPhaseReport .addAll(server.damageEntity(entityTarget, hit, nDamage, false, ae.getSwarmTargetId() == entityTarget .getId() ? DamageType.IGNORE_PASSENGER : damageType, false, false, throughFront, underWater, nukeS2S)); // for salvo shots, report that the aimed location was hit after // applying damage, because the location is first reported when // dealing the damage if (hit.hitAimedLocation() && bSalvo) { Report r = new Report(3410); r.subject = subjectId; vPhaseReport.lastElement().newlines = 0; vPhaseReport.addElement(r); } } // If a BA squad is shooting at infantry, damage may be random and need // to be rerolled for the next hit (if any) from the same attack. if ((ae instanceof BattleArmor) && (target instanceof Infantry)) { nDamPerHit = calcDamagePerHit(); } } protected void handleIgnitionDamage(Vector<Report> vPhaseReport, Building bldg, int hits) { if (!bSalvo) { // hits! Report r = new Report(2270); r.subject = subjectId; r.newlines = 0; vPhaseReport.addElement(r); } TargetRoll tn = new TargetRoll(wtype.getFireTN(), wtype.getName()); if (tn.getValue() != TargetRoll.IMPOSSIBLE) { Report.addNewline(vPhaseReport); server.tryIgniteHex(target.getPosition(), subjectId, false, false, tn, true, -1, vPhaseReport); } } protected void handleClearDamage(Vector<Report> vPhaseReport, Building bldg, int nDamage) { handleClearDamage(vPhaseReport, bldg, nDamage, true); } protected void handleClearDamage(Vector<Report> vPhaseReport, Building bldg, int nDamage, boolean hitReport) { if (!bSalvo && hitReport) { // hits! Report r = new Report(2270); r.subject = subjectId; vPhaseReport.addElement(r); } // report that damage was "applied" to terrain Report r = new Report(3385); r.indent(2); r.subject = subjectId; r.add(nDamage); vPhaseReport.addElement(r); // Any clear attempt can result in accidental ignition, even // weapons that can't normally start fires. that's weird. // Buildings can't be accidentally ignited. // TODO: change this for TacOps - now you roll another 2d6 first and on // a 5 or less // you do a normal ignition as though for intentional fires if ((bldg != null) && server.tryIgniteHex(target.getPosition(), subjectId, false, false, new TargetRoll(wtype.getFireTN(), wtype.getName()), 5, vPhaseReport)) { return; } Vector<Report> clearReports = server.tryClearHex(target.getPosition(), nDamage, subjectId); if (clearReports.size() > 0) { vPhaseReport.lastElement().newlines = 0; } vPhaseReport.addAll(clearReports); return; } protected void handleBuildingDamage(Vector<Report> vPhaseReport, Building bldg, int nDamage, Coords coords) { if (!bSalvo) { // hits! Report r = new Report(3390); r.subject = subjectId; vPhaseReport.addElement(r); } Report.addNewline(vPhaseReport); Vector<Report> buildingReport = server.damageBuilding(bldg, nDamage, coords); for (Report report : buildingReport) { report.subject = subjectId; } vPhaseReport.addAll(buildingReport); // Damage any infantry in the hex. vPhaseReport.addAll(server.damageInfantryIn(bldg, nDamage, coords, wtype.getInfantryDamageClass())); } protected boolean allShotsHit() { if ((((target.getTargetType() == Targetable.TYPE_BLDG_IGNITE) || (target .getTargetType() == Targetable.TYPE_BUILDING)) && (nRange <= 1)) || (target.getTargetType() == Targetable.TYPE_HEX_CLEAR)) { return true; } if (game.getOptions().booleanOption("aero_sanity") && target.getTargetType() == Targetable.TYPE_ENTITY && ((Entity) target).isCapitalScale() && !((Entity) target).isCapitalFighter()) { return true; } return false; } protected void reportMiss(Vector<Report> vPhaseReport) { reportMiss(vPhaseReport, false); } protected void reportMiss(Vector<Report> vPhaseReport, boolean singleNewline) { // Report the miss. Report r = new Report(3220); r.subject = subjectId; if (singleNewline) { r.newlines = 1; } else { r.newlines = 2; } vPhaseReport.addElement(r); } protected WeaponHandler() { // deserialization only } // Among other things, basically a refactored Server#preTreatWeaponAttack public WeaponHandler(ToHitData t, WeaponAttackAction w, IGame g, Server s) { damageType = DamageType.NONE; toHit = t; waa = w; game = g; ae = game.getEntity(waa.getEntityId()); weapon = ae.getEquipment(waa.getWeaponId()); wtype = (WeaponType) weapon.getType(); typeName = wtype.getInternalName(); target = game.getTarget(waa.getTargetType(), waa.getTargetId()); server = s; subjectId = getAttackerId(); nRange = Compute.effectiveDistance(game, ae, target); if (target instanceof Mech) { throughFront = Compute.isThroughFrontHex(game, ae.getPosition(), (Entity) target); } else { throughFront = true; } // is this an underwater attack on a surface naval vessel? underWater = toHit.getHitTable() == ToHitData.HIT_UNDERWATER; if (null != ae.getCrew()) { roll = ae.getCrew().rollGunnerySkill(); } else { roll = Compute.d6(2); } nweapons = getNumberWeapons(); nweaponsHit = 1; // use ammo when creating this, so it works when shooting the last shot // a unit has and we fire multiple weapons of the same type // TODO: need to adjust this for cases where not all the ammo is // available for (int i = 0; i < nweapons; i++) { useAmmo(); } if (target instanceof Entity) { ((Entity) target).addAttackedByThisTurn(w.getEntityId()); } } protected void useAmmo() { if (wtype.hasFlag(WeaponType.F_ONESHOT)) { weapon.setFired(true); } setDone(); } protected void setDone() { weapon.setUsedThisRound(true); } protected void addHeat() { if (!(toHit.getValue() == TargetRoll.IMPOSSIBLE)) { if (ae.usesWeaponBays() && !game.getOptions().booleanOption("heat_by_bay")) { int loc = weapon.getLocation(); boolean rearMount = weapon.isRearMounted(); if (!ae.hasArcFired(loc, rearMount)) { ae.heatBuildup += ae.getHeatInArc(loc, rearMount); ae.setArcFired(loc, rearMount); } } else { if (!isStrafing() || isStrafingFirstShot()) { ae.heatBuildup += (weapon.getCurrentHeat()); } } } } /** * Does this attack use the cluster hit table? necessary to determine how * Aero damage should be applied */ protected boolean usesClusterTable() { return false; } /** * special resolution, like minefields and arty * * @param vPhaseReport - a <code>Vector</code> containing the phase report * @param entityTarget - the <code>Entity</code> targeted, or <code>null</code>, if * no Entity targeted * @return true when done with processing, false when not */ protected boolean specialResolution(Vector<Report> vPhaseReport, Entity entityTarget) { return false; } public boolean announcedEntityFiring() { return announcedEntityFiring; } public void setAnnouncedEntityFiring(boolean announcedEntityFiring) { this.announcedEntityFiring = announcedEntityFiring; } public WeaponAttackAction getWaa() { return waa; } public int checkTerrain(int nDamage, Entity entityTarget, Vector<Report> vPhaseReport) { boolean isAboveWoods = ((entityTarget != null) && ((entityTarget .relHeight() >= 2) || (entityTarget.isAirborne()))); if (game.getOptions().booleanOption("tacops_woods_cover") && !isAboveWoods && (game.getBoard().getHex(entityTarget.getPosition()) .containsTerrain(Terrains.WOODS) || game.getBoard() .getHex(entityTarget.getPosition()) .containsTerrain(Terrains.JUNGLE)) && !(entityTarget.getSwarmAttackerId() == ae.getId())) { ITerrain woodHex = game.getBoard() .getHex(entityTarget.getPosition()) .getTerrain(Terrains.WOODS); ITerrain jungleHex = game.getBoard() .getHex(entityTarget.getPosition()) .getTerrain(Terrains.JUNGLE); int treeAbsorbs = 0; String hexType = ""; if (woodHex != null) { treeAbsorbs = woodHex.getLevel() * 2; hexType = "wooded"; } else if (jungleHex != null) { treeAbsorbs = jungleHex.getLevel() * 2; hexType = "jungle"; } // Do not absorb more damage than the weapon can do. treeAbsorbs = Math.min(nDamage, treeAbsorbs); nDamage = Math.max(0, nDamage - treeAbsorbs); server.tryClearHex(entityTarget.getPosition(), treeAbsorbs, ae.getId()); Report.addNewline(vPhaseReport); Report terrainReport = new Report(6427); terrainReport.subject = entityTarget.getId(); terrainReport.add(hexType); terrainReport.add(treeAbsorbs); terrainReport.indent(2); terrainReport.newlines = 0; vPhaseReport.add(terrainReport); } return nDamage; } /** * Check for Laser Inhibiting smoke clouds */ public int checkLI(int nDamage, Entity entityTarget, Vector<Report> vPhaseReport) { weapon = ae.getEquipment(waa.getWeaponId()); wtype = (WeaponType) weapon.getType(); ArrayList<Coords> coords = Coords.intervening(ae.getPosition(), entityTarget.getPosition()); int refrac = 0; double travel = 0; double range = ae.getPosition().distance(target.getPosition()); double atkLev = ae.relHeight(); double tarLev = entityTarget.relHeight(); double levDif = Math.abs(atkLev - tarLev); String hexType = "LASER inhibiting smoke"; // loop through all intervening coords. // If you could move this to compute.java, then remove - import // java.util.ArrayList; for (Coords curr : coords) { // skip hexes not actually on the board if (!game.getBoard().contains(curr)) { continue; } ITerrain smokeHex = game.getBoard().getHex(curr) .getTerrain(Terrains.SMOKE); if (game.getBoard().getHex(curr).containsTerrain(Terrains.SMOKE) && wtype.hasFlag(WeaponType.F_ENERGY) && ((smokeHex.getLevel() == SmokeCloud.SMOKE_LI_LIGHT) || (smokeHex .getLevel() == SmokeCloud.SMOKE_LI_HEAVY))) { int levit = ((game.getBoard().getHex(curr).getLevel()) + 2); // does the hex contain LASER inhibiting smoke? if ((tarLev > atkLev) && (levit >= ((travel * (levDif / range)) + atkLev))) { refrac++; } else if ((atkLev > tarLev) && (levit >= (((range - travel) * (levDif / range)) + tarLev))) { refrac++; } else if ((atkLev == tarLev) && (levit >= 0)) { refrac++; } travel++; } } if (refrac != 0) { // Damage reduced by 2 for each interviening smoke. refrac = (refrac * 2); // Do not absorb more damage than the weapon can do. (Are both of // these really necessary?) refrac = Math.min(nDamage, refrac); nDamage = Math.max(0, (nDamage - refrac)); Report.addNewline(vPhaseReport); Report fogReport = new Report(6427); fogReport.subject = entityTarget.getId(); fogReport.add(hexType); fogReport.add(refrac); fogReport.indent(2); fogReport.newlines = 0; vPhaseReport.add(fogReport); } return nDamage; } protected boolean canDoDirectBlowDamage() { return true; } /** * Insert any additionaly attacks that should occur before this attack */ protected void insertAttacks(IGame.Phase phase, Vector<Report> vPhaseReport) { return; } /** * @return the number of weapons of this type firing (for squadron weapon * groups) */ protected int getNumberWeapons() { return weapon.getNWeapons(); } /** * Restores the equipment from the name */ public void restore() { if (typeName == null) { typeName = wtype.getName(); } else { wtype = (WeaponType) EquipmentType.get(typeName); } if (wtype == null) { System.err .println("WeaponHandler.restore: could not restore equipment type \"" + typeName + "\""); } } protected int getClusterModifiers(boolean clusterRangePenalty) { int nMissilesModifier = nSalvoBonus; int[] ranges = wtype.getRanges(weapon); if (clusterRangePenalty && game.getOptions().booleanOption("tacops_clusterhitpen")) { if (nRange <= 1) { nMissilesModifier += 1; } else if (nRange <= ranges[RangeType.RANGE_MEDIUM]) { nMissilesModifier += 0; } else { nMissilesModifier -= 1; } } if (game.getOptions().booleanOption(OptionsConstants.AC_TAC_OPS_RANGE) && (nRange > ranges[RangeType.RANGE_LONG])) { nMissilesModifier -= 2; } if (game.getOptions().booleanOption(OptionsConstants.AC_TAC_OPS_LOS_RANGE) && (nRange > ranges[RangeType.RANGE_EXTREME])) { nMissilesModifier -= 3; } if (bGlancing) { nMissilesModifier -= 4; } if (bDirect) { nMissilesModifier += (toHit.getMoS() / 3) * 2; } if (game.getPlanetaryConditions().hasEMI()) { nMissilesModifier -= 2; } if (null != ae.getCrew()) { if (ae.getCrew().getOptions().booleanOption("sandblaster") && ae.getCrew().getOptions().stringOption("weapon_specialist") .equals(wtype.getName())) { if (nRange > ranges[RangeType.RANGE_MEDIUM]) { nMissilesModifier += 2; } else if (nRange > ranges[RangeType.RANGE_SHORT]) { nMissilesModifier += 3; } else { nMissilesModifier += 4; } } else if (ae.getCrew().getOptions().booleanOption("cluster_master")) { nMissilesModifier += 2; } else if (ae.getCrew().getOptions().booleanOption("cluster_hitter")) { nMissilesModifier += 1; } } return nMissilesModifier; } public boolean isStrafing() { return isStrafing; } public void setStrafing(boolean isStrafing) { this.isStrafing = isStrafing; } public boolean isStrafingFirstShot() { return isStrafingFirstShot; } public void setStrafingFirstShot(boolean isStrafingFirstShot) { this.isStrafingFirstShot = isStrafingFirstShot; } }
chvink/kilomek
megamek/src/megamek/common/weapons/WeaponHandler.java
Java
gpl-3.0
56,885
package org.ebookdroid.core; import android.graphics.Rect; import android.graphics.RectF; import com.foobnix.model.AppBook; import org.ebookdroid.common.settings.SettingsManager; import org.ebookdroid.common.settings.types.DocumentViewMode; import org.ebookdroid.common.settings.types.PageAlign; import org.ebookdroid.ui.viewer.IActivityController; public class HScrollController extends AbstractScrollController { public HScrollController(final IActivityController base) { super(base, DocumentViewMode.HORIZONTAL_SCROLL); } /** * {@inheritDoc} * * @see org.ebookdroid.ui.viewer.IViewController#calculateCurrentPage(org.ebookdroid.core.ViewState) */ @Override public final int calculateCurrentPage(final ViewState viewState, final int firstVisible, final int lastVisible) { int result = 0; long bestDistance = Long.MAX_VALUE; final int viewX = Math.round(viewState.viewRect.centerX()); final Iterable<Page> pages = firstVisible != -1 ? viewState.model.getPages(firstVisible, lastVisible + 1) : viewState.model.getPages(0); for (final Page page : pages) { final RectF bounds = viewState.getBounds(page); final int pageX = Math.round(bounds.centerX()); final long dist = Math.abs(pageX - viewX); if (dist < bestDistance) { bestDistance = dist; result = page.index.viewIndex; } } return result; } @Override public int getBottomScrollLimit() { return 0; } /** * {@inheritDoc} * * @see org.ebookdroid.ui.viewer.IViewController#getScrollLimits() */ @Override public final Rect getScrollLimits() { final int width = getWidth(); final int height = getHeight(); final Page lpo = model.getLastPageObject(); final float zoom = getBase().getZoomModel().getZoom(); final int right = lpo != null ? (int) lpo.getBounds(zoom).right - width : 0; final int bottom = (int) (height * zoom) - height; return new Rect(0, -height/2, right, bottom+height/2); } /** * {@inheritDoc} * * @see org.ebookdroid.ui.viewer.IViewController#invalidatePageSizes(org.ebookdroid.ui.viewer.IViewController.InvalidateSizeReason, * org.ebookdroid.core.Page) */ @Override public synchronized final void invalidatePageSizes(final InvalidateSizeReason reason, final Page changedPage) { if (!isInitialized) { return; } if (reason == InvalidateSizeReason.PAGE_ALIGN) { return; } final int height = getHeight(); final int width = getWidth(); final AppBook bookSettings = SettingsManager.getBookSettings(); final PageAlign pageAlign = DocumentViewMode.getPageAlign(bookSettings); if (changedPage == null) { float widthAccum = 0; for (final Page page : model.getPages()) { final RectF pageBounds = calcPageBounds(pageAlign, page.getAspectRatio(), width, height); pageBounds.offset(widthAccum, 0); page.setBounds(pageBounds); widthAccum += pageBounds.width() + 3; } } else { float widthAccum = changedPage.getBounds(1.0f).left; for (final Page page : model.getPages(changedPage.index.viewIndex)) { final RectF pageBounds = calcPageBounds(pageAlign, page.getAspectRatio(), width, height); pageBounds.offset(widthAccum, 0); page.setBounds(pageBounds); widthAccum += pageBounds.width() + 3; } } } @Override public RectF calcPageBounds(final PageAlign pageAlign, final float pageAspectRatio, final int width, final int height) { return new RectF(0, 0, height * pageAspectRatio, height); } }
foobnix/LirbiReader
app/src/main/java/org/ebookdroid/core/HScrollController.java
Java
gpl-3.0
3,996
def main(): """Instantiate a DockerStats object and collect stats.""" print('Docker Service Module') if __name__ == '__main__': main()
gomex/docker-zabbix
docker_service/__init__.py
Python
gpl-3.0
148
# ScratchABit - interactive disassembler # # Copyright (c) 2018 Paul Sokolovsky # # 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/>. import capstone import _any_capstone dis = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM) def PROCESSOR_ENTRY(): return _any_capstone.Processor("arm_32", dis)
pfalcon/ScratchABit
plugins/cpu/arm_32_arm_capstone.py
Python
gpl-3.0
891
package gui; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.WindowConstants; public class WorkFrame extends JFrame { /** * */ private static final long serialVersionUID = -7783509968212805832L; private final JFrame parent; public static int width, height; private static final File saveFile = new File("config" + File.separator + "windowResolutions"); /** * used to save the resolution for specific panes */ private String name; /** * * @param parent * @param pane * the content pane * @param paneName * required to save the panes resolution, should be unique */ public WorkFrame(JFrame parent, JComponent pane, String paneName) { super(); setBounds(100, 100, WorkFrame.width, height); setContentPane(pane); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setLocationRelativeTo(null); setResizable(true); this.parent = parent; name = paneName; // must be called after the name is set! Dimension dim = loadResolution(); if (dim != null) setSize(dim); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { saveResolution(getSize()); WorkFrame.this.parent.setEnabled(true); WorkFrame.this.parent.setVisible(true); } }); parent.setEnabled(false); parent.setVisible(false); setVisible(true); } public void saveResolution(Dimension d) { if (name == null) { ErrorHandle.popUp("Name for this Window is not set"); } try { boolean found = false; StringBuilder text = new StringBuilder(); NumberFormat formatter = new DecimalFormat("#0.00"); if (saveFile.exists()) { BufferedReader read = new BufferedReader(new FileReader(saveFile)); String line; while ((line = read.readLine()) != null) { if (line.contains(name)) { found = true; line = name + ":" + formatter.format(d.getHeight()) + ":" + formatter.format(d.getWidth()); System.out.println(line); } text.append(line + System.lineSeparator()); } read.close(); } else { if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } } if (!saveFile.exists() || !found) { text.append(name + ":" + formatter.format(d.getHeight()) + ":" + formatter.format(d.getWidth()) + System.lineSeparator()); System.out.println(text.toString()); } FileOutputStream fileOut = new FileOutputStream(saveFile); fileOut.write(text.toString().getBytes()); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } /** * * @return saved Dimension if available */ public Dimension loadResolution() { if (name == null) { ErrorHandle.popUp("Name for this Window is not set"); } Dimension d = null; NumberFormat format = NumberFormat.getNumberInstance(Locale.GERMAN); format.setMaximumFractionDigits(2); if (!saveFile.exists()) return d; try { BufferedReader read = new BufferedReader(new FileReader(saveFile)); String line; while ((line = read.readLine()) != null) { if (line.contains(name)) { String[] str = line.split(":", 3); d = new Dimension(); d.setSize(format.parse(str[2]).doubleValue(), format.parse(str[1]).doubleValue()); read.close(); return d; } } read.close(); } catch (IOException | ParseException e) { e.printStackTrace(); } return d; } }
otting/NebenkostenAssistent
src/gui/WorkFrame.java
Java
gpl-3.0
4,016
<?php class SiteOrigin_Panels_Widget_Animated_Image extends SiteOrigin_Panels_Widget { function __construct() { parent::__construct( __('Animated Image (Pootle)', 'siteorigin-panels'), array( 'description' => __('An image that animates in when it enters the screen.', 'siteorigin-panels'), 'default_style' => 'simple', ), array(), array( 'image' => array( 'type' => 'text', 'label' => __('Image URL', 'siteorigin-panels'), ), 'animation' => array( 'type' => 'select', 'label' => __('Animation', 'siteorigin-panels'), 'options' => array( 'fade' => __('Fade In', 'siteorigin-panels'), 'slide-up' => __('Slide Up', 'siteorigin-panels'), 'slide-down' => __('Slide Down', 'siteorigin-panels'), 'slide-left' => __('Slide Left', 'siteorigin-panels'), 'slide-right' => __('Slide Right', 'siteorigin-panels'), ) ), ) ); } function enqueue_scripts(){ static $enqueued = false; if(!$enqueued) { wp_enqueue_script('siteorigin-widgets-'.$this->origin_id.'-onscreen', plugin_dir_url(__FILE__).'js/onscreen.js', array('jquery'), POOTLEPAGE_VERSION); wp_enqueue_script('siteorigin-widgets-'.$this->origin_id, plugin_dir_url(__FILE__).'js/main.js', array('jquery'), POOTLEPAGE_VERSION); $enqueued = true; } } }
pootlepress/genesis-page-builder
widgets/widgets/animated-image/animated-image.php
PHP
gpl-3.0
1,322
package com.infox.sysmgr.entity.base; import java.io.Serializable; public class BaseField implements Serializable { private static final long serialVersionUID = 1L; private int hashCode = Integer.MIN_VALUE; // fields private java.lang.String name; private java.lang.String fieldType; private java.lang.String fieldDefault; private java.lang.String fieldProperty; private java.lang.String comment; private java.lang.String nullable; private java.lang.String extra; public int getHashCode() { return hashCode; } public void setHashCode(int hashCode) { this.hashCode = hashCode; } public java.lang.String getName() { return name; } public void setName(java.lang.String name) { this.name = name; } public java.lang.String getFieldType() { return fieldType; } public void setFieldType(java.lang.String fieldType) { this.fieldType = fieldType; } public java.lang.String getFieldDefault() { return fieldDefault; } public void setFieldDefault(java.lang.String fieldDefault) { this.fieldDefault = fieldDefault; } public java.lang.String getFieldProperty() { return fieldProperty; } public void setFieldProperty(java.lang.String fieldProperty) { this.fieldProperty = fieldProperty; } public java.lang.String getComment() { return comment; } public void setComment(java.lang.String comment) { this.comment = comment; } public java.lang.String getNullable() { return nullable; } public void setNullable(java.lang.String nullable) { this.nullable = nullable; } public java.lang.String getExtra() { return extra; } public void setExtra(java.lang.String extra) { this.extra = extra; } }
yhqmcq/infox
src/main/java/com/infox/sysmgr/entity/base/BaseField.java
Java
gpl-3.0
1,767
/* * This file is part of the GeMTC software for MTC model generation and * analysis. GeMTC is distributed from http://drugis.org/gemtc. * Copyright (C) 2009-2012 Gert van Valkenhoef. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.drugis.mtc.presentation.results; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.table.AbstractTableModel; import org.drugis.mtc.Parameter; import org.drugis.mtc.presentation.InconsistencyWrapper; import org.drugis.mtc.presentation.MTCModelWrapper; import org.drugis.mtc.summary.QuantileSummary; @SuppressWarnings("serial") public class NetworkVarianceTableModel extends AbstractTableModel { private static final int RANDOM_EFFECTS = 0; private final MTCModelWrapper<?> d_mtc; private final PropertyChangeListener d_listener; public NetworkVarianceTableModel(final MTCModelWrapper<?> mtc) { d_mtc = mtc; d_listener = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { fireTableDataChanged(); } }; if (isInconsistency()) { attachListener(((InconsistencyWrapper<?>) d_mtc).getInconsistencyVariance()); } attachListener(mtc.getRandomEffectsStandardDeviation()); } private void attachListener(final Parameter p) { final QuantileSummary quantileSummary = d_mtc.getQuantileSummary(p); if(quantileSummary != null) { quantileSummary.addPropertyChangeListener(d_listener); } } @Override public Class<?> getColumnClass(final int columnIndex) { if (columnIndex == 0) { return String.class; } else { return QuantileSummary.class; } } @Override public String getColumnName(final int column) { return column == 0 ? "Parameter" : "Median (95% CrI)"; } @Override public int getRowCount() { return isInconsistency() ? 2 : 1; } private boolean isInconsistency() { return (d_mtc instanceof InconsistencyWrapper); } @Override public Object getValueAt(final int row, final int col) { if (col == 0) { return getRowDescription(row); } else { return getEstimate(row); } } private QuantileSummary getEstimate(final int row) { return row == RANDOM_EFFECTS ? getRandomEffectsSummary() : getInconsistencySummary(); } private QuantileSummary getInconsistencySummary() { if (isInconsistency()) { final Parameter p = ((InconsistencyWrapper<?>) d_mtc).getInconsistencyVariance(); return d_mtc.getQuantileSummary(p); } return null; } private QuantileSummary getRandomEffectsSummary() { final Parameter p = d_mtc.getRandomEffectsStandardDeviation(); return d_mtc.getQuantileSummary(p); } private String getRowDescription(final int row) { if (row == RANDOM_EFFECTS) { return "Random Effects Standard Deviation"; } else { return "Inconsistency Standard Deviation"; } } @Override public int getColumnCount() { return 2; } }
drugis/mtc
mtc-gui/src/main/java/org/drugis/mtc/presentation/results/NetworkVarianceTableModel.java
Java
gpl-3.0
3,491
angular.module('app.travels', ['pascalprecht.translate']) .controller('TravelsCtrl', function($scope, $http, $ionicModal, $timeout, $ionicLoading, $filter) { $scope.loadMorePagination = true; $scope.travels = []; $scope.page = 0; $scope.doRefresh = function() { /* travels refresh: */ $http.get(urlapi + 'travels?page=' + $scope.page) .then(function(data) { console.log('data success travels'); console.log(data); // for browser console //$scope.travels = data.data; // for UI $scope.travels = $scope.travels.concat(data.data); $scope.$broadcast('scroll.refreshComplete'); //refresher stop $scope.$broadcast('scroll.infiniteScrollComplete'); if (data.data.length < 1) { console.log("setting loadMorePagination to false"); $scope.loadMorePagination = false; $scope.$broadcast('scroll.infiniteScrollComplete'); } }, function(data) { console.log('data error'); $scope.$broadcast('scroll.refreshComplete'); //refresher stop $ionicLoading.show({ template: 'Error connecting server', noBackdrop: true, duration: 2000 }); }); }; $scope.doRefresh(); $scope.paginationNext = function() { if ($scope.loadMorePagination == true) { $scope.page++; console.log($scope.page); $scope.doRefresh(); }else{ console.log("limit pagination reached"); $scope.$broadcast('scroll.infiniteScrollComplete'); } }; });
arnaucode/carsincommonApp
www/js/travels.js
JavaScript
gpl-3.0
1,615
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /******/(function (modules) { // webpackBootstrap /******/ // The module cache /******/var installedModules = {}; /******/ /******/ // The require function /******/function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/if (installedModules[moduleId]) { /******/return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/var module = installedModules[moduleId] = { /******/i: moduleId, /******/l: false, /******/exports: {} /******/ }; /******/ /******/ // Execute the module function /******/modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/module.l = true; /******/ /******/ // Return the exports of the module /******/return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/__webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/__webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/__webpack_require__.d = function (exports, name, getter) { /******/if (!__webpack_require__.o(exports, name)) { /******/Object.defineProperty(exports, name, { /******/configurable: false, /******/enumerable: true, /******/get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/__webpack_require__.n = function (module) { /******/var getter = module && module.__esModule ? /******/function getDefault() { return module['default']; } : /******/function getModuleExports() { return module; }; /******/__webpack_require__.d(getter, 'a', getter); /******/return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/__webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/__webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/return __webpack_require__(__webpack_require__.s = 34); /******/ })( /************************************************************************/ /******/{ /***/2: /***/function _(module, __webpack_exports__, __webpack_require__) { "use strict"; /** * File get-customize-action.js. * * Function to get the Customize action for a given panel. */ /* harmony default export */ __webpack_exports__["a"] = function (panel) { var _window$wp$i18n = window.wp.i18n, __ = _window$wp$i18n.__, sprintf = _window$wp$i18n.sprintf; var panelInstance = panel && panel.length ? window.wp.customize.panel.instance(panel) : undefined; if (panelInstance) { return sprintf(__('Customizing &#9656; %s', 'super-awesome-theme'), panelInstance.params.title); } return __('Customizing', 'super-awesome-theme'); }; /***/ }, /***/3: /***/function _(module, __webpack_exports__, __webpack_require__) { "use strict"; /** * File customize-controls-util.js. * * Class containing Customizer controls utility methods. */ var CustomizeControlsUtil = function () { function CustomizeControlsUtil(wpCustomize) { _classCallCheck(this, CustomizeControlsUtil); this.customizer = wpCustomize || window.wp.customize; } _createClass(CustomizeControlsUtil, [{ key: 'bindSetting', value: function bindSetting(settingId, callback) { this.customizer.instance(settingId, function (setting) { callback(setting.get()); setting.bind(function () { callback(setting.get()); }); }); } }, { key: 'bindSettingToComponents', value: function bindSettingToComponents(settingId, componentIds, callback, componentType) { var self = this; componentType = componentType || 'control'; function listenToSetting() { var components = Array.prototype.slice.call(arguments, 0, componentIds.length); self.bindSetting(settingId, function (value) { components.forEach(function (component) { callback(value, component); }); }); } this.customizer[componentType].instance.apply(this.customizer[componentType], componentIds.concat([listenToSetting])); } }, { key: 'bindSettingToPanels', value: function bindSettingToPanels(settingId, panelIds, callback) { this.bindSettingToComponents(settingId, panelIds, callback, 'panel'); } }, { key: 'bindSettingToSections', value: function bindSettingToSections(settingId, sectionIds, callback) { this.bindSettingToComponents(settingId, sectionIds, callback, 'section'); } }, { key: 'bindSettingToControls', value: function bindSettingToControls(settingId, controlIds, callback) { this.bindSettingToComponents(settingId, controlIds, callback, 'control'); } }, { key: 'bindSettings', value: function bindSettings(settingIds, callback) { function bindSettings() { var settings = Array.prototype.slice.call(arguments, 0, settingIds.length); var values = {}; function updateSetting(setting) { values[setting.id] = setting.get(); } settings.forEach(function (setting) { updateSetting(setting); setting.bind(function () { updateSetting(setting); callback(values); }); }); callback(values); } this.customizer.instance.apply(this.customizer, settingIds.concat([bindSettings])); } }, { key: 'bindSettingsToComponents', value: function bindSettingsToComponents(settingIds, componentIds, callback, componentType) { var self = this; componentType = componentType || 'control'; function listenToSettings() { var components = Array.prototype.slice.call(arguments, 0, componentIds.length); self.bindSettings(settingIds, function (values) { components.forEach(function (component) { callback(values, component); }); }); } this.customizer[componentType].instance.apply(this.customizer[componentType], componentIds.concat([listenToSettings])); } }, { key: 'bindSettingsToPanels', value: function bindSettingsToPanels(settingIds, panelIds, callback) { this.bindSettingsToComponents(settingIds, panelIds, callback, 'panel'); } }, { key: 'bindSettingsToSections', value: function bindSettingsToSections(settingIds, sectionIds, callback) { this.bindSettingsToComponents(settingIds, sectionIds, callback, 'section'); } }, { key: 'bindSettingsToControls', value: function bindSettingsToControls(settingIds, controlIds, callback) { this.bindSettingsToComponents(settingIds, controlIds, callback, 'control'); } }]); return CustomizeControlsUtil; }(); /* harmony default export */ __webpack_exports__["a"] = CustomizeControlsUtil; /***/ }, /***/34: /***/function _(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */var __WEBPACK_IMPORTED_MODULE_0__customize_customize_controls_util__ = __webpack_require__(3); /* harmony import */var __WEBPACK_IMPORTED_MODULE_1__customize_get_customize_action__ = __webpack_require__(2); /** * File sidebar.customize-controls.js. * * Theme Customizer handling for the sidebar. */ (function (wp, data) { var api = wp.customize; var util = new __WEBPACK_IMPORTED_MODULE_0__customize_customize_controls_util__["a" /* default */](api); var __ = wp.i18n.__; var sidebarModeDependants = ['sidebar_size', 'blog_sidebar_enabled']; if (data.displayShopSidebarEnabledSetting) { sidebarModeDependants.push('shop_sidebar_enabled'); } api.bind('ready', function () { api.when('sidebar_mode', 'sidebar_size', 'blog_sidebar_enabled', function (sidebarMode, sidebarSize, blogSidebarEnabled) { sidebarMode.transport = 'postMessage'; sidebarSize.transport = 'postMessage'; blogSidebarEnabled.transport = 'postMessage'; }); api.panel.instance('layout', function () { api.section.add(new api.Section('sidebar', { panel: 'layout', title: __('Sidebar', 'super-awesome-theme'), customizeAction: Object(__WEBPACK_IMPORTED_MODULE_1__customize_get_customize_action__["a" /* default */])('layout') })); api.control.add(new api.Control('sidebar_mode', { setting: 'sidebar_mode', section: 'sidebar', label: __('Sidebar Mode', 'super-awesome-theme'), description: __('Specify if and how the sidebar should be displayed.', 'super-awesome-theme'), type: 'radio', choices: data.sidebarModeChoices })); api.control.add(new api.Control('sidebar_size', { setting: 'sidebar_size', section: 'sidebar', label: __('Sidebar Size', 'super-awesome-theme'), description: __('Specify the width of the sidebar.', 'super-awesome-theme'), type: 'radio', choices: data.sidebarSizeChoices })); api.control.add(new api.Control('blog_sidebar_enabled', { setting: 'blog_sidebar_enabled', section: 'sidebar', label: __('Enable Blog Sidebar?', 'super-awesome-theme'), description: __('If you enable the blog sidebar, it will be shown beside your blog and single post content instead of the primary sidebar.', 'super-awesome-theme'), type: 'checkbox' })); if (data.displayShopSidebarEnabledSetting) { api.control.add(new api.Control('shop_sidebar_enabled', { setting: 'shop_sidebar_enabled', section: 'sidebar', label: __('Enable Shop Sidebar?', 'super-awesome-theme'), description: __('If you enable the shop sidebar, it will be shown beside your shop and single product content instead of the primary sidebar.', 'super-awesome-theme'), type: 'checkbox' })); } }); // Handle visibility of the sidebar controls. util.bindSettingToControls('sidebar_mode', sidebarModeDependants, function (value, control) { control.active.set('no_sidebar' !== value); }); // Handle visibility of the actual blog sidebar widget area. util.bindSettingToSections('blog_sidebar_enabled', ['sidebar-widgets-blog'], function (value, section) { if (value) { section.activate(); return; } section.deactivate(); }); // Handle visibility of the actual shop sidebar widget area. if (data.displayShopSidebarEnabledSetting) { util.bindSettingToSections('shop_sidebar_enabled', ['sidebar-widgets-shop'], function (value, section) { if (value) { section.activate(); return; } section.deactivate(); }); } // Show a notification for the blog sidebar instead of hiding it. api.control('blog_sidebar_enabled', function (control) { var origOnChangeActive = control.onChangeActive; var hasNotification = false; control.onChangeActive = function (active) { var noticeCode = 'blog_sidebar_not_available'; if (active) { if (hasNotification) { hasNotification = false; control.container.find('input[type="checkbox"]').prop('disabled', false); control.container.find('.description').slideDown(180); control.notifications.remove(noticeCode); } origOnChangeActive.apply(this, arguments); } else { if ('no_sidebar' === api.instance('sidebar_mode').get()) { origOnChangeActive.apply(this, arguments); return; } hasNotification = true; control.container.find('input[type="checkbox"]').prop('disabled', true); control.container.find('.description').slideUp(180); control.notifications.add(noticeCode, new api.Notification(noticeCode, { type: 'info', message: __('This page doesn&#8217;t support the blog sidebar. Navigate to the blog page or another page that supports it.', 'super-awesome-theme') })); } }; }); }); })(window.wp, window.themeSidebarControlsData); /***/ } /******/ });
taco-themes/boilerplate
assets/dist/js/sidebar.customize-controls.js
JavaScript
gpl-3.0
13,082
/***************************************************************************** * 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 { // Filter out points that are duplicated, dominated, or sharing the same value of an objective as the reference point // This does not alter the final result of the computation. // Wrapped algorithm is susceptible to such cases, thus it is a precaution measure. std::vector<fitness_vector>::iterator it = points.begin(); while (it != points.end()) { bool erase = false; // Quick check for sharing an objective with the reference point for (unsigned int d_idx = 0 ; d_idx < 4 ; ++d_idx) { if (fabs(r_point[d_idx] - (*it)[d_idx]) < 1e-10) { erase = true; break; } } // If the point was not eliminated during first check, try the domination check if (!erase) { std::vector<fitness_vector>::iterator it2 = points.begin(); while (it2 != points.end()){ if (it == it2) { ++it2; continue; } bool dominates = true; for (unsigned int d_idx = 0 ; d_idx < 4 ; ++d_idx) { if ((*it)[d_idx] < (*it2)[d_idx]) { dominates = false; break; } } if (dominates) { erase = true; break; } ++it2; } } // Erase the point if necessary if (erase) { it = points.erase(it); } else { ++it; } } // 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; } /// Exclusive method /** * As of yet, this algorithm does not support this method, even in its naive form, due to a poor handling of the dominated points. */ double hv4d::exclusive(const unsigned int p_idx, std::vector<fitness_vector> &points, const fitness_vector &r_point) const { (void)p_idx; (void)points; (void)r_point; pagmo_throw(value_error, "This method is not supported by the hv4d algorithm"); } /// Least contributor method /** * As of yet, this algorithm does not support this method, even in its naive form, due to a poor handling of the dominated points. */ unsigned int hv4d::least_contributor(std::vector<fitness_vector> &points, const fitness_vector &r_point) const { (void)points; (void)r_point; pagmo_throw(value_error, "This method is not supported by the hv4d algorithm"); } /// Greatest contributor method /** * As of yet, this algorithm does not support this method, even in its naive form, due to a poor handling of the dominated points. */ unsigned int hv4d::greatest_contributor(std::vector<fitness_vector> &points, const fitness_vector &r_point) const { (void)points; (void)r_point; pagmo_throw(value_error, "This method is not supported by the hv4d algorithm"); } /// Contributions method /** * As of yet, this algorithm does not support this method, even in its naive form, due to a poor handling of the dominated points. */ std::vector<double> hv4d::contributions(std::vector<fitness_vector> &points, const fitness_vector &r_point) const { (void)points; (void)r_point; pagmo_throw(value_error, "This method is not supported by the hv4d algorithm"); } /// 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);
enikulenkov/PaGMO
src/util/hv_algorithm/hv4d.cpp
C++
gpl-3.0
6,462
<?php namespace BES\ContactBundle\Entity; use Doctrine\ORM\Mapping as ORM; use SKCMS\ContactBundle\Entity\ContactMessage as BaseMessage; /** * ContactMessage * * @ORM\Table() * @ORM\Entity(repositoryClass="BES\ContactBundle\Entity\ContactMessageRepository") */ class ContactMessage extends BaseMessage { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * Get id * * @return integer */ public function getId() { return $this->id; } }
kokmok/beswebdev
src/BES/ContactBundle/Entity/ContactMessage.php
PHP
gpl-3.0
610
# Example made by OssiLehtinen # from svgpathtools import svg2paths, wsvg import numpy as np import uArmRobot import time #Configure Serial Port #serialport = "com3" # for windows serialport = "/dev/ttyACM0" # for linux like system # Connect to uArm myRobot = uArmRobot.robot(serialport,0) # user 0 for firmware < v4 and use 1 for firmware v4 myRobot.debug = True # Enable / Disable debug output on screen, by default disabled myRobot.connect() myRobot.mode(1) # Set mode to Normal # Read in the svg paths, attributes = svg2paths('drawing.svg') scale = .25 steps_per_seg = 3 coords = [] x_offset = 200 height = 90 draw_speed = 1000 # Convert the paths to a list of coordinates for i in range(len(paths)): path = paths[i] attribute = attributes[i] # A crude check for whether a path should be drawn. Does it have a style defined? if 'style' in attribute: for seg in path: segcoords = [] for p in range(steps_per_seg+1): cp = seg.point(float(p)/float(steps_per_seg)) segcoords.append([-np.real(cp)*scale+x_offset, np.imag(cp)*scale]) coords.append(segcoords) # The starting point myRobot.goto(coords[0][0][0], coords[0][0][1], height, 6000) for seg in coords: myRobot.goto(seg[0][0], seg[0][1], height, 6000) time.sleep(0.15) for p in seg: myRobot.goto_laser(p[0], p[1], height, draw_speed) # Back to the starting point (and turn the laser off) myRobot.goto(coords[0][0][0], coords[0][0][1], height, 6000)
AnykeyNL/uArmProPython
svg_example.py
Python
gpl-3.0
1,467
<?php // This file is part of mod_checkmark for Moodle - http://moodle.org/ // // It 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. // // It 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/>. /** * backup/moodle2/backup_checkmark_stepslib.php Define all the backup steps that will be used by the backup_checkmark_activity_task * * @package mod_checkmark * @author Philipp Hager * @copyright 2014 Academic Moodle Cooperation {@link http://www.academic-moodle-cooperation.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; /** * Define the complete checkmark structure for backup, with file and id annotations * * @package mod_checkmark * @author Philipp Hager * @copyright 2014 Academic Moodle Cooperation {@link http://www.academic-moodle-cooperation.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class backup_checkmark_activity_structure_step extends backup_activity_structure_step { /** * Define backup structure * * @return object standard activity structure */ protected function define_structure() { // Are we including userinfo? $userinfo = $this->get_setting_value('userinfo'); // Define each element separated! $checkmark = new backup_nested_element('checkmark', array('id'), array( 'name', 'intro', 'introformat', 'alwaysshowdescription', 'resubmit', 'cutoffdate', 'emailteachers', 'timedue', 'timeavailable', 'exampleprefix', 'grade', 'trackattendance', 'attendancegradelink', 'presentationgrading', 'presentationgrade', 'presentationgradebook', 'timemodified')); $submissions = new backup_nested_element('submissions'); $submission = new backup_nested_element('submission', array('id'), array( 'userid', 'timecreated', 'timemodified')); $feedbacks = new backup_nested_element('feedbacks'); $feedback = new backup_nested_element('feedback', array('id'), array( 'userid', 'grade', 'feedback', 'format', 'attendance', 'presentationgrade', 'presentationfeedback', 'presentationformat', 'graderid', 'mailed', 'timecreated', 'timemodified')); $examples = new backup_nested_element('examples'); $example = new backup_nested_element('example', array('id'), array('checkmarkid', 'name', 'grade')); $checks = new backup_nested_element('checks'); $check = new backup_nested_element('check', array('id'), array('checkmarkid', 'submissionid', 'exampleid', 'state')); // Now build the tree! $checkmark->add_child($examples); $examples->add_child($example); $checkmark->add_child($submissions); $submissions->add_child($submission); $checkmark->add_child($feedbacks); $feedbacks->add_child($feedback); // Second level. $submission->add_child($checks); $checks->add_child($check); // Define sources! $checkmark->set_source_table('checkmark', array('id' => backup::VAR_ACTIVITYID)); $example->set_source_table('checkmark_examples', array('checkmarkid' => backup::VAR_PARENTID)); // All the rest of elements only happen if we are including user info! if ($userinfo) { $submission->set_source_table('checkmark_submissions', array('checkmarkid' => backup::VAR_PARENTID)); $feedback->set_source_table('checkmark_feedbacks', array('checkmarkid' => backup::VAR_PARENTID)); $check->set_source_table('checkmark_checks', array('submissionid' => backup::VAR_PARENTID)); } // Define id annotations! $checkmark->annotate_ids('scale', 'grade'); $checkmark->annotate_ids('scale', 'presentationgrade'); $submission->annotate_ids('user', 'userid'); $feedback->annotate_ids('user', 'userid'); $feedback->annotate_ids('user', 'graderid'); $check->annotate_ids('checkmark_example', 'exampleid'); // Define file annotations! $checkmark->annotate_files('mod_checkmark', 'intro', null); // This file area has no itemid! // Return the root element (checkmark), wrapped into standard activity structure! return $this->prepare_activity_structure($checkmark); } }
nitro2010/moodle
mod/checkmark/backup/moodle2/backup_checkmark_stepslib.php
PHP
gpl-3.0
4,986
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Newegg.Oversea.Silverlight.ControlPanel.Core.Base; using ECCentral.Portal.Basic.Utilities; using System.Collections.Generic; using Newegg.Oversea.Silverlight.Utilities.Validation; using System.Linq; using System.ComponentModel; using ECCentral.Portal.UI.SO.Resources; namespace ECCentral.Portal.UI.SO.Models { public class SODeliveryExpVM : ModelBase { private string message; public string Message { get { return message; } set { SetValue<string>("Message", ref message, value); } } private int orderType; public int OrderType { get { return orderType; } set { SetValue<int>("OrderType", ref orderType, value); } } private List<CodeNamePair> orderTypeList; public List<CodeNamePair> OrderTypeList { get { return orderTypeList; } set { SetValue<List<CodeNamePair>>("OrderTypeList", ref orderTypeList, value); } } private string orderSysNos; [Validate(ValidateType.Required)] public string OrderSysNos { get { return orderSysNos; } set { try { List<string> orderList = value.Replace(";", ";").Trim() .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .ToList<string>(); orderList.ForEach(x => { int.Parse(x); }); if (orderList == null || orderList.Count == 0) { this.ValidationErrors.Add(new System.ComponentModel.DataAnnotations.ValidationResult(ResDeliveryList.Msg_ErrorDataAnnotations)); throw new ArgumentException(ResDeliveryList.Msg_ErrorDataAnnotations); } } catch { this.ValidationErrors.Add(new System.ComponentModel.DataAnnotations.ValidationResult(ResDeliveryList.Msg_ErrorDataAnnotations)); throw new ArgumentException(ResDeliveryList.Msg_ErrorDataAnnotations); } this.ValidationErrors.Clear(); SetValue<string>("OrderSysNos", ref orderSysNos, value); } } } }
ZeroOne71/ql
02_ECCentral/02_Portal/UI/ECCentral.Portal.UI.SO/Models/SODeliveryExpVM.cs
C#
gpl-3.0
2,701
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-client. # # lai-client 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. # # lai-client 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 lai-client. If not, see <http://www.gnu.org/licenses/>. import pymongo from pymongo.errors import AutoReconnect from lai.db.base import DBBase from lai.database import UPDATE_PROCESS, COMMIT_PROCESS from lai.database import DatabaseException, NotFoundError from lai import Document class DBMongo(DBBase): def __init__(self, name, host='127.0.0.1', port=27017): self.name = name self.host = host self.port = port def connect(self): try: self.connection = pymongo.Connection(self.host, self.port) self.db = self.connection[self.name] except AutoReconnect: raise DatabaseException("It's not possible connect to the database") def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id'] def search(self, regex): try: spec = {'$or': [{'data.content' : {'$regex': regex, '$options': 'im'}}, {'data.description': {'$regex': regex, '$options': 'im'}}]} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def get(self, id, pk='id', deleted=False): try: if pk == 'id': id = int(id) if deleted: spec = {pk: id} else: spec = {pk: id, 'data': {'$exists': 1}} fields = {'_id': 0} row = self.db.docs.find_one(spec, fields) except Exception as e: raise DatabaseException(e) if row: return Document(**row) raise NotFoundError('%s %s not found' % (pk, id)) def getall(self): try: spec = {'data': {'$exists': 1}} fields = {'_id': 0} sort = [('tid', 1)] cur = self.db.docs.find(spec, fields, sort=sort) except Exception as e: raise DatabaseException(e) return [Document(**row) for row in cur] def save(self, doc): if doc.id: return self.update(doc) else: return self.insert(doc) def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc def update(self, doc, process=None): if process is None: pk = 'id' id = doc.id doc.synced = False set = doc elif process == UPDATE_PROCESS: if self.db.docs.find({'sid': doc.sid}).count() == 0: return self.insert(doc, synced=True) pk = 'sid' id = doc.sid doc.synced = not doc.merged() # must be commited if was merged doc.merged(False) set = {'tid': doc.tid, 'data': doc.data, 'user': doc.user, 'public': doc.public, 'synced': doc.synced} elif process == COMMIT_PROCESS: pk = 'id' id = doc.id doc.synced = True set = {'sid': doc.sid, 'tid': doc.tid, 'synced': doc.synced} else: raise DatabaseException('Incorrect update process') try: rs = self.db.docs.update({pk: id}, {'$set': set}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return doc def delete(self, doc): if doc.id is None: raise DatabaseException('Document does not have id') if doc.sid is None: try: rs = self.db.docs.remove({'id': doc.id}, safe=True) assert rs['n'] == 1 except Exception as e: raise DatabaseException(e) return None doc.data = None return self.update(doc) def save_last_sync(self, ids, process): try: spec = {'_id': 'last_sync'} document = {'$set': {process: ids}} self.db.internal.update(spec, document, upsert=True) except Exception as e: raise DatabaseException(e) def get_docs_to_commit(self): try: spec = {'synced': False} fields = {'_id': 0} cur = self.db.docs.find(spec, fields) except Exception as e: raise DatabaseException(e) return list(cur) def get_last_tid(self): try: spec = {'tid': {'$gt': 0}} sort = [('tid', -1)] row = self.db.docs.find_one(spec, sort=sort) except Exception as e: raise DatabaseException(e) if row: return row['tid'] return 0 def status(self): docs = {'updated' : [], 'committed': [], 'to_commit': []} row = self.db.internal.find_one({'_id': 'last_sync'}) if row and 'update' in row: for id in row['update']: docs['updated'].append(self.get(id, deleted=True)) if row and 'commit' in row: for id in row['commit']: docs['committed'].append(self.get(id, deleted=True)) to_commit = self.get_docs_to_commit() for row in to_commit: doc = Document(**row) docs['to_commit'].append(doc) return docs def __str__(self): return "%s://%s:%s/%s" % ('mongo', self.host, self.port, self.name)
lvidarte/lai-client
lai/db/mongo.py
Python
gpl-3.0
6,391
from matplotlib import pyplot as plt path = "C:/Temp/mnisterrors/chunk" + str(input("chunk: ")) + ".txt" with open(path, "r") as f: errorhistory = [float(line.rstrip('\n')) for line in f] plt.plot(errorhistory) plt.show()
jabumaho/MNIST-neural-network
plot_error.py
Python
gpl-3.0
235
require 'nil/file' require 'nil/http' class Rune attr_reader :id, :name, :description def initialize(id, name, description) @id = id @name = name @description = description end end def processTier(tier) host = 'http://na.leagueoflegends.com' url = "#{host}/runes/#{tier}" puts "Downloading tier #{tier}: #{url}" contents = Nil.httpDownload(url) if contents == nil raise 'Unable to download rune data' end pattern = /<td class="rune_type"><img src="(.+?(\d+)\.png)"><\/td>.*?<td class="rune_name">(.+?)<\/td>.*?<td class="rune_description">(.+?)<\/td>/m output = [] contents.scan(pattern) do |match| path = match[0] id = match[1].to_i name = match[2] description = match[3] rune = Rune.new(id, name, description) output << rune imageURL = "#{host}#{path}" filename = "../Image/Rune/#{id}.png" if !File.exists?(filename) puts "Downloading rune image: #{imageURL}" download = Nil.httpDownload(imageURL) if download == nil raise "Unable to retrieve #{imageURL}" end Nil.writeFile(filename, download) end end return output end def javaScriptString(input) output = input.gsub('"', "\\\"") return "\"#{output}\"" end runes = [] (1..3).each do |i| runes += processTier(i) end runes.sort! do |x, y| x.id <=> y.id end output = "function Rune(name, description)\n" output += "{\n" output += " this.name = name;\n" output += " this.description = description;\n" output += "}\n\n" output += "function getRune(id)\n" output += "{\n" output += " switch(id)\n" output += " {\n" runes.each do |rune| output += " case #{rune.id}:\n" output += " return new Rune(#{javaScriptString(rune.name)}, #{javaScriptString(rune.description)});\n" end output += " default:\n" output += " return new Rune('Unknown rune', 'Unknown');\n" output += " }\n" output += "}" Nil.writeFile('../Script/Module/Runes.js', output)
epicvrvs/RiotControl
Web/Generation/runes.rb
Ruby
gpl-3.0
1,965
<?php /** * $Id$ * * Copyright 2008 secure-net-concepts <info@secure-net-concepts.de> * * This file is part of Nagios Administrator http://www.nagiosadmin.de. * * Nagios Administrator 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. * * Nagios Administrator 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 Nagios Administrator. If not, see <http://www.gnu.org/licenses/>. * * @package nagiosadmin * @subpackage generator * @license http://www.gnu.org/licenses/gpl.html * @link www.nagiosadmin.de * @version $Revision$ * @author Henrik Westphal <westphal@secure-net-concepts.de> */ ?> </div> </div>
senecon/nagiosadmin
apps/backend/modules/generator/templates/_generator_footer.php
PHP
gpl-3.0
1,088
package com.gildedgames.aether.client.renderer.tile_entities; import com.gildedgames.aether.client.models.entities.tile.ModelPresent; import com.gildedgames.aether.common.items.blocks.ItemBlockPresent; import com.gildedgames.aether.common.tiles.TileEntityPresent; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.util.ResourceLocation; import java.util.Random; public class TileEntityPresentRenderer extends TileEntitySpecialRenderer<TileEntityPresent> { public static final ResourceLocation[] boxTextures = new ResourceLocation[16]; public static final ResourceLocation[] bowTextures = new ResourceLocation[16]; public static final String[] colors = new String[] { "black", "red", "green", "brown", "blue", "purple", "cyan", "silver", "gray", "pink", "lime", "yellow", "light_blue", "magenta", "orange", "white" }; static { for (int i = 0; i < 16; i++) { boxTextures[i] = new ResourceLocation("aether", "textures/tile_entities/present/present_box_" + colors[i] + ".png"); bowTextures[i] = new ResourceLocation("aether", "textures/tile_entities/present/present_ribbon_" + colors[i] + ".png"); } } private final ModelPresent model = new ModelPresent(); private final Random random = new Random(); @Override public void renderTileEntityAt(TileEntityPresent present, double x, double y, double z, float partialTicks, int destroyStage) { GlStateManager.pushMatrix(); ItemBlockPresent.PresentData data = null; if (present != null) { data = present.getPresentData(); } byte boxColor = data == null ? 15 : data.getDye().getBoxColor(); byte bowColor = data == null ? 1 : data.getDye().getBowColor(); // Sanitize dye colors to prevent rogue presents! boxColor = (boxColor >= 15 ? 15 : (boxColor < 0 ? 0 : boxColor)); bowColor = (bowColor >= 15 ? 15 : (bowColor < 0 ? 0 : bowColor)); GlStateManager.enableRescaleNormal(); GlStateManager.translate((float) x + 0.5f, (float) y, (float) z + 0.5f); if (present != null) { this.random.setSeed((long) (present.getPos().getX() + present.getPos().getY() + present.getPos().getZ()) * 5L); float offset = this.random.nextFloat() * 0.1f; float scale = 1f + ((this.random.nextFloat() * 0.1f) - 0.1f); float rotate = this.random.nextFloat() * 180f; GlStateManager.translate(offset, 0, offset); GlStateManager.rotate(180f, 1f, 0f, 1f); GlStateManager.rotate(rotate, 0f, 1f, 0f); GlStateManager.scale(scale, scale, scale); } else { GlStateManager.rotate(180f, 1.0f, 0f, 0.4f); GlStateManager.scale(1.5F, 1.5F, 1.5F); } this.bindTexture(boxTextures[boxColor]); this.model.renderBox(0.0625F); this.bindTexture(bowTextures[bowColor]); this.model.renderBow(0.0625F); this.model.renderBox(0.0625F); GlStateManager.disableRescaleNormal(); GlStateManager.popMatrix(); } }
Better-Aether/Better-Aether
src/main/java/com/gildedgames/aether/client/renderer/tile_entities/TileEntityPresentRenderer.java
Java
gpl-3.0
2,920
using KotaeteMVC.Context; using KotaeteMVC.Models.Entities; using KotaeteMVC.Models.ViewModels; using KotaeteMVC.Models.ViewModels.Base; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace KotaeteMVC.Service { public class LikesService : UsersService { public LikesService(KotaeteDbContext context, int pageSize) : base(context, pageSize) { } public AnswerLikeViewModel GetLikeButtonViewModel(int answerId) { var currentUserName = this.GetCurrentUserName(); return new AnswerLikeViewModel() { HasLiked = HasLikedAnswer(currentUserName, answerId), LikeCount = GetLikesCount(answerId), AnswerId = answerId }; } public int GetLikesCount(int answerId) { return _context.AnswerLikes.Count(like => like.AnswerId == answerId && like.Active); } public bool HasLikedAnswer(string userName, int answerId) { return _context.AnswerLikes.Any(like => like.Active && like.AnswerId == answerId && like.ApplicationUser.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase)); } public bool LikeAnswer(int answerId) { Answer answer = GetAnswerById(answerId); if (answer == null) { return false; } var currentUser = GetCurrentUser(); if (currentUser == null) { return false; } if (_context.AnswerLikes.Any(like => like.ApplicationUserId == currentUser.Id && like.AnswerId == answer.AnswerId && like.Active)) { return false; } else { var answerLike = new AnswerLike() { Active = true, Answer = answer, ApplicationUser = currentUser, TimeStamp = DateTime.Now }; using (var transaction = _context.Database.BeginTransaction()) { _context.AnswerLikes.Add(answerLike); try { _context.SaveChanges(); answerLike.AddNotification(); _context.SaveChanges(); transaction.Commit(); return true; } catch (Exception e) { return false; } } } } private Answer GetAnswerById(int answerId) { return _context.Answers.FirstOrDefault(answ => answ.AnswerId == answerId && answ.Active); } public bool UnlikeAnswer(int answerId) { var answer = GetAnswerById(answerId); if (answer == null) { return false; } var currentUser = GetCurrentUser(); var answerLike = _context.AnswerLikes.FirstOrDefault(like => like.Active && like.ApplicationUserId == currentUser.Id && like.AnswerId == answerId); if (answerLike == null) { return false; } else { answerLike.Active = false; try { _context.SaveChanges(); return true; } catch (Exception e) { return false; } } } public AnswerListProfileViewModel GetLikedAnswerListProfileModel(string userName, int page) { var answersService = new AnswersService(_context, _pageSize); var user = GetUserWithName(userName); if (user == null) { return null; } else { var answersQuery = _context.AnswerLikes.Where(like => like.Active && like.ApplicationUserId == user.Id).OrderByDescending(like => like.TimeStamp).Select(like => like.Answer); var paginationInitializer = new PaginationInitializer("AnswersLikedPage", "answers-list", userName, _pageSize); var model = answersService.GetAnswerListProfileModelForQuery(userName, page, answersQuery); paginationInitializer.InitializePaginationModel(model.AnswerList, page, answersQuery.Count()); return model; } } } }
seranfuen/kotaete
KotaeteMVC/Service/LikesService.cs
C#
gpl-3.0
4,678
/** __ __ * _____ _/ /_/ /_ Computational Intelligence Library (CIlib) * / ___/ / / / __ \ (c) CIRG @ UP * / /__/ / / / /_/ / http://cilib.net * \___/_/_/_/_.___/ */ package net.sourceforge.cilib.problem.boundaryconstraint; import net.sourceforge.cilib.entity.Entity; import net.sourceforge.cilib.entity.Property; import net.sourceforge.cilib.type.types.Numeric; import net.sourceforge.cilib.type.types.Types; import net.sourceforge.cilib.type.types.container.Vector; /** * Once the entity has over shot the search space boundaries, re-initialise * the Entity once again to be within the search space of the problem at a * random position. * * @see Types#isInsideBounds(net.sourceforge.cilib.type.types.Type) */ public class PreviousPosition implements BoundaryConstraint { private double bound = 1.0e290; /** * {@inheritDoc} */ @Override public PreviousPosition getClone() { return this; } /** * {@inheritDoc} */ @Override public void enforce(Entity entity) { double total = 0; for (Numeric curElement : (Vector) entity.getPosition()) { total += Math.abs(curElement.doubleValue() * 2); } if (total > bound || Double.isNaN(total) || total == Double.POSITIVE_INFINITY) { entity.setPosition(entity.get(Property.PREVIOUS_SOLUTION)); } } public void setBound(double bound) { this.bound = bound; } }
censlin/cilib-old
library/src/main/java/net/sourceforge/cilib/problem/boundaryconstraint/PreviousPosition.java
Java
gpl-3.0
1,495
<?php namespace AramisAuto\EmailController\MessageStrategy; use AramisAuto\EmailController\Event\MessageEvent; class NullMessageStrategy extends AbstractMessageStrategy { public function execute() { $event = new MessageEvent($this->getMessage()); $this->getEventDispatcher()->dispatch($this->success(), $event); } }
ARAMISAUTO/email-controller
src/src/AramisAuto/EmailController/MessageStrategy/NullMessageStrategy.php
PHP
gpl-3.0
346
# We calculate the flatness with the Roche model # calculate omk knowing omc and vice-versa from numpy import * from scipy.optimize import root # we have to solve a cubic equation a-J2*a**3=1+J2+0.5*omk**2 def eps(omk): return omk**2/(2+omk**2) def om_k(omc): khi=arcsin(omc) return sqrt(6*sin(khi/3)/omc-2) omc=0.88 print 'omc=',omc,' omk=',om_k(omc)
ester-project/ester
postprocessing/Roche.py
Python
gpl-3.0
361
package org.monstercraft.irc.ircplugin.event.events; import java.util.EventListener; import org.monstercraft.irc.ircplugin.event.EventMulticaster; import org.monstercraft.irc.ircplugin.event.listeners.IRCListener; import org.monstercraft.irc.plugin.wrappers.IRCServer; public class PluginDisconnectEvent extends IRCEvent { private static final long serialVersionUID = 8708860642802706979L; private final IRCServer server; public PluginDisconnectEvent(final IRCServer server) { this.server = server; } @Override public void dispatch(final EventListener el) { ((IRCListener) el).onDisconnect(server); } @Override public long getMask() { return EventMulticaster.IRC_DISCONNECT_EVENT; } }
Monstercraft/MonsterIRC
src/main/java/org/monstercraft/irc/ircplugin/event/events/PluginDisconnectEvent.java
Java
gpl-3.0
758
/***************************************************************************** * Copyright 2010-2012 Katholieke Universiteit Leuven * * Use of this software is governed by the GNU LGPLv3.0 license * * Written by Broes De Cat, Bart Bogaerts, Stef De Pooter, Johan Wittocx, * Jo Devriendt, Joachim Jansen and Pieter Van Hertum * K.U.Leuven, Departement Computerwetenschappen, * Celestijnenlaan 200A, B-3001 Leuven, Belgium ****************************************************************************/ #include <iostream> #include <ostream> #include <limits> #include <stdlib.h> #include <sstream> #include "common.hpp" #include "GlobalData.hpp" using namespace std; std::string getGlobalNamespaceName() { return "idpglobal"; // NOTE: this string is also used in idp_intern.idp } std::string getInternalNamespaceName() { return "idpintern"; } std::string installdirectorypath = string(IDPINSTALLDIR); void setInstallDirectoryPath(const std::string& dirpath) { installdirectorypath = dirpath; } std::string getInstallDirectoryPath() { return installdirectorypath; } string getPathOfLuaInternals() { stringstream ss; ss << getInstallDirectoryPath() << INTERNALLIBARYLUA; return ss.str(); } string getPathOfIdpInternals() { stringstream ss; ss << getInstallDirectoryPath() << INTERNALLIBARYIDP; return ss.str(); } string getPathOfConfigFile() { stringstream ss; ss << getInstallDirectoryPath() << CONFIGFILENAME; return ss.str(); } std::string tabs() { stringstream ss; auto nb = GlobalData::instance()->getTabSize(); for (size_t i = 0; i < nb; ++i) { ss << " "; } return ss.str(); } std::string nt() { stringstream ss; ss << '\n' << tabs(); return ss.str(); } void pushtab() { GlobalData::instance()->setTabSize(GlobalData::instance()->getTabSize() + 1); } void poptab() { GlobalData::instance()->resetTabSize(); } /*void notyetimplemented(const string& message) { clog << "WARNING or ERROR: The following feature is not yet implemented:\n" << '\t' << message << '\n' << "Please send an e-mail to krr@cs.kuleuven.be if you really need this feature.\n"; }*/ IdpException notyetimplemented(const string& message) { stringstream ss; ss << "The following feature is not yet implemented: " << message << '\n'; ss << "Please send an e-mail to krr@cs.kuleuven.be if you really need this feature."; return IdpException(ss.str()); } bool isInt(double d) { return (double(int(d)) == d); } bool isInt(const string& s) { stringstream i(s); int n; return (i >> n).eof(); } bool isDouble(const string& s) { stringstream i(s); double d; return (i >> d).eof(); } int toInt(const string& s) { stringstream i(s); int n; if (not (i >> n).eof()) { return 0; } else { return n; } } double toDouble(const string& s) { stringstream i(s); double d; if (not (i >> d).eof()) { return 0; } else { return d; } } double applyAgg(const AggFunction& agg, const vector<double>& args) { double d = 0; switch (agg) { case AggFunction::CARD: d = double(args.size()); break; case AggFunction::SUM: d = 0; for (size_t n = 0; n < args.size(); ++n) { d += args[n]; } break; case AggFunction::PROD: d = 1; for (size_t n = 0; n < args.size(); ++n) { d = d * args[n]; } break; case AggFunction::MIN: d = getMaxElem<int>(); for (size_t n = 0; n < args.size(); ++n) { d = (d <= args[n] ? d : args[n]); } break; case AggFunction::MAX: d = getMinElem<int>(); for (size_t n = 0; n < args.size(); ++n) { d = (d >= args[n] ? d : args[n]); } break; } return d; } bool operator==(VarId left, VarId right){ return left.id==right.id; } bool operator!=(VarId left, VarId right){ return not (left.id==right.id); } bool operator<(VarId left, VarId right){ return left.id<right.id; } bool operator==(DefId left, DefId right){ return left.id==right.id; } bool operator!=(DefId left, DefId right){ return not (left.id==right.id); } bool operator<(DefId left, DefId right){ return left.id<right.id; } bool operator==(SetId left, SetId right){ return left.id==right.id; } bool operator!=(SetId left, SetId right){ return not (left.id==right.id); } bool operator<(SetId left, SetId right){ return left.id<right.id; } std::ostream& operator<<(std::ostream& out, const VarId& id) { out <<id.id; return out; } std::ostream& operator<<(std::ostream& out, const DefId& id) { out <<id.id; return out; } std::ostream& operator<<(std::ostream& out, const SetId& id) { out <<id.id; return out; } // TODO remove when all are using gcc 4.5 bool operator==(CompType left, CompType right) { return (int) left == (int) right; } bool operator>(CompType left, CompType right) { return (int) left > (int) right; } bool operator<(CompType left, CompType right) { return not (left == right || left > right); } TsType invertImplication(TsType type) { if (type == TsType::IMPL) { return TsType::RIMPL; } if (type == TsType::RIMPL) { return TsType::IMPL; } return type; } bool isPos(SIGN s) { return s == SIGN::POS; } bool isNeg(SIGN s) { return s == SIGN::NEG; } SIGN operator not(SIGN rhs) { return rhs == SIGN::POS ? SIGN::NEG : SIGN::POS; } SIGN operator~(SIGN rhs) { return not rhs; } QUANT operator not(QUANT t) { return t == QUANT::UNIV ? QUANT::EXIST : QUANT::UNIV; } Context operator not(Context t) { Context result = Context::BOTH; switch (t) { case Context::BOTH: result = Context::BOTH; break; case Context::POSITIVE: result = Context::NEGATIVE; break; case Context::NEGATIVE: result = Context::POSITIVE; break; } return result; } Context operator~(Context t) { return not t; } TruthValue operator not(TruthValue t) { TruthValue result = TruthValue::Unknown; switch (t) { case TruthValue::Unknown: result = TruthValue::Unknown; break; case TruthValue::True: result = TruthValue::False; break; case TruthValue::False: result = TruthValue::True; break; } return result; } TruthValue operator~(TruthValue t) { return not t; } bool isConj(SIGN sign, bool conj) { return (sign == SIGN::POS && conj) || (sign == SIGN::NEG && ~conj); } PRINTTOSTREAMIMPL(std::string) PRINTTOSTREAMIMPL(char) PRINTTOSTREAMIMPL(char*) PRINTTOSTREAMIMPL(CompType) PRINTTOSTREAMIMPL(TruthType) PRINTTOSTREAMIMPL(TsType) PRINTTOSTREAMIMPL(AggFunction) PRINTTOSTREAMIMPL(TruthValue) std::ostream& operator<<(std::ostream& output, const CompType& type) { switch (type) { case CompType::EQ: output << " = "; break; case CompType::NEQ: output << " ~= "; break; case CompType::LT: output << " < "; break; case CompType::GT: output << " > "; break; case CompType::LEQ: output << " =< "; break; case CompType::GEQ: output << " >= "; break; } return output; } std::ostream& operator<<(std::ostream& output, const TruthType& type){ switch (type) { case TruthType::CERTAIN_FALSE: output << " cf "; break; case TruthType::CERTAIN_TRUE: output << " ct "; break; case TruthType::POSS_FALSE: output << " pf "; break; case TruthType::POSS_TRUE: output << " pt "; break; } return output; } std::ostream& operator<<(std::ostream& output, const TruthValue& type){ switch (type) { case TruthValue::True: output << "true"; break; case TruthValue::False: output << "false"; break; case TruthValue::Unknown: output << "unknown"; break; } return output; } std::ostream& operator<<(std::ostream& output, const TsType& type) { switch (type) { case TsType::RIMPL: output << " <= "; break; case TsType::IMPL: output << " => "; break; case TsType::RULE: output << " <- "; break; case TsType::EQ: output << " <=> "; break; } return output; } std::ostream& operator<<(std::ostream& output, const AggFunction& type) { switch (type) { case AggFunction::CARD: output << "card"; break; case AggFunction::SUM: output << "sum"; break; case AggFunction::PROD: output << "prod"; break; case AggFunction::MAX: output << "max"; break; case AggFunction::MIN: output << "min"; break; } return output; } CompType invertComp(CompType comp) { CompType result = CompType::EQ; switch (comp) { case CompType::EQ: result = comp; break; case CompType::NEQ: result = comp; break; case CompType::LT: result = CompType::GT; break; case CompType::GT: result = CompType::LT; break; case CompType::LEQ: result = CompType::GEQ; break; case CompType::GEQ: result = CompType::LEQ; break; } return result; } CompType negateComp(CompType comp) { CompType result = CompType::EQ; switch (comp) { case CompType::EQ: result = CompType::NEQ; break; case CompType::NEQ: result = CompType::EQ; break; case CompType::LT: result = CompType::GEQ; break; case CompType::GT: result = CompType::LEQ; break; case CompType::LEQ: result = CompType::GT; break; case CompType::GEQ: result = CompType::LT; break; } return result; }
KULeuven-KRR/IDP
src/common.cpp
C++
gpl-3.0
8,878
/** */ package sc.ndt.editor.fast.fastfst; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>nTEC Sres</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link sc.ndt.editor.fast.fastfst.nTEC_Sres#getValue <em>Value</em>}</li> * <li>{@link sc.ndt.editor.fast.fastfst.nTEC_Sres#getName <em>Name</em>}</li> * </ul> * </p> * * @see sc.ndt.editor.fast.fastfst.FastfstPackage#getnTEC_Sres() * @model * @generated */ public interface nTEC_Sres extends EObject { /** * Returns the value of the '<em><b>Value</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Value</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Value</em>' attribute. * @see #setValue(float) * @see sc.ndt.editor.fast.fastfst.FastfstPackage#getnTEC_Sres_Value() * @model * @generated */ float getValue(); /** * Sets the value of the '{@link sc.ndt.editor.fast.fastfst.nTEC_Sres#getValue <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Value</em>' attribute. * @see #getValue() * @generated */ void setValue(float value); /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see sc.ndt.editor.fast.fastfst.FastfstPackage#getnTEC_Sres_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link sc.ndt.editor.fast.fastfst.nTEC_Sres#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); } // nTEC_Sres
cooked/NDT
sc.ndt.editor.fast.fst/src-gen/sc/ndt/editor/fast/fastfst/nTEC_Sres.java
Java
gpl-3.0
2,191
#!/usr/bin/env python import sys import os output_dir = "erc2-chromatin15state-all-files" if not os.path.exists(output_dir): sys.stderr.write("Creating dir [%s]...\n" % (output_dir)) os.makedirs(output_dir) prefix = "/home/cbreeze/for_Alex" suffix = "_15_coreMarks_mnemonics.bed" marks = [ '1_TssA', '2_TssAFlnk', '3_TxFlnk', '4_Tx', '5_TxWk', '6_EnhG', '7_Enh', '8_ZNF/Rpts', '9_Het', '10_TssBiv', '11_BivFlnk', '12_EnhBiv', '13_ReprPC', '14_ReprPCWk', '15_Quies' ] all = [ 'E001', 'E002', 'E003', 'E004', 'E005', 'E006', 'E007', 'E008', 'E009', 'E010', 'E011', 'E012', 'E013', 'E014', 'E015', 'E016', 'E017', 'E018', 'E019', 'E020', 'E021', 'E022', 'E023', 'E024', 'E025', 'E026', 'E027', 'E028', 'E029', 'E030', 'E031', 'E032', 'E033', 'E034', 'E035', 'E036', 'E037', 'E038', 'E039', 'E040', 'E041', 'E042', 'E043', 'E044', 'E045', 'E046', 'E047', 'E048', 'E049', 'E050', 'E051', 'E052', 'E053', 'E054', 'E055', 'E056', 'E057', 'E058', 'E059', 'E061', 'E062', 'E063', 'E065', 'E066', 'E067', 'E068', 'E069', 'E070', 'E071', 'E072', 'E073', 'E074', 'E075', 'E076', 'E077', 'E078', 'E079', 'E080', 'E081', 'E082', 'E083', 'E084', 'E085', 'E086', 'E087', 'E088', 'E089', 'E090', 'E091', 'E092', 'E093', 'E094', 'E095', 'E096', 'E097', 'E098', 'E099', 'E100', 'E101', 'E102', 'E103', 'E104', 'E105', 'E106', 'E107', 'E108', 'E109', 'E110', 'E111', 'E112', 'E113', 'E114', 'E115', 'E116', 'E117', 'E118', 'E119', 'E120', 'E121', 'E122', 'E123', 'E124', 'E125', 'E126', 'E127', 'E128', 'E129' ] # prefix, suffix, marks, all for sample in all: fns = {} fhs = {} # set up output file handles for all combinations of per-sample and marks for mark in marks: fns[mark] = os.path.join(output_dir, "%s_%s.bed" % (sample, mark.replace('/', '-'))) sys.stderr.write("Setting up output handle to [%s]...\n" % (fns[mark])) fhs[mark] = open(fns[mark], "w") # split per-sample mnemonics to per-sample, per-mark file psm_fn = "%s/%s%s" % (prefix, sample, suffix) sys.stderr.write("Reading PSM [%s]...\n" % (psm_fn)) with open(psm_fn, "r") as psm_fh: for line in psm_fh: (chr, start, stop, state_call) = line.strip().split('\t') fhs[state_call].write('\t'.join([chr, start, stop]) + '\n') # close handles for mark in marks: sys.stderr.write("Closing output handle to [%s]...\n" % (fns[mark])) fhs[mark].close() fns[mark] = None fhs[mark] = None
charlesbreeze/eFORGE
docs/eforge-db-construction/construct_erc2-chromatin15state-all_files.py
Python
gpl-3.0
3,559
import { parseProgrammes, parseSubjects, parseCourses, } from "@education-data/parser"; import { join } from "path"; import { writeFileSync } from "fs"; import { format } from "date-fns"; import { sv } from "date-fns/locale"; import { sourceDirectory, outputDirectory, replacementsDirectory } from "./cfg"; async function main() { console.info("\n[parsing subject data]"); await parseSubjects(sourceDirectory, outputDirectory, replacementsDirectory); console.info("\n[parsing course data]"); await parseCourses( { get(code: string) { const subjects = require("./out/subjects.json"); const name = subjects.find((el) => el.code === code); return require(join(process.cwd(), "./out", name.file)); }, } as Map<string, any>, sourceDirectory, outputDirectory, replacementsDirectory ); console.info("\n[parsing program data]"); await parseProgrammes( sourceDirectory + "/../gyP1_6_S1_4", outputDirectory, replacementsDirectory ); p; writeFileSync( "./out/meta.json", JSON.stringify({ fetchTime: new Date().toISOString(), humanizedFetchTime: format(new Date(), "do LLLL, yyyy", { locale: sv, }), }) ); } main().catch((err) => { console.error(err); process.exit(1); });
eweilow/swedish-education-data
packages/data-swedish-gymnasium/index.ts
TypeScript
gpl-3.0
1,305
<?php /** * This file is part of CMSGears Framework. Please view License file distributed * with the source code for license details. * * @link https://www.cmsgears.org/ * @copyright Copyright (c) 2015 VulpineCode Technologies Pvt. Ltd. */ namespace cmsgears\cart\common\models\resources; // Yii Imports use Yii; use yii\db\Expression; use yii\behaviors\TimestampBehavior; // CMG Imports use cmsgears\core\common\config\CoreGlobal; use cmsgears\cart\common\config\CartGlobal; use cmsgears\core\common\models\interfaces\base\IAuthor; use cmsgears\core\common\models\interfaces\resources\IContent; use cmsgears\core\common\models\interfaces\resources\IData; use cmsgears\core\common\models\interfaces\resources\IGridCache; use cmsgears\cart\common\models\base\CartTables; use cmsgears\cart\common\models\resources\Uom; use cmsgears\core\common\models\traits\base\AuthorTrait; use cmsgears\core\common\models\traits\resources\ContentTrait; use cmsgears\core\common\models\traits\resources\DataTrait; use cmsgears\core\common\models\traits\resources\GridCacheTrait; use cmsgears\core\common\behaviors\AuthorBehavior; /** * OrderItem stores the items associated with order. * * @property integer $id * @property integer $orderId * @property integer $primaryUnitId * @property integer $purchasingUnitId * @property integer $quantityUnitId * @property integer $weightUnitId * @property integer $volumeUnitId * @property integer $lengthUnitId * @property integer $createdBy * @property integer $modifiedBy * @property integer $parentId * @property integer $parentType * @property string $type * @property integer $name * @property string $sku * @property integer $status * @property float $price * @property float $discount * @property float $tax1 * @property float $tax2 * @property float $tax3 * @property float $tax4 * @property float $tax5 * @property float $total * @property integer $primary * @property integer $purchase * @property integer $quantity * @property integer $weight * @property integer $volume * @property integer $length * @property integer $width * @property integer $height * @property integer $radius * @property datetime $createdAt * @property datetime $modifiedAt * @property string $content * @property string $data * @property string $gridCache * @property boolean $gridCacheValid * @property datetime $gridCachedAt * * @since 1.0.0 */ class OrderItem extends \cmsgears\core\common\models\base\ModelResource implements IAuthor, IContent, IData, IGridCache { // Variables --------------------------------------------------- // Globals ------------------------------- // Constants -------------- const STATUS_NEW = 0; const STATUS_CANCELLED = 100; const STATUS_DELIVERED = 200; const STATUS_RETURNED = 300; const STATUS_RECEIVED = 400; // Public ----------------- public static $statusMap = [ self::STATUS_NEW => 'New', self::STATUS_CANCELLED => 'Cancelled', self::STATUS_DELIVERED => 'Delivered', self::STATUS_RETURNED => 'Returned', self::STATUS_RECEIVED => 'Received' ]; public static $urlRevStatusMap = [ 'new' => self::STATUS_NEW, 'cancelled' => self::STATUS_CANCELLED, 'delivered' => self::STATUS_DELIVERED, 'returned' => self::STATUS_RETURNED, 'received' => self::STATUS_RECEIVED ]; public static $filterStatusMap = [ 'new' => 'New', 'cancelled' => 'Cancelled', 'delivered' => 'Delivered', 'returned' => 'Returned', 'received' => 'Received' ]; // Protected -------------- // Variables ----------------------------- // Public ----------------- // Protected -------------- protected $modelType = CartGlobal::TYPE_ORDER_ITEM; // Private ---------------- // Traits ------------------------------------------------------ use AuthorTrait; use ContentTrait; use DataTrait; use GridCacheTrait; // Constructor and Initialisation ------------------------------ public function init() { parent::init(); if( $this->isNewRecord ) { $this->price = 0; $this->discount = 0; $this->total = 0; $this->primary = 0; $this->purchase = 0; $this->quantity = 0; $this->weight = 0; $this->volume = 0; $this->length = 0; $this->width = 0; $this->height = 0; $this->radius = 0; $this->tax1 = 0; $this->tax2 = 0; $this->tax3 = 0; $this->tax4 = 0; $this->tax5 = 0; } } // Instance methods -------------------------------------------- // Yii interfaces ------------------------ // Yii parent classes -------------------- // yii\base\Component ----- /** * @inheritdoc */ public function behaviors() { return [ 'authorBehavior' => [ 'class' => AuthorBehavior::class ], 'timestampBehavior' => [ 'class' => TimestampBehavior::class, 'createdAtAttribute' => 'createdAt', 'updatedAtAttribute' => 'modifiedAt', 'value' => new Expression('NOW()') ] ]; } // yii\base\Model --------- /** * @inheritdoc */ public function rules() { // Model Rules $rules = [ // Required, Safe [ [ 'orderId', 'name', 'price', 'purchase' ], 'required' ], [ [ 'id', 'content' ], 'safe' ], // Unique [ 'orderId', 'unique', 'targetAttribute' => [ 'parentId', 'parentType', 'orderId' ], 'comboNotUnique' => Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_EXIST ) ], // Text Limit [ [ 'parentType', 'type' ], 'string', 'min' => 1, 'max' => Yii::$app->core->mediumText ], [ [ 'name', 'sku' ], 'string', 'min' => 1, 'max' => Yii::$app->core->xxLargeText ], // Other [ [ 'price', 'discount', 'primary', 'purchase', 'quantity', 'total', 'weight', 'volume', 'length', 'width', 'height', 'radius' ], 'number', 'min' => 0 ], [ [ 'tax1', 'tax2', 'tax3', 'tax4', 'tax5' ], 'number', 'min' => 0 ], [ 'status', 'number', 'integerOnly' => true, 'min' => 0 ], [ 'gridCacheValid', 'boolean' ], [ [ 'orderId', 'primaryUnitId', 'purchasingUnitId', 'quantityUnitId', 'weightUnitId', 'volumeUnitId', 'lengthUnitId', 'createdBy', 'modifiedBy', 'parentId' ], 'number', 'integerOnly' => true, 'min' => 1 ], [ [ 'createdAt', 'modifiedAt' ], 'date', 'format' => Yii::$app->formatter->datetimeFormat ] ]; return $rules; } /** * @inheritdoc */ public function attributeLabels() { return [ 'orderId' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_ORDER ), 'primaryUnitId' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_UNIT_PRIMARY ), 'purchasingUnitId' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_UNIT_PURCHASING ), 'quantityUnitId' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_UNIT_QUANTITY ), 'weightUnitId' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_UNIT_WEIGHT ), 'volumeUnitId' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_UNIT_VOLUME ), 'lengthUnitId' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_UNIT_LENGTH ), 'createdBy' => Yii::$app->coreMessage->getMessage( CoreGlobal::FIELD_OWNER ), 'parentId' => Yii::$app->coreMessage->getMessage( CoreGlobal::FIELD_PARENT ), 'parentType' => Yii::$app->coreMessage->getMessage( CoreGlobal::FIELD_PARENT_TYPE ), 'type' => Yii::$app->coreMessage->getMessage( CoreGlobal::FIELD_TYPE ), 'name' => Yii::$app->coreMessage->getMessage( CoreGlobal::FIELD_NAME ), 'sku' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_SKU ), 'status' => Yii::$app->coreMessage->getMessage( CoreGlobal::FIELD_STATUS ), 'price' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_PRICE ), 'discount' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_DISCOUNT ), 'tax1' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_TAX ), 'tax2' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_TAX ), 'tax3' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_TAX ), 'tax4' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_TAX ), 'tax5' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_TAX ), 'total' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_TOTAL ), 'primary' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_QTY_PRIMARY ), 'purchase' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_QTY_PURCHASE ), 'quantity' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_QUANTITY ), 'weight' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_WEIGHT ), 'volume' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_VOLUME ), 'length' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_LENGTH ), 'width' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_WIDTH ), 'height' => Yii::$app->cartMessage->getMessage( CartGlobal::FIELD_HEIGHT ), 'content' => Yii::$app->coreMessage->getMessage( CoreGlobal::FIELD_CONTENT ), 'data' => Yii::$app->coreMessage->getMessage( CoreGlobal::FIELD_DATA ), 'gridCache' => Yii::$app->coreMessage->getMessage( CoreGlobal::FIELD_GRID_CACHE ) ]; } // CMG interfaces ------------------------ // CMG parent classes -------------------- // Validators ---------------------------- // OrderItem ----------------------------- /** * Returns the order associated with the item. * * @return Order */ public function getOrder() { return $this->hasOne( Order::class, [ 'id' => 'orderId' ] ); } /** * Returns primary unit associated with the item. * * @return \cmsgears\cart\common\models\resources\Uom */ public function getPrimaryUnit() { return $this->hasOne( Uom::class, [ 'id' => 'primaryUnitId' ] )->from( CartTables::TABLE_UOM . ' as primaryUnit' ); } /** * Returns purchasing unit associated with the item. * * @return \cmsgears\cart\common\models\resources\Uom */ public function getPurchasingUnit() { return $this->hasOne( Uom::class, [ 'id' => 'purchasingUnitId' ] )->from( CartTables::TABLE_UOM . ' as purchasingUnit' ); } /** * Returns quantity unit associated with the item. * * @return \cmsgears\cart\common\models\resources\Uom */ public function getQuantityUnit() { return $this->hasOne( Uom::class, [ 'id' => 'quantityUnitId' ] )->from( CartTables::TABLE_UOM . ' as quantityUnit' ); } /** * Returns weight unit associated with the item. * * @return \cmsgears\cart\common\models\resources\Uom */ public function getWeightUnit() { return $this->hasOne( Uom::class, [ 'id' => 'weightUnitId' ] )->from( CartTables::TABLE_UOM . ' as weightUnit' ); } /** * Returns volume unit associated with the item. * * @return \cmsgears\cart\common\models\resources\Uom */ public function getVolumeUnit() { return $this->hasOne( Uom::class, [ 'id' => 'lengthUnitId' ] )->from( CartTables::TABLE_UOM . ' as volumeUnit' ); } /** * Returns length unit associated with the item. It will be used for length, width, height and radius. * * @return \cmsgears\cart\common\models\resources\Uom */ public function getLengthUnit() { return $this->hasOne( Uom::class, [ 'id' => 'lengthUnitId' ] )->from( CartTables::TABLE_UOM . ' as lengthUnit' ); } public function isNew() { return $this->status == self::STATUS_NEW; } public function isCancelled() { return $this->status == self::STATUS_CANCELLED; } public function isDelivered() { return $this->status == self::STATUS_DELIVERED; } public function isReturned() { return $this->status == self::STATUS_RETURNED; } public function isReceived() { return $this->status == self::STATUS_RECEIVED; } public function getStatusStr() { return static::$statusMap[ $this->status ]; } /** * Returns the total price of the item. * * Total Price = ( Unit Price - Unit Discount ) * Purchasing Quantity * * @param type $precision * @return type */ public function getTotalPrice( $precision = 2 ) { $price = ( $this->price - $this->discount ) * $this->purchase; return round( $price, $precision ); } // Static Methods ---------------------------------------------- // Yii parent classes -------------------- // yii\db\ActiveRecord ---- /** * @inheritdoc */ public static function tableName() { return CartTables::getTableName( CartTables::TABLE_ORDER_ITEM ); } // CMG parent classes -------------------- // OrderItem ----------------------------- // Read - Query ----------- /** * @inheritdoc */ public static function queryWithHasOne( $config = [] ) { $relations = isset( $config[ 'relations' ] ) ? $config[ 'relations' ] : [ 'order', 'purchasingUnit', 'creator' ]; $config[ 'relations' ] = $relations; return parent::queryWithAll( $config ); } public static function queryWithUoms( $config = [] ) { $relations = isset( $config[ 'relations' ] ) ? $config[ 'relations' ] : [ 'order', 'primaryUnit', 'purchasingUnit', 'quantityUnit', 'weightUnit', 'volumeUnit', 'lengthUnit', 'creator' ]; $config[ 'relations' ] = $relations; return parent::queryWithAll( $config ); } /** * Return query to find the order item by order id. * * @param integer $orderId * @return \yii\db\ActiveQuery to query by order id. */ public static function queryByOrderId( $orderId ) { return self::find()->where( 'orderId=:oid', [ ':oid' => $orderId ] ); } // Read - Find ------------ /** * Return the order items associated with given order id. * * @param integer $orderId * @return OrderItem[] */ public static function findByOrderId( $orderId ) { return self::queryByOrderId( $orderId )->all(); } /** * Return the order item associated with given parent id, parent type and order id. * * @param integer $parentId * @param string $parentType * @param integer $orderId * @return OrderItem */ public static function findByParentOrderId( $parentId, $parentType, $orderId ) { return self::find()->where( 'parentId=:pid AND parentType=:ptype AND orderId=:oid', [ ':pid' => $parentId, ':ptype' => $parentType, ':oid' => $orderId ] )->one(); } // Create ----------------- // Update ----------------- // Delete ----------------- /** * Delete order items associated with given order id. * * @param integer $orderId * @return integer Number of rows. */ public static function deleteByOrderId( $orderId ) { return self::deleteAll( 'orderId=:id', [ ':id' => $orderId ] ); } }
cmsgears/module-cart
common/models/resources/OrderItem.php
PHP
gpl-3.0
14,285
<?php //---------------------------------------------------------------------- // // Copyright (C) 2017-2022 Artem Rodygin // // This file is part of eTraxis. // // You should have received a copy of the GNU General Public License // along with eTraxis. If not, see <https://www.gnu.org/licenses/>. // //---------------------------------------------------------------------- namespace App\Controller; use KnpU\OAuth2ClientBundle\Client\ClientRegistry; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * OAuth2 controller. * * @Route("/oauth2") */ class OAuth2Controller extends AbstractController { /** * OAuth2 callback URL for Microsoft Azure. * * @Route("/azure", name="oauth2_azure") */ public function azure(ClientRegistry $clientRegistry): Response { if ($this->getUser()) { return $this->forward(LoginController::class); } return $clientRegistry->getClient('azure')->redirect([], []); } /** * OAuth2 callback URL for Google. * * @Route("/google", name="oauth2_google") */ public function google(ClientRegistry $clientRegistry): Response { if ($this->getUser()) { return $this->forward(LoginController::class); } return $clientRegistry->getClient('google')->redirect([], []); } }
etraxis/etraxis
src/Controller/OAuth2Controller.php
PHP
gpl-3.0
1,461
/* * 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/>. */ /** * AbstractIntegralNumberEditor.java * Copyright (C) 2009 University of Waikato, Hamilton, New Zealand */ package adams.gui.goe; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JComponent; import javax.swing.JPopupMenu; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import adams.gui.core.MouseUtils; /** * An abstract ancestor for custom editors for integral numbers, like bytes, * shorts, integers and longs. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 4943 $ */ public abstract class AbstractIntegralNumberEditor extends AbstractNumberEditor { /** * Creates the spinner model to use. * * @return the model */ protected SpinnerNumberModel createModel() { SpinnerNumberModel result; result = new SpinnerNumberModel(); updateBounds(result); return result; } /** * Updates the bounds of the spinner model. * * @param model the model to update */ protected abstract void updateBounds(SpinnerNumberModel model); /** * Updates the bounds. */ protected void updateBounds() { SpinnerNumberModel model; if (m_CustomEditor != null) { model = (SpinnerNumberModel) ((JSpinner) m_CustomEditor).getModel(); updateBounds(model); } } /** * Creates the custom editor to use. * * @return the custom editor */ protected JComponent createCustomEditor() { JSpinner result; result = new JSpinner(createModel()); result.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSpinner spinner = (JSpinner) e.getSource(); if (!spinner.getValue().equals(getValue())) setValue(spinner.getValue()); } }); // workaround for mouselistener problem: // http://bugs.sun.com/view_bug.do?bug_id=4760088 ((JSpinner.DefaultEditor) result.getEditor()).getTextField().addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { JPopupMenu popup = createPopup(); if (MouseUtils.isRightClick(e) && (popup != null)) popup.show(m_CustomEditor, e.getX(), e.getY()); else super.mouseClicked(e); } }); return result; } /** * Initializes the display of the value. */ protected void initForDisplay() { resetChosenOption(); if (!((JSpinner) m_CustomEditor).getValue().equals(getValue())) ((JSpinner) m_CustomEditor).setValue(getValue()); } }
automenta/adams-core
src/main/java/adams/gui/goe/AbstractIntegralNumberEditor.java
Java
gpl-3.0
3,227
<?php if (!defined('PmWiki')) exit(); ## This is a sample config.php file. To use this file, copy it to ## local/config.php, then edit it for whatever customizations you want. ## Also, be sure to take a look at http://www.pmwiki.org/wiki/Cookbook ## for more details on the types of customizations that can be added ## to PmWiki. ## $WikiTitle is the name that appears in the browser's title bar. $WikiTitle = 'PmWiki'; ## $ScriptUrl is your preferred URL for accessing wiki pages ## $PubDirUrl is the URL for the pub directory. # $ScriptUrl = 'http://www.mydomain.com/path/to/pmwiki.php'; # $PubDirUrl = 'http://www.mydomain.com/path/to/pub'; ## If you want to use URLs of the form .../pmwiki.php/Group/PageName ## instead of .../pmwiki.php?p=Group.PageName, try setting ## $EnablePathInfo below. Note that this doesn't work in all environments, ## it depends on your webserver and PHP configuration. You might also ## want to check http://www.pmwiki.org/wiki/Cookbook/CleanUrls more ## details about this setting and other ways to create nicer-looking urls. # $EnablePathInfo = 1; ## $PageLogoUrl is the URL for a logo image -- you can change this ## to your own logo if you wish. # $PageLogoUrl = "$PubDirUrl/skins/pmwiki/pmwiki-32.gif"; ## If you want to have a custom skin, then set $Skin to the name ## of the directory (in pub/skins/) that contains your skin files. ## See PmWiki.Skins and Cookbook.Skins. # $Skin = 'pmwiki'; ## You'll probably want to set an administrative password that you ## can use to get into password-protected pages. Also, by default ## the "attr" passwords for the PmWiki and Main groups are locked, so ## an admin password is a good way to unlock those. See PmWiki.Passwords ## and PmWiki.PasswordsAdmin. # $DefaultPasswords['admin'] = crypt('secret'); ## Unicode (UTF-8) allows the display of all languages and all alphabets. ## Highly recommended for new wikis. include_once("scripts/xlpage-utf-8.php"); include_once("$FarmD/cookbook/chordpro.php"); ## If you're running a publicly available site and allow anyone to ## edit without requiring a password, you probably want to put some ## blocklists in place to avoid wikispam. See PmWiki.Blocklist. # $EnableBlocklist = 1; # enable manual blocklists # $EnableBlocklist = 10; # enable automatic blocklists ## PmWiki comes with graphical user interface buttons for editing; ## to enable these buttons, set $EnableGUIButtons to 1. # $EnableGUIButtons = 1; ## To enable markup syntax from the Creole common wiki markup language ## (http://www.wikicreole.org/), include it here: # include_once("scripts/creole.php"); ## Some sites may want leading spaces on markup lines to indicate ## "preformatted text blocks", set $EnableWSPre=1 if you want to do ## this. Setting it to a higher number increases the number of ## space characters required on a line to count as "preformatted text". # $EnableWSPre = 1; # lines beginning with space are preformatted (default) # $EnableWSPre = 4; # lines with 4 or more spaces are preformatted # $EnableWSPre = 0; # disabled ## If you want uploads enabled on your system, set $EnableUpload=1. ## You'll also need to set a default upload password, or else set ## passwords on individual groups and pages. For more information ## see PmWiki.UploadsAdmin. # $EnableUpload = 1; # $UploadPermAdd = 0; # $DefaultPasswords['upload'] = crypt('secret'); ## Setting $EnableDiag turns on the ?action=diag and ?action=phpinfo ## actions, which often helps others to remotely troubleshoot ## various configuration and execution problems. # $EnableDiag = 1; # enable remote diagnostics ## By default, PmWiki doesn't allow browsers to cache pages. Setting ## $EnableIMSCaching=1; will re-enable browser caches in a somewhat ## smart manner. Note that you may want to have caching disabled while ## adjusting configuration files or layout templates. # $EnableIMSCaching = 1; # allow browser caching ## Set $SpaceWikiWords if you want WikiWords to automatically ## have spaces before each sequence of capital letters. # $SpaceWikiWords = 1; # turn on WikiWord spacing ## Set $EnableWikiWords if you want to allow WikiWord links. ## For more options with WikiWords, see scripts/wikiwords.php . # $EnableWikiWords = 1; # enable WikiWord links ## $DiffKeepDays specifies the minimum number of days to keep a page's ## revision history. The default is 3650 (approximately 10 years). # $DiffKeepDays=30; # keep page history at least 30 days ## By default, viewers are prevented from seeing the existence ## of read-protected pages in search results and page listings, ## but this can be slow as PmWiki has to check the permissions ## of each page. Setting $EnablePageListProtect to zero will ## speed things up considerably, but it will also mean that ## viewers may learn of the existence of read-protected pages. ## (It does not enable them to access the contents of the pages.) # $EnablePageListProtect = 0; ## The refcount.php script enables ?action=refcount, which helps to ## find missing and orphaned pages. See PmWiki.RefCount. # if ($action == 'refcount') include_once("scripts/refcount.php"); ## The feeds.php script enables ?action=rss, ?action=atom, ?action=rdf, ## and ?action=dc, for generation of syndication feeds in various formats. # if ($action == 'rss') include_once("scripts/feeds.php"); # RSS 2.0 # if ($action == 'atom') include_once("scripts/feeds.php"); # Atom 1.0 # if ($action == 'dc') include_once("scripts/feeds.php"); # Dublin Core # if ($action == 'rdf') include_once("scripts/feeds.php"); # RSS 1.0 ## In the 2.2.0-beta series, {$var} page variables were absolute, but now ## relative page variables provide greater flexibility and are recommended. ## (If you're starting a new site, it's best to leave this setting alone.) # $EnableRelativePageVars = 1; # 1=relative; 0=absolute ## By default, pages in the Category group are manually created. ## Uncomment the following line to have blank category pages ## automatically created whenever a link to a non-existent ## category page is saved. (The page is created only if ## the author has edit permissions to the Category group.) # $AutoCreate['/^Category\\./'] = array('ctime' => $Now); ## PmWiki allows a great deal of flexibility for creating custom markup. ## To add support for '*bold*' and '~italic~' markup (the single quotes ## are part of the markup), uncomment the following lines. ## (See PmWiki.CustomMarkup and the Cookbook for details and examples.) # Markup("'~", "inline", "/'~(.*?)~'/", "<i>$1</i>"); # '~italic~' # Markup("'*", "inline", "/'\\*(.*?)\\*'/", "<b>$1</b>"); # '*bold*' ## If you want to have to approve links to external sites before they ## are turned into links, uncomment the line below. See PmWiki.UrlApprovals. ## Also, setting $UnapprovedLinkCountMax limits the number of unapproved ## links that are allowed in a page (useful to control wikispam). # $UnapprovedLinkCountMax = 10; # include_once("scripts/urlapprove.php"); ## The following lines make additional editing buttons appear in the ## edit page for subheadings, lists, tables, etc. # $GUIButtons['h2'] = array(400, '\\n!! ', '\\n', '$[Heading]', # '$GUIButtonDirUrlFmt/h2.gif"$[Heading]"'); # $GUIButtons['h3'] = array(402, '\\n!!! ', '\\n', '$[Subheading]', # '$GUIButtonDirUrlFmt/h3.gif"$[Subheading]"'); # $GUIButtons['indent'] = array(500, '\\n->', '\\n', '$[Indented text]', # '$GUIButtonDirUrlFmt/indent.gif"$[Indented text]"'); # $GUIButtons['outdent'] = array(510, '\\n-<', '\\n', '$[Hanging indent]', # '$GUIButtonDirUrlFmt/outdent.gif"$[Hanging indent]"'); # $GUIButtons['ol'] = array(520, '\\n# ', '\\n', '$[Ordered list]', # '$GUIButtonDirUrlFmt/ol.gif"$[Ordered (numbered) list]"'); # $GUIButtons['ul'] = array(530, '\\n* ', '\\n', '$[Unordered list]', # '$GUIButtonDirUrlFmt/ul.gif"$[Unordered (bullet) list]"'); # $GUIButtons['hr'] = array(540, '\\n----\\n', '', '', # '$GUIButtonDirUrlFmt/hr.gif"$[Horizontal rule]"'); # $GUIButtons['table'] = array(600, # '||border=1 width=80%\\n||!Hdr ||!Hdr ||!Hdr ||\\n|| || || ||\\n|| || || ||\\n', '', '', # '$GUIButtonDirUrlFmt/table.gif"$[Table]"');
tukusejssirs/eSpievatko
spievatko/espievatko/pmwiki_cho/local/config.php
PHP
gpl-3.0
8,561
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # Copyright (c) 2017 Stephen Bunn (stephen@bunn.io) # GNU GPLv3 <https://www.gnu.org/licenses/gpl-3.0.en.html> from ._common import * from .rethinkdb import RethinkDBPipe from .mongodb import MongoDBPipe
ritashugisha/neat
neat/pipe/__init__.py
Python
gpl-3.0
255
package fi.pyramus.dao.users; import java.util.Date; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import fi.pyramus.dao.PyramusEntityDAO; import fi.pyramus.domainmodel.base.Person; import fi.pyramus.domainmodel.users.PasswordResetRequest; import fi.pyramus.domainmodel.users.PasswordResetRequest_; @Stateless public class PasswordResetRequestDAO extends PyramusEntityDAO<PasswordResetRequest> { public PasswordResetRequest create(Person person, String secret, Date date) { EntityManager entityManager = getEntityManager(); PasswordResetRequest passwordResetRequest = new PasswordResetRequest(); passwordResetRequest.setPerson(person); passwordResetRequest.setSecret(secret); passwordResetRequest.setDate(date); entityManager.persist(passwordResetRequest); return passwordResetRequest; } public PasswordResetRequest findBySecret(String secret) { EntityManager entityManager = getEntityManager(); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<PasswordResetRequest> criteria = criteriaBuilder.createQuery(PasswordResetRequest.class); Root<PasswordResetRequest> root = criteria.from(PasswordResetRequest.class); criteria.select(root); criteria.where( criteriaBuilder.equal(root.get(PasswordResetRequest_.secret), secret) ); return getSingleResult(entityManager.createQuery(criteria)); } public List<PasswordResetRequest> listByPerson(Person person) { EntityManager entityManager = getEntityManager(); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<PasswordResetRequest> criteria = criteriaBuilder.createQuery(PasswordResetRequest.class); Root<PasswordResetRequest> root = criteria.from(PasswordResetRequest.class); criteria.select(root); criteria.where( criteriaBuilder.equal(root.get(PasswordResetRequest_.person), person) ); return entityManager.createQuery(criteria).getResultList(); } @Override public void delete(PasswordResetRequest request) { super.delete(request); } }
leafsoftinfo/pyramus
persistence/src/main/java/fi/pyramus/dao/users/PasswordResetRequestDAO.java
Java
gpl-3.0
2,326
import pandas as pd from larray.core.array import Array from larray.inout.pandas import from_frame __all__ = ['read_stata'] def read_stata(filepath_or_buffer, index_col=None, sort_rows=False, sort_columns=False, **kwargs) -> Array: r""" Reads Stata .dta file and returns an Array with the contents Parameters ---------- filepath_or_buffer : str or file-like object Path to .dta file or a file handle. index_col : str or None, optional Name of column to set as index. Defaults to None. sort_rows : bool, optional Whether or not to sort the rows alphabetically (sorting is more efficient than not sorting). This only makes sense in combination with index_col. Defaults to False. sort_columns : bool, optional Whether or not to sort the columns alphabetically (sorting is more efficient than not sorting). Defaults to False. Returns ------- Array See Also -------- Array.to_stata Notes ----- The round trip to Stata (Array.to_stata followed by read_stata) loose the name of the "column" axis. Examples -------- >>> read_stata('test.dta') # doctest: +SKIP {0}\{1} row country sex 0 0 BE F 1 1 FR M 2 2 FR F >>> read_stata('test.dta', index_col='row') # doctest: +SKIP row\{1} country sex 0 BE F 1 FR M 2 FR F """ df = pd.read_stata(filepath_or_buffer, index_col=index_col, **kwargs) return from_frame(df, sort_rows=sort_rows, sort_columns=sort_columns)
gdementen/larray
larray/inout/stata.py
Python
gpl-3.0
1,657
using System.Threading.Tasks; namespace Yavsc.Services { public interface ISmsSender { Task SendSmsAsync(TwilioSettings settings, string number, string message); } }
pazof/yavsc
src/Yavsc.Server/Interfaces/ISmsSender.cs
C#
gpl-3.0
188
<?php namespace MultisiteMigrationFramework\modules; use MultisiteMigrationFramework\classes\MultisiteMigration; use MultisiteMigrationFramework\classes\MultisiteMigrationSystemAuthorization; if (! defined('ABSPATH')) { exit; } /** * This module allows a new site to be created in the network with a specified blog ID * * @class CreateBlogSpecificID * @version 1.0 * @package MULTISITE-Migration/Modules * @category Class * @author Emerson Maningo */ final class CreateBlogSpecificID { /** * Multisite migration property */ private $multisite_migration; /** * System authorization */ private $system_authorization; /** * Constructor * @param MultisiteMigration $MultisiteMigration */ public function __construct(MultisiteMigration $MultisiteMigration, MultisiteMigrationSystemAuthorization $system_authorization) { $this->multisite_migration = $MultisiteMigration; $this->system_authorization = $system_authorization; } /** * Get multisite migration * @return \MultisiteMigrationFramework\classes\MultisiteMigration * @compatible 5.6 */ public function getMultisiteMigration() { return $this->multisite_migration; } /** * Get system authorization * @return \MultisiteMigrationFramework\classes\MultisiteMigrationSystemAuthorization * @compatible 5.6 */ public function getSystemAuthorization() { return $this->system_authorization; } /** * Init hooks * @compatible 5.6 */ final public function initHooks() { if (! $this->getSystemAuthorization()->isUserAuthorized()) { return; } add_filter('query', array( $this, 'filterBlogIdToTargetBlogIdInQuery'), 0, 1); add_action('network_site_new_form', array( $this, 'addNewBlogIdForm')); } /** * Filter passed blog ID to target ID when conditions are meet * Hooked to `query` * @param string $query * @return void|string * @compatible 5.6 */ public function filterBlogIdToTargetBlogIdInQuery($query = '') { if (! $this->getSystemAuthorization()->isUserAuthorized()) { return $query; } if ($this->isInsertQueryForWpBlogs($query) && $this->validateChangeBlogIdRequest()) { $target_blogid = $this->validateChangeBlogIdRequest(); $dissected_query_array = $this->dissectQuery($query); if (! is_array($dissected_query_array) || empty($dissected_query_array)) { return $query; } $replaceables = array(); foreach ($dissected_query_array as $k => $v) { if (strpos($v, "(") !== false) { $replaceables[] = $k; } } $count = count($replaceables); if (2 !== $count) { return $query; } foreach ($replaceables as $key_count => $key_to_update) { if (0 === $key_count && isset($dissected_query_array[ $key_to_update ])) { //Inject `blog_id` field $value_to_update = $dissected_query_array[ $key_to_update ]; $blogid_field_injected = str_replace("(", "(`blog_id`,", $value_to_update); $dissected_query_array[ $key_to_update ] = $blogid_field_injected; } elseif (1 === $key_count && isset($dissected_query_array[ $key_to_update ])) { //Inject `blog_id` value $value_to_update = $dissected_query_array[ $key_to_update ]; $blogid_value_injected = str_replace("(", "($target_blogid,", $value_to_update); $dissected_query_array[ $key_to_update ] = $blogid_value_injected; } } $query = implode(" ", $dissected_query_array); } return $query; } /** * Add new blog ID form in create site form * @compatible 5.6 */ public function addNewBlogIdForm() { ?> <h3><?php echo sprintf( '%s ( %s )', __('Multisite Migration Target Blog ID', $this->getMultisiteMigration()->getSystemInitialization()->getTranslationDomain()), __('Optional', $this->getMultisiteMigration()->getSystemInitialization()->getTranslationDomain()) ); ?></h3> <p><?php _e('You can assign a specific blog ID for this newly created site. This is optional. Make sure the target blog ID is available and not used with any site.', $this->getMultisiteMigration()->getSystemInitialization()->getTranslationDomain()); ?></p> <p><?php _e('If target blog ID provided is already used with existing sites; WordPress will generate a new blog ID. Then the target blog ID is ignored.', $this->getMultisiteMigration()->getSystemInitialization()->getTranslationDomain()); ?></p> <input type="number" name="multisite_migration_target_blog_id" min="1"> <input type="hidden" name="multisite_migration_changeblogid_nonce" value="<?php echo wp_create_nonce('multisite_migration_changeblogid_nonce')?>" /> <?php } /** * Validate change blog ID request * @return number * @compatible 5.6 */ protected function validateChangeBlogIdRequest() { $valid = 0; /** * Get posted request */ $post = $this->getPostedRequest(); if (! $post) { return $valid; } if (! isset($post['add-site'])) { return $valid; } if (! isset($post['multisite_migration_changeblogid_nonce']) || ! isset($post['multisite_migration_target_blog_id'])) { return $valid; } $nonce = $post['multisite_migration_changeblogid_nonce']; $blog_id = (int) $post['multisite_migration_target_blog_id']; /** * Validate nonce */ if (! wp_verify_nonce($nonce, 'multisite_migration_changeblogid_nonce') || ! $blog_id) { return $valid; } /** * Validate if blog is available */ $blogdetails = get_blog_details($blog_id); if (! $blogdetails) { //Blog is available $valid = $blog_id; } return $valid; } /** * Get posted request * @return mixed * @compatible 5.6 */ protected function getPostedRequest() { return filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING); } /** * Dissect query * @param string $query * @return array * @compatible 5.6 */ protected function dissectQuery($query = '') { $dissected_query_array = array(); if (! empty($query)) { $dissected_query_array = explode(" ", $query); } return $dissected_query_array; } /** * Analyze if the query is an INSERT statement to the `wp_blogs` table * @param string $query * @return boolean * @compatible 5.6 */ protected function isInsertQueryForWpBlogs($query = '') { $ret = false; $dissected_query_array = $this->dissectQuery($query); if (! isset($dissected_query_array[0])) { return $ret; } $test = strtolower($dissected_query_array[0]); if ('insert' !== $test) { return $ret; } $into_key = (int) array_search(strtolower('INTO'), array_map('strtolower', $dissected_query_array)); if (! $into_key) { return $ret; } global $wpdb; if (! isset($wpdb->blogs)) { return $ret; } $wpblog_table = $wpdb->blogs; $table_key = $into_key + 1; if (! isset($dissected_query_array[ $table_key ])) { return $ret; } $given = $dissected_query_array[ $table_key ]; $given = str_replace(array( '`', "'", '"' ), array( '','','' ), $given); if (strpos($wpblog_table, $given) !== false) { //Found $ret = true; } return $ret; } }
codex-m/multisite-migration
modules/CreateBlogSpecificID.php
PHP
gpl-3.0
8,311
package com.stt.util2; import java.util.UUID; /** * @Author shitongtong * <p> * Created by shitongtong on 2017/3/24. */ public class UUIDUtil { /** * 带"-"分割的 * @return */ public static String randomUUID(){ return UUID.randomUUID().toString(); } /** * 不带"-"分割的 * @return */ public static String randomUUID2(){ return noSplit(randomUUID()); } /** * 去"-"分割 * @param uuid * @return */ public static String noSplit(String uuid){ return uuid.replaceAll("-",""); } }
shitongtong/libraryManage
stt-util/src/main/java/com/stt/util2/UUIDUtil.java
Java
gpl-3.0
603
#include "mesh_chunk_builder.h" #include "mesh_chunk_vertices.h" #include "chunk.h" #include "color.h" #include "voxel.h" using minecpp::MeshChunkBuilder; using minecpp::MeshChunkVertices; using minecpp::RGBA8; void MeshChunkBuilder::computeLightsPlacing(unsigned componentIndex) noexcept { while (!lightsPlace[componentIndex].empty()) { const LightPlace& lightPlace = lightsPlace[componentIndex].front(); const int x = lightPlace.index & (constants::CHUNK_WIDTH - 1); const int y = lightPlace.index >> 8; const int z = (lightPlace.index >> 4) & (constants::CHUNK_WIDTH - 1); Chunk* const chunk = lightPlace.chunk; const unsigned lightComponent = color::getComponent(chunk->getLight(lightPlace.index), componentIndex); lightsPlace[componentIndex].pop(); processLightsPlacing(chunk, x - 1, y , z , lightComponent, componentIndex); processLightsPlacing(chunk, x + 1, y , z , lightComponent, componentIndex); processLightsPlacing(chunk, x , y - 1, z , lightComponent, componentIndex); processLightsPlacing(chunk, x , y + 1, z , lightComponent, componentIndex); processLightsPlacing(chunk, x , y , z - 1, lightComponent, componentIndex); processLightsPlacing(chunk, x , y , z + 1, lightComponent, componentIndex); } } void MeshChunkBuilder::processLightsPlacing(Chunk* chunk, int x, int y, int z, unsigned lightComponent, unsigned componentIndex) noexcept { ptrdiff_t index; Chunk* const chunkFound = chunk->findChunk(x, y, z, index); if (chunkFound && !chunkFound->getVoxel(index)) { const unsigned neightborLight = chunkFound->getLight(index); const unsigned neightborLightComponent = color::getComponent(neightborLight, componentIndex); if (neightborLightComponent + 1 < lightComponent) { lightsPlace[componentIndex].push({index, chunkFound}); chunkFound->setLight(index, color::setComponent(neightborLight, componentIndex, lightComponent - 1)); } } } void MeshChunkBuilder::computeLightsRemoving(unsigned componentIndex) noexcept { while (!lightsRemove[componentIndex].empty()) { const LightRemove& lightRemove = lightsRemove[componentIndex].front(); const int x = lightRemove.index & (constants::CHUNK_WIDTH - 1); const int y = lightRemove.index >> 8; const int z = (lightRemove.index >> 4) & (constants::CHUNK_WIDTH - 1); Chunk* const chunk = lightRemove.chunk; const unsigned lightComponent = color::getComponent(lightRemove.light, componentIndex); lightsRemove[componentIndex].pop(); processLightsRemoving(chunk, x - 1, y , z , lightComponent, componentIndex); processLightsRemoving(chunk, x + 1, y , z , lightComponent, componentIndex); processLightsRemoving(chunk, x , y - 1, z , lightComponent, componentIndex); processLightsRemoving(chunk, x , y + 1, z , lightComponent, componentIndex); processLightsRemoving(chunk, x , y , z - 1, lightComponent, componentIndex); processLightsRemoving(chunk, x , y , z + 1, lightComponent, componentIndex); } } void MeshChunkBuilder::processLightsRemoving(Chunk* chunk, int x, int y, int z, unsigned lightComponent, unsigned componentIndex) noexcept { ptrdiff_t index; Chunk* const chunkFound = chunk->findChunk(x, y, z, index); if (chunkFound) { const unsigned neightborLight = chunkFound->getLight(index); const unsigned neightborLightComponent = color::getComponent(neightborLight, componentIndex); if (neightborLightComponent && neightborLightComponent < lightComponent) { lightsRemove[componentIndex].push({index, chunkFound, neightborLightComponent}); chunkFound->setLight(index, color::setComponent(neightborLight, componentIndex, 0)); } else if (neightborLightComponent >= lightComponent) { lightsPlace[componentIndex].push({index, chunkFound}); } } } void MeshChunkBuilder::computeLights() noexcept { for (unsigned i = 0; i < 3; ++i) { computeLightsRemoving(i); computeLightsPlacing(i); } computeSunLightsRemoving(); computeSunLightsPlacing(); } void MeshChunkBuilder::computeSunLightsPlacing() noexcept { while (!lightsPlace[3].empty()) { const LightPlace& lightPlace = lightsPlace[3].front(); const int x = lightPlace.index & (constants::CHUNK_WIDTH - 1); const int y = lightPlace.index >> 8; const int z = (lightPlace.index >> 4) & (constants::CHUNK_WIDTH - 1); Chunk* const chunk = lightPlace.chunk; const unsigned lightComponent = chunk->getLight(lightPlace.index) >> 12 & 15; lightsPlace[3].pop(); processSunLightsPlacing(chunk, x - 1, y , z , lightComponent, 0); processSunLightsPlacing(chunk, x + 1, y , z , lightComponent, 0); processSunLightsPlacing(chunk, x , y - 1, z , lightComponent, 1); processSunLightsPlacing(chunk, x , y + 1, z , lightComponent, 0); processSunLightsPlacing(chunk, x , y , z - 1, lightComponent, 0); processSunLightsPlacing(chunk, x , y , z + 1, lightComponent, 0); } } void MeshChunkBuilder::processSunLightsPlacing(Chunk* chunk, int x, int y, int z, unsigned lightComponent, bool vertDown) noexcept { ptrdiff_t index; Chunk* const chunkFound = chunk->findChunk(x, y, z, index); if (chunkFound && !chunkFound->getVoxel(index)) { const unsigned neightborLight = chunkFound->getLight(index); const unsigned neightborLightComponent = neightborLight >> 12 & 15; if (vertDown && lightComponent == constants::MAX_LIGHT_LEVEL) { lightsPlace[3].push({index, chunkFound}); chunkFound->setLight(index, (neightborLight & 0x0FFF) | 0xF000); } else if (neightborLightComponent + 1 < lightComponent) { lightsPlace[3].push({index, chunkFound}); chunkFound->setLight(index, (neightborLight & 0x0FFF) | (lightComponent - 1) << 12); } } } void MeshChunkBuilder::computeSunLightsRemoving() noexcept { while (!lightsRemove[3].empty()) { const LightRemove& lightRemove = lightsRemove[3].front(); const int x = lightRemove.index & (constants::CHUNK_WIDTH - 1); const int y = lightRemove.index >> 8; const int z = (lightRemove.index >> 4) & (constants::CHUNK_WIDTH - 1); Chunk* const chunk = lightRemove.chunk; const unsigned lightComponent = lightRemove.light >> 12 & 15; lightsRemove[3].pop(); processSunLightsRemoving(chunk, x - 1, y , z , lightComponent, 0); processSunLightsRemoving(chunk, x + 1, y , z , lightComponent, 0); processSunLightsRemoving(chunk, x , y - 1, z , lightComponent, 1); processSunLightsRemoving(chunk, x , y + 1, z , lightComponent, 0); processSunLightsRemoving(chunk, x , y , z - 1, lightComponent, 0); processSunLightsRemoving(chunk, x , y , z + 1, lightComponent, 0); } } void MeshChunkBuilder::processSunLightsRemoving(Chunk* chunk, int x, int y, int z, unsigned lightComponent, bool vertDown) noexcept { ptrdiff_t index; Chunk* const chunkFound = chunk->findChunk(x, y, z, index); if (chunkFound) { const unsigned neightborLight = chunkFound->getLight(index); const unsigned neightborLightComponent = neightborLight >> 12 & 15; if (neightborLightComponent) { if (neightborLightComponent < lightComponent || (vertDown && lightComponent == constants::MAX_LIGHT_LEVEL)) { lightsRemove[3].push({index, chunkFound, neightborLightComponent}); chunkFound->setLight(index, neightborLight & 0xFFF); } else if (neightborLightComponent >= lightComponent) { lightsPlace[3].push({index, chunkFound}); } } } } void MeshChunkBuilder::prepareSunLights(Chunk* chunk) noexcept { for (int i = 0; i < constants::CHUNK_WIDTH; ++i) { for (int j = 0; j < constants::CHUNK_WIDTH; ++j) { for (int k = constants::CHUNK_HEIGHT - 1; k >= 0; --k) { const ptrdiff_t index = Chunk::getVoxelIndex(j, k, i); if (chunk->getVoxel(index)) break; chunk->setLight(index, (chunk->getLight(index) & 0xFFF) | 0xF000); } } } for (int i = 0; i < constants::CHUNK_WIDTH; ++i) { for (int j = 0; j < constants::CHUNK_WIDTH; ++j) { for (int k = constants::CHUNK_HEIGHT - 1; k >= 0; --k) { if (chunk->getVoxel(Chunk::getVoxelIndex(j, k, i))) break; processLightsPlacing(chunk, k - 1, i , j , constants::MAX_LIGHT_LEVEL, 3); processLightsPlacing(chunk, k + 1, i , j , constants::MAX_LIGHT_LEVEL, 3); processLightsPlacing(chunk, k , i , j - 1, constants::MAX_LIGHT_LEVEL, 3); processLightsPlacing(chunk, k , i , j + 1, constants::MAX_LIGHT_LEVEL, 3); } } } } MeshChunkVertices MeshChunkBuilder::build(const Chunk& chunk) const noexcept { std::vector<VertexP3FRGBA8> verticesDefault; for (int i = 0; i < constants::CHUNK_HEIGHT; ++i) { for (int j = 0; j < constants::CHUNK_WIDTH; ++j) { for (int k = 0; k < constants::CHUNK_WIDTH; ++k) { const unsigned voxel = chunk.getVoxel(Chunk::getVoxelIndex(k, i, j)); if (!voxel) continue; const unsigned voxelColor = voxel::getColor(voxel); const unsigned char r = voxelColor & 15; const unsigned char g = voxelColor >> 4 & 15; const unsigned char b = voxelColor >> 8 & 15; const unsigned char a = voxelColor >> 12 & 15; if (!chunk.findVoxel(k - 1, i, j)) { quadYZ({&verticesDefault, &chunk, k, i, j, r, g, b, a, 0}); } if (!chunk.findVoxel(k + 1, i, j)) { quadYZ({&verticesDefault, &chunk, k, i, j, r, g, b, a, 1}); } if (!chunk.findVoxel(k, i, j - 1)) { quadXY({&verticesDefault, &chunk, k, i, j, r, g, b, a, 0}); } if (!chunk.findVoxel(k, i, j + 1)) { quadXY({&verticesDefault, &chunk, k, i, j, r, g, b, a, 1}); } if (!chunk.findVoxel(k, i - 1, j)) { quadXZ({&verticesDefault, &chunk, k, i, j, r, g, b, a, 0}); } if (!chunk.findVoxel(k, i + 1, j)) { quadXZ({&verticesDefault, &chunk, k, i, j, r, g, b, a, 1}); } } } } return {std::move(verticesDefault)}; } void MeshChunkBuilder::placeLight(Chunk* chunk, ptrdiff_t index, unsigned light) noexcept { for (unsigned i = 0; i < 3; ++i) lightsPlace[i].push({index, chunk}); chunk->setLight(index, light); } void MeshChunkBuilder::removeLight(Chunk* chunk, ptrdiff_t index) noexcept { const unsigned light = chunk->getLight(index); for (unsigned i = 0; i < 3; ++i) lightsRemove[i].push({index, chunk, color::getComponent(light, i)}); chunk->setLight(index, light & 0xF000); } void MeshChunkBuilder::removeSunLight(Chunk* chunk, ptrdiff_t index) noexcept { const unsigned light = chunk->getLight(index); lightsRemove[3].push({index, chunk, light & 0xF000}); chunk->setLight(index, light & 0xFFF); } void MeshChunkBuilder::quadXY(const BuildingInfo& buildingInfo) const noexcept { const float x = buildingInfo.x; const float y = buildingInfo.y; const float z = buildingInfo.z + buildingInfo.side; const int dz = (buildingInfo.side << 1) - 1; const RGB8 vertexColor{buildingInfo.r, buildingInfo.g, buildingInfo.b}; const RGBA8 color1 = computeVertexXYColor(buildingInfo, -1, -1, dz); const RGBA8 color2 = computeVertexXYColor(buildingInfo, 1, 1, dz); const RGBA8 color3 = computeVertexXYColor(buildingInfo, 1, -1, dz); const RGBA8 color4 = computeVertexXYColor(buildingInfo, -1, 1, dz); buildingInfo.vertices->push_back({{x , y , z}, vertexColor, color1}); buildingInfo.vertices->push_back({{x + 1.0F, y , z}, vertexColor, color3}); buildingInfo.vertices->push_back({{x + 1.0F, y + 1.0F, z}, vertexColor, color2}); buildingInfo.vertices->push_back({{x + 1.0F, y + 1.0F, z}, vertexColor, color2}); buildingInfo.vertices->push_back({{x , y + 1.0F, z}, vertexColor, color4}); buildingInfo.vertices->push_back({{x , y , z}, vertexColor, color1}); } void MeshChunkBuilder::quadYZ(const BuildingInfo& buildingInfo) const noexcept { const float x = buildingInfo.x + buildingInfo.side; const float y = buildingInfo.y; const float z = buildingInfo.z; const int dx = (buildingInfo.side << 1) - 1; const RGB8 vertexColor{buildingInfo.r, buildingInfo.g, buildingInfo.b}; const RGBA8 color1 = computeVertexYZColor(buildingInfo, dx, -1, -1); const RGBA8 color2 = computeVertexYZColor(buildingInfo, dx, 1, 1); const RGBA8 color3 = computeVertexYZColor(buildingInfo, dx, -1, 1); const RGBA8 color4 = computeVertexYZColor(buildingInfo, dx, 1, -1); buildingInfo.vertices->push_back({{x, y , z }, vertexColor, color1}); buildingInfo.vertices->push_back({{x, y , z + 1.0F}, vertexColor, color3}); buildingInfo.vertices->push_back({{x, y + 1.0F, z + 1.0F}, vertexColor, color2}); buildingInfo.vertices->push_back({{x, y + 1.0F, z + 1.0F}, vertexColor, color2}); buildingInfo.vertices->push_back({{x, y + 1.0F, z }, vertexColor, color4}); buildingInfo.vertices->push_back({{x, y , z }, vertexColor, color1}); } void MeshChunkBuilder::quadXZ(const BuildingInfo& buildingInfo) const noexcept { const float x = buildingInfo.x; const float y = buildingInfo.y + buildingInfo.side; const float z = buildingInfo.z; const int dy = (buildingInfo.side << 1) - 1; const RGB8 vertexColor{buildingInfo.r, buildingInfo.g, buildingInfo.b}; const RGBA8 color1 = computeVertexXZColor(buildingInfo, -1, dy, -1); const RGBA8 color2 = computeVertexXZColor(buildingInfo, 1, dy, 1); const RGBA8 color3 = computeVertexXZColor(buildingInfo, 1, dy, -1); const RGBA8 color4 = computeVertexXZColor(buildingInfo, -1, dy, 1); buildingInfo.vertices->push_back({{x , y, z }, vertexColor, color1}); buildingInfo.vertices->push_back({{x + 1.0F, y, z }, vertexColor, color3}); buildingInfo.vertices->push_back({{x + 1.0F, y, z + 1.0F}, vertexColor, color2}); buildingInfo.vertices->push_back({{x + 1.0F, y, z + 1.0F}, vertexColor, color2}); buildingInfo.vertices->push_back({{x , y, z + 1.0F}, vertexColor, color4}); buildingInfo.vertices->push_back({{x , y, z }, vertexColor, color1}); } RGBA8 MeshChunkBuilder::computeVertexXYColor(const BuildingInfo& buildingInfo, int dx, int dy, int dz) const noexcept { const unsigned light1 = buildingInfo.chunk->findLight(buildingInfo.x + dx, buildingInfo.y , buildingInfo.z + dz); const unsigned light2 = buildingInfo.chunk->findLight(buildingInfo.x , buildingInfo.y , buildingInfo.z + dz); const unsigned light3 = buildingInfo.chunk->findLight(buildingInfo.x + dx, buildingInfo.y + dy, buildingInfo.z + dz); const unsigned light4 = buildingInfo.chunk->findLight(buildingInfo.x , buildingInfo.y + dy, buildingInfo.z + dz); return combineColors(light1, light2, light3, light4); } RGBA8 MeshChunkBuilder::computeVertexYZColor(const BuildingInfo& buildingInfo, int dx, int dy, int dz) const noexcept { const unsigned light1 = buildingInfo.chunk->findLight(buildingInfo.x + dx, buildingInfo.y , buildingInfo.z + dz); const unsigned light2 = buildingInfo.chunk->findLight(buildingInfo.x + dx, buildingInfo.y , buildingInfo.z ); const unsigned light3 = buildingInfo.chunk->findLight(buildingInfo.x + dx, buildingInfo.y + dy, buildingInfo.z + dz); const unsigned light4 = buildingInfo.chunk->findLight(buildingInfo.x + dx, buildingInfo.y + dy, buildingInfo.z ); return combineColors(light1, light2, light3, light4); } RGBA8 MeshChunkBuilder::computeVertexXZColor(const BuildingInfo& buildingInfo, int dx, int dy, int dz) const noexcept { const unsigned light1 = buildingInfo.chunk->findLight(buildingInfo.x , buildingInfo.y + dy, buildingInfo.z + dz); const unsigned light2 = buildingInfo.chunk->findLight(buildingInfo.x , buildingInfo.y + dy, buildingInfo.z ); const unsigned light3 = buildingInfo.chunk->findLight(buildingInfo.x + dx, buildingInfo.y + dy, buildingInfo.z + dz); const unsigned light4 = buildingInfo.chunk->findLight(buildingInfo.x + dx, buildingInfo.y + dy, buildingInfo.z ); return combineColors(light1, light2, light3, light4); } RGBA8 MeshChunkBuilder::combineColors(unsigned light1, unsigned light2, unsigned light3, unsigned light4) const noexcept { const GLubyte r = ((light1 & 0x000F) + (light2 & 0x000F) + (light3 & 0x000F) + (light4 & 0x000F)) >> 2; const GLubyte g = ((light1 & 0x00F0) + (light2 & 0x00F0) + (light3 & 0x00F0) + (light4 & 0x00F0)) >> 6; const GLubyte b = ((light1 & 0x0F00) + (light2 & 0x0F00) + (light3 & 0x0F00) + (light4 & 0x0F00)) >> 10; const GLubyte a = ((light1 & 0xF000) + (light2 & 0xF000) + (light3 & 0xF000) + (light4 & 0xF000)) >> 14; return {r, g, b, a}; }
jangolare/MineCPP
src/mesh_chunk_builder.cpp
C++
gpl-3.0
18,147