repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Squareys/magnum-examples
src/picking/PickingExample.cpp
14002
/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 — Vladimír Vondruš <mosra@centrum.cz> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Corrade/Utility/Resource.h> #include <Magnum/Image.h> #include <Magnum/PixelFormat.h> #include <Magnum/GL/AbstractShaderProgram.h> #include <Magnum/GL/Buffer.h> #include <Magnum/GL/Context.h> #include <Magnum/GL/DefaultFramebuffer.h> #include <Magnum/GL/Framebuffer.h> #include <Magnum/GL/Mesh.h> #include <Magnum/GL/Renderbuffer.h> #include <Magnum/GL/RenderbufferFormat.h> #include <Magnum/GL/Renderer.h> #include <Magnum/GL/Shader.h> #include <Magnum/GL/Texture.h> #include <Magnum/GL/TextureFormat.h> #include <Magnum/GL/Version.h> #include <Magnum/Math/Color.h> #include <Magnum/MeshTools/CompressIndices.h> #include <Magnum/MeshTools/Interleave.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Primitives/Plane.h> #include <Magnum/Primitives/UVSphere.h> #include <Magnum/Trade/MeshData3D.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/SceneGraph/MatrixTransformation3D.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> namespace Magnum { namespace Examples { using namespace Magnum::Math::Literals; typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D; typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D; class PhongIdShader: public GL::AbstractShaderProgram { public: typedef GL::Attribute<0, Vector3> Position; typedef GL::Attribute<1, Vector3> Normal; enum: UnsignedInt { ColorOutput = 0, ObjectIdOutput = 1 }; explicit PhongIdShader(); PhongIdShader& setObjectId(UnsignedInt id) { setUniform(_objectIdUniform, id); return *this; } PhongIdShader& setLightPosition(const Vector3& position) { setUniform(_lightPositionUniform, position); return *this; } PhongIdShader& setAmbientColor(const Color3& color) { setUniform(_ambientColorUniform, color); return *this; } PhongIdShader& setColor(const Color3& color) { setUniform(_colorUniform, color); return *this; } PhongIdShader& setTransformationMatrix(const Matrix4& matrix) { setUniform(_transformationMatrixUniform, matrix); return *this; } PhongIdShader& setNormalMatrix(const Matrix3x3& matrix) { setUniform(_normalMatrixUniform, matrix); return *this; } PhongIdShader& setProjectionMatrix(const Matrix4& matrix) { setUniform(_projectionMatrixUniform, matrix); return *this; } private: Int _objectIdUniform, _lightPositionUniform, _ambientColorUniform, _colorUniform, _transformationMatrixUniform, _normalMatrixUniform, _projectionMatrixUniform; }; PhongIdShader::PhongIdShader() { Utility::Resource rs("picking-data"); GL::Shader vert{GL::Version::GL330, GL::Shader::Type::Vertex}, frag{GL::Version::GL330, GL::Shader::Type::Fragment}; vert.addSource(rs.get("PhongId.vert")); frag.addSource(rs.get("PhongId.frag")); CORRADE_INTERNAL_ASSERT(GL::Shader::compile({vert, frag})); attachShaders({vert, frag}); CORRADE_INTERNAL_ASSERT(link()); _objectIdUniform = uniformLocation("objectId"); _lightPositionUniform = uniformLocation("light"); _ambientColorUniform = uniformLocation("ambientColor"); _colorUniform = uniformLocation("color"); _transformationMatrixUniform = uniformLocation("transformationMatrix"); _projectionMatrixUniform = uniformLocation("projectionMatrix"); _normalMatrixUniform = uniformLocation("normalMatrix"); } class PickableObject: public Object3D, SceneGraph::Drawable3D { public: explicit PickableObject(UnsignedByte id, PhongIdShader& shader, const Color3& color, GL::Mesh& mesh, Object3D& parent, SceneGraph::DrawableGroup3D& drawables): Object3D{&parent}, SceneGraph::Drawable3D{*this, &drawables}, _id{id}, _selected{false}, _shader(shader), _color{color}, _mesh(mesh) {} void setSelected(bool selected) { _selected = selected; } private: virtual void draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) { _shader.setTransformationMatrix(transformationMatrix) .setNormalMatrix(transformationMatrix.rotationScaling()) .setProjectionMatrix(camera.projectionMatrix()) .setAmbientColor(_selected ? _color*0.3f : Color3{}) .setColor(_color*(_selected ? 2.0f : 1.0f)) /* relative to the camera */ .setLightPosition({13.0f, 2.0f, 5.0f}) .setObjectId(_id); _mesh.draw(_shader); } UnsignedByte _id; bool _selected; PhongIdShader& _shader; Color3 _color; GL::Mesh& _mesh; }; class PickingExample: public Platform::Application { public: explicit PickingExample(const Arguments& arguments); private: void drawEvent() override; void mousePressEvent(MouseEvent& event) override; void mouseMoveEvent(MouseMoveEvent& event) override; void mouseReleaseEvent(MouseEvent& event) override; Scene3D _scene; Object3D* _cameraObject; SceneGraph::Camera3D* _camera; SceneGraph::DrawableGroup3D _drawables; PhongIdShader _shader; GL::Buffer _cubeVertices, _cubeIndices, _sphereVertices, _sphereIndices, _planeVertices; GL::Mesh _cube, _plane, _sphere; enum { ObjectCount = 6 }; PickableObject* _objects[ObjectCount]; GL::Framebuffer _framebuffer; GL::Renderbuffer _color, _objectId, _depth; Vector2i _previousMousePosition, _mousePressPosition; }; PickingExample::PickingExample(const Arguments& arguments): Platform::Application{arguments, Configuration{}.setTitle("Magnum object picking example")}, _framebuffer{GL::defaultFramebuffer.viewport()} { MAGNUM_ASSERT_GL_VERSION_SUPPORTED(GL::Version::GL330); /* Global renderer configuration */ GL::Renderer::enable(GL::Renderer::Feature::DepthTest); /* Configure framebuffer (using R8UI for object ID which means 255 objects max) */ _color.setStorage(GL::RenderbufferFormat::RGBA8, GL::defaultFramebuffer.viewport().size()); _objectId.setStorage(GL::RenderbufferFormat::R8UI, GL::defaultFramebuffer.viewport().size()); _depth.setStorage(GL::RenderbufferFormat::DepthComponent24, GL::defaultFramebuffer.viewport().size()); _framebuffer.attachRenderbuffer(GL::Framebuffer::ColorAttachment{0}, _color) .attachRenderbuffer(GL::Framebuffer::ColorAttachment{1}, _objectId) .attachRenderbuffer(GL::Framebuffer::BufferAttachment::Depth, _depth) .mapForDraw({{PhongIdShader::ColorOutput, GL::Framebuffer::ColorAttachment{0}}, {PhongIdShader::ObjectIdOutput, GL::Framebuffer::ColorAttachment{1}}}); CORRADE_INTERNAL_ASSERT(_framebuffer.checkStatus(GL::FramebufferTarget::Draw) == GL::Framebuffer::Status::Complete); /* Set up meshes */ { Trade::MeshData3D data = Primitives::cubeSolid(); _cubeVertices.setData(MeshTools::interleave(data.positions(0), data.normals(0)), GL::BufferUsage::StaticDraw); _cubeIndices.setData(MeshTools::compressIndicesAs<UnsignedShort>(data.indices()), GL::BufferUsage::StaticDraw); _cube.setCount(data.indices().size()) .setPrimitive(data.primitive()) .addVertexBuffer(_cubeVertices, 0, PhongIdShader::Position{}, PhongIdShader::Normal{}) .setIndexBuffer(_cubeIndices, 0, MeshIndexType::UnsignedShort); } { Trade::MeshData3D data = Primitives::uvSphereSolid(16, 32); _sphereVertices.setData(MeshTools::interleave(data.positions(0), data.normals(0)), GL::BufferUsage::StaticDraw); _sphereIndices.setData(MeshTools::compressIndicesAs<UnsignedShort>(data.indices()), GL::BufferUsage::StaticDraw); _sphere.setCount(data.indices().size()) .setPrimitive(data.primitive()) .addVertexBuffer(_sphereVertices, 0, PhongIdShader::Position{}, PhongIdShader::Normal{}) .setIndexBuffer(_sphereIndices, 0, MeshIndexType::UnsignedShort); } { Trade::MeshData3D data = Primitives::planeSolid(); _planeVertices.setData(MeshTools::interleave(data.positions(0), data.normals(0)), GL::BufferUsage::StaticDraw); _plane.setCount(data.positions(0).size()) .setPrimitive(data.primitive()) .addVertexBuffer(_planeVertices, 0, PhongIdShader::Position{}, PhongIdShader::Normal{}); } /* Set up objects */ (*(_objects[0] = new PickableObject{1, _shader, 0x3bd267_rgbf, _cube, _scene, _drawables})) .rotate(34.0_degf, Vector3(1.0f).normalized()) .translate({1.0f, 0.3f, -1.2f}); (*(_objects[1] = new PickableObject{2, _shader, 0x2f83cc_rgbf, _sphere, _scene, _drawables})) .translate({-1.2f, -0.3f, -0.2f}); (*(_objects[2] = new PickableObject{3, _shader, 0xdcdcdc_rgbf, _plane, _scene, _drawables})) .rotate(278.0_degf, Vector3(1.0f).normalized()) .scale(Vector3(0.45f)) .translate({-1.0f, 1.2f, 1.5f}); (*(_objects[3] = new PickableObject{4, _shader, 0xc7cf2f_rgbf, _sphere, _scene, _drawables})) .translate({-0.2f, -1.7f, -2.7f}); (*(_objects[4] = new PickableObject{5, _shader, 0xcd3431_rgbf, _sphere, _scene, _drawables})) .translate({0.7f, 0.6f, 2.2f}) .scale(Vector3(0.75f)); (*(_objects[5] = new PickableObject{6, _shader, 0xa5c9ea_rgbf, _cube, _scene, _drawables})) .rotate(-92.0_degf, Vector3(1.0f).normalized()) .scale(Vector3(0.25f)) .translate({-0.5f, -0.3f, 1.8f}); /* Configure camera */ _cameraObject = new Object3D{&_scene}; _cameraObject->translate(Vector3::zAxis(8.0f)); _camera = new SceneGraph::Camera3D{*_cameraObject}; _camera->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 4.0f/3.0f, 0.001f, 100.0f)) .setViewport(GL::defaultFramebuffer.viewport().size()); } void PickingExample::drawEvent() { /* Draw to custom framebuffer */ _framebuffer .clearColor(0, Color3{0.125f}) .clearColor(1, Vector4ui{}) .clearDepth(1.0f) .bind(); _camera->draw(_drawables); /* Bind the main buffer back */ GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth) .bind(); /* Blit color to window framebuffer */ _framebuffer.mapForRead(GL::Framebuffer::ColorAttachment{0}); GL::AbstractFramebuffer::blit(_framebuffer, GL::defaultFramebuffer, {{}, _framebuffer.viewport().size()}, GL::FramebufferBlit::Color); swapBuffers(); } void PickingExample::mousePressEvent(MouseEvent& event) { if(event.button() != MouseEvent::Button::Left) return; _previousMousePosition = _mousePressPosition = event.position(); event.setAccepted(); } void PickingExample::mouseMoveEvent(MouseMoveEvent& event) { if(!(event.buttons() & MouseMoveEvent::Button::Left)) return; const Vector2 delta = 3.0f* Vector2{event.position() - _previousMousePosition}/ Vector2{GL::defaultFramebuffer.viewport().size()}; (*_cameraObject) .rotate(Rad{-delta.y()}, _cameraObject->transformation().right().normalized()) .rotateY(Rad{-delta.x()}); _previousMousePosition = event.position(); event.setAccepted(); redraw(); } void PickingExample::mouseReleaseEvent(MouseEvent& event) { if(event.button() != MouseEvent::Button::Left || _mousePressPosition != event.position()) return; /* Read object ID at given click position (framebuffer has Y up while windowing system Y down) */ _framebuffer.mapForRead(GL::Framebuffer::ColorAttachment{1}); Image2D data = _framebuffer.read( Range2Di::fromSize({event.position().x(), _framebuffer.viewport().sizeY() - event.position().y() - 1}, {1, 1}), {PixelFormat::R8UI}); /* Highlight object under mouse and deselect all other */ for(auto* o: _objects) o->setSelected(false); UnsignedByte id = data.data<UnsignedByte>()[0]; if(id > 0 && id < ObjectCount + 1) _objects[id - 1]->setSelected(true); event.setAccepted(); redraw(); } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::PickingExample)
unlicense
bpiec/monkeylang_csharp
Monkey.Ast/Expressions/FunctionLiteral.cs
1865
using Monkey.Ast.Statements; using System.Collections.Generic; using System.Linq; using System.Text; namespace Monkey.Ast.Expressions { public class FunctionLiteral : IExpression { public string TokenLiteral => Token?.Literal; public override string ToString() { var o = new StringBuilder(); var parameters = Parameters.Select(q => q.ToString()).ToArray(); o.Append(TokenLiteral); o.Append("("); o.Append(string.Join(", ", parameters)); o.Append(") "); o.Append(Body); return o.ToString(); } public override bool Equals(object obj) { if (!(obj is FunctionLiteral function)) { return false; } if (Parameters == null && function.Parameters == null) { return true; } if (Parameters.Count != function.Parameters.Count) { return false; } for (var i = 0; i < Parameters.Count; i++) { if (!Parameters[i].Equals(function.Parameters[i])) { return false; } } return Body.Equals(function.Body); } public override int GetHashCode() { var hashCode = -691572618; hashCode = hashCode * -1521134295 + EqualityComparer<List<Identifier>>.Default.GetHashCode(Parameters); hashCode = hashCode * -1521134295 + EqualityComparer<BlockStatement>.Default.GetHashCode(Body); return hashCode; } public Token.Token Token { get; set; } // The 'fn' token public List<Identifier> Parameters { get; set; } public BlockStatement Body { get; set; } } }
unlicense
jlaura/isis3
isis/src/voyager/objs/VoyagerCamera/VoyagerCamera.cpp
7914
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include "VoyagerCamera.h" #include <SpiceUsr.h> #include <QString> #include "CameraDetectorMap.h" #include "CameraFocalPlaneMap.h" #include "CameraGroundMap.h" #include "CameraSkyMap.h" #include "FileName.h" #include "IString.h" #include "iTime.h" #include "NaifStatus.h" #include "ReseauDistortionMap.h" #include "Spice.h" using namespace std; namespace Isis { /** * Constructs a Voyager Camera Model using the image labels. The constructor * determines the pixel pitch, focal length, kernels and reseaus, and sets up * the focal plane map, detector origin, ground map and sky map. As required * for all framing cameras, the start and end exposure times are set in this * constructor. * * @param cube The image cube. * * @throw iException::User - "File does not appear to be a Voyager image. * Invalid InstrumentId." * @throw iException::User - "File does not appear to be a Voyager image. * Invalid SpacecraftName." * * @author 2010-07-19 Mackenzie Boyd * * @internal * @history 2010-07-19 Mackenzie Boyd - Original Version * @history 2011-05-03 Jeannie Walldren - Added NAIF error check. Updated * documentation. Added call to * ShutterOpenCloseTimes() method. */ VoyagerCamera::VoyagerCamera (Cube &cube) : FramingCamera(cube) { NaifStatus::CheckErrors(); // Set the pixel pitch SetPixelPitch(); SetFocalLength(); // Find out what camera is being used, and set the focal length, altinstcode, // and camera Pvl &lab = *cube.label(); PvlGroup &inst = lab.findGroup ("Instrument",Pvl::Traverse); QString spacecraft = (QString)inst["SpacecraftName"]; QString instId = (QString)inst["InstrumentId"]; QString reseauFileName = ""; // These set up which kernel and other files to access, if (spacecraft == "VOYAGER_1") { p_ckFrameId = -31100; p_spkTargetId = -31; m_spacecraftNameLong = "Voyager 1"; m_spacecraftNameShort = "Voyager1"; reseauFileName += "1/reseaus/vg1"; if (instId == "NARROW_ANGLE_CAMERA") { reseauFileName += "na"; m_instrumentNameLong = "Narrow Angle Camera"; m_instrumentNameShort = "NAC"; } else if (instId == "WIDE_ANGLE_CAMERA") { reseauFileName += "wa"; m_instrumentNameLong = "Wide Angle Camera"; m_instrumentNameShort = "WAC"; } else { QString msg = "File does not appear to be a Voyager image. InstrumentId [" + instId + "] is invalid Voyager value."; throw IException(IException::User, msg, _FILEINFO_); } } else if (spacecraft == "VOYAGER_2") { p_ckFrameId = -32100; p_spkTargetId = -32; m_spacecraftNameLong = "Voyager 2"; m_spacecraftNameShort = "Voyager2"; reseauFileName += "2/reseaus/vg2"; if (instId == "NARROW_ANGLE_CAMERA") { reseauFileName += "na"; m_instrumentNameLong = "Narrow Angle Camera"; m_instrumentNameShort = "NAC"; } else if (instId == "WIDE_ANGLE_CAMERA") { reseauFileName += "wa"; m_instrumentNameLong = "Wide Angle Camera"; m_instrumentNameShort = "WAC"; } else { QString msg = "File does not appear to be a Voyager image. InstrumentId [" + instId + "] is invalid Voyager value."; throw IException(IException::User, msg, _FILEINFO_); } } else { QString msg = "File does not appear to be a Voyager image. SpacecraftName [" + spacecraft + "] is invalid Voyager value."; throw IException(IException::User, msg, _FILEINFO_); } new CameraDetectorMap(this); // Setup focal plane map, and detector origin CameraFocalPlaneMap *focalMap = new CameraFocalPlaneMap(this, naifIkCode()); focalMap->SetDetectorOrigin(500.0, 500.0); // Master reseau location file reseauFileName = "$voyager" + reseauFileName + "MasterReseaus.pvl"; FileName masterReseaus(reseauFileName); try { new ReseauDistortionMap(this, lab, masterReseaus.expanded()); } catch (IException &e) { e.print(); } // Setup the ground and sky map new CameraGroundMap(this); new CameraSkyMap(this); // StartTime is the most accurate time available because in voy2isis the // StartTime is modified to be highly accurate. // exposure duration keyword value is measured in seconds double exposureDuration = inst["ExposureDuration"]; iTime startTime; startTime.setUtc((QString)inst["StartTime"]); // set the start (shutter open) and end (shutter close) times for the image /***************************************************************************** * AS NOTED IN ISIS2 PROGRAM lev1u_vgr_routines.c: * StartTime (FDS count) from the labels calculated to correspond the true spacecraft * clock count for the frame. The true spacecraft clock count is readout * time of the frame, which occurred 2 seconds after shutter close. *****************************************************************************/ pair<iTime, iTime> shuttertimes = ShutterOpenCloseTimes(startTime.Et(), exposureDuration); // add half the exposure duration to the start time to get the center if the image iTime centerTime = shuttertimes.first.Et() + exposureDuration / 2.0; setTime(centerTime); LoadCache(); NaifStatus::CheckErrors(); } /** * Returns the shutter open and close times. The user should pass in the * ExposureDuration keyword value and the StartTime keyword value, converted * to ephemeris time. The StartTime keyword value from the labels represents * the true spacecraft clock count. This is the readout time of the frame, * which occurred 2 seconds after the shutter close. To find the end time of * the exposure, 2 seconds are subtracted from the time input parameter. To * find the start time of the exposure, the exposure duration is subtracted * from the end time. This method overrides the FramingCamera class method. * * @param exposureDuration ExposureDuration keyword value from the labels, in * seconds. * @param time The StartTime keyword value from the labels, converted to * ephemeris time. * * @return @b pair < @b iTime, @b iTime > The first value is the shutter * open time and the second is the shutter close time. * * @author 2011-05-03 Jeannie Walldren * @internal * @history 2011-05-03 Jeannie Walldren - Original version. */ pair<iTime, iTime> VoyagerCamera::ShutterOpenCloseTimes(double time, double exposureDuration) { pair<iTime, iTime> shuttertimes; // To get shutter end (close) time, subtract 2 seconds from the StartTime keyword value shuttertimes.second = time - 2; // To get shutter start (open) time, take off the exposure duration from the end time. shuttertimes.first = shuttertimes.second.Et() - exposureDuration; return shuttertimes; } } /** * This is the function that is called in order to instantiate a VoyagerCamera * object. * * @param cube The image Cube * * @return Isis::Camera* VoyagerCamera * @author 2010-07-19 Mackenzie Boyd * @internal * @history 2010-07-19 Mackenzie Boyd - Original Version */ extern "C" Isis::Camera *VoyagerCameraPlugin(Isis::Cube &cube) { return new Isis::VoyagerCamera(cube); }
unlicense
tpetrina/presentations
2018/Fer-UWP/Xamarin/Xamarin/App.xaml.cs
545
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; namespace Xamarin { public partial class App : Application { public App () { InitializeComponent(); MainPage = new Xamarin.MainPage(); } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
unlicense
OneNationUnderCanadia/Engineering-Projects-Repo
Broomba/src/main/Magnets.java
2156
package main; import lejos.nxt.SensorPort; import lejos.nxt.addon.MagneticSensor; import lejos.robotics.navigation.DifferentialPilot; import lejos.util.Delay; /** * Abstraction for Magnets * * @author Joey Spillers */ public class Magnets { ///[0] Forward, [1] Right, [2] Back, [3] Left static int[] low = {10000,10000,10000,10000}; static int[] high = {0,0,0,0}; static MagneticSensor compass = new MagneticSensor(SensorPort.S2); /** * Calibrates using the useless Magnet Sensor<br> * * @param pilot * DifferentialPilot used * * @author Joey Spillers */ public void calibrate(DifferentialPilot pilot){ /*I2CSensor magnet = new I2CSensor(SensorPort.S1); byte[] buf = null; int len=10; magnet.getData(0x41, buf, len); magnet.*/ GUI gui = new GUI(); int[][] data = new int[4][10]; for(int i = 0; i< 4; i++){ for(int k = 0; k<10; k++){ Delay.msDelay(500); data[i][k] = compass.readValue(); gui.valuePrint(data[i][k]); } pilot.rotate(95.5); } highAndLow(data); } /** * Searches Numbs and sets the lowest and highest value in each second-level array<br> * * @param numbs * To be used with the Calibration method only; Contains a ton of values * * @author Joey Spillers */ public static void highAndLow(int[][] numbs){ int count = 0; for(int i=0; i< 4; i++){ count = 0; while(count < numbs[i].length) { if(numbs[i][count]< low[i]) { low[i] = numbs[i][count]; } if(numbs[i][count] > high[i]) { high[i] = numbs[i][count]; } count++; } } } /** * returns the North Value of the Magnet Sensor<br> * * @author Joey Spillers */ public int[] getHigh(){ return high; } /** * returns the South Value of the Magnet Sensor<br> * * @author Joey Spillers */ public int[] getLow(){ return low; } /** * returns the Current Value of the Magnet Sensor<br> * * @author Joey Spillers */ public int getValue(){ return compass.readValue(); } }
unlicense
Zhiyuan-Yang/LeetCode
SearchRotatedArray.java
1029
public class Solution { public int search_bf(int[] A, int target) { for (int i = 0; i < A.length; i++) { if (A[i] == target) { return i; } } return -1; } public int search_bs(int[] A, int target) { return searchHelper(A, 0, A.length-1, target); } public int searchHelper(int[] A, int begin, int end, int target) { while (begin < end) { int mid = (begin + end)/2; if (A[mid] == target) { return mid; } else if (A[begin] <= A[mid]) { if (A[begin] <= target && target < A[mid]) { end = mid; } else { begin = mid + 1; } } else { if (A[mid] < target && target <= A[end]) { begin = mid + 1; } else { end = mid; } } } return A[begin] == target ? begin : -1; } }
unlicense
bendiken/bitcache
spec/zeromq_spec.rb
100
require File.join(File.dirname(__FILE__), 'spec_helper') describe Bitcache::ZeroMQ do # TODO end
unlicense
Laure129/findheadposes
djangoapp/admin.py
267
from django.contrib import admin from .models import User, Gallery, Photo class PhotoAdmin(admin.ModelAdmin): list_display = ['image', 'task', 'gallery'] class Meta: model = Photo admin.site.register(Gallery) admin.site.register(Photo, PhotoAdmin)
unlicense
pedroedrasousa/opengl-stuff-cpp
engine/Frustum.cpp
7477
#include <windows.h> #include <math.h> #include "Frustum.h" void Frustum::ComputeFrustum(const Mat4 &mProjection, const Mat4 &mModelView) { Mat4 mClip; mClip = mProjection * mModelView; // Extrair os planos que limitam a cena m_Frustum[RIGHT].a = mClip.m[ 3] - mClip.m[ 0]; m_Frustum[RIGHT].b = mClip.m[ 7] - mClip.m[ 4]; m_Frustum[RIGHT].c = mClip.m[11] - mClip.m[ 8]; m_Frustum[RIGHT].d = mClip.m[15] - mClip.m[12]; m_Frustum[RIGHT].Normalize(); m_Frustum[LEFT].a = mClip.m[ 3] + mClip.m[ 0]; m_Frustum[LEFT].b = mClip.m[ 7] + mClip.m[ 4]; m_Frustum[LEFT].c = mClip.m[11] + mClip.m[ 8]; m_Frustum[LEFT].d = mClip.m[15] + mClip.m[12]; m_Frustum[LEFT].Normalize(); m_Frustum[BOTTOM].a = mClip.m[ 3] + mClip.m[ 1]; m_Frustum[BOTTOM].b = mClip.m[ 7] + mClip.m[ 5]; m_Frustum[BOTTOM].c = mClip.m[11] + mClip.m[ 9]; m_Frustum[BOTTOM].d = mClip.m[15] + mClip.m[13]; m_Frustum[BOTTOM].Normalize(); m_Frustum[TOP].a = mClip.m[ 3] - mClip.m[ 1]; m_Frustum[TOP].b = mClip.m[ 7] - mClip.m[ 5]; m_Frustum[TOP].c = mClip.m[11] - mClip.m[ 9]; m_Frustum[TOP].d = mClip.m[15] - mClip.m[13]; m_Frustum[TOP].Normalize(); m_Frustum[BACK].a = mClip.m[ 3] - mClip.m[ 2]; m_Frustum[BACK].b = mClip.m[ 7] - mClip.m[ 6]; m_Frustum[BACK].c = mClip.m[11] - mClip.m[10]; m_Frustum[BACK].d = mClip.m[15] - mClip.m[14]; m_Frustum[BACK].Normalize(); m_Frustum[FRONT].a = mClip.m[ 3] + mClip.m[ 2]; m_Frustum[FRONT].b = mClip.m[ 7] + mClip.m[ 6]; m_Frustum[FRONT].c = mClip.m[11] + mClip.m[10]; m_Frustum[FRONT].d = mClip.m[15] + mClip.m[14]; m_Frustum[FRONT].Normalize(); } float Frustum::DistToEye(const Vec3 &pos) const { return m_Frustum[FRONT].a * pos.x + m_Frustum[FRONT].b * pos.y + m_Frustum[FRONT].c * pos.z + m_Frustum[FRONT].d; } bool Frustum::PointInFrustum(const Vec3 &pos) const { for(int i = 0; i < 6; i++) if(m_Frustum[i].a * pos.x + m_Frustum[i].b * pos.y + m_Frustum[i].c * pos.z + m_Frustum[i].d <= 0) return false; return true; } float Frustum::SphereInFrustum(const Vec3 &pos, float radius) const { float d; for(int i = 0; i < 6; i++ ) if( d = m_Frustum[i].a * pos.x + m_Frustum[i].b * pos.y + m_Frustum[i].c * pos.z + m_Frustum[i].d ) if( d <= -radius) return 0.0f; return d + radius; } bool Frustum::CubeInFrustum(const Vec3 &pos, float size) const { for(int i = 0; i < 6; i++) { if(m_Frustum[i].a * (pos.x + size) + m_Frustum[i].b * (pos.y + size) + m_Frustum[i].c * (pos.z + size) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x + size) + m_Frustum[i].b * (pos.y + size) + m_Frustum[i].c * (pos.z - size) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x + size) + m_Frustum[i].b * (pos.y - size) + m_Frustum[i].c * (pos.z + size) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x + size) + m_Frustum[i].b * (pos.y - size) + m_Frustum[i].c * (pos.z - size) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x - size) + m_Frustum[i].b * (pos.y + size) + m_Frustum[i].c * (pos.z + size) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x - size) + m_Frustum[i].b * (pos.y + size) + m_Frustum[i].c * (pos.z - size) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x - size) + m_Frustum[i].b * (pos.y - size) + m_Frustum[i].c * (pos.z + size) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x - size) + m_Frustum[i].b * (pos.y - size) + m_Frustum[i].c * (pos.z - size) + m_Frustum[i].d > 0) continue; return false; } return true; } bool Frustum::ParallelepipedInFrustum(const Vec3 &pos, float width, float height, float depth) const { width *= 0.5; height *= 0.5; depth *= 0.5; for(int i = 0; i < 6; i++) { if(m_Frustum[i].a * (pos.x + width) + m_Frustum[i].b * (pos.y + height) + m_Frustum[i].c * (pos.z + depth) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x + width) + m_Frustum[i].b * (pos.y + height) + m_Frustum[i].c * (pos.z - depth) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x + width) + m_Frustum[i].b * (pos.y - height) + m_Frustum[i].c * (pos.z + depth) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x + width) + m_Frustum[i].b * (pos.y - height) + m_Frustum[i].c * (pos.z - depth) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x - width) + m_Frustum[i].b * (pos.y + height) + m_Frustum[i].c * (pos.z + depth) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x - width) + m_Frustum[i].b * (pos.y + height) + m_Frustum[i].c * (pos.z - depth) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x - width) + m_Frustum[i].b * (pos.y - height) + m_Frustum[i].c * (pos.z + depth) + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * (pos.x - width) + m_Frustum[i].b * (pos.y - height) + m_Frustum[i].c * (pos.z - depth) + m_Frustum[i].d > 0) continue; return false; } return true; } bool Frustum::ParallelepipedInFrustum(const Vec3 &pos, const Vec3 *v) const { Vec3 v1 = v[0] + pos; Vec3 v2 = v[1] + pos; Vec3 v3 = v[2] + pos; Vec3 v4 = v[3] + pos; Vec3 v5 = v[4] + pos; Vec3 v6 = v[5] + pos; Vec3 v7 = v[6] + pos; Vec3 v8 = v[7] + pos; for(int i = 0; i < 6; i++) { if(m_Frustum[i].a * v1.x + m_Frustum[i].b * v1.y + m_Frustum[i].c * v1.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v2.x + m_Frustum[i].b * v2.y + m_Frustum[i].c * v2.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v3.x + m_Frustum[i].b * v3.y + m_Frustum[i].c * v3.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v4.x + m_Frustum[i].b * v4.y + m_Frustum[i].c * v4.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v5.x + m_Frustum[i].b * v5.y + m_Frustum[i].c * v5.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v6.x + m_Frustum[i].b * v6.y + m_Frustum[i].c * v6.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v7.x + m_Frustum[i].b * v7.y + m_Frustum[i].c * v7.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v8.x + m_Frustum[i].b * v8.y + m_Frustum[i].c * v8.z + m_Frustum[i].d > 0) continue; return false; } return true; } bool Frustum::ParallelepipedInFrustum(const Mat4 &mPose, const Vec3 *v) const { Vec4 v1 = mPose * Vec4(v[0], 1.0f); Vec4 v2 = mPose * Vec4(v[1], 1.0f); Vec4 v3 = mPose * Vec4(v[2], 1.0f); Vec4 v4 = mPose * Vec4(v[3], 1.0f); Vec4 v5 = mPose * Vec4(v[4], 1.0f); Vec4 v6 = mPose * Vec4(v[5], 1.0f); Vec4 v7 = mPose * Vec4(v[6], 1.0f); Vec4 v8 = mPose * Vec4(v[7], 1.0f); for(int i = 0; i < 6; i++) { if(m_Frustum[i].a * v1.x + m_Frustum[i].b * v1.y + m_Frustum[i].c * v1.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v2.x + m_Frustum[i].b * v2.y + m_Frustum[i].c * v2.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v3.x + m_Frustum[i].b * v3.y + m_Frustum[i].c * v3.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v4.x + m_Frustum[i].b * v4.y + m_Frustum[i].c * v4.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v5.x + m_Frustum[i].b * v5.y + m_Frustum[i].c * v5.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v6.x + m_Frustum[i].b * v6.y + m_Frustum[i].c * v6.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v7.x + m_Frustum[i].b * v7.y + m_Frustum[i].c * v7.z + m_Frustum[i].d > 0) continue; if(m_Frustum[i].a * v8.x + m_Frustum[i].b * v8.y + m_Frustum[i].c * v8.z + m_Frustum[i].d > 0) continue; return false; } return true; }
unlicense
SandraKrle/sandrakrle.github.io
assets/js/header.js
693
function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.classList += " responsive"; } else if (x.className === "topnav topnav-scrolled") { x.className += " responsive"; } else if (x.classList === "topnav topnav-scrolled responsive") { x.className -= " responsive"; } else { x.className = "topnav topnav-scrolled"; } } $(window).scroll(function () { var mn = $(".topnav"); mns = "topnav-scrolled"; hdr = $('.hero').height(); if ($(this).scrollTop() > hdr) { mn.addClass(mns); } else { mn.removeClass(mns); } });
unlicense
pythonpatterns/patterns
p0093.py
92
import numpy as np v = np.array([1,2,3,4]).reshape(-1,1) print(v) """< [[1][2][3][4]] >"""
unlicense
DevJPM/CryptoJPM
Source/CryptoPPTests/stdafx.cpp
308
// stdafx.cpp : Quelldatei, die nur die Standard-Includes einbindet // CryptoPPTests.pch ist der vorkompilierte Header. // stdafx.obj enthält die vorkompilierten Typinformationen #include "stdafx.h" // TODO: Auf zusätzliche Header verweisen, die in STDAFX.H // und nicht in dieser Datei erforderlich sind.
unlicense
tierous/yiirisma
protected/controllers/CommentController.php
2431
<?php class CommentController extends Controller { public $layout = '//layouts/column2'; public function actionView($id) { IsAuth::Admin(); $this->render('view', array( 'model' => $this->loadModel($id), )); } public function actionCreate() { IsAuth::Admin(); $model = new Comment; if (isset($_POST['Comment'])) { $model->attributes = $_POST['Comment']; if ($model->save()) $this->redirect(array('view', 'id' => $model->comment_id)); } $this->render('create', array( 'model' => $model, )); } public function actionUpdate($id) { IsAuth::Admin(); $model = $this->loadModel($id); if (isset($_POST['Comment'])) { $model->attributes = $_POST['Comment']; if ($model->save()) $this->redirect(array('view', 'id' => $model->comment_id)); } $this->render('update', array( 'model' => $model, )); } public function actionDelete($id) { IsAuth::Admin(); $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if (!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin')); } public function actionIndex() { IsAuth::Admin(); $dataProvider = new CActiveDataProvider('Comment'); $this->render('index', array( 'dataProvider' => $dataProvider, )); } public function actionAdmin() { IsAuth::Admin(); $model = new Comment('search'); $model->unsetAttributes(); // clear any default values if (isset($_GET['Comment'])) $model->attributes = $_GET['Comment']; $this->render('admin', array( 'model' => $model, )); } public function loadModel($id) { $model = Comment::model()->findByPk($id); if ($model === null) throw new CHttpException(404, 'The requested page does not exist.'); return $model; } protected function performAjaxValidation($model) { if (isset($_POST['ajax']) && $_POST['ajax'] === 'comment-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } }
unlicense
pirati-cz/dokuwiki-piratiform
widgets/SelectWidget.php
4293
<?php require_once('Widget.php'); class SelectWidget extends Widget { public function render(){ if($this->getOption('expanded',false)){ $out = ''; $out .= '<div class="control-group'; if($this->hasOption('rowclass')) $out .= ' '.$this->getOption('rowclass'); if($this->validator->hasError()) $out .= ' error'; $out .= '">'; $label = $this->getOption('label'); if(!empty($label)) $out .= '<label class="control-label">'.$this->getOption('label').'</label>'; $out .= '<div class="controls">'; if($this->validator->hasError()) $out .= '<span class="help-block">'.$this->validator->getError().'</span>'; $out .= $this->renderWidget(); $out .= '</div>'; $out .= '</div>'; return $out; } else return parent::render(); } public function renderWidget(){ $events = $this->renderEvents(); if($this->getOption('expanded',false)){ $out = ''; foreach($this->getOption('choices') as $value=>$name){ $out .= '<label class="'.($this->getOption('multiple',false)?'checkbox':'radio').'">'; if($this->getOption('required',true)) $out .= '&nbsp;<span class="label label-important" title="Povinný údaj">!</span>'; $out .= '<input type="'.($this->getOption('multiple',false)?'checkbox':'radio').'" name="'.$this->getOption('name').'" id="'.$this->getOption('formname').'_'.$this->getOption('name').'" value="'.$value.'"'; if($this->hasValue() and $this->getValue()==$value) $out .= ' checked="checked"'; $out .= $events['element']; // attributes foreach($this->attributes as $attrname=>$attrvalue){ if($attrname=='readonly'){ $attrname='disabled'; $attrvalue='disabled'; } $out .= ' '.$attrname.'="'.$attrvalue.'"'; } if($this->getOption('required',true)) $out .= ' required="required"'; $out .= '> '.$name; if($this->hasAttribute('readonly')) $out .= ' <input type="hidden" name="'.$this->getOption('name').'" value="'.$value.'">'; $out .= '</label>'; if($this->hasOption('help')) $out .= '<span class="help-block">'.$this->getOption('help').'</span>'; } } else { $out = '<select name="'.$this->getOption('name').'" id="'.$this->getOption('formname').'_'.$this->getOption('name').'"'; if($this->getOption('required',true)) $out .= ' required="required"'; foreach($this->attributes as $attrname=>$attrvalue){ $out .= ' '.$attrname.'="'.$attrvalue.'"'; } $out .= '>'; if($this->hasOption('empty')){ $em = $this->getOption('empty'); $out .= '<option value="'.key($em).'">'.current($em).'</option>'; } foreach($this->getOption('choices') as $value=>$name){ $out .= '<option value="'.$value.'"'; if($this->hasValue()){ if($this->getValue()==$value) $out .= ' selected="selected"'; } if(in_array($value,$this->getOption('dchoices',array()))){ $out .= ' disabled="disabled"'; } $out .= '>'.$name.'</option>'; } $out .= '</select>'; if($this->getOption('required',true)) $out .= '&nbsp;<span class="label label-important" title="Povinný údaj">!</span>'; if($this->hasOption('help')) $out .= '<span class="help-block">'.$this->getOption('help').'</span>'; } // init events $out .= '<script type="text/javascript">'; $out .= 'jQuery(document).ready(function(){ '.$events['init'].' });'; $out .= '</script>'; return $out; } }
unlicense
jlaura/isis3
isis/src/qisis/objs/Directory/Directory.cpp
64629
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include "Directory.h" #include <QAction> #include <QApplication> #include <QDockWidget> #include <QGridLayout> #include <QMainWindow> #include <QMenu> #include <QMenuBar> #include <QMessageBox> #include <QRegExp> #include <QSettings> #include <QSizePolicy> #include <QSplitter> #include <QStringList> #include <QtDebug> #include <QVariant> #include <QXmlStreamWriter> #include "BundleObservation.h" #include "BundleObservationView.h" #include "BundleObservationViewWorkOrder.h" #include "ChipViewportsWidget.h" #include "CloseProjectWorkOrder.h" #include "CnetEditorView.h" #include "CnetEditorViewWorkOrder.h" #include "ControlHealthMonitorView.h" #include "ControlHealthMonitorWorkOrder.h" #include "CnetEditorWidget.h" #include "Control.h" #include "ControlDisplayProperties.h" #include "ControlList.h" #include "ControlNet.h" #include "ControlNetTool.h" #include "ControlPointEditView.h" #include "ControlPointEditWidget.h" #include "CubeDnView.h" #include "CubeDnViewWorkOrder.h" #include "ExportControlNetWorkOrder.h" #include "ExportImagesWorkOrder.h" #include "FileItem.h" #include "FileName.h" #include "Footprint2DView.h" #include "Footprint2DViewWorkOrder.h" #include "HistoryTreeWidget.h" #include "IException.h" #include "IString.h" #include "ImageFileListViewWorkOrder.h" #include "ImageFileListWidget.h" #include "ImportControlNetWorkOrder.h" #include "ImportImagesWorkOrder.h" #include "ImportShapesWorkOrder.h" #include "ImportMapTemplateWorkOrder.h" #include "ImportRegistrationTemplateWorkOrder.h" #include "JigsawRunWidget.h" #include "JigsawWorkOrder.h" #include "MatrixSceneWidget.h" #include "MatrixViewWorkOrder.h" #include "MosaicControlNetTool.h" #include "MosaicSceneWidget.h" #include "OpenProjectWorkOrder.h" #include "Project.h" #include "ProjectItem.h" #include "ProjectItemModel.h" #include "ProjectItemTreeView.h" #include "RemoveImagesWorkOrder.h" #include "RenameProjectWorkOrder.h" #include "SaveProjectWorkOrder.h" #include "SaveProjectAsWorkOrder.h" #include "SensorGetInfoWorkOrder.h" #include "SensorInfoWidget.h" #include "SetActiveControlWorkOrder.h" #include "SetActiveImageListWorkOrder.h" #include "TableView.h" #include "TableViewContent.h" #include "TargetInfoWidget.h" #include "TargetGetInfoWorkOrder.h" #include "TemplateEditorWidget.h" #include "TemplateEditViewWorkOrder.h" #include "ToolPad.h" #include "WarningTreeWidget.h" #include "WorkOrder.h" #include "Workspace.h" #include "XmlStackedHandler.h" #include "XmlStackedHandlerReader.h" namespace Isis { /** * @brief The Constructor * @throws IException::Programmer To handle the event that a Project cannot be created. * @throws IException::Programmer To handle the event that a Directory cannot be created * because the WorkOrders we are attempting to add to the Directory are corrupt. */ Directory::Directory(QObject *parent) : QObject(parent) { try { m_project = new Project(*this); } catch (IException &e) { throw IException(e, IException::Programmer, "Could not create directory because Project could not be created.", _FILEINFO_); } //connect( m_project, SIGNAL(imagesAdded(ImageList *) ), //this, SLOT(imagesAddedToProject(ImageList *) ) ); //connect( m_project, SIGNAL(targetsAdded(TargetBodyList *) ), //this, SLOT(targetsAddedToProject(TargetBodyList *) ) ); //connect( m_project, SIGNAL(guiCamerasAdded(GuiCameraList *) ), //this, SLOT(guiCamerasAddedToProject(GuiCameraList *) ) ); connect( m_project, SIGNAL(projectLoaded(Project *) ), this, SLOT(updateRecentProjects(Project *) ) ); // Send cnetModified() to project, so that we can set the project's clean state. // In the slot cnetModified(), it checks if the active was modified and then emits // activeControlModified(). This signal is connected below to this activeControlModified(), // which connects to views that use the active cnet to redraw themselves. // Ultimately, cnetModified() allows us to save changes made to any cnet, and // activeControlModified() allows other views to be redrawn. connect(this, SIGNAL(cnetModified()), m_project, SLOT(cnetModified())); connect(project(), SIGNAL(activeControlModified()), this, SIGNAL(activeControlModified())); connect(m_project, SIGNAL(activeControlSet(bool)), this, SLOT(newActiveControl(bool))); connect(m_project, SIGNAL(discardActiveControlEdits()), this, SLOT(reloadActiveControlInCnetEditorView())); m_projectItemModel = new ProjectItemModel(this); m_projectItemModel->addProject(m_project); connect(m_projectItemModel, SIGNAL(cleanProject(bool)), this, SIGNAL(cleanProject(bool))); try { // Context menu actions createWorkOrder<SetActiveImageListWorkOrder>(); createWorkOrder<SetActiveControlWorkOrder>(); createWorkOrder<CnetEditorViewWorkOrder>(); createWorkOrder<CubeDnViewWorkOrder>(); createWorkOrder<Footprint2DViewWorkOrder>(); createWorkOrder<MatrixViewWorkOrder>(); createWorkOrder<SensorGetInfoWorkOrder>(); //createWorkOrder<RemoveImagesWorkOrder>(); createWorkOrder<TargetGetInfoWorkOrder>(); createWorkOrder<BundleObservationViewWorkOrder>(); createWorkOrder<TemplateEditViewWorkOrder>(); createWorkOrder<ControlHealthMonitorWorkOrder>(); // Main menu actions m_exportControlNetWorkOrder = createWorkOrder<ExportControlNetWorkOrder>(); m_exportImagesWorkOrder = createWorkOrder<ExportImagesWorkOrder>(); m_importControlNetWorkOrder = createWorkOrder<ImportControlNetWorkOrder>(); m_importImagesWorkOrder = createWorkOrder<ImportImagesWorkOrder>(); m_importShapesWorkOrder = createWorkOrder<ImportShapesWorkOrder>(); m_importMapTemplateWorkOrder = createWorkOrder<ImportMapTemplateWorkOrder>(); m_importRegistrationTemplateWorkOrder = createWorkOrder<ImportRegistrationTemplateWorkOrder>(); m_openProjectWorkOrder = createWorkOrder<OpenProjectWorkOrder>(); m_saveProjectWorkOrder = createWorkOrder<SaveProjectWorkOrder>(); m_saveProjectAsWorkOrder = createWorkOrder<SaveProjectAsWorkOrder>(); m_runJigsawWorkOrder = createWorkOrder<JigsawWorkOrder>(); m_closeProjectWorkOrder = createWorkOrder<CloseProjectWorkOrder>(); m_renameProjectWorkOrder = createWorkOrder<RenameProjectWorkOrder>(); m_recentProjectsLoaded = false; } catch (IException &e) { throw IException(e, IException::Programmer, "Could not create directory because work orders are corrupt.", _FILEINFO_); } initializeActions(); m_editPointId = ""; } /** * @brief The Destructor. */ Directory::~Directory() { m_workOrders.clear(); if (m_project) { m_project ->deleteLater(); m_project = NULL; } } /** * @brief Get the list of actions that the Directory can provide for the file menu. * @return @b QList<QAction *> Returns a list of file menu actions. */ QList<QAction *> Directory::fileMenuActions() { return m_fileMenuActions; } /** * @brief Get the list of actions that the Directory can provide for the project menu. * @return @b QList<QAction *> Returns a list of project menu actions. */ QList<QAction *> Directory::projectMenuActions() { return m_projectMenuActions; } /** * @brief Get the list of actions that the Directory can provide for the edit menu. * @return @b QList<QAction *> Returns a list of edit menu actions. */ QList<QAction *> Directory::editMenuActions() { return m_editMenuActions; } /** * @brief Get the list of actions that the Directory can provide for the view menu. * @return @b QList<QAction *> Returns a list of view menu actions. */ QList<QAction *> Directory::viewMenuActions() { return m_viewMenuActions; } /** * @brief Get the list of actions that the Directory can provide for the settings menu. * @return @b QList<QAction *> Returns a list of menu actions for the settings. */ QList<QAction *> Directory::settingsMenuActions() { return m_settingsMenuActions; } /** * @brief Get the list of actions that the Directory can provide for the help menu. * @return @b QList<QAction *> Returns a list of help menu actions. */ QList<QAction *> Directory::helpMenuActions() { return m_helpMenuActions; } /** * @brief Get the list of actions that the Directory can provide for the permanent Tool Bar. * @return @b QList<QAction *> Returns a list of permanent tool bar menu actions. */ QList<QAction *> Directory::permToolBarActions() { return m_permToolBarActions; } /** * @brief Get the list of actions that the Directory can provide for the active Tool Bar. * @return @b QList<QAction *> Returns a list of active Tool Bar actions. */ QList<QAction *> Directory::activeToolBarActions() { return m_activeToolBarActions; } /** * @brief Get the list of actions that the Directory can provide for the Tool Pad. * @return @b QList<QAction *> Returns a list of Tool Pad actions. */ QList<QAction *> Directory::toolPadActions() { return m_toolPadActions; } /** * @brief Cleans directory of everything to do with the current project. * * This function was implemented to be called from the Project::clear function * to allow for a new project to be opened in IPCE. */ void Directory::clean() { emit directoryCleaned(); m_historyTreeWidget->clear(); m_warningTreeWidget->clear(); m_bundleObservationViews.clear(); m_cnetEditorViewWidgets.clear(); m_cubeDnViewWidgets.clear(); m_fileListWidgets.clear(); m_footprint2DViewWidgets.clear(); m_controlPointEditViewWidget.clear(); m_matrixViewWidgets.clear(); m_sensorInfoWidgets.clear(); m_targetInfoWidgets.clear(); m_templateEditorWidgets.clear(); m_jigsawRunWidget.clear(); m_projectItemModel->clean(); } /** * @brief Loads and displays a list of recently opened projects in the file menu. * @internal * @history Tyler Wilson 2017-10-17 - This function updates the Recent Projects File * menu. References #4492. * @history Adam Goins 2017-11-27 - Updated this function to add the most recent * project to the recent projects menu. References #5216. */ void Directory::updateRecentProjects() { if (m_recentProjectsLoaded) { QMenu *recentProjectsMenu = new QMenu("&Recent Projects"); foreach (QAction *action, m_fileMenuActions) { QString actionText(action->text()); if (actionText == "&Recent Projects") { // Grab the pointer to the actual ""&Recent Projects" menu in IPCE recentProjectsMenu = qobject_cast<QMenu*>(action->parentWidget()); break; } } QString projName = m_recentProjects.at(0).split("/").last(); QAction *openRecentProjectAction = m_openProjectWorkOrder->clone(); openRecentProjectAction->setText(projName); openRecentProjectAction->setToolTip(m_recentProjects.at(0)); if (recentProjectsMenu->isEmpty()) { recentProjectsMenu->addAction(openRecentProjectAction); return; } QAction *firstAction = recentProjectsMenu->actions().at(0); // If the opened project is already the most recent project, return. if (firstAction->text() == projName) { return; } // If the action we're placing at the first index already exists, // Then point to that action. foreach (QAction *action, recentProjectsMenu->actions()) { if (action->text() == projName) { openRecentProjectAction = action; break; } } recentProjectsMenu->insertAction(firstAction, openRecentProjectAction); if (recentProjectsMenu->actions().length() > Project::maxRecentProjects()) { recentProjectsMenu->removeAction(recentProjectsMenu->actions().last()); } } else { QMenu *fileMenu = new QMenu(); QMenu *recentProjectsMenu = fileMenu->addMenu("&Recent Projects"); int nRecentProjects = m_recentProjects.size(); for (int i = 0; i < nRecentProjects; i++) { FileName projectFileName = m_recentProjects.at(i); if (!projectFileName.fileExists() ) continue; QAction *openRecentProjectAction = m_openProjectWorkOrder->clone(); if ( !( (OpenProjectWorkOrder*)openRecentProjectAction ) ->isExecutable(m_recentProjects.at(i),true ) ) continue; QString projName = m_recentProjects.at(i).split("/").last(); openRecentProjectAction->setText(m_recentProjects.at(i).split("/").last() ); openRecentProjectAction->setToolTip(m_recentProjects.at(i)); recentProjectsMenu->addAction(openRecentProjectAction); } fileMenu->addSeparator(); m_fileMenuActions.append( fileMenu->actions() ); m_recentProjectsLoaded = true; } } /** * @brief Initializes the actions that the Directory can provide to a main window. * * Any work orders that need to be disabled by default can be done so here. * You need to grab the clone pointer, setEnabled(false), then set up the proper connections * between the project signals (representing changes to state) and WorkOrder::enableWorkOrder. * * @todo 2017-02-14 Tracie Sucharski - As far as I can tell the created menus are never used. * Instead of creating menus to use the addAction method, can't we simply create actions and * add them to the member variables which save the list of actions for each menu? */ void Directory::initializeActions() { // Menus are created temporarily to convinently organize the actions. QMenu *fileMenu = new QMenu(); //fileMenu->addAction(m_importControlNetWorkOrder->clone()); //fileMenu->addAction(m_importImagesWorkOrder->clone()); QAction *openProjectAction = m_openProjectWorkOrder->clone(); openProjectAction->setIcon(QIcon(FileName( "$ISISROOT/appdata/images/icons/archive-insert-directory.png").expanded())); fileMenu->addAction(openProjectAction); m_permToolBarActions.append(openProjectAction); QAction *saveAction = m_saveProjectWorkOrder->clone(); saveAction->setShortcut(Qt::Key_S | Qt::CTRL); saveAction->setIcon( QIcon(FileName("$ISISROOT/appdata/images/icons/document-save.png") .expanded())); saveAction->setDisabled(true); connect( project()->undoStack(), SIGNAL( cleanChanged(bool) ), saveAction, SLOT( setDisabled(bool) ) ); fileMenu->addAction(saveAction); m_permToolBarActions.append(saveAction); QAction *saveAsAction = m_saveProjectAsWorkOrder->clone(); saveAsAction->setIcon(QIcon(FileName("$ISISROOT/appdata/images/icons/document-save-as.png") .expanded())); fileMenu->addAction(saveAsAction); m_permToolBarActions.append(saveAsAction); fileMenu->addSeparator(); QMenu *importMenu = fileMenu->addMenu("&Import"); importMenu->addAction(m_importControlNetWorkOrder->clone() ); importMenu->addAction(m_importImagesWorkOrder->clone() ); importMenu->addAction(m_importShapesWorkOrder->clone() ); QMenu *importTemplateMenu = importMenu->addMenu("&Import Templates"); importTemplateMenu->addAction(m_importMapTemplateWorkOrder->clone() ); importTemplateMenu->addAction(m_importRegistrationTemplateWorkOrder->clone() ); QMenu *exportMenu = fileMenu->addMenu("&Export"); // Temporarily grab the export control network clone so we can listen for the // signals that tell us when we can export a cnet. We cannot export a cnet unless at least // one has been imported to the project. WorkOrder *clone = m_exportControlNetWorkOrder->clone(); clone->setEnabled(false); connect(m_project, SIGNAL(controlListAdded(ControlList *)), clone, SLOT(enableWorkOrder())); // TODO this is not setup yet // connect(m_project, &Project::allControlsRemoved, // clone, &WorkOrder::disableWorkOrder); exportMenu->addAction(clone); // Similarly for export images, disable the work order until we have images in the project. clone = m_exportImagesWorkOrder->clone(); clone->setEnabled(false); connect(m_project, SIGNAL(imagesAdded(ImageList *)), clone, SLOT(enableWorkOrder())); exportMenu->addAction(clone); fileMenu->addSeparator(); fileMenu->addAction(m_closeProjectWorkOrder->clone() ); m_fileMenuActions.append( fileMenu->actions() ); m_projectMenuActions.append(m_renameProjectWorkOrder->clone()); // For JigsawWorkOrder, disable the work order utnil we have both an active control and image // list. Setup a tool tip so user can see why the work order is disabled by default. // NOTE: Trying to set a what's this on the clone doesn't seem to work for disabled actions, // even though Qt's documentation says it should work on disabled actions. clone = m_runJigsawWorkOrder->clone(); if (project()->controls().count() && project()->images().count()) { clone->setEnabled(true); } else { clone->setEnabled(false); } // Listen for when both images and control net have been added to the project. connect(m_project, SIGNAL(controlsAndImagesAvailable()), clone, SLOT(enableWorkOrder())); // Listen for when both an active control and active image list have been set. // When this happens, we can enable the JigsawWorkOrder. // connect(m_project, &Project::activeControlAndImageListSet, // clone, &WorkOrder::enableWorkOrder); m_projectMenuActions.append(clone); // m_projectMenuActions.append( projectMenu->actions() ); m_editMenuActions = QList<QAction *>(); m_viewMenuActions = QList<QAction *>(); m_settingsMenuActions = QList<QAction *>(); m_helpMenuActions = QList<QAction *>(); } /** * @brief Set up the history info in the history dockable widget. * @param historyContainer The widget to fill. */ void Directory::setHistoryContainer(QDockWidget *historyContainer) { if (!m_historyTreeWidget) { m_historyTreeWidget = new HistoryTreeWidget( project() ); } historyContainer->setWidget(m_historyTreeWidget); } /** * @brief Set up the warning info in the warning dockable widget. * @param warningContainer The widget to fill. */ void Directory::setWarningContainer(QDockWidget *warningContainer) { if (!m_warningTreeWidget) { m_warningTreeWidget = new WarningTreeWidget; } warningContainer->setWidget(m_warningTreeWidget); } /** * @brief Add recent projects to the recent projects list. * @param recentProjects List of projects to add to list. */ void Directory::setRecentProjectsList(QStringList recentProjects) { m_recentProjects.append(recentProjects); } /** * @description This slot was created specifically for the CnetEditorWidgets when user chooses a * new active control and wants to discard any edits in the old active control. The only view * which will not be updated with the new control are any CnetEditorViews showing the old active * control. CnetEditorWidget classes do not have the ability to reload a control net, so the * CnetEditor view displaying the old control is removed, then recreated. * */ void Directory::reloadActiveControlInCnetEditorView() { foreach(CnetEditorView *cnetEditorView, m_cnetEditorViewWidgets) { if (cnetEditorView->control() == project()->activeControl()) { emit closeView(cnetEditorView); addCnetEditorView(project()->activeControl()); } } } /** * @description This slot is connected from the signal activeControlSet(bool) emitted from Project. * * * @param newControl bool * */ void Directory::newActiveControl(bool newControl) { if (newControl && m_controlPointEditViewWidget) { emit closeView(m_controlPointEditViewWidget); delete m_controlPointEditViewWidget; } // If the new active control is the same as what is showing in the cnetEditorWidget, allow // editing of control points from the widget, otherwise turnoff from context menu foreach(CnetEditorView *cnetEditorView, m_cnetEditorViewWidgets) { if (cnetEditorView->control() == project()->activeControl()) { cnetEditorView->cnetEditorWidget()->pointTableView()->content()->setActiveControlNet(true); cnetEditorView->cnetEditorWidget()->measureTableView()->content()->setActiveControlNet(true); } else { cnetEditorView->cnetEditorWidget()->pointTableView()->content()->setActiveControlNet(false); cnetEditorView->cnetEditorWidget()->measureTableView()->content()->setActiveControlNet(false); } } } /** * @brief Public accessor for the list of recent projects. * @return @b QStringList List of recent projects. */ QStringList Directory::recentProjectsList() { return m_recentProjects; } /** * @brief Add the BundleObservationView to the window. * @return @b (BundleObservationView *) The BundleObservationView displayed. */ BundleObservationView *Directory::addBundleObservationView(FileItemQsp fileItem) { BundleObservationView *result = new BundleObservationView(fileItem); connect( result, SIGNAL( destroyed(QObject *) ), this, SLOT( cleanupBundleObservationViews(QObject *) ) ); connect(result, SIGNAL(windowChangeEvent(bool)), m_project, SLOT(setClean(bool))); m_bundleObservationViews.append(result); QString str = fileItem->fileName(); FileName fileName = fileItem->fileName(); // strip out bundle results name from fileName QString path = fileName.originalPath(); int pos = path.lastIndexOf("/"); QString bundleResultsName = ""; if (pos != -1) { bundleResultsName = path.remove(0,pos+1); } if (str.contains("bundleout")) { result->setWindowTitle( tr("Summary (%1)"). arg( bundleResultsName ) ); result->setObjectName( result->windowTitle() ); } if (str.contains("residuals")) { result->setWindowTitle( tr("Measure Residuals (%1)"). arg( bundleResultsName ) ); result->setObjectName( result->windowTitle() ); } else if (str.contains("points")) { result->setWindowTitle( tr("Control Points (%1)"). arg( bundleResultsName ) ); result->setObjectName( result->windowTitle() ); } else if (str.contains("images")) { result->setWindowTitle( tr("Images (%1)"). arg( bundleResultsName ) ); result->setObjectName( result->windowTitle() ); } emit newWidgetAvailable(result); return result; } /** * @brief Add the widget for the cnet editor view to the window. * @param Control to edit. * @return @b (CnetEditorView *) The view to add to the window. */ CnetEditorView *Directory::addCnetEditorView(Control *control, QString objectName) { QString title = tr("Cnet Editor View %1").arg( control->displayProperties()->displayName() ); FileName configFile("$HOME/.Isis/" + QApplication::applicationName() + "/" + title + ".config"); CnetEditorView *result = new CnetEditorView(this, control, configFile); if (project()->activeControl() && (control == project()->activeControl())) { result->cnetEditorWidget()->pointTableView()->content()->setActiveControlNet(true); result->cnetEditorWidget()->measureTableView()->content()->setActiveControlNet(true); } // connect destroyed signal to cleanupCnetEditorViewWidgets slot connect(result, SIGNAL( destroyed(QObject *) ), this, SLOT( cleanupCnetEditorViewWidgets(QObject *) ) ); connect(result, SIGNAL(windowChangeEvent(bool)), m_project, SLOT(setClean(bool))); // Connections for control point editing between views connect(result->cnetEditorWidget(), SIGNAL(editControlPoint(ControlPoint *, QString)), this, SLOT(modifyControlPoint(ControlPoint *, QString))); // If a cnet is modified, we have to set the clean state in project and redraw measures. connect(result->cnetEditorWidget(), SIGNAL(cnetModified()), this, SIGNAL(cnetModified())); connect(this, SIGNAL(cnetModified()), result->cnetEditorWidget(), SLOT(rebuildModels())); m_cnetEditorViewWidgets.append(result); m_controlMap.insertMulti(control, result); result->setWindowTitle(title); if (objectName != "") { result->setObjectName(objectName); } else { // If no objectName, create unique identifier QString newObjectName = QUuid::createUuid().toString().remove(QRegExp("[{}]")); result->setObjectName(newObjectName); } emit newWidgetAvailable(result); return result; } /** * @brief Add the qview workspace to the window. * @return @b (CubeDnView*) The work space to display. */ CubeDnView *Directory::addCubeDnView(QString objectName) { CubeDnView *result = new CubeDnView(this, qobject_cast<QMainWindow *>(parent())); result->setModel(m_projectItemModel); m_cubeDnViewWidgets.append(result); connect( result, SIGNAL( destroyed(QObject *) ), this, SLOT( cleanupCubeDnViewWidgets(QObject *) ) ); connect(result, SIGNAL(windowChangeEvent(bool)), m_project, SLOT(setClean(bool))); result->setWindowTitle( tr("Cube DN View %1").arg(m_cubeDnViewWidgets.count() ) ); // Unique objectNames are needed for the save/restoreState if (objectName != "") { result->setObjectName(objectName); } else { // If no objectName, create unique identifier QString newObjectName = QUuid::createUuid().toString().remove(QRegExp("[{}]")); result->setObjectName(newObjectName); } emit newWidgetAvailable(result); // Connections between mouse button events from view and control point editing connect(result, SIGNAL(modifyControlPoint(ControlPoint *, QString)), this, SLOT(modifyControlPoint(ControlPoint *, QString))); connect(result, SIGNAL(deleteControlPoint(ControlPoint *)), this, SLOT(deleteControlPoint(ControlPoint *))); connect(result, SIGNAL(createControlPoint(double, double, Cube *, bool)), this, SLOT(createControlPoint(double, double, Cube *, bool))); // This signal is connected to the CubeDnView signal which connects to the slot, // ControlNetTool::paintAllViewports(). ControlNetTool always redraws all control points, so // both signals go to the same slot. connect(this, SIGNAL(redrawMeasures()), result, SIGNAL(redrawMeasures())); // If the active cnet is modified, redraw the measures connect(this, SIGNAL(activeControlModified()), result, SIGNAL(redrawMeasures())); connect (project(), SIGNAL(activeControlSet(bool)), result, SLOT(enableControlNetTool(bool))); return result; } /** * @brief Add the qmos view widget to the window. * @return @b (Footprint2DView*) A pointer to the Footprint2DView to display. */ Footprint2DView *Directory::addFootprint2DView(QString objectName) { Footprint2DView *result = new Footprint2DView(this); // Set source model on Proxy result->setModel(m_projectItemModel); m_footprint2DViewWidgets.append(result); result->setWindowTitle( tr("Footprint View %1").arg( m_footprint2DViewWidgets.count() ) ); // Unique objectNames are needed for the save/restoreState if (objectName != "") { result->setObjectName(objectName); } else { // If no objectName, create unique identifier QString newObjectName = QUuid::createUuid().toString().remove(QRegExp("[{}]")); result->setObjectName(newObjectName); } connect(result, SIGNAL(destroyed(QObject *)), this, SLOT(cleanupFootprint2DViewWidgets(QObject *))); connect(result, SIGNAL(windowChangeEvent(bool)), m_project, SLOT(setClean(bool))); emit newWidgetAvailable(result); // Connections between mouse button events from footprint2DView and control point editing connect(result, SIGNAL(modifyControlPoint(ControlPoint *)), this, SLOT(modifyControlPoint(ControlPoint *))); connect(result, SIGNAL(deleteControlPoint(ControlPoint *)), this, SLOT(deleteControlPoint(ControlPoint *))); connect(result, SIGNAL(createControlPoint(double, double)), this, SLOT(createControlPoint(double, double))); // The ControlPointEditWidget is only object that emits cnetModified when ControlPoint is // deleted or saved. This requires the footprint view ControlNetGraphicsItems to be re-built // when the active cnet is modified. connect(this, SIGNAL(activeControlModified()), result->mosaicSceneWidget(), SIGNAL(cnetModified())); // This signal is connected to the MosaicGraphicsScene::update(), which eventually calls // ControlNetGraphicsItem::paint(), then ControlPointGraphicsItem::paint(). This should only // be used if ControlNet has not changed. Used to update the current edit point in the view // to be drawn with different color/shape. connect(this, SIGNAL(redrawMeasures()), result, SIGNAL(redrawMeasures())); connect (project(), SIGNAL(activeControlSet(bool)), result, SLOT(enableControlNetTool(bool))); return result; } ControlHealthMonitorView *Directory::controlHealthMonitorView() { return m_controlHealthMonitorView; } ControlHealthMonitorView *Directory::addControlHealthMonitorView() { if (!controlHealthMonitorView()) { Control *activeControl = project()->activeControl(); if (activeControl == NULL) { QString message = "No active control network chosen. Choose active control network on " "project tree.\n"; QMessageBox::critical(qobject_cast<QWidget *>(parent()), "Error", message); return NULL; } ControlHealthMonitorView *result = new ControlHealthMonitorView(this); result->setWindowTitle(tr("Control NetHealth Monitor")); result->setObjectName(result->windowTitle()); m_controlHealthMonitorView = result; emit newWidgetAvailable(result); } return controlHealthMonitorView(); } ControlPointEditView *Directory::addControlPointEditView() { if (!controlPointEditView()) { // TODO Need parent for controlPointWidget ControlPointEditView *result = new ControlPointEditView(this); result->setWindowTitle(tr("Control Point Editor")); result->setObjectName(result->windowTitle()); Control *activeControl = project()->activeControl(); if (activeControl == NULL) { // Error and return to Select Tool QString message = "No active control network chosen. Choose active control network on " "project tree.\n"; QMessageBox::critical(qobject_cast<QWidget *>(parent()), "Error", message); return NULL; } result->controlPointEditWidget()->setControl(activeControl); if (!project()->activeImageList() || !project()->activeImageList()->serialNumberList()) { QString message = "No active image list chosen. Choose an active image list on the project " "tree.\n"; QMessageBox::critical(qobject_cast<QWidget *>(parent()), "Error", message); return NULL; } result->controlPointEditWidget()->setSerialNumberList( project()->activeImageList()->serialNumberList()); m_controlPointEditViewWidget = result; connect(result, SIGNAL(destroyed(QObject *)), this, SLOT(cleanupControlPointEditViewWidget(QObject *))); emit newWidgetAvailable(result); // 2017-06-09 Ken commented out for Data Workshop demo // m_chipViewports = new ChipViewportsWidget(result); // connect(m_chipViewports, SIGNAL(destroyed(QObject *)), this, SLOT(cleanupchipViewportWidges())); // m_chipViewports->setWindowTitle(tr("ChipViewport View")); // m_chipViewports->setObjectName(m_chipViewports->windowTitle()); // m_chipViewports->setSerialNumberList(project()->activeImageList()->serialNumberList()); // m_chipViewports->setControlNet(activeControl->controlNet(), activeControl->fileName()); // emit newWidgetAvailable(m_chipViewports); // 2017-06-09 Ken commented out for Data Workshop demo // Create connections between signals from control point edit view and equivalent directory // signals that can then be connected to other views that display control nets. // If the active was modified, this will be signaled in project's cnetModified() and // connected to other views to redraw themselves. connect(result->controlPointEditWidget(), SIGNAL(cnetModified()), this, SIGNAL(cnetModified())); connect (project(), SIGNAL(activeControlSet(bool)), result->controlPointEditWidget(), SLOT(setControlFromActive())); connect(result, SIGNAL(windowChangeEvent(bool)), m_project, SLOT(setClean(bool))); // Recolors the save net button in controlPointEditView to black after the cnets are saved. connect(m_project, SIGNAL(cnetSaved(bool)), result->controlPointEditWidget(), SLOT(colorizeSaveNetButton(bool))); } return controlPointEditView(); } #if 0 ChipViewportsWidget *Directory::addControlPointChipView() { ChipViewportsWidget *result = new ChipViewportsWidget(this); connect(result, SIGNAL(destroyed(QObject *)), this, SLOT(cleanupchipViewportWidges())); m_controlPointChipViews.append(result); result->setWindowTitle(tr("ChipViewport View %1").arg(m_controlPointChipViews.count())); result->setObjectName(result->windowTitle()); emit newWidgetAvailable(result); return result; } #endif /** * @brief Add the matrix view widget to the window. * @return @b (MatrixSceneWidget*) The widget to view. */ MatrixSceneWidget *Directory::addMatrixView() { MatrixSceneWidget *result = new MatrixSceneWidget(NULL, true, true, this); connect( result, SIGNAL( destroyed(QObject *) ), this, SLOT( cleanupMatrixViewWidgets(QObject *) ) ); m_matrixViewWidgets.append(result); result->setWindowTitle( tr("Matrix View %1").arg( m_matrixViewWidgets.count() ) ); result->setObjectName( result->windowTitle() ); emit newWidgetAvailable(result); return result; } /** * @brief Add target body data view widget to the window. * @return (TargetInfoWidget*) The widget to view. */ TargetInfoWidget *Directory::addTargetInfoView(TargetBodyQsp target) { TargetInfoWidget *result = new TargetInfoWidget(target.data(), this); connect( result, SIGNAL( destroyed(QObject *) ), this, SLOT( cleanupTargetInfoWidgets(QObject *) ) ); m_targetInfoWidgets.append(result); result->setWindowTitle( tr("%1").arg(target->displayProperties()->displayName() ) ); result->setObjectName( result->windowTitle() ); emit newWidgetAvailable(result); return result; } /** * @brief Add template editor view widget to the window. * @return (TemplateEditorWidget*) The widget to view. */ TemplateEditorWidget *Directory::addTemplateEditorView(Template *currentTemplate) { TemplateEditorWidget *result = new TemplateEditorWidget(currentTemplate, this); connect( result, SIGNAL( destroyed(QObject *) ), this, SLOT( cleanupTemplateEditorWidgets(QObject *) ) ); m_templateEditorWidgets.append(result); result->setWindowTitle( tr("%1").arg( FileName(currentTemplate->fileName()).name() ) ); result->setObjectName( result->windowTitle() ); emit newWidgetAvailable(result); return result; } JigsawRunWidget *Directory::addJigsawRunWidget() { if (jigsawRunWidget()) { return m_jigsawRunWidget; } JigsawRunWidget *result = new JigsawRunWidget(m_project); connect( result, SIGNAL( destroyed(QObject *) ), this, SLOT( cleanupJigsawRunWidget(QObject *) ) ); m_jigsawRunWidget = result; result->setAttribute(Qt::WA_DeleteOnClose); result->show(); emit newWidgetAvailable(result); return result; } /** * @brief Add sensor data view widget to the window. * @return @b (SensorInfoWidget*) The widget to view. */ SensorInfoWidget *Directory::addSensorInfoView(GuiCameraQsp camera) { SensorInfoWidget *result = new SensorInfoWidget(camera.data(), this); connect( result, SIGNAL( destroyed(QObject *) ), this, SLOT( cleanupSensorInfoWidgets(QObject *) ) ); m_sensorInfoWidgets.append(result); result->setWindowTitle( tr("%1").arg(camera->displayProperties()->displayName() ) ); result->setObjectName( result->windowTitle() ); emit newWidgetAvailable(result); return result; } /** * @brief Add an imageFileList widget to the window. * @return @b (ImageFileListWidget *) A pointer to the widget to add to the window. */ ImageFileListWidget *Directory::addImageFileListView(QString objectName) { ImageFileListWidget *result = new ImageFileListWidget(this); connect( result, SIGNAL( destroyed(QObject *) ), this, SLOT( cleanupFileListWidgets(QObject *) ) ); m_fileListWidgets.append(result); result->setWindowTitle( tr("File List %1").arg( m_fileListWidgets.count() ) ); // Unique objectNames are needed for the save/restoreState if (objectName != "") { result->setObjectName(objectName); } else { // If no objectName, create unique identifier QString newObjectName = QUuid::createUuid().toString().remove(QRegExp("[{}]")); result->setObjectName(newObjectName); } return result; } /** * @brief Adds a ProjectItemTreeView to the window. * @return @b (ProjectItemTreeView *) The added view. */ ProjectItemTreeView *Directory::addProjectItemTreeView() { ProjectItemTreeView *result = new ProjectItemTreeView(); result->setModel(m_projectItemModel); result->setWindowTitle( tr("Project")); result->setObjectName( result->windowTitle() ); // The model emits this signal when the user double-clicks on the project name, the parent // node located on the ProjectTreeView. connect(m_projectItemModel, SIGNAL(projectNameEdited(QString)), this, SLOT(initiateRenameProjectWorkOrder(QString))); connect(result, SIGNAL(windowChangeEvent(bool)), m_project, SLOT(setClean(bool))); return result; } /** * Slot which is connected to the model's signal, projectNameEdited, which is emitted when the user * double-clicks the project name, the parent node located on the ProjectTreeView. A * RenameProjectWorkOrder is created then passed to the Project which executes the WorkOrder. * * @param QString projectName New project name */ void Directory::initiateRenameProjectWorkOrder(QString projectName) { // Create the WorkOrder and add it to the Project. The Project will then execute the // WorkOrder. RenameProjectWorkOrder *workOrder = new RenameProjectWorkOrder(projectName, project()); project()->addToProject(workOrder); } /** * @brief Gets the ProjectItemModel for this directory. * @return @b (ProjectItemModel *) Returns a pointer to the ProjectItemModel. */ ProjectItemModel *Directory::model() { return m_projectItemModel; } /** * @brief Returns a pointer to the warning widget. * @return @b (QWidget *) The WarningTreeWidget pointer. */ QWidget *Directory::warningWidget() { return m_warningTreeWidget; } /** * @brief Removes pointers to deleted BundleObservationView objects. */ void Directory::cleanupBundleObservationViews(QObject *obj) { BundleObservationView *bundleObservationView = static_cast<BundleObservationView *>(obj); if (!bundleObservationView) { return; } m_bundleObservationViews.removeAll(bundleObservationView); m_project->setClean(false); } // /** // * @brief Removes pointers to deleted Control Health Monitor objects. // */ // void Directory::cleanupControlHealthMonitorView(QObject *obj) { // // ControlHealthMonitorView *healthMonitorView = static_cast<ControlHealthMonitorView *>(obj); // if (!healthMonitorView) { // return; // } // // m_project->setClean(false); // } /** * @brief Removes pointers to deleted CnetEditorWidget objects. */ void Directory::cleanupCnetEditorViewWidgets(QObject *obj) { CnetEditorView *cnetEditorView = static_cast<CnetEditorView *>(obj); if (!cnetEditorView) { return; } Control *control = m_controlMap.key(cnetEditorView); m_controlMap.remove(control, cnetEditorView); if ( m_controlMap.count(control) == 0 && project()->activeControl() != control) { control->closeControlNet(); } m_cnetEditorViewWidgets.removeAll(cnetEditorView); m_project->setClean(false); } /** * @description Return true if control is not currently being viewed in a CnetEditorWidget * * @param Control * Control used to search current CnetEditorWidgets * * @return @b (bool) Returns true if control is currently being viewed in CnetEditorWidget */ bool Directory::controlUsedInCnetEditorWidget(Control *control) { bool result; if ( m_controlMap.count(control) == 0) { result = false; } else { result = true; } return result; } /** * @brief Removes pointers to deleted CubeDnView objects. */ void Directory::cleanupCubeDnViewWidgets(QObject *obj) { CubeDnView *cubeDnView = static_cast<CubeDnView *>(obj); if (!cubeDnView) { return; } m_cubeDnViewWidgets.removeAll(cubeDnView); m_project->setClean(false); } /** * @brief Removes pointers to deleted ImageFileListWidget objects. */ void Directory::cleanupFileListWidgets(QObject *obj) { ImageFileListWidget *imageFileListWidget = static_cast<ImageFileListWidget *>(obj); if (!imageFileListWidget) { return; } m_fileListWidgets.removeAll(imageFileListWidget); m_project->setClean(false); } /** * @brief Removes pointers to deleted Footprint2DView objects. */ void Directory::cleanupFootprint2DViewWidgets(QObject *obj) { Footprint2DView *footprintView = static_cast<Footprint2DView *>(obj); if (!footprintView) { return; } m_footprint2DViewWidgets.removeAll(footprintView); m_project->setClean(false); } /** * @brief Delete the ControlPointEditWidget and set it's pointer to NULL. */ void Directory::cleanupControlPointEditViewWidget(QObject *obj) { ControlPointEditView *controlPointEditView = static_cast<ControlPointEditView *>(obj); if (!controlPointEditView) { return; } m_controlPointEditViewWidget = NULL; m_project->setClean(false); } /** * @brief Removes pointers to deleted MatrixSceneWidget objects. */ void Directory::cleanupMatrixViewWidgets(QObject *obj) { MatrixSceneWidget *matrixWidget = static_cast<MatrixSceneWidget *>(obj); if (!matrixWidget) { return; } m_matrixViewWidgets.removeAll(matrixWidget); m_project->setClean(false); } /** * @brief Removes pointers to deleted SensorInfoWidget objects. */ void Directory::cleanupSensorInfoWidgets(QObject *obj) { SensorInfoWidget *sensorInfoWidget = static_cast<SensorInfoWidget *>(obj); if (!sensorInfoWidget) { return; } m_sensorInfoWidgets.removeAll(sensorInfoWidget); m_project->setClean(false); } /** * @brief Removes pointers to deleted TargetInfoWidget objects. */ void Directory::cleanupTargetInfoWidgets(QObject *obj) { TargetInfoWidget *targetInfoWidget = static_cast<TargetInfoWidget *>(obj); if (!targetInfoWidget) { return; } m_targetInfoWidgets.removeAll(targetInfoWidget); m_project->setClean(false); } /** * @brief Removes pointers to deleted TemplateEditorWidget objects. */ void Directory::cleanupTemplateEditorWidgets(QObject *obj) { TemplateEditorWidget *templateEditorWidget = static_cast<TemplateEditorWidget *>(obj); if (!templateEditorWidget) { return; } m_templateEditorWidgets.removeAll(templateEditorWidget); m_project->setClean(false); } void Directory::cleanupJigsawRunWidget(QObject *obj) { JigsawRunWidget *jigsawRunWidget = static_cast<JigsawRunWidget *>(obj); if (!jigsawRunWidget) { return; } m_jigsawRunWidget = NULL; } /** * @brief Adds a new Project object to the list of recent projects if it has not * already been added. * @param project A pointer to the Project to add. */ void Directory::updateRecentProjects(Project *project) { m_recentProjects.insert( 0, project->projectRoot() ); } /** * @brief Gets the Project for this directory. * @return @b (Project *) Returns a pointer to the Project. */ Project *Directory::project() const { return m_project; } /** * @brief Returns a list of all the control network views for this directory. * @return @b QList<CnetEditorView *> A pointer list of all the CnetEditorWidget objects. */ QList<CnetEditorView *> Directory::cnetEditorViews() { QList<CnetEditorView *> results; foreach (CnetEditorView *widget, m_cnetEditorViewWidgets) { results.append(widget); } return results; } /** * @brief Accessor for the list of CubeDnViews currently available. * @return @b QList<CubeDnView *> The list CubeDnView objects. */ QList<CubeDnView *> Directory::cubeDnViews() { QList<CubeDnView *> results; foreach (CubeDnView *widget, m_cubeDnViewWidgets) { results.append(widget); } return results; } /** * @brief Accessor for the list of MatrixSceneWidgets currently available. * @return @b QList<MatrixSceneWidget *> The list of MatrixSceneWidget objects. */ QList<MatrixSceneWidget *> Directory::matrixViews() { QList<MatrixSceneWidget *> results; foreach (MatrixSceneWidget *widget, m_matrixViewWidgets) { results.append(widget); } return results; } /** * @brief Accessor for the list of SensorInfoWidgets currently available. * @return QList<SensorInfoWidget *> The list of SensorInfoWidget objects. */ QList<SensorInfoWidget *> Directory::sensorInfoViews() { QList<SensorInfoWidget *> results; foreach (SensorInfoWidget *widget, m_sensorInfoWidgets) { results.append(widget); } return results; } /** * @brief Accessor for the list of TargetInfoWidgets currently available. * @return @b QList<TargetInfoWidget *> The list of TargetInfoWidget objects. */ QList<TargetInfoWidget *> Directory::targetInfoViews() { QList<TargetInfoWidget *> results; foreach (TargetInfoWidget *widget, m_targetInfoWidgets) { results.append(widget); } return results; } /** * @brief Accessor for the list of TemplateEditorWidgets currently available. * @return @b QList<TemplateEditorWidget *> The list of TemplateEditorWidget objects. */ QList<TemplateEditorWidget *> Directory::templateEditorViews() { QList<TemplateEditorWidget *> results; foreach (TemplateEditorWidget *widget, m_templateEditorWidgets) { results.append(widget); } return results; } /** * @brief Accessor for the list of Footprint2DViews currently available. * @return QList<Footprint2DView *> The list of MosaicSceneWidget objects. */ QList<Footprint2DView *> Directory::footprint2DViews() { QList<Footprint2DView *> results; foreach (Footprint2DView *view, m_footprint2DViewWidgets) { results.append(view); } return results; } /** * @brief Accessor for the list of ImageFileListWidgets currently available. * @return QList<ImageFileListWidget *> The list of ImageFileListWidgets. */ QList<ImageFileListWidget *> Directory::imageFileListViews() { QList<ImageFileListWidget *> results; foreach (ImageFileListWidget *widget, m_fileListWidgets) { results.append(widget); } return results; } /** * @brief Gets the ControlPointEditWidget associated with the Directory. * @return @b (ControlPointEditWidget *) Returns a pointer to the ControlPointEditWidget. */ ControlPointEditView *Directory::controlPointEditView() { return m_controlPointEditViewWidget; } JigsawRunWidget *Directory::jigsawRunWidget() { return m_jigsawRunWidget; } /* ChipViewportsWidget *Directory::controlPointChipViewports() { return m_chipViewports; } */ /** * @brief Gets the ControlNetEditor associated with this the Directory. * @return @b (ControlNetEditor *) Returns a pointer to the ControlNetEditor. */ //ControlNetEditor *Directory::controlNetEditor() { // return m_cnetEditor; //} /** * @brief Returns a list of progress bars associated with this Directory. * @return @b QList<QProgressBar *> */ QList<QProgressBar *> Directory::progressBars() { QList<QProgressBar *> result; return result; } /** * @brief Displays a Warning * @param text The text to be displayed as a warning. */ void Directory::showWarning(QString text) { m_warningTreeWidget->showWarning(text); emit newWarning(); } /** * @brief Creates an Action to redo the last action. * @return @b (QAction *) Returns an action pointer to redo the last action. */ QAction *Directory::redoAction() { return project()->undoStack()->createRedoAction(this); } /** * @brief Creates an Action to undo the last action. * @return @b (QAction *) Returns an action pointer to undo the last action. */ QAction *Directory::undoAction() { return project()->undoStack()->createUndoAction(this); } /** * @brief Loads the Directory from an XML file. * @param xmlReader The reader that takes in and parses the XML file. */ void Directory::load(XmlStackedHandlerReader *xmlReader) { xmlReader->pushContentHandler( new XmlHandler(this) ); } /** * @brief Save the directory to an XML file. * @param stream The XML stream writer * @param newProjectRoot The FileName of the project this Directory is attached to. * * @internal * @history 2016-11-07 Ian Humphrey - Restored saving of footprints (footprint2view). * References #4486. */ void Directory::save(QXmlStreamWriter &stream, FileName newProjectRoot) const { stream.writeStartElement("directory"); if ( !m_fileListWidgets.isEmpty() ) { stream.writeStartElement("fileListWidgets"); foreach (ImageFileListWidget *fileListWidget, m_fileListWidgets) { fileListWidget->save(stream, project(), newProjectRoot); } stream.writeEndElement(); } // Save footprints if ( !m_footprint2DViewWidgets.isEmpty() ) { stream.writeStartElement("footprintViews"); foreach (Footprint2DView *footprint2DViewWidget, m_footprint2DViewWidgets) { footprint2DViewWidget->save(stream, project(), newProjectRoot); } stream.writeEndElement(); } // Save cubeDnViews if ( !m_cubeDnViewWidgets.isEmpty() ) { stream.writeStartElement("cubeDnViews"); foreach (CubeDnView *cubeDnView, m_cubeDnViewWidgets) { cubeDnView->save(stream, project(), newProjectRoot); } stream.writeEndElement(); } // Save cnetEditorViews if ( !m_cnetEditorViewWidgets.isEmpty() ) { stream.writeStartElement("cnetEditorViews"); foreach (CnetEditorView *cnetEditorWidget, m_cnetEditorViewWidgets) { cnetEditorWidget->save(stream, project(), newProjectRoot); } stream.writeEndElement(); } stream.writeEndElement(); } /** * @brief This function sets the Directory pointer for the Directory::XmlHandler class * @param directory The new directory we are setting XmlHandler's member variable to. */ Directory::XmlHandler::XmlHandler(Directory *directory) { m_directory = directory; } /** * @brief The Destructor for Directory::XmlHandler */ Directory::XmlHandler::~XmlHandler() { } /** * @brief The XML reader invokes this method at the start of every element in the * XML document. This method expects <footprint2DView/> and <imageFileList/> * elements. * A quick example using this function: * startElement("xsl","stylesheet","xsl:stylesheet",attributes) * * @param namespaceURI The Uniform Resource Identifier of the element's namespace * @param localName The local name string * @param qName The XML qualified string (or empty, if QNames are not available). * @param atts The XML attributes attached to each element * @return @b bool Returns True signalling to the reader the start of a valid XML element. If * False is returned, something bad happened. * */ bool Directory::XmlHandler::startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &atts) { bool result = XmlStackedHandler::startElement(namespaceURI, localName, qName, atts); if (result) { QString viewObjectName; if (localName == "footprint2DView") { viewObjectName = atts.value("objectName"); m_directory->addFootprint2DView(viewObjectName)->load(reader()); } else if (localName == "imageFileList") { viewObjectName = atts.value("objectName"); m_directory->addImageFileListView(viewObjectName)->load(reader()); } else if (localName == "cubeDnView") { viewObjectName = atts.value("objectName"); m_directory->addCubeDnView(viewObjectName)->load(reader(), m_directory->project()); } else if (localName == "cnetEditorView") { viewObjectName = atts.value("objectName"); QString id = atts.value("id"); m_directory->addCnetEditorView(m_directory->project()->control(id), viewObjectName); } } return result; } /** * @brief Reformat actionPairings to be user friendly for use in menus. * * actionPairings is: * Widget A -> * Action 1 * Action 2 * Action 3 * Widget B -> * Action 1 * Action 3 * NULL * Action 4 * ... * * We convert this into a list of actions, that when added to a menu, looks like: * Action 1 -> Widget A * Widget B * Action 2 on Widget A * Action 3 -> Widget A * Widget B * ---------------------- * Action 4 on Widget B * * The NULL separators aren't 100% yet, but work a good part of the time. * * This works by doing a data transformation and then using the resulting data structures * to populate the menu. * * actionPairings is transformed into: * restructuredData: * Action 1 -> (Widget A, QAction *) * (Widget B, QAction *) * Action 2 -> (Widget A, QAction *) * Action 3 -> (Widget A, QAction *) * (Widget B, QAction *) * Action 4 -> (Widget B, QAction *) * * and * * sortedActionTexts - A list of unique (if not empty) strings: * "Action 1" * "Action 2" * "Action 3" * "" * "Action 4" * * This transformation is done by looping linearly through actionPairings and for each action in * the pairings we add to the restructured data and append the action's text to * sortedActionTexts. * * We loop through sortedActionTexts and populate the menu based based on the current (sorted) * action text. If the action text is NULL (we saw a separator in the input), we add a NULL * (separator) to the resulting list of actions. If it isn't NULL, we create a menu or utilize * the action directly depending on if there are multiple actions with the same text. * * @param actionPairings A list of action pairings. * @return @b QList<QAction *> A list of actions that can be added to a menu. * */ QList<QAction *> Directory::restructureActions( QList< QPair< QString, QList<QAction *> > > actionPairings) { QList<QAction *> results; QStringList sortedActionTexts; // This is a map from the Action Text to the actions and their widget titles QMap< QString, QList< QPair<QString, QAction *> > > restructuredData; QPair< QString, QList<QAction *> > singleWidgetPairing; foreach (singleWidgetPairing, actionPairings) { QString widgetTitle = singleWidgetPairing.first; QList<QAction *> widgetActions = singleWidgetPairing.second; foreach (QAction *widgetAction, widgetActions) { if (widgetAction) { QString actionText = widgetAction->text(); restructuredData[actionText].append( qMakePair(widgetTitle, widgetAction) ); if ( !sortedActionTexts.contains(actionText) ) { sortedActionTexts.append(actionText); } } else { // Add separator if ( !sortedActionTexts.isEmpty() && !sortedActionTexts.last().isEmpty() ) { sortedActionTexts.append(""); } } } } if ( sortedActionTexts.count() && sortedActionTexts.last().isEmpty() ) { sortedActionTexts.removeLast(); } foreach (QString actionText, sortedActionTexts) { if ( actionText.isEmpty() ) { results.append(NULL); } else { // We know this list isn't empty because we always appended to the value when we // accessed a particular key. QList< QPair<QString, QAction *> > actions = restructuredData[actionText]; if (actions.count() == 1) { QAction *finalAct = actions.first().second; QString widgetTitle = actions.first().first; finalAct->setText( tr("%1 on %2").arg(actionText).arg(widgetTitle) ); results.append(finalAct); } else { QAction *menuAct = new QAction(actionText, NULL); QMenu *menu = new QMenu; menuAct->setMenu(menu); QList<QAction *> actionsInsideMenu; QPair<QString, QAction *> widgetTitleAndAction; foreach (widgetTitleAndAction, actions) { QString widgetTitle = widgetTitleAndAction.first; QAction *action = widgetTitleAndAction.second; action->setText(widgetTitle); actionsInsideMenu.append(action); } qSort(actionsInsideMenu.begin(), actionsInsideMenu.end(), &actionTextLessThan); QAction *allAct = new QAction(tr("All"), NULL); foreach (QAction *actionInMenu, actionsInsideMenu) { connect( allAct, SIGNAL( triggered() ), actionInMenu, SIGNAL( triggered() ) ); menu->addAction(actionInMenu); } menu->addSeparator(); menu->addAction(allAct); results.append(menuAct); } } } return results; } /** * @brief This is for determining the ordering of the descriptive text of * for the actions. * @param lhs The first QAction argument. * @param rhs The second QAction argument. * @return @b bool Returns True if the text for the lhs QAction is less than * the text for the rhs QAction. Returns False otherwise. */ bool Directory::actionTextLessThan(QAction *lhs, QAction *rhs) { return lhs->text().localeAwareCompare( rhs->text() ) < 0; } /** * @brief Updates the SIGNAL/SLOT connections for the cotrol net editor. */ void Directory::updateControlNetEditConnections() { #if 0 if (m_controlPointEditView && m_footprint2DViewWidgets.size() == 1) { connect(m_footprint2DViewWidgets.at(0), SIGNAL(controlPointSelected(ControlPoint *)), m_controlPointEdit, SLOT(loadControlPoint(ControlPoint *))); connect(m_cnetEditor, SIGNAL(controlPointCreated(ControlPoint *)), m_controlPointEditWidget, SLOT(setEditPoint(ControlPoint *))); // MosaicControlTool->MosaicSceneWidget->ControlNetEditor connect( m_footprint2DViewWidgets.at(0), SIGNAL( deleteControlPoint(QString) ), m_cnetEditor, SLOT( deleteControlPoint(QString) ) ); // ControlNetEditor->MosaicSceneWidget->MosaicControlTool connect( m_cnetEditor, SIGNAL( controlPointDeleted() ), m_footprint2DViewWidgets.at(0), SIGNAL( controlPointDeleted() ) ); // TODO Figure out which footprint view has the "active" cnet. //qDebug() << "\t\tMos items: " << m_footprint2DViewWidgets.at(0); connect(m_controlPointEditWidget, SIGNAL(controlPointChanged(QString)), m_footprint2DViewWidgets.at(0), SIGNAL(controlPointChanged(QString))); } #endif } /** * Slot that is connected from a left mouse button operation on views * * @param controlPoint (ControlPoint *) The control point selected from view for editing * @param serialNumber (QString) The serial number of Cube that was used to select control point * from the CubeDnView. This parameter will be empty if control point was * selected from Footprint2DView. * */ void Directory::modifyControlPoint(ControlPoint *controlPoint, QString serialNumber) { if (controlPoint) { if (!controlPointEditView()) { if (!addControlPointEditView()) { return; } } m_editPointId = controlPoint->GetId(); emit redrawMeasures(); controlPointEditView()->controlPointEditWidget()->setEditPoint(controlPoint, serialNumber); } } /** * Slot that is connected from a middle mouse button operation on views * * @param controlPoint (ControlPoint *) The control point selected from view for editing * */ void Directory::deleteControlPoint(ControlPoint *controlPoint) { if (controlPoint) { if (!controlPointEditView()) { if (!addControlPointEditView()) { return; } } m_editPointId = controlPoint->GetId(); // Update views with point to be deleted shown as current edit point emit redrawMeasures(); controlPointEditView()->controlPointEditWidget()->deletePoint(controlPoint); } } /** * Slot that is connected from a right mouse button operation on views * * @param latitude (double) Latitude location where the control point was created * @param longitude (double) Longitude location where the control point was created * @param cube (Cube *) The Cube in the CubeDnView that was used to select location for new control * point. This parameter will be empty if control point was selected from * Footprint2DView. * @param isGroundSource (bool) Indicates whether the Cube in the CubeDnView that was used to select * location for new control point is a ground source. This parameter will be * empty if control point was selected from Footprint2DView. * */ void Directory::createControlPoint(double latitude, double longitude, Cube *cube, bool isGroundSource) { if (!controlPointEditView()) { if (!addControlPointEditView()) { return; } } controlPointEditView()->controlPointEditWidget()->createControlPoint( latitude, longitude, cube, isGroundSource); m_editPointId = controlPointEditView()->controlPointEditWidget()->editPointId(); } /** * Return the current control point id loaded in the ControlPointEditWidget * * @return @b QString Id of the control point loaded in the ControlPointEditWidget */ QString Directory::editPointId() { return m_editPointId; } }
unlicense
yafeunteun/PSEUDO-IRC-SERVER
doc/html/search/enumvalues_62.js
149
var searchData= [ ['banned',['BANNED',['../channel_8h.html#a015eb90e0de9f16e87bd149d4b9ce959af4e03aa221959f565374a83c85ef7f2f',1,'channel.h']]] ];
unlicense
AnCh7/sweetshot
src/Steepshot.Core/Models/Requests/LoginRequest.cs
733
using System; using Newtonsoft.Json; namespace Steepshot.Core.Models.Requests { public class LoginWithPostingKeyRequest : BaseRequest { public LoginWithPostingKeyRequest(string username, string postingKey) { if (string.IsNullOrWhiteSpace(username)) throw new ArgumentNullException(nameof(username)); if (string.IsNullOrWhiteSpace(postingKey)) throw new ArgumentNullException(nameof(postingKey)); Username = username; PostingKey = postingKey; } [JsonProperty(PropertyName = "username")] public string Username { get; set; } [JsonProperty(PropertyName = "posting_key")] public string PostingKey { get; set; } } }
unlicense
cartman300/Vulkan.NET
Vulkan.NET/VK_KHR_surface/Structs_VK_KHR_surface.cs
1080
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using size_t = System.IntPtr; using uint32_t = System.UInt32; using int32_t = System.Int32; using uint8_t = System.Byte; using uint64_t = System.UInt64; using VkSurfaceTransformFlagsKHR = System.UInt32; // VkFlags using VkCompositeAlphaFlagsKHR = System.UInt32; // VkFlags using VkImageUsageFlags = System.UInt32; // VkFlags namespace VulkanNET.VK_KHR_surface { public unsafe struct VkSurfaceCapabilitiesKHR { public uint32_t minImageCount; public uint32_t maxImageCount; public VkExtent2D currentExtent; public VkExtent2D minImageExtent; public VkExtent2D maxImageExtent; public uint32_t maxImageArrayLayers; public VkSurfaceTransformFlagsKHR supportedTransforms; public VkSurfaceTransformFlagBitsKHR currentTransform; public VkCompositeAlphaFlagsKHR supportedCompositeAlpha; public VkImageUsageFlags supportedUsageFlags; } public unsafe struct VkSurfaceFormatKHR { public VkFormat format; public VkColorSpaceKHR colorSpace; } }
unlicense
muhit18/metrouni
views/admin/hours/tables/hours.php
2140
<?php if ( !empty($hours)) : ?> <table border="0" class="table-list"> <thead> <tr> <th width="20"><?php echo form_checkbox(array('name' => 'action_to_all', 'class' => 'check-all')); ?></th> <th><?php echo lang('metrouni:hour_lecture_label'); ?></th> <th class="collapse"><?php echo lang('metrouni:hour_day_label'); ?></th> <th class="collapse"><?php echo lang('metrouni:hour_beginhour_label'); ?></th> <th class="collapse"><?php echo lang('metrouni:hour_endhour_label'); ?></th> <th><?php echo lang('metrouni:hour_closed_label'); ?></th> <th width="180"></th> </tr> </thead> <tfoot> <tr> <td colspan="7"> <div class="inner"><?php $this->load->view('admin/partials/pagination'); ?></div> </td> </tr> </tfoot> <tbody> <?php foreach ($hours as $hour) : ?> <tr> <td><?php echo form_checkbox('action_to[]', $hour->id); ?></td> <td><?php echo $hour->hour; ?></td> <td class="collapse"><?php echo $hour->day; ?></td> <td class="collapse"><?php echo $hour->beginhour; ?></td> <td class="collapse"><?php echo $hour->endhour; ?></td> <td><?php echo $hour->closed; ?></td> <td> <?php echo anchor('admin/metrouni/hours/preview/' . $hour->id, lang('global:preview'), 'class="btn green modal"'); ?> <?php echo anchor('admin/metrouni/hours/edit/' . $hour->id, lang('global:edit'), 'class="btn orange edit"'); ?> <?php echo anchor('admin/metrouni/hours/delete/' . $hour->id, lang('global:delete'), array('class' => 'confirm btn red delete')); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php else: ?> <div class="no_data"><?php echo lang('metrouni:hour_none'); ?></div> <?php endif; ?>
unlicense
zyxakarene/LearningOpenGl
MainGame/src/zyx/OnTeaPotClicked.java
671
package zyx; import zyx.engine.curser.CursorManager; import zyx.engine.curser.GameCursor; import zyx.engine.utils.worldpicker.ClickedInfo; import zyx.game.controls.sound.SoundManager; import zyx.utils.cheats.DebugPoint; import zyx.engine.utils.worldpicker.IWorldPickedItem; import zyx.game.controls.input.MouseData; public class OnTeaPotClicked implements IWorldPickedItem { @Override public void onGeometryPicked(ClickedInfo info) { CursorManager.getInstance().setCursor(GameCursor.HAND); if (MouseData.data.isLeftClicked()) { DebugPoint.addToScene(info.position, 5000); SoundManager.getInstance().playSound("sound.Explosion", info.position); } } }
unlicense
dk00/old-stuff
csie/08design-patterns/src/com/sun/tools/javac/comp/ConstFold.java
14917
/* * Copyright 1999-2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.tools.javac.comp; import com.sun.tools.javac.code.*; import com.sun.tools.javac.jvm.*; import com.sun.tools.javac.util.*; import com.sun.tools.javac.code.Type.*; import static com.sun.tools.javac.code.TypeTags.*; import static com.sun.tools.javac.jvm.ByteCodes.*; /** Helper class for constant folding, used by the attribution phase. * This class is marked strictfp as mandated by JLS 15.4. * * <p><b>This is NOT part of any API supported by Sun Microsystems. If * you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> */ strictfp class ConstFold { protected static final Context.Key<ConstFold> constFoldKey = new Context.Key<ConstFold>(); private Symtab syms; public static ConstFold instance(Context context) { ConstFold instance = context.get(constFoldKey); if (instance == null) instance = new ConstFold(context); return instance; } private ConstFold(Context context) { context.put(constFoldKey, this); syms = Symtab.instance(context); } static Integer minusOne = -1; static Integer zero = 0; static Integer one = 1; /** Convert boolean to integer (true = 1, false = 0). */ private static Integer b2i(boolean b) { return b ? one : zero; } private static int intValue(Object x) { return ((Number)x).intValue(); } private static long longValue(Object x) { return ((Number)x).longValue(); } private static float floatValue(Object x) { return ((Number)x).floatValue(); } private static double doubleValue(Object x) { return ((Number)x).doubleValue(); } /** Fold binary or unary operation, returning constant type reflecting the * operations result. Return null if fold failed due to an * arithmetic exception. * @param opcode The operation's opcode instruction (usually a byte code), * as entered by class Symtab. * @param argtypes The operation's argument types (a list of length 1 or 2). * Argument types are assumed to have non-null constValue's. */ Type fold(int opcode, List<Type> argtypes) { int argCount = argtypes.length(); if (argCount == 1) return fold1(opcode, argtypes.head); else if (argCount == 2) return fold2(opcode, argtypes.head, argtypes.tail.head); else throw new AssertionError(); } /** Fold unary operation. * @param opcode The operation's opcode instruction (usually a byte code), * as entered by class Symtab. * opcode's ifeq to ifge are for postprocessing * xcmp; ifxx pairs of instructions. * @param operand The operation's operand type. * Argument types are assumed to have non-null constValue's. */ Type fold1(int opcode, Type operand) { try { Object od = operand.constValue(); switch (opcode) { case nop: return operand; case ineg: // unary - return syms.intType.constType(-intValue(od)); case ixor: // ~ return syms.intType.constType(~intValue(od)); case bool_not: // ! return syms.booleanType.constType(b2i(intValue(od) == 0)); case ifeq: return syms.booleanType.constType(b2i(intValue(od) == 0)); case ifne: return syms.booleanType.constType(b2i(intValue(od) != 0)); case iflt: return syms.booleanType.constType(b2i(intValue(od) < 0)); case ifgt: return syms.booleanType.constType(b2i(intValue(od) > 0)); case ifle: return syms.booleanType.constType(b2i(intValue(od) <= 0)); case ifge: return syms.booleanType.constType(b2i(intValue(od) >= 0)); case lneg: // unary - return syms.longType.constType(new Long(-longValue(od))); case lxor: // ~ return syms.longType.constType(new Long(~longValue(od))); case fneg: // unary - return syms.floatType.constType(new Float(-floatValue(od))); case dneg: // ~ return syms.doubleType.constType(new Double(-doubleValue(od))); default: return null; } } catch (ArithmeticException e) { return null; } } /** Fold binary operation. * @param opcode The operation's opcode instruction (usually a byte code), * as entered by class Symtab. * opcode's ifeq to ifge are for postprocessing * xcmp; ifxx pairs of instructions. * @param left The type of the operation's left operand. * @param right The type of the operation's right operand. */ Type fold2(int opcode, Type left, Type right) { try { if (opcode > ByteCodes.preMask) { // we are seeing a composite instruction of the form xcmp; ifxx. // In this case fold both instructions separately. Type t1 = fold2(opcode >> ByteCodes.preShift, left, right); return (t1.constValue() == null) ? t1 : fold1(opcode & ByteCodes.preMask, t1); } else { Object l = left.constValue(); Object r = right.constValue(); switch (opcode) { case iadd: return syms.intType.constType(intValue(l) + intValue(r)); case isub: return syms.intType.constType(intValue(l) - intValue(r)); case imul: return syms.intType.constType(intValue(l) * intValue(r)); case idiv: return syms.intType.constType(intValue(l) / intValue(r)); case imod: return syms.intType.constType(intValue(l) % intValue(r)); case iand: return (left.tag == BOOLEAN ? syms.booleanType : syms.intType) .constType(intValue(l) & intValue(r)); case bool_and: return syms.booleanType.constType(b2i((intValue(l) & intValue(r)) != 0)); case ior: return (left.tag == BOOLEAN ? syms.booleanType : syms.intType) .constType(intValue(l) | intValue(r)); case bool_or: return syms.booleanType.constType(b2i((intValue(l) | intValue(r)) != 0)); case ixor: return (left.tag == BOOLEAN ? syms.booleanType : syms.intType) .constType(intValue(l) ^ intValue(r)); case ishl: case ishll: return syms.intType.constType(intValue(l) << intValue(r)); case ishr: case ishrl: return syms.intType.constType(intValue(l) >> intValue(r)); case iushr: case iushrl: return syms.intType.constType(intValue(l) >>> intValue(r)); case if_icmpeq: return syms.booleanType.constType( b2i(intValue(l) == intValue(r))); case if_icmpne: return syms.booleanType.constType( b2i(intValue(l) != intValue(r))); case if_icmplt: return syms.booleanType.constType( b2i(intValue(l) < intValue(r))); case if_icmpgt: return syms.booleanType.constType( b2i(intValue(l) > intValue(r))); case if_icmple: return syms.booleanType.constType( b2i(intValue(l) <= intValue(r))); case if_icmpge: return syms.booleanType.constType( b2i(intValue(l) >= intValue(r))); case ladd: return syms.longType.constType( new Long(longValue(l) + longValue(r))); case lsub: return syms.longType.constType( new Long(longValue(l) - longValue(r))); case lmul: return syms.longType.constType( new Long(longValue(l) * longValue(r))); case ldiv: return syms.longType.constType( new Long(longValue(l) / longValue(r))); case lmod: return syms.longType.constType( new Long(longValue(l) % longValue(r))); case land: return syms.longType.constType( new Long(longValue(l) & longValue(r))); case lor: return syms.longType.constType( new Long(longValue(l) | longValue(r))); case lxor: return syms.longType.constType( new Long(longValue(l) ^ longValue(r))); case lshl: case lshll: return syms.longType.constType( new Long(longValue(l) << intValue(r))); case lshr: case lshrl: return syms.longType.constType( new Long(longValue(l) >> intValue(r))); case lushr: return syms.longType.constType( new Long(longValue(l) >>> intValue(r))); case lcmp: if (longValue(l) < longValue(r)) return syms.intType.constType(minusOne); else if (longValue(l) > longValue(r)) return syms.intType.constType(one); else return syms.intType.constType(zero); case fadd: return syms.floatType.constType( new Float(floatValue(l) + floatValue(r))); case fsub: return syms.floatType.constType( new Float(floatValue(l) - floatValue(r))); case fmul: return syms.floatType.constType( new Float(floatValue(l) * floatValue(r))); case fdiv: return syms.floatType.constType( new Float(floatValue(l) / floatValue(r))); case fmod: return syms.floatType.constType( new Float(floatValue(l) % floatValue(r))); case fcmpg: case fcmpl: if (floatValue(l) < floatValue(r)) return syms.intType.constType(minusOne); else if (floatValue(l) > floatValue(r)) return syms.intType.constType(one); else if (floatValue(l) == floatValue(r)) return syms.intType.constType(zero); else if (opcode == fcmpg) return syms.intType.constType(one); else return syms.intType.constType(minusOne); case dadd: return syms.doubleType.constType( new Double(doubleValue(l) + doubleValue(r))); case dsub: return syms.doubleType.constType( new Double(doubleValue(l) - doubleValue(r))); case dmul: return syms.doubleType.constType( new Double(doubleValue(l) * doubleValue(r))); case ddiv: return syms.doubleType.constType( new Double(doubleValue(l) / doubleValue(r))); case dmod: return syms.doubleType.constType( new Double(doubleValue(l) % doubleValue(r))); case dcmpg: case dcmpl: if (doubleValue(l) < doubleValue(r)) return syms.intType.constType(minusOne); else if (doubleValue(l) > doubleValue(r)) return syms.intType.constType(one); else if (doubleValue(l) == doubleValue(r)) return syms.intType.constType(zero); else if (opcode == dcmpg) return syms.intType.constType(one); else return syms.intType.constType(minusOne); case if_acmpeq: return syms.booleanType.constType(b2i(l.equals(r))); case if_acmpne: return syms.booleanType.constType(b2i(!l.equals(r))); case string_add: return syms.stringType.constType( left.stringValue() + right.stringValue()); default: return null; } } } catch (ArithmeticException e) { return null; } } /** Coerce constant type to target type. * @param etype The source type of the coercion, * which is assumed to be a constant type compatble with * ttype. * @param ttype The target type of the coercion. */ Type coerce(Type etype, Type ttype) { // WAS if (etype.baseType() == ttype.baseType()) if (etype.tsym.type == ttype.tsym.type) return etype; if (etype.tag <= DOUBLE) { Object n = etype.constValue(); switch (ttype.tag) { case BYTE: return syms.byteType.constType(0 + (byte)intValue(n)); case CHAR: return syms.charType.constType(0 + (char)intValue(n)); case SHORT: return syms.shortType.constType(0 + (short)intValue(n)); case INT: return syms.intType.constType(intValue(n)); case LONG: return syms.longType.constType(longValue(n)); case FLOAT: return syms.floatType.constType(floatValue(n)); case DOUBLE: return syms.doubleType.constType(doubleValue(n)); } } return ttype; } }
unlicense
bitmovin/bitmovin-python
examples/encoding/create_simple_encoding_with_audio_mix_filter.py
13123
import datetime from bitmovin import Bitmovin, Encoding, HTTPSInput, S3Output, H264CodecConfiguration, \ AACCodecConfiguration, H264Profile, StreamInput, SelectionMode, Stream, EncodingOutput, ACLEntry, ACLPermission, \ FMP4Muxing, MuxingStream, CloudRegion, DashManifest, FMP4Representation, FMP4RepresentationType, Period, \ VideoAdaptationSet, AudioAdaptationSet, AudioMixFilter, AudioMixFilterChannelLayout, AudioMixChannel, \ AudioMixSourceChannel, AudioMixFilterChannelType, StreamFilter from bitmovin.errors import BitmovinError API_KEY = '<INSERT_YOUR_API_KEY>' # https://<INSERT_YOUR_HTTP_HOST>/<INSERT_YOUR_HTTP_PATH> HTTPS_INPUT_HOST = '<INSERT_YOUR_HTTPS_HOST>' HTTPS_INPUT_PATH = '<INSERT_YOUR_HTTPS_PATH>' S3_OUTPUT_ACCESSKEY = '<INSERT_YOUR_ACCESS_KEY>' S3_OUTPUT_SECRETKEY = '<INSERT_YOUR_SECRET_KEY>' S3_OUTPUT_BUCKETNAME = '<INSERT_YOUR_BUCKET_NAME>' date_component = str(datetime.datetime.now()).replace(' ', '_').replace(':', '-').split('.')[0].replace('_', '__') OUTPUT_BASE_PATH = 'your/output/base/path/{}/'.format(date_component) def main(): bitmovin = Bitmovin(api_key=API_KEY) https_input = HTTPSInput(name='create_simple_encoding HTTPS input', host=HTTPS_INPUT_HOST) https_input = bitmovin.inputs.HTTPS.create(https_input).resource s3_output = S3Output(access_key=S3_OUTPUT_ACCESSKEY, secret_key=S3_OUTPUT_SECRETKEY, bucket_name=S3_OUTPUT_BUCKETNAME, name='Sample S3 Output') s3_output = bitmovin.outputs.S3.create(s3_output).resource encoding = Encoding(name='example encoding', cloud_region=CloudRegion.GOOGLE_EUROPE_WEST_1) encoding = bitmovin.encodings.Encoding.create(encoding).resource video_codec_configuration_1080p = H264CodecConfiguration(name='example_video_codec_configuration_1080p', bitrate=4800000, rate=25.0, width=1920, height=1080, profile=H264Profile.HIGH) video_codec_configuration_1080p = bitmovin.codecConfigurations.H264.create(video_codec_configuration_1080p).resource video_codec_configuration_720p = H264CodecConfiguration(name='example_video_codec_configuration_720p', bitrate=2400000, rate=25.0, width=1280, height=720, profile=H264Profile.HIGH) video_codec_configuration_720p = bitmovin.codecConfigurations.H264.create(video_codec_configuration_720p).resource audio_codec_configuration = AACCodecConfiguration(name='example_audio_codec_configuration_english', bitrate=128000, rate=48000) audio_codec_configuration = bitmovin.codecConfigurations.AAC.create(audio_codec_configuration).resource video_input_stream = StreamInput(input_id=https_input.id, input_path=HTTPS_INPUT_PATH, selection_mode=SelectionMode.AUTO) audio_input_stream = StreamInput(input_id=https_input.id, input_path=HTTPS_INPUT_PATH, selection_mode=SelectionMode.AUTO) video_stream_1080p = Stream(codec_configuration_id=video_codec_configuration_1080p.id, input_streams=[video_input_stream], name='Sample Stream 1080p') video_stream_1080p = bitmovin.encodings.Stream.create(object_=video_stream_1080p, encoding_id=encoding.id).resource video_stream_720p = Stream(codec_configuration_id=video_codec_configuration_720p.id, input_streams=[video_input_stream], name='Sample Stream 720p') video_stream_720p = bitmovin.encodings.Stream.create(object_=video_stream_720p, encoding_id=encoding.id).resource audio_stream = Stream(codec_configuration_id=audio_codec_configuration.id, input_streams=[audio_input_stream], name='Sample Stream AUDIO') audio_stream = bitmovin.encodings.Stream.create(object_=audio_stream, encoding_id=encoding.id).resource audio_mix_filter = AudioMixFilter(name="Audio Mix Channel", channel_layout=AudioMixFilterChannelLayout.CL_STEREO) audio_mix_channel_1 = AudioMixChannel(channel_number=0, source_channels=[AudioMixSourceChannel(channel_number=0, channel_type=AudioMixFilterChannelType.CHANNEL_NUMBER)]) audio_mix_channel_2 = AudioMixChannel(channel_number=1, source_channels=[AudioMixSourceChannel(channel_number=1, channel_type=AudioMixFilterChannelType.CHANNEL_NUMBER)]) audio_mix_filter.audio_mix_channels = [audio_mix_channel_1, audio_mix_channel_2] audio_mix_filter = bitmovin.filters.AudioMix.create(object_=audio_mix_filter).resource stream_filter = [StreamFilter(id=audio_mix_filter.id, position=0)] bitmovin.encodings.Stream.Filter.create(encoding_id=encoding.id, stream_id=audio_stream.id, stream_filter=stream_filter) acl_entry = ACLEntry(permission=ACLPermission.PUBLIC_READ) video_muxing_stream_1080p = MuxingStream(video_stream_1080p.id) video_muxing_stream_720p = MuxingStream(video_stream_720p.id) audio_muxing_stream = MuxingStream(audio_stream.id) video_muxing_1080p_output = EncodingOutput(output_id=s3_output.id, output_path=OUTPUT_BASE_PATH + 'video/1080p/', acl=[acl_entry]) video_muxing_1080p = FMP4Muxing(segment_length=4, segment_naming='seg_%number%.m4s', init_segment_name='init.mp4', streams=[video_muxing_stream_1080p], outputs=[video_muxing_1080p_output], name='Sample Muxing 1080p') video_muxing_1080p = bitmovin.encodings.Muxing.FMP4.create(object_=video_muxing_1080p, encoding_id=encoding.id).resource video_muxing_720p_output = EncodingOutput(output_id=s3_output.id, output_path=OUTPUT_BASE_PATH + 'video/720p/', acl=[acl_entry]) video_muxing_720p = FMP4Muxing(segment_length=4, segment_naming='seg_%number%.m4s', init_segment_name='init.mp4', streams=[video_muxing_stream_720p], outputs=[video_muxing_720p_output], name='Sample Muxing 720p') video_muxing_720p = bitmovin.encodings.Muxing.FMP4.create(object_=video_muxing_720p, encoding_id=encoding.id).resource audio_muxing_output = EncodingOutput(output_id=s3_output.id, output_path=OUTPUT_BASE_PATH + 'audio/', acl=[acl_entry]) audio_muxing = FMP4Muxing(segment_length=4, segment_naming='seg_%number%.m4s', init_segment_name='init.mp4', streams=[audio_muxing_stream], outputs=[audio_muxing_output], name='Sample Muxing AUDIO') audio_muxing = bitmovin.encodings.Muxing.FMP4.create(object_=audio_muxing, encoding_id=encoding.id).resource bitmovin.encodings.Encoding.start(encoding_id=encoding.id) try: bitmovin.encodings.Encoding.wait_until_finished(encoding_id=encoding.id) except BitmovinError as bitmovin_error: print("Exception occurred while waiting for encoding to finish: {}".format(bitmovin_error)) manifest_output = EncodingOutput(output_id=s3_output.id, output_path=OUTPUT_BASE_PATH, acl=[acl_entry]) dash_manifest = DashManifest(manifest_name='example_manifest_sintel_dash.mpd', outputs=[manifest_output], name='Sample DASH Manifest') dash_manifest = bitmovin.manifests.DASH.create(dash_manifest).resource period = Period() period = bitmovin.manifests.DASH.add_period(object_=period, manifest_id=dash_manifest.id).resource video_adaptation_set = VideoAdaptationSet() video_adaptation_set = bitmovin.manifests.DASH.add_video_adaptation_set(object_=video_adaptation_set, manifest_id=dash_manifest.id, period_id=period.id).resource audio_adaptation_set = AudioAdaptationSet(lang='en') audio_adaptation_set = bitmovin.manifests.DASH.add_audio_adaptation_set(object_=audio_adaptation_set, manifest_id=dash_manifest.id, period_id=period.id).resource fmp4_representation_1080p = FMP4Representation(FMP4RepresentationType.TEMPLATE, encoding_id=encoding.id, muxing_id=video_muxing_1080p.id, segment_path='video/1080p/') fmp4_representation_1080p = bitmovin.manifests.DASH.add_fmp4_representation(object_=fmp4_representation_1080p, manifest_id=dash_manifest.id, period_id=period.id, adaptationset_id=video_adaptation_set.id ).resource fmp4_representation_720p = FMP4Representation(FMP4RepresentationType.TEMPLATE, encoding_id=encoding.id, muxing_id=video_muxing_720p.id, segment_path='video/720p/') fmp4_representation_720p = bitmovin.manifests.DASH.add_fmp4_representation(object_=fmp4_representation_720p, manifest_id=dash_manifest.id, period_id=period.id, adaptationset_id=video_adaptation_set.id ).resource fmp4_representation_audio = FMP4Representation(FMP4RepresentationType.TEMPLATE, encoding_id=encoding.id, muxing_id=audio_muxing.id, segment_path='audio/') fmp4_representation_audio = bitmovin.manifests.DASH.add_fmp4_representation(object_=fmp4_representation_audio, manifest_id=dash_manifest.id, period_id=period.id, adaptationset_id=audio_adaptation_set.id ).resource bitmovin.manifests.DASH.start(manifest_id=dash_manifest.id) try: bitmovin.manifests.DASH.wait_until_finished(manifest_id=dash_manifest.id) except BitmovinError as bitmovin_error: print("Exception occurred while waiting for manifest creation to finish: {}".format(bitmovin_error)) if __name__ == '__main__': main()
unlicense
kurogetsusai/saiko
src/functions/function.js
1282
/** Functions to do operations on functions. * @module functions/function */ /** Composes any number of functions: (f∘g)(x) = f(g(x)). * Functions are applied from right to left (the last parameter is invoked first). * All functions should accept 1 parameter, except the rightmost one, which can * have any number of parameters. * If run without parameters, returns a function which returns the first parameter. * @param {...function} functions - the functions to compose * @returns {function} - the function composing all input functions */ export const compose = (...functions) => functions.length === 0 ? param => param : functions.reduce((f, g) => (...params) => f(g(...params)) ); /** If func is a function, it runs it and returns its result. If func is not a * function, returns func. * @param {*} func * @param {...*} parameters * @returns {*} - func's result */ export const evaluate = func => (...parameters) => typeof func === 'function' ? func(...parameters) : func; /** The same as compose but applies parameter from left to right. * @param {...function} functions - the functions to compose * @returns {function} - the function composing all input functions */ export const sequence = (...functions) => compose(...functions.reverse());
unlicense
mirzadelic/django-social-example
django_social_example/django_app/wsgi.py
398
""" WSGI config for django_app project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_app.settings") application = get_wsgi_application()
unlicense
itssuedev/theme-itssue
front-page.php
918
<?php /** * front-page.php - 사이트의 랜딩 페이지를 담당하는 템플릿 * * @package theme-itssue */ get_header(); ?> <div class="slider"> <!-- 슬라이더 영역 --> <?php echo do_shortcode( get_theme_mod( 'it_customize_front_slider' ) ); ?> <!-- /슬라이더 영역 --> </div><!-- .slider --> <div class="blocks"> <?php $i = 1; for( ; 3 >= $i; $i++ ) : ?> <div id="front-block-<?php echo $i; ?>" class="one-third"> <?php echo it_front_block( $i ); ?> </div> <?php endfor; ?> </div> <div class="blocks"> <div class="two-third"> <?php for( ; 7>= $i; $i++ ) : ?> <div id="front-block-<?php echo $i; ?>" class="one-second"> <?php echo it_front_block( $i ); ?> </div> <?php endfor; ?> </div> <div class="one-third block-fbw"> <?php echo do_shortcode( get_theme_mod( 'it_customize_front_sns' ) ); ?> </div> </div> <?php get_footer();
unlicense
amounir86/amounir86-2011-elections
voter-info/shapes/json/248_3549.js
848
GoogleElectionMap.shapeReady({name:"248_3549",type:"state",state:"248_3549",bounds:[],centroid:[],shapes:[ {points:[ {x:29.0591502876797,y: 30.7664419760837} , {x:29.0570619461407,y: 30.74170754417} , {x:28.9982574450908,y: 30.7511733766875} , {x:28.9898422162064,y: 30.7648891065078} , {x:28.9877921585818,y: 30.7727608661071} , {x:28.9834676181508,y: 30.7800660699305} , {x:28.9803888000917,y: 30.7988166429999} , {x:28.9807723538443,y: 30.8171787144629} , {x:28.9843169343547,y: 30.8319505077746} , {x:28.9893671528622,y: 30.8297479824357} , {x:28.9910281232255,y: 30.8290221123466} , {x:28.9929221671831,y: 30.8287202881013} , {x:29.0016736384834,y: 30.8272133082872} , {x:29.0291142316824,y: 30.8239666773417} , {x:29.05092624936,y: 30.8216938348472} , {x:29.063811478168,y: 30.8216345577087} , {x:29.0591502876797,y: 30.7664419760837} ]} ]})
unlicense
prakhar1989/rust-rosetta
src/zig-zag_matrix.rs
1661
// implements http://rosettacode.org/wiki/Zig-zag_matrix // with the sorting indexes algorithm // explained in the discussion page // http://rosettacode.org/wiki/Talk:Zig-zag_matrix #[deriving(Show, PartialEq, Eq)] struct SortIndex { x: uint, y: uint } impl SortIndex { fn new(x:uint, y:uint) -> SortIndex { SortIndex{x:x, y:y} } } impl PartialOrd for SortIndex { fn partial_cmp(&self, other: &SortIndex) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for SortIndex { fn cmp(&self, other: &SortIndex) -> Ordering { let lower = if self.x + self.y == other.x + other.y { if (self.x + self.y) % 2 == 0 { self.x < other.x } else { self.y < other.y } } else { (self.x + self.y) < (other.x + other.y) }; if lower { Less } else if self == other { Equal } else { Greater } } } fn zigzag(n:uint) -> Vec<Vec<uint>> { let mut l:Vec<SortIndex> = range(0u, n*n).map(|i| SortIndex::new(i%n,i/n)).collect(); l.sort(); let mut result : Vec<Vec<uint>> = Vec::from_elem(n, Vec::from_elem(n,0u)); for (i,&SortIndex{x,y}) in l.iter().enumerate() { *result.get_mut(y).get_mut(x) = i } result } #[cfg(not(test))] fn main() { println!("{}", zigzag(5)); } #[test] fn result() { let exp =vec![vec![0, 1, 5, 6,14], vec![2, 4, 7,13,15], vec![3, 8,12,16,21], vec![9, 11,17,20,22], vec![10,18,19,23,24]]; assert_eq!(zigzag(5), exp); }
unlicense
zyphlar/freshbooks-resizer
injected.js
515
window.normalWidth = window.outerWidth; window.normalHeight = window.outerHeight; window.minWidth = window.outerWidth; window.minHeight = 160; function freshbooksResize(){ var resizeButton = document.getElementById("freshbooks-resize-button"); if(window.outerHeight == window.normalHeight){ window.resizeTo(window.minWidth,window.minHeight); resizeButton.innerHTML = "&#x25B2;"; } else{ window.resizeTo(window.normalWidth,window.normalHeight); resizeButton.innerHTML = "&#x25BC;"; } }
unlicense
thinkAmi-sandbox/Django_permissions_sample
myapp/migrations/0001_initial.py
881
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-30 13:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('public_content', models.CharField(max_length=255, verbose_name='public')), ('private_content', models.CharField(max_length=255, verbose_name='private')), ('permission_content', models.CharField(max_length=255, verbose_name='private')), ], options={ 'permissions': (('can_view', 'Can see content'),), }, ), ]
unlicense
nekokat/codewars
8 kyu_1/duck-duck-goose.rb
171
#Kata: Duck Duck Goose #URL: https://www.codewars.com/kata/582e0e592029ea10530009ce def duck_duck_goose(players, goose) players[(goose%players.size).pred].name end
unlicense
matyb/leh
leh-test/integration/leh/util/LEHCachingPerformanceTest.java
3534
package leh.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import leh.example.food.Food; import leh.example.food.Food.FoodType; import leh.example.person.Employee; import leh.example.person.Person; import org.junit.Before; import org.junit.Test; public class LEHCachingPerformanceTest { List<String> timings; @Before public void setUp(){ timings = new ArrayList<String>(); } /* * last count: on an i5 4670K 16GB of DDR3 and SSD in Win 8 w/ JDK 1.7.0.45. * * took: 243ms. for: *Executing supported Object APIs 1000 times. * took: 241ms. for: =LEH Equivalent java.lang.Object methods: * took: 50ms. for: -class leh.util.LEH$LEHInstance.getHashCode(instance1) * took: 5ms. for: -class leh.util.LEH$LEHInstance.isEqual(instance1, instance1.getSpouse()) * took: 48ms. for: -class leh.util.LEH$LEHInstance.isEqual(instance1, instance2) * took: 134ms. for: -class leh.util.LEH$LEHInstance.getToString(person1) * * @throws Exception */ @Test public void testCachingPerformance_1000times() throws Exception { executePubliclyExposedLEHMethods(1000); } private void executePubliclyExposedLEHMethods(final int runs) { time(1, "*Executing supported Object APIs " + runs + " times.", new Runnable(){ public void run() { final Employee instance1 = createEmployee(); final Employee instance2 = createEmployee(); time(1, " =LEH Equivalent java.lang.Object methods:", new Runnable() { public void run() { executePubliclyExposedLEHMethods(runs, instance1, instance2); } }); } }); for(int i = timings.size() - 1; i > -1; i--){ System.out.println(timings.get(i)); } } private void executePubliclyExposedLEHMethods(int runs, final Employee instance1, final Employee instance2) { final LEHDelegate leh = LEH.getInstance(); String testNamePrefix = " -" + leh.getClass() + "."; final Object wrappedInstance = leh.getInstance(instance1); time(runs, testNamePrefix + "getToString(person1)", new Runnable() { public void run() { wrappedInstance.toString(); } }); time(runs, testNamePrefix + "isEqual(instance1, instance2)", new Runnable() { public void run() { wrappedInstance.equals(instance2); } }); time(runs, testNamePrefix + "isEqual(instance1, instance1.getSpouse())", new Runnable() { public void run() { wrappedInstance.equals(instance1.getSpouse()); } }); time(runs, testNamePrefix + "getHashCode(instance1)", new Runnable() { public void run() { wrappedInstance.hashCode(); } }); } private Employee createEmployee() { final Employee person = new Employee(); person.setSsn("123456789"); Date birthDate = new Date(); person.setBirthDate(birthDate); final Person spouse = new Person(); Food food = new Food(); food.setType(FoodType.PIZZA); spouse.setFavoriteFoods(Arrays.asList(food)); spouse.setFirstName("Brian"); person.setSpouse(spouse); return person; } // just private because there's really no good reason other "unit" tests // should be doing this... if this were appropriate for unit tests it would // be in a test util class. private void time(int runs, String testName, Runnable behavior) { long start = System.currentTimeMillis(); for (int i = 0; i < runs; i++) { behavior.run(); } long time = System.currentTimeMillis() - start; timings.add(String.format("%1$-" + 20 + "s", "took: " + time + "ms. for: ") + testName); } }
unlicense
EpitaJS/js-class-2016-episode-3
jspm_packages/npm/lodash@4.0.1/keys.js
790
/* */ var baseHas = require('./internal/baseHas'), baseKeys = require('./internal/baseKeys'), indexKeys = require('./internal/indexKeys'), isArrayLike = require('./isArrayLike'), isIndex = require('./internal/isIndex'), isPrototype = require('./internal/isPrototype'); function keys(object) { var isProto = isPrototype(object); if (!(isProto || isArrayLike(object))) { return baseKeys(object); } var indexes = indexKeys(object), skipIndexes = !!indexes, result = indexes || [], length = result.length; for (var key in object) { if (baseHas(object, key) && !(skipIndexes && (key == 'length' || isIndex(key, length))) && !(isProto && key == 'constructor')) { result.push(key); } } return result; } module.exports = keys;
unlicense
Mostly-Horrific/Visual-Novel-Engine
VNNLangaugeTests/Properties/AssemblyInfo.cs
1403
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("VNNLangaugeTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("VNNLangaugeTests")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("3f64c6fa-060a-4d8e-b3cc-887efc157d89")] // 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")]
unlicense
RodionSmolnikov/RSUStationOptimalPlacement
src/main/java/system/Executor.java
1353
package system; import entities.interfaces.Model; import entities.interfaces.ParameterContainer; import entities.interfaces.ResultCollector; /** * Created by Rodion on 04.04.2015. */ public abstract class Executor { private ResultCollector collector; private int threadCount; public static final int DEFAULT_THREAD_COUNT = 4; protected Executor(ResultCollector collector, int threadCount) { this.collector = collector; this.threadCount = threadCount; } protected Executor(ResultCollector collector) { this.collector = collector; this.threadCount = DEFAULT_THREAD_COUNT; } public int getThreadCount() { return threadCount; } public ResultCollector getCollector() { return collector; } public void execute(ModelFactory factory) throws Exception { factory.setCollector(getCollector()); long time = System.currentTimeMillis(); getCollector().pushFlashMessage("Start execution"); action(factory); getCollector().pushFlashMessage("End execution. Execution time = " + (System.currentTimeMillis() - time) + " ms"); getCollector().printResults(); printExecutionResult(); } public abstract void action(ModelFactory model) throws Exception; public abstract void printExecutionResult(); }
unlicense
Tom94/AiModtpDifficultyCalculator
AiModtpDifficulty.cs
9169
using System; using System.Collections.Generic; using System.Text; using osu.GameModes.Edit.AiMod; using osu.GameplayElements.Beatmaps; using osu.GameplayElements.HitObjects; using osu.Interfacing; namespace AiModtpDifficultyCalculator { /// <summary> /// osu!tp's difficulty calculator ported to the osu! sdk as far as so far possible. /// </summary> public class AiModtpDifficulty : AiModRuleset { // Those values are used as array indices. Be careful when changing them! public enum DifficultyType : int { Speed = 0, Aim, }; // We will store the HitObjects as a member variable. List<tpHitObject> tpHitObjects; private const double STAR_SCALING_FACTOR = 0.045; private const double EXTREME_SCALING_FACTOR = 0.5; private const float PLAYFIELD_WIDTH = 512; public override AiModType Type { get { return AiModType.Compose; } } protected override void RunAllRules(List<HitObjectBase> hitObjects) { BeatmapBase Beatmap = OsuHelper.GetCurrentBeatmap(); // Mods are not yet supported. TODO // Fill our custom tpHitObject class, that carries additional information tpHitObjects = new List<tpHitObject>(hitObjects.Count); float CircleRadius = (PLAYFIELD_WIDTH / 16.0f) * (1.0f - 0.7f * ((float)Beatmap.DifficultyCircleSize - 5.0f) / 5.0f); foreach(HitObjectBase hitObject in hitObjects) { tpHitObjects.Add(new tpHitObject(hitObject, CircleRadius)); } // Sort tpHitObjects by StartTime of the HitObjects - just to make sure. Not using CompareTo, since it results in a crash (HitObjectBase inherits MarshalByRefObject) tpHitObjects.Sort((a,b) => a.BaseHitObject.StartTime - b.BaseHitObject.StartTime); if (CalculateStrainValues() == false) { Reports.Add(new AiReport(Severity.Error, "Could not compute strain values. Aborting difficulty calculation.")); return; } double SpeedDifficulty = CalculateDifficulty(DifficultyType.Speed); double AimDifficulty = CalculateDifficulty(DifficultyType.Aim); // OverallDifficulty is not considered in this algorithm and neither is HpDrainRate. That means, that in this form the algorithm determines how hard it physically is // to play the map, assuming, that too much of an error will not lead to a death. // It might be desirable to include OverallDifficulty into map difficulty, but in my personal opinion it belongs more to the weighting of the actual peformance // and is superfluous in the beatmap difficulty rating. // If it were to be considered, then I would look at the hit window of normal HitCircles only, since Sliders and Spinners are (almost) "free" 300s and take map length // into account as well. Reports.Add(new AiReport(Severity.Info, "Speed difficulty: " + SpeedDifficulty + " | Aim difficulty: " + AimDifficulty)); // The difficulty can be scaled by any desired metric. // In osu!tp it gets squared to account for the rapid increase in difficulty as the limit of a human is approached. (Of course it also gets scaled afterwards.) // It would not be suitable for a star rating, therefore: // The following is a proposal to forge a star rating from 0 to 5. It consists of taking the square root of the difficulty, since by simply scaling the easier // 5-star maps would end up with one star. double SpeedStars = Math.Sqrt(SpeedDifficulty) * STAR_SCALING_FACTOR; double AimStars = Math.Sqrt(AimDifficulty) * STAR_SCALING_FACTOR; Reports.Add(new AiReport(Severity.Info, "Speed stars: " + SpeedStars + " | Aim stars: " + AimStars)); // Again, from own observations and from the general opinion of the community a map with high speed and low aim (or vice versa) difficulty is harder, // than a map with mediocre difficulty in both. Therefore we can not just add both difficulties together, but will introduce a scaling that favors extremes. double StarRating = SpeedStars + AimStars + Math.Abs(SpeedStars - AimStars) * EXTREME_SCALING_FACTOR; // Another approach to this would be taking Speed and Aim separately to a chosen power, which again would be equivalent. This would be more convenient if // the hit window size is to be considered as well. // Note: The star rating is tuned extremely tight! Airman (/b/104229) and Freedom Dive (/b/126645), two of the hardest ranked maps, both score ~4.66 stars. // Expect the easier kind of maps that officially get 5 stars to obtain around 2 by this metric. The tutorial still scores about half a star. // Tune by yourself as you please. ;) Reports.Add(new AiReport(Severity.Info, "Total star rating: " + StarRating)); } // Exceptions would be nicer to handle errors, but for this small project it shall be ignored. private bool CalculateStrainValues() { // Traverse hitObjects in pairs to calculate the strain value of NextHitObject from the strain value of CurrentHitObject and environment. List<tpHitObject>.Enumerator HitObjectsEnumerator = tpHitObjects.GetEnumerator(); if (HitObjectsEnumerator.MoveNext() == false) { Reports.Add(new AiReport(Severity.Info, "Can not compute difficulty of empty beatmap.")); return false; } tpHitObject CurrentHitObject = HitObjectsEnumerator.Current; tpHitObject NextHitObject; // First hitObject starts at strain 1. 1 is the default for strain values, so we don't need to set it here. See tpHitObject. while (HitObjectsEnumerator.MoveNext()) { NextHitObject = HitObjectsEnumerator.Current; NextHitObject.CalculateStrains(CurrentHitObject); CurrentHitObject = NextHitObject; } return true; } // In milliseconds. For difficulty calculation we will only look at the highest strain value in each time interval of size STRAIN_STEP. // This is to eliminate higher influence of stream over aim by simply having more HitObjects with high strain. // The higher this value, the less strains there will be, indirectly giving long beatmaps an advantage. private const double STRAIN_STEP = 400; // The weighting of each strain value decays to 0.9 * it's previous value private const double DECAY_WEIGHT = 0.9; private double CalculateDifficulty(DifficultyType Type) { // Find the highest strain value within each strain step List<double> HighestStrains = new List<double>(); double IntervalEndTime = STRAIN_STEP; double MaximumStrain = 0; // We need to keep track of the maximum strain in the current interval tpHitObject PreviousHitObject = null; foreach (tpHitObject hitObject in tpHitObjects) { // While we are beyond the current interval push the currently available maximum to our strain list while(hitObject.BaseHitObject.StartTime > IntervalEndTime) { HighestStrains.Add(MaximumStrain); // The maximum strain of the next interval is not zero by default! We need to take the last hitObject we encountered, take its strain and apply the decay // until the beginning of the next interval. if(PreviousHitObject == null) { MaximumStrain = 0; } else { double Decay = Math.Pow(tpHitObject.DECAY_BASE[(int)Type], (double)(IntervalEndTime - PreviousHitObject.BaseHitObject.StartTime) / 1000); MaximumStrain = PreviousHitObject.Strains[(int)Type] * Decay; } // Go to the next time interval IntervalEndTime += STRAIN_STEP; } // Obtain maximum strain if (hitObject.Strains[(int)Type] > MaximumStrain) { MaximumStrain = hitObject.Strains[(int)Type]; } PreviousHitObject = hitObject; } // Build the weighted sum over the highest strains for each interval double Difficulty = 0; double Weight = 1; HighestStrains.Sort((a,b) => b.CompareTo(a)); // Sort from highest to lowest strain. foreach(double Strain in HighestStrains) { Difficulty += Weight * Strain; Weight *= DECAY_WEIGHT; } return Difficulty; } } }
unlicense
TheCherno/EventSystem
src/com/thecherno/app/core/Window.java
2308
package com.thecherno.app.core; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.SwingUtilities; import com.thecherno.app.events.Event; import com.thecherno.app.events.types.MouseMovedEvent; import com.thecherno.app.events.types.MousePressedEvent; import com.thecherno.app.events.types.MouseReleasedEvent; import com.thecherno.app.layers.Layer; @SuppressWarnings("serial") public class Window extends JFrame { private Screen screen; private List<Layer> layerStack = new ArrayList<Layer>(); public Window(String name, int width, int height) { screen = new Screen(width, height); setTitle(name); add(screen); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); screen.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { MouseReleasedEvent event = new MouseReleasedEvent(e.getButton(), e.getX(), e.getY()); onEvent(event); } public void mousePressed(MouseEvent e) { MousePressedEvent event = new MousePressedEvent(e.getButton(), e.getX(), e.getY()); onEvent(event); } }); screen.addMouseMotionListener(new MouseMotionListener() { public void mouseMoved(MouseEvent e) { MouseMovedEvent event = new MouseMovedEvent(e.getX(), e.getY(), false); onEvent(event); } public void mouseDragged(MouseEvent e) { MouseMovedEvent event = new MouseMovedEvent(e.getX(), e.getY(), true); onEvent(event); } }); screen.init(); run(); } private void run() { screen.beginRendering(); screen.clear(); onRender(screen.getGraphicsObject()); screen.endRendering(); try { Thread.sleep(3); } catch (InterruptedException e) { } SwingUtilities.invokeLater(() -> run()); } public void onEvent(Event event) { for (int i = layerStack.size() - 1; i >= 0; i--) layerStack.get(i).onEvent(event); } private void onRender(Graphics g) { for (int i = 0; i < layerStack.size(); i++) layerStack.get(i).onRender(g); } public void addLayer(Layer layer) { System.out.println(layer); layerStack.add(layer); } }
unlicense
srdjan-bozovic/kursnalista
universal/src/MSC/MSC.Universal.Shared/Implementation/LocalStorageCacheService.cs
9811
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Windows.Storage; using MSC.Universal.Shared.Contracts.Services; using Newtonsoft.Json; namespace MSC.Universal.Shared.Implementation { public class LocalStorageCacheService : ICacheService, IDisposable { private const char FileNameSeparator = '»'; private readonly IDataContext _cacheContext; private readonly List<string> _files; private IStorageFolder _root; private static object Sync = new object(); public LocalStorageCacheService(IDataContext cacheContext) { _cacheContext = cacheContext; _cacheContext.ContextChanged += ContextChanged; _files = new List<string>(); } #region EnsureRoot public void Dispose() { _cacheContext.ContextChanged -= ContextChanged; } private async void ContextChanged(object sender, EventArgs e) { if (_root != null && _cacheContext.Context != _root.Name) { await InitializeRootAsync().ConfigureAwait(false); } } private async Task EnsureRootAsync() { if (_root != null) return; await InitializeRootAsync().ConfigureAwait(false); } private async Task InitializeRootAsync() { var localFolder = ApplicationData.Current.LocalFolder; var folders = await localFolder.GetFoldersAsync().AsTask().ConfigureAwait(false); if (_root != null) { var previousRoot = folders.FirstOrDefault(f => f.Name == _root.Name); if (previousRoot != null) await previousRoot.DeleteAsync().AsTask().ConfigureAwait(false); } _root = folders.FirstOrDefault(f => f.Name == _cacheContext.Context); if (_root == null) { _root = await localFolder.CreateFolderAsync(_cacheContext.Context).AsTask().ConfigureAwait(false); } var files = (await _root.GetFilesAsync().AsTask().ConfigureAwait(false)) .Select(f => f.Name); var expired = new List<string>(); lock (Sync) { _files.Clear(); foreach (var file in files) { if (IsExpired(file)) { expired.Add(file); } else { _files.Add(file); } } } // ReSharper disable once CSharpWarnings::CS4014, no need to wait storage operation RemoveFilesAsync(expired); } #endregion public async Task<bool> ExistsAsync<T>(string key) { try { await EnsureRootAsync().ConfigureAwait(false); return FindFileName<T>(key) != null; } catch { return false; } } private string FindFileName<T>(string key) { return FindFileName( f => f.StartsWith(string.Format("{2}{0}{1}{0}", FileNameSeparator, key, typeof(T).Name)) ); } private string FindFileName<T>(string key, DateTime updatedTime) { return FindFileName( f => f.StartsWith(string.Format("{2}{0}{1}{0}{3}{0}", FileNameSeparator, key, typeof (T).Name, updatedTime.Ticks)) ); } private string FindFileName(Func<string, bool> query) { lock (Sync) { var results = _files .Where(query) .OrderByDescending(f => f); if (results.Any()) return results.First(); return null; } } public Task PutAsync<T>(string key, T value, DateTime staleTime, DateTime expirationTime) { return PutAsync(key, DateTime.MinValue, value, staleTime, expirationTime); } public async Task PutAsync<T>(string key, DateTime updatedTime, T value, DateTime staleTime, DateTime expirationTime) { try { await EnsureRootAsync().ConfigureAwait(false); await RemoveAsync<T>(key).ConfigureAwait(false); var fileName = string.Format("{2}{0}{1}{0}{3}{0}{4}{0}{5}{0}.txt", FileNameSeparator, key, value.GetType().Name, updatedTime.Ticks, staleTime.Ticks, expirationTime.Ticks); var storageFile = await _root.CreateFileAsync( fileName, CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false); var json = JsonConvert.SerializeObject(value); using (var writer = new StreamWriter(await storageFile.OpenStreamForWriteAsync().ConfigureAwait(false))) { await writer.WriteAsync(json).ConfigureAwait(false); } lock (Sync) { _files.Add(storageFile.Name); } } // ReSharper disable once EmptyGeneralCatchClause catch { } } public Task UpdateAsync<T>(string key, T value) { return UpdateAsync(() => FindFileName<T>(key), value); } public Task UpdateAsync<T>(string key, DateTime updatedTime, T value) { return UpdateAsync(() => FindFileName<T>(key, updatedTime), value); } private async Task UpdateAsync<T>(Func<string> findFileFunc, T value) { try { await EnsureRootAsync().ConfigureAwait(false); var fileName = findFileFunc(); if (!string.IsNullOrEmpty(fileName)) { var storageFile = await _root.CreateFileAsync( fileName, CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false); var json = JsonConvert.SerializeObject(value); using ( var writer = new StreamWriter(await storageFile.OpenStreamForWriteAsync().ConfigureAwait(false)) ) { await writer.WriteAsync(json).ConfigureAwait(false); } } } // ReSharper disable once EmptyGeneralCatchClause catch { } } public Task<ICacheItem<T>> GetAsync<T>(string key) { return GetAsync<T>(() => FindFileName<T>(key)); } public Task<ICacheItem<T>> GetAsync<T>(string key, DateTime updatedTime) { return GetAsync<T>(() => FindFileName<T>(key, updatedTime)); } private async Task<ICacheItem<T>> GetAsync<T>(Func<string> findFileFunc) { try { await EnsureRootAsync().ConfigureAwait(false); var fileName = findFileFunc(); if (string.IsNullOrEmpty(fileName)) return new CacheItem<T>(); var file = await _root.GetFileAsync(fileName).AsTask().ConfigureAwait(false); string json; using (var reader = new StreamReader(await file.OpenStreamForReadAsync().ConfigureAwait(false))) { json = await reader.ReadToEndAsync().ConfigureAwait(false); } var meta = fileName.Split(FileNameSeparator); return new CacheItem<T>( JsonConvert.DeserializeObject<T>(json), new DateTime(long.Parse(meta[2])), new DateTime(long.Parse(meta[3])), new DateTime(long.Parse(meta[4])) ); } catch { return new CacheItem<T>(); } } public async Task CleanExpiredAsync() { IEnumerable<string> filesToRemove; lock (Sync) { filesToRemove = _files.Where(IsExpired).ToArray(); } await RemoveFilesAsync(filesToRemove).ConfigureAwait(false); } private static bool IsExpired(string file) { var meta = file.Split(FileNameSeparator); return DateTime.Now > new DateTime(long.Parse(meta[4])); } public async Task RemoveAsync<T>(string key) { IEnumerable<string> filesToRemove; lock (Sync) { filesToRemove = _files.Where(f => f.StartsWith(string.Format("{2}{0}{1}{0}", FileNameSeparator, key, typeof(T).Name))).ToArray(); } await RemoveFilesAsync(filesToRemove).ConfigureAwait(false); } private async Task RemoveFilesAsync(IEnumerable<string> filesToRemove) { foreach (var file in filesToRemove) { var storedFile = await _root.GetFileAsync(file).AsTask().ConfigureAwait(false); await storedFile.DeleteAsync().AsTask().ConfigureAwait(false); lock (Sync) { _files.Remove(file); } } } } }
unlicense
will-gilbert/SmartGWT-Mobile
mobile/src/main/java/com/smartgwt/mobile/client/widgets/events/HasPercentChangedHandlers.java
1283
/* * Smart GWT (GWT for SmartClient) * Copyright 2008 and beyond, Isomorphic Software, Inc. * * Smart GWT is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. Smart GWT is also * available under typical commercial license terms - see * http://smartclient.com/license * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package com.smartgwt.mobile.client.widgets.events; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.HasHandlers; public interface HasPercentChangedHandlers extends HasHandlers { /** * This method is called when the percentDone value changes. Observe this method to be notified upon a change to the * percentDone value. * * @param handler the percentChanged handler * @return {@link com.google.gwt.event.shared.HandlerRegistration} used to remove this handler */ HandlerRegistration addPercentChangedHandler(PercentChangedHandler handler); }
unlicense
Trickness/pl_learning
Algorithms/cpp/linked_list/double_linked_list.hpp
10110
#ifndef SWZ_LINKED_LIST #define SWZ_LINKED_LIST namespace{ #include <iostream> } template<typename T> class double_linked_list_node{ public: explicit double_linked_list_node(T* value); explicit double_linked_list_node(T value); ~double_linked_list_node() = default; T* key; double_linked_list_node *prev; double_linked_list_node *next; double_linked_list_node *&right = next; double_linked_list_node *&left = prev; }; template<typename T> class double_linked_list{ public: double_linked_list(void); ~double_linked_list(void); const size_t& len(void); void list_insert(double_linked_list_node<T>* x); void list_insert(T* value); void list_insert(T value); void list_insert(double_linked_list<T> &list); void list_insert_left(double_linked_list_node<T>* f,double_linked_list_node<T>* x); void list_insert_left(double_linked_list_node<T>* f,T* value); void list_insert_left(double_linked_list_node<T>* f,T value); void list_insert_left(double_linked_list_node<T>* f,double_linked_list<T> &list); void list_insert_right(double_linked_list_node<T> *f,double_linked_list_node<T>* x); void list_insert_right(double_linked_list_node<T> *f,T* value); void list_insert_right(double_linked_list_node<T> *f,T value); void list_insert_right(double_linked_list_node<T> *f,double_linked_list<T> &list); double_linked_list_node<T>* list_search(T *k); double_linked_list_node<T>* list_search(T k); double_linked_list_node<T>* list_search(double_linked_list_node<T> *k); double_linked_list_node<T>* list_head(void); bool list_delete(double_linked_list_node<T>* x); bool list_delete(T* value); bool list_delete(T value); void list_clear(void); // It maybe cause memory leaking.... void list_destroy(void); void list_print(void); protected: size_t length; double_linked_list_node<T> *head; }; template<typename T> double_linked_list_node<T>::double_linked_list_node(T *value) :key(value),prev(nullptr),next(nullptr){ } template<typename T> double_linked_list_node<T>::double_linked_list_node(T value) :prev(nullptr),next(nullptr){ this->key = new T(value); } template<typename T> double_linked_list<T>::double_linked_list(void){ this->head = nullptr; this->length = 0; } template<typename T> double_linked_list<T>::~double_linked_list(void){ this->list_destroy(); } template<typename T> inline double_linked_list_node<T>* double_linked_list<T>::list_head(void){ return this->head; } template<typename T> inline void double_linked_list<T>::list_clear(void){ this->length = 0; this->head = nullptr; } template<typename T> void double_linked_list<T>::list_destroy(void){ if(this->length == 0) return; double_linked_list_node<T>* curr = nullptr; double_linked_list_node<T>* x = this->head; size_t len = this->length; this->list_clear(); for(int i=0;i<len;++i){ curr = x; x = curr->next; delete curr; } x = nullptr; curr = nullptr; } template<typename T> inline const size_t& double_linked_list<T>::len(void){ return this->length; } template<typename T> void double_linked_list<T>::list_insert_left(double_linked_list_node<T>* fiducial_node, double_linked_list_node<T>* x){ if(this->head == nullptr){ this->head = x; x->prev = x; x->next = x; this->length = 1; return; } if(fiducial_node == nullptr){ auto y = this->head->left; x->left = y; x->right = this->head; this->head->left = x; y->right = x; }else{ if(!this->list_search(fiducial_node)) return; auto y = fiducial_node->left; x->left = y; x->right = fiducial_node; fiducial_node->left = x; y->right = x; } ++this->length; return; } template<typename T> inline void double_linked_list<T>::list_insert_left(double_linked_list_node<T>* fiducial_node, T *value){ auto x = new double_linked_list_node<T>(value); return this->list_insert_left(fiducial_node,x); } template<typename T> inline void double_linked_list<T>::list_insert_left(double_linked_list_node<T>* fiducial_node, T value){ auto x = new double_linked_list_node<T>(value); return this->list_insert_left(fiducial_node,x); } template<typename T> void double_linked_list<T>::list_insert_left(double_linked_list_node<T>* f, double_linked_list<T> &list){ if(list.len() == 0) return; auto x = list.list_head(); if(this->length == 0){ this->head = x; this->length = list.len(); list.list_clear(); return; } auto t = f; if(f == nullptr) t = this->head; else if(!this->list_search(f)) return; this->length += list.len(); list.list_clear(); auto y = t->left; auto z = x->right; y->right = z; z->left = y; x->right = t; t->left = x; } template<typename T> void double_linked_list<T>::list_insert_right(double_linked_list_node<T>* f, double_linked_list<T> &list){ if(list.len() == 0) return; auto x = list.list_head(); if(this->length == 0){ this->head = x; this->length = list.len(); list.clear(); return; } auto t = f; if(f == nullptr) t = this->head; else if(!this->list_search(f)) return; this->length += list.len(); list.list_clear(); auto y = t->right; auto z = x->right; y->left = x; z->left = t; x->right = y; t->right = z; } template<typename T> void double_linked_list<T>::list_insert_right(double_linked_list_node<T>* fiducial_node, double_linked_list_node<T>* x){ if(this->head == nullptr){ this->head = x; x->prev = x; x->next = x; this->length = 1; return; } if(fiducial_node == nullptr){ auto y = this->head->right; x->right = y; x->left = this->head; this->head->right = x; y->left = x; }else{ if(!this->list_search(fiducial_node)) return; auto y = fiducial_node->right; x->right = y; x->left = fiducial_node; fiducial_node->right = x; y->left = x; } ++this->length; return; } template<typename T> inline void double_linked_list<T>::list_insert_right(double_linked_list_node<T>* fiducial_node, T *value){ auto x = new double_linked_list_node<T>(value); return this->list_insert_right(fiducial_node,x); } template<typename T> inline void double_linked_list<T>::list_insert_right(double_linked_list_node<T>* fiducial_node, T value){ auto x = new double_linked_list_node<T>(value); return this->list_insert_right(fiducial_node,x); } template<typename T> inline void double_linked_list<T>::list_insert(double_linked_list_node<T>* x){ this->list_insert_left(nullptr,x); } template<typename T> inline void double_linked_list<T>::list_insert(T* value){ auto x = new double_linked_list_node<T>(value); return this->list_insert(x); } template<typename T> inline void double_linked_list<T>::list_insert(T value){ auto x = new double_linked_list_node<T>(value); return this->list_insert(x); } template<typename T> void double_linked_list<T>::list_insert(double_linked_list<T> &list){ if(list.len() == 0) return; auto x = list.list_head(); if(this->length == 0){ this->head = x; }else{ auto n = this->head->next; auto p = x->prev; this->head->next = p; p->prev = this->head; n->prev = x; x->next = n; } this->length += list.len(); list.list_clear(); } template<typename T> double_linked_list_node<T>* double_linked_list<T>::list_search(T* value){ if(value == nullptr) return nullptr; if(this->head->key == value) return this->head; for(auto x=this->head->next;x!=this->head;x=x->next) if(x->key == value) return x; return nullptr; } template<typename T> double_linked_list_node<T>* double_linked_list<T>::list_search(T value){ if(*(this->head->key) == value) return this->head; for(auto x=this->head->next;x!=this->head;x=x->next) if(*(x->key) == value) return x; return nullptr; } template<typename T> double_linked_list_node<T>* double_linked_list<T>::list_search(double_linked_list_node<T>*value){ if(value == nullptr) return nullptr; if(this->head == value) return this->head; for(auto x=this->head->next;x!=this->head;x=x->next) if(x == value) return x; return nullptr; } template<typename T> bool double_linked_list<T>::list_delete(double_linked_list_node<T> *x){ if(this->length == 0) return false; if(this->list_search(x)){ if(x == this->head) this->head = x->next; if(this->length == 1) this->head = nullptr; x->next->prev = x->prev; x->prev->next = x->next; delete x; --this->length; return true; } return false; } template<typename T> inline bool double_linked_list<T>::list_delete(T *value){ return this->list_delete(this->list_search(value)); } template<typename T> inline bool double_linked_list<T>::list_delete(T value){ return this->list_delete(this->list_search(value)); } template<typename T> void double_linked_list<T>::list_print(void){ auto x=this->head; std::cout << "----LIST_PRINT_START----" << std::endl; std::cout << "List has " << this->length << " members" << std::endl; for(int i=0;i<this->length;++i){ std::cout << "Number: "<< i << " : " << *(x->key) << std::endl; x = x->next; } std::cout << "----LIST_PRINT_END------" << std::endl; } #endif
unlicense
qyp2009/Aiqipa
src/com/example/aiqipa/NewsDetailActivity.java
778
package com.example.aiqipa; import com.example.aiqipa.application.PublicVars; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class NewsDetailActivity extends Activity{ private String articleID =""; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_news_detail); this.loadInitParams(); WebView webView = (WebView) this.findViewById(R.id.webView_newsDetail); webView.loadUrl(PublicVars.NEWS_ARTICLE_URL+PublicVars.DEFAULT_NEWS_ARTICLE_ID); } private void loadInitParams(){ Bundle bundle = this.getIntent().getExtras(); this.articleID = bundle.getString(PublicVars.NEWS_ARTICLE_ID); } }
unlicense
davidmerfield/Typeset.js
src/punctuation.js
492
module.exports = (text) => { // Dashes text = text.replace(/--/g, "–"); text = text.replace(/ – /g, "&thinsp;&mdash;&thinsp;"); // Elipses text = text.replace(/\.\.\./g, "…"); // Nbsp for punc with spaces const NBSP = "&nbsp;"; const NBSP_PUNCTUATION_START = /([«¿¡]) /g; const NBSP_PUNCTUATION_END = / ([\!\?:;\.,‽»])/g; text = text.replace(NBSP_PUNCTUATION_START, "$1" + NBSP); text = text.replace(NBSP_PUNCTUATION_END, NBSP + "$1"); return text; };
unlicense
Krusen/ErgastApi.Net
src/ErgastApi/Requests/Rounds.cs
653
namespace ErgastApi.Requests { // TODO: Move to Ids namespace together with Drivers, Circuits etc.? Or the other way around? /// <summary> /// Constants for querying relative rounds, e.g. last round. /// </summary> public static class Rounds { /// <summary> /// This is the same as not specifying a round. /// </summary> public const string All = null; /// <summary> /// The last round. /// </summary> public const string Last = "last"; /// <summary> /// The next round. /// </summary> public const string Next = "next"; } }
unlicense
StyxOfDynamite/zod-interview
Gulpfile.js
339
var gulp = require('gulp') var watch = require('gulp-watch') var phplint = require('phplint').lint gulp.task('phplint', function (cb) { phplint(['app/**/*.php', 'database/**/*.php'], {limit: 10}, function (err, stdout, stderr) { if (err) { cb(err) process.exit(1) } cb() }) }) gulp.task('test', ['phplint'])
unlicense
inri13666/google-api-php-client-v2
libs/Google/Service/Directory/Notifications.php
1111
<?php namespace Google\Service\Directory; class Notifications extends \Google\Collection { public $etag; protected $itemsType = 'Google\Service\Directory\Notification'; protected $itemsDataType = 'array'; public $kind; public $nextPageToken; public $unreadNotificationsCount; public function setEtag($etag) { $this->etag = $etag; } public function getEtag() { return $this->etag; } public function setItems($items) { $this->items = $items; } public function getItems() { return $this->items; } public function setKind($kind) { $this->kind = $kind; } public function getKind() { return $this->kind; } public function setNextPageToken($nextPageToken) { $this->nextPageToken = $nextPageToken; } public function getNextPageToken() { return $this->nextPageToken; } public function setUnreadNotificationsCount($unreadNotificationsCount) { $this->unreadNotificationsCount = $unreadNotificationsCount; } public function getUnreadNotificationsCount() { return $this->unreadNotificationsCount; } }
unlicense
GoldenR1618/SoftUni-Exercises-and-Exams
07.C#_OOP_Advanced/10.EXAM_PREPARATION_1/Recycling Station_Авторско Решение/RecyclingStation/Models/Waste/StorableGarbage.cs
280
namespace RecyclingStation.Models.Waste { using RecyclingStation.Attributes; [Storable] public class StorableGarbage : Garbage { public StorableGarbage(string name, double weight, double volume) : base(name, weight, volume) { } } }
unlicense
syncxplus/php
src/app/Index.php
169
<?php namespace app; use app\common\AppBase; class Index extends AppBase { function get() { echo \Template::instance()->render('index.html'); } }
unlicense
indy256/codelibrary
cpp/strings/kmp.cpp
917
#include <bits/stdc++.h> using namespace std; // https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm vector<int> prefix_function(string s) { vector<int> p(s.length()); int k = 0; for (int i = 1; i < s.length(); i++) { while (k > 0 && s[k] != s[i]) k = p[k - 1]; if (s[k] == s[i]) ++k; p[i] = k; } return p; } int find_substring(string haystack, string needle) { int m = needle.length(); if (m == 0) return 0; vector<int> p = prefix_function(needle); for (int i = 0, k = 0; i < haystack.length(); i++) { while (k > 0 && needle[k] != haystack[i]) k = p[k - 1]; if (needle[k] == haystack[i]) ++k; if (k == m) return i + 1 - m; } return -1; } // usage example int main() { int pos = find_substring("acabc", "ab"); cout << pos << endl; }
unlicense
mmozeiko/RcloneBrowser
src/icon_cache.cpp
1526
#include "icon_cache.h" #include "item_model.h" #if defined(Q_OS_OSX) #include "osx_helper.h" #endif IconCache::IconCache(QObject* parent) : QObject(parent) { mFileIcon = QFileIconProvider().icon(QFileIconProvider::File); #ifdef Q_OS_WIN32 CoInitializeEx(NULL, COINIT_MULTITHREADED); #endif mThread.start(); moveToThread(&mThread); } IconCache::~IconCache() { mThread.quit(); mThread.wait(); #ifdef Q_OS_WIN32 CoUninitialize(); #endif } void IconCache::getIcon(Item* item, const QPersistentModelIndex& parent) { QString ext = QFileInfo(item->name).suffix(); QIcon icon; auto it = mIcons.find(ext); if (it == mIcons.end()) { #if defined(Q_OS_WIN32) SHFILEINFOW info; if (SHGetFileInfoW(reinterpret_cast<LPCWSTR>(("dummy." + ext).utf16()), FILE_ATTRIBUTE_NORMAL, &info, sizeof(info), SHGFI_ICON | SHGFI_USEFILEATTRIBUTES) && info.hIcon) { icon = QtWin::fromHICON(info.hIcon); DestroyIcon(info.hIcon); } #elif defined(Q_OS_OSX) icon = osxGetIcon(ext.toUtf8().constData()); #else QMimeType mime = mMimeDatabase.mimeTypeForFile(item->name, QMimeDatabase::MatchExtension); if (mime.isValid()) { icon = QIcon::fromTheme(mime.iconName()); } #endif if (icon.isNull()) { icon = mFileIcon; } mIcons.insert(ext, icon); } else { icon = it.value(); } emit iconReady(item, parent, icon); }
unlicense
CppGoneWild/TileGame
src/tool/tcp/Server.cpp
7951
#include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #include "../logg/Stream.hh" #include "Exception.hh" #include "Server.hh" #include "priv/send_recv.hh" struct sockaddr_storage no_addr; class NoAddrInitialiser { private: NoAddrInitialiser() { memset(&no_addr, 0, sizeof(no_addr)); } static const NoAddrInitialiser self; }; NoAddrInitialiser const NoAddrInitialiser::self; /* _____ ____ * / ___/___ ______ _____ ______ _ / __ \___ ___ _____ * \__ \/ _ \/ ___/ | / / _ \/ ___(_|_) /_/ / _ \/ _ \/ ___/ * ___/ / __/ / | |/ / __/ / _ _ / ____/ __/ __/ / * /____/\___/_/ |___/\___/_/ (_|_)_/ \___/\___/_/ */ tcp::Server::Peer::Peer(int fd, struct sockaddr_storage const & paddr, bool w) : fd(fd), wait_on(w), ack_packets() { memcpy(&addr, &paddr, sizeof(addr)); } tcp::Server::Peer::Peer(tcp::Server::Peer && other) : fd(other.fd), wait_on(other.wait_on), ack_packets(std::move(other.ack_packets)) { memcpy(&addr, &(other.addr), sizeof(addr)); } tcp::Server::Peer & tcp::Server::Peer::operator=(tcp::Server::Peer && other) { fd = other.fd; memcpy(&addr, &(other.addr), sizeof(addr)); wait_on = other.wait_on; ack_packets = std::move(other.ack_packets); return (*this); } tcp::Server::Peer & tcp::Server::Peer::operator=(struct sockaddr_storage const & paddr) { memcpy(&addr, &paddr, sizeof(addr)); return (*this); } /* _____ * / ___/___ ______ _____ _____ * \__ \/ _ \/ ___/ | / / _ \/ ___/ * ___/ / __/ / | |/ / __/ / * /____/\___/_/ |___/\___/_/ */ tcp::Server::Server() : listenPort(-1), listenSocket(-1), peers() { memset(&listenAddr, 0, sizeof(listenAddr)); } tcp::Server::Server(short port) : listenPort(port), listenSocket(-1), peers() { launch(port); } tcp::Server::~Server() { closeAllSocket(); } /** * @todo leak near freeaddrinfo */ void tcp::Server::launch(short port) { // LOG(logg::cout) << "Server launching on port : " << listenPort; if (listenSocket != -1) throw tcp::Exception("Already listening"); listenPort = port; // getaddrinfo struct addrinfo hints, *res; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; // use IPv4 or IPv6, whichever hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // fill in my IP for me if (::getaddrinfo(NULL, std::to_string(listenPort).c_str(), &hints, &res) != 0) throw tcp::Exception(std::string("getaddrinfo:") + strerror(errno)); memcpy(&listenAddr, res, sizeof(listenAddr)); ::freeaddrinfo(res); // create socket listenSocket = ::socket(listenAddr.ai_family, listenAddr.ai_socktype, listenAddr.ai_protocol); if (listenSocket == -1) throw tcp::Exception(std::string("socket:") + strerror(errno)); // SO_REUSEADDR int yes=1; if (::setsockopt(listenSocket,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof yes) == -1) throw tcp::Exception(std::string("setsockopt(SO_REUSEADDR):") + strerror(errno)); // Bind if (::bind(listenSocket, listenAddr.ai_addr, listenAddr.ai_addrlen) != 0) throw tcp::Exception(std::string("bind:") + strerror(errno)); // listen if (::listen(listenSocket, 50) == -1) throw tcp::Exception(std::string("listen:") + strerror(errno)); // LOG(logg::cout) << "Server launched"; } void tcp::Server::waitForData(std::vector<tcp::Peer> & newPeers, std::vector<tcp::Peer> & readPeers, int u_sec) { // LOG(logg::cout) << "Will wait : " << u_sec; struct timeval tv; memset(&tv, 0, sizeof(tv)); tv.tv_usec = u_sec; int fdmax = 0; fd_set readfds; FD_ZERO(&readfds); if (listenSocket != -1) { FD_SET(listenSocket, &readfds); fdmax = listenSocket; } for (auto i = peers.begin(); i != peers.end(); i++) if (i->fd != -1 && i->wait_on) { FD_SET(i->fd, &readfds); fdmax = std::max(fdmax, i->fd); } if (::select(fdmax + 1, &readfds, NULL, NULL, (u_sec >= 0) ? (&tv) : (NULL)) == -1) throw tcp::Exception(std::string("select:") + strerror(errno)); if (listenSocket != -1 && FD_ISSET(listenSocket, &readfds)) { bool do_more_accept = true; while (do_more_accept) { struct sockaddr_storage their_addr; socklen_t addr_size = sizeof(their_addr); int new_fd = ::accept(listenSocket, (struct sockaddr *)&their_addr, &addr_size); if (new_fd == -1) throw tcp::Exception(std::string("accept:") + strerror(errno)); peers.emplace_back(new_fd, their_addr, true); newPeers.emplace_back(peers.back(), *this); LOG_INFO(logg::cout) << "Accepted new peer connectionm the new fd is : " << new_fd; struct timeval listenTv; memset(&listenTv, 0, sizeof(listenTv)); fd_set listenfds; FD_ZERO(&listenfds); FD_SET(listenSocket, &listenfds); if (::select(listenSocket + 1, &listenfds, NULL, NULL, &listenTv) == -1) throw tcp::Exception(std::string("select:") + strerror(errno)); do_more_accept = FD_ISSET(listenSocket, &listenfds); } } for (auto i = peers.begin(); i != peers.end(); i++) if (i->fd != -1 && i->wait_on && FD_ISSET(i->fd, &readfds)) readPeers.emplace_back(*i, *this); } void tcp::Server::closeListenSocket() { if (listenSocket != -1) ::close(listenSocket); memset(&listenAddr, 0, sizeof(listenAddr)); } void tcp::Server::closeAllPeerSocket() { for (auto i = peers.begin(); i != peers.end(); i++) ::close(i->fd); peers.clear(); } void tcp::Server::closeAllSocket() { closeListenSocket(); closeAllPeerSocket(); } void tcp::Server::close(tcp::Server::Peer & peer) { auto it = peers.begin(); while (it != peers.end()) { if (it->fd == peer.fd) { ::close(it->fd); peers.erase(it); return ; } it++; } } /* ____ * / __ \___ ___ _____ * / /_/ / _ \/ _ \/ ___/ * / ____/ __/ __/ / * /_/ \___/\___/_/ */ tcp::Peer::Peer(tcp::Server::Peer & peer, tcp::Server & server) : peer(peer), server(server) {} tcp::Peer::~Peer() {} bool tcp::Peer::operator==(tcp::Peer const & other) const { return (peer.fd == other.peer.fd); } bool tcp::Peer::operator!=(tcp::Peer const & other) const { return (peer.fd != other.peer.fd); } void tcp::Peer::send(tcp::Packet & packet) { if (packet.isAcknowledge() && packet.id == 0) // will wait an answer { peer.ack_packets.emplace_back(std::move(packet)); tcp::Packet & p = peer.ack_packets.back(); p.id = tcp::Packet::generateId(); tcp::Packet::Id id = p.id; tcp::priv::send(peer.fd, (const char *)(&id), sizeof(id)); tcp::priv::send(peer.fd, p.buffer); } else // will not wait an answer or is an ack { tcp::Packet::Id id = packet.id * -1; tcp::priv::send(peer.fd, (char *)(&id), sizeof(id)); tcp::priv::send(peer.fd, packet.buffer); } } bool tcp::Peer::recv(tcp::Packet & packet) { packet.getBuffer().clear(); tcp::Packet::Id id; tcp::priv::recv(peer.fd, (char *)(&id), sizeof(id)); if (id >= 0) // Simple or will need ack { packet.id = id; tcp::priv::recv(peer.fd, packet.buffer); if (id == 0) packet.ack_callback = nullptr; else { packet.ack_callback = std::bind(&tcp::Peer::send, this, std::placeholders::_1); packet.awaiting_answer = true; } return (true); } // is an actual ack id *= -1; tcp::Packet ack; bool found = false; auto i = peer.ack_packets.begin(); while (i != peer.ack_packets.end()) if (id == i->getId()) { ack = std::move(*i); peer.ack_packets.erase(i); found = true; break ; } else i++; if (found) { LOG_TRACE(logg::cout) << "Acknwoledgement for id : " << id; tcp::priv::recv(peer.fd, ack.getBuffer()); ack.acknowledge(); } else throw tcp::Exception(std::string("Client:Recv an unknow Acknwoledgement.")); return (found); } bool tcp::Peer::isWaitingOn() const { return (peer.wait_on); } void tcp::Peer::waitOn(bool yes) { peer.wait_on = yes; } void tcp::Peer::close() { server.close(peer); } struct sockaddr_storage const & tcp::Peer::getAddr() const { return (peer.addr); }
unlicense
seckcoder/lang-learn
python/celery_user/test.py
308
from proj.tasks import add from datetime import datetime, timedelta #res = add.delay(4, 4) res = add.apply_async(args=[4], countdown=1) print res.get() next_time = datetime.utcnow() + timedelta(seconds=3) print next_time print datetime.now() res = add.apply_async(args=[3, 5], eta=next_time) print res.get()
unlicense
JoshuaKennedy/jccc_cs235
mcm10.06b/mcm10.06b/main.cpp
4361
// ************************************************************* // // NextMonth.cpp // // This program defines and tests a class named Month. // The class has one member variable (an integer) to represent // the month. It has a constructor to set the month using an // integer argument (1 for January, 2 for February, and so // forth), a default constructor that sets the month to 1 // (January), an output function that outputs the month as an // integer, an output function that outputs the month as the // first three letters in the name of the month, and a member // function that returns the next month. // // ************************************************************* #include <iostream> using namespace std; // // Definition of the Month class // class Month { public: Month (int monthNum); // Precondition: The parameter monthNum contains a valid // month number (1 - 12) // Postcondition: The member variable month has been set to // the value of the parameter monthNum. Month(); // Sets the member variable month to 1 (defaults to January). void outputMonthNumber(); // Postcondition: The member variable month has been output // to the screen if it is valid; otherwise a "not valid" // message is printed. void outputMonthLetters(); // Postcondition: The first three letters of the name of the // month has been output to the screen if the month is // valid (1 - 12); otherwise a message indicating the month // is not valid is output. Month nextMonth(); // Precondition: The month is defined and valid. // Returns the next month as an object of type Month. private: int month; }; int main () { // // Variable declarations // int monthNum; char letter1, letter2, letter3; // first 3 letters of a month char testAgain; // y or n - loop control // // Loop to test the next month function // do { cout << endl; cout << "Enter a month number: "; cin >> monthNum; Month testMonth(monthNum); cout << endl; cout << "This month ..." << endl; testMonth.outputMonthNumber(); testMonth.outputMonthLetters(); Month next = testMonth.nextMonth(); cout << endl; cout << "Next month ..." << endl; next.outputMonthNumber(); next.outputMonthLetters(); // // See if user wants to try another month // cout << endl; cout << "Do you want to test again? (y or n) "; cin >> testAgain; } while (testAgain == 'y' || testAgain == 'Y'); return 0; } Month::Month() { month = 1; } Month::Month (int monthNum) { month = monthNum; } void Month::outputMonthNumber() { if (month >= 1 && month <= 12) cout << "Month: " << month << endl; else cout << "Error - The month is not a valid!" << endl; } void Month::outputMonthLetters() { switch (month) { case 1: cout << "Jan" << endl; break; case 2: cout << "Feb" << endl; break; case 3: cout << "Mar" << endl; break; case 4: cout << "Apr" << endl; break; case 5: cout << "May" << endl; break; case 6: cout << "Jun" << endl; break; case 7: cout << "Jul" << endl; break; case 8: cout << "Aug" << endl; break; case 9: cout << "Sep" << endl; break; case 10: cout << "Oct" << endl; break; case 11: cout << "Nov" << endl; break; case 12: cout << "Dec" << endl; break; default: cout << "Error - the month is not a valid!" << endl; } } // -------------------------------- // ----- ENTER YOUR CODE HERE ----- // -------------------------------- Month Month::nextMonth() { if (this->month == 12) return Month(1); else return Month(this->month + 1); } // -------------------------------- // --------- END USER CODE -------- // --------------------------------
unlicense
codeApeFromChina/resource
frame_packages/java_libs/hibernate-distribution-3.6.10.Final/project/hibernate-testsuite/src/test/java/org/hibernate/test/annotations/embeddables/nested/Customer.java
1986
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.annotations.embeddables.nested; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.util.ArrayList; import java.util.List; import org.hibernate.annotations.GenericGenerator; /** * @author Thomas Vanstals * @author Steve Ebersole */ @Entity public class Customer { private Long id; private List<Investment> investments = new ArrayList<Investment>(); @Id @GeneratedValue( generator="increment" ) @GenericGenerator( name = "increment", strategy = "increment" ) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ElementCollection(fetch = FetchType.EAGER) public List<Investment> getInvestments() { return investments; } public void setInvestments(List<Investment> investments) { this.investments = investments; } }
unlicense
jjeb/kettle-trunk
engine/src/org/pentaho/di/job/entries/ssh2get/JobEntrySSH2GET.java
42737
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.job.entries.ssh2get; import static org.pentaho.di.job.entry.validator.AndValidator.putValidators; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.integerValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator; import java.io.File; import java.io.FileOutputStream; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileType; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.Job; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.pentaho.di.resource.ResourceReference; import org.w3c.dom.Node; import com.trilead.ssh2.Connection; import com.trilead.ssh2.HTTPProxyData; import com.trilead.ssh2.KnownHosts; import com.trilead.ssh2.SFTPv3Client; import com.trilead.ssh2.SFTPv3DirectoryEntry; import com.trilead.ssh2.SFTPv3FileAttributes; import com.trilead.ssh2.SFTPv3FileHandle; /** * This defines a SSH2 GET job entry. * * @author Samatar * @since 17-12-2007 * */ public class JobEntrySSH2GET extends JobEntryBase implements Cloneable, JobEntryInterface { private static Class<?> PKG = JobEntrySSH2GET.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private String serverName; private String userName; private String password; private String serverPort; private String ftpDirectory; private String localDirectory; private String wildcard; private boolean onlyGettingNewFiles; /* Don't overwrite files */ private boolean usehttpproxy; private String httpProxyHost; private String httpproxyport; private String httpproxyusername; private String httpProxyPassword; private boolean publicpublickey; private String keyFilename; private String keyFilePass; private boolean useBasicAuthentication; private String afterFtpPut; private String destinationfolder; private boolean createdestinationfolder; private boolean cachehostkey; private int timeout; boolean createtargetfolder; boolean includeSubFolders; static KnownHosts database = new KnownHosts(); int nbfilestoget=0; int nbgot=0; int nbrerror=0; public JobEntrySSH2GET(String n) { super(n, ""); serverName=null; publicpublickey=false; keyFilename=null; keyFilePass=null; usehttpproxy=false; httpProxyHost=null; httpproxyport=null; httpproxyusername=null; httpProxyPassword=null; serverPort="22"; useBasicAuthentication=false; afterFtpPut="do_nothing"; destinationfolder=null; includeSubFolders=false; createdestinationfolder=false; createtargetfolder=false; cachehostkey=false; timeout=0; setID(-1L); } public JobEntrySSH2GET() { this(""); } public Object clone() { JobEntrySSH2GET je = (JobEntrySSH2GET) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer(128); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("servername", serverName)); retval.append(" ").append(XMLHandler.addTagValue("username", userName)); retval.append(" ").append(XMLHandler.addTagValue("password", Encr.encryptPasswordIfNotUsingVariables(getPassword()))); retval.append(" ").append(XMLHandler.addTagValue("serverport", serverPort)); retval.append(" ").append(XMLHandler.addTagValue("ftpdirectory", ftpDirectory)); retval.append(" ").append(XMLHandler.addTagValue("localdirectory", localDirectory)); retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard)); retval.append(" ").append(XMLHandler.addTagValue("only_new", onlyGettingNewFiles)); retval.append(" ").append(XMLHandler.addTagValue("usehttpproxy", usehttpproxy)); retval.append(" ").append(XMLHandler.addTagValue("httpproxyhost", httpProxyHost)); retval.append(" ").append(XMLHandler.addTagValue("httpproxyport", httpproxyport)); retval.append(" ").append(XMLHandler.addTagValue("httpproxyusername", httpproxyusername)); retval.append(" ").append(XMLHandler.addTagValue("httpproxypassword", httpProxyPassword)); retval.append(" ").append(XMLHandler.addTagValue("publicpublickey", publicpublickey)); retval.append(" ").append(XMLHandler.addTagValue("keyfilename", keyFilename)); retval.append(" ").append(XMLHandler.addTagValue("keyfilepass", keyFilePass)); retval.append(" ").append(XMLHandler.addTagValue("usebasicauthentication", useBasicAuthentication)); retval.append(" ").append(XMLHandler.addTagValue("afterftpput", afterFtpPut)); retval.append(" ").append(XMLHandler.addTagValue("destinationfolder", destinationfolder)); retval.append(" ").append(XMLHandler.addTagValue("createdestinationfolder", createdestinationfolder)); retval.append(" ").append(XMLHandler.addTagValue("cachehostkey", cachehostkey)); retval.append(" ").append(XMLHandler.addTagValue("timeout", timeout)); retval.append(" ").append(XMLHandler.addTagValue("createtargetfolder", createtargetfolder)); retval.append(" ").append(XMLHandler.addTagValue("includeSubFolders", includeSubFolders)); return retval.toString(); } public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases, slaveServers); serverName = XMLHandler.getTagValue(entrynode, "servername"); userName = XMLHandler.getTagValue(entrynode, "username"); password = Encr.decryptPasswordOptionallyEncrypted(XMLHandler.getTagValue(entrynode, "password")); serverPort = XMLHandler.getTagValue(entrynode, "serverport"); ftpDirectory = XMLHandler.getTagValue(entrynode, "ftpdirectory"); localDirectory = XMLHandler.getTagValue(entrynode, "localdirectory"); wildcard = XMLHandler.getTagValue(entrynode, "wildcard"); onlyGettingNewFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "only_new") ); usehttpproxy = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "usehttpproxy") ); httpProxyHost = XMLHandler.getTagValue(entrynode, "httpproxyhost"); httpproxyport = XMLHandler.getTagValue(entrynode, "httpproxyport"); httpproxyusername = XMLHandler.getTagValue(entrynode, "httpproxyusername"); httpProxyPassword = XMLHandler.getTagValue(entrynode, "httpproxypassword"); publicpublickey = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "publicpublickey") ); keyFilename = XMLHandler.getTagValue(entrynode, "keyfilename"); keyFilePass = XMLHandler.getTagValue(entrynode, "keyfilepass"); useBasicAuthentication = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "usebasicauthentication") ); afterFtpPut = XMLHandler.getTagValue(entrynode, "afterftpput"); destinationfolder = XMLHandler.getTagValue(entrynode, "destinationfolder"); createdestinationfolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "createdestinationfolder") ); cachehostkey = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "cachehostkey") ); timeout = Const.toInt(XMLHandler.getTagValue(entrynode, "timeout"), 0); createtargetfolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "createtargetfolder") ); includeSubFolders = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "includeSubFolders") ); } catch(KettleXMLException xe) { throw new KettleXMLException(BaseMessages.getString(PKG, "JobSSH2GET.Log.UnableLoadXML", xe.getMessage())); } } public void loadRep(Repository rep, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException { try { serverName = rep.getJobEntryAttributeString(id_jobentry, "servername"); userName = rep.getJobEntryAttributeString(id_jobentry, "username"); password = Encr.decryptPasswordOptionallyEncrypted( rep.getJobEntryAttributeString(id_jobentry, "password") ); serverPort =rep.getJobEntryAttributeString(id_jobentry, "serverport"); ftpDirectory = rep.getJobEntryAttributeString(id_jobentry, "ftpdirectory"); localDirectory = rep.getJobEntryAttributeString(id_jobentry, "localdirectory"); wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard"); onlyGettingNewFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "only_new"); usehttpproxy = rep.getJobEntryAttributeBoolean(id_jobentry, "usehttpproxy"); httpProxyHost = rep.getJobEntryAttributeString(id_jobentry, "httpproxyhost"); httpproxyusername = rep.getJobEntryAttributeString(id_jobentry, "httpproxyusername"); httpProxyPassword = rep.getJobEntryAttributeString(id_jobentry, "httpproxypassword"); publicpublickey = rep.getJobEntryAttributeBoolean(id_jobentry, "publicpublickey"); keyFilename = rep.getJobEntryAttributeString(id_jobentry, "keyfilename"); keyFilePass = rep.getJobEntryAttributeString(id_jobentry, "keyfilepass"); useBasicAuthentication = rep.getJobEntryAttributeBoolean(id_jobentry, "usebasicauthentication"); afterFtpPut = rep.getJobEntryAttributeString(id_jobentry, "afterftpput"); destinationfolder = rep.getJobEntryAttributeString(id_jobentry, "destinationfolder"); createdestinationfolder = rep.getJobEntryAttributeBoolean(id_jobentry, "createdestinationfolder"); cachehostkey = rep.getJobEntryAttributeBoolean(id_jobentry, "cachehostkey"); timeout = (int)rep.getJobEntryAttributeInteger(id_jobentry, "timeout"); createtargetfolder = rep.getJobEntryAttributeBoolean(id_jobentry, "createtargetfolder"); includeSubFolders = rep.getJobEntryAttributeBoolean(id_jobentry, "includeSubFolders"); } catch(KettleException dbe) { throw new KettleException(BaseMessages.getString(PKG, "JobSSH2GET.Log.UnableLoadRep",""+id_jobentry,dbe.getMessage())); } } public void saveRep(Repository rep, ObjectId id_job) throws KettleException { try { rep.saveJobEntryAttribute(id_job, getObjectId(), "servername", serverName); rep.saveJobEntryAttribute(id_job, getObjectId(), "username", userName); rep.saveJobEntryAttribute(id_job, getObjectId(), "password", Encr.encryptPasswordIfNotUsingVariables(password)); rep.saveJobEntryAttribute(id_job, getObjectId(), "serverport", serverPort); rep.saveJobEntryAttribute(id_job, getObjectId(), "ftpdirectory", ftpDirectory); rep.saveJobEntryAttribute(id_job, getObjectId(), "localdirectory", localDirectory); rep.saveJobEntryAttribute(id_job, getObjectId(), "wildcard", wildcard); rep.saveJobEntryAttribute(id_job, getObjectId(), "only_new", onlyGettingNewFiles); rep.saveJobEntryAttribute(id_job, getObjectId(), "usehttpproxy", usehttpproxy); rep.saveJobEntryAttribute(id_job, getObjectId(), "httpproxyhost", httpProxyHost); rep.saveJobEntryAttribute(id_job, getObjectId(), "httpproxyport", httpproxyport); rep.saveJobEntryAttribute(id_job, getObjectId(), "httpproxyusername", httpproxyusername); rep.saveJobEntryAttribute(id_job, getObjectId(), "httpproxypassword", httpProxyPassword); rep.saveJobEntryAttribute(id_job, getObjectId(), "publicpublickey", publicpublickey); rep.saveJobEntryAttribute(id_job, getObjectId(), "keyfilename", keyFilename); rep.saveJobEntryAttribute(id_job, getObjectId(), "keyfilepass", keyFilePass); rep.saveJobEntryAttribute(id_job, getObjectId(), "usebasicauthentication", useBasicAuthentication); rep.saveJobEntryAttribute(id_job, getObjectId(), "afterftpput", afterFtpPut); rep.saveJobEntryAttribute(id_job, getObjectId(), "destinationfolder", destinationfolder); rep.saveJobEntryAttribute(id_job, getObjectId(), "createdestinationfolder", createdestinationfolder); rep.saveJobEntryAttribute(id_job, getObjectId(), "cachehostkey", cachehostkey); rep.saveJobEntryAttribute(id_job, getObjectId(), "timeout", timeout); rep.saveJobEntryAttribute(id_job, getObjectId(), "createtargetfolder", createtargetfolder); rep.saveJobEntryAttribute(id_job, getObjectId(), "includeSubFolders", includeSubFolders); } catch(KettleDatabaseException dbe) { throw new KettleException(BaseMessages.getString(PKG, "JobSSH2GET.Log.UnableSaveRep",""+id_job,dbe.getMessage())); } } /** * @return Returns the directory. */ public String getFtpDirectory() { return ftpDirectory; } /** * @param directory The directory to set. */ public void setFtpDirectory(String directory) { this.ftpDirectory = directory; } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } /** * @return Returns the afterftpput. */ public String getAfterFTPPut() { return afterFtpPut; } /** * @param afterFtpPut The action after (FTP/SSH) transfer to execute */ public void setAfterFTPPut(String afterFtpPut) { this.afterFtpPut = afterFtpPut; } /** * @param proxyPassword The httpproxypassword to set. */ public void setHTTPProxyPassword(String proxyPassword) { this.httpProxyPassword = proxyPassword; } /** * @return Returns the password. */ public String getHTTPProxyPassword() { return httpProxyPassword; } /** * @param keyFilePass The key file pass to set. */ public void setKeyFilePass(String keyFilePass) { this.keyFilePass = keyFilePass; } /** * @return Returns the key file pass. */ public String getKeyFilePass() { return keyFilePass; } /** * @return Returns the serverName. */ public String getServerName() { return serverName; } /** * @param serverName The serverName to set. */ public void setServerName(String serverName) { this.serverName = serverName; } /** * @param proxyhost The httpproxyhost to set. */ public void setHTTPProxyHost(String proxyhost) { this.httpProxyHost = proxyhost; } /** * @return Returns the HTTP proxy host. */ public String getHTTPProxyHost() { return httpProxyHost; } /** * @param keyfilename The key filename to set. */ public void setKeyFilename(String keyfilename) { this.keyFilename = keyfilename; } /** * @return Returns the key filename. */ public String getKeyFilename() { return keyFilename; } /** * @return Returns the userName. */ public String getUserName() { return userName; } /** * @param userName The userName to set. */ public void setUserName(String userName) { this.userName = userName; } /** * @param proxyusername The httpproxyusername to set. */ public void setHTTPProxyUsername(String proxyusername) { this.httpproxyusername = proxyusername; } /** * @return Returns the userName. */ public String getHTTPProxyUsername() { return httpproxyusername; } /** * @return Returns the wildcard. */ public String getWildcard() { return wildcard; } /** * @param wildcard The wildcard to set. */ public void setWildcard(String wildcard) { this.wildcard = wildcard; } /** * @return Returns the localDirectory. */ public String getlocalDirectory() { return localDirectory; } /** * @param localDirectory The localDirectory to set. */ public void setlocalDirectory(String localDirectory) { this.localDirectory = localDirectory; } /** * @return Returns the onlyGettingNewFiles. */ public boolean isOnlyGettingNewFiles() { return onlyGettingNewFiles; } /** * @param onlyGettingNewFiles The onlyGettingNewFiles to set. */ public void setOnlyGettingNewFiles(boolean onlyGettingNewFiles) { this.onlyGettingNewFiles = onlyGettingNewFiles; } /** * @param cachehostkeyin The cachehostkey to set. */ public void setCacheHostKey(boolean cachehostkeyin) { this.cachehostkey = cachehostkeyin; } /** * @return Returns the cachehostkey. */ public boolean isCacheHostKey() { return cachehostkey; } /** * @param httpproxy The usehttpproxy to set. */ public void setUseHTTPProxy(boolean httpproxy) { this.usehttpproxy = httpproxy; } /** * @return Returns the usehttpproxy. */ public boolean isUseHTTPProxy() { return usehttpproxy; } /** * @return Returns the use basic authentication flag. */ public boolean isUseBasicAuthentication() { return useBasicAuthentication; } /** * @param useBasicAuthentication The use basic authentication flag to set. */ public void setUseBasicAuthentication(boolean useBasicAuthentication) { this.useBasicAuthentication = useBasicAuthentication; } /** * @param includeSubFolders The include sub folders flag to set. */ public void setIncludeSubFolders(boolean includeSubFolders) { this.includeSubFolders = includeSubFolders; } /** * @return Returns the include sub folders flag. */ public boolean isIncludeSubFolders() { return includeSubFolders; } /** * @param createdestinationfolderin The createdestinationfolder to set. */ public void setCreateDestinationFolder(boolean createdestinationfolderin) { this.createdestinationfolder = createdestinationfolderin; } /** * @return Returns the createdestinationfolder. */ public boolean isCreateDestinationFolder() { return createdestinationfolder; } /** * @return Returns the CreateTargetFolder. */ public boolean isCreateTargetFolder() { return createtargetfolder; } /** * @param createtargetfolderin The createtargetfolder to set. */ public void setCreateTargetFolder(boolean createtargetfolderin) { this.createtargetfolder = createtargetfolderin; } /** * @param publickey The publicpublickey to set. */ public void setUsePublicKey(boolean publickey) { this.publicpublickey = publickey; } /** * @return Returns the usehttpproxy. */ public boolean isUsePublicKey() { return publicpublickey; } public String getServerPort() { return serverPort; } public void setServerPort(String serverPort) { this.serverPort = serverPort; } public void setHTTPProxyPort(String proxyport) { this.httpproxyport = proxyport; } public String getHTTPProxyPort() { return httpproxyport; } public void setDestinationFolder(String destinationfolderin) { this.destinationfolder = destinationfolderin; } public String getDestinationFolder() { return destinationfolder; } /** * @param timeout The timeout to set. */ public void setTimeout(int timeout) { this.timeout = timeout; } /** * @return Returns the timeout. */ public int getTimeout() { return timeout; } public Result execute(Result previousResult, int nr) { Result result = previousResult; result.setResult( false ); if(log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "JobSSH2GET.Log.GettingFieldsValue")); // Get real variable value String realServerName=environmentSubstitute(serverName); int realServerPort=Const.toInt(environmentSubstitute(serverPort),22); String realUserName=environmentSubstitute(userName); String realServerPassword=Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password)); // Proxy Host String realProxyHost=environmentSubstitute(httpProxyHost); int realProxyPort=Const.toInt(environmentSubstitute(httpproxyport),22); String realproxyUserName=environmentSubstitute(httpproxyusername); String realProxyPassword=Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(httpProxyPassword)); // Key file String realKeyFilename=environmentSubstitute(keyFilename); String relKeyFilepass=environmentSubstitute(keyFilePass); // target files String realLocalDirectory=environmentSubstitute(localDirectory); String realwildcard=environmentSubstitute(wildcard); // Remote source String realftpDirectory=environmentSubstitute(ftpDirectory); // Destination folder (Move to) String realDestinationFolder=environmentSubstitute(destinationfolder); try{ // Remote source realftpDirectory=FTPUtils.normalizePath(realftpDirectory); // Destination folder (Move to) realDestinationFolder=FTPUtils.normalizePath(realDestinationFolder); }catch(Exception e){ logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.CanNotNormalizePath",e.getMessage())); result.setNrErrors(1); return result; } // Check for mandatory fields if(log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "JobSSH2GET.Log.CheckingMandatoryFields")); boolean mandatoryok=true; if(Const.isEmpty(realServerName)) { mandatoryok=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.ServernameMissing")); } if(usehttpproxy) { if(Const.isEmpty(realProxyHost)) { mandatoryok=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.HttpProxyhostMissing")); } } if(publicpublickey) { if(Const.isEmpty(realKeyFilename)) { mandatoryok=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.KeyFileMissing")); }else { // Let's check if key file exists... if(!new File(realKeyFilename).exists()) { mandatoryok=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.KeyFileNotExist")); } } } if(Const.isEmpty(realLocalDirectory)) { mandatoryok=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.LocalFolderMissing")); }else{ // Check if target folder exists... if(!new File(realLocalDirectory).exists()) { if(createtargetfolder) { // Create Target folder if(!CreateFolder(realLocalDirectory)) mandatoryok=false; }else { mandatoryok=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.LocalFolderNotExists", realLocalDirectory)); } }else{ if(!new File(realLocalDirectory).isDirectory()) { mandatoryok=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.LocalFolderNotFolder",realLocalDirectory)); } } } if(afterFtpPut.equals("move_file")) { if(Const.isEmpty(realDestinationFolder)) { mandatoryok=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.DestinatFolderMissing")); } } if(mandatoryok) { Connection conn = null; SFTPv3Client client = null; boolean good=true; try { // Create a connection instance conn = getConnection(realServerName,realServerPort,realProxyHost,realProxyPort,realproxyUserName,realProxyPassword); if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.ConnectionInstanceCreated")); if(timeout>0) { // Use timeout // Cache Host Key if(cachehostkey) conn.connect(new SimpleVerifier(database),0,timeout*1000); else conn.connect(null,0,timeout*1000); }else { // Cache Host Key if(cachehostkey) conn.connect(new SimpleVerifier(database)); else conn.connect(); } // Authenticate boolean isAuthenticated = false; if(publicpublickey) { isAuthenticated=conn.authenticateWithPublicKey(realUserName, new File(realKeyFilename), relKeyFilepass); }else { isAuthenticated=conn.authenticateWithPassword(realUserName, realServerPassword); } // LET'S CHECK AUTHENTICATION ... if (isAuthenticated == false) logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.AuthenticationFailed")); else { if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "JobSSH2GET.Log.Connected",serverName,userName)); client = new SFTPv3Client(conn); if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.ProtocolVersion",""+client.getProtocolVersion())); // Check if ftp (source) directory exists if(!Const.isEmpty(realftpDirectory)) { if (!sshDirectoryExists(client, realftpDirectory)) { good=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.RemoteDirectoryNotExist",realftpDirectory)); } else if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.RemoteDirectoryExist",realftpDirectory)); } if(realDestinationFolder!=null) { // Check now destination folder if(!sshDirectoryExists(client , realDestinationFolder)) { if(createdestinationfolder) { if(!CreateRemoteFolder(client,realDestinationFolder)) good=false; }else { good=false; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.DestinatFolderNotExist",realDestinationFolder)); } } } if(good) { Pattern pattern=null; if (!Const.isEmpty(realwildcard)) { pattern = Pattern.compile(realwildcard); } if(includeSubFolders) { if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.RecursiveModeOn")); copyRecursive( realftpDirectory ,realLocalDirectory, client,pattern,parentJob); }else{ if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.RecursiveModeOff")); GetFiles(realftpDirectory, realLocalDirectory,client,pattern,parentJob); } /********************************RESULT ********************/ if(log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.JobEntryEnd1")); logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.TotalFiles",""+nbfilestoget)); logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.TotalFilesPut",""+nbgot)); logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.TotalFilesError",""+nbrerror)); logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.JobEntryEnd2")); } if(nbrerror==0) result.setResult(true); /********************************RESULT ********************/ } } } catch (Exception e) { result.setNrErrors(nbrerror); logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.Error.ErrorFTP",e.getMessage())); } finally { if (conn!=null) conn.close(); if(client!=null) client.close(); } } return result; } private Connection getConnection(String servername,int serverport, String proxyhost,int proxyport,String proxyusername,String proxypassword) { /* Create a connection instance */ Connection conn = new Connection(servername,serverport); /* We want to connect through a HTTP proxy */ if(usehttpproxy) { conn.setProxyData(new HTTPProxyData(proxyhost, proxyport)); /* Now connect */ // if the proxy requires basic authentication: if(useBasicAuthentication) { conn.setProxyData(new HTTPProxyData(proxyhost, proxyport, proxyusername, proxypassword)); } } return conn; } /** * Check existence of a file * * @param sftpClient * @param filename * @return true, if file exists * @throws Exception */ public boolean sshFileExists(SFTPv3Client sftpClient, String filename) { try { SFTPv3FileAttributes attributes = sftpClient.stat(filename); if (attributes != null) { return (attributes.isRegularFile()); } else { return false; } } catch (Exception e) { return false; } } /** * Check existence of a local file * * @param filename * @return true, if file exists */ public boolean FileExists(String filename) { FileObject file=null; try { file=KettleVFS.getFileObject(filename, this); if(!file.exists()) return false; else { if(file.getType() == FileType.FILE) return true; else return false; } } catch (Exception e) { return false; } } /** * Checks if file is a directory * * @param sftpClient * @param filename * @return true, if filename is a directory */ public boolean isDirectory(SFTPv3Client sftpClient, String filename) { try { return sftpClient.stat(filename).isDirectory(); } catch(Exception e) {} return false; } /** * Checks if a directory exists * * @param sftpClient * @param directory * @return true, if directory exists */ public boolean sshDirectoryExists(SFTPv3Client sftpClient, String directory) { try { SFTPv3FileAttributes attributes = sftpClient.stat(directory); if (attributes != null) { return (attributes.isDirectory()); } else { return false; } } catch (Exception e) { return false; } } /** * Returns the file size of a file * * @param sftpClient * @param filename * @return the size of the file * @throws Exception */ public long getFileSize(SFTPv3Client sftpClient, String filename) throws Exception { return sftpClient.stat(filename).size.longValue(); } /********************************************************** * * @param selectedfile * @param wildcard * @param pattern * @return True if the selectedfile matches the wildcard **********************************************************/ private boolean getFileWildcard(String selectedfile,Pattern pattern) { boolean getIt=true; // First see if the file matches the regular expression! if (pattern!=null) { Matcher matcher = pattern.matcher(selectedfile); getIt = matcher.matches(); } return getIt; } private boolean deleteOrMoveFiles(SFTPv3Client sftpClient, String filename,String destinationFolder) { boolean retval=false; // Delete the file if this is needed! if (afterFtpPut.equals("delete_file")) { try { sftpClient.rm(filename); retval=true; if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.DeletedFile",filename)); }catch (Exception e) { logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.Error.CanNotDeleteRemoteFile",filename), e); } } else if (afterFtpPut.equals("move_file")) { String DestinationFullFilename=destinationFolder+Const.FILE_SEPARATOR+filename; try { sftpClient.mv(filename, DestinationFullFilename); retval=true; if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.DeletedFile",filename)); }catch (Exception e) { logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.Error.MovedFile",filename,destinationFolder), e); } } return retval; } /** * copy a directory from the remote host to the local one. * * @param sourceLocation the source directory on the remote host * @param targetLocation the target directory on the local host * @param sftpClient is an instance of SFTPv3Client that makes SFTP client connection over SSH-2 * @return the number of files successfully copied * @throws Exception */ @SuppressWarnings("unchecked") private void GetFiles(String sourceLocation, String targetLocation, SFTPv3Client sftpClient,Pattern pattern, Job parentJob) throws Exception { String sourceFolder="."; if (!Const.isEmpty(sourceLocation)) sourceFolder=sourceLocation + FTPUtils.FILE_SEPARATOR; else sourceFolder+=FTPUtils.FILE_SEPARATOR; Vector<SFTPv3DirectoryEntry> filelist = sftpClient.ls(sourceFolder); if(filelist!=null) { Iterator<SFTPv3DirectoryEntry> iterator = filelist.iterator(); while (iterator.hasNext() && !parentJob.isStopped()) { SFTPv3DirectoryEntry dirEntry = iterator.next(); if (dirEntry == null) continue; if (dirEntry.filename.equals(".") || dirEntry.filename.equals("..") || isDirectory(sftpClient, sourceFolder+dirEntry.filename)) continue; if(getFileWildcard(dirEntry.filename,pattern)) { // Copy file from remote host copyFile(sourceFolder + dirEntry.filename, targetLocation + FTPUtils.FILE_SEPARATOR + dirEntry.filename, sftpClient); } } } } /** * copy a directory from the remote host to the local one recursivly. * * @param sourceLocation the source directory on the remote host * @param targetLocation the target directory on the local host * @param sftpClient is an instance of SFTPv3Client that makes SFTP client connection over SSH-2 * @return the number of files successfully copied * @throws Exception */ private void copyRecursive(String sourceLocation, String targetLocation, SFTPv3Client sftpClient,Pattern pattern,Job parentJob) throws Exception { String sourceFolder="."+FTPUtils.FILE_SEPARATOR; if (sourceLocation!=null) sourceFolder=sourceLocation; if (this.isDirectory(sftpClient, sourceFolder)) { Vector<?> filelist = sftpClient.ls(sourceFolder); Iterator<?> iterator = filelist.iterator(); while (iterator.hasNext()) { SFTPv3DirectoryEntry dirEntry = (SFTPv3DirectoryEntry) iterator .next(); if (dirEntry == null) continue; if (dirEntry.filename.equals(".") || dirEntry.filename.equals("..")) continue; copyRecursive(sourceFolder + FTPUtils.FILE_SEPARATOR+dirEntry.filename, targetLocation + Const.FILE_SEPARATOR + dirEntry.filename, sftpClient,pattern,parentJob); } } else if (isFile(sftpClient, sourceFolder)) { if(getFileWildcard(sourceFolder,pattern)) copyFile(sourceFolder, targetLocation, sftpClient); } } /** * Checks if file is a file * * @param sftpClient * @param filename * @return true, if filename is a directory */ public boolean isFile(SFTPv3Client sftpClient, String filename) { try { return sftpClient.stat(filename).isRegularFile(); } catch(Exception e) {} return false; } /** * * @param sourceLocation * @param targetLocation * @param sftpClient * @return */ private void copyFile(String sourceLocation, String targetLocation, SFTPv3Client sftpClient) { SFTPv3FileHandle sftpFileHandle = null; FileOutputStream fos = null; File transferFile = null; long remoteFileSize = -1; boolean filecopied=true; try { transferFile = new File(targetLocation); if ((onlyGettingNewFiles == false) || (onlyGettingNewFiles == true) && !FileExists(transferFile.getAbsolutePath())) { new File(transferFile.getParent()).mkdirs(); remoteFileSize = this.getFileSize(sftpClient, sourceLocation); if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.ReceivingFile",sourceLocation,transferFile.getAbsolutePath(),""+remoteFileSize)); sftpFileHandle = sftpClient.openFileRO(sourceLocation); fos = null; long offset = 0; fos = new FileOutputStream(transferFile); byte[] buffer = new byte[2048]; while (true) { int len = sftpClient.read(sftpFileHandle, offset,buffer, 0, buffer.length); if (len <= 0) break; fos.write(buffer, 0, len); offset += len; } fos.flush(); fos.close(); fos = null; nbfilestoget++; if (remoteFileSize > 0 && remoteFileSize != transferFile.length()) { filecopied=false; nbrerror++; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.Error.RemoteFileLocalDifferent",""+remoteFileSize,transferFile.length()+"","" + offset)); } else { nbgot++; if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.RemoteFileLocalCopied",sourceLocation,transferFile+"")); } } // Let's now delete or move file if needed... if(filecopied && !afterFtpPut.equals("do_nothing")) { deleteOrMoveFiles(sftpClient, sourceLocation,environmentSubstitute(destinationfolder)); } } catch (Exception e) { nbrerror++; logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.Error.WritingFile",transferFile.getAbsolutePath(),e.getMessage())); } finally { try { if(sftpFileHandle!=null) { sftpClient.closeFile(sftpFileHandle); sftpFileHandle = null; } if (fos != null) try { fos.close(); fos = null; } catch (Exception ex) { } } catch(Exception e ) {} } } private boolean CreateFolder(String filefolder) { FileObject folder=null; try { folder= KettleVFS.getFileObject(filefolder, this); if(!folder.exists()) { if(createtargetfolder) { folder.createFolder(); if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.FolderCreated",folder.toString())); } else return false; } return true; } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.CanNotCreateFolder", folder.toString()), e); } finally { if ( folder != null ) { try { folder.close(); } catch (Exception ex ) {}; } } return false; } /** * Create remote folder * * @param sftpClient * @param foldername * @return true, if foldername is created */ private boolean CreateRemoteFolder(SFTPv3Client sftpClient, String foldername) { boolean retval=false; if(!sshDirectoryExists(sftpClient, foldername)) { try { sftpClient.mkdir(foldername, 0700); retval=true; if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.RemoteFolderCreated",foldername)); }catch (Exception e) { logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.Error.CreatingRemoteFolder",foldername), e); } } return retval; } public boolean evaluates() { return true; } public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) { List<ResourceReference> references = super.getResourceDependencies(jobMeta); if (!Const.isEmpty(serverName)) { String realServerName = jobMeta.environmentSubstitute(serverName); ResourceReference reference = new ResourceReference(this); reference.getEntries().add( new ResourceEntry(realServerName, ResourceType.SERVER)); references.add(reference); } return references; } @Override public void check(List<CheckResultInterface> remarks, JobMeta jobMeta) { andValidator().validate(this, "serverName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ andValidator() .validate(this, "localDirectory", remarks, putValidators(notBlankValidator(), fileExistsValidator())); //$NON-NLS-1$ andValidator().validate(this, "userName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ andValidator().validate(this, "password", remarks, putValidators(notNullValidator())); //$NON-NLS-1$ andValidator().validate(this, "serverPort", remarks, putValidators(integerValidator())); //$NON-NLS-1$ } }
apache-2.0
freeVM/freeVM
enhanced/archive/classlib/java6/modules/swing/src/test/api/java.injected/javax/swing/text/html/HTML_AttributeTest.java
11084
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Alexey A. Ivanov * @version $Revision$ */ package javax.swing.text.html; import javax.swing.text.html.HTML.Attribute; import junit.framework.TestCase; public class HTML_AttributeTest extends TestCase { private Attribute attr; public void testACTION() { attr = HTML.Attribute.ACTION; assertEquals("action", attr.toString()); } public void testALIGN() { attr = HTML.Attribute.ALIGN; assertEquals("align", attr.toString()); } public void testALINK() { attr = HTML.Attribute.ALINK; assertEquals("alink", attr.toString()); } public void testALT() { attr = HTML.Attribute.ALT; assertEquals("alt", attr.toString()); } public void testARCHIVE() { attr = HTML.Attribute.ARCHIVE; assertEquals("archive", attr.toString()); } public void testBACKGROUND() { attr = HTML.Attribute.BACKGROUND; assertEquals("background", attr.toString()); } public void testBGCOLOR() { attr = HTML.Attribute.BGCOLOR; assertEquals("bgcolor", attr.toString()); } public void testBORDER() { attr = HTML.Attribute.BORDER; assertEquals("border", attr.toString()); } public void testCELLPADDING() { attr = HTML.Attribute.CELLPADDING; assertEquals("cellpadding", attr.toString()); } public void testCELLSPACING() { attr = HTML.Attribute.CELLSPACING; assertEquals("cellspacing", attr.toString()); } public void testCHECKED() { attr = HTML.Attribute.CHECKED; assertEquals("checked", attr.toString()); } public void testCLASS() { attr = HTML.Attribute.CLASS; assertEquals("class", attr.toString()); } public void testCLASSID() { attr = HTML.Attribute.CLASSID; assertEquals("classid", attr.toString()); } public void testCLEAR() { attr = HTML.Attribute.CLEAR; assertEquals("clear", attr.toString()); } public void testCODE() { attr = HTML.Attribute.CODE; assertEquals("code", attr.toString()); } public void testCODEBASE() { attr = HTML.Attribute.CODEBASE; assertEquals("codebase", attr.toString()); } public void testCODETYPE() { attr = HTML.Attribute.CODETYPE; assertEquals("codetype", attr.toString()); } public void testCOLOR() { attr = HTML.Attribute.COLOR; assertEquals("color", attr.toString()); } public void testCOLS() { attr = HTML.Attribute.COLS; assertEquals("cols", attr.toString()); } public void testCOLSPAN() { attr = HTML.Attribute.COLSPAN; assertEquals("colspan", attr.toString()); } public void testCOMMENT() { attr = HTML.Attribute.COMMENT; assertEquals("comment", attr.toString()); } public void testCOMPACT() { attr = HTML.Attribute.COMPACT; assertEquals("compact", attr.toString()); } public void testCONTENT() { attr = HTML.Attribute.CONTENT; assertEquals("content", attr.toString()); } public void testCOORDS() { attr = HTML.Attribute.COORDS; assertEquals("coords", attr.toString()); } public void testDATA() { attr = HTML.Attribute.DATA; assertEquals("data", attr.toString()); } public void testDECLARE() { attr = HTML.Attribute.DECLARE; assertEquals("declare", attr.toString()); } public void testDIR() { attr = HTML.Attribute.DIR; assertEquals("dir", attr.toString()); } public void testDUMMY() { attr = HTML.Attribute.DUMMY; assertEquals("dummy", attr.toString()); } public void testENCTYPE() { attr = HTML.Attribute.ENCTYPE; assertEquals("enctype", attr.toString()); } public void testENDTAG() { attr = HTML.Attribute.ENDTAG; assertEquals("endtag", attr.toString()); } public void testFACE() { attr = HTML.Attribute.FACE; assertEquals("face", attr.toString()); } public void testFRAMEBORDER() { attr = HTML.Attribute.FRAMEBORDER; assertEquals("frameborder", attr.toString()); } public void testHALIGN() { attr = HTML.Attribute.HALIGN; assertEquals("halign", attr.toString()); } public void testHEIGHT() { attr = HTML.Attribute.HEIGHT; assertEquals("height", attr.toString()); } public void testHREF() { attr = HTML.Attribute.HREF; assertEquals("href", attr.toString()); } public void testHSPACE() { attr = HTML.Attribute.HSPACE; assertEquals("hspace", attr.toString()); } public void testHTTPEQUIV() { attr = HTML.Attribute.HTTPEQUIV; assertEquals("http-equiv", attr.toString()); } public void testID() { attr = HTML.Attribute.ID; assertEquals("id", attr.toString()); } public void testISMAP() { attr = HTML.Attribute.ISMAP; assertEquals("ismap", attr.toString()); } public void testLANG() { attr = HTML.Attribute.LANG; assertEquals("lang", attr.toString()); } public void testLANGUAGE() { attr = HTML.Attribute.LANGUAGE; assertEquals("language", attr.toString()); } public void testLINK() { attr = HTML.Attribute.LINK; assertEquals("link", attr.toString()); } public void testLOWSRC() { attr = HTML.Attribute.LOWSRC; assertEquals("lowsrc", attr.toString()); } public void testMARGINHEIGHT() { attr = HTML.Attribute.MARGINHEIGHT; assertEquals("marginheight", attr.toString()); } public void testMARGINWIDTH() { attr = HTML.Attribute.MARGINWIDTH; assertEquals("marginwidth", attr.toString()); } public void testMAXLENGTH() { attr = HTML.Attribute.MAXLENGTH; assertEquals("maxlength", attr.toString()); } public void testMETHOD() { attr = HTML.Attribute.METHOD; assertEquals("method", attr.toString()); } public void testMULTIPLE() { attr = HTML.Attribute.MULTIPLE; assertEquals("multiple", attr.toString()); } public void testN() { attr = HTML.Attribute.N; assertEquals("n", attr.toString()); } public void testNAME() { attr = HTML.Attribute.NAME; assertEquals("name", attr.toString()); } public void testNOHREF() { attr = HTML.Attribute.NOHREF; assertEquals("nohref", attr.toString()); } public void testNORESIZE() { attr = HTML.Attribute.NORESIZE; assertEquals("noresize", attr.toString()); } public void testNOSHADE() { attr = HTML.Attribute.NOSHADE; assertEquals("noshade", attr.toString()); } public void testNOWRAP() { attr = HTML.Attribute.NOWRAP; assertEquals("nowrap", attr.toString()); } public void testPROMPT() { attr = HTML.Attribute.PROMPT; assertEquals("prompt", attr.toString()); } public void testREL() { attr = HTML.Attribute.REL; assertEquals("rel", attr.toString()); } public void testREV() { attr = HTML.Attribute.REV; assertEquals("rev", attr.toString()); } public void testROWS() { attr = HTML.Attribute.ROWS; assertEquals("rows", attr.toString()); } public void testROWSPAN() { attr = HTML.Attribute.ROWSPAN; assertEquals("rowspan", attr.toString()); } public void testSCROLLING() { attr = HTML.Attribute.SCROLLING; assertEquals("scrolling", attr.toString()); } public void testSELECTED() { attr = HTML.Attribute.SELECTED; assertEquals("selected", attr.toString()); } public void testSHAPE() { attr = HTML.Attribute.SHAPE; assertEquals("shape", attr.toString()); } public void testSHAPES() { attr = HTML.Attribute.SHAPES; assertEquals("shapes", attr.toString()); } public void testSIZE() { attr = HTML.Attribute.SIZE; assertEquals("size", attr.toString()); } public void testSRC() { attr = HTML.Attribute.SRC; assertEquals("src", attr.toString()); } public void testSTANDBY() { attr = HTML.Attribute.STANDBY; assertEquals("standby", attr.toString()); } public void testSTART() { attr = HTML.Attribute.START; assertEquals("start", attr.toString()); } public void testSTYLE() { attr = HTML.Attribute.STYLE; assertEquals("style", attr.toString()); } public void testTARGET() { attr = HTML.Attribute.TARGET; assertEquals("target", attr.toString()); } public void testTEXT() { attr = HTML.Attribute.TEXT; assertEquals("text", attr.toString()); } public void testTITLE() { attr = HTML.Attribute.TITLE; assertEquals("title", attr.toString()); } public void testTYPE() { attr = HTML.Attribute.TYPE; assertEquals("type", attr.toString()); } public void testUSEMAP() { attr = HTML.Attribute.USEMAP; assertEquals("usemap", attr.toString()); } public void testVALIGN() { attr = HTML.Attribute.VALIGN; assertEquals("valign", attr.toString()); } public void testVALUE() { attr = HTML.Attribute.VALUE; assertEquals("value", attr.toString()); } public void testVALUETYPE() { attr = HTML.Attribute.VALUETYPE; assertEquals("valuetype", attr.toString()); } public void testVERSION() { attr = HTML.Attribute.VERSION; assertEquals("version", attr.toString()); } public void testVLINK() { attr = HTML.Attribute.VLINK; assertEquals("vlink", attr.toString()); } public void testVSPACE() { attr = HTML.Attribute.VSPACE; assertEquals("vspace", attr.toString()); } public void testWIDTH() { attr = HTML.Attribute.WIDTH; assertEquals("width", attr.toString()); } }
apache-2.0
fspinnenhirn/oacc-core-ci
src/test/java/com/acciente/oacc/TestAccessControl_getDomainNameByResource.java
5815
/* * Copyright 2009-2015, Acciente LLC * * Acciente LLC licenses this file to you under the * Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in * writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing * permissions and limitations under the License. */ package com.acciente.oacc; import org.junit.Test; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class TestAccessControl_getDomainNameByResource extends TestAccessControlBase { @Test public void getDomainNameByResource_validAsSystemResource() { authenticateSystemResource(); generateUnauthenticatableResource(); final String resourceClassName = generateResourceClass(false, true); final String sysDomainName = accessControlContext.getDomainNameByResource(SYS_RESOURCE); final Resource queriedResource = accessControlContext.createResource(resourceClassName, sysDomainName); // verify final String domainName = accessControlContext.getDomainNameByResource(queriedResource); assertThat(domainName, is(not(nullValue()))); assertThat(domainName, is(sysDomainName)); } @Test public void getDomainNameByResource_withExtId() { authenticateSystemResource(); generateUnauthenticatableResource(); final String resourceClassName = generateResourceClass(false, true); final String sysDomainName = accessControlContext.getDomainNameByResource(SYS_RESOURCE); final String externalId = generateUniqueExternalId(); accessControlContext.createResource(resourceClassName, sysDomainName, externalId); // verify final String domainName = accessControlContext.getDomainNameByResource(Resources.getInstance(externalId)); assertThat(domainName, is(not(nullValue()))); assertThat(domainName, is(sysDomainName)); } @Test public void getDomainNameByResource_validAsAuthenticated() { authenticateSystemResource(); final char[] password = generateUniquePassword(); final Resource accessorResource = generateAuthenticatableResource(password); generateUnauthenticatableResource(); final String resourceClassName = generateResourceClass(false, true); final String queriedResourceDomain = generateDomain(); final Resource queriedResource = accessControlContext.createResource(resourceClassName, queriedResourceDomain); // authenticate and verify accessControlContext.authenticate(accessorResource, PasswordCredentials.newInstance(password)); final String domainName = accessControlContext.getDomainNameByResource(queriedResource); assertThat(domainName, is(queriedResourceDomain)); } @Test public void getDomainNameByResource_nonExistentReferences_shouldFail() { authenticateSystemResource(); final char[] password = generateUniquePassword(); final Resource accessorResource = generateAuthenticatableResource(password); generateUnauthenticatableResource(); // authenticate and verify accessControlContext.authenticate(accessorResource, PasswordCredentials.newInstance(password)); try { accessControlContext.getDomainNameByResource(Resources.getInstance(-999L)); fail("getting domain name by resource for non-existent resource should have failed"); } catch (IllegalArgumentException e) { assertThat(e.getMessage().toLowerCase(), containsString("not found")); } try { accessControlContext.getDomainNameByResource(Resources.getInstance("invalid")); fail("getting domain name by resource for non-existent external resource should have failed"); } catch (IllegalArgumentException e) { assertThat(e.getMessage().toLowerCase(), containsString("not found")); } try { accessControlContext.getDomainNameByResource(Resources.getInstance(-999L, "invalid")); fail("getting domain name by resource for mismatched internal/external resource ids should have failed"); } catch (IllegalArgumentException e) { assertThat(e.getMessage().toLowerCase(), containsString("not resolve")); } } @Test public void getDomainNameByResource_nulls() { final char[] password = generateUniquePassword(); final Resource accessorResource = generateAuthenticatableResource(password); generateUnauthenticatableResource(); // authenticate and verify accessControlContext.authenticate(accessorResource, PasswordCredentials.newInstance(password)); try { accessControlContext.getDomainNameByResource(null); fail("getting resource class info by resource for null resource should have failed"); } catch (NullPointerException e) { assertThat(e.getMessage().toLowerCase(), containsString("resource required")); } try { accessControlContext.getDomainNameByResource(Resources.getInstance(null)); fail("getting resource class info by resource for null internal/external resource ids should have failed"); } catch (IllegalArgumentException e) { assertThat(e.getMessage().toLowerCase(), containsString("resource id and/or external id is required")); } } }
apache-2.0
baby-gnu/one
src/sunstone/public/app/tabs/hosts-tab/panels/vms/panelId.js
1270
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ define(function(require){ return 'host_vms_tab'; })
apache-2.0
UKHomeOffice/drt-scalajs-spa-exploration
client/src/main/scala/drt/client/services/handlers/ContactDetailsHandler.scala
988
package drt.client.services.handlers import diode.data.{Pending, Pot, Ready} import diode.{ActionResult, Effect, ModelRW} import drt.client.actions.Actions.{GetContactDetails, RetryActionAfter, UpdateContactDetails} import drt.client.services.{DrtApi, PollDelay} import drt.shared.ContactDetails import upickle.default.read import scala.concurrent.Future import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue class ContactDetailsHandler[M](modelRW: ModelRW[M, Pot[ContactDetails]]) extends LoggingActionHandler(modelRW) { protected def handle: PartialFunction[Any, ActionResult[M]] = { case GetContactDetails => updated(Pending(), Effect(DrtApi.get("contact-details") .map(r => UpdateContactDetails(read[ContactDetails](r.responseText))).recoverWith { case _ => Future(RetryActionAfter(GetContactDetails, PollDelay.recoveryDelay)) })) case UpdateContactDetails(contactDetails) => updated(Ready(contactDetails)) } }
apache-2.0
leafclick/intellij-community
platform/lang-impl/src/com/intellij/psi/codeStyle/statusbar/CodeStyleStatusBarWidget.java
8563
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.codeStyle.statusbar; import com.intellij.application.options.CodeStyle; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.StatusBarWidget; import com.intellij.openapi.wm.impl.status.EditorBasedStatusBarPopup; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.*; import com.intellij.psi.codeStyle.modifier.CodeStyleSettingsModifier; import com.intellij.psi.codeStyle.modifier.CodeStyleStatusBarUIContributor; import com.intellij.psi.codeStyle.modifier.TransientCodeStyleSettings; import com.intellij.util.concurrency.NonUrgentExecutor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.intellij.psi.codeStyle.CommonCodeStyleSettings.IndentOptions; public class CodeStyleStatusBarWidget extends EditorBasedStatusBarPopup implements CodeStyleSettingsListener { public static final String WIDGET_ID = CodeStyleStatusBarWidget.class.getName(); public CodeStyleStatusBarWidget(@NotNull Project project) { super(project, true); } @NotNull @Override protected WidgetState getWidgetState(@Nullable VirtualFile file) { if (file == null) return WidgetState.HIDDEN; PsiFile psiFile = getPsiFile(); if (psiFile == null || !psiFile.isWritable()) return WidgetState.HIDDEN; CodeStyleSettings settings = CodeStyle.getSettings(psiFile); IndentOptions indentOptions = CodeStyle.getIndentOptions(psiFile); if (settings instanceof TransientCodeStyleSettings) { return createWidgetState(psiFile, indentOptions, getUiContributor((TransientCodeStyleSettings)settings)); } else { return createWidgetState(psiFile, indentOptions, getUiContributor(file, indentOptions)); } } @Nullable private static CodeStyleStatusBarUIContributor getUiContributor(@NotNull TransientCodeStyleSettings settings) { final CodeStyleSettingsModifier modifier = settings.getModifier(); return modifier != null ? modifier.getStatusBarUiContributor(settings) : null; } @Nullable private static IndentStatusBarUIContributor getUiContributor(@NotNull VirtualFile file, @NotNull IndentOptions indentOptions) { FileIndentOptionsProvider provider = findProvider(file, indentOptions); if (provider != null) { return provider.getIndentStatusBarUiContributor(indentOptions); } return null; } @Nullable private static FileIndentOptionsProvider findProvider(@NotNull VirtualFile file, @NotNull IndentOptions indentOptions) { FileIndentOptionsProvider optionsProvider = indentOptions.getFileIndentOptionsProvider(); if (optionsProvider != null) return optionsProvider; for (FileIndentOptionsProvider provider : FileIndentOptionsProvider.EP_NAME.getExtensions()) { IndentStatusBarUIContributor uiContributor = provider.getIndentStatusBarUiContributor(indentOptions); if (uiContributor != null && uiContributor.areActionsAvailable(file)) { return provider; } } return null; } private static WidgetState createWidgetState(@NotNull PsiFile psiFile, @NotNull final IndentOptions indentOptions, @Nullable CodeStyleStatusBarUIContributor uiContributor) { if (uiContributor != null) { return new MyWidgetState(uiContributor.getTooltip(), uiContributor.getStatusText(psiFile), psiFile, indentOptions, uiContributor); } else { String indentInfo = IndentStatusBarUIContributor.getIndentInfo(indentOptions); String tooltip = IndentStatusBarUIContributor.createTooltip(indentInfo, null); return new MyWidgetState(tooltip, indentInfo, psiFile, indentOptions, null); } } @Nullable private PsiFile getPsiFile() { Editor editor = getEditor(); if (editor != null) { return PsiDocumentManager.getInstance(getProject()).getPsiFile(editor.getDocument()); } return null; } @Nullable @Override protected ListPopup createPopup(DataContext context) { WidgetState state = getWidgetState(context.getData(CommonDataKeys.VIRTUAL_FILE)); Editor editor = getEditor(); PsiFile psiFile = getPsiFile(); if (state instanceof MyWidgetState && editor != null && psiFile != null) { final CodeStyleStatusBarUIContributor uiContributor = ((MyWidgetState)state).getContributor(); AnAction[] actions = getActions(uiContributor, psiFile); ActionGroup actionGroup = new ActionGroup() { @Override public AnAction @NotNull [] getChildren(@Nullable AnActionEvent e) { return actions; } }; return JBPopupFactory.getInstance().createActionGroupPopup( uiContributor != null ? uiContributor.getActionGroupTitle() : null, actionGroup, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false); } return null; } private static AnAction @NotNull [] getActions(@Nullable final CodeStyleStatusBarUIContributor uiContributor, @NotNull PsiFile psiFile) { List<AnAction> allActions = new ArrayList<>(); if (uiContributor != null) { AnAction[] actions = uiContributor.getActions(psiFile); if (actions != null) { allActions.addAll(Arrays.asList(actions)); } } if (uiContributor == null || (uiContributor instanceof IndentStatusBarUIContributor) && ((IndentStatusBarUIContributor)uiContributor).isShowFileIndentOptionsEnabled()) { allActions.add(CodeStyleStatusBarWidgetProvider.createDefaultIndentConfigureAction(psiFile)); } if (uiContributor != null) { AnAction disabledAction = uiContributor.createDisableAction(psiFile.getProject()); if (disabledAction != null) { allActions.add(disabledAction); } AnAction showAllAction = uiContributor.createShowAllAction(psiFile.getProject()); if (showAllAction != null) { allActions.add(showAllAction); } } return allActions.toArray(AnAction.EMPTY_ARRAY); } @Override protected void registerCustomListeners() { Project project = getProject(); ReadAction .nonBlocking(() -> CodeStyleSettingsManager.getInstance(project)) .expireWith(project) .finishOnUiThread(ModalityState.any(), manager -> { manager.addListener(this); Disposer.register(this, () -> CodeStyleSettingsManager.removeListener(project, this)); } ).submit(NonUrgentExecutor.getInstance()); } @Override public void codeStyleSettingsChanged(@NotNull CodeStyleSettingsChangeEvent event) { update(); } @NotNull @Override protected StatusBarWidget createInstance(@NotNull Project project) { return new CodeStyleStatusBarWidget(project); } @NotNull @Override public String ID() { return WIDGET_ID; } private static class MyWidgetState extends WidgetState { private final @NotNull IndentOptions myIndentOptions; private final @Nullable CodeStyleStatusBarUIContributor myContributor; private final @NotNull PsiFile myPsiFile; protected MyWidgetState(String toolTip, String text, @NotNull PsiFile psiFile, @NotNull IndentOptions indentOptions, @Nullable CodeStyleStatusBarUIContributor uiContributor) { super(toolTip, text, true); myIndentOptions = indentOptions; myContributor = uiContributor; myPsiFile = psiFile; if (uiContributor != null) { setIcon(uiContributor.getIcon()); } } @Nullable public CodeStyleStatusBarUIContributor getContributor() { return myContributor; } @NotNull public IndentOptions getIndentOptions() { return myIndentOptions; } @NotNull public PsiFile getPsiFile() { return myPsiFile; } } }
apache-2.0
SURFnet/Stepup-u2f-bundle
src/Dto/RegisterRequest.php
1909
<?php /** * Copyright 2014 SURFnet bv * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Surfnet\StepupU2fBundle\Dto; use JsonSerializable; use Symfony\Component\Validator\Constraints as Assert; final class RegisterRequest implements JsonSerializable { /** * @Assert\NotBlank(message="Register request version may not be empty") * @Assert\Type("string", message="Register request version must be a string") * * @var string */ public $version; /** * @Assert\NotBlank(message="Register request challenge may not be empty") * @Assert\Type("string", message="Register request challenge must be a string") * * @var string */ public $challenge; /** * @Assert\NotBlank(message="Register request AppID may not be empty") * @Assert\Type("string", message="Register request AppID must be a string") * * @var string */ public $appId; public function jsonSerialize() { // The array keys below conform to the U2F JavaScript RegisterRequest dictionary // https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-javascript-api.html // #dictionary-registerrequest-members return [ 'version' => $this->version, 'challenge' => $this->challenge, 'appId' => $this->appId, ]; } }
apache-2.0
limagiran/hearthstone
src/com/limagiran/hearthstone/card/view/EscudoDivino.java
795
package com.limagiran.hearthstone.card.view; import com.limagiran.hearthstone.card.control.Card; import com.limagiran.hearthstone.util.DimensionValues; import java.awt.Color; import java.awt.Graphics; import java.io.Serializable; import javax.swing.JLabel; /** * * @author Vinicius */ public class EscudoDivino extends JLabel implements Serializable { private final Card card; public EscudoDivino(Card card) { this.card = card; init(); } @Override public void paintComponent(Graphics g) { g.setColor(new Color(255, 201, 14, 100)); g.fillOval(8, 2, 128, 163); } @Override public String toString() { return card.getToString(); } private void init() { setPreferredSize(DimensionValues.MESA); } }
apache-2.0
pinotlytics/pinot
pinot-core/src/main/java/com/linkedin/pinot/core/operator/dociditerators/AndDocIdIterator.java
4760
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.core.operator.dociditerators; import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linkedin.pinot.core.common.BlockDocIdIterator; import com.linkedin.pinot.core.common.Constants; public final class AndDocIdIterator implements BlockDocIdIterator { static final Logger LOGGER = LoggerFactory.getLogger(AndDocIdIterator.class); public final BlockDocIdIterator[] docIdIterators; public ScanBasedDocIdIterator[] scanBasedDocIdIterators; public final int[] docIdPointers; public boolean reachedEnd = false; public int currentDocId = -1; int currentMax = -1; private boolean hasScanBasedIterators; public AndDocIdIterator(BlockDocIdIterator[] blockDocIdIterators) { int numIndexBasedIterators = 0; int numScanBasedIterators = 0; for (int i = 0; i < blockDocIdIterators.length; i++) { if (blockDocIdIterators[i] instanceof IndexBasedDocIdIterator) { numIndexBasedIterators = numIndexBasedIterators + 1; } else if (blockDocIdIterators[i] instanceof ScanBasedDocIdIterator) { numScanBasedIterators = numScanBasedIterators + 1; } } // if we have at least one index based then do intersection based on index based only, and then // check if matching docs apply on scan based iterator if (numIndexBasedIterators > 0 && numScanBasedIterators > 0) { hasScanBasedIterators = true; int nonScanIteratorsSize = blockDocIdIterators.length - numScanBasedIterators; this.docIdIterators = new BlockDocIdIterator[nonScanIteratorsSize]; this.scanBasedDocIdIterators = new ScanBasedDocIdIterator[numScanBasedIterators]; int nonScanBasedIndex = 0; int scanBasedIndex = 0; for (int i = 0; i < blockDocIdIterators.length; i++) { if (blockDocIdIterators[i] instanceof ScanBasedDocIdIterator) { this.scanBasedDocIdIterators[scanBasedIndex++] = (ScanBasedDocIdIterator) blockDocIdIterators[i]; } else { this.docIdIterators[nonScanBasedIndex++] = blockDocIdIterators[i]; } } } else { hasScanBasedIterators = false; this.docIdIterators = blockDocIdIterators; } this.docIdPointers = new int[docIdIterators.length]; Arrays.fill(docIdPointers, -1); } @Override public int advance(int targetDocId) { if (currentDocId == Constants.EOF) { return currentDocId; } if (currentDocId >= targetDocId) { return currentDocId; } // next() method will always increment currentMax by 1. currentMax = targetDocId - 1; return next(); } @Override public int next() { if (currentDocId == Constants.EOF) { return currentDocId; } currentMax = currentMax + 1; // always increment the pointer to current max, when this is called first time, every one will // be set to start of posting list. for (int i = 0; i < docIdIterators.length; i++) { docIdPointers[i] = docIdIterators[i].advance(currentMax); if (docIdPointers[i] == Constants.EOF) { reachedEnd = true; currentMax = Constants.EOF; break; } if (docIdPointers[i] > currentMax) { currentMax = docIdPointers[i]; if (i > 0) { // we need to advance all pointer since we found a new max i = -1; } } if (i == docIdIterators.length - 1 && hasScanBasedIterators) { // this means we found the docId common to all nonScanBased iterators, now we need to ensure // that its also found in scanBasedIterator, if not matched, we restart the intersection for (ScanBasedDocIdIterator iterator : scanBasedDocIdIterators) { if (!iterator.isMatch(currentMax)) { i = -1; currentMax = currentMax + 1; break; } } } } currentDocId = currentMax; return currentDocId; } @Override public int currentDocId() { return currentDocId; } public String toString() { return Arrays.toString(docIdIterators); } }
apache-2.0
paulmw/flume-test-source
src/main/java/com/cloudera/flume/TestSource.java
3140
// Copyright 2014 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.flume; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.EventDeliveryException; import org.apache.flume.EventDrivenSource; import org.apache.flume.channel.ChannelProcessor; import org.apache.flume.conf.Configurable; import org.apache.flume.event.EventBuilder; import org.apache.flume.source.AbstractSource; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestSource extends AbstractSource implements EventDrivenSource, Configurable { private Random random; private int delay; @Override public void configure(Context context) { random = new Random(context.getInteger("seed", 0)); delay = context.getInteger("delay", 200); } private ExecutorService service; @Override public synchronized void start() { service = Executors.newSingleThreadExecutor(); EventHandler handler = new EventHandler(this.getChannelProcessor(), random, delay); service.execute(handler); } @Override public synchronized void stop() { // NOP } public static class EventHandler implements Runnable { private ChannelProcessor channelProcessor; private Random random; private int delay; public EventHandler(ChannelProcessor channelProcessor, Random random, int delay) { this.channelProcessor = channelProcessor; this.random = random; this.delay = delay; } @Override public void run() { boolean running = true; while (running) { try { process(); Thread.sleep(delay); } catch (Exception e) { throw new IllegalStateException(e); } } } public void process() throws EventDeliveryException { channelProcessor.processEvent(generateEvent()); } private Event generateEvent() { Map<String, String> header = new HashMap<String, String>(); int numHeaders = random.nextInt(3); for (int i = 0; i < numHeaders; i++) { header.put("k" + random.nextInt(100), "v" + random.nextInt(100)); } byte[] bytes = new byte[random.nextInt(10000)]; random.nextBytes(bytes); return EventBuilder.withBody(bytes, header); } } }
apache-2.0
googleapis/google-cloud-cpp
google/cloud/storage/internal/resumable_upload_session_test.cc
4722
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/resumable_upload_session.h" #include "google/cloud/testing_util/status_matchers.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { using ::google::cloud::testing_util::StatusIs; using ::testing::HasSubstr; TEST(ResumableUploadResponseTest, Base) { auto actual = ResumableUploadResponse::FromHttpResponse( HttpResponse{200, R"""({"name": "test-object-name"})""", {{"ignored-header", "value"}, {"location", "location-value"}, {"range", "bytes=0-1999"}}}) .value(); ASSERT_TRUE(actual.payload.has_value()); EXPECT_EQ("test-object-name", actual.payload->name()); EXPECT_EQ("location-value", actual.upload_session_url); EXPECT_EQ(2000, actual.committed_size.value_or(0)); EXPECT_EQ(ResumableUploadResponse::kDone, actual.upload_state); std::ostringstream os; os << actual; auto actual_str = os.str(); EXPECT_THAT(actual_str, HasSubstr("upload_session_url=location-value")); EXPECT_THAT(actual_str, HasSubstr("committed_size=2000")); EXPECT_THAT(actual_str, HasSubstr("annotations=")); } TEST(ResumableUploadResponseTest, NoLocation) { auto actual = ResumableUploadResponse::FromHttpResponse( HttpResponse{308, {}, {{"range", "bytes=0-1999"}}}) .value(); EXPECT_FALSE(actual.payload.has_value()); EXPECT_EQ("", actual.upload_session_url); EXPECT_EQ(2000, actual.committed_size.value_or(0)); EXPECT_EQ(ResumableUploadResponse::kInProgress, actual.upload_state); } TEST(ResumableUploadResponseTest, NoRange) { auto actual = ResumableUploadResponse::FromHttpResponse( HttpResponse{201, R"""({"name": "test-object-name"})""", {{"location", "location-value"}}}) .value(); ASSERT_TRUE(actual.payload.has_value()); EXPECT_EQ("test-object-name", actual.payload->name()); EXPECT_EQ("location-value", actual.upload_session_url); EXPECT_FALSE(actual.committed_size.has_value()); EXPECT_EQ(ResumableUploadResponse::kDone, actual.upload_state); } TEST(ResumableUploadResponseTest, MissingBytesInRange) { auto actual = ResumableUploadResponse::FromHttpResponse(HttpResponse{ 308, {}, {{"location", "location-value"}, {"range", "units=0-2000"}}}); EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("units=0-2000"))); } TEST(ResumableUploadResponseTest, MissingRangeEnd) { auto actual = ResumableUploadResponse::FromHttpResponse( HttpResponse{308, {}, {{"range", "bytes=0-"}}}); EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=0-"))); } TEST(ResumableUploadResponseTest, InvalidRangeEnd) { auto actual = ResumableUploadResponse::FromHttpResponse( HttpResponse{308, {}, {{"range", "bytes=0-abcd"}}}); EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=0-abcd"))); } TEST(ResumableUploadResponseTest, InvalidRangeBegin) { auto actual = ResumableUploadResponse::FromHttpResponse( HttpResponse{308, {}, {{"range", "bytes=abcd-2000"}}}); EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=abcd-2000"))); } TEST(ResumableUploadResponseTest, UnexpectedRangeBegin) { auto actual = ResumableUploadResponse::FromHttpResponse( HttpResponse{308, {}, {{"range", "bytes=3000-2000"}}}); EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=3000-2000"))); } TEST(ResumableUploadResponseTest, NegativeEnd) { auto actual = ResumableUploadResponse::FromHttpResponse( HttpResponse{308, {}, {{"range", "bytes=0--7"}}}); EXPECT_THAT(actual, StatusIs(StatusCode::kInternal, HasSubstr("bytes=0--7"))); } } // namespace } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google
apache-2.0
torrances/swtk-commons
commons-dict-wiktionary/src/main/java/org/swtk/commons/dict/wiktionary/generated/m/s/e/WiktionaryMSE000.java
978
package org.swtk.commons.dict.wiktionary.generated.m.s.e; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.swtk.common.dict.dto.wiktionary.Entry; import com.trimc.blogger.commons.utils.GsonUtils; public class WiktionaryMSE000 { private static Map<String, Entry> map = new HashMap<String, Entry>(); static { add("mser", "{\"term\":\"mser\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"Initialism. of \u0027\u0027 ()\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"An extended-release formulation of morphine sulfate\", \"priority\":1}]}, \"synonyms\":{}}"); } private static void add(String term, String json) { map.put(term, GsonUtils.toObject(json, Entry.class)); } public static Entry get(String term) { return map.get(term); } public static boolean has(String term) { return null != get(term); } public static Collection<String> terms() { return map.keySet(); } }
apache-2.0
leeyikjiun/scf4j
scf4j-api/src/main/java/sg/yikjiun/scf4j/map/IntLongMap.java
912
/* * Copyright 2015 Lee Yik Jiun * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sg.yikjiun.scf4j.map; /** * @author Lee Yik Jiun */ public interface IntLongMap { void clear(); boolean containsKey(int key); boolean containsValue(long value); long get(int key); boolean isEmpty(); long put(int key, long value); long remove(int key); int size(); }
apache-2.0
acsukesh/java-chassis
core/src/test/java/org/apache/servicecomb/core/definition/loader/TestSchemaListenerManager.java
1871
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicecomb.core.definition.loader; import java.util.Arrays; import org.apache.servicecomb.core.definition.MicroserviceMetaManager; import org.apache.servicecomb.core.definition.SchemaMeta; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class TestSchemaListenerManager { SchemaMeta schemaMeta = Mockito.mock(SchemaMeta.class); @Before public void setUp() { Mockito.when(schemaMeta.getSchemaId()).thenReturn("test"); } @Test public void testInitializationListener() { SchemaListener listener = new SchemaListener() { @Override public void onSchemaLoaded(SchemaMeta... schemaMetas) { Assert.assertEquals(1, schemaMetas.length); Assert.assertEquals("test", schemaMetas[0].getSchemaId()); } }; SchemaListenerManager mgr = new SchemaListenerManager(); mgr.setSchemaListenerList(Arrays.asList(listener)); mgr.setMicroserviceMetaManager(new MicroserviceMetaManager()); mgr.notifySchemaListener(schemaMeta); } }
apache-2.0
404mike/llgc-shipping
public/shipping/app/scripts/controllers/mike.js
316
'use strict'; /** * @ngdoc function * @name shippingApp.controller:MikeCtrl * @description * # MikeCtrl * Controller of the shippingApp */ angular.module('shippingApp') .controller('MikeCtrl', function () { this.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; });
apache-2.0
vulah/vulah
app/AppKernel.php
1690
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Vulah\Infrastructure\WebBundle\VulahWebBundle(), new Vulah\Infrastructure\ApiBundle\VulahApiBundle(), new AshleyDawson\GlideBundle\AshleyDawsonGlideBundle(), ]; if (in_array($this->getEnvironment(), ['dev', 'test'], true)) { $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); } return $bundles; } public function getRootDir() { return __DIR__; } public function getCacheDir() { return dirname(__DIR__).'/var/cache/'.$this->getEnvironment(); } public function getLogDir() { return dirname(__DIR__).'/var/logs'; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml'); } }
apache-2.0
eldar258/edzabarov
chapter_101/src/main/java/ru/job4j/benchmark/Handler.java
1438
package ru.job4j.benchmark; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Class ru.job4j.benchmark. * * @author edzabarov * @since 07.12.2017 */ public class Handler extends DefaultHandler { private static final String ADD_ORDER = "AddOrder"; private static final String DELETE_ORDER = "DeleteOrder"; private static final String NAME_BOOK = "book"; private static final String NAME_OPERATION = "operation"; private static final String PRICE = "price"; private static final String VOLUME = "volume"; private static final String ORDER_ID = "orderId"; private Distributor distributor = new Distributor(); @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { //super.startElement(s, s1, s2, attributes); if (qName.equals(ADD_ORDER)) { Order order = new Order(attributes.getValue(NAME_BOOK), attributes.getValue(NAME_OPERATION), attributes.getValue(PRICE), attributes.getValue(VOLUME), attributes.getValue(ORDER_ID)); distributor.putOrder(order); } else if (qName.equals(DELETE_ORDER)) { distributor.deleteOrder(attributes.getValue(NAME_BOOK), attributes.getValue(ORDER_ID)); } } public Distributor getDistributor() { return this.distributor; } }
apache-2.0
resin-io/resin-etcher
lib/gui/app/app.ts
10061
/* * Copyright 2016 balena.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as electron from 'electron'; import * as sdk from 'etcher-sdk'; import * as _ from 'lodash'; import outdent from 'outdent'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { v4 as uuidV4 } from 'uuid'; import * as packageJSON from '../../../package.json'; import { DrivelistDrive, isSourceDrive } from '../../shared/drive-constraints'; import * as EXIT_CODES from '../../shared/exit-codes'; import * as messages from '../../shared/messages'; import * as availableDrives from './models/available-drives'; import * as flashState from './models/flash-state'; import { init as ledsInit } from './models/leds'; import { deselectImage, getImage } from './models/selection-state'; import * as settings from './models/settings'; import { Actions, observe, store } from './models/store'; import * as analytics from './modules/analytics'; import { scanner as driveScanner } from './modules/drive-scanner'; import * as exceptionReporter from './modules/exception-reporter'; import * as osDialog from './os/dialog'; import * as windowProgress from './os/window-progress'; import MainPage from './pages/main/MainPage'; import './css/main.css'; window.addEventListener( 'unhandledrejection', (event: PromiseRejectionEvent | any) => { // Promise: event.reason // Anything else: event const error = event.reason || event; analytics.logException(error); event.preventDefault(); }, ); // Set application session UUID store.dispatch({ type: Actions.SET_APPLICATION_SESSION_UUID, data: uuidV4(), }); // Set first flashing workflow UUID store.dispatch({ type: Actions.SET_FLASHING_WORKFLOW_UUID, data: uuidV4(), }); const applicationSessionUuid = store.getState().toJS().applicationSessionUuid; const flashingWorkflowUuid = store.getState().toJS().flashingWorkflowUuid; console.log(outdent` ${outdent} _____ _ _ | ___| | | | | |__ | |_ ___| |__ ___ _ __ | __|| __/ __| '_ \\ / _ \\ '__| | |___| || (__| | | | __/ | \\____/ \\__\\___|_| |_|\\___|_| Interested in joining the Etcher team? Drop us a line at join+etcher@balena.io Version = ${packageJSON.version}, Type = ${packageJSON.packageType} `); const currentVersion = packageJSON.version; analytics.logEvent('Application start', { packageType: packageJSON.packageType, version: currentVersion, }); const debouncedLog = _.debounce(console.log, 1000, { maxWait: 1000 }); function pluralize(word: string, quantity: number) { return `${quantity} ${word}${quantity === 1 ? '' : 's'}`; } observe(() => { if (!flashState.isFlashing()) { return; } const currentFlashState = flashState.getFlashState(); windowProgress.set(currentFlashState); let eta = ''; if (currentFlashState.eta !== undefined) { eta = `eta in ${currentFlashState.eta.toFixed(0)}s`; } let active = ''; if (currentFlashState.type !== 'decompressing') { active = pluralize('device', currentFlashState.active); } // NOTE: There is usually a short time period between the `isFlashing()` // property being set, and the flashing actually starting, which // might cause some non-sense flashing state logs including // `undefined` values. debouncedLog(outdent({ newline: ' ' })` ${_.capitalize(currentFlashState.type)} ${active}, ${currentFlashState.percentage}% at ${(currentFlashState.speed || 0).toFixed(2)} MB/s (total ${(currentFlashState.speed * currentFlashState.active).toFixed(2)} MB/s) ${eta} with ${pluralize('failed device', currentFlashState.failed)} `); }); /** * @summary The radix used by USB ID numbers */ const USB_ID_RADIX = 16; /** * @summary The expected length of a USB ID number */ const USB_ID_LENGTH = 4; /** * @summary Convert a USB id (e.g. product/vendor) to a string * * @example * console.log(usbIdToString(2652)) * > '0x0a5c' */ function usbIdToString(id: number): string { return `0x${_.padStart(id.toString(USB_ID_RADIX), USB_ID_LENGTH, '0')}`; } /** * @summary Product ID of BCM2708 */ const USB_PRODUCT_ID_BCM2708_BOOT = 0x2763; /** * @summary Product ID of BCM2710 */ const USB_PRODUCT_ID_BCM2710_BOOT = 0x2764; /** * @summary Compute module descriptions */ const COMPUTE_MODULE_DESCRIPTIONS: _.Dictionary<string> = { [USB_PRODUCT_ID_BCM2708_BOOT]: 'Compute Module 1', [USB_PRODUCT_ID_BCM2710_BOOT]: 'Compute Module 3', }; async function driveIsAllowed(drive: { devicePath: string; device: string; raw: string; }) { const driveBlacklist = (await settings.get('driveBlacklist')) || []; return !( driveBlacklist.includes(drive.devicePath) || driveBlacklist.includes(drive.device) || driveBlacklist.includes(drive.raw) ); } type Drive = | sdk.sourceDestination.BlockDevice | sdk.sourceDestination.UsbbootDrive | sdk.sourceDestination.DriverlessDevice; function prepareDrive(drive: Drive) { if (drive instanceof sdk.sourceDestination.BlockDevice) { // @ts-ignore (BlockDevice.drive is private) return drive.drive; } else if (drive instanceof sdk.sourceDestination.UsbbootDrive) { // This is a workaround etcher expecting a device string and a size // @ts-ignore drive.device = drive.usbDevice.portId; drive.size = null; // @ts-ignore drive.progress = 0; drive.disabled = true; drive.on('progress', (progress) => { updateDriveProgress(drive, progress); }); return drive; } else if (drive instanceof sdk.sourceDestination.DriverlessDevice) { const description = COMPUTE_MODULE_DESCRIPTIONS[ drive.deviceDescriptor.idProduct.toString() ] || 'Compute Module'; return { device: `${usbIdToString( drive.deviceDescriptor.idVendor, )}:${usbIdToString(drive.deviceDescriptor.idProduct)}`, displayName: 'Missing drivers', description, mountpoints: [], isReadOnly: false, isSystem: false, disabled: true, icon: 'warning', size: null, link: 'https://www.raspberrypi.org/documentation/hardware/computemodule/cm-emmc-flashing.md', linkCTA: 'Install', linkTitle: 'Install missing drivers', linkMessage: outdent` Would you like to download the necessary drivers from the Raspberry Pi Foundation? This will open your browser. Once opened, download and run the installer from the "Windows Installer" section to install the drivers `, }; } } function setDrives(drives: _.Dictionary<DrivelistDrive>) { availableDrives.setDrives(_.values(drives)); } function getDrives() { return _.keyBy(availableDrives.getDrives(), 'device'); } async function addDrive(drive: Drive) { const preparedDrive = prepareDrive(drive); if (!(await driveIsAllowed(preparedDrive))) { return; } const drives = getDrives(); drives[preparedDrive.device] = preparedDrive; setDrives(drives); } function removeDrive(drive: Drive) { if ( drive instanceof sdk.sourceDestination.BlockDevice && // @ts-ignore BlockDevice.drive is private isSourceDrive(drive.drive, getImage()) ) { // Deselect the image if it was on the drive that was removed. // This will also deselect the image if the drive mountpoints change. deselectImage(); } const preparedDrive = prepareDrive(drive); const drives = getDrives(); delete drives[preparedDrive.device]; setDrives(drives); } function updateDriveProgress( drive: sdk.sourceDestination.UsbbootDrive, progress: number, ) { const drives = getDrives(); // @ts-ignore const driveInMap = drives[drive.device]; if (driveInMap) { // @ts-ignore drives[drive.device] = { ...driveInMap, progress }; setDrives(drives); } } driveScanner.on('attach', addDrive); driveScanner.on('detach', removeDrive); driveScanner.on('error', (error) => { // Stop the drive scanning loop in case of errors, // otherwise we risk presenting the same error over // and over again to the user, while also heavily // spamming our error reporting service. driveScanner.stop(); return exceptionReporter.report(error); }); driveScanner.start(); let popupExists = false; window.addEventListener('beforeunload', async (event) => { if (!flashState.isFlashing() || popupExists) { analytics.logEvent('Close application', { isFlashing: flashState.isFlashing(), }); return; } // Don't close window while flashing event.returnValue = false; // Don't open any more popups popupExists = true; analytics.logEvent('Close attempt while flashing'); try { const confirmed = await osDialog.showWarning({ confirmationLabel: 'Yes, quit', rejectionLabel: 'Cancel', title: 'Are you sure you want to close Etcher?', description: messages.warning.exitWhileFlashing(), }); if (confirmed) { analytics.logEvent('Close confirmed while flashing', { flashInstanceUuid: flashState.getFlashUuid(), }); // This circumvents the 'beforeunload' event unlike // electron.remote.app.quit() which does not. electron.remote.process.exit(EXIT_CODES.SUCCESS); } analytics.logEvent('Close rejected while flashing', { applicationSessionUuid, flashingWorkflowUuid, }); popupExists = false; } catch (error) { exceptionReporter.report(error); } }); export async function main() { await ledsInit(); ReactDOM.render( React.createElement(MainPage), document.getElementById('main'), // callback to set the correct zoomFactor for webviews as well async () => { const fullscreen = await settings.get('fullscreen'); const width = fullscreen ? window.screen.width : window.outerWidth; try { electron.webFrame.setZoomFactor(width / settings.DEFAULT_WIDTH); } catch (err) { // noop } }, ); }
apache-2.0
yurloc/guvnor
guvnor-structure/guvnor-structure-backend/src/main/java/org/guvnor/structure/backend/config/watch/ConfigServiceWatchServiceExecutor.java
311
package org.guvnor.structure.backend.config.watch; import org.uberfire.java.nio.file.WatchKey; public interface ConfigServiceWatchServiceExecutor { void execute( final WatchKey watchKey, final long localLastModifiedValue, final AsyncWatchServiceCallback callback); }
apache-2.0
weld/core
tests-arquillian/src/test/java/org/jboss/weld/tests/extensions/lifecycle/processBeanAttributes/notfired/ProcessBeanAttributesNotFiredTest.java
3394
/* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.tests.extensions.lifecycle.processBeanAttributes.notfired; import static org.junit.Assert.assertFalse; import java.lang.reflect.Type; import java.security.Principal; import jakarta.enterprise.context.Conversation; import jakarta.enterprise.event.Event; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.Decorator; import jakarta.enterprise.inject.spi.EventMetadata; import jakarta.enterprise.inject.spi.Extension; import jakarta.enterprise.inject.spi.InjectionPoint; import jakarta.enterprise.inject.spi.Interceptor; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import jakarta.transaction.UserTransaction; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.BeanArchive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.weld.test.util.Utils; import org.jboss.weld.tests.category.Integration; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; /** * @author <a href="mailto:mluksa@redhat.com">Marko Luksa</a> */ @RunWith(Arquillian.class) @Category(Integration.class) public class ProcessBeanAttributesNotFiredTest { @Deployment public static Archive<?> getDeployment() { return ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(ProcessBeanAttributesNotFiredTest.class)) .addClasses(Foo.class, MyExtension.class) .addAsServiceProvider(Extension.class, MyExtension.class); } @Test public void testProcessBeanAttributesNotFiredForProgrammaticallyAddedBeans() { assertFalse("ProcessBeanAttributes was called for built-in bean", MyExtension.observedNames.contains(MyExtension.PROGRAMMATICALLY_ADDED_BEAN_NAME)); } @Test public void testProcessBeanAttributesNotFiredForBuiltInBeans() { final Type[] types = new Type[] {Instance.class, Bean.class, Event.class, EventMetadata.class, InjectionPoint.class, BeanManager.class, Decorator.class, Interceptor.class, UserTransaction.class, Principal.class, HttpServletRequest.class, HttpSession.class, Conversation.class, ServletContext.class }; for (Type type : types) { assertFalse("ProcessBeanAttributes was called for built-in bean " + type, MyExtension.observedTypes.contains(type)); } } }
apache-2.0
yibome/yibo-library
src/main/java/net/dev123/mblog/tencent/TencentUserAdaptor.java
5869
package net.dev123.mblog.tencent; import static net.dev123.commons.util.ParseUtil.getInt; import static net.dev123.commons.util.ParseUtil.getLong; import static net.dev123.commons.util.ParseUtil.getRawString; import java.util.ArrayList; import java.util.Date; import net.dev123.commons.PagableList; import net.dev123.commons.ServiceProvider; import net.dev123.commons.util.ParseUtil; import net.dev123.commons.util.StringUtil; import net.dev123.entity.Gender; import net.dev123.exception.ExceptionCode; import net.dev123.exception.LibException; import net.dev123.mblog.entity.Status; import net.dev123.mblog.entity.User; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * TencentUserAdaptor * * @version * @author 马庆升 * @time 2010-8-30 下午03:58:58 */ public class TencentUserAdaptor { /** * 从JSON字符串创建User对象 * * @param jsonString * JSON字符串 * @return User对象 * @throws LibException */ public static User createUser(String jsonString) throws LibException { try { JSONObject json = new JSONObject(jsonString); return createUser(json); } catch (JSONException e) { throw new LibException(ExceptionCode.JSON_PARSE_ERROR, e); } } /** * 从JSON字符串创建User对象列表 * * @param jsonString * JSON字符串 * @return User对象列表 * @throws LibException */ public static PagableList<User> createPagableUserList(String jsonString) throws LibException { try { if ("[]".equals(jsonString) || "{}".equals(jsonString)) { return new PagableList<User>(0, 0, 0); } JSONObject json = new JSONObject(jsonString); int hasNext = ParseUtil.getInt("hasNext", json); long nextCursor = 1L; // 下一页 long previousCursor = 2L; // 上一页 if (hasNext == 1) { //数据已拉取完毕 nextCursor = 0L; } JSONArray jsonList = null; if (json.has("info") && !"null".equals(json.getString("info"))) { jsonList = json.getJSONArray("info"); } else { jsonList = new JSONArray(); } int size = jsonList.length(); PagableList<User> userList = new PagableList<User>(size, previousCursor, nextCursor); for (int i = 0; i < size; i++) { userList.add(createUser(jsonList.getJSONObject(i))); } return userList; } catch (JSONException e) { throw new LibException(ExceptionCode.JSON_PARSE_ERROR, e); } } /** * 从JSON字符串创建User对象列表 * * @param jsonString * JSON字符串 * @return User对象列表 * @throws LibException */ public static ArrayList<User> createUserList(String jsonString) throws LibException { try { if ("[]".equals(jsonString) || "{}".equals(jsonString)) { return new ArrayList<User>(0); } JSONObject json = new JSONObject(jsonString); if (!json.has("info")) { return new ArrayList<User>(0); } JSONArray jsonList = json.getJSONArray("info"); int hasNext = ParseUtil.getInt("hasnext", json); long nextCursor = 1L; // 下一页 long previousCursor = 2L; // 上一页 if (hasNext == 1) { //数据已拉取完毕 nextCursor = 0; } int size = jsonList.length(); PagableList<User> userList = new PagableList<User>(size, previousCursor, nextCursor); for (int i = 0; i < size; i++) { userList.add(createUser(jsonList.getJSONObject(i))); } return userList; } catch (JSONException e) { throw new LibException(ExceptionCode.JSON_PARSE_ERROR, e); } } /** * 从JSON对象创建User对象,包级别访问权限控制 * * @param json * JSON对象 * @return User对象 * @throws LibException */ static User createUser(JSONObject json) throws LibException { try { User user = new User(); user.setId(getRawString("name", json)); user.setName(getRawString("name", json)); user.setScreenName(getRawString("nick", json)); user.setLocation(getRawString("location", json)); user.setDescription(getRawString("introduction", json)); user.setContributorsEnabled(false); String head = getRawString("head", json); if (StringUtil.isNotEmpty(head)) { user.setProfileImageUrl(head + "/50"); } user.setUrl(null); user.setProtected(false); user.setGeoEnabled(false); user.setVerified(getInt("isvip", json) == 1); user.setFollowersCount(getInt("fansnum", json)); user.setFriendsCount(getInt("idolnum", json)); user.setCreatedAt(null); user.setFavouritesCount(0); user.setStatusesCount(getInt("tweetnum", json)); user.setFollowing(getInt("ismyidol", json) == 1); user.setFollowedBy(getInt("ismyfans", json) == 1); user.setBlocking(getInt("ismyblack", json) == 1); user.setGender(Gender.UNKNOW); if (!json.isNull("sex")) { int gender = getInt("sex", json); switch (gender) { case 0: user.setGender(Gender.UNKNOW); break; case 1: user.setGender(Gender.MALE); break; case 2: user.setGender(Gender.FEMALE); break; default: break; } } if (!json.isNull("tweet")) { JSONArray tweets = json.getJSONArray("tweet"); JSONObject tweet = tweets.getJSONObject(0); Status status = new Status(); status.setText(getRawString("text", tweet)); status.setSource(getRawString("from", tweet)); status.setCreatedAt(new Date(getLong("timestamp", tweet) * 1000L)); status.setId(getRawString("id", tweet)); status.setServiceProvider(ServiceProvider.Tencent); user.setStatus(status); } user.setServiceProvider(ServiceProvider.Tencent); return user; } catch (JSONException e) { throw new LibException(ExceptionCode.JSON_PARSE_ERROR, e); } } }
apache-2.0
GwtMaterialDesign/gwt-material-addins
src/main/java/gwt/material/design/addins/client/masonry/events/RemoveCompleteEvent.java
1806
/* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2017 GwtMaterialDesign * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package gwt.material.design.addins.client.masonry.events; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HasHandlers; import com.google.gwt.user.client.ui.Widget; /** * Fired when masonry removes an item. * * @author kevzlou7979 */ public class RemoveCompleteEvent extends GwtEvent<RemoveCompleteEvent.RemoveCompleteHandler> { public interface RemoveCompleteHandler extends EventHandler { void onRemoveComplete(RemoveCompleteEvent event); } private Widget target; public static final Type<RemoveCompleteHandler> TYPE = new Type<>(); public RemoveCompleteEvent(Widget target) { this.target = target; } public static void fire(HasHandlers source, Widget target) { source.fireEvent(new RemoveCompleteEvent(target)); } @Override public Type<RemoveCompleteHandler> getAssociatedType() { return TYPE; } public Widget getTarget() { return target; } @Override protected void dispatch(RemoveCompleteHandler handler) { handler.onRemoveComplete(this); } }
apache-2.0
SparklingComet/FakeTrollPlus
src/main/java/org/shanerx/faketrollplus/commands/Fakedeop.java
1934
/* * Copyright 2016-2017 SparklingComet @ http://shanerx.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.shanerx.faketrollplus.commands; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.shanerx.faketrollplus.FakeTrollPlus; import org.shanerx.faketrollplus.utils.Message; public class Fakedeop implements CommandExecutor { private FakeTrollPlus plugin; public Fakedeop(final FakeTrollPlus instance) { plugin = instance; } @Override public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) { if (!Message.verifyCommandSender(cmd, sender, "faketroll.fakedeop", Message.getBool("fake-deop.enable"), () -> args.length != 1)) { return false; } final Player target = plugin.getTarget(args[0]); if (target == null) { sender.sendMessage(Message.PREFIX + Message.getString("invalid-target")); return false; } if (!(sender instanceof Player)) { target.sendMessage(Message.col("&7&o[Server: De-opped " + target.getName() + "]")); return false; } target.sendMessage(Message.col("&7&o[" + sender.getName() + ": De-opped " + target.getName() + "]")); sender.sendMessage(Message.PREFIX + Message.getString("fake-deop.sender").replace("%player%", target.getName())); return true; } }
apache-2.0
google/android-uiconductor
frontend/src/app/constants/jstree.ts
2026
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** Data format for jstree events(action parameter) */ export interface JsTreeAction { node: JsTreeInternalNode; event?: {type?: string}; } /** Single node data coming from jstree._model.data */ export interface JsTreeInternalNode { text: string; id: string; children: string[]; original: JsTreeNode; } /** Tree data coming from jstree._model.data */ export interface JsTreeInternal { [index: string]: JsTreeInternalNode; } /** JSON data coming from backend. */ export declare interface TreeNode { value: string; id: string; emitLoadNextLevel: boolean; additionalData?: string[]; children?: TreeNode[]; } /** Declared state of a jstree node. */ export interface JsTreeState { opened?: boolean; disabled?: boolean; selected?: boolean; } /** Key value interface for extracting xml node information */ export interface NodeAttribute { name: string; value?: string; } /** Interface used to pass new node data to test_explorer */ export interface NodeParentPair { parentId: string; node: JsTreeNode; } /** Object expected by jstree library. */ export class JsTreeNode { icon: string = 'fa fa-folder'; state: JsTreeState = {'opened': true}; children: JsTreeNode[] = []; additionalData?: string[]; attributes?: NodeAttribute[]; constructor( public text: string, readonly id: string, public isFolder = true) { if (!isFolder) { this.icon = 'fa fa-file-code-o'; } } }
apache-2.0
oboehm/jfachwert
src/test/java/de/jfachwert/pruefung/LuhnVerfahrenTest.java
2245
/* * Copyright (c) 2018 by Oliver Boehm * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * (c)reated 11.12.2018 by oboehm (ob@oasd.de) */ package de.jfachwert.pruefung; import de.jfachwert.PruefzifferVerfahren; import org.junit.Test; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Unit-Tests fuer {@link LuhnVerfahren}-Klasse. Die Ergebnisse wurden dabei * mit http://www.ee.unb.ca/cgi-bin/tervo/luhn.pl ueberprueft. * * @author oboehm */ public final class LuhnVerfahrenTest extends AbstractPruefzifferVerfahrenTest<String> { private static final PruefzifferVerfahren<String> MOD10 = new LuhnVerfahren(); /** * Hierueber wird das Pruefziffer-Verfahren fuer den Test erwartet. * * @return Pruefzifferverfahren zum Testen */ protected PruefzifferVerfahren<String> getPruefzifferVerfahren() { return MOD10; } /** * Zum Testen des Pruefzifferverfahrens brauchen wir einen Wert, der * gueltig sein sollte. * * @return ein gueltiger Wert */ @Override protected String getValidWert() { return "260326822"; } @Test public void testIsInvalid() { assertFalse(MOD10.isValid("500")); } @Test public void testPruefzifferOnly() { assertFalse(MOD10.isValid("5")); } /** * Dieser Testfalls stammt aus der Pruefung der KassenkIK mit der IK-Nummer * "108018132" (AOK Baden Wuerttemberg). */ @Test public void testGetPruefziffer() { String nummer = "8018132"; assertEquals("2", MOD10.getPruefziffer(nummer)); assertTrue(MOD10.isValid(nummer)); } }
apache-2.0
typesafe-query/typesafe-query
typesafe-query-core/src/main/java/com/github/typesafe_query/meta/ComparableDBColumn.java
2070
/** * */ package com.github.typesafe_query.meta; import com.github.typesafe_query.query.Exp; import com.github.typesafe_query.query.Order; import com.github.typesafe_query.query.Param; import com.github.typesafe_query.query.TypesafeQuery; /** * @author Takahiko Sato(MOSA architect Inc.) * */ public interface ComparableDBColumn<T extends Comparable<? super T>> extends DBColumn<T>{ //--->conversions <C extends ComparableDBColumn<T>> C coalesce(C c); <C extends ComparableDBColumn<T>> C coalesce(T t); //--->expressions Exp gt(ComparableDBColumn<T> c); Exp gt(T t); Exp gt(Param p); Exp gt(TypesafeQuery subQuery); Exp lt(ComparableDBColumn<T> c); Exp lt(T t); Exp lt(Param p); Exp lt(TypesafeQuery subQuery); Exp ge(ComparableDBColumn<T> c); Exp ge(T t); Exp ge(Param p); Exp ge(TypesafeQuery subQuery); Exp le(ComparableDBColumn<T> c); Exp le(T t); Exp le(Param p); Exp le(TypesafeQuery subQuery); Exp isNull(); Exp isNotNull(); Exp between(ComparableDBColumn<T> from,ComparableDBColumn<T> to); Exp between(ComparableDBColumn<T> from,T to); Exp between(T from,ComparableDBColumn<T> to); Exp between(T from,T to); Exp between(ComparableDBColumn<T> from,Param to); Exp between(Param from,T to); Exp between(Param from,ComparableDBColumn<T> to); Exp between(T from,Param to); Exp between(Param from,Param to); Exp notBetween(ComparableDBColumn<T> from,ComparableDBColumn<T> to); Exp notBetween(ComparableDBColumn<T> from,T to); Exp notBetween(T from,ComparableDBColumn<T> to); Exp notBetween(T from,T to); Exp notBetween(ComparableDBColumn<T> from,Param to); Exp notBetween(Param from,T to); Exp notBetween(Param from,ComparableDBColumn<T> to); Exp notBetween(T from,Param to); Exp notBetween(Param from,Param to); @SuppressWarnings("unchecked") Exp in(T...ts); Exp in(TypesafeQuery query); @SuppressWarnings("unchecked") Exp notIn(T...ts); Exp notIn(TypesafeQuery query); //---->orders Order asc(); Order desc(); ComparableDBColumn<T> any(); ComparableDBColumn<T> some(); ComparableDBColumn<T> all(); }
apache-2.0
perandersson/everstore-java-adapter
vanilla/src/main/java/everstore/vanilla/protocol/parsers/CommitResponseParser.java
948
package everstore.vanilla.protocol.parsers; import everstore.api.JournalSize; import everstore.vanilla.io.EndianAwareInputStream; import everstore.vanilla.protocol.Header; import everstore.vanilla.protocol.MessageResponse; import everstore.vanilla.protocol.messages.CommitTransactionResponse; import java.io.IOException; public final class CommitResponseParser implements ResponseParser { public final class State extends ResponseState { public State(MessageResponse response) { super(response, true); } } @Override public ResponseState parse(Header header, EndianAwareInputStream stream) throws IOException { final boolean success = stream.readIntAsBool(); final JournalSize size = new JournalSize(stream.readInt()); return new State(new CommitTransactionResponse(success, size)); } public static final CommitResponseParser INSTANCE = new CommitResponseParser(); }
apache-2.0
cedral/aws-sdk-cpp
aws-cpp-sdk-worklink/source/model/UpdateDevicePolicyConfigurationResult.cpp
1405
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/worklink/model/UpdateDevicePolicyConfigurationResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::WorkLink::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; UpdateDevicePolicyConfigurationResult::UpdateDevicePolicyConfigurationResult() { } UpdateDevicePolicyConfigurationResult::UpdateDevicePolicyConfigurationResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } UpdateDevicePolicyConfigurationResult& UpdateDevicePolicyConfigurationResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { AWS_UNREFERENCED_PARAM(result); return *this; }
apache-2.0
cedral/aws-sdk-cpp
aws-cpp-sdk-sagemaker/source/model/CreateUserProfileResult.cpp
1444
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/sagemaker/model/CreateUserProfileResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::SageMaker::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; CreateUserProfileResult::CreateUserProfileResult() { } CreateUserProfileResult::CreateUserProfileResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } CreateUserProfileResult& CreateUserProfileResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("UserProfileArn")) { m_userProfileArn = jsonValue.GetString("UserProfileArn"); } return *this; }
apache-2.0
Tyesb/lovetothinkserv
matcher/Migrations/201412162206586_deploy.cs
642
namespace matcher.Migrations { using System; using System.Data.Entity.Migrations; public partial class deploy : DbMigration { public override void Up() { //DropPrimaryKey("dbo.TMatching"); //AddColumn("dbo.TMatching", "id", c => c.Int(nullable: false, identity: true)); //AddPrimaryKey("dbo.TMatching", "id"); } public override void Down() { //DropPrimaryKey("dbo.TMatching"); //DropColumn("dbo.TMatching", "id"); //AddPrimaryKey("dbo.TMatching", new[] { "TweetID1", "TweetID2" }); } } }
apache-2.0
gistia/slackbot
robots/project/project.go
20049
package robots import ( "errors" "fmt" "regexp" "strconv" "strings" "github.com/gistia/slackbot/db" "github.com/gistia/slackbot/mavenlink" "github.com/gistia/slackbot/pivotal" "github.com/gistia/slackbot/robots" "github.com/gistia/slackbot/utils" ) type bot struct { handler utils.SlackHandler } func init() { handler := utils.NewSlackHandler("Project", ":books:") s := &bot{handler: handler} robots.RegisterRobot("project", s) robots.RegisterRobot("pr", s) } func (r bot) Run(p *robots.Payload) string { go r.DeferredAction(p) return "" } func (r bot) DeferredAction(p *robots.Payload) { ch := utils.NewCmdHandler(p, r.handler, "project") ch.Handle("list", r.list) ch.Handle("link", r.link) ch.Handle("stories", r.stories) ch.Handle("mystories", r.myStories) ch.Handle("setsprint", r.setSprint) ch.Handle("addsprint", r.addSprint) ch.Handle("setchannel", r.setChannel) ch.Handle("addstory", r.addStory) ch.Handle("start", r.startTask) ch.Handle("create", r.create) ch.Handle("rename", r.rename) ch.Handle("members", r.members) ch.Handle("addmember", r.addmember) ch.Handle("unassigned", r.unassigned) ch.Handle("assign", r.assign) ch.Handle("estimate", r.estimate) ch.Handle("addtime", r.addTime) ch.HandleDefault(r.list) ch.Process(p.Text) } func (r bot) addTime(p *robots.Payload, cmd utils.Command) error { args, err := cmd.ParseArgs("mavenlink-id", "time-in-hours") if err != nil { return err } mvnID, timeStr := args[0], args[1] hours, err := strconv.ParseFloat(timeStr, 64) if err != nil { return err } mvn, err := mavenlink.NewFor(p.UserName) if err != nil { return err } story, err := mvn.GetStory(mvnID) if err != nil { return err } minutes := int(hours * 60) _, err = mvn.AddTimeEntry(story, minutes) if err != nil { return err } r.handler.Send(p, fmt.Sprintf("Added *%.1f* hours to story *%s - %s*", hours, story.Id, story.Title)) return nil } func (r bot) estimate(p *robots.Payload, cmd utils.Command) error { args, err := cmd.ParseArgs("pivotal-id", "estimate") if err != nil { return err } pvtId, estimate := args[0], args[1] pvt, err := pivotal.NewFor(p.UserName) if err != nil { return err } // pvtStory, err := pvt.GetStory(pvtId) // if err != nil { // return err // } // numEstimate, err := strconv.Atoi(estimate) if err != nil { return err } story, err := pvt.EstimateStory(pvtId, numEstimate) if err != nil { return err } s := "Story successfully updated:\n" r.handler.SendWithAttachments(p, s, []robots.Attachment{ utils.FmtAttachment("", story.Name, story.Url, ""), }) return nil } func (r bot) myStories(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) var pr *db.Project var err error if name == "" { pr, err = db.GetProjectByChannel(p.ChannelName) } else { pr, err = db.GetProjectByName(name) } if err != nil { return err } if pr == nil { r.handler.Send(p, "Missing project name.") return nil } pvt, err := pivotal.NewFor(p.UserName) if err != nil { return err } user, err := db.GetUserByName(p.UserName) if err != nil { return err } filter := map[string]string{ "owned_by": user.StrPivotalId(), "state": "started,finished", } stories, err := pvt.FilteredStories(pr.StrPivotalId(), filter) if err != nil { return err } if len(stories) < 1 { r.handler.Send(p, "No open stories in project *"+pr.Name+"* for *"+p.UserName+"*") return nil } str := "Current stories in project *" + pr.Name + "* for *" + p.UserName + "*:\n" atts := []robots.Attachment{} for _, s := range stories { fallback := fmt.Sprintf("%d - %s - %s\n", s.Id, s.Name, s.State) title := fmt.Sprintf("%d - %s\n", s.Id, s.Name) a := utils.FmtAttachment(fallback, title, s.Url, s.State) atts = append(atts, a) } r.handler.SendWithAttachments(p, str, atts) return nil } func (r bot) unassigned(p *robots.Payload, cmd utils.Command) error { res, err := cmd.ParseArgs("project") if err != nil { return err } name := res[0] pr, err := getProject(name) if err != nil { return err } pvt, err := pivotal.NewFor(p.UserName) if err != nil { return err } msg := "Unassigned stories for *" + name + "*:\n" stories, err := pvt.GetUnassignedStories(pr.StrPivotalId()) if len(stories) < 1 { r.handler.Send(p, "No unassigned stories for *"+name+"*") return nil } for _, s := range stories { msg += fmt.Sprintf("%d - %s\n", s.Id, s.Name) } r.handler.Send(p, msg) return nil } func (r bot) assign(p *robots.Payload, cmd utils.Command) error { res, err := cmd.ParseArgs("pivotal-story-id", "username") if err != nil { return err } storyId, username := res[0], res[1] pvt, err := pivotal.NewFor(p.UserName) if err != nil { return err } user, err := db.GetUserByName(username) if err != nil { return err } if user == nil { return errors.New("User *" + username + "* not found") } story, err := pvt.AssignStory(storyId, *user.PivotalId) if err != nil { return err } s := "Story successfully updated:\n" r.handler.SendWithAttachments(p, s, []robots.Attachment{ utils.FmtAttachment("", story.Name, story.Url, ""), }) return nil } func (r bot) addmember(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) if name == "" { err := errors.New( "Missing project name. Use `!project addmember <project> <username>`") return err } username := cmd.Arg(1) if name == "" { err := errors.New( "Missing user name. Use `!project addmember <project> <username>`") return err } pr, err := getProject(name) if err != nil { return err } pvt, err := pivotal.NewFor(p.UserName) if err != nil { return err } if pr == nil { r.handler.Send(p, "Project *"+name+"* not found") return nil } user, err := db.GetUserByName(username) if pr == nil { r.handler.Send(p, "Project *"+name+"* not found") return nil } if user == nil { r.handler.Send(p, "User *"+username+"* not found") return nil } _, err = pvt.CreateProjectMembership(pr.StrPivotalId(), *user.PivotalId, "member") if err != nil { return err } r.handler.Send(p, "New member *"+username+"* added to *"+name+"*") return nil } func (r bot) members(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) if name == "" { err := errors.New( "Missing project name. Use `!project addtask <project> <task-name>`") return err } pr, err := getProject(name) if err != nil { return err } pvt, err := pivotal.NewFor(p.UserName) if err != nil { return err } if pr == nil { r.handler.Send(p, "Project *"+name+"* not found") return nil } members, err := pvt.GetProjectMemberships(pr.StrPivotalId()) if err != nil { return err } s := "Pivotal members for project *" + pr.Name + "*:\n" for _, m := range members { s += fmt.Sprintf("%d - %s\n", m.Person.Id, m.Person.Name) } r.handler.Send(p, s) return nil } func (r bot) rename(p *robots.Payload, cmd utils.Command) error { old := cmd.Arg(0) new := cmd.Arg(1) if new == "" || old == "" { r.handler.Send(p, "You need to provide the old and new name. Usage: `!project rename <old-name> <new-name>`") return nil } pr, err := db.GetProjectByName(old) if err != nil { return err } if pr == nil { r.handler.Send(p, "Project *"+old+"* not found.") return nil } pr.Name = new err = db.UpdateProject(*pr) if err != nil { return err } r.handler.Send(p, "Project *"+old+"* renamed to *"+new+"*") return nil } func (r bot) create(p *robots.Payload, cmd utils.Command) error { alias := cmd.Arg(0) if alias == "" { r.handler.Send(p, "Missing project alias. Usage: `!project createproject <alias> <long-name>`") return nil } name := cmd.StrFrom(1) if name == "" { r.handler.Send(p, "Missing project name. Usage: `!project createproject <alias> <long-name>`") return nil } mvn, err := mavenlink.NewFor(p.UserName) if err != nil { return err } pvt, err := pivotal.NewFor(p.UserName) if err != nil { return err } pvtProject := pivotal.Project{ Name: name, // PointScale: "1,2,3,4,5,6,7,8,9,10,16,20", } pvtNewProject, err := pvt.CreateProject(pvtProject) if err != nil { return err } mvnProject := mavenlink.Project{ Title: name, Description: fmt.Sprintf("[pvt:%s]", pvtNewProject.Id), CreatorRole: "maven", } mvnNewProject, err := mvn.CreateProject(mvnProject) if err != nil { return err } if mvnNewProject == nil { return errors.New("Mavenlink returned a nil project") } pvtNewProject.Description = "[mvn:" + mvnNewProject.Id + "]" pvtNewProject, err = pvt.UpdateProject(*pvtNewProject) if err != nil { return err } err = r.makeLink(p, alias, mvnNewProject.Id, strconv.FormatInt(pvtNewProject.Id, 10)) if err != nil { return err } r.handler.Send(p, "Project *"+name+"* created on Pivotal and Mavenlink.") return nil } func (r bot) startTask(p *robots.Payload, cmd utils.Command) error { // pr, err := getProject(cmd.Arg(0)) // if err != nil { // return err // } mvn, err := mavenlink.NewFor(p.UserName) if err != nil { return err } pvt, err := pivotal.NewFor(p.UserName) if err != nil { return err } if storyId := cmd.Arg(0); storyId != "" { pvtStory, err := pvt.GetStory(storyId) if err != nil { return err } pvtStory, err = pvt.SetStoryState(pvtStory.GetStringId(), "started") if err != nil { return err } if mvnId := pvtStory.GetMavenlinkId(); mvnId != "" { mvnStory, err := mvn.GetStory(mvnId) if err != nil { return err } fmt.Printf(" ** Got story: %+v\n", mvnStory) mvnStory.State = "started" mvnStory, err = mvn.SetStoryState(mvnStory.Id, "started") if err != nil { return err } } r.handler.Send(p, "Story *"+pvtStory.Name+"* started") return nil } // stories, err := mvn.ChildStories(pr.MvnSprintStoryId) // if err != nil { // return err // } // r.handler.Send(p, "Click the story you want to start on *"+pr.Name+"*:") // url := os.Getenv("APP_URL") // atts := mavenlink.CustomFormatStories(stories, url+"selection/startTask/") // for _, a := range atts { // r.handler.SendWithAttachments(p, "", []robots.Attachment{a}) // } return nil } func getProject(name string) (*db.Project, error) { pr, err := db.GetProjectByName(name) if err != nil { return nil, err } if pr == nil { err := errors.New("Project *" + name + "* not found.") return nil, err } return pr, nil } func (r bot) addStory(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) if name == "" { err := errors.New( "Missing project name. Use `!project addtask <project> [type:<story-type>] <task-name>`") return err } storyType := cmd.Param("type") if storyType == "" { storyType = "feature" } storyName := strings.Join(cmd.ArgsFrom(1), " ") if storyName == "" { err := errors.New( "Missing story name. Use `!project addtask <project> <task-name>`") return err } pr, err := getProject(name) if err != nil { return err } mvn, err := mavenlink.NewFor(p.UserName) if err != nil { return err } pvt, err := pivotal.NewFor(p.UserName) if err != nil { return err } pvtStory := pivotal.Story{ Name: storyName, ProjectId: pr.PivotalId, Type: storyType, } pvtNewStory, err := pvt.CreateStory(pvtStory) if err != nil { return err } desc := fmt.Sprintf("[pvt:%d]", pvtNewStory.Id) mvnStory := mavenlink.Story{ Title: storyName, Description: desc, ParentId: pr.MvnSprintStoryId, WorkspaceId: strconv.FormatInt(pr.MavenlinkId, 10), StoryType: "task", } mvnNewStory, err := mvn.CreateStory(mvnStory) if err != nil { return err } tmpStory := pivotal.Story{ Id: pvtNewStory.Id, Description: "[mvn:" + mvnNewStory.Id + "]", } pvtNewStory, err = pvt.UpdateStory(tmpStory) if err != nil { return err } pvtAtt := utils.FmtAttachment( fmt.Sprintf("- Pivotal %d - %s\n", pvtNewStory.Id, pvtNewStory.Name), fmt.Sprintf("Pivotal %d - %s\n", pvtNewStory.Id, pvtNewStory.Name), pvtNewStory.Url, "") mvnAtt := utils.FmtAttachment( fmt.Sprintf("- Mavenlink %s - %s\n", mvnNewStory.Id, mvnNewStory.Title), fmt.Sprintf("Mavenlink %s - %s\n", mvnNewStory.Id, mvnNewStory.Title), mvnNewStory.URL(), "") s := "Stories successfully added:\n" r.handler.SendWithAttachments(p, s, []robots.Attachment{pvtAtt, mvnAtt}) return nil } func (r bot) addSprint(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) if name == "" { r.handler.Send(p, "Missing project name") return nil } ps, err := db.GetProjectByName(name) if err != nil { return err } mvn, err := mavenlink.NewFor(p.UserName) if err != nil { return err } sprintName := cmd.StrFrom(1) if sprintName == "" { sprintName = "Sprint 1" if ps.MvnSprintStoryId != "" { s, err := mvn.GetStory(ps.MvnSprintStoryId) if err != nil { return err } matched, err := regexp.MatchString(`Sprint [\d]+`, s.Title) if err != nil { return err } if matched { num, err := strconv.ParseInt(strings.Split(s.Title, " ")[1], 10, 64) if err != nil { return err } sprintName = fmt.Sprintf("Sprint %d", (num + 1)) } } } s := mavenlink.Story{ Title: sprintName, WorkspaceId: strconv.FormatInt(ps.MavenlinkId, 10), StoryType: "milestone", } ns, err := mvn.CreateStory(s) if err != nil { return err } fmt.Printf("%+v\n", ns) ps.MvnSprintStoryId = ns.Id err = db.UpdateProject(*ps) if err != nil { return err } s = *ns r.handler.Send(p, "Added new sprint to *"+ps.Name+"*: "+s.Id+" - "+s.Title) return nil } func (r bot) setChannel(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) if name == "" { r.handler.Send(p, "Missing project name") return nil } ps, err := db.GetProjectByName(name) if err != nil { return err } ps.Channel = p.ChannelName if err := db.UpdateProject(*ps); err != nil { return err } r.handler.Send(p, "Project *"+name+"* assigned to *"+ps.Channel+"* channel.") return nil } func (r bot) stories(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) var ps *db.Project var err error if name != "" { ps, err = db.GetProjectByName(name) if err != nil { return err } if ps == nil { r.handler.Send(p, "Project *"+name+"* not found") return nil } } if ps == nil { ps, err = db.GetProjectByChannel(p.ChannelName) if err != nil { return err } if ps == nil { r.handler.Send(p, "Missing project name") return nil } } mvn, err := mavenlink.NewFor(p.UserName) if err != nil { return err } sprint, err := mvn.GetStory(ps.MvnSprintStoryId) if err != nil { return err } stories, err := mvn.GetChildStories(ps.MvnSprintStoryId) if err != nil { return err } r.handler.Send(p, "Mavenlink stories for *"+ps.Name+"*, sprint *"+sprint.Title+"*:") atts := mavenlink.FormatStories(stories) for _, a := range atts { r.handler.SendWithAttachments(p, "", []robots.Attachment{a}) } var totalEstimated int64 var totalLogged int64 for _, s := range stories { totalEstimated += s.TimeEstimateInMinutes totalLogged += s.LoggedBillableTimeInMinutes } s := "" if totalEstimated > 0 { s += fmt.Sprintf("Total estimated: %s", utils.FormatHour(totalEstimated)) } if totalLogged > 0 { if totalEstimated > 0 { s += " - " } s += fmt.Sprintf("Total logged: %s", utils.FormatHour(totalLogged)) } if s != "" { r.handler.Send(p, s) } return nil } func (r bot) setSprint(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) if name == "" { r.handler.Send(p, "Missing project name") return nil } id := cmd.Arg(1) if id == "" { r.handler.Send(p, "Missing mavenlink story id to assign as current sprint") return nil } ps, err := db.GetProjectByName(name) if err != nil { return err } mvn, err := mavenlink.NewFor(p.UserName) if err != nil { return err } mvnStory, err := mvn.GetStory(id) if err != nil { return err } if mvnStory == nil { r.handler.Send(p, "Story with id "+id+" wasn't found") return nil } fmt.Println("Got story", mvnStory.Id) ps.MvnSprintStoryId = mvnStory.Id if err := db.UpdateProject(*ps); err != nil { return err } r.handler.Send(p, "Project *"+name+"* updated.") return nil } func (r bot) list(p *robots.Payload, cmd utils.Command) error { ps, err := db.GetProjects() if err != nil { return err } if ps == nil || len(ps) < 1 { r.handler.Send(p, "There are no linked projects currently. Use `link` command to add one.") return nil } s := "" for _, pr := range ps { fmt.Println(" *** Project", pr) fmt.Println(" Starting PVT", strconv.FormatInt(pr.PivotalId, 10)) pvtPr, err := r.getPvtProject(p, strconv.FormatInt(pr.PivotalId, 10)) if err != nil { return err } fmt.Println(" Starting MVN", strconv.FormatInt(pr.MavenlinkId, 10)) mvnPr, err := r.getMvnProject(p, strconv.FormatInt(pr.MavenlinkId, 10)) if err != nil { return err } sprintInfo := "" if pr.MvnSprintStoryId != "" { mvn, err := mavenlink.NewFor(p.UserName) if err != nil { return err } fmt.Println(" Starting Story", pr.MvnSprintStoryId) sprintStory, err := mvn.GetStory(pr.MvnSprintStoryId) fmt.Println(" Sotry result", err) if err != nil { fmt.Println(" Returning error:", err) return err } sprintInfo = "Current sprint: " + sprintStory.Title + "\n" fmt.Println(" Finished Story") } s += fmt.Sprintf( "*%s*\nPivotal %d - %s to Mavenlink %s - %s\n%s", pr.Name, pvtPr.Id, pvtPr.Name, mvnPr.Id, mvnPr.Title, sprintInfo) fmt.Println(" Finished Project") } fmt.Println(" Sending response:", s) r.handler.Send(p, s) return nil } func (r bot) link(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) if name == "" { r.handler.Send(p, "Missing project name. Usage: !project link name mvn:id pvt:id") return nil } mvn := cmd.Param("mvn") if mvn == "" { r.handler.Send(p, "Missing mavenlink project. Usage: !project link name mvn:id pvt:id") return nil } pvt := cmd.Param("pvt") if pvt == "" { r.handler.Send(p, "Missing pivotal project. Usage: !project link name mvn:id pvt:id") return nil } err := r.makeLink(p, name, mvn, pvt) if err != nil { return err } return nil } func (r bot) getMvnProject(p *robots.Payload, id string) (*mavenlink.Project, error) { mvn, err := mavenlink.NewFor(p.UserName) if err != nil { return nil, err } return mvn.GetProject(id) } func (r bot) getPvtProject(p *robots.Payload, id string) (*pivotal.Project, error) { pvt, err := pivotal.NewFor(p.UserName) if err != nil { return nil, err } return pvt.GetProject(id) } func (r bot) makeLink(p *robots.Payload, name string, mvnId string, pvtId string) error { prj, err := db.GetProjectByName(name) if err != nil { return err } if prj != nil { r.handler.Send(p, fmt.Sprintf("Project with name %s already exists.", name)) return nil } mvnProject, err := r.getMvnProject(p, mvnId) if err != nil { msg := fmt.Sprintf("Error loading mavenlink project %s: %s", mvnId, err.Error()) return errors.New(msg) } pvtProject, err := r.getPvtProject(p, pvtId) if err != nil { msg := fmt.Sprintf("Error loading pivotal project %s: %s", pvtId, err.Error()) return errors.New(msg) } mvnInt, err := strconv.ParseInt(mvnProject.Id, 10, 64) if err != nil { return err } pvtInt := pvtProject.Id project := db.Project{ Name: name, MavenlinkId: mvnInt, PivotalId: pvtInt, CreatedBy: p.UserName, } err = db.CreateProject(project) if err != nil { return err } r.handler.Send(p, fmt.Sprintf("Project %s linked %s - %s and %d - %s", name, mvnProject.Id, mvnProject.Title, pvtProject.Id, pvtProject.Name)) return err } func (r bot) sendError(p *robots.Payload, err error) { msg := fmt.Sprintf("Error running project command: %s\n", err.Error()) r.handler.Send(p, msg) } func (r bot) Description() (description string) { return "Project bot\n\tUsage: !project <command>\n" }
apache-2.0
LIP-Computing/os_restful_client
os_restfulcli/tests/test_controller/test_parser.py
801
# -*- coding: utf-8 -*- # Copyright 2015 LIP - Lisbon # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import testtools from os_restfulcli.tests.test_controller.fakes import * class TestCaseAPIController(testtools.TestCase): def setUp(self): super(TestCaseAPIController, self).setUp()
apache-2.0
nguerrera/roslyn
src/VisualStudio/LiveShare/Impl/Shims/FindImplementationsHandlerShim.cs
3637
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LiveShare.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.LiveShare { internal class FindImplementationsHandlerShim : AbstractLiveShareHandlerShim<TextDocumentPositionParams, object> { private readonly IThreadingContext _threadingContext; public FindImplementationsHandlerShim(IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers, IThreadingContext threadingContext) : base(requestHandlers, Methods.TextDocumentImplementationName) { _threadingContext = threadingContext; } public override async Task<object> HandleAsync(TextDocumentPositionParams param, RequestContext<Solution> requestContext, CancellationToken cancellationToken) { // TypeScript requires this call to be on the UI thread. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return await base.HandleAsyncPreserveThreadContext(param, requestContext, cancellationToken).ConfigureAwait(false); } } [ExportLspRequestHandler(LiveShareConstants.RoslynContractName, Methods.TextDocumentImplementationName)] [Obsolete("Used for backwards compatibility with old liveshare clients.")] internal class RoslynFindImplementationsHandlerShim : FindImplementationsHandlerShim { [ImportingConstructor] public RoslynFindImplementationsHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers, IThreadingContext threadingContext) : base(requestHandlers, threadingContext) { } } [ExportLspRequestHandler(LiveShareConstants.CSharpContractName, Methods.TextDocumentImplementationName)] internal class CSharpFindImplementationsHandlerShim : FindImplementationsHandlerShim { [ImportingConstructor] public CSharpFindImplementationsHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers, IThreadingContext threadingContext) : base(requestHandlers, threadingContext) { } } [ExportLspRequestHandler(LiveShareConstants.VisualBasicContractName, Methods.TextDocumentImplementationName)] internal class VisualBasicFindImplementationsHandlerShim : FindImplementationsHandlerShim { [ImportingConstructor] public VisualBasicFindImplementationsHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers, IThreadingContext threadingContext) : base(requestHandlers, threadingContext) { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentImplementationName)] internal class TypeScriptFindImplementationsHandlerShim : FindImplementationsHandlerShim { [ImportingConstructor] public TypeScriptFindImplementationsHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers, IThreadingContext threadingContext) : base(requestHandlers, threadingContext) { } } }
apache-2.0
nuttycom/commons-pipeline
src/main/java/org/apache/commons/pipeline/stage/ExtendedBaseStage.java
24780
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pipeline.stage; import java.lang.management.ManagementFactory; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.StandardMBean; import org.apache.commons.lang.time.StopWatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.math.stat.descriptive.SynchronizedDescriptiveStatistics; import org.apache.commons.pipeline.Feeder; import org.apache.commons.pipeline.Stage; import org.apache.commons.pipeline.StageContext; import org.apache.commons.pipeline.StageException; /** * Base class for pipeline stages. Keeps track of performance statistics and allows * for collection and adjustment via JMX (optional) * * Cannot extend BaseStage because it marks the emit methods as final. * * @author mzsanford */ public abstract class ExtendedBaseStage implements Stage, ExtendedBaseStageMBean { /** Minimum percentage of blocking before we report per-branch stats. */ private static final float BRANCH_BLOCK_THRESHOLD = 1.0f; /** Default size of the moving-window average statistics */ private static final int DEFAULT_DESCRIPTIVE_STATS_WINDOW_SIZE = 100; /** Default queue name when reporting statistics */ private static final String DEFAULT_QUEUE_NAME = "[DefaultQueue]"; /** Default number of objects after which a status message is logged */ private static final int DEFAULT_STATUS_INTERVAL = 1000; protected final Log log = LogFactory.getLog( getClass() ); protected StageContext stageContext; private Feeder downstreamFeeder; private String stageName; private final AtomicLong objectsReceived = new AtomicLong(0); private final AtomicLong unhandledExceptions = new AtomicLong(0); private final AtomicLong totalServiceTime = new AtomicLong(0); private final AtomicLong totalEmitTime = new AtomicLong(0); private final AtomicLong totalEmits = new AtomicLong(0); private final Map<String, AtomicLong> emitTimeByBranch = new HashMap<String, AtomicLong>(); private int currentStatWindowSize = DEFAULT_DESCRIPTIVE_STATS_WINDOW_SIZE; private SynchronizedDescriptiveStatistics serviceTimeStatistics; private long statusInterval = DEFAULT_STATUS_INTERVAL; private Integer statusBatchSize = 1; private boolean collectBranchStats = false; private boolean preProcessed = false; // prevent recursion. private boolean postProcessed = false; // prevent recursion. private boolean jmxEnabled = true; /** * Class name for status message. Needed because java.util.logging only * reports the base class name. */ private final String className = getClass().getSimpleName(); /** * ThreadLocal sum of time spent waiting on blocked queues during the current process call. */ protected static ThreadLocal<AtomicLong> emitTotal = new ThreadLocal<AtomicLong>() { protected synchronized AtomicLong initialValue() { return new AtomicLong(); } }; /** * ThreadLocal sum of time spent waiting on blocked queues during the current process call by queue name. */ protected static ThreadLocal<Map<String, AtomicLong>> threadLocalEmitBranchTime = new ThreadLocal<Map<String, AtomicLong>>() { protected synchronized Map<String, AtomicLong> initialValue() { return new HashMap<String, AtomicLong>(); } }; /** * ThreadLocal count of emit calls during the current process call. */ protected static ThreadLocal<AtomicInteger> emitCount = new ThreadLocal<AtomicInteger>() { protected synchronized AtomicInteger initialValue() { return new AtomicInteger(); } }; /** * ThreadLocal formatter since they are not thread safe. */ protected static ThreadLocal<NumberFormat> floatFormatter = new ThreadLocal<NumberFormat>() { protected synchronized NumberFormat initialValue() { return new DecimalFormat("##0.000"); } }; public ExtendedBaseStage() { // Empty constructor provided for future use. } public void init( StageContext context ) { this.stageContext = context; if (jmxEnabled) { enableJMX(context); } } @SuppressWarnings("unchecked") private final void enableJMX(StageContext context) { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); if (mbs != null) { // Try to build a unique JMX name. StringBuilder sb = new StringBuilder("org.apache.commons.pipeline:"); sb.append("class=").append(className); if (stageName != null) { sb.append(",name=").append(stageName); } try { ObjectName name = new ObjectName(sb.toString()); if (mbs.isRegistered(name)) { log.info("JMX Overlap. Multiple instances of '" + name + "'. Only one will be registered."); } else { Class mbeanInterface = ExtendedBaseStageMBean.class; try { // Find out if the stage has a more specific MBean. Reflection can be slow // but this operation is pretty fast. Not to mention it's only done at startup. Class[] interfaces = getClass().getInterfaces(); for (int i=0 ; i < interfaces.length; i++) { Class current = interfaces[i]; // Only use interfaces that extend ExtendedBaseStageMBean to maintain a minimum // amount of functionality. if (current != ExtendedBaseStageMBean.class && ExtendedBaseStageMBean.class.isAssignableFrom(current)) { mbeanInterface = current; break; } } } catch (Exception e) { // In the event of security or cast exceptions, default back to base. log.info("Reflection error while checking for JMX interfaces."); // Reset in the off chance it got hosed. mbeanInterface = ExtendedBaseStageMBean.class; } StandardMBean mbean = new StandardMBean(this, mbeanInterface); mbs.registerMBean(mbean, name); log.info("JMX MBean registered: " + name.toString() + " (" + mbeanInterface.getSimpleName() + ")"); } } catch (Exception e) { log.warn("Failed to register with JMX server",e); } } } /** * Called when a stage has been created but before the first object is * sent to the stage for processing. Subclasses * should use the innerPreprocess method, which is called by this method. * * @see org.apache.commons.pipeline.Stage#preprocess() */ public final void preprocess() throws StageException { if ( !preProcessed ) { serviceTimeStatistics = new SynchronizedDescriptiveStatistics(); serviceTimeStatistics.setWindowSize(currentStatWindowSize); innerPreprocess(); } preProcessed = true; } public final void process( Object obj ) throws StageException { objectsReceived.incrementAndGet(); StopWatch stopWatch = new StopWatch(); stopWatch.start(); try { this.innerProcess( obj ); } catch (Exception e) { // Hate to catch Exception, but don't want anything killing off the thread // and hanging the pipeline. log.error("Uncaught exception in " + className + ": " + e.getMessage(), e); unhandledExceptions.incrementAndGet(); } stopWatch.stop(); long totalTime = stopWatch.getTime(); totalServiceTime.addAndGet(totalTime); // I hate to synchronize anything in the base class, but this // call should be very fast and is not thread safe. serviceTimeStatistics.addValue(totalTime); // Use ThreadLocals so that the stats only reflect process // calls that have completed. Otherwise the emit times can // exceed the process times. totalEmits.addAndGet(emitCount.get().intValue()); totalEmitTime.addAndGet(emitTotal.get().longValue()); emitCount.remove(); emitTotal.remove(); if (collectBranchStats) { for (Map.Entry<String, AtomicLong> entry : threadLocalEmitBranchTime.get().entrySet()) { if (emitTimeByBranch.containsKey(entry.getKey())) { emitTimeByBranch.get(entry.getKey()).addAndGet(entry.getValue().longValue()); } else { // Race condition. containsKey could return false and another thread could insert // here. We can synchronize here and we will very rarely hit this block. Only the first // time each queue is accessed. synchronized (emitTimeByBranch) { // Double check for the race condition. if (emitTimeByBranch.containsKey(entry.getKey())) { emitTimeByBranch.get(entry.getKey()).addAndGet(entry.getValue().longValue()); } else { emitTimeByBranch.put(entry.getKey(), new AtomicLong(entry.getValue().longValue())); } } } } threadLocalEmitBranchTime.remove(); } if ( objectsReceived.longValue() % statusInterval == 0 ) { logStatus(); } } /** * Convenience method to feed the specified object to the next stage downstream. */ public final void emit( Object obj ) { if ( log.isDebugEnabled() ) { log.debug( this.getClass() + " is emitting object " + obj ); } if ( this.downstreamFeeder == null ) { synchronized (this) { // Lazy init the default feeder. this.downstreamFeeder = stageContext.getDownstreamFeeder( this ); } } feed( DEFAULT_QUEUE_NAME, downstreamFeeder, obj ); } /** * Convenience method to feed the specified object to the first stage of the specified branch. */ public final void emit( String branch, Object obj ) { Feeder feeder = this.stageContext.getBranchFeeder( branch ); feed( branch, feeder, obj ); } private void feed(String name, Feeder feeder, Object obj ) { if ( feeder == null ) { // The pipeline code should never allow this to happen. String objectType = ( obj != null ? obj.getClass().getSimpleName() : "null" ); log.error( "Ignoring attempt to emit " + objectType + " object to invalid feeder" ); return; } StopWatch emitWatch = new StopWatch(); emitWatch.start(); // Pass the emitted object to the next stage (default or branch) feeder.feed( obj ); emitWatch.stop(); // Use ThreadLocal variables so the emit totals do not // go up until the process call completes. emitTotal.get().addAndGet( emitWatch.getTime() ); emitCount.get().incrementAndGet(); if (collectBranchStats) { if (! threadLocalEmitBranchTime.get().containsKey(name)) { AtomicLong currentTotal = new AtomicLong(emitWatch.getTime()); threadLocalEmitBranchTime.get().put(name, currentTotal); } else { threadLocalEmitBranchTime.get().get(name).addAndGet(emitWatch.getTime()); } } } /** * Called when a stage has completed all processing. Subclasses * should use the innerPostprocess method, which is called by this method. * * @see org.apache.commons.pipeline.Stage#postprocess() */ public final void postprocess() throws StageException { if ( !postProcessed ) { logStatus(); innerPostprocess(); } postProcessed = true; } public void release() { // No-op implementation to fulfill interface } public abstract void innerProcess( Object obj ) throws StageException; public void innerPreprocess() throws StageException { // No-op default implementation. } public void innerPostprocess() throws StageException { // No-op default implementation. } /** * Class-specific status message. Null or empty status' will be ignored. */ public abstract String status(); public void logStatus() { String logMessage = getStatusMessage(); log.info(logMessage); } /** * @return Log message including both base stage and class specific stats. */ public String getStatusMessage() { StringBuilder sb = new StringBuilder( 512 ); NumberFormat formatter = floatFormatter.get(); float serviceTime = ( totalServiceTime.floatValue() / 1000.0f ); float emitTime = ( totalEmitTime.floatValue() / 1000.0f ); float netServiceTime = ( serviceTime - emitTime ); float emitPercentage = 0.0f; float emitFloat = totalEmits.floatValue(); float recvFloat = objectsReceived.floatValue(); if (recvFloat > 0) { emitPercentage = (emitFloat / recvFloat)*100.0f; } sb.append( "\n\t === " ).append( className ).append( " Generic Stats === " ); if (statusBatchSize > 1) { sb.append("\n\tStatus Batch Size (all /obj and /sec include this): ").append(statusBatchSize); } sb.append( "\n\tTotal objects received:" ).append( objectsReceived ); sb.append( "\n\tTotal unhandled exceptions:" ).append( unhandledExceptions ); sb.append( "\n\tTotal objects emitted:" ).append( totalEmits ); if (emitFloat > 0) { sb.append(" (").append(formatter.format(emitPercentage)).append("%)"); } sb.append( "\n\tTotal gross processing time (sec):" ) .append( formatter.format( serviceTime ) ); sb.append( "\n\tTotal emit blocked time (sec):" ) .append( formatter.format( emitTime ) ); sb.append( "\n\tTotal net processing time (sec):" ) .append( formatter.format( netServiceTime ) ); float avgServiceTime = 0; float avgEmitTime = 0; float avgNetServiceTime = 0; if ( objectsReceived.longValue() > 0 ) { avgServiceTime = ( serviceTime / objectsReceived.floatValue()/statusBatchSize ); avgEmitTime = ( emitTime / objectsReceived.floatValue()/statusBatchSize ); avgNetServiceTime = ( netServiceTime / objectsReceived.floatValue()/statusBatchSize ); } sb.append( "\n\tAverage gross processing time (sec/obj):" ) .append( formatter.format( avgServiceTime ) ); sb.append( "\n\tAverage emit blocked time (sec/obj):" ) .append( formatter.format( avgEmitTime ) ); sb.append( "\n\tAverage net processing time (sec/obj):" ) .append( formatter.format( avgNetServiceTime ) ); if (serviceTimeStatistics != null) { long count = serviceTimeStatistics.getN(); if (count > 0) { double avgMillis = getCurrentServiceTimeAverage()/(float)statusBatchSize; sb.append( "\n\tAverage gross processing time in last ") .append(count) .append(" (sec/obj):" ) .append( formatter.format( avgMillis/1000 ) ); } } float grossThroughput = 0; if ( avgServiceTime > 0 ) { grossThroughput = ( 1.0f / avgServiceTime ); } float netThroughput = 0; if ( avgNetServiceTime > 0 ) { netThroughput = ( 1.0f / avgNetServiceTime ); } sb.append( "\n\tGross throughput (obj/sec):" ) .append( formatter.format( grossThroughput ) ); sb.append( "\n\tNet throughput (obj/sec):" ) .append( formatter.format( netThroughput ) ); float percWorking = 0; float percBlocking = 0; if ( serviceTime > 0 ) { percWorking = ( netServiceTime / serviceTime ) * 100; percBlocking = ( emitTime / serviceTime ) * 100; } sb.append( "\n\t% time working:" ).append( formatter.format( percWorking ) ); sb.append( "\n\t% time blocking:" ).append( formatter.format( percBlocking ) ); // No need to output for a non-branching stage or if there was very little // blocking (as defined in the constant) if (collectBranchStats && emitTimeByBranch.size() > 1 && percBlocking >= BRANCH_BLOCK_THRESHOLD) { try { for (Map.Entry<String, AtomicLong> entry : emitTimeByBranch.entrySet()) { float branchBlockSec = (entry.getValue().floatValue()/1000.0f); float branchBlockPerc = (branchBlockSec/emitTime) * 100; sb.append("\n\t\t% branch ").append(entry.getKey()).append(":").append(formatter.format(branchBlockPerc)); } } catch (RuntimeException e) { // Synchronizing would be slow, ConcurrentMod is possible but unlikely since the map is // only modified the first time a stage is emitted to so just catch and // log it. No need to stop all processing over a reporting failure. sb.append("\n\t\tproblem getting per-branch stats: ").append(e.getMessage()); } } String stageSpecificStatus = this.status(); if ( stageSpecificStatus != null && stageSpecificStatus.length() > 0 ) { sb.append( "\n\t === " ) .append( className ) .append( " Specific Stats === " ); sb.append( stageSpecificStatus ); } return sb.toString(); } protected String formatTotalTimeStat( String name, AtomicLong totalTime ) { return formatTotalTimeStat( name, totalTime.longValue() ); } protected String formatTotalTimeStat( String name, long totalTime ) { if ( name == null || totalTime < 0 ) { return ""; } NumberFormat formatter = floatFormatter.get(); StringBuilder sb = new StringBuilder(); // Total processing time minus calls to emit. float totalSec = totalTime / 1000.0f; float average = 0; if ( getObjectsReceived() > 0 ) { average = totalSec / getObjectsReceived() / (float)statusBatchSize; } if ( log.isDebugEnabled() ) { sb.append( "\n\tTotal " ) .append( name ) .append( " processing time (sec):" ) .append( formatter.format( totalSec ) ); } sb.append( "\n\tAverage " ) .append( name ) .append( " processing time (sec/obj):" ) .append( formatter.format( average ) ); if ( log.isDebugEnabled() && average > 0 ) { float throughput = ( 1.0f ) / average * (float)statusBatchSize; sb.append( "\n\tThroughput for " ) .append( name ) .append( " (obj/sec):" ) .append( formatter.format( throughput ) ); } return sb.toString(); } protected String formatCounterStat( String name, AtomicInteger count ) { return formatCounterStat(name, count.get()); } protected String formatCounterStat( String name, AtomicLong count ) { return formatCounterStat(name, count.get()); } protected String formatCounterStat( String name, long count ) { if ( name == null || count < 0 || getObjectsReceived() <= 0) { return ""; } NumberFormat formatter = floatFormatter.get(); StringBuilder sb = new StringBuilder(); float perc = ((float)count*(float)statusBatchSize/(float)getObjectsReceived())*100.0f; sb.append( "\n\tNumber of " ) .append( name ) .append( " (" ) .append( formatter.format(perc) ) .append( "%) :") .append( count ); return sb.toString(); } /** * @see org.apache.commons.pipeline.ExtendedBaseStageMBean#getStatusInterval() */ public Long getStatusInterval() { return Long.valueOf(statusInterval); } /** * @see org.apache.commons.pipeline.ExtendedBaseStageMBean#setStatusInterval(long) */ public void setStatusInterval( Long statusInterval ) { this.statusInterval = statusInterval; } public Integer getStatusBatchSize() { return statusBatchSize; } public void setStatusBatchSize(Integer statusBatchSize) { this.statusBatchSize = statusBatchSize; } /** * @see org.apache.commons.pipeline.ExtendedBaseStageMBean#getObjectsReceived() */ public long getObjectsReceived() { return objectsReceived.longValue(); } /** * @see org.apache.commons.pipeline.ExtendedBaseStageMBean#getTotalServiceTime() */ public long getTotalServiceTime() { return totalServiceTime.longValue(); } /** * @see org.apache.commons.pipeline.ExtendedBaseStageMBean#getTotalEmitTime() */ public long getTotalEmitTime() { return totalEmitTime.longValue(); } /** * @see org.apache.commons.pipeline.ExtendedBaseStageMBean#getTotalEmits() */ public long getTotalEmits() { return totalEmits.longValue(); } /** * @see org.apache.commons.pipeline.ExtendedBaseStageMBean#getCollectBranchStats() */ public Boolean getCollectBranchStats() { return collectBranchStats; } /** * @see org.apache.commons.pipeline.ExtendedBaseStageMBean#setCollectBranchStats(Boolean) */ public void setCollectBranchStats(Boolean collectBranchStats) { this.collectBranchStats = collectBranchStats; } public Integer getCurrentStatWindowSize() { return Integer.valueOf(currentStatWindowSize); } public void setCurrentStatWindowSize(Integer newStatWindowSize) { if (serviceTimeStatistics != null && newStatWindowSize != this.currentStatWindowSize) { synchronized (serviceTimeStatistics) { serviceTimeStatistics.setWindowSize(newStatWindowSize); } } this.currentStatWindowSize = newStatWindowSize; } public String getStageName() { return stageName; } public void setStageName(String name) { this.stageName = name; } public boolean isJmxEnabled() { return jmxEnabled; } public void setJmxEnabled(boolean jmxEnabled) { this.jmxEnabled = jmxEnabled; } /** * Returns a moving average of the service time. This does not yet take into account time spent * calling emit, nor does it return minimum, maximum or other statistical information at this time. * * @return Average time to process the last <code>currentStatWindowSize</code> objects. */ public double getCurrentServiceTimeAverage() { double avg = -1.0d; // Hate to synchronize in the base class, but this should be very quick. avg = serviceTimeStatistics.getMean(); return avg; } }
apache-2.0
google/google-java-format
core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java
25841
/* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.googlejavaformat.java; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.googlejavaformat.java.JavaFormatterOptions.Style; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** Tests for {@link ImportOrderer}. */ @RunWith(Enclosed.class) public class ImportOrdererTest { /** Tests for import ordering in Google style. */ @RunWith(Parameterized.class) public static class GoogleStyle { private final String input; private final String reordered; public GoogleStyle(String input, String reordered) { this.input = input; this.reordered = reordered; } @Parameters(name = "{index}: {0}") public static Collection<Object[]> parameters() { // Inputs are provided as three-dimensional arrays. Each element of the outer array is a test // case. It consists of two arrays of lines. The first array of lines is the test input, and // the second one is the expected output. If the second array has a single element starting // with !! then it is expected that ImportOrderer will throw a FormatterException with that // message. // // If a line ends with \ then we remove the \ and don't append a \n. That allows us to check // some parsing edge cases. String[][][] inputsOutputs = { { // Empty input produces empty output. {}, // {} }, { { "foo", "bar", }, { "foo", "bar", }, }, { { "package foo;", // "", "import com.google.first.Bar;", "", "public class Blim {}", }, { "package foo;", // "", "import com.google.first.Bar;", "", "public class Blim {}", }, }, { { "package foo;", "", "import com.google.first.Bar;", "import com.google.second.Foo;", "", "public class Blim {}", }, { "package foo;", "", "import com.google.first.Bar;", "import com.google.second.Foo;", "", "public class Blim {}", }, }, { { "package foo;", "", "import com.google.second.Foo;", "import com.google.first.Bar;", "", "public class Blim {}", }, { "package foo;", "", "import com.google.first.Bar;", "import com.google.second.Foo;", "", "public class Blim {}", }, }, { { "import java.util.Collection;", "// BUG: diagnostic contains", "import java.util.List;", "", "class B74235047 {}" }, { "import java.util.Collection;", "// BUG: diagnostic contains", "import java.util.List;", "", "class B74235047 {}" } }, { { "import java.util.Set;", "import java.util.Collection;", "// BUG: diagnostic contains", "import java.util.List;", "", "class B74235047 {}" }, { "import java.util.Collection;", "// BUG: diagnostic contains", "import java.util.List;", "import java.util.Set;", "", "class B74235047 {}" } }, { { "import java.util.List;", "// BUG: diagnostic contains", "import java.util.Set;", "import java.util.Collection;", "", "class B74235047 {}" }, { "import java.util.Collection;", "import java.util.List;", "// BUG: diagnostic contains", "import java.util.Set;", "", "class B74235047 {}" } }, { { "// BEGIN-STRIP", "import com.google.testing.testsize.MediumTest;", "import com.google.testing.testsize.MediumTestAttribute;", "// END-STRIP", "", "class B74235047 {}" }, { "// BEGIN-STRIP", "import com.google.testing.testsize.MediumTest;", "import com.google.testing.testsize.MediumTestAttribute;", "// END-STRIP", "", "class B74235047 {}" } }, { { "import com.google.testing.testsize.MediumTest; // Keep this import", "import com.google.testing.testsize.MediumTestAttribute; // Keep this import", "", "class B74235047 {}" }, { "import com.google.testing.testsize.MediumTest; // Keep this import", "import com.google.testing.testsize.MediumTestAttribute; // Keep this import", "", "class B74235047 {}" } }, { { "import java.util.Set;", "import java.util.List;", "", "// This comment doesn't get moved because of the blank line.", "", "class B74235047 {}" }, { "import java.util.List;", "import java.util.Set;", "", "// This comment doesn't get moved because of the blank line.", "", "class B74235047 {}" } }, { { "import b.B;", "// MOE: end_strip", "import c.C;", "// MOE: begin_strip", "import a.A;", "", "class B74235047 {}" }, { "import a.A;", "import b.B;", "// MOE: end_strip", "import c.C;", "// MOE: begin_strip", "", "class B74235047 {}" } }, { { // Check double semicolons "package foo;", "", "import com.google.second.Foo;;", "import com.google.first.Bar;;", "", "public class Blim {}", }, { "package foo;", "", "import com.google.first.Bar;", "import com.google.second.Foo;", "", "public class Blim {}", }, }, { { "package foo;", "", "import com.google.second.Foo;", "import com.google.first.Bar;", "import com.google.second.Foo;", "import com.google.first.Bar;", "", "public class Blim {}", }, { "package foo;", "", "import com.google.first.Bar;", "import com.google.second.Foo;", "", "public class Blim {}", }, }, { // Google style frowns on wildcard imports, but we handle them all the same. { "package foo;", "", "import com.google.second.*;", "import com.google.first.Bar;", "import com.google.first.*;", "", "public class Blim {}", }, { "package foo;", "", "import com.google.first.*;", "import com.google.first.Bar;", "import com.google.second.*;", "", "public class Blim {}", }, }, { { "package com.google.example;", "", "import com.google.common.base.Preconditions;", "", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "", "import java.util.List;", "", "import javax.annotation.Nullable;", "", "import static org.junit.Assert.fail;", "import static com.google.truth.Truth.assertThat;", "", "@RunWith(JUnit4.class)", "public class SomeTest {}", }, { "package com.google.example;", "", "import static com.google.truth.Truth.assertThat;", "import static org.junit.Assert.fail;", "", "import com.google.common.base.Preconditions;", "import java.util.List;", "import javax.annotation.Nullable;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "", "@RunWith(JUnit4.class)", "public class SomeTest {}", }, }, // we unindent imports, if we reorder them { { " import com.foo.Second;", // " import com.foo.First;", " public class Foo {}", }, { "import com.foo.First;", // "import com.foo.Second;", "", "public class Foo {}", } }, // Error cases { { "package com.google.example;", // "", "import\\", // \\ means there is no newline here. }, { "!!Unexpected token after import: ", } }, { { "package com.google.example;", // "", "import", }, { "!!Unexpected token after import: \n", } }, { { "package com.google.example;", // "", "import foo\\", }, { "!!Expected ; after import", } }, { { "package com.google.example;", // "", "import foo.\\", }, { "!!Could not parse imported name, at: ", } }, { { "import com.foo.Second;", "import com.foo.First;", "/* we don't support block comments", " between imports either */", "import com.foo.Third;", }, { "!!Imports not contiguous (perhaps a comment separates them?)", } }, { { "import com.foo.Second; /* no block comments after imports */", // "import com.foo.First;", }, { "!!Imports not contiguous (perhaps a comment separates them?)", } }, { { "import com.foo.Second;", "import com.foo.First;", "/* but we're not fooled by comments that look like imports:", "import com.foo.Third;", "*/", }, { "import com.foo.First;", "import com.foo.Second;", "", "/* but we're not fooled by comments that look like imports:", "import com.foo.Third;", "*/", } }, { { "import com . foo . Second ;", // syntactically valid, but we don't support it "import com.foo.First;", }, { "!!Expected ; after import", } }, { { "import com.abc.@;", // "import com.abc.@@;", }, { "!!Could not parse imported name, at: @", } }, { { "import com.abc.3;", // digits not syntactically valid "import com.abc.2;", }, { // .3 is a single token (a floating-point constant) "!!Expected ; after import", } }, { { "import com.foo.Second", // missing semicolon "import com.foo.First;", }, { "!!Expected ; after import", } }, { { "import com.foo.Second; import com.foo.First;", "class Test {}", }, { "import com.foo.First;", // "import com.foo.Second;", "", "class Test {}", } }, { { "import com.foo.Second; import com.foo.First; class Test {}", }, { "import com.foo.First;", // "import com.foo.Second;", "", "class Test {}", } }, { { "package p;", // "", "/** test */", "", "import a.A;", "", "/** test */", "", "class Test {}", }, { "package p;", // "", "/** test */", "", "import a.A;", "", "/** test */", "", "class Test {}", } }, { { "package p; import a.A; class Test {}", }, { "package p;", // "", "import a.A;", "", "class Test {}", } }, { { "package p;", "", "import java.lang.Bar;", "import java.lang.Baz;", ";", "import java.lang.Foo;", "", "interface Test {}", }, { "package p;", "", "import java.lang.Bar;", "import java.lang.Baz;", "import java.lang.Foo;", "", "interface Test {}", } } }; ImmutableList.Builder<Object[]> builder = ImmutableList.builder(); Arrays.stream(inputsOutputs).forEach(input -> builder.add(createRow(input))); return builder.build(); } @Test public void reorder() throws FormatterException { try { String output = ImportOrderer.reorderImports(input, Style.GOOGLE); assertWithMessage("Expected exception").that(reordered).doesNotMatch("^!!"); assertWithMessage(input).that(output).isEqualTo(reordered); } catch (FormatterException e) { if (!reordered.startsWith("!!")) { throw e; } assertThat(reordered).endsWith("\n"); assertThat(e) .hasMessageThat() .isEqualTo("error: " + reordered.substring(2, reordered.length() - 1)); } } } /** Tests for import ordering in AOSP style. */ @RunWith(Parameterized.class) public static class AospStyle { private final String input; private final String reordered; public AospStyle(String input, String reordered) { this.input = input; this.reordered = reordered; } @Parameters(name = "{index}: {0}") public static Collection<Object[]> parameters() { // Inputs are provided as three-dimensional arrays. Each element of the outer array is a test // case. It consists of two arrays of lines. The first array of lines is the test input, and // the second one is the expected output. If the second array has a single element starting // with !! then it is expected that ImportOrderer will throw a FormatterException with that // message. // // If a line ends with \ then we remove the \ and don't append a \n. That allows us to check // some parsing edge cases. String[][][] inputsOutputs = { // Capital letter before lowercase { { "package foo;", "", "import android.abC.Bar;", "import android.abc.Bar;", "public class Blim {}", }, { "package foo;", "", "import android.abC.Bar;", "import android.abc.Bar;", "", "public class Blim {}", } }, // Blank line between "com.android" and "com.anythingelse" { { "package foo;", "", "import com.android.Bar;", "import com.google.Bar;", "public class Blim {}", }, { "package foo;", "", "import com.android.Bar;", "", "import com.google.Bar;", "", "public class Blim {}", } }, // Rough ordering -- statics, android, third party, then java, with blank lines between // major groupings { { "package foo;", "", "import static net.Bar.baz;", "import static org.junit.Bar.baz;", "import static com.google.Bar.baz;", "import static java.lang.Bar.baz;", "import static junit.Bar.baz;", "import static javax.annotation.Bar.baz;", "import static android.Bar.baz;", "import net.Bar;", "import org.junit.Bar;", "import com.google.Bar;", "import java.lang.Bar;", "import junit.Bar;", "import javax.annotation.Bar;", "import android.Bar;", "public class Blim {}", }, { "package foo;", "", "import static android.Bar.baz;", "", "import static com.google.Bar.baz;", "", "import static junit.Bar.baz;", "", "import static net.Bar.baz;", "", "import static org.junit.Bar.baz;", "", "import static java.lang.Bar.baz;", "", "import static javax.annotation.Bar.baz;", "", "import android.Bar;", "", "import com.google.Bar;", "", "import junit.Bar;", "", "import net.Bar;", "", "import org.junit.Bar;", "", "import java.lang.Bar;", "", "import javax.annotation.Bar;", "", "public class Blim {}", } }, { { "package foo;", "", "import static java.first.Bar.baz;", "import static com.second.Bar.baz;", "import com.first.Bar;", "import static android.second.Bar.baz;", "import dalvik.first.Bar;", "import static dalvik.first.Bar.baz;", "import static androidx.second.Bar.baz;", "import java.second.Bar;", "import static com.android.second.Bar.baz;", "import static net.first.Bar.baz;", "import gov.second.Bar;", "import junit.second.Bar;", "import static libcore.second.Bar.baz;", "import static java.second.Bar.baz;", "import static net.second.Bar.baz;", "import static org.first.Bar.baz;", "import static dalvik.second.Bar.baz;", "import javax.first.Bar;", "import static javax.second.Bar.baz;", "import android.first.Bar;", "import android.second.Bar;", "import static javax.first.Bar.baz;", "import androidx.first.Bar;", "import static androidx.first.Bar.baz;", "import androidx.second.Bar;", "import com.android.first.Bar;", "import gov.first.Bar;", "import com.android.second.Bar;", "import dalvik.second.Bar;", "import static org.second.Bar.baz;", "import net.first.Bar;", "import libcore.second.Bar;", "import static android.first.Bar.baz;", "import com.second.Bar;", "import static gov.second.Bar.baz;", "import static gov.first.Bar.baz;", "import static junit.first.Bar.baz;", "import libcore.first.Bar;", "import junit.first.Bar;", "import javax.second.Bar;", "import static libcore.first.Bar.baz;", "import net.second.Bar;", "import static com.first.Bar.baz;", "import org.second.Bar;", "import static junit.second.Bar.baz;", "import java.first.Bar;", "import org.first.Bar;", "import static com.android.first.Bar.baz;", "public class Blim {}", }, { "package foo;", // "", "import static android.first.Bar.baz;", "import static android.second.Bar.baz;", "", "import static androidx.first.Bar.baz;", "import static androidx.second.Bar.baz;", "", "import static com.android.first.Bar.baz;", "import static com.android.second.Bar.baz;", "", "import static dalvik.first.Bar.baz;", "import static dalvik.second.Bar.baz;", "", "import static libcore.first.Bar.baz;", "import static libcore.second.Bar.baz;", "", "import static com.first.Bar.baz;", "import static com.second.Bar.baz;", "", "import static gov.first.Bar.baz;", "import static gov.second.Bar.baz;", "", "import static junit.first.Bar.baz;", "import static junit.second.Bar.baz;", "", "import static net.first.Bar.baz;", "import static net.second.Bar.baz;", "", "import static org.first.Bar.baz;", "import static org.second.Bar.baz;", "", "import static java.first.Bar.baz;", "import static java.second.Bar.baz;", "", "import static javax.first.Bar.baz;", "import static javax.second.Bar.baz;", "", "import android.first.Bar;", "import android.second.Bar;", "", "import androidx.first.Bar;", "import androidx.second.Bar;", "", "import com.android.first.Bar;", "import com.android.second.Bar;", "", "import dalvik.first.Bar;", "import dalvik.second.Bar;", "", "import libcore.first.Bar;", "import libcore.second.Bar;", "", "import com.first.Bar;", "import com.second.Bar;", "", "import gov.first.Bar;", "import gov.second.Bar;", "", "import junit.first.Bar;", "import junit.second.Bar;", "", "import net.first.Bar;", "import net.second.Bar;", "", "import org.first.Bar;", "import org.second.Bar;", "", "import java.first.Bar;", "import java.second.Bar;", "", "import javax.first.Bar;", "import javax.second.Bar;", "", "public class Blim {}", }, } }; ImmutableList.Builder<Object[]> builder = ImmutableList.builder(); Arrays.stream(inputsOutputs).forEach(input -> builder.add(createRow(input))); return builder.build(); } @Test public void reorder() throws FormatterException { try { String output = ImportOrderer.reorderImports(input, Style.AOSP); assertWithMessage("Expected exception").that(reordered).doesNotMatch("^!!"); assertWithMessage(input).that(output).isEqualTo(reordered); } catch (FormatterException e) { if (!reordered.startsWith("!!")) { throw e; } assertThat(reordered).endsWith("\n"); assertThat(e) .hasMessageThat() .isEqualTo("error: " + reordered.substring(2, reordered.length() - 1)); } } } private static Object[] createRow(String[][] inputAndOutput) { assertThat(inputAndOutput).hasLength(2); String[] input = inputAndOutput[0]; String[] output = inputAndOutput[1]; if (output.length == 0) { output = input; } Object[] row = { Joiner.on('\n').join(input) + '\n', // Joiner.on('\n').join(output) + '\n', }; // If a line ends with \ then we remove the \ and don't append a \n. That allows us to check // some parsing edge cases. row[0] = ((String) row[0]).replace("\\\n", ""); return row; } }
apache-2.0
dspjlj/wsp
src/com/jlj/dao/imp/WscorderproDaoImp.java
4776
package com.jlj.dao.imp; import java.sql.SQLException; import java.util.List; import javax.annotation.Resource; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Component; import com.jlj.dao.IWscorderproDao; import com.jlj.model.Wscorderpro; @Component("wscorderproDao") public class WscorderproDaoImp implements IWscorderproDao { private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } //保存一条记录 public void save(Wscorderpro wscorderpro) { this.hibernateTemplate.save(wscorderpro); } //删除一条记录 public void delete(Wscorderpro wscorderpro) { this.hibernateTemplate.delete(wscorderpro); } //根据ID删除一条记录 public void deleteById(int id) { this.hibernateTemplate.delete(this.loadById(id)); } //修改一条记录 public void update(Wscorderpro wscorderpro) { this.hibernateTemplate.update(wscorderpro); } //根据hql语句、条件、条件值修改某些记录 public void updateByHql(final String hql,final String[] paramNames,final Object[] values) { this.hibernateTemplate.execute(new HibernateCallback(){ public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query=session.createQuery(hql); for (int i = 0; i < paramNames.length; i++) { query.setParameter(paramNames[i], values[i]); } query.executeUpdate(); return null; } }); } //获得所有记录 public List<Wscorderpro> getWscorderpros() { return this.hibernateTemplate.loadAll(Wscorderpro.class); } //根据hql语句来查询所有记录 public List<Wscorderpro> queryList(String queryString) { return this.hibernateTemplate.find(queryString); } //根据hql、条件值查询某些记录 public List<Wscorderpro> getObjectsByCondition(String queryString, Object[] p) { return this.hibernateTemplate.find(queryString,p); } //根据hql语句、条件、条件值查询某些记录 public List<Wscorderpro> queryList(String queryString, String[] paramNames, Object[] values) { List list = this.hibernateTemplate.findByNamedParam(queryString, paramNames, values); return list; } //根据hql、id列表查询某些记录 public List<Wscorderpro> getObjectsByIdList(final String hql,final List<Integer> idList) { return this.hibernateTemplate.executeFind(new HibernateCallback(){ public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query=session.createQuery(hql); query.setParameterList("idList", idList); return query.list(); } }); } //根据hql语句、条件值、分页查询某些记录 public List<Wscorderpro> pageList(final String queryString,final Object[] p,final Integer page, final Integer size) { return this.hibernateTemplate.executeFind(new HibernateCallback(){ public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query=session.createQuery(queryString); if(p!=null&&p.length>0){ for (int i = 0; i < p.length; i++) { query.setParameter(i, p[i]); } } if(page!=null&&page>0&&size!=null&&size>0){ query.setFirstResult((page-1)*size).setMaxResults(size); } return query.list(); } }); } //根据hql、条件值获得一个唯一值 public int getUniqueResult(final String queryString,final Object[] p) { Session session=this.hibernateTemplate.getSessionFactory().getCurrentSession(); Query query= session.createQuery(queryString); if(p!=null&&p.length>0){ for (int i = 0; i < p.length; i++) { query.setParameter(i, p[i]); } } Object obj=query.uniqueResult(); return ((Long)obj).intValue(); } //根据id查询一条记录 public Wscorderpro loadById(int id) { return (Wscorderpro) this.hibernateTemplate.load(Wscorderpro.class, id); } //根据hql语句、条件、值来查询一条记录 public Wscorderpro queryByNamedParam(String queryString, String[] paramNames, Object[] values) { List list=this.hibernateTemplate.findByNamedParam(queryString, paramNames, values); return list.size()>0?(Wscorderpro)list.get(0):null; } //根据hql语句、条件值来查询是否存在该记录 public boolean checkClientExistsWithName(String queryString, Object[] p) { List list = this.hibernateTemplate.find(queryString,p); return list.size()>0 ? true : false; } }
apache-2.0
gogap/spirit
component_message.go
3507
package spirit import ( "bytes" "encoding/json" "strconv" "github.com/gogap/errors" "github.com/nu7hatch/gouuid" ) const ( ERROR_MSG_ADDR = "-100" ERROR_MSG_ADDR_INT int32 = -100 ) type MessageGraph map[string]MessageAddress func (p MessageGraph) AddAddress(addrs ...MessageAddress) int { lenAddr := 0 startIndex := len(p) + 1 if addrs != nil { lenAddr = len(addrs) for i, addr := range addrs { p[strconv.Itoa(i+startIndex)] = addr } } return lenAddr } func (p MessageGraph) AddAddressToHead(addrs ...MessageAddress) int { lAddr := len(addrs) if lAddr == 0 { return 0 } // move for k, v := range p { i, _ := strconv.Atoi(k) p[strconv.Itoa(i+lAddr)] = v } startIndex := 1 if addrs != nil { for i, addr := range addrs { p[strconv.Itoa(i+startIndex)] = addr } } return lAddr } func (p MessageGraph) SetErrorAddress(address MessageAddress) { p[ERROR_MSG_ADDR] = address } func (p MessageGraph) ClearErrorAddress() { if _, exist := p[ERROR_MSG_ADDR]; exist { delete(p, ERROR_MSG_ADDR) } } type ComponentMessage struct { id string graph MessageGraph currentGraphIndex int32 payload Payload hooksMetaData []MessageHookMetadata } func NewComponentMessage(graph MessageGraph, payload Payload) (message ComponentMessage, err error) { msgId := "" if payload.id == "" { if id, e := uuid.NewV4(); e != nil { err = ERR_UUID_GENERATE_FAILED.New(errors.Params{"err": e}) return } else { msgId = id.String() } payload.id = msgId } else { msgId = payload.id } message = ComponentMessage{ id: msgId, graph: graph, currentGraphIndex: 1, payload: payload, } return } func (p *ComponentMessage) Serialize() (data []byte, err error) { jsonMap := map[string]interface{}{ "id": p.id, "graph": p.graph, "current_graph_index": p.currentGraphIndex, "message_hooks_metadata": p.hooksMetaData, "payload": map[string]interface{}{ "id": p.id, "context": p.payload.context, "command": p.payload.command, "content": p.payload.content, "error": p.payload.err, }, } if data, err = json.Marshal(&jsonMap); err != nil { err = ERR_MESSAGE_SERIALIZE_FAILED.New(errors.Params{"err": err}) return } return } func (p *ComponentMessage) UnSerialize(data []byte) (err error) { var tmp struct { Id string `json:"id"` Graph MessageGraph `json:"graph"` CurrentGraphIndex int32 `json:"current_graph_index"` HooksMetaData []MessageHookMetadata `json:"message_hooks_metadata"` Payload struct { Id string `json:"id,omitempty"` Context ComponentContext `json:"context,omitempty"` Command ComponentCommands `json:"command,omitempty"` Content interface{} `json:"content,omitempty"` Error Error `json:"error,omitempty"` } `json:"payload"` } decoder := json.NewDecoder(bytes.NewReader(data)) decoder.UseNumber() if err = decoder.Decode(&tmp); err != nil { return } p.id = tmp.Id p.graph = tmp.Graph p.currentGraphIndex = tmp.CurrentGraphIndex p.payload = Payload{ id: tmp.Payload.Id, context: tmp.Payload.Context, command: tmp.Payload.Command, content: tmp.Payload.Content, err: tmp.Payload.Error, } p.hooksMetaData = tmp.HooksMetaData return } func (p *ComponentMessage) Id() string { return p.id }
apache-2.0
adamrduffy/trinidad-1.0.x
trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/util/nls/LocaleUtils.java
5223
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.trinidadinternal.util.nls; import java.util.Locale; import org.apache.myfaces.trinidad.context.LocaleContext; import javax.faces.context.FacesContext; import org.apache.myfaces.trinidad.logging.TrinidadLogger; /** * Utility class dealing with Locale-related issues, including * common direction and alignment constants. * <p> * @version $Name: $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/util/nls/LocaleUtils.java#0 $) $Date: 10-nov-2005.18:49:13 $ */ public final class LocaleUtils { /** * Reading direction constant */ public static final int DIRECTION_DEFAULT = 0; /** * Reading direction constant */ public static final int DIRECTION_LEFTTORIGHT = 1; /** * Reading direction constant */ public static final int DIRECTION_RIGHTTOLEFT = 2; /** * Conversion function to go from LocaleContext to the obsolete * reading direction API. */ public static int getReadingDirection(LocaleContext localeContext) { return localeContext.isRightToLeft() ? DIRECTION_RIGHTTOLEFT : DIRECTION_LEFTTORIGHT; } /** * Given a locale, returns the default reading direction. */ public static int getReadingDirectionForLocale( Locale loc ) { if (loc == null) { loc = Locale.getDefault(); } String language = loc.getLanguage(); // arabic and hebrew are right-to-left languages. We treat "iw" as // hebrew because "iw" was the old code for Hebrew and the JDK // still uses it if (language.equals("ar") || language.equals("he") || language.equals("iw")) { return DIRECTION_RIGHTTOLEFT; } else { return DIRECTION_LEFTTORIGHT; } } /** * Decodes an IANA string (e.g., en-us) into a Locale object. */ public static Locale getLocaleForIANAString(String ianaString) { if ((ianaString == null) || "".equals(ianaString)) return null; String language; String country = ""; String variant = ""; int dashIndex = ianaString.indexOf('-'); if (dashIndex < 0) { language = ianaString; } else { language = ianaString.substring(0, dashIndex); int start = dashIndex + 1; dashIndex = ianaString.indexOf('-', start); if (dashIndex < 0) { country = ianaString.substring(start); } else { country = ianaString.substring(start, dashIndex); variant = ianaString.substring(dashIndex + 1); } } /* * Validate the rules for Locale per its Javadoc: * - The language argument is a valid ISO Language Code. * These codes are the lower-case, two-letter codes as defined by ISO-639. * - The country argument is a valid ISO Country Code. These * codes are the upper-case, two-letter codes as defined by ISO-3166. * * Rather than checking a list, we check the length and case and ignore * the arguments which fail to meet those criteria (use defaults instead). */ if (language.length() != 2) { language = ""; _LOG.warning("INVALID_LOCALE_LANG_LENGTH", ianaString); } else { if (Character.isUpperCase(language.charAt(0)) || Character.isUpperCase(language.charAt(1))) { language = ""; _LOG.warning("INVALID_LOCALE_LANG_CASE", ianaString); } } if (language.length() == 0) { Locale defaultLocale = FacesContext.getCurrentInstance().getViewRoot().getLocale(); return defaultLocale; } if (country.length() > 0) { if (country.length() != 2) { country = ""; _LOG.warning("INVALID_LOCALE_COUNTRY_LENGTH", ianaString); } else { if (Character.isLowerCase(country.charAt(0)) || Character.isLowerCase(country.charAt(1))) { country = ""; _LOG.warning("INVALID_LOCALE_COUNTRY_CASE", ianaString); } } } if (variant.indexOf('/') > 0) { // Disallow slashes in the variant to avoid XSS variant = ""; _LOG.warning("INVALID_LOCALE_VARIANT_HAS_SLASH", ianaString); } return new Locale(language, country, variant); } static private final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(LocaleUtils.class); }
apache-2.0
lisnju/server
src/main/java/com/gm/server/GetQuestsServlet.java
1415
package com.gm.server; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gm.common.model.Rpc.QuestPb; import com.gm.common.model.Rpc.Quests; import com.gm.server.model.Quest; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; public class GetQuestsServlet extends APIServlet { /** * */ private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { execute(req, resp); } //Input: key : the key of requester // //Output: QuestsPb message, containing all the quests owned by me. public void handle(HttpServletRequest req, HttpServletResponse resp) throws ApiException, IOException { Key userKey = KeyFactory.stringToKey(ParamKey.key.getValue(req)); // get all the quests owned by the user List<Quest> quests = dao.query(Quest.class).setAncestor(userKey).prepare().asList(); // prepare output message Quests.Builder questsMsg = Quests.newBuilder(); for (Quest q : quests){ QuestPb qMsg = q.getMSG(userKey.getId()).build(); questsMsg.addQuest(qMsg); } resp.getOutputStream().write(questsMsg.build().toByteArray()); } }
apache-2.0
aminmarashi/binary-common-utils
src/index.js
53
throw (Error('Use this module with relative path'));
apache-2.0
Dennis-Koch/ambeth
jambeth/jambeth-cache/src/main/java/com/koch/ambeth/cache/mixin/IPropertyChangeItemListenerExtendable.java
302
package com.koch.ambeth.cache.mixin; public interface IPropertyChangeItemListenerExtendable { void registerIPropertyChangeItemListener(IPropertyChangeItemListener propertyChangeItemListener); void unregisterIPropertyChangeItemListener( IPropertyChangeItemListener propertyChangeItemListener); }
apache-2.0
jeffbrown/grailsnolib
grails-core/src/main/groovy/org/codehaus/groovy/grails/validation/routines/DomainValidator.java
20028
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.validation.routines; import java.io.Serializable; import java.util.Arrays; import java.util.List; /** * <p><b>Domain name</b> validation routines.</p> * * <p> * This validator provides methods for validating Internet domain names * and top-level domains. * </p> * * <p>Domain names are evaluated according * to the standards <a href="http://www.ietf.org/rfc/rfc1034.txt">RFC1034</a>, * section 3, and <a href="http://www.ietf.org/rfc/rfc1123.txt">RFC1123</a>, * section 2.1. No accomodation is provided for the specialized needs of * other applications; if the domain name has been URL-encoded, for example, * validation will fail even though the equivalent plaintext version of the * same name would have passed. * </p> * * <p> * Validation is also provided for top-level domains (TLDs) as defined and * maintained by the Internet Assigned Numbers Authority (IANA): * </p> * * <ul> * <li>{@link #isValidInfrastructureTld} - validates infrastructure TLDs * (<code>.arpa</code>, etc.)</li> * <li>{@link #isValidGenericTld} - validates generic TLDs * (<code>.com, .org</code>, etc.)</li> * <li>{@link #isValidCountryCodeTld} - validates country code TLDs * (<code>.us, .uk, .cn</code>, etc.)</li> * </ul> * * <p> * (<b>NOTE</b>: This class does not provide IP address lookup for domain names or * methods to ensure that a given domain name matches a specific IP; see * {@link java.net.InetAddress} for that functionality.) * </p> * * @since Validator 1.4 */ public class DomainValidator implements Serializable { private static final long serialVersionUID = -7709130257134339371L; // Regular expression strings for hostnames (derived from RFC2396 and RFC 1123) private static final String DOMAIN_LABEL_REGEX = "\\p{Alnum}(?:[\\p{Alnum}-]*\\p{Alnum})*"; private static final String TOP_LABEL_REGEX = "\\p{Alpha}{2,}"; private static final String DOMAIN_NAME_REGEX = "^(?:" + DOMAIN_LABEL_REGEX + "\\.)+" + "(" + TOP_LABEL_REGEX + ")$"; /** * Singleton instance of this validator. */ private static final DomainValidator DOMAIN_VALIDATOR = new DomainValidator(); /** * RegexValidator for matching domains. */ private final RegexValidator domainRegex = new RegexValidator(DOMAIN_NAME_REGEX); /** * Returns the singleton instance of this validator. * @return the singleton instance of this validator */ public static DomainValidator getInstance() { return DOMAIN_VALIDATOR; } /** Private constructor. */ private DomainValidator() { // singleton } /** * Returns true if the specified <code>String</code> parses * as a valid domain name with a recognized top-level domain. * The parsing is case-sensitive. * @param domain the parameter to check for domain name syntax * @return true if the parameter is a valid domain name */ public boolean isValid(String domain) { String[] groups = domainRegex.match(domain); if (groups != null && groups.length > 0) { return isValidTld(groups[0]); } return false; } /** * Returns true if the specified <code>String</code> matches any * IANA-defined top-level domain. Leading dots are ignored if present. * The search is case-sensitive. * @param tld the parameter to check for TLD status * @return true if the parameter is a TLD */ public boolean isValidTld(String tld) { return isValidInfrastructureTld(tld) || isValidGenericTld(tld) || isValidCountryCodeTld(tld); } /** * Returns true if the specified <code>String</code> matches any * IANA-defined infrastructure top-level domain. Leading dots are * ignored if present. The search is case-sensitive. * @param iTld the parameter to check for infrastructure TLD status * @return true if the parameter is an infrastructure TLD */ public boolean isValidInfrastructureTld(String iTld) { return INFRASTRUCTURE_TLD_LIST.contains(chompLeadingDot(iTld.toLowerCase())); } /** * Returns true if the specified <code>String</code> matches any * IANA-defined generic top-level domain. Leading dots are ignored * if present. The search is case-sensitive. * @param gTld the parameter to check for generic TLD status * @return true if the parameter is a generic TLD */ public boolean isValidGenericTld(String gTld) { return GENERIC_TLD_LIST.contains(chompLeadingDot(gTld.toLowerCase())); } /** * Returns true if the specified <code>String</code> matches any * IANA-defined country code top-level domain. Leading dots are * ignored if present. The search is case-sensitive. * @param ccTld the parameter to check for country code TLD status * @return true if the parameter is a country code TLD */ public boolean isValidCountryCodeTld(String ccTld) { return COUNTRY_CODE_TLD_LIST.contains(chompLeadingDot(ccTld.toLowerCase())); } private String chompLeadingDot(String str) { if (str.startsWith(".")) { return str.substring(1); } return str; } // --------------------------------------------- // ----- TLDs defined by IANA // ----- Authoritative and comprehensive list at: // ----- http://data.iana.org/TLD/tlds-alpha-by-domain.txt private static final String[] INFRASTRUCTURE_TLDS = { "arpa", // internet infrastructure "root" // diagnostic marker for non-truncated root zone }; private static final String[] GENERIC_TLDS = { "aero", // air transport industry "asia", // Pan-Asia/Asia Pacific "biz", // businesses "cat", // Catalan linguistic/cultural community "com", // commercial enterprises "coop", // cooperative associations "info", // informational sites "jobs", // Human Resource managers "mobi", // mobile products and services "museum", // museums, surprisingly enough "name", // individuals' sites "net", // internet support infrastructure/business "org", // noncommercial organizations "pro", // credentialed professionals and entities "tel", // contact data for businesses and individuals "travel", // entities in the travel industry "gov", // United States Government "edu", // accredited postsecondary US education entities "mil", // United States Military "int" // organizations established by international treaty }; private static final String[] COUNTRY_CODE_TLDS = { "ac", // Ascension Island "ad", // Andorra "ae", // United Arab Emirates "af", // Afghanistan "ag", // Antigua and Barbuda "ai", // Anguilla "al", // Albania "am", // Armenia "an", // Netherlands Antilles "ao", // Angola "aq", // Antarctica "ar", // Argentina "as", // American Samoa "at", // Austria "au", // Australia (includes Ashmore and Cartier Islands and Coral Sea Islands) "aw", // Aruba "ax", // Aland "az", // Azerbaijan "ba", // Bosnia and Herzegovina "bb", // Barbados "bd", // Bangladesh "be", // Belgium "bf", // Burkina Faso "bg", // Bulgaria "bh", // Bahrain "bi", // Burundi "bj", // Benin "bm", // Bermuda "bn", // Brunei Darussalam "bo", // Bolivia "br", // Brazil "bs", // Bahamas "bt", // Bhutan "bv", // Bouvet Island "bw", // Botswana "by", // Belarus "bz", // Belize "ca", // Canada "cc", // Cocos (Keeling) Islands "cd", // Democratic Republic of the Congo (formerly Zaire) "cf", // Central African Republic "cg", // Republic of the Congo "ch", // Switzerland "ci", // Cote d'Ivoire "ck", // Cook Islands "cl", // Chile "cm", // Cameroon "cn", // China, mainland "co", // Colombia "cr", // Costa Rica "cu", // Cuba "cv", // Cape Verde "cx", // Christmas Island "cy", // Cyprus "cz", // Czech Republic "de", // Germany "dj", // Djibouti "dk", // Denmark "dm", // Dominica "do", // Dominican Republic "dz", // Algeria "ec", // Ecuador "ee", // Estonia "eg", // Egypt "er", // Eritrea "es", // Spain "et", // Ethiopia "eu", // European Union "fi", // Finland "fj", // Fiji "fk", // Falkland Islands "fm", // Federated States of Micronesia "fo", // Faroe Islands "fr", // France "ga", // Gabon "gb", // Great Britain (United Kingdom) "gd", // Grenada "ge", // Georgia "gf", // French Guiana "gg", // Guernsey "gh", // Ghana "gi", // Gibraltar "gl", // Greenland "gm", // The Gambia "gn", // Guinea "gp", // Guadeloupe "gq", // Equatorial Guinea "gr", // Greece "gs", // South Georgia and the South Sandwich Islands "gt", // Guatemala "gu", // Guam "gw", // Guinea-Bissau "gy", // Guyana "hk", // Hong Kong "hm", // Heard Island and McDonald Islands "hn", // Honduras "hr", // Croatia (Hrvatska) "ht", // Haiti "hu", // Hungary "id", // Indonesia "ie", // Ireland "il", // Israel "im", // Isle of Man "in", // India "io", // British Indian Ocean Territory "iq", // Iraq "ir", // Iran "is", // Iceland "it", // Italy "je", // Jersey "jm", // Jamaica "jo", // Jordan "jp", // Japan "ke", // Kenya "kg", // Kyrgyzstan "kh", // Cambodia (Khmer) "ki", // Kiribati "km", // Comoros "kn", // Saint Kitts and Nevis "kp", // North Korea "kr", // South Korea "kw", // Kuwait "ky", // Cayman Islands "kz", // Kazakhstan "la", // Laos (currently being marketed as the official domain for Los Angeles) "lb", // Lebanon "lc", // Saint Lucia "li", // Liechtenstein "lk", // Sri Lanka "lr", // Liberia "ls", // Lesotho "lt", // Lithuania "lu", // Luxembourg "lv", // Latvia "ly", // Libya "ma", // Morocco "mc", // Monaco "md", // Moldova "me", // Montenegro "mg", // Madagascar "mh", // Marshall Islands "mk", // Republic of Macedonia "ml", // Mali "mm", // Myanmar "mn", // Mongolia "mo", // Macau "mp", // Northern Mariana Islands "mq", // Martinique "mr", // Mauritania "ms", // Montserrat "mt", // Malta "mu", // Mauritius "mv", // Maldives "mw", // Malawi "mx", // Mexico "my", // Malaysia "mz", // Mozambique "na", // Namibia "nc", // New Caledonia "ne", // Niger "nf", // Norfolk Island "ng", // Nigeria "ni", // Nicaragua "nl", // Netherlands "no", // Norway "np", // Nepal "nr", // Nauru "nu", // Niue "nz", // New Zealand "om", // Oman "pa", // Panama "pe", // Peru "pf", // French Polynesia With Clipperton Island "pg", // Papua New Guinea "ph", // Philippines "pk", // Pakistan "pl", // Poland "pm", // Saint-Pierre and Miquelon "pn", // Pitcairn Islands "pr", // Puerto Rico "ps", // Palestinian territories (PA-controlled West Bank and Gaza Strip) "pt", // Portugal "pw", // Palau "py", // Paraguay "qa", // Qatar "re", // Reunion "ro", // Romania "rs", // Serbia "ru", // Russia "rw", // Rwanda "sa", // Saudi Arabia "sb", // Solomon Islands "sc", // Seychelles "sd", // Sudan "se", // Sweden "sg", // Singapore "sh", // Saint Helena "si", // Slovenia "sj", // Svalbard and Jan Mayen Islands Not in use (Norwegian dependencies; see .no) "sk", // Slovakia "sl", // Sierra Leone "sm", // San Marino "sn", // Senegal "so", // Somalia "sr", // Suriname "st", // Sao Tome and Principe "su", // Soviet Union (deprecated) "sv", // El Salvador "sy", // Syria "sz", // Swaziland "tc", // Turks and Caicos Islands "td", // Chad "tf", // French Southern and Antarctic Lands "tg", // Togo "th", // Thailand "tj", // Tajikistan "tk", // Tokelau "tl", // East Timor (deprecated old code) "tm", // Turkmenistan "tn", // Tunisia "to", // Tonga "tp", // East Timor "tr", // Turkey "tt", // Trinidad and Tobago "tv", // Tuvalu "tw", // Taiwan, Republic of China "tz", // Tanzania "ua", // Ukraine "ug", // Uganda "uk", // United Kingdom "um", // United States Minor Outlying Islands "us", // United States of America "uy", // Uruguay "uz", // Uzbekistan "va", // Vatican City State "vc", // Saint Vincent and the Grenadines "ve", // Venezuela "vg", // British Virgin Islands "vi", // U.S. Virgin Islands "vn", // Vietnam "vu", // Vanuatu "wf", // Wallis and Futuna "ws", // Samoa (formerly Western Samoa) "ye", // Yemen "yt", // Mayotte "yu", // Serbia and Montenegro (originally Yugoslavia) "za", // South Africa "zm", // Zambia "zw", // Zimbabwe }; private static final List<String> INFRASTRUCTURE_TLD_LIST = Arrays.asList(INFRASTRUCTURE_TLDS); private static final List<String> GENERIC_TLD_LIST = Arrays.asList(GENERIC_TLDS); private static final List<String> COUNTRY_CODE_TLD_LIST = Arrays.asList(COUNTRY_CODE_TLDS); }
apache-2.0
zhouweiaccp/code
Cache/Plugin_Cache/supercache/Store/General/Collections/LimitedQueue.cs
2872
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace STSdb4.General.Collections { public class LimitedQueue<T> : IEnumerable<T> { private T[] buffer; private int index = 0; public int Count { get; private set; } public LimitedQueue(int capacity) { if (capacity <= 0) throw new ArgumentOutOfRangeException("capacity"); buffer = new T[capacity]; } public int Capacity { get { return buffer.Length; } } public void Enqueue(T item) { int idx = (index + Count) % Capacity; buffer[idx] = item; if (Count < Capacity) Count++; else index = (index + 1) % Capacity; } public T Dequeue() { if (Count == 0) throw new ArgumentOutOfRangeException(); T item = buffer[index]; index = (index + 1) % Capacity; Count--; return item; } public void Clear() { Count = 0; } public T First { get { if (Count == 0) throw new ArgumentOutOfRangeException(); return buffer[index]; } } public T Last { get { if (Count == 0) throw new ArgumentOutOfRangeException(); return buffer[(index + Count - 1) % Capacity]; } } public T this[int index] { get { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index"); return buffer[(this.index + index) % Capacity]; } set { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index"); buffer[(this.index + index) % Capacity] = value; } } #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { for (int i = 0; i < Count; i++) yield return buffer[(index + i) % Capacity]; } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion public LimitedQueue<T> Clone() { LimitedQueue<T> result = new LimitedQueue<T>(Capacity); result.index = this.index; result.Count = this.Count; Array.Copy(this.buffer, result.buffer, Capacity); return result; } } }
apache-2.0
andybab/Impala
tests/hs2/test_fetch_first.py
19301
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Tests the FETCH_FIRST fetch orientation for HS2 clients. # Impala permits FETCH_FIRST for a particular query iff result caching is enabled # via the 'impala.resultset.cache.size' confOverlay option. FETCH_FIRST will # succeed as long all previously fetched rows fit into the bounded result cache. import pytest from tests.hs2.hs2_test_suite import HS2TestSuite, needs_session from TCLIService import TCLIService from tests.common.impala_cluster import ImpalaCluster class TestFetchFirst(HS2TestSuite): IMPALA_RESULT_CACHING_OPT = "impala.resultset.cache.size"; def __test_invalid_result_caching(self, sql_stmt): """ Tests that invalid requests for query-result caching fail using the given sql_stmt.""" impala_cluster = ImpalaCluster() impalad = impala_cluster.impalads[0].service execute_statement_req = TCLIService.TExecuteStatementReq() execute_statement_req.sessionHandle = self.session_handle execute_statement_req.statement = sql_stmt execute_statement_req.confOverlay = dict() # Test that a malformed result-cache size returns an error. execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "bad_number" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) HS2TestSuite.check_response(execute_statement_resp, TCLIService.TStatusCode.ERROR_STATUS, "Invalid value 'bad_number' for 'impala.resultset.cache.size' option") self.__verify_num_cached_rows(0) assert 0 == impalad.get_num_in_flight_queries() # Test that a result-cache size exceeding the per-Impalad maximum returns an error. # The default maximum result-cache size is 100000. execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "100001" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) HS2TestSuite.check_response(execute_statement_resp, TCLIService.TStatusCode.ERROR_STATUS, "Requested result-cache size of 100001 exceeds Impala's maximum of 100000") self.__verify_num_cached_rows(0) assert 0 == impalad.get_num_in_flight_queries() def __verify_num_cached_rows(self, num_cached_rows): """Asserts that Impala has the given number of rows in its result set cache. Also sanity checks the metric for tracking the bytes consumed by the cache.""" self.impalad_test_service.wait_for_metric_value( 'impala-server.resultset-cache.total-num-rows', num_cached_rows, timeout=60) cached_bytes = self.impalad_test_service.get_metric_value( 'impala-server.resultset-cache.total-bytes') if num_cached_rows > 0: assert cached_bytes > 0 else: assert cached_bytes == 0 @pytest.mark.xfail(run=False, reason="IMPALA-1264") @pytest.mark.execute_serially @needs_session(TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V6) def test_query_stmts_v6(self): self.run_query_stmts_test(); @pytest.mark.xfail(run=False, reason="IMPALA-1264") @pytest.mark.execute_serially @needs_session(TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V1) def test_query_stmts_v1(self): self.run_query_stmts_test(); def run_query_stmts_test(self): """Tests Impala's limited support for the FETCH_FIRST fetch orientation for queries. Impala permits FETCH_FIRST for a particular query iff result caching is enabled via the 'impala.resultset.cache.size' confOverlay option. FETCH_FIRST will succeed as long as all previously fetched rows fit into the bounded result cache. Regardless of whether a FETCH_FIRST succeeds or not, clients may always resume fetching with FETCH_NEXT. """ # Negative tests for the result caching option. self.__test_invalid_result_caching("SELECT COUNT(*) FROM functional.alltypes") # Test that FETCH_NEXT without result caching succeeds and FETCH_FIRST fails. execute_statement_req = TCLIService.TExecuteStatementReq() execute_statement_req.sessionHandle = self.session_handle execute_statement_req.confOverlay = dict() execute_statement_req.statement =\ "SELECT * FROM functional.alltypessmall ORDER BY id LIMIT 30" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) HS2TestSuite.check_response(execute_statement_resp) for i in xrange(1, 5): # Fetch 10 rows with the FETCH_NEXT orientation. expected_num_rows = 10 if i == 4: expected_num_rows = 0; self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 10, expected_num_rows) # Fetch 10 rows with the FETCH_FIRST orientation, expecting an error. # After a failed FETCH_FIRST, the client can still resume FETCH_NEXT. self.fetch_fail(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, "Restarting of fetch requires enabling of query result caching") self.__verify_num_cached_rows(0) self.close(execute_statement_resp.operationHandle) # Basic test of FETCH_FIRST where the entire result set is cached, and we repeatedly # fetch all results. execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "30" execute_statement_req.statement =\ "SELECT * FROM functional.alltypessmall ORDER BY id LIMIT 30" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) for _ in xrange(1, 5): self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, 30) self.__verify_num_cached_rows(30) self.close(execute_statement_resp.operationHandle) # Test FETCH_NEXT and FETCH_FIRST where the entire result set does not fit into # the cache. FETCH_FIRST will succeed as long as the fetched results # fit into the cache. execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "29" execute_statement_req.statement =\ "SELECT * FROM functional.alltypessmall ORDER BY id LIMIT 30" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) # Fetch 10 rows. They fit in the result cache. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 10) self.__verify_num_cached_rows(10) # Restart the fetch and expect success. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, 10) # Fetch 10 more rows. The result cache has 20 rows total now. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 10) self.__verify_num_cached_rows(20) # Restart the fetch and expect success. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, 10) self.__verify_num_cached_rows(20) # Fetch 10 more rows from the cache. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 10) self.__verify_num_cached_rows(20) # This fetch exhausts the result cache. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 10) self.__verify_num_cached_rows(0) # Since the cache is exhausted, FETCH_FIRST will fail. self.fetch_fail(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, "The query result cache exceeded its limit of 29 rows. " "Restarting the fetch is not possible") self.__verify_num_cached_rows(0) # This fetch should succeed but return 0 rows because the stream is eos. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 10, 0) self.__verify_num_cached_rows(0) self.close(execute_statement_resp.operationHandle) # Test that FETCH_FIRST serves results from the cache as well as the query # coordinator in a single fetch request. execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "29" execute_statement_req.statement =\ "SELECT * FROM functional.alltypessmall ORDER BY id LIMIT 30" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) # Fetch 7 rows. They fit in the result cache. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 7) self.__verify_num_cached_rows(7) # Restart the fetch asking for 12 rows, 7 of which are served from the cache and 5 # from the coordinator. The result cache should have 12 rows total now. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, 12) self.__verify_num_cached_rows(12) # Restart the fetch asking for 40 rows. We expect 30 results returned and that the # cache is exhausted. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, 40, 30) self.__verify_num_cached_rows(0) # Fetch next should succeed and return 0 rows (eos). self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 7, 0) self.__verify_num_cached_rows(0) # Since the cache is exhausted, FETCH_FIRST will fail. self.fetch_fail(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, "The query result cache exceeded its limit of 29 rows. " "Restarting the fetch is not possible") self.__verify_num_cached_rows(0) self.close(execute_statement_resp.operationHandle) # Test that resuming FETCH_NEXT after a failed FETCH_FIRST works. execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "10" execute_statement_req.statement =\ "SELECT * FROM functional.alltypessmall ORDER BY id LIMIT 30" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) # Fetch 9 rows. They fit in the result cache. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 9) self.__verify_num_cached_rows(9) # Fetch 9 rows. Cache is exhausted now. self.fetch_until(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 9) self.__verify_num_cached_rows(0) # Restarting the fetch should fail. self.fetch_fail(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, "The query result cache exceeded its limit of 10 rows. " "Restarting the fetch is not possible") self.__verify_num_cached_rows(0) # Resuming FETCH_NEXT should succeed. There are 12 remaining rows to fetch. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 100, 12) self.__verify_num_cached_rows(0) self.close(execute_statement_resp.operationHandle) @pytest.mark.execute_serially @needs_session def test_constant_query_stmts(self): """Tests query stmts that return a constant result set. These queries are handled somewhat specially by Impala, therefore, we test them separately. We expect FETCH_FIRST to always succeed if result caching is enabled.""" # Tests a query with limit 0. execute_statement_req = TCLIService.TExecuteStatementReq() execute_statement_req.sessionHandle = self.session_handle execute_statement_req.confOverlay = dict() execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "10" execute_statement_req.statement =\ "SELECT * FROM functional.alltypessmall ORDER BY id LIMIT 0" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) for i in xrange(0, 3): # Fetch some rows. Expect to get 0 rows. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, i * 10, 0) self.__verify_num_cached_rows(0) # Fetch some rows with FETCH_FIRST. Expect to get 0 rows. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, i * 10, 0) self.__verify_num_cached_rows(0) self.close(execute_statement_resp.operationHandle) # Tests a constant select. execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "10" execute_statement_req.statement = "SELECT 1, 1.0, 'a', trim('abc'), NULL" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) # Fetch 100 rows with FETCH_FIRST. Expect to get 1 row. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, 100, 1) self.__verify_num_cached_rows(1) for i in xrange(0, 3): # Fetch some rows with FETCH_FIRST. Expect to get 1 row. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, i * 10, 1) self.__verify_num_cached_rows(1) # Fetch some more rows. Expect to get 1 row. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, i * 10, 0) self.__verify_num_cached_rows(1) self.close(execute_statement_resp.operationHandle) @pytest.mark.execute_serially @needs_session def test_non_query_stmts(self): """Tests Impala's limited support for the FETCH_FIRST fetch orientation for non-query stmts that return a result set, such as SHOW, COMPUTE STATS, etc. The results of non-query statements are always cached entirely, and therefore, the cache can never be exhausted, i.e., FETCH_FIRST should always succeed. However, we only allow FETCH_FIRST on non-query stmts if query caching was enabled by the client for consistency. We use a 'show stats' stmt as a representative of these types of non-query stmts. """ # Negative tests for the result caching option. self.__test_invalid_result_caching("show table stats functional.alltypes") # Test that FETCH_NEXT without result caching succeeds and FETCH_FIRST fails. # The show stmt returns exactly 25 results. execute_statement_req = TCLIService.TExecuteStatementReq() execute_statement_req.sessionHandle = self.session_handle execute_statement_req.confOverlay = dict() execute_statement_req.statement = "show table stats functional.alltypes" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) HS2TestSuite.check_response(execute_statement_resp) for i in xrange(1, 5): # Fetch 10 rows with the FETCH_NEXT orientation. expected_num_rows = 10 if i == 3: expected_num_rows = 5 if i == 4: expected_num_rows = 0 self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 10, expected_num_rows) # Fetch 10 rows with the FETCH_FIRST orientation, expecting an error. # After a failed FETCH_FIRST, the client can still resume FETCH_NEXT. self.fetch_fail(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, "Restarting of fetch requires enabling of query result caching") # The results of non-query stmts are not counted as 'cached'. self.__verify_num_cached_rows(0) # Tests that FETCH_FIRST always succeeds as long as result caching is enabled. # The show stmt returns exactly 25 results. The cache cannot be exhausted. execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "1" execute_statement_req.statement = "show table stats functional.alltypes" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) HS2TestSuite.check_response(execute_statement_resp) for _ in xrange(1, 5): self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, 30, 25) # The results of non-query stmts are not counted as 'cached'. self.__verify_num_cached_rows(0) # Test combinations of FETCH_FIRST and FETCH_NEXT. # The show stmt returns exactly 25 results. execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "1" execute_statement_req.statement = "show table stats functional.alltypes" execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) HS2TestSuite.check_response(execute_statement_resp) # Fetch 10 rows. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 10) # Restart the fetch asking for 20 rows. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, 20) # FETCH_NEXT asking for 100 rows. There are only 5 remaining rows. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 100, 5) # Restart the fetch asking for 10 rows. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_FIRST, 5) # FETCH_NEXT asking for 100 rows. There are only 20 remaining rows. self.fetch(execute_statement_resp.operationHandle, TCLIService.TFetchOrientation.FETCH_NEXT, 100, 20) @pytest.mark.execute_serially @needs_session def test_parallel_insert(self): """Tests parallel inserts with result set caching on. Parallel inserts have a coordinator instance but no coordinator fragment, so the query mem tracker is initialized differently. (IMPALA-963) """ self.client.set_configuration({'sync_ddl': 1}) self.client.execute("create table %s.orderclone like tpch.orders" % self.TEST_DB) execute_statement_req = TCLIService.TExecuteStatementReq() execute_statement_req.sessionHandle = self.session_handle execute_statement_req.confOverlay = dict() execute_statement_req.confOverlay[self.IMPALA_RESULT_CACHING_OPT] = "10" execute_statement_req.statement = ("insert overwrite %s.orderclone " "select * from tpch.orders " "where o_orderkey < 0" % self.TEST_DB) execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) HS2TestSuite.check_response(execute_statement_resp)
apache-2.0
tallycheck/data-support
meta-descriptor-base/src/main/java/com/taoswork/tallycheck/descriptor/metadata/classtree/EntityClassTreeAccessor.java
871
package com.taoswork.tallycheck.descriptor.metadata.classtree; import com.taoswork.tallycheck.general.solution.autotree.AutoTreeAccessor; import com.taoswork.tallycheck.general.solution.autotree.AutoTreeGenealogy; /** * Created by Gao Yuan on 2015/5/23. */ public class EntityClassTreeAccessor extends AutoTreeAccessor<EntityClass, EntityClassTree> { public EntityClassTreeAccessor() { this(new EntityClassGenealogy()); } public EntityClassTreeAccessor(AutoTreeGenealogy<EntityClass> genealogy) { super(genealogy); } public EntityClassTree add(EntityClassTree existingNode, Class<?> newNodeData) { return (EntityClassTree) super.add(existingNode, new EntityClass(newNodeData)); } @Override public EntityClassTree createNode(EntityClass entityClass) { return new EntityClassTree(entityClass); } }
apache-2.0
mikemoraned/geowhatsit-server
lib/GeoHashRegion.js
1343
// Generated by CoffeeScript 1.6.1 (function() { var GeoHashRegion, LatLon, geohash; geohash = require('ngeohash'); LatLon = require('./LatLon'); GeoHashRegion = (function() { function GeoHashRegion(center, error, hash) { this.center = center; this.error = error; this.hash = hash; } GeoHashRegion.prototype.toHash = function(precision) { return geohash.encode(this.center.latitude, this.center.longitude, precision); }; GeoHashRegion.prototype.boundingBox = function() { return { topLeft: new LatLon(this.center.latitude + this.error.latitude, this.center.longitude - this.error.longitude), bottomRight: new LatLon(this.center.latitude - this.error.latitude, this.center.longitude + this.error.longitude) }; }; GeoHashRegion.fromPointInRegion = function(latLon, precision) { var hash; hash = geohash.encode(latLon.latitude, latLon.longitude, precision); return GeoHashRegion.fromHash(hash); }; GeoHashRegion.fromHash = function(hash) { var center, decoded; decoded = geohash.decode(hash); center = new LatLon(decoded.latitude, decoded.longitude); return new GeoHashRegion(center, decoded.error, hash); }; return GeoHashRegion; })(); module.exports = GeoHashRegion; }).call(this);
apache-2.0
spring-projects/spring-data-examples
jpa/deferred/src/main/java/example/service/Customer906Service.java
221
package example.service; import example.repo.Customer906Repository; import org.springframework.stereotype.Service; @Service public class Customer906Service { public Customer906Service(Customer906Repository repo) {} }
apache-2.0
Lukasa/cryptography
tests/hazmat/primitives/test_3des.py
4195
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """ Test using the NIST Test Vectors """ from __future__ import absolute_import, division, print_function import binascii import os import pytest from cryptography.hazmat.primitives.ciphers import algorithms, modes from .utils import generate_encrypt_test from ...utils import load_nist_vectors @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.TripleDES("\x00" * 8), modes.CBC("\x00" * 8) ), skip_message="Does not support TripleDES CBC", ) @pytest.mark.cipher class TestTripleDESModeCBC(object): test_KAT = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CBC"), [ "TCBCinvperm.rsp", "TCBCpermop.rsp", "TCBCsubtab.rsp", "TCBCvarkey.rsp", "TCBCvartext.rsp", ], lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)), lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)), ) test_MMT = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CBC"), [ "TCBCMMT1.rsp", "TCBCMMT2.rsp", "TCBCMMT3.rsp", ], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3) ), lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.TripleDES("\x00" * 8), modes.OFB("\x00" * 8) ), skip_message="Does not support TripleDES OFB", ) @pytest.mark.cipher class TestTripleDESModeOFB(object): test_KAT = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "OFB"), [ "TOFBpermop.rsp", "TOFBsubtab.rsp", "TOFBvarkey.rsp", "TOFBvartext.rsp", "TOFBinvperm.rsp", ], lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), ) test_MMT = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "OFB"), [ "TOFBMMT1.rsp", "TOFBMMT2.rsp", "TOFBMMT3.rsp", ], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3) ), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.TripleDES("\x00" * 8), modes.CFB("\x00" * 8) ), skip_message="Does not support TripleDES CFB", ) @pytest.mark.cipher class TestTripleDESModeCFB(object): test_KAT = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CFB"), [ "TCFB64invperm.rsp", "TCFB64permop.rsp", "TCFB64subtab.rsp", "TCFB64varkey.rsp", "TCFB64vartext.rsp", ], lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)), lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), ) test_MMT = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CFB"), [ "TCFB64MMT1.rsp", "TCFB64MMT2.rsp", "TCFB64MMT3.rsp", ], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3) ), lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), )
apache-2.0