repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
mathiewz/modernized-slick | src/main/java/com/github/mathiewz/slick/svg/inkscape/EllipseProcessor.java | package com.github.mathiewz.slick.svg.inkscape;
import org.w3c.dom.Element;
import com.github.mathiewz.slick.geom.Ellipse;
import com.github.mathiewz.slick.geom.Shape;
import com.github.mathiewz.slick.geom.Transform;
import com.github.mathiewz.slick.svg.Diagram;
import com.github.mathiewz.slick.svg.Figure;
import com.github.mathiewz.slick.svg.Loader;
import com.github.mathiewz.slick.svg.NonGeometricData;
/**
* Processor for ellipse and path nodes marked as arcs
*
* @author kevin
*/
public class EllipseProcessor implements ElementProcessor {
/**
* @see com.github.mathiewz.slick.svg.inkscape.ElementProcessor#process(com.github.mathiewz.slick.svg.Loader, org.w3c.dom.Element, com.github.mathiewz.slick.svg.Diagram, com.github.mathiewz.slick.geom.Transform)
*/
@Override
public void process(Loader loader, Element element, Diagram diagram, Transform t) {
Transform transform = Util.getTransform(element);
transform = new Transform(t, transform);
Float x = Util.getFloatAttribute(element, "cx");
Float y = Util.getFloatAttribute(element, "cy");
Float rx = Util.getFloatAttribute(element, "rx");
Float ry = Util.getFloatAttribute(element, "ry");
Ellipse ellipse = new Ellipse(x, y, rx, ry);
Shape shape = ellipse.transform(transform);
NonGeometricData data = Util.getNonGeometricData(element);
data.addAttribute("cx", x.toString());
data.addAttribute("cy", y.toString());
data.addAttribute("rx", rx.toString());
data.addAttribute("ry", ry.toString());
diagram.addFigure(new Figure(Figure.ELLIPSE, shape, data, transform));
}
/**
* @see com.github.mathiewz.slick.svg.inkscape.ElementProcessor#handles(org.w3c.dom.Element)
*/
@Override
public boolean handles(Element element) {
if (element.getNodeName().equals("ellipse")) {
return true;
}
if (element.getNodeName().equals("path")) {
if ("arc".equals(element.getAttributeNS(Util.SODIPODI, "type"))) {
return true;
}
}
return false;
}
}
|
cpopescu/whispercast | whisperstreamlib/f4v/frames/header.h | <reponame>cpopescu/whispercast<filename>whisperstreamlib/f4v/frames/header.h
// Copyright (c) 2009, Whispersoft s.r.l.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Whispersoft s.r.l. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: <NAME>
#ifndef __MEDIA_F4V_F4V_FRAME_HEADER_H__
#define __MEDIA_F4V_F4V_FRAME_HEADER_H__
#include <whisperlib/common/base/types.h>
namespace streaming {
namespace f4v {
class FrameHeader {
public:
enum Type {
AUDIO_FRAME,
VIDEO_FRAME,
RAW_FRAME,
};
static const string& TypeName(Type type);
public:
FrameHeader();
FrameHeader(int64 offset, int64 size, int64 decoding_timestamp,
int64 composition_offset_ms, int64 duration,
int64 sample_index, Type type, bool is_keyframe);
virtual ~FrameHeader();
int64 offset() const { return offset_; }
int64 size() const { return size_; }
int64 timestamp() const { return decoding_timestamp_; }
int64 decoding_timestamp() const { return decoding_timestamp_; }
int64 composition_offset_ms() const { return composition_offset_ms_; }
int64 composition_timestamp() const { return decoding_timestamp_ + composition_offset_ms_; }
int64 duration() const { return duration_; }
int64 sample_index() const { return sample_index_; }
Type type() const { return type_; }
const string& type_name() const { return TypeName(type_); }
bool is_keyframe() const { return is_keyframe_; }
void set_keyframe(bool keyframe) { is_keyframe_ = keyframe; }
bool Equals(const FrameHeader& other) const;
string ToString() const;
private:
// offset from file begin
int64 offset_;
// in bytes
int64 size_;
// milliseconds, relative to MDAT body start
int64 decoding_timestamp_;
// milliseconds, always greater than decoding_timestamp
int64 composition_offset_ms_;
// milliseconds duration
int64 duration_;
// samples, relative to MDAT body start
int64 sample_index_;
// frame type
Type type_;
// key frame, applicable to video frames only
bool is_keyframe_;
};
} // namespace f4v
} // namespace streaming
#endif // __MEDIA_F4V_F4V_FRAME_HEADER_H__
|
katrinazhu/game_engine | src/author/view/pages/level_editor/windows/level_edit_window/ILevelEditWindowInternal.java | /**
*
*/
package author.view.pages.level_editor.windows.level_edit_window;
/**
* @author <NAME> (ct168)
*
*/
interface ILevelEditWindowInternal {
void close();
}
|
51breeze/es-javascript | core/Plugins.js | <filename>core/Plugins.js
const plugins=new Map();
module.exports={
register(name, plugin){
plugins.set(name, plugin);
},
getPlugin(name){
return plugins.get(name);
}
} |
danielatomoiaga/openEHR_SDK | client/src/test/java/org/ehrbase/client/classgenerator/examples/openereactcarecomposition/definition/StoryHistoryObservation.java | <gh_stars>0
package org.ehrbase.client.classgenerator.examples.openereactcarecomposition.definition;
import com.nedap.archie.rm.datastructures.Cluster;
import com.nedap.archie.rm.generic.PartyProxy;
import org.ehrbase.client.annotations.Archetype;
import org.ehrbase.client.annotations.Entity;
import org.ehrbase.client.annotations.Path;
import org.ehrbase.client.classgenerator.examples.shareddefinition.Language;
import java.time.temporal.TemporalAccessor;
import java.util.List;
@Entity
@Archetype("openEHR-EHR-OBSERVATION.story.v1")
public class StoryHistoryObservation {
@Path("/data[at0001]/events[at0002]/data[at0003]/items[at0004]")
private List<StoryHistorySoftSignsElement> softSigns;
@Path("/data[at0001]/events[at0002]/data[at0003]/items[at0004]/value|value")
private String notesValue;
@Path("/data[at0001]/events[at0002]/data[at0003]/items[at0006]")
private List<Cluster> structuredDetail;
@Path("/language")
private Language language;
@Path("/data[at0001]/events[at0002]/time|value")
private TemporalAccessor timeValue;
@Path("/subject")
private PartyProxy subject;
@Path("/data[at0001]/origin|value")
private TemporalAccessor originValue;
@Path("/protocol[at0007]/items[at0008]")
private List<Cluster> extension;
public void setSoftSigns(List<StoryHistorySoftSignsElement> softSigns) {
this.softSigns = softSigns;
}
public List<StoryHistorySoftSignsElement> getSoftSigns() {
return this.softSigns;
}
public void setNotesValue(String notesValue) {
this.notesValue = notesValue;
}
public String getNotesValue() {
return this.notesValue;
}
public void setStructuredDetail(List<Cluster> structuredDetail) {
this.structuredDetail = structuredDetail;
}
public List<Cluster> getStructuredDetail() {
return this.structuredDetail;
}
public void setLanguage(Language language) {
this.language = language;
}
public Language getLanguage() {
return this.language;
}
public void setTimeValue(TemporalAccessor timeValue) {
this.timeValue = timeValue;
}
public TemporalAccessor getTimeValue() {
return this.timeValue;
}
public void setSubject(PartyProxy subject) {
this.subject = subject;
}
public PartyProxy getSubject() {
return this.subject;
}
public void setOriginValue(TemporalAccessor originValue) {
this.originValue = originValue;
}
public TemporalAccessor getOriginValue() {
return this.originValue;
}
public void setExtension(List<Cluster> extension) {
this.extension = extension;
}
public List<Cluster> getExtension() {
return this.extension;
}
}
|
wgsyd/wgtf | src/core/lib/tf_types/vector4.hpp | <reponame>wgsyd/wgtf
#pragma once
#include "vector3.hpp"
namespace wgt
{
class Vector4
{
public:
float x;
float y;
float z;
float w;
Vector4() : x(0.f), y(0.f), z(0.f), w(0.f)
{
}
Vector4(const Vector4& v) : x(v.x), y(v.y), z(v.z), w(v.w)
{
}
Vector4(const Vector3& v, float w_) : x(v.x), y(v.y), z(v.z), w(w_)
{
}
Vector4(float x_, float y_, float z_, float w_) : x(x_), y(y_), z(z_), w(w_)
{
}
Vector4 operator*(float v) const
{
return Vector4(x * v, y * v, z * v, w * v);
}
void operator*=(float v)
{
x *= v;
y *= v;
z *= v;
w *= v;
}
bool operator==(const Vector4& v) const
{
return x == v.x && y == v.y && z == v.z && w == v.w;
}
bool operator!=(const Vector4& v) const
{
return !(*this == v);
}
};
} // end namespace wgt
|
kellyselden/ember-cli-dependency-graph | test/fixtures/code-corps-ember/code-corps-ember/components/tooltip-on-element.js | <filename>test/fixtures/code-corps-ember/code-corps-ember/components/tooltip-on-element.js
define('code-corps-ember/components/tooltip-on-element', ['exports', 'code-corps-ember/config/environment', 'ember-tooltips/components/tooltip-on-element'], function (exports, _environment, _tooltipOnElement) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _didUpdateTimeoutLength = _environment.default.environment === 'test' ? 0 : 1000;
exports.default = _tooltipOnElement.default.extend({ _didUpdateTimeoutLength: _didUpdateTimeoutLength });
}); |
iMigno/click_framework | src/main/java/com/clickntap/smart/SmartUserAgent.java | <filename>src/main/java/com/clickntap/smart/SmartUserAgent.java
package com.clickntap.smart;
public class SmartUserAgent {
private String channel;
private String header;
private String ip;
private String host;
public SmartUserAgent(SmartContext smartContext) {
header = smartContext.getRequest().getHeader("User-Agent");
ip = smartContext.getRequest().getRemoteAddr();
host = smartContext.getRequest().getRemoteHost();
String ua = header.toLowerCase();
channel = "web";
if (ua.indexOf("windows ce") >= 0)
channel = "mobile";
if (ua.indexOf("iphone os") >= 0)
channel = "mobile";
if (ua.indexOf("mobile") >= 0)
channel = "mobile";
if (ua.indexOf("series") >= 0)
channel = "mobile";
if (ua.indexOf("armv") >= 0)
channel = "mobile";
if (ua.indexOf("vodafone") >= 0)
channel = "mobile";
if (ua.indexOf("android") >= 0)
channel = "mobile";
}
public String getChannel() {
return channel;
}
public String getHeader() {
return header;
}
public String getIp() {
return ip;
}
public String getHost() {
return host;
}
}
|
jfsong1122/iostest | objc/Project/Pods/Headers/Public/BDWebKitToB/BDWebSSLPlugin.h | <reponame>jfsong1122/iostest
//
// BDWebSSLPlugin.h
// BDWebKit
//
// Created by 温宇涛 on 2020/2/21.
//
#import <BDWebCoreToB/IWKPluginObject.h>
NS_ASSUME_NONNULL_BEGIN
@interface BDWebSSLPlugin : IWKPluginObject <IWKInstancePlugin>
@end
NS_ASSUME_NONNULL_END
|
ibara/LiteBSD-Ports | comms/zmtx-zmrx/version.h | /* the release version number as printed by the programs */
#define VERSION "1.02"
|
creatubbles/ctb-mcmod | src/main/java/com/creatubbles/repack/endercore/client/gui/widget/GuiScrollableList.java | package com.creatubbles.repack.endercore.client.gui.widget;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import com.creatubbles.repack.endercore.api.client.gui.IGuiScreen;
import com.creatubbles.repack.endercore.api.client.gui.ListSelectionListener;
public abstract class GuiScrollableList<T> {
private final Minecraft mc = Minecraft.getMinecraft();
protected int originX;
protected int originY;
protected int width;
protected int height;
protected int minY;
protected int maxY;
protected int minX;
protected int maxX;
protected final int slotHeight;
private int scrollUpButtonID;
private int scrollDownButtonID;
protected int mouseX;
protected int mouseY;
private float initialClickY = -2.0F;
private float scrollMultiplier;
private float amountScrolled;
protected int selectedIndex = -1;
private long lastClickedTime;
private boolean showSelectionBox = true;
protected int margin = 4;
protected List<ListSelectionListener<T>> listeners = new CopyOnWriteArrayList<ListSelectionListener<T>>();
public GuiScrollableList(int width, int height, int originX, int originY, int slotHeight) {
this.width = width;
this.height = height;
this.originX = originX;
this.originY = originY;
this.slotHeight = slotHeight;
minY = originY;
maxY = minY + height;
minX = originX;
maxX = minX + width;
}
public void onGuiInit(IGuiScreen gui) {
minY = originY + gui.getGuiTop();
maxY = minY + height;
minX = originX + gui.getGuiLeft();
maxX = minX + width;
}
public void addSelectionListener(ListSelectionListener<T> listener) {
listeners.add(listener);
}
public void removeSelectionListener(ListSelectionListener<T> listener) {
listeners.remove(listener);
}
public T getSelectedElement() {
return getElementAt(selectedIndex);
}
public void setSelection(T selection) {
setSelection(getIndexOf(selection));
}
public void setSelection(int index) {
if (index == selectedIndex) {
return;
}
selectedIndex = index;
for (ListSelectionListener<T> listener : listeners) {
listener.selectionChanged(this, selectedIndex);
}
}
public int getIndexOf(T element) {
if (element == null) {
return -1;
}
for (int i = 0; i < getNumElements(); i++) {
if (element.equals(getElementAt(i))) {
return i;
}
}
return -1;
}
public abstract T getElementAt(int index);
public abstract int getNumElements();
protected abstract void drawElement(int elementIndex, int x, int y, int height, VertexBuffer renderer);
protected boolean elementClicked(int elementIndex, boolean doubleClick) {
return true;
}
public void setShowSelectionBox(boolean val) {
showSelectionBox = val;
}
protected int getContentHeight() {
return getNumElements() * slotHeight;
}
public void setScrollButtonIds(int scrollUpButtonID, int scrollDownButtonID) {
this.scrollUpButtonID = scrollUpButtonID;
this.scrollDownButtonID = scrollDownButtonID;
}
private void clampScrollToBounds() {
int i = getContentOverhang();
if (i < 0) {
i *= -1;
}
if (amountScrolled < 0.0F) {
amountScrolled = 0.0F;
}
if (amountScrolled > i) {
amountScrolled = i;
}
}
public int getContentOverhang() {
return getContentHeight() - (height - margin);
}
public void actionPerformed(GuiButton b) {
if (b.enabled) {
if (b.id == scrollUpButtonID) {
amountScrolled -= slotHeight * 2 / 3;
initialClickY = -2.0F;
clampScrollToBounds();
} else if (b.id == scrollDownButtonID) {
amountScrolled += slotHeight * 2 / 3;
initialClickY = -2.0F;
clampScrollToBounds();
}
}
}
/**
* draws the slot to the screen, pass in mouse's current x and y and partial ticks
*/
public void drawScreen(int mX, int mY, float partialTick) {
this.mouseX = mX;
this.mouseY = mY;
processMouseEvents();
clampScrollToBounds();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_FOG);
ScaledResolution sr = new ScaledResolution(mc);
int sx = minX * sr.getScaleFactor();
int sw = width * sr.getScaleFactor();
int sy = mc.displayHeight - maxY * sr.getScaleFactor();
int sh = height * sr.getScaleFactor();
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(sx, sy, sw, sh);
VertexBuffer renderer = Tessellator.getInstance().getBuffer();
drawContainerBackground(renderer);
int contentYOffset = this.minY + margin - (int) this.amountScrolled;
for (int i = 0; i < getNumElements(); ++i) {
int elementY = contentYOffset + i * this.slotHeight;
int slotHeight = this.slotHeight - margin;
if (elementY <= maxY && elementY + slotHeight >= minY) {
if (showSelectionBox && i == selectedIndex) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_TEXTURE_2D);
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
renderer.putColor4(8421504);
renderer.pos(minX, elementY + slotHeight + 2, 0.0D).tex(0.0D, 1.0D).endVertex();
renderer.pos(maxX, elementY + slotHeight + 2, 0.0D).tex(1.0D, 1.0D).endVertex();
renderer.pos(maxX, elementY - 2, 0.0D).tex(1.0D, 0.0D).endVertex();
renderer.pos(minX, elementY - 2, 0.0D).tex(0.0D, 0.0D).endVertex();
renderer.putColor4(0);
renderer.pos(minX + 1, elementY + slotHeight + 1, 0.0D).tex(0.0D, 1.0D).endVertex();
renderer.pos(maxX - 1, elementY + slotHeight + 1, 0.0D).tex(1.0D, 1.0D).endVertex();
renderer.pos(maxX - 1, elementY - 1, 0.0D).tex(1.0D, 0.0D).endVertex();
renderer.pos(minX + 1, elementY - 1, 0.0D).tex(0.0D, 0.0D).endVertex();
Tessellator.getInstance().draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
drawElement(i, minX, elementY, slotHeight, renderer);
}
}
GL11.glDisable(GL11.GL_SCISSOR_TEST);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glDisable(GL11.GL_TEXTURE_2D);
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
renderer.putColor4(0);
renderer.pos(this.minX, this.minY + margin, 0.0D).tex(0.0D, 1.0D).endVertex();
renderer.pos(this.maxX, this.minY + margin, 0.0D).tex(1.0D, 1.0D).endVertex();
renderer.putColor4(0xFF000000);
renderer.pos(this.maxX, this.minY, 0.0D).tex(1.0D, 0.0D).endVertex();
renderer.pos(this.minX, this.minY, 0.0D).tex(0.0D, 0.0D).endVertex();
Tessellator.getInstance().draw();
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
renderer.putColor4(0xFF000000);
renderer.pos(this.minX, this.maxY, 0.0D).tex(0.0D, 1.0D).endVertex();
renderer.pos(this.maxX, this.maxY, 0.0D).tex(1.0D, 1.0D).endVertex();
renderer.putColor4(0);
renderer.pos(this.maxX, this.maxY - margin, 0.0D).tex(1.0D, 0.0D).endVertex();
renderer.pos(this.minX, this.maxY - margin, 0.0D).tex(0.0D, 0.0D).endVertex();
Tessellator.getInstance().draw();
renderScrollBar(renderer);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glDisable(GL11.GL_BLEND);
}
protected void renderScrollBar(VertexBuffer renderer) {
int contentHeightOverBounds = getContentOverhang();
if (contentHeightOverBounds > 0) {
int clear = (maxY - minY) * (maxY - minY) / getContentHeight();
if (clear < 32) {
clear = 32;
}
if (clear > maxY - minY - 8) {
clear = maxY - minY - 8;
}
int y = (int) this.amountScrolled * (maxY - minY - clear) / contentHeightOverBounds + minY;
if (y < minY) {
y = minY;
}
GL11.glDisable(GL11.GL_TEXTURE_2D);
int scrollBarMinX = getScrollBarX();
int scrollBarMaxX = scrollBarMinX + 6;
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
renderer.putColor4(0xFF000000);
renderer.pos(scrollBarMinX, maxY, 0.0D).tex(0.0D, 1.0D).endVertex();
renderer.pos(scrollBarMaxX, maxY, 0.0D).tex(1.0D, 1.0D).endVertex();
renderer.pos(scrollBarMaxX, minY, 0.0D).tex(1.0D, 0.0D).endVertex();
renderer.pos(scrollBarMinX, minY, 0.0D).tex(0.0D, 0.0D).endVertex();
renderer.putColorRGB_F4(0.3f, 0.3f, 0.3f);
renderer.pos(scrollBarMinX, y + clear, 0.0D).tex(0.0D, 1.0D).endVertex();
renderer.pos(scrollBarMaxX, y + clear, 0.0D).tex(1.0D, 1.0D).endVertex();
renderer.pos(scrollBarMaxX, y, 0.0D).tex(1.0D, 0.0D).endVertex();
renderer.pos(scrollBarMinX, y, 0.0D).tex(0.0D, 0.0D).endVertex();
renderer.putColorRGB_F4(0.7f, 0.7f, 0.7f);
renderer.pos(scrollBarMinX, y + clear - 1, 0.0D).tex(0.0D, 1.0D).endVertex();
renderer.pos(scrollBarMaxX - 1, y + clear - 1, 0.0D).tex(1.0D, 1.0D).endVertex();
renderer.pos(scrollBarMaxX - 1, y, 0.0D).tex(1.0D, 0.0D).endVertex();
renderer.pos(scrollBarMinX, y, 0.0D).tex(0.0D, 0.0D).endVertex();
Tessellator.getInstance().draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
}
private void processMouseEvents() {
if (Mouse.isButtonDown(0)) {
processMouseBown();
} else {
while (!mc.gameSettings.touchscreen && Mouse.next()) {
int mouseWheelDelta = Mouse.getEventDWheel();
if (mouseWheelDelta != 0) {
if (mouseWheelDelta > 0) {
mouseWheelDelta = -1;
} else if (mouseWheelDelta < 0) {
mouseWheelDelta = 1;
}
amountScrolled += mouseWheelDelta * slotHeight / 2;
}
}
initialClickY = -1.0F;
}
}
private void processMouseBown() {
int contentHeightOverBounds;
if (initialClickY == -1.0F) {
if (mouseY >= minY && mouseY <= maxY && mouseX >= minX && mouseX <= maxX + 6) {
boolean clickInBounds = true;
int y = mouseY - minY + (int) amountScrolled - margin;
int mouseOverElement = y / slotHeight;
if (mouseX >= minX && mouseX <= maxX && mouseOverElement >= 0 && y >= 0 && mouseOverElement < getNumElements()) {
boolean doubleClick = mouseOverElement == selectedIndex && Minecraft.getSystemTime() - lastClickedTime < 250L;
if (elementClicked(mouseOverElement, doubleClick)) {
setSelection(mouseOverElement);
}
lastClickedTime = Minecraft.getSystemTime();
} else if (mouseX >= minX && mouseX <= maxX && y < 0) {
clickInBounds = false;
}
int scrollBarMinX = getScrollBarX();
int scrollBarMaxX = scrollBarMinX + 6;
if (mouseX >= scrollBarMinX && mouseX <= scrollBarMaxX) {
scrollMultiplier = -1.0F;
contentHeightOverBounds = getContentOverhang();
if (contentHeightOverBounds < 1) {
contentHeightOverBounds = 1;
}
int empty = (int) ((float) ((maxY - minY) * (maxY - minY)) / (float) getContentHeight());
if (empty < 32) {
empty = 32;
}
if (empty > maxY - minY - 8) {
empty = maxY - minY - 8;
}
scrollMultiplier /= (float) (maxY - minY - empty) / (float) contentHeightOverBounds;
} else {
scrollMultiplier = 1.0F;
}
if (clickInBounds) {
initialClickY = mouseY;
} else {
initialClickY = -2.0F;
}
} else {
initialClickY = -2.0F;
}
} else if (initialClickY >= 0.0F) {
// Scrolling
amountScrolled -= (mouseY - initialClickY) * scrollMultiplier;
initialClickY = mouseY;
}
}
protected int getScrollBarX() {
return minX + width;
}
protected void drawContainerBackground(VertexBuffer renderer) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_TEXTURE_2D);
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR);
renderer.putColor4(2105376);
renderer.pos(minX, maxY, 0.0D).endVertex();
renderer.pos(maxX, maxY, 0.0D).endVertex();
renderer.pos(maxX, minY, 0.0D).endVertex();
renderer.pos(minX, minY, 0.0D).endVertex();
Tessellator.getInstance().draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
}
|
robertsawko/proteus | scripts/readFun.py | <filename>scripts/readFun.py
#! /usr/bin/env python
from numpy import *
import proteus
from proteus.MeshTools import *
from proteus.FemTools import *
## \ingroup scripts
#
# \file readFun.py
#
# \brief A script for reading an ADH .3dm mesh and .data file to build a finite element function.
def readFun():
from optparse import OptionParser
usage = "usage: %readFun [options] meshFile funFile funOutFile"
parser = OptionParser(usage=usage)
parser.add_option("-m", "--matlab",
help="print edges to files for plotting in matlab",
action="store_true",
dest="matlab",
default=False)
parser.add_option("-M", "--view-matlab",
help="plot edges in matlab",
action="store_true",
dest="viewMatlab",
default=False)
parser.add_option("-x", "--nnodes-x",
help="use NX nodes in the x direction",
action="store",
type="int",
dest="nx",
default=2)
parser.add_option("-y", "--nnodes-y",
help="use NY nodes in the y direction",
action="store",
type="int",
dest="ny",
default=2)
parser.add_option("-z", "--nnodes-z",
help="use NZ nodes in the z direction",
action="store",
type="int",
dest="nz",
default=2)
(opts, args) = parser.parse_args()
if len(args) == 3:
meshFilename = args[0]
funFilename = args[1]
funOutFilename = args[2]
else:
print(usage)
exit(1)
mesh=TetrahedralMesh()
mesh.readMeshADH(meshFilename)
spaceMap = SpaceMapping(mesh)
funIn = open(funFilename,'r')
nNodes=0
fun = []
data = []
for i in range(6):
line = funIn.readline()
print line.strip()
words = line.split()
if words[0] == 'ND':
nNodes = int(words[1])
line = funIn.readline()
while line.strip() != 'ENDDS':
print "Reading "+line.strip()
words = line.split()
u = zeros(nNodes,Float)
for i in range(nNodes):
u[mesh.oldToNewNode[i]] = float(funIn.readline())
data.append(u)
fun.append(ScalarFiniteElementFunction(u,
mesh,
LinearNodalBasisTet(),
NodalInterpolationConditions(mesh)))
line = funIn.readline()
print "Read %i timesteps" % len(fun)
#find maximum coorindates (assume they are positive)
nodesX = mesh.nodeArray[:][0]
nodesY = mesh.nodeArray[:][1]
nodesZ = mesh.nodeArray[:][2]
maxx = max(nodesX)
maxy = max(nodesY)
maxz = max(nodesZ)
minx = min(nodesX)
miny = min(nodesY)
minz = min(nodesZ)
offSet = EVec(minx,miny,minz)
Lx = maxx - minx
Ly = maxy - miny
Lz = maxz - minz
print "Building rectangular output grid ["+`minx`+","+`maxx`+"] (x), [" + \
`miny`+","+`maxy`+"] (y), [" + \
`minz`+","+`maxz`+"] (z)"
outputGrid = RectangularGrid(opts.nx,opts.ny,opts.nz,Lx,Ly,Lz)
#now compute the projection of the mesh and solution onto this grid
eList={}
xiList={}
xOut = open('x.grf','w')
yOut = open('y.grf','w')
zOut = open('z.grf','w')
for k in range(outputGrid.nz):
for j in range(outputGrid.ny):
for i in range(outputGrid.nx):
X = outputGrid.getNode(i,j,k)+offSet
e = spaceMap.findElement(X)
eList[(i,j,k)]=e
if e!='OFFMESH':
xiList[(i,j,k)]=spaceMap.inverseAffineMap(e,X)
xOut.write('%15.8e '% X.x())
yOut.write('%15.8e '% X.y())
zOut.write('%15.8e '% X.z())
xOut.write('\n')
yOut.write('\n')
zOut.write('\n')
xOut.close()
yOut.close()
zOut.close()
U = zeros((opts.nx,opts.ny,opts.nz),Float)
for ts,f in enumerate(fun):
funOut = open(funOutFilename+`ts`+'.grf','w')
for k in range(outputGrid.nz):
for j in range(outputGrid.ny):
for i in range(outputGrid.nx):
if eList[(i,j,k)] != 'OFFMESH':
U[i,j,k] = f.u_of_xi(eList[(i,j,k)],xiList[(i,j,k)])
else:
U[i,j,k] = float('nan')
funOut.write('%15.8e '% U[i,j,k])
funOut.write('\n')
funOut.close()
if __name__ == '__main__':
# import sys
# import profile
# profile.run('readFun(sys.argv[1],sys.argv[2],sys.argv[3])','readFunProf')
# import pstats
# p = pstats.Stats('readFunProf')
# p.sort_stats('cumulative').print_stats(20)
# p.sort_stats('time').print_stats(20)
readFun()
|
vbauer/caesar | src/test/java/com/github/vbauer/caesar/runner/impl/FutureMethodRunnerTest.java | <filename>src/test/java/com/github/vbauer/caesar/runner/impl/FutureMethodRunnerTest.java<gh_stars>100-1000
package com.github.vbauer.caesar.runner.impl;
import com.github.vbauer.caesar.basic.BasicRunnerTest;
import com.github.vbauer.caesar.exception.MissedSyncMethodException;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* @author <NAME>
*/
public class FutureMethodRunnerTest extends BasicRunnerTest {
@Test(expected = CancellationException.class)
public void testTimeout() throws Throwable {
final Future<Boolean> future = getFutureAsync().timeout();
Assert.assertNotNull(future);
Assert.fail(String.valueOf(future.get()));
}
@Test
public void testWithoutResult() throws Throwable {
getSync().empty();
final Future<Void> future = getFutureAsync().empty();
Assert.assertNotNull(future);
Assert.assertNull(future.get());
}
@Test
public void test1ArgumentWithoutResult() throws Throwable {
getSync().emptyHello(PARAMETER);
final Future<Void> future = getFutureAsync().emptyHello(PARAMETER);
Assert.assertNotNull(future);
Assert.assertNull(future.get());
}
@Test
public void test1ArgumentWithResult() throws Throwable {
Assert.assertEquals(getSync().hello(PARAMETER), getFutureAsync().hello(PARAMETER).get());
}
@Test
public void test2ArgumentsWithResult() throws Throwable {
Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), getFutureAsync().hello(PARAMETER, PARAMETER).get());
}
@Test(expected = ExecutionException.class)
public void testException() throws Throwable {
getFutureAsync().exception().get();
Assert.fail();
}
@Test(expected = MissedSyncMethodException.class)
public void testIncorrectProxyOnDemand() {
Assert.fail(String.valueOf(getFutureAsync().methodWithoutSyncImpl()));
}
}
|
job-hunter-toolkit/job-hunter-toolk | jobpostings/uber.go | package jobpostings
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
)
type uberInfo struct {
//Status string `json:"status"`
Data struct {
Results []struct {
ID int `json:"id"`
Title string `json:"title"`
//Description string `json:"description"`
//InternalDescription string `json:"internalDescription"`
//ManagerID int `json:"managerID"`
//Department string `json:"department"`
//Type string `json:"type"`
//ProgramAndPlatform string `json:"programAndPlatform"`
Location struct {
Country string `json:"country"`
Region string `json:"region"`
City string `json:"city"`
} `json:"location"`
//Featured bool `json:"featured"`
//Level string `json:"level"`
//CreationDate time.Time `json:"creationDate"`
//OtherLevels interface{} `json:"otherLevels"`
//Team string `json:"team"`
//PortalID string `json:"portalID"`
//IsPipeline bool `json:"isPipeline"`
//ManagerFirstName string `json:"managerFirstName"`
//ManagerLastName string `json:"managerLastName"`
//ManagerEmail string `json:"managerEmail"`
//ManagerRole string `json:"managerRole"`
//RecruiterID int `json:"recruiterID"`
//RecruiterFirstName string `json:"recruiterFirstName"`
//RecruiterLastName string `json:"recruiterLastName"`
//RecruiterEmail string `json:"recruiterEmail"`
//StatusID string `json:"statusID"`
//StatusName string `json:"statusName"`
//UpdatedDate time.Time `json:"updatedDate"`
//UniqueSkills string `json:"uniqueSkills"`
//TimeType string `json:"timeType"`
} `json:"results"`
//TotalResults struct {
// Low int `json:"low"`
// High int `json:"high"`
// Unsigned bool `json:"unsigned"`
//} `json:"totalResults"`
} `json:"data"`
}
// GetUberJobPostings finds JobPostings found at https://www.uber.com/api/loadSearchJobsResults
func GetUberJobPostings(ctx context.Context) (<-chan *JobPosting, error) {
body := strings.NewReader("{\"limit\":10,\"page\":0,\"params\":{}}")
req, err := http.NewRequest("POST", "https://www.uber.com/api/loadSearchJobsResults", body)
if err != nil {
return nil, err
}
req.Header.Set("X-Csrf-Token", "<3")
req.Header.Set("Content-Type", "application/json")
req = req.WithContext(ctx)
resp, err := HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
doc := uberInfo{}
err = json.NewDecoder(resp.Body).Decode(&doc)
if err != nil {
return nil, err
}
company := "uber"
jobPostings := make(chan *JobPosting)
go func() {
defer close(jobPostings)
for _, item := range doc.Data.Results {
url := "https://www.uber.com/global/en/careers/list/" + fmt.Sprintf("%d", item.ID)
titleStr := strings.TrimSpace(item.Title)
locationStr := strings.TrimSpace(fmt.Sprintf("%s, %s, %s", item.Location.Country, item.Location.Region, item.Location.City))
jobPostings <- &JobPosting{
Company: company,
URL: url,
Title: titleStr,
Location: locationStr,
}
}
}()
return jobPostings, nil
}
|
trungtuan/motech | platform/event/src/test/java/org/motechproject/event/it/EventHandlerForServerEventRelayTransactionIT.java | <filename>platform/event/src/test/java/org/motechproject/event/it/EventHandlerForServerEventRelayTransactionIT.java<gh_stars>1-10
package org.motechproject.event.it;
import org.motechproject.event.MotechEvent;
import org.motechproject.event.listener.annotations.MotechListener;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class EventHandlerForServerEventRelayTransactionIT {
public static final String FAILING_EVENT_SUBJECT = "FailingEventSubject";
public static final String SUCCESSFUL_EVENT_SUBJECT = "SuccessfulEventSubject";
public static final String LONG_RUNNING_PROCESS = "LongRunningProcess";
public static final int TASK_DURATION = 3;
private boolean doThrowException;
private int retries;
public EventHandlerForServerEventRelayTransactionIT setupForFailure(boolean doThrowException) {
this.doThrowException = doThrowException;
retries = 0;
return this;
}
@MotechListener(subjects = {FAILING_EVENT_SUBJECT})
public void canFail(MotechEvent motechEvent) {
retries++;
if (doThrowException) throw new RuntimeException();
}
public int retries() {
return retries;
}
@MotechListener(subjects = {SUCCESSFUL_EVENT_SUBJECT})
public void wouldPass(MotechEvent motechEvent) {
}
@MotechListener(subjects = {LONG_RUNNING_PROCESS})
public void handleLongRunningProcess(MotechEvent motechEvent) throws Exception{
System.out.println(new Date() + "|" + Thread.currentThread().getId() + " handleLongRunningProcess start");
Thread.sleep(1000* TASK_DURATION);
System.out.println(new Date() + "|" + Thread.currentThread().getId() + " handleLongRunningProcess end");
}
}
|
KerakTelor86/AlgoCopypasta | source/01_Miscellaneous/07_Random Primes.cpp | 36671 74101 724729 825827 924997 1500005681 2010408371 2010405347
|
openstack-atlas/atlas-lb | core-api/core-common-api/src/test/java/org/opestack/atlas/api/validation/validator/HealthMonitorValidatorTest.java | <gh_stars>1-10
package org.opestack.atlas.api.validation.validator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.openstack.atlas.api.validation.result.ValidatorResult;
import org.openstack.atlas.api.validation.validator.HealthMonitorValidator;
import org.openstack.atlas.api.validation.validator.builder.ConnectMonitorValidatorBuilder;
import org.openstack.atlas.api.validation.validator.builder.HealthMonitorValidatorBuilder;
import org.openstack.atlas.api.validation.validator.builder.HttpMonitorValidatorBuilder;
import org.openstack.atlas.core.api.v1.HealthMonitor;
import org.openstack.atlas.service.domain.stub.StubFactory;
import static org.openstack.atlas.api.validation.context.HttpRequestType.PUT;
@RunWith(Enclosed.class)
public class HealthMonitorValidatorTest {
public static class WhenValidatingPutContextForConnectMonitor {
private HealthMonitor healthMonitor;
private HealthMonitorValidator validator;
@Before
public void standUp() {
validator = new HealthMonitorValidator(
new HealthMonitorValidatorBuilder(
new ConnectMonitorValidatorBuilder(),
new HttpMonitorValidatorBuilder()));
healthMonitor = StubFactory.createHydratedDataModelConnectMonitorForPut();
}
@Test
public void shouldPassValidationWhenGivenAValidMonitor() {
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertTrue(result.passedValidation());
}
@Test
public void shouldPassValidationWhenSpecifyingOnlyDelay() {
healthMonitor.setTimeout(null);
healthMonitor.setAttemptsBeforeDeactivation(null);
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertTrue(result.passedValidation());
}
@Test
public void shouldPassValidationWhenSpecifyingOnlyTimeout() {
healthMonitor.setDelay(null);
healthMonitor.setAttemptsBeforeDeactivation(null);
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertTrue(result.passedValidation());
}
@Test
public void shouldPassValidationWhenSpecifyingOnlyAttempts() {
healthMonitor.setDelay(null);
healthMonitor.setTimeout(null);
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertTrue(result.passedValidation());
}
@Test
public void shouldFailValidationWhenPassingInANullHealthMonitor() {
ValidatorResult result = validator.validate(null, PUT);
Assert.assertFalse(result.passedValidation());
}
@Test
public void shouldFailValidationWhenPassingInAnEmptyHealthMonitor() {
ValidatorResult result = validator.validate(new HealthMonitor(), PUT);
Assert.assertFalse(result.passedValidation());
}
@Test
public void shouldFailValidationWhenNoMainAttributesSet() {
healthMonitor.setDelay(null);
healthMonitor.setTimeout(null);
healthMonitor.setAttemptsBeforeDeactivation(null);
ValidatorResult result = validator.validate(new HealthMonitor(), PUT);
Assert.assertFalse(result.passedValidation());
}
@Test
public void shouldFailValidationWhenSpecifyingPath() {
healthMonitor.setPath("/this/should/not/be/set");
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertFalse(result.passedValidation());
}
}
public static class WhenValidatingPutContextForHttpMonitor {
private HealthMonitor healthMonitor;
private HealthMonitorValidator validator;
@Before
public void standUp() {
validator = new HealthMonitorValidator(
new HealthMonitorValidatorBuilder(
new ConnectMonitorValidatorBuilder(),
new HttpMonitorValidatorBuilder()));
healthMonitor = StubFactory.createHydratedDataModelHttpMonitorForPut();
}
@Test
public void shouldPassValidationWhenGivenAValidMonitor() {
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertTrue(result.passedValidation());
}
@Test
public void shouldPassValidationWhenSpecifyingOnlyDelay() {
healthMonitor.setTimeout(null);
healthMonitor.setAttemptsBeforeDeactivation(null);
healthMonitor.setPath(null);
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertTrue(result.passedValidation());
}
@Test
public void shouldPassValidationWhenSpecifyingOnlyTimeout() {
healthMonitor.setDelay(null);
healthMonitor.setAttemptsBeforeDeactivation(null);
healthMonitor.setPath(null);
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertTrue(result.passedValidation());
}
@Test
public void shouldPassValidationWhenSpecifyingOnlyAttempts() {
healthMonitor.setDelay(null);
healthMonitor.setTimeout(null);
healthMonitor.setPath(null);
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertTrue(result.passedValidation());
}
@Test
public void shouldPassValidationWhenSpecifyingOnlyPath() {
healthMonitor.setDelay(null);
healthMonitor.setTimeout(null);
healthMonitor.setAttemptsBeforeDeactivation(null);
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertTrue(result.passedValidation());
}
@Test
public void shouldFailValidationWhenPassingInANullHealthMonitor() {
ValidatorResult result = validator.validate(null, PUT);
Assert.assertFalse(result.passedValidation());
}
@Test
public void shouldFailValidationWhenPassingInAnEmptyHealthMonitor() {
ValidatorResult result = validator.validate(new HealthMonitor(), PUT);
Assert.assertFalse(result.passedValidation());
}
@Test
public void shouldFailValidationWhenNoMainAttributesSet() {
healthMonitor.setDelay(null);
healthMonitor.setTimeout(null);
healthMonitor.setAttemptsBeforeDeactivation(null);
healthMonitor.setPath(null);
ValidatorResult result = validator.validate(healthMonitor, PUT);
Assert.assertFalse(result.passedValidation());
}
}
}
|
djewsbury/XLE | RenderCore/Techniques/ShaderVariationSet.cpp | // Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "ShaderVariationSet.h"
#include "ParsingContext.h"
#include "../Types.h"
#include "../FrameBufferDesc.h"
#include "../UniformsStream.h"
#include "../BufferView.h"
#include "../Metal/InputLayout.h"
#include "../Metal/Shader.h"
#include "../Metal/DeviceContext.h"
#include "../Metal/PipelineLayout.h"
#include "../../ShaderParser/AutomaticSelectorFiltering.h"
#include "../../ShaderParser/ShaderAnalysis.h"
#include "../../Assets/AssetsCore.h"
#include "../../Assets/Assets.h"
#include "../../Assets/Continuation.h"
#include "../../Utility/Streams/PreprocessorInterpreter.h"
namespace RenderCore { namespace Techniques
{
static uint64_t Hash(IteratorRange<const ParameterBox* const*> shaderSelectors)
{
if (shaderSelectors.empty()) return 0;
uint64_t inputHash = 0;
const bool simpleHash = false;
if (constant_expression<simpleHash>::result()) {
for (unsigned c = 0; c < shaderSelectors.size(); ++c) {
inputHash ^= shaderSelectors[c]->GetParameterNamesHash();
inputHash ^= shaderSelectors[c]->GetHash() << (c * 6); // we have to be careful of cases where the values in one box is very similar to the values in another
}
} else {
inputHash = HashCombine(shaderSelectors[0]->GetHash(), shaderSelectors[0]->GetParameterNamesHash());
for (unsigned c = 1; c < shaderSelectors.size(); ++c) {
inputHash = HashCombine(shaderSelectors[c]->GetParameterNamesHash(), inputHash);
inputHash = HashCombine(shaderSelectors[c]->GetHash(), inputHash);
}
}
return inputHash;
}
static std::string MakeFilteredDefinesTable(
IteratorRange<const ParameterBox* const*> selectors,
const ShaderSourceParser::ManualSelectorFiltering& techniqueFiltering,
IteratorRange<const ShaderSourceParser::SelectorFilteringRules**> automaticFiltering,
const ShaderSourceParser::SelectorPreconfiguration* preconfiguration)
{
if (!preconfiguration) {
const ParameterBox* p[selectors.size()+1];
p[0] = &techniqueFiltering._setValues;
for (unsigned c=0; c<selectors.size(); ++c) p[c+1] = selectors[c];
return BuildFlatStringTable(ShaderSourceParser::FilterSelectors({p, p+selectors.size()+1}, techniqueFiltering._relevanceMap, automaticFiltering));
} else {
// If we have a preconfiguration file, we need to run that over the selectors first. It will define or undefine
// selectors based on it's script. Because it can also undefine, we need to be working with non-const parameter boxes
// and so we might as well just merge together all of the param boxes here to make the next few steps a little
// easier
if (selectors.empty()) {
ParameterBox empty;
ParameterBox* p = ∅
return MakeFilteredDefinesTable({&p, &p+1}, techniqueFiltering, automaticFiltering, preconfiguration);
}
// Merge in the "_setValues" from technique filtering, so it can be available to the preconfiguration operation
ParameterBox mergedSelectors = techniqueFiltering._setValues;
for (auto i=selectors.begin(); i!=selectors.end(); ++i)
mergedSelectors.MergeIn(**i);
mergedSelectors = preconfiguration->Preconfigure(std::move(mergedSelectors));
ParameterBox* p = &mergedSelectors;
return BuildFlatStringTable(ShaderSourceParser::FilterSelectors({&p, &p+1}, techniqueFiltering._relevanceMap, automaticFiltering));
}
}
auto UniqueShaderVariationSet::FilterSelectors(
IteratorRange<const ParameterBox* const*> selectors,
const ShaderSourceParser::ManualSelectorFiltering& techniqueFiltering,
IteratorRange<const ShaderSourceParser::SelectorFilteringRules**> automaticFiltering,
const ShaderSourceParser::SelectorPreconfiguration* preconfiguration) -> const FilteredSelectorSet&
{
auto inputHash = Hash(selectors);
inputHash = HashCombine(techniqueFiltering.GetHash(), inputHash);
for (const auto*f:automaticFiltering)
inputHash = HashCombine(f->GetHash(), inputHash);
if (preconfiguration)
inputHash = HashCombine(preconfiguration->GetHash(), inputHash);
auto i = LowerBound(_globalToFiltered, inputHash);
if (i!=_globalToFiltered.cend() && i->first == inputHash) {
return i->second;
} else {
FilteredSelectorSet result;
result._selectors = MakeFilteredDefinesTable(selectors, techniqueFiltering, automaticFiltering, preconfiguration);
result._hashValue = result._selectors.empty() ? 0ull : Hash64(result._selectors);
i = _globalToFiltered.insert(i, {inputHash, result});
return i->second;
}
}
UniqueShaderVariationSet::UniqueShaderVariationSet() {}
UniqueShaderVariationSet::~UniqueShaderVariationSet() {}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class TechniqueShaderVariationSet::Variation
{
public:
::Assets::PtrToMarkerPtr<Metal::ShaderProgram> _shaderFuture;
};
::Assets::PtrToMarkerPtr<Metal::ShaderProgram> TechniqueShaderVariationSet::FindVariation(
int techniqueIndex,
const ParameterBox* shaderSelectors[SelectorStages::Max])
{
const auto& techEntry = _technique->GetEntry(techniqueIndex);
auto& filteredSelectors = _variationSet.FilterSelectors(
MakeIteratorRange(shaderSelectors, &shaderSelectors[SelectorStages::Max]),
techEntry._selectorFiltering, {}, nullptr);
auto i = LowerBound(_filteredSelectorsToVariation, filteredSelectors._hashValue);
if (i != _filteredSelectorsToVariation.end() && i->first == filteredSelectors._hashValue) {
return i->second._shaderFuture;
} else {
Variation variation;
assert(!techEntry._vertexShaderName.empty());
assert(!techEntry._pixelShaderName.empty());
if (techEntry._geometryShaderName.empty()) {
variation._shaderFuture = ::Assets::MakeAssetPtr<Metal::ShaderProgram>(_pipelineLayout, techEntry._vertexShaderName, techEntry._pixelShaderName, filteredSelectors._selectors);
} else {
variation._shaderFuture = ::Assets::MakeAssetPtr<Metal::ShaderProgram>(_pipelineLayout, techEntry._vertexShaderName, techEntry._geometryShaderName, techEntry._pixelShaderName, filteredSelectors._selectors);
}
i = _filteredSelectorsToVariation.insert(i, std::make_pair(filteredSelectors._hashValue, variation));
return i->second._shaderFuture;
}
}
TechniqueShaderVariationSet::TechniqueShaderVariationSet(
const std::shared_ptr<Technique>& technique,
const std::shared_ptr<ICompiledPipelineLayout>& pipelineLayout)
: _technique(technique)
, _pipelineLayout(pipelineLayout)
{}
TechniqueShaderVariationSet::~TechniqueShaderVariationSet(){}
const ::Assets::DependencyValidation& TechniqueShaderVariationSet::GetDependencyValidation() const
{
return _technique->GetDependencyValidation();
}
void TechniqueShaderVariationSet::ConstructToPromise(
std::promise<std::shared_ptr<TechniqueShaderVariationSet>>&& promise,
StringSection<::Assets::ResChar> modelScaffoldName,
const std::shared_ptr<ICompiledPipelineLayout>& pipelineLayout)
{
auto scaffoldFuture = ::Assets::MakeAssetPtr<Technique>(modelScaffoldName);
::Assets::WhenAll(scaffoldFuture).ThenConstructToPromise(
std::move(promise),
[pipelineLayout](std::shared_ptr<Technique> technique) {
return std::make_shared<TechniqueShaderVariationSet>(technique, pipelineLayout);
});
}
}}
|
thejihuijin/realsense_sdk | sdk/src/cameras/playback/include/playback_device_impl.h | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved.
#pragma once
#include <memory>
#include <mutex>
#include <thread>
#include <queue>
#include <condition_variable>
#include "playback_device_interface.h"
#include "disk_read_interface.h"
#include "rs_stream_impl.h"
#ifdef WIN32
#ifdef realsense_playback_EXPORTS
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif /* realsense_playback_EXPORTS */
#else /* defined (WIN32) */
#define DLL_EXPORT
#endif
namespace rs
{
namespace playback
{
class rs_frame_ref_impl : public rs_frame_ref
{
public:
rs_frame_ref_impl(std::shared_ptr<rs::core::file_types::frame_sample> frame) : m_frame(frame) {}
std::shared_ptr<rs::core::file_types::frame_sample> get_frame() { return m_frame; }
virtual const uint8_t *get_frame_data() const override { return m_frame->data; }
virtual double get_frame_timestamp() const override { return m_frame->finfo.time_stamp; }
virtual unsigned long long get_frame_number() const override { return m_frame->finfo.number; }
virtual long long get_frame_system_time() const override { return m_frame->finfo.system_time; }
virtual int get_frame_width() const override { return m_frame->finfo.width; }
virtual int get_frame_height() const override { return m_frame->finfo.height; }
virtual int get_frame_framerate() const override { return m_frame->finfo.framerate; }
virtual int get_frame_stride() const override { return m_frame->finfo.stride; }
virtual int get_frame_bpp() const override { return m_frame->finfo.bpp; }
virtual rs_format get_frame_format() const override { return m_frame->finfo.format; }
virtual rs_stream get_stream_type() const override { return m_frame->finfo.stream; }
virtual rs_timestamp_domain get_frame_timestamp_domain() const { return m_frame->finfo.time_stamp_domain; }
virtual double get_frame_metadata(rs_frame_metadata frame_metadata) const override { return m_frame->metadata.at(frame_metadata); }
virtual bool supports_frame_metadata(rs_frame_metadata frame_metadata) const override { return m_frame->metadata.find(frame_metadata) != m_frame->metadata.end(); }
private:
std::shared_ptr<rs::core::file_types::frame_sample> m_frame;
};
struct thread_sync
{
std::thread thread;
std::mutex mutex;
std::condition_variable sample_ready_cv;
};
struct frame_thread_sync : public thread_sync
{
std::condition_variable sample_deleted_cv;
std::shared_ptr<core::file_types::frame_sample> sample;
std::shared_ptr<rs_frame_callback> callback;
uint32_t active_samples_count;
};
struct imu_thread_sync : public thread_sync
{
std::queue<std::shared_ptr<core::file_types::sample>> samples;
std::shared_ptr<rs_motion_callback> motion_callback;
std::shared_ptr<rs_timestamp_callback> time_stamp_callback;
uint32_t max_queue_size;
void push_sample_to_user(std::shared_ptr<core::file_types::sample> sample)
{
if(sample->info.type == core::file_types::sample_type::st_motion && motion_callback)
{
auto motion = std::dynamic_pointer_cast<core::file_types::motion_sample>(sample);
if(motion)
motion_callback->on_event(motion->data);
}
if(sample->info.type == core::file_types::sample_type::st_time && time_stamp_callback)
{
auto time_stamp = std::dynamic_pointer_cast<core::file_types::time_stamp_sample>(sample);
if(time_stamp)
time_stamp_callback->on_event(time_stamp->data);
}
}
};
class DLL_EXPORT rs_device_ex : public device_interface
{
public:
rs_device_ex(const std::string &file_path);
virtual ~rs_device_ex();
virtual const rs_stream_interface & get_stream_interface(rs_stream stream) const override;
virtual const char * get_name() const override;
virtual const char * get_serial() const override;
virtual const char * get_firmware_version() const override;
virtual float get_depth_scale() const override;
virtual void enable_stream(rs_stream stream, int width, int height, rs_format format, int fps, rs_output_buffer_format output) override;
virtual void enable_stream_preset(rs_stream stream, rs_preset preset) override;
virtual void disable_stream(rs_stream stream) override;
virtual void enable_motion_tracking() override;
virtual void set_stream_callback(rs_stream stream, void(*on_frame)(rs_device * device, rs_frame_ref * frame, void * user), void * user) override;
virtual void set_stream_callback(rs_stream stream, rs_frame_callback * callback) override;
virtual void disable_motion_tracking() override;
virtual void set_motion_callback(void(*on_event)(rs_device * device, rs_motion_data data, void * user), void * user) override;
virtual void set_motion_callback(rs_motion_callback * callback) override;
virtual void set_timestamp_callback(void(*on_event)(rs_device * device, rs_timestamp_data data, void * user), void * user) override;
virtual void set_timestamp_callback(rs_timestamp_callback * callback) override;
virtual void start(rs_source source) override;
virtual void stop(rs_source source) override;
virtual bool is_capturing() const override;
virtual int is_motion_tracking_active() const override;
virtual void wait_all_streams() override;
virtual bool poll_all_streams() override;
virtual bool supports(rs_capabilities capability) const override;
virtual bool supports(rs_camera_info info_param) const override;
virtual bool supports_option(rs_option option) const override;
virtual void get_option_range(rs_option option, double & min, double & max, double & step, double & def) override;
virtual void set_options(const rs_option options[], size_t count, const double values[]) override;
virtual void get_options(const rs_option options[], size_t count, double values[]) override;
virtual void release_frame(rs_frame_ref * ref) override;
virtual rs_frame_ref * clone_frame(rs_frame_ref * frame) override;
virtual const char * get_usb_port_id() const;
virtual const char * get_camera_info(rs_camera_info info_type) const;
virtual rs_motion_intrinsics get_motion_intrinsics() const;
virtual rs_extrinsics get_motion_extrinsics_from(rs_stream from) const;
virtual void start_fw_logger(char fw_log_op_code, int grab_rate_in_ms, std::timed_mutex &mutex);
virtual void stop_fw_logger();
virtual const char * get_option_description(rs_option option) const;
virtual bool init() override;
virtual bool is_real_time() override;
virtual void pause() override;
virtual void resume() override;
virtual bool set_frame_by_index(int index, rs_stream stream) override;
virtual bool set_frame_by_timestamp(uint64_t timestamp) override;
virtual void set_real_time(bool realtime) override;
virtual int get_frame_index(rs_stream stream) override;
virtual int get_frame_count(rs_stream stream) override;
virtual int get_frame_count() override;
virtual playback::file_info get_file_info() override;
private:
bool all_streams_available();
void set_enabled_streams();
void start_callbacks_threads();
void join_callbacks_threads();
void signal_all();
void end_of_file();
void frame_callback_thread(rs_stream stream);
void motion_callback_thread();
void handle_frame_callback(std::shared_ptr<core::file_types::sample> sample);
void handle_motion_callback(std::shared_ptr<core::file_types::sample> sample);
bool wait_for_active_frames();
void internal_pause();
static const int LIBREALSENSE_IMU_BUFFER_SIZE = 12;
bool m_wait_streams_request;
std::condition_variable m_all_stream_available_cv;
std::mutex m_all_stream_available_mutex;
bool m_is_streaming;
std::mutex m_mutex;
std::mutex m_pause_resume_mutex;
std::string m_file_path;
std::map<rs_stream,std::unique_ptr<rs_stream_impl>> m_available_streams;
std::map<rs_stream,std::shared_ptr<core::file_types::frame_sample>> m_curr_frames;
std::map<rs_stream, frame_thread_sync> m_frame_thread;
imu_thread_sync m_imu_thread;
std::unique_ptr<disk_read_interface> m_disk_read;
size_t m_enabled_streams_count;
};
}
}
|
xyxiaoyou/snappy-store | tests/core/src/main/java/com/gemstone/gemfire/internal/size/ObjectTraverserPerf.java | /*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal.size;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import com.gemstone.gemfire.DataSerializable;
import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.internal.HeapDataOutputStream;
import com.gemstone.gemfire.internal.shared.Version;
/**
* @author dsmith
*
*/
public class ObjectTraverserPerf {
private static final int ITERATIONS = 1000;
private static final int OBJECT_DEPTH = 1000;
private static final boolean USE_SERIALIZATION = true;
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, IOException {
TestObject testObject = new TestObject(null);
for(int i =0; i < OBJECT_DEPTH; i++) {
testObject = new TestObject(testObject);
}
//warm up
for(int i = 0; i < ITERATIONS; i++) {
calcSize(testObject);
}
long start = System.nanoTime();
for(int i = 0; i < ITERATIONS; i++) {
calcSize(testObject);
}
long end = System.nanoTime();
System.out.println("Sized object of depth " + OBJECT_DEPTH + " for " + ITERATIONS + " iterations elapsed(ns) :" + (end - start));
}
private static void calcSize(TestObject testObject)
throws IllegalAccessException, IOException {
if(USE_SERIALIZATION) {
// NullDataOutputStream out = new NullDataOutputStream();
HeapDataOutputStream out= new HeapDataOutputStream(Version.CURRENT);
testObject.toData(out);
} else {
ObjectGraphSizer.size(testObject);
}
}
public static class TestObject implements DataSerializable {
public int field1;
public int field2;
public final String field3 = new String("hello");
public final DataSerializable field4;
public TestObject(DataSerializable field4) {
this.field4 = field4;
}
public void fromData(DataInput in) throws IOException,
ClassNotFoundException {
throw new UnsupportedOperationException("Don't need this method for the test");
}
public void toData(DataOutput out) throws IOException {
out.write(field1);
out.write(field2);
DataSerializer.writeString(field3, out);
if(field4 != null) {
field4.toData(out);
}
}
}
}
|
FAD95/NEXT.JS-Course | node_modules/@iconify/icons-mdi/src/violin.js | <gh_stars>1-10
let data = {
"body": "<path d=\"M11 2a1 1 0 0 0-1 1v6a.5.5 0 0 0 .5.5H12a.5.5 0 0 1 .5.5a.5.5 0 0 1-.5.5h-1.5C9.73 10.5 9 9.77 9 9V5.16C7.27 5.6 6 7.13 6 9v1.5A2.5 2.5 0 0 1 8.5 13A2.5 2.5 0 0 1 6 15.5V17c0 2.77 2.23 5 5 5h2c2.77 0 5-2.23 5-5v-1.5a2.5 2.5 0 0 1-2.5-2.5a2.5 2.5 0 0 1 2.5-2.5V9c0-2.22-1.78-4-4-4V3a1 1 0 0 0-1-1h-2m-.25 14.5h2.5l-.5 3.5h-1.5l-.5-3.5z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
export default data;
|
MinSomai/uadmin | test.go | <reponame>MinSomai/uadmin
package uadmin
import (
"errors"
"fmt"
"github.com/sergeyglazyrindev/uadmin/blueprint/auth"
interfaces3 "github.com/sergeyglazyrindev/uadmin/blueprint/auth/interfaces"
"github.com/sergeyglazyrindev/uadmin/core"
"github.com/sergeyglazyrindev/uadmin/utils"
"github.com/stretchr/testify/suite"
"gorm.io/gorm"
"net/http"
"net/http/httptest"
"os"
"reflect"
"regexp"
"runtime/debug"
"testing"
"time"
)
type TestSuite struct {
suite.Suite
App *App
UadminDatabase *core.UadminDatabase
}
func (suite *TestSuite) SetupTest() {
app := NewFullAppForTests()
suite.App = app
}
func (suite *TestSuite) StoreDatabase(uadminDatabase *core.UadminDatabase) {
suite.UadminDatabase = uadminDatabase
}
func (suite *TestSuite) TearDownSuite() {
ClearTestApp()
}
func ClearTestApp() {
appForTests = nil
appInstance = nil
}
func failOnPanic(t *testing.T) {
r := recover()
if r != nil {
t.Errorf("test panicked: %v\n%s", r, debug.Stack())
t.FailNow()
}
}
func newSuiteInformation() *suite.SuiteInformation {
testStats := make(map[string]*suite.TestInformation)
return &suite.SuiteInformation{
TestStats: testStats,
}
}
var allTestsFilter = func(_, _ string) (bool, error) { return true, nil }
func methodFilter(name string) (bool, error) {
if ok, _ := regexp.MatchString("^Test", name); !ok {
return false, nil
}
return regexp.MatchString("", name)
}
func startStats(s *suite.SuiteInformation, testName string) {
s.TestStats[testName] = &suite.TestInformation{
TestName: testName,
Start: time.Now(),
}
}
func endStats(s *suite.SuiteInformation, testName string, passed bool) {
s.TestStats[testName].End = time.Now()
s.TestStats[testName].Passed = passed
}
func RunTests(t *testing.T, currentsuite suite.TestingSuite) {
defer failOnPanic(t)
currentsuite.SetT(t)
var suiteSetupDone bool
var stats *suite.SuiteInformation
if _, ok := currentsuite.(suite.WithStats); ok {
stats = newSuiteInformation()
}
tests := []testing.InternalTest{}
methodFinder := reflect.TypeOf(currentsuite)
suiteName := methodFinder.Elem().Name()
for i := 0; i < methodFinder.NumMethod(); i++ {
method := methodFinder.Method(i)
ok, err := methodFilter(method.Name)
if err != nil {
fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err)
os.Exit(1)
}
if !ok {
continue
}
if !suiteSetupDone {
if stats != nil {
stats.Start = time.Now()
}
if setupAllSuite, ok := currentsuite.(suite.SetupAllSuite); ok {
setupAllSuite.SetupSuite()
}
suiteSetupDone = true
}
test := testing.InternalTest{
Name: method.Name,
F: func(t *testing.T) {
parentT := currentsuite.T()
currentsuite.SetT(t)
defer failOnPanic(t)
defer func() {
if stats != nil {
passed := !t.Failed()
endStats(stats, method.Name, passed)
}
if afterTestSuite, ok := currentsuite.(suite.AfterTest); ok {
afterTestSuite.AfterTest(suiteName, method.Name)
}
if tearDownTestSuite, ok := currentsuite.(suite.TearDownTestSuite); ok {
tearDownTestSuite.TearDownTest()
}
currentsuite.SetT(parentT)
}()
utils.SentEmailsDuringTests.ClearTestEmails()
config := core.NewConfig("configs/" + os.Getenv("TEST_ENVIRONMENT") + ".yml")
core.CurrentConfig = config
core.CurrentConfig.InTests = true
core.CurrentConfig.TemplatesFS = templatesRoot
core.CurrentConfig.LocalizationFS = localizationRoot
core.CurrentDatabaseSettings = &core.DatabaseSettings{
Default: config.D.Db.Default,
Slave: config.D.Db.Slave,
}
if config.D.Db.Default.Type == "sqlite" {
a := NewApp(os.Getenv("TEST_ENVIRONMENT"), true)
a.Config.InTests = true
core.CurrentConfig.InTests = true
uadminDatabase := core.NewUadminDatabase()
uadminDatabase.Adapter.SetTimeZone(uadminDatabase.Db, "UTC")
core.UadminTestDatabase = uadminDatabase
reflect.ValueOf(currentsuite).MethodByName("StoreDatabase").Call([]reflect.Value{reflect.ValueOf(uadminDatabase)})
if setupTestSuite, ok := currentsuite.(suite.SetupTestSuite); ok {
setupTestSuite.SetupTest()
}
upCommand := MigrateCommand{}
upCommand.Proceed("up", make([]string, 0))
if beforeTestSuite, ok := currentsuite.(suite.BeforeTest); ok {
beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name)
}
if stats != nil {
startStats(stats, method.Name)
}
method.Func.Call([]reflect.Value{reflect.ValueOf(currentsuite)})
appInstance.BlueprintRegistry.ResetMigrationTree()
downCommand := MigrateCommand{}
downCommand.Proceed("down", make([]string, 0))
//err := os.Remove(suite.app.Config.D.Db.Default.Name)
//if err != nil {
// assert.Equal(suite.T(), true, false, fmt.Errorf("Couldnt remove db with name %s", suite.app.Config.D.Db.Default.Name))
//}
core.UadminTestDatabase = nil
uadminDatabase.Close()
} else {
a := NewApp(os.Getenv("TEST_ENVIRONMENT"), true)
core.CurrentConfig.InTests = true
a.Config.InTests = true
if !CreatedDatabaseForTests && core.CurrentDatabaseSettings.Default.Type != "sqlite" {
adapter := core.NewDbAdapter(nil, core.CurrentDatabaseSettings.Default.Type)
adapter.InitializeDatabaseForTests(core.CurrentDatabaseSettings.Default)
CreatedDatabaseForTests = true
}
uadminDatabase := core.NewUadminDatabase()
core.UadminTestDatabase = uadminDatabase
uadminDatabase.Adapter.SetIsolationLevelForTests(uadminDatabase.Db)
uadminDatabase.Adapter.SetTimeZone(uadminDatabase.Db, "UTC")
if setupTestSuite, ok := currentsuite.(suite.SetupTestSuite); ok {
setupTestSuite.SetupTest()
}
upCommand := MigrateCommand{}
upCommand.Proceed("up", make([]string, 0))
uadminDatabase.Db.Transaction(func(tx *gorm.DB) error {
newUadminDatabase := &core.UadminDatabase{Db: tx, Adapter: uadminDatabase.Adapter}
core.UadminTestDatabase = newUadminDatabase
reflect.ValueOf(currentsuite).MethodByName("StoreDatabase").Call([]reflect.Value{reflect.ValueOf(newUadminDatabase)})
if setupTestSuite, ok := currentsuite.(suite.SetupTestSuite); ok {
setupTestSuite.SetupTest()
}
if beforeTestSuite, ok := currentsuite.(suite.BeforeTest); ok {
beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name)
}
if stats != nil {
startStats(stats, method.Name)
}
method.Func.Call([]reflect.Value{reflect.ValueOf(currentsuite)})
// return nil will commit the whole transaction
return errors.New("dont commit")
})
core.UadminTestDatabase.Adapter.ClearTestDatabase()
core.UadminTestDatabase = nil
uadminDatabase.Close()
}
},
}
tests = append(tests, test)
}
if suiteSetupDone {
defer func() {
if tearDownAllSuite, ok := currentsuite.(suite.TearDownAllSuite); ok {
tearDownAllSuite.TearDownSuite()
}
if suiteWithStats, measureStats := currentsuite.(suite.WithStats); measureStats {
stats.End = time.Now()
suiteWithStats.HandleStats(suiteName, stats)
}
}()
}
runTests(t, tests)
}
type runner interface {
Run(name string, f func(t *testing.T)) bool
}
func runTests(t testing.TB, tests []testing.InternalTest) {
if len(tests) == 0 {
t.Log("warning: no tests to run")
return
}
r, ok := t.(runner)
if !ok { // backwards compatibility with Go 1.6 and below
if !testing.RunTests(allTestsFilter, tests) {
t.Fail()
}
return
}
for _, test := range tests {
r.Run(test.Name, test.F)
}
}
//func NewTestApp() *App {
// a := App{}
// a.DashboardAdminPanel = core.NewDashboardAdminPanel()
// core.CurrentDashboardAdminPanel = a.DashboardAdminPanel
// a.Config = core.NewConfig("configs/" + "test" + ".yml")
// a.Config.InTests = true
// core.CurrentConfig = a.Config
// a.CommandRegistry = &CommandRegistry{
// Actions: make(map[string]core.ICommand),
// }
// a.BlueprintRegistry = core.NewBlueprintRegistry()
// a.Database = core.NewDatabase(a.Config)
// a.Router = gin.Default()
// a.Router.Use(cors.New(cors.Config{
// AllowOrigins: []string{"https://foo.com"},
// AllowMethods: []string{"PUT", "PATCH"},
// AllowHeaders: []string{"Origin"},
// ExposeHeaders: []string{"Content-Length"},
// AllowCredentials: true,
// AllowOriginFunc: func(origin string) bool {
// return origin == "https://github.com"
// },
// MaxAge: 12 * time.Hour,
// }))
// a.RegisterBaseCommands()
// core.CurrentDatabaseSettings = &core.DatabaseSettings{
// Default: a.Config.D.Db.Default,
// Slave: a.Config.D.Db.Slave,
// }
// uadminDatabase := core.NewUadminDatabase()
// uadminDatabase.Adapter.SetIsolationLevelForTests(uadminDatabase.Db)
// a.BlueprintRegistry.ResetMigrationTree()
// StoreCurrentApp(&a)
// if core.CurrentConfig.D.Db.Default.Type == "sqlite" {
// appInstance.BlueprintRegistry.ResetMigrationTree()
// downCommand := MigrateCommand{}
// downCommand.Proceed("down", make([]string, 0))
// }
// upCommand := MigrateCommand{}
// upCommand.Proceed("up", make([]string, 0))
// return &a
//}
// Helper function to process a request and test its response
func TestHTTPResponse(t *testing.T, app *App, req *http.Request, f func(w *httptest.ResponseRecorder) bool) {
// Create a response recorder
w := httptest.NewRecorder()
// Create the service and process the above request.
app.Router.ServeHTTP(w, req)
if !f(w) {
t.Fail()
}
}
var appForTests *App
var CreatedDatabaseForTests bool
func NewFullAppForTests() *App {
if appForTests != nil {
if appForTests.Config.D.Db.Default.Type == "sqlite" {
appForTests.BlueprintRegistry.ResetMigrationTree()
upCommand := MigrateCommand{}
upCommand.Proceed("up", make([]string, 0))
}
return appForTests
}
a := NewApp(os.Getenv("TEST_ENVIRONMENT"), true)
a.Config.InTests = true
StoreCurrentApp(a)
appForTests = a
a.Initialize()
authBlueprintInterface, _ := a.BlueprintRegistry.GetByName("auth")
authBlueprint := authBlueprintInterface.(auth.Blueprint)
authBlueprint.AuthAdapterRegistry.RegisterNewAdapter(&interfaces3.DirectAuthProvider{})
authBlueprint.AuthAdapterRegistry.RegisterNewAdapter(&interfaces3.TokenAuthProvider{})
authBlueprint.AuthAdapterRegistry.RegisterNewAdapter(&interfaces3.TokenWithExpirationAuthProvider{})
a.InitializeRouter()
// appForTests.DashboardAdminPanel.RegisterHTTPHandlers(a.Router)
return a
}
//type UadminTestSuite struct {
// suite.Suite
//}
//
//func (suite *UadminTestSuite) SetupTest() {
// db := dialect.GetDB()
// db = db.Exec("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED")
// if db.Error != nil {
// assert.Equal(suite.T(), true, false, "Couldnt setup isolation level for db")
// }
// db = db.Exec("BEGIN")
// if db.Error != nil {
// assert.Equal(suite.T(), true, false, "Couldnt start transaction")
// }
//}
//
//func (suite *UadminTestSuite) TearDownSuite() {
// db := dialect.GetDB()
// db = db.Exec("ROLLBACK")
// if db.Error != nil {
// assert.Equal(suite.T(), true, false, "Couldnt rollback transaction")
// }
//}
|
swkim01/stm32lib | stm32lib/ssd1306.c | /*
*----------------------------------------------------------------------
* Copyright (C) <NAME>, 2018
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of
* this software and associated documentation files
* (the "Software"), to deal in the Software without
* restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice
* shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*----------------------------------------------------------------------
*/
#include "../stm32lib/ssd1306.h"
/* Write command */
#define ssd1306_writecommand(command) i2c_write(SSD1306_I2C, SSD1306_I2C_ADDR, 0x00, (command))
/* Write data */
#define ssd1306_writedata(data) i2c_write(SSD1306_I2C, SSD1306_I2C_ADDR, 0x40, (data))
/* Absolute value */
#define ABS(x) ((x) > 0 ? (x) : -(x))
/* SSD1306 data buffer */
static uint8_t SSD1306_Buffer[SSD1306_WIDTH * SSD1306_HEIGHT / 8];
/* Private SSD1306 structure */
typedef struct {
uint16_t cursor_x;
uint16_t cursor_y;
uint8_t inverted;
uint8_t initialized;
} SSD1306_t;
/* Private variable */
static SSD1306_t SSD1306;
SSD1306_Res_t ssd1306_init(void)
{
/* I2C 초기화 */
i2c_init(SSD1306_I2C, SSD1306_I2C_PINSPACK);
i2c_set_frequency(SSD1306_I2C, 4000000);
/* 장치 연결 점검 */
if (i2c_ready(SSD1306_I2C, SSD1306_I2C_ADDR) < 0) {
/* 오류 반환 */
return SSD1306_RES_NOTCONNECT;
}
//printf("ssd1306_init\r\n");
/* A little delay */
HAL_Delay(100);
/* LCD 초기화 */
ssd1306_writecommand(0xAE); //display off
ssd1306_writecommand(0x20); //Set Memory Addressing Mode
ssd1306_writecommand(0x10); //00,Horizontal Addressing Mode;01,Vertical Addressing Mode;10,Page Addressing Mode (RESET);11,Invalid
ssd1306_writecommand(0xB0); //Set Page Start Address for Page Addressing Mode,0-7
ssd1306_writecommand(0xC8); //Set COM Output Scan Direction
ssd1306_writecommand(0x00); //---set low column address
ssd1306_writecommand(0x10); //---set high column address
ssd1306_writecommand(0x40); //--set start line address
ssd1306_writecommand(0x81); //--set contrast control register
ssd1306_writecommand(0xFF);
ssd1306_writecommand(0xA1); //--set segment re-map 0 to 127
ssd1306_writecommand(0xA6); //--set normal display
ssd1306_writecommand(0xA8); //--set multiplex ratio(1 to 64)
ssd1306_writecommand(0x3F); //
ssd1306_writecommand(0xA4); //0xa4,Output follows RAM content;0xa5,Output ignores RAM content
ssd1306_writecommand(0xD3); //-set display offset
ssd1306_writecommand(0x00); //-not offset
ssd1306_writecommand(0xD5); //--set display clock divide ratio/oscillator frequency
ssd1306_writecommand(0xF0); //--set divide ratio
ssd1306_writecommand(0xD9); //--set pre-charge period
ssd1306_writecommand(0x22); //
ssd1306_writecommand(0xDA); //--set com pins hardware configuration
ssd1306_writecommand(0x12);
ssd1306_writecommand(0xDB); //--set vcomh
ssd1306_writecommand(0x20); //0x20,0.77xVcc
ssd1306_writecommand(0x8D); //--set DC-DC enable
ssd1306_writecommand(0x14); //
ssd1306_writecommand(0xAF); //--turn on SSD1306 panel
/* 스크린 지움 */
ssd1306_fill(SSD1306_COLOR_BLACK);
/* 스크린 갱신 */
ssd1306_updatescreen();
/* 기본 값 설정 */
SSD1306.cursor_x = 0;
SSD1306.cursor_y = 0;
/* Initialized OK */
SSD1306.initialized = 1;
/* Return OK */
return SSD1306_RES_OK;
}
void ssd1306_updatescreen(void)
{
uint8_t m;
for (m = 0; m < 8; m++) {
ssd1306_writecommand(0xB0 + m);
ssd1306_writecommand(0x00);
ssd1306_writecommand(0x10);
/* Write multi data */
i2c_nwrite(SSD1306_I2C, SSD1306_I2C_ADDR, 0x40, &SSD1306_Buffer[SSD1306_WIDTH * m], SSD1306_WIDTH);
}
}
void ssd1306_invert(void)
{
uint16_t i;
/* Toggle invert */
SSD1306.inverted = !SSD1306.inverted;
/* Do memory toggle */
for (i = 0; i < sizeof(SSD1306_Buffer); i++) {
SSD1306_Buffer[i] = ~SSD1306_Buffer[i];
}
}
void ssd1306_fill(SSD1306_Color_t color)
{
/* Set memory */
memset(SSD1306_Buffer, (color == SSD1306_COLOR_BLACK) ? 0x00 : 0xFF, sizeof(SSD1306_Buffer));
}
void ssd1306_drawpixel(uint16_t x, uint16_t y, SSD1306_Color_t color)
{
if (
x >= SSD1306_WIDTH ||
y >= SSD1306_HEIGHT
) {
/* Error */
return;
}
/* Check if pixels are inverted */
if (SSD1306.inverted) {
color = (SSD1306_Color_t)!color;
}
/* Set color */
if (color == SSD1306_COLOR_WHITE) {
SSD1306_Buffer[x + (y / 8) * SSD1306_WIDTH] |= 1 << (y % 8);
} else {
SSD1306_Buffer[x + (y / 8) * SSD1306_WIDTH] &= ~(1 << (y % 8));
}
}
void ssd1306_gotoxy(uint16_t x, uint16_t y)
{
/* Set write pointers */
SSD1306.cursor_x = x;
SSD1306.cursor_y = y;
}
char ssd1306_putc(uint16_t ch, Font_t *font, SSD1306_Color_t color, uint8_t size)
{
uint32_t i, b, j;
/* Check available space in LCD */
if (font == NULL ||
SSD1306_WIDTH <= (SSD1306.cursor_x + size * font->width) ||
SSD1306_HEIGHT <= (SSD1306.cursor_y + size * font->height)
) {
/* Error */
return 0;
}
/* Go through font */
if (font->type == ASCII_FONT) {
for (i = 0; i < font->height; i++) {
b = font->data.data[(ch - font->first) * font->height + i];
for (j = 0; j < font->width; j++) {
if ((b << j) & 0x8000) {
if (size == 1)
ssd1306_drawpixel(SSD1306.cursor_x + j, (SSD1306.cursor_y + i), color);
else
ssd1306_fillrectangle(SSD1306.cursor_x + j*size, SSD1306.cursor_y + i*size, size, size, color);
}/* else {
ssd1306_drawpixel(SSD1306.cursor_x + j, (SSD1306.cursor_y + i), (SSD1306_Color_t)!color);
}*/
}
}
} else if (font->type == GFX_FONT) {
ssd1306_putc_gfx(ch, font, color, size);
} else if (font->type == COMB_FONT) {
ssd1306_putc_hangul(ch, font, color, size);
}
/* Increase pointer */
//SSD1306.cursor_x += font->width * size;
/* Return character count written */
return 1;
}
char ssd1306_putc_gfx(uint16_t ch, Font_t* font, SSD1306_Color_t color, uint8_t size)
{
const GFXFont_t *gfxfont = font->data.gfxfont;
ch -= gfxfont->first;
GFXglyph *glyph = &(gfxfont->glyph)[ch];
uint8_t *bitmap = gfxfont->bitmap;
uint32_t bo = glyph->bitmapOffset;
uint8_t w = glyph->width, h = glyph->height;
int8_t xo = glyph->xOffset, yo = 0/*glyph->yOffset*/;
uint8_t xx, yy, bits = 0, bit = 0;
int16_t xo16 = 0, yo16 = 0;
//printf("ch=%d, offset=%ld, w=%d, h=%d\r\n", ch, bo, w, h);
if (size > 1) {
xo16 = xo;
yo16 = yo;
}
for(yy=0; yy<h; yy++) {
for(xx=0; xx<w; xx++) {
if(!(bit++ & 7)) {
bits = bitmap[bo++];
}
if(bits & 0x80) {
if (size == 1)
ssd1306_drawpixel(SSD1306.cursor_x + xo + xx, (SSD1306.cursor_y + yo + yy), color);
else
ssd1306_fillrectangle(SSD1306.cursor_x + (xo16+xx)*size, SSD1306.cursor_y + (yo16+yy)*size, size, size, color);
}
bits <<= 1;
}
}
return 1;
}
char ssd1306_putc_hangul(uint16_t ch, Font_t* font, SSD1306_Color_t color, uint8_t size)
{
uint16_t i, j, w;
uint8_t wb = font->width/8;
uint8_t b, *pFs;
/* Go through font */
pFs = get_hangul_glyph(ch, font);
for (i = 0; i < font->height; i++) {
for (w = 0; w < wb; w++) {
b = pFs[i*wb+w];
for (j = 0; j < 8; j++) {
if ((b << j) & 0x80) {
if (size == 1)
ssd1306_drawpixel(SSD1306.cursor_x + w*8 + j, SSD1306.cursor_y + i, color);
else
ssd1306_fillrectangle(SSD1306.cursor_x + (w*8 + j)*size, SSD1306.cursor_y + i*size, size, size, color);
}/* else {
ssd1306_drawpixel(SSD1306.cursor_x + w*8 + j, (SSD1306.cursor_y + i), (SSD1306_Color_t)!color);
}*/
}
}
}
return 1;
}
char ssd1306_puts(char* str, FontSet_t* fontset, SSD1306_Color_t color, uint8_t size)
{
int i;
char c, c2, c3;
char count=0;
uint16_t utf16;
int cursor_x = SSD1306.cursor_x;
/* Write characters */
while (*str) {
c = *str++;
count++;
// convert utf-8 to unicode
if (c <= 0x7F){
utf16 = c;
} else {
/*------------------------------
UTF-8 을 UTF-16으로 변환한다. UTF-8 1110xxxx 10xxxxxx 10xxxxxx
------------------------------*/
c2 = *str++;
c3 = *str++;
utf16 = ((c & 0x0f) << 12) | ((c2 & 0x3f) << 6) | (c3 & 0x3f);
}
if (utf16 == '\n') {
/* Increase pointer */
SSD1306.cursor_x = cursor_x;
SSD1306.cursor_y += size * fontset->height;
} else {
/* Write character by character */
for (i = 0; fontset->fontlist[i] && i < 5; i++) {
Font_t *font = fontset->fontlist[i];
if (utf16 >= font->first && utf16 <= font->last) {
ssd1306_putc(utf16, font, color, size);
SSD1306.cursor_x += size * font->width;
break;
}
}
}
}
/* Everything OK, char count should be returned */
return count;
}
void ssd1306_drawline(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, SSD1306_Color_t c)
{
int16_t dx, dy, sx, sy, err, e2, i, tmp;
/* Check for overflow */
if (x0 >= SSD1306_WIDTH) {
x0 = SSD1306_WIDTH - 1;
}
if (x1 >= SSD1306_WIDTH) {
x1 = SSD1306_WIDTH - 1;
}
if (y0 >= SSD1306_HEIGHT) {
y0 = SSD1306_HEIGHT - 1;
}
if (y1 >= SSD1306_HEIGHT) {
y1 = SSD1306_HEIGHT - 1;
}
dx = (x0 < x1) ? (x1 - x0) : (x0 - x1);
dy = (y0 < y1) ? (y1 - y0) : (y0 - y1);
sx = (x0 < x1) ? 1 : -1;
sy = (y0 < y1) ? 1 : -1;
err = ((dx > dy) ? dx : -dy) / 2;
if (dx == 0) {
if (y1 < y0) {
tmp = y1;
y1 = y0;
y0 = tmp;
}
if (x1 < x0) {
tmp = x1;
x1 = x0;
x0 = tmp;
}
/* Vertical line */
for (i = y0; i <= y1; i++) {
ssd1306_drawpixel(x0, i, c);
}
/* Return from function */
return;
}
if (dy == 0) {
if (y1 < y0) {
tmp = y1;
y1 = y0;
y0 = tmp;
}
if (x1 < x0) {
tmp = x1;
x1 = x0;
x0 = tmp;
}
/* Horizontal line */
for (i = x0; i <= x1; i++) {
ssd1306_drawpixel(i, y0, c);
}
/* Return from function */
return;
}
while (1) {
ssd1306_drawpixel(x0, y0, c);
if (x0 == x1 && y0 == y1) {
break;
}
e2 = err;
if (e2 > -dx) {
err -= dy;
x0 += sx;
}
if (e2 < dy) {
err += dx;
y0 += sy;
}
}
}
void ssd1306_drawrectangle(uint16_t x, uint16_t y, uint16_t w, uint16_t h, SSD1306_Color_t c)
{
/* Check input parameters */
if (
x >= SSD1306_WIDTH ||
y >= SSD1306_HEIGHT
) {
/* Return error */
return;
}
/* Check width and height */
if ((x + w) >= SSD1306_WIDTH) {
w = SSD1306_WIDTH - x;
}
if ((y + h) >= SSD1306_HEIGHT) {
h = SSD1306_HEIGHT - y;
}
/* Draw 4 lines */
ssd1306_drawline(x, y, x + w, y, c); /* Top line */
ssd1306_drawline(x, y + h, x + w, y + h, c); /* Bottom line */
ssd1306_drawline(x, y, x, y + h, c); /* Left line */
ssd1306_drawline(x + w, y, x + w, y + h, c); /* Right line */
}
void ssd1306_fillrectangle(uint16_t x, uint16_t y, uint16_t w, uint16_t h, SSD1306_Color_t c)
{
uint8_t i;
/* Check input parameters */
if (
x >= SSD1306_WIDTH ||
y >= SSD1306_HEIGHT
) {
/* Return error */
return;
}
/* Check width and height */
if ((x + w) >= SSD1306_WIDTH) {
w = SSD1306_WIDTH - x;
}
if ((y + h) >= SSD1306_HEIGHT) {
h = SSD1306_HEIGHT - y;
}
/* Draw lines */
for (i = 0; i <= h; i++) {
/* Draw lines */
ssd1306_drawline(x, y + i, x + w, y + i, c);
}
}
void ssd1306_drawtriangle(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2, uint16_t x3, uint16_t y3, SSD1306_Color_t color)
{
/* Draw lines */
ssd1306_drawline(x1, y1, x2, y2, color);
ssd1306_drawline(x2, y2, x3, y3, color);
ssd1306_drawline(x3, y3, x1, y1, color);
}
void ssd1306_filltriangle(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2, uint16_t x3, uint16_t y3, SSD1306_Color_t color)
{
int16_t deltax = 0, deltay = 0, x = 0, y = 0, xinc1 = 0, xinc2 = 0,
yinc1 = 0, yinc2 = 0, den = 0, num = 0, numadd = 0, numpixels = 0,
curpixel = 0;
deltax = ABS(x2 - x1);
deltay = ABS(y2 - y1);
x = x1;
y = y1;
if (x2 >= x1) {
xinc1 = 1;
xinc2 = 1;
} else {
xinc1 = -1;
xinc2 = -1;
}
if (y2 >= y1) {
yinc1 = 1;
yinc2 = 1;
} else {
yinc1 = -1;
yinc2 = -1;
}
if (deltax >= deltay){
xinc1 = 0;
yinc2 = 0;
den = deltax;
num = deltax / 2;
numadd = deltay;
numpixels = deltax;
} else {
xinc2 = 0;
yinc1 = 0;
den = deltay;
num = deltay / 2;
numadd = deltax;
numpixels = deltay;
}
for (curpixel = 0; curpixel <= numpixels; curpixel++) {
ssd1306_drawline(x, y, x3, y3, color);
num += numadd;
if (num >= den) {
num -= den;
x += xinc1;
y += yinc1;
}
x += xinc2;
y += yinc2;
}
}
void ssd1306_drawcircle(int16_t x0, int16_t y0, int16_t r, SSD1306_Color_t c)
{
int16_t f = 1 - r;
int16_t ddF_x = 1;
int16_t ddF_y = -2 * r;
int16_t x = 0;
int16_t y = r;
//ssd1306_drawpixel(x0, y0 + r, c);
//ssd1306_drawpixel(x0, y0 - r, c);
//ssd1306_drawpixel(x0 + r, y0, c);
//ssd1306_drawpixel(x0 - r, y0, c);
while (x <= y) {
ssd1306_drawpixel(x0 + x, y0 + y, c);
ssd1306_drawpixel(x0 - x, y0 + y, c);
ssd1306_drawpixel(x0 + x, y0 - y, c);
ssd1306_drawpixel(x0 - x, y0 - y, c);
ssd1306_drawpixel(x0 + y, y0 + x, c);
ssd1306_drawpixel(x0 - y, y0 + x, c);
ssd1306_drawpixel(x0 + y, y0 - x, c);
ssd1306_drawpixel(x0 - y, y0 - x, c);
if (f >= 0) {
y--;
ddF_y += 2;
f += ddF_y;
}
x++;
ddF_x += 2;
f += ddF_x;
}
}
void ssd1306_fillcircle(int16_t x0, int16_t y0, int16_t r, SSD1306_Color_t c)
{
int16_t f = 1 - r;
int16_t ddF_x = 1;
int16_t ddF_y = -2 * r;
int16_t x = 0;
int16_t y = r;
//ssd1306_drawpixel(x0, y0 + r, c);
//ssd1306_drawpixel(x0, y0 - r, c);
//ssd1306_drawpixel(x0 + r, y0, c);
//ssd1306_drawpixel(x0 - r, y0, c);
//ssd1306_drawline(x0 - r, y0, x0 + r, y0, c);
while (x <= y) {
ssd1306_drawline(x0 - x, y0 + y, x0 + x, y0 + y, c);
ssd1306_drawline(x0 + x, y0 - y, x0 - x, y0 - y, c);
ssd1306_drawline(x0 + y, y0 + x, x0 - y, y0 + x, c);
ssd1306_drawline(x0 + y, y0 - x, x0 - y, y0 - x, c);
if (f >= 0) {
y--;
ddF_y += 2;
f += ddF_y;
}
x++;
ddF_x += 2;
f += ddF_x;
}
}
void ssd1306_on(void)
{
ssd1306_writecommand(0x8D);
ssd1306_writecommand(0x14);
ssd1306_writecommand(0xAF);
}
void ssd1306_off(void)
{
ssd1306_writecommand(0x8D);
ssd1306_writecommand(0x10);
ssd1306_writecommand(0xAE);
}
|
julianladisch/stripes-cli | lib/doc/yargs-help-parser.js | /*
Recursively parses Yargs command --help output to generate a command tree for use in generating a CLI command reference.
This is currently specific to stripes-cli, but a future refactor could make it general purpose for other Yargs-based CLIs
*/
const childProcess = require('child_process');
const logger = require('../cli/logger')('docs');
// Captures command name, eg. "stripes foo bar" (match[1]), and description (match[2]) separated by two new-lines
const commandRegex = /(stripes\s.*)\n\n\b(.*)\n/;
// Captures content between "Commands:" and the next empty line
const subCommandGroupRegex = /Commands:([\s\S]*?)^$/gm;
// Captures content between "Options:" and the next empty line
const optionsGroupRegex = /Options:([\s\S]*?)^$/gm;
// Captures content between "Positionals:" and the next empty line
const positionalsGroupRegex = /Positionals:([\s\S]*?)^$/gm;
// Captures content between "Examples:" and the end
const exampleGroupRegex = /Examples:([\s\S]*)$/gm;
// Capture a single command in the "Commands:" section
// Positive lookahead (?=...) matches two or more spaces (preceding the description) or ' [' or ' <'
const subCommandRegex = /^(?:\s+)(stripes.*?)(?=\s{2,}|\s\[|\s<)/gm;
// Capture a single item in the "Options:", "Positionals:", or "Examples:" section
// Item name (match[1]) begins after space indent, description/details (match[2]) is separated by two or more spaces
const defaultItemRegex = /^\s+(.*?)[^\S\n]{2,}\b(.*)$/gm;
// Returns an object of option metadata gathered from a previously matched option line
function parseOption(optionMatch) {
// match[1] is the option name
// match[2] is the description and metadata in square brackets []
if (!optionMatch && optionMatch.length > 1) {
return null;
}
const option = {
name: optionMatch[1],
description: '',
type: '',
default: '',
};
if (optionMatch.length > 2) {
const descriptionMatch = optionMatch[2].match(/^[^[]*/); // Everything up to first '['
const typeMatch = optionMatch[2].match(/\[(boolean|string|number|count|array)]/);
const defaultMatch = optionMatch[2].match(/\[default: ([^\]]*)]/); // [default: value]
const choicesMatch = optionMatch[2].match(/\[choices: ([^\]]*)]/); // [choices: "enable", "disable"]
const requiredMatch = optionMatch[2].match(/\[required\]/); // [required]
const stdinMatch = optionMatch[2].match(/\(stdin\)/); // (stdin)
if (descriptionMatch) {
option.description = descriptionMatch[0].trim();
}
if (typeMatch) {
option.type = typeMatch[1].trim();
}
if (defaultMatch) {
option.default = defaultMatch[1].trim();
}
if (choicesMatch) {
option.choices = choicesMatch[1].trim();
}
if (requiredMatch) {
option.required = true;
}
if (stdinMatch) {
option.stdin = true;
}
}
return option;
}
// Returns array of item data per matched group of text (commands, options, examples, etc.)
// itemRegex determines how to parse lines within group
// itemMap is a function to map item matches to an object
function parseGroup(helpText, groupRegex, itemRegex, itemMap) {
const groupMatch = helpText.match(groupRegex);
const items = [];
if (groupMatch) {
groupMatch.forEach((group) => {
let itemMatch;
while (itemMatch !== null) {
itemMatch = itemRegex.exec(group);
if (itemMatch && itemMatch.length > 1) {
const itemData = itemMap(itemMatch);
if (itemData) {
items.push(itemData);
}
}
}
});
}
return items;
}
// Returns markdown command description with usage wrapped in a code block
function parseDescription(helpText) {
const match = helpText.match(commandRegex);
if (match) {
return match[2];
}
return '';
}
// Returns markdown command description with usage wrapped in a code block
function parseUsage(helpText) {
const match = helpText.match(commandRegex);
if (match) {
return match[1];
}
return '';
}
// Returns array of sub-commands
function parseSubCommands(helpText) {
const parseCommand = match => match[1];
return parseGroup(helpText, subCommandGroupRegex, subCommandRegex, parseCommand);
}
// Returns array of command options
function parseOptions(helpText) {
return parseGroup(helpText, optionsGroupRegex, defaultItemRegex, parseOption);
}
// Returns array of command positionals
function parsePositionals(helpText) {
return parseGroup(helpText, positionalsGroupRegex, defaultItemRegex, parseOption);
}
// Returns array of command examples
function parseExamples(helpText) {
const parseExample = (match) => {
return {
usage: match[1],
description: match[2],
};
};
return parseGroup(helpText, exampleGroupRegex, defaultItemRegex, parseExample);
}
// Return command line help for a single command from by invoking "stripes <command> --help"
function getYargsHelpText(command, scriptPath) {
logger.log(`invoking child process for "${scriptPath} ${command} --help"...`);
const helpText = childProcess.execSync(`${scriptPath} ${command} --help`, { encoding: 'utf8' });
logger.log(`completed child process for "${scriptPath} ${command} --help"`);
return helpText;
}
// Walks the entire command tree as visible from --help
function gatherCommands(commandName, scriptPath) {
const name = commandName.replace(/^stripes\s?/, '');
const helpText = getYargsHelpText(name, scriptPath);
return {
name,
fullName: commandName,
description: parseDescription(helpText),
usage: parseUsage(helpText),
subCommands: parseSubCommands(helpText).map(sub => gatherCommands(sub, scriptPath)),
positionals: parsePositionals(helpText),
options: parseOptions(helpText),
examples: parseExamples(helpText),
};
}
module.exports = {
gatherCommands,
};
|
d4rkr00t/aik | flow-typed/npm-custom/insight.js | declare module "insight" {
declare module.exports: Function;
}
|
unclealex72/west-ham-calendar | app/logging/Fatal.scala | package logging
import cats.data.NonEmptyList
import model.FatalError
/**
* A service for logging fatal errors.
* Created by alex on 28/02/16.
*/
trait Fatal {
def fail(errors: NonEmptyList[String], optionalException: Option[Throwable], optionalLinkBuilder: Option[FatalError => String])(implicit remoteStream: RemoteStream): Unit
def fail(error: String, optionalException: Option[Throwable], optionalLinkBuilder: Option[FatalError => String])(implicit remoteStream: RemoteStream): Unit =
fail(NonEmptyList.of(error), optionalException, optionalLinkBuilder)
def fail(errors: NonEmptyList[String], exception: Throwable)(implicit remoteStream: RemoteStream): Unit = fail(errors, Some(exception), None)
def fail(error: String, exception: Throwable)(implicit remoteStream: RemoteStream): Unit = fail(error, Some(exception), None)
def fail(errors: NonEmptyList[String])(implicit remoteStream: RemoteStream): Unit = fail(errors, None, None)
def fail(error: String)(implicit remoteStream: RemoteStream): Unit = fail(error, None, None)
def fail(errors: NonEmptyList[String], exception: Throwable, linkBuilder: FatalError => String)(implicit remoteStream: RemoteStream): Unit =
fail(errors, Some(exception), Some(linkBuilder))
def fail(error: String, exception: Throwable, linkBuilder: FatalError => String)(implicit remoteStream: RemoteStream): Unit =
fail(error, Some(exception), Some(linkBuilder))
def fail(errors: NonEmptyList[String], linkBuilder: FatalError => String)(implicit remoteStream: RemoteStream): Unit =
fail(errors, None, Some(linkBuilder))
def fail(error: String, linkBuilder: FatalError => String)(implicit remoteStream: RemoteStream): Unit =
fail(error, None, Some(linkBuilder))
}
|
PanDAWMS/panda-jedi | pandajedi/jeditest/jobSplitterTest.py | <reponame>PanDAWMS/panda-jedi<gh_stars>1-10
# logger
from pandacommon.pandalogger.PandaLogger import PandaLogger
from pandajedi.jedicore.MsgWrapper import MsgWrapper
from pandajedi.jedicore.JediTaskBufferInterface import JediTaskBufferInterface
from pandajedi.jediddm.DDMInterface import DDMInterface
from pandajedi.jediorder.JobBroker import JobBroker
from pandajedi.jediorder.JobSplitter import JobSplitter
from pandajedi.jediorder.JobGenerator import JobGeneratorThread
from pandajedi.jedicore.ThreadUtils import ThreadPool,ListWithLock
from pandajedi.jediorder.TaskSetupper import TaskSetupper
from pandajedi.jedicore import Interaction
import sys
logger = PandaLogger().getLogger('JobGenerator')
tmpLog = MsgWrapper(logger)
tbIF = JediTaskBufferInterface()
tbIF.setupInterface()
siteMapper = tbIF.getSiteMapper()
ddmIF = DDMInterface()
ddmIF.setupInterface()
jediTaskID = int(sys.argv[1])
try:
datasetID = [int(sys.argv[2])]
except Exception:
datasetID = None
s,taskSpec = tbIF.getTaskWithID_JEDI(jediTaskID)
cloudName = taskSpec.cloud
vo = taskSpec.vo
prodSourceLabel = taskSpec.prodSourceLabel
queueID = taskSpec.workQueue_ID
gshare_name = taskSpec.gshare
workQueue = tbIF.getWorkQueueMap().getQueueWithIDGshare(queueID, gshare_name)
brokerageLockIDs = ListWithLock([])
threadPool = ThreadPool()
# get typical number of files
typicalNumFilesMap = tbIF.getTypicalNumInput_JEDI(vo,prodSourceLabel,workQueue,
useResultCache=600)
tmpListList = tbIF.getTasksToBeProcessed_JEDI(None,vo,workQueue,
prodSourceLabel,
cloudName,nFiles=10,simTasks=[jediTaskID],
fullSimulation=True,
typicalNumFilesMap=typicalNumFilesMap,
simDatasets=datasetID,
numNewTaskWithJumbo=5,
ignore_lock=True)
taskSetupper = TaskSetupper(vo,prodSourceLabel)
taskSetupper.initializeMods(tbIF,ddmIF)
for dummyID,tmpList in tmpListList:
task_common = {}
for taskSpec,cloudName,inputChunk in tmpList:
jobBroker = JobBroker(taskSpec.vo,taskSpec.prodSourceLabel)
tmpStat = jobBroker.initializeMods(ddmIF.getInterface(vo),tbIF)
jobBrokerCore = jobBroker.getImpl(taskSpec.vo, taskSpec.prodSourceLabel)
jobBrokerCore.setTestMode()
jobBrokerCore.set_task_common_dict(task_common)
splitter = JobSplitter()
gen = JobGeneratorThread(None,threadPool,tbIF,ddmIF,siteMapper,False,taskSetupper,None,
None,'dummy',None,None,brokerageLockIDs, False)
taskParamMap = None
if taskSpec.useLimitedSites():
tmpStat,taskParamMap = gen.readTaskParams(taskSpec,taskParamMap,tmpLog)
jobBroker.setLockID(taskSpec.vo,taskSpec.prodSourceLabel,123,0)
tmpStat,inputChunk = jobBroker.doBrokerage(taskSpec,cloudName,inputChunk,taskParamMap)
brokerageLockID = jobBroker.getBaseLockID(taskSpec.vo,taskSpec.prodSourceLabel)
if brokerageLockID is not None:
brokerageLockIDs.append(brokerageLockID)
for brokeragelockID in brokerageLockIDs:
tbIF.unlockProcessWithPID_JEDI(taskSpec.vo,taskSpec.prodSourceLabel,workQueue.queue_id,
brokeragelockID,True)
tmpStat, subChunks, isSkipped = splitter.doSplit(taskSpec, inputChunk, siteMapper,
allow_chunk_size_limit=True)
if tmpStat == Interaction.SC_SUCCEEDED and isSkipped:
# run again without chunk size limit to generate jobs for skipped snippet
tmpStat, tmpChunks, isSkipped = splitter.doSplit(taskSpec, inputChunk,
siteMapper,
allow_chunk_size_limit=False)
if tmpStat == Interaction.SC_SUCCEEDED:
subChunks += tmpChunks
tmpStat,pandaJobs,datasetToRegister,oldPandaIDs,parallelOutMap,outDsMap = gen.doGenerate(taskSpec,cloudName,subChunks,inputChunk,tmpLog,True,
splitter=splitter)
|
Mishco/99-problems-java | src/main/java/lists/P28.java | package lists;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;
/**
* We suppose that a list (InList) contains elements that are lists themselves.
* The objective is to sort the elements of InList according to their length.
* E.g. short lists first, longer lists later, or vice versa.
* <p>
* Example:
* ?- lsort([[a,b,c],[d,e],[f,g,h],[d,e],[i,j,k,l],[m,n],[o]],L).
* L = [[o], [d, e], [d, e], [m, n], [a, b, c], [f, g, h], [i, j, k, l]]
*/
public final class P28 {
private P28() {
}
/**
* Sort list by size of sublist.
*
* @param input input list of items
* @param <T> type of item
* @return sorted list
*/
public static <T> List<List<T>> lsort(final List<List<T>> input) {
input.sort(Comparator.comparingInt(List::size));
return input;
}
/**
* Sort list by frequency of sublist.
*
* @param input input list of items
* @param <T> type of item
* @return sorted list
*/
public static <T> List<List<T>> lfsort(final List<List<T>> input) {
Map<Integer, Integer> frequencies = new HashMap<>();
input.stream()
.map(List::size)
.forEach(l -> frequencies.put(
l,
frequencies.compute(l,
(k, v) -> v == null
? 1
: v + 1)));
return input
.stream()
.sorted(Comparator
.comparingInt(xs -> frequencies.get(xs.size())))
.collect(toList());
}
}
|
xqueue/maileon-java-api-client | java-api-client/src/main/java/com/maileon/api/transactions/ImportContactReference.java | <reponame>xqueue/maileon-java-api-client
package com.maileon.api.transactions;
import java.io.Serializable;
public class ImportContactReference implements Serializable {
private Long id;
private String email;
private String externalId;
private Integer permission;
private String errorField;
/**
* Get Maileon ID of contact.
*
* @return
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* Get email of contact
*
* @return email of contact
*/
public String getEmail() {
return email;
}
/**
* Set email of contact.
*
* @param email email of contact
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Get external ID of contact.
*
* @return external ID of contact.
*/
public String getExternalId() {
return externalId;
}
/**
* Set external ID of contact.
*
* @param externalId external id of contact
*/
public void setExternalId(String externalId) {
this.externalId = externalId;
}
public Integer getPermission() {
return permission;
}
/**
* Set permission of of contact.
*
* @param permission permission of contact.
* @see com.maileon.api.contacts.Permission
*/
public void setPermission(Integer permission) {
this.permission = permission;
}
/**
* Get the name of a field with invalid value.
*
* @return the name of field.
*/
public String getErrorField() {
return errorField;
}
public void setErrorField(String errorField) {
this.errorField = errorField;
}
@Override
public String toString() {
StringBuilder s = new StringBuilder("{");
boolean notempty = false;
if (id != null) {
s.append("id=").append(id);
notempty = true;
}
if (email != null) {
if (notempty) {
s.append(',');
}
s.append("email=").append(email);
notempty = true;
}
if (externalId != null) {
if (notempty) {
s.append(',');
}
s.append("externalId=").append(externalId);
}
if (permission != null) {
if (notempty) {
s.append(',');
}
s.append("permission=").append(permission);
}
if (errorField != null) {
if (notempty) {
s.append(',');
}
s.append("errorField=").append(errorField);
}
s.append('}');
return s.toString();
}
}
|
hellobagus/ifcasplus_web | js/highcharts-master/samples/issues/highcharts-4.1.5/1457-ranges-reversed-axis/demo.js | <gh_stars>0
$(function () {
QUnit.test('Reversed axis range', function (assert) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'columnrange',
inverted: false
},
yAxis: {
reversed: true
},
series: [{
animation: false,
name: 'Temperatures',
data: [
[1, 2],
[2, 3],
[3, 4]
],
dataLabels: {
enabled: true
}
}]
});
var point = chart.series[0].points[0];
assert.strictEqual(
parseInt(point.graphic.element.getAttribute('height'), 10) > 25,
true,
'First element has a height'
);
assert.strictEqual(
point.dataLabel.y < point.plotLow,
true,
'"Low" data label is drawn above point'
);
assert.strictEqual(
Math.round(point.dataLabelUpper.y) >= Math.round(point.plotHigh),
true,
'"High" data label is drawn below point'
);
});
QUnit.test('Reversed axis range - inverted', function (assert) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'columnrange',
inverted: true
},
yAxis: {
reversed: true
},
series: [{
animation: false,
name: 'Temperatures',
data: [
[1, 2],
[2, 3],
[3, 4]
],
dataLabels: {
enabled: true
}
}]
});
var point = chart.series[0].points[0];
assert.strictEqual(
parseInt(point.graphic.element.getAttribute('height'), 10) > 25,
true,
'First element has a height'
);
});
}); |
abhinotes/eventuate-local | eventuate-local-console/eventuate-local-console-client/src/reducers/subscription.js | <gh_stars>100-1000
/**
* Created by andrew on 12/13/16.
*/
import { handleActions } from 'redux-actions';
import Immutable, { Map, List } from 'immutable';
import invariant from 'invariant';
import { subscribedTypes } from '../actions/subscription';
export default handleActions({
[subscribedTypes]: (state, action) => {
const { items = [], key } = action.payload;
if (!key) {
return state.setIn(['current'], null);
}
return state.setIn(['current'], key).setIn(['items', key], items);
}
}, Map()); |
scommons/scommons | ui/src/main/scala/scommons/client/ui/popup/OkPopup.scala | package scommons.client.ui.popup
import scommons.client.ui.{Buttons, UiSettings}
import scommons.client.util.ActionsData
import scommons.react._
import scommons.react.hooks._
case class OkPopupProps(message: String,
onClose: () => Unit,
image: Option[String] = None)
object OkPopup extends FunctionComponent[OkPopupProps] {
private case class OkPopupState(opened: Boolean = false)
private[popup] var modalComp: UiComponent[ModalProps] = Modal
protected def render(compProps: Props): ReactElement = {
val (state, setState) = useStateUpdater(() => OkPopupState())
val props = compProps.wrapped
<(modalComp())(^.wrapped := ModalProps(
header = None,
buttons = List(Buttons.OK),
actions = ActionsData(Set(Buttons.OK.command), _ => {
case _ => props.onClose()
},
if (state.opened) Some(Buttons.OK.command)
else None
),
onClose = props.onClose,
onOpen = { () =>
setState(_.copy(opened = true))
}
))(
<.div(^.className := "row-fluid")(
props.image.map { image =>
<.img(^.className := image, ^.src := UiSettings.imgClearCacheUrl)()
},
<.p()(props.message)
)
)
}
}
|
knuu/Introduction_to_Computing_and_Programming_Using_Python | ch04/ex4-1-1.py | <reponame>knuu/Introduction_to_Computing_and_Programming_Using_Python<gh_stars>1-10
def isIn(s, t):
if len(s) > len(t):
s, t = t, s
for i in range(0, len(t)-len(s)+1):
if s == t[i:i+len(s)]:
return True
return False
if __name__ == '__main__':
print(isIn('hogefugafoobar', 'foobar'))
print(isIn('hoge', 'foo'))
|
kmdsbng/api-elements.js | packages/openapi3-parser/test/unit/parser/oas/parseSecuritySchemeObject-test.js | const { Fury } = require('fury');
const { expect } = require('../../chai');
const parse = require('../../../../lib/parser/oas/parseSecuritySchemeObject');
const Context = require('../../../../lib/context');
const { minim: namespace } = new Fury();
describe('Security Scheme Object', () => {
let context;
beforeEach(() => {
context = new Context(namespace);
});
it('provides warning when security scheme is not an object', () => {
const securityScheme = new namespace.elements.String();
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' is not an object");
});
describe('#type', () => {
it('provides an warning when type is not a string', () => {
const securityScheme = new namespace.elements.Object({
type: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'type' is not a string");
});
it('provides an warning when value is not a permitted value', () => {
const securityScheme = new namespace.elements.Object({
type: 'space',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'type' must be either 'apiKey', 'http', 'oauth2' or 'openIdConnect'");
});
it('provides an unsupported warning for openIdConnect type', () => {
const securityScheme = new namespace.elements.Object({
type: 'openIdConnect',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'type' 'openIdConnect' is unsupported");
});
});
describe('#name', () => {
it('provides a warning when name does not exist', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
in: 'query',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' is missing required property 'name'");
});
it('provides a warning when name is not a string', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 1,
in: 'query',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'name' is not a string");
});
});
describe('#in', () => {
it('provides a warning when in does not exist', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' is missing required property 'in'");
});
it('provides a warning when in is not a string', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'in' is not a string");
});
it('provides a warning when in is not a permitted value', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'space',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'in' must be either 'query', 'header' or 'cookie'");
});
});
describe('#scheme', () => {
it('provides a warning when scheme does not exist', () => {
const securityScheme = new namespace.elements.Object({
type: 'http',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' is missing required property 'scheme'");
});
it('provides a warning when scheme is not a string', () => {
const securityScheme = new namespace.elements.Object({
type: 'http',
scheme: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'scheme' is not a string");
});
});
describe('#description', () => {
it('attaches description to member', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'query',
description: 'an example security scheme',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult.get(0)).to.be.instanceof(namespace.elements.AuthScheme);
expect(parseResult.get(0).description.toValue()).to.equal(
'an example security scheme'
);
});
it('provides a warning when description is not a string', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'query',
description: true,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(2);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'description' is not a string");
});
});
describe('when type is apiKey', () => {
it('parses correctly when in a header', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'header',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult.get(0)).to.be.instanceof(namespace.elements.AuthScheme);
expect(parseResult.get(0).element).to.equal('Token Authentication Scheme');
const { members } = parseResult.get(0);
expect(members.length).to.equal(1);
expect(members.get(0).key.toValue()).to.equal('httpHeaderName');
expect(members.get(0).value.toValue()).to.equal('example');
});
it('parses correctly when in a query', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'query',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult.get(0)).to.be.instanceof(namespace.elements.AuthScheme);
expect(parseResult.get(0).element).to.equal('Token Authentication Scheme');
const { members } = parseResult.get(0);
expect(members.length).to.equal(1);
expect(members.get(0).key.toValue()).to.equal('queryParameterName');
expect(members.get(0).value.toValue()).to.equal('example');
});
it('parses correctly when in a cookie', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'cookie',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult.get(0)).to.be.instanceof(namespace.elements.AuthScheme);
expect(parseResult.get(0).element).to.equal('Token Authentication Scheme');
const { members } = parseResult.get(0);
expect(members.length).to.equal(1);
expect(members.get(0).key.toValue()).to.equal('cookieName');
expect(members.get(0).value.toValue()).to.equal('example');
});
it('provides warning for invalid scheme', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'query',
scheme: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(2);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'apiKey' contains invalid key 'scheme'");
});
it('provides warning for invalid flows', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'query',
flows: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(2);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'apiKey' contains invalid key 'flows'");
});
});
describe('when type is oauth2', () => {
it('parses correctly when single flow', () => {
const securityScheme = new namespace.elements.Object({
type: 'oauth2',
flows: {
password: {
tokenUrl: '/token',
scopes: {},
},
},
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult.get(0)).to.be.instanceof(namespace.elements.Array);
expect(parseResult.get(0).length).to.equal(1);
expect(parseResult.get(0).get(0)).to.be.instanceof(namespace.elements.AuthScheme);
expect(parseResult.get(0).get(0).element).to.equal('Oauth2 Scheme');
});
it('parses correctly when multiple flows', () => {
const securityScheme = new namespace.elements.Object({
type: 'oauth2',
description: 'oauth2 implementation',
flows: {
password: {
tokenUrl: '/token',
scopes: {},
},
implicit: {
authorizationUrl: '/authorization',
scopes: {},
},
},
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult.get(0)).to.be.instanceof(namespace.elements.Array);
expect(parseResult.get(0).length).to.equal(2);
expect(parseResult.get(0).get(0)).to.be.instanceof(namespace.elements.AuthScheme);
expect(parseResult.get(0).get(0).element).to.equal('Oauth2 Scheme');
expect(parseResult.get(0).get(0).description.toValue()).to.equal('oauth2 implementation');
expect(parseResult.get(0).get(1)).to.be.instanceof(namespace.elements.AuthScheme);
expect(parseResult.get(0).get(1).element).to.equal('Oauth2 Scheme');
expect(parseResult.get(0).get(1).description.toValue()).to.equal('oauth2 implementation');
});
it('provides warning for invalid name', () => {
const securityScheme = new namespace.elements.Object({
type: 'oauth2',
flows: {},
name: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(2);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'oauth2' contains invalid key 'name'");
});
it('provides warning for invalid in', () => {
const securityScheme = new namespace.elements.Object({
type: 'oauth2',
flows: {},
in: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(2);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'oauth2' contains invalid key 'in'");
});
it('provides warning for invalid scheme', () => {
const securityScheme = new namespace.elements.Object({
type: 'oauth2',
flows: {},
scheme: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(2);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'oauth2' contains invalid key 'scheme'");
});
});
describe('when type is http', () => {
it('parses correctly when scheme is basic', () => {
const securityScheme = new namespace.elements.Object({
type: 'http',
scheme: 'basic',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult.get(0)).to.be.instanceof(namespace.elements.AuthScheme);
expect(parseResult.get(0).element).to.equal('Basic Authentication Scheme');
expect(parseResult.get(0).members.length).to.equal(0);
});
it('provides warning for invalid name', () => {
const securityScheme = new namespace.elements.Object({
type: 'http',
scheme: 'basic',
name: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(2);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'http' contains invalid key 'name'");
});
it('provides warning for invalid in', () => {
const securityScheme = new namespace.elements.Object({
type: 'http',
scheme: 'basic',
in: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(2);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'http' contains invalid key 'in'");
});
it('provides warning for invalid flows', () => {
const securityScheme = new namespace.elements.Object({
type: 'http',
scheme: 'basic',
flows: 1,
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(2);
expect(parseResult).to.contain.warning("'Security Scheme Object' 'http' contains invalid key 'flows'");
});
it('provides warning for invalid scheme', () => {
const securityScheme = new namespace.elements.Object({
type: 'http',
scheme: 'basic[',
});
const parseResult = parse(context, securityScheme);
expect(parseResult.length).to.equal(1);
expect(parseResult).to.contain.warning(
"'Security Scheme Object' 'http' contains unsupported scheme 'basic[', supported schemes bearer, basic"
);
});
});
describe('warnings for unsupported properties', () => {
it('provides warning for unsupported bearerFormat property', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'query',
bearerFormat: '',
});
const parseResult = parse(context, securityScheme);
expect(parseResult).to.contain.warning("'Security Scheme Object' contains unsupported key 'bearerFormat'");
});
it('provides warning for unsupported openIdConnectUrl property', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'query',
openIdConnectUrl: '',
});
const parseResult = parse(context, securityScheme);
expect(parseResult).to.contain.warning("'Security Scheme Object' contains unsupported key 'openIdConnectUrl'");
});
it('does not provide warning/errors for extensions', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'query',
'x-extension': '',
});
const parseResult = parse(context, securityScheme);
expect(parseResult).to.not.contain.annotations;
});
});
it('provides warning for invalid keys', () => {
const securityScheme = new namespace.elements.Object({
type: 'apiKey',
name: 'example',
in: 'query',
invalid: '',
});
const parseResult = parse(context, securityScheme);
expect(parseResult).to.contain.warning("'Security Scheme Object' contains invalid key 'invalid'");
});
});
|
benja-M-1/homebrew-cask | Casks/mucommander.rb | cask "mucommander" do
version "0.9.5-1"
sha256 "476ffd9e271163513d9fde2d015d1da3f2777e54b913b10d4ef49ac7e016bae1"
# github.com/mucommander/mucommander/ was verified as official when first introduced to the cask
url "https://github.com/mucommander/mucommander/releases/download/#{version}/mucommander-#{version}.dmg"
appcast "https://github.com/mucommander/mucommander/releases.atom"
name "muCommander"
homepage "https://www.mucommander.com/"
app "muCommander.app"
end
|
leandrogonqn/Proyecto2017Seguros | dom/src/main/java/com/pacinetes/dom/polizaautomotor/PolizaAutomotor.java | <reponame>leandrogonqn/Proyecto2017Seguros<filename>dom/src/main/java/com/pacinetes/dom/polizaautomotor/PolizaAutomotor.java
/*******************************************************************************
* Copyright 2017 SiGeSe
*
* 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.pacinetes.dom.polizaautomotor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.Discriminator;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.Inheritance;
import javax.jdo.annotations.InheritanceStrategy;
import javax.jdo.annotations.Join;
import javax.jdo.annotations.Queries;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.Auditing;
import org.apache.isis.applib.annotation.CollectionLayout;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.Editing;
import org.apache.isis.applib.annotation.InvokeOn;
import org.apache.isis.applib.annotation.Optionality;
import org.apache.isis.applib.annotation.Parameter;
import org.apache.isis.applib.annotation.ParameterLayout;
import org.apache.isis.applib.annotation.Property;
import org.apache.isis.applib.annotation.PropertyLayout;
import org.apache.isis.applib.annotation.Publishing;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.applib.services.i18n.TranslatableString;
import org.apache.isis.applib.services.message.MessageService;
import org.apache.isis.applib.services.repository.RepositoryService;
import org.apache.isis.applib.services.title.TitleService;
import org.apache.isis.applib.value.Blob;
import com.pacinetes.dom.adjunto.Adjunto;
import com.pacinetes.dom.adjunto.AdjuntoRepository;
import com.pacinetes.dom.compania.Compania;
import com.pacinetes.dom.compania.CompaniaRepository;
import com.pacinetes.dom.detalletipopago.DetalleTipoPago;
import com.pacinetes.dom.detalletipopago.DetalleTipoPagoMenu;
import com.pacinetes.dom.detalletipopago.DetalleTipoPagoRepository;
import com.pacinetes.dom.detalletipopago.TipoPago;
import com.pacinetes.dom.estado.Estado;
import com.pacinetes.dom.mail.Mail;
import com.pacinetes.dom.modelo.Modelo;
import com.pacinetes.dom.modelo.ModeloRepository;
import com.pacinetes.dom.persona.Persona;
import com.pacinetes.dom.persona.PersonaRepository;
import com.pacinetes.dom.poliza.Poliza;
import com.pacinetes.dom.poliza.PolizaRepository;
import com.pacinetes.dom.reportes.PolizaAutomotorReporte;
import com.pacinetes.dom.reportes.ReporteRepository;
import com.pacinetes.dom.tipodecobertura.TipoDeCobertura;
import com.pacinetes.dom.tipodecobertura.TipoDeCoberturaRepository;
import com.pacinetes.dom.vehiculo.Vehiculo;
import com.pacinetes.dom.vehiculo.VehiculoRepository;
import net.sf.jasperreports.engine.JRException;
@javax.jdo.annotations.PersistenceCapable(identityType = IdentityType.DATASTORE, schema = "simple", table = "Polizas")
@Queries({ @javax.jdo.annotations.Query(name = "listarPorEstado", language = "JDOQL", value = "SELECT "
+ "FROM com.pacinetes.dom.simple.Polizas " + "WHERE polizaEstado == :polizaEstado") })
@DomainObject(publishing = Publishing.ENABLED, auditing = Auditing.ENABLED)
@Inheritance(strategy = InheritanceStrategy.SUPERCLASS_TABLE)
@Discriminator(value = "RiesgoAutomotores")
public class PolizaAutomotor extends Poliza {
// region > title
public TranslatableString title() {
return TranslatableString.tr("{name}", "name", "Poliza Automotor N°: " + getPolizaNumero());
}
// endregion
// Constructor
@SuppressWarnings("deprecation")
public PolizaAutomotor(String polizaNumero, Persona polizaCliente, Compania polizaCompania,
List<Vehiculo> riesgoAutomotorListaVehiculos, TipoDeCobertura riesgoAutomotorTiposDeCoberturas,
Date polizaFechaEmision, Date polizaFechaVigencia, Date polizaFechaVencimiento, TipoPago polizaTipoDePago,
DetalleTipoPago polizaPago, double polizaImporteTotal) {
setPolizaNumero(polizaNumero);
setPolizasCliente(polizaCliente);
setPolizasCompania(polizaCompania);
setRiesgoAutomotorListaVehiculos(riesgoAutomotorListaVehiculos);
setRiesgoAutomotorTipoDeCobertura(riesgoAutomotorTiposDeCoberturas);
setPolizaFechaEmision(polizaFechaEmision);
polizaFechaVigencia.setHours(12);
polizaFechaVigencia.setSeconds(1);
setPolizaFechaVigencia(polizaFechaVigencia);
polizaFechaVencimiento.setHours(12);
setPolizaFechaVencimiento(polizaFechaVencimiento);
setPolizaPago(polizaPago);
setPolizaTipoDePago(polizaTipoDePago);
setPolizaImporteTotal(polizaImporteTotal);
setPolizaEstado(Estado.previgente);
polizaEstado.actualizarEstado(this);
}
@SuppressWarnings("deprecation")
public PolizaAutomotor(String polizaNumero, Persona polizaCliente, Compania polizaCompania,
List<Vehiculo> riesgoAutomotorListaVehiculos, TipoDeCobertura riesgoAutomotorTiposDeCoberturas,
Date polizaFechaEmision, Date polizaFechaVigencia, Date polizaFechaVencimiento, TipoPago polizaTipoDePago,
DetalleTipoPago polizaPago, double polizaImporteTotal, List<Adjunto> riesgoAutomotorListaAdjunto,
Poliza riesgoAutomotores) {
setPolizaNumero(polizaNumero);
setPolizasCliente(polizaCliente);
setPolizasCompania(polizaCompania);
setRiesgoAutomotorListaVehiculos(riesgoAutomotorListaVehiculos);
setRiesgoAutomotorTipoDeCobertura(riesgoAutomotorTiposDeCoberturas);
setPolizaFechaEmision(polizaFechaEmision);
polizaFechaVigencia.setHours(12);
polizaFechaVigencia.setSeconds(1);
setPolizaFechaVigencia(polizaFechaVigencia);
polizaFechaVencimiento.setHours(12);
setPolizaFechaVencimiento(polizaFechaVencimiento);
setPolizaTipoDePago(polizaTipoDePago);
setPolizaPago(polizaPago);
setPolizaImporteTotal(polizaImporteTotal);
setRiesgoAutomotorAdjunto(riesgoAutomotorListaAdjunto);
riesgoAutomotores.setPolizaRenovacion(this);
setPolizaEstado(Estado.previgente);
polizaEstado.actualizarEstado(this);
}
public String iconName() {
String a;
if (this.getRiesgoAutomotorListaVehiculos().size() == 1)
a = "individual";
else
a = "flotas";
return a;
}
// Vehiculo
@Join
@Property(editing = Editing.ENABLED)
@CollectionLayout(named = "Lista de vehiculos")
private List<Vehiculo> riesgoAutomotorListaVehiculos;
public List<Vehiculo> getRiesgoAutomotorListaVehiculos() {
return riesgoAutomotorListaVehiculos;
}
public void setRiesgoAutomotorListaVehiculos(List<Vehiculo> riesgoAutomotorListaVehiculos) {
this.riesgoAutomotorListaVehiculos = riesgoAutomotorListaVehiculos;
}
// Tipo Cobertura
@Column(name = "tipoDeCoberturaId")
@Property(editing = Editing.DISABLED)
@PropertyLayout(named = "Tipo de Cobertura")
private TipoDeCobertura riesgoAutomotorTipoDeCobertura;
public TipoDeCobertura getRiesgoAutomotorTipoDeCobertura() {
return riesgoAutomotorTipoDeCobertura;
}
public void setRiesgoAutomotorTipoDeCobertura(TipoDeCobertura riesgoAutomotorTipoDeCobertura) {
this.riesgoAutomotorTipoDeCobertura = riesgoAutomotorTipoDeCobertura;
}
// adjunto
@Join
@Column(allowsNull = "false")
@Property(editing = Editing.DISABLED)
@PropertyLayout(named = "Adjunto")
private List<Adjunto> riesgoAutomotorAdjunto;
public List<Adjunto> getRiesgoAutomotorAdjunto() {
return riesgoAutomotorAdjunto;
}
public void setRiesgoAutomotorAdjunto(List<Adjunto> riesgoAutomotorAdjunto) {
this.riesgoAutomotorAdjunto = riesgoAutomotorAdjunto;
}
// Actualizar PolizaNumero
public PolizaAutomotor actualizarPolizaNumero(@ParameterLayout(named = "Numero") final String polizaNumero) {
setPolizaNumero(polizaNumero);
return this;
}
public String default0ActualizarPolizaNumero() {
return getPolizaNumero();
}
// Actualizar Poliza Cliente
public PolizaAutomotor actualizarPolizaCliente(@ParameterLayout(named = "Cliente") final Persona polizaCliente) {
setPolizasCliente(polizaCliente);
return this;
}
public List<Persona> choices0ActualizarPolizaCliente() {
return personaRepository.listarActivos();
}
public Persona default0ActualizarPolizaCliente() {
return getPolizaCliente();
}
// Actualizar polizaCompania
public PolizaAutomotor actualizarPolizaCompania(
@ParameterLayout(named = "Compañia") final Compania polizaCompania) {
setPolizasCompania(polizaCompania);
return this;
}
public List<Compania> choices0ActualizarPolizaCompania() {
return companiaRepository.listarActivos();
}
public Compania default0ActualizarPolizaCompania() {
return getPolizaCompania();
}
// Actualizar riesgoAutomotorTiposDeCoberturas
public PolizaAutomotor actualizarRiesgoAutomotorTiposDeCoberturas(
@ParameterLayout(named = "Tipos De Coberturas") final TipoDeCobertura riesgoAutomotorTiposDeCoberturas) {
setRiesgoAutomotorTipoDeCobertura(riesgoAutomotorTiposDeCoberturas);
return this;
}
public List<TipoDeCobertura> choices0ActualizarRiesgoAutomotorTiposDeCoberturas() {
return tiposDeCoberturasRepository.listarActivos();
}
public TipoDeCobertura default0ActualizarRiesgoAutomotorTiposDeCoberturas() {
return getRiesgoAutomotorTipoDeCobertura();
}
// Actualizar polizaFechaEmision
public PolizaAutomotor actualizarPolizaFechaEmision(
@ParameterLayout(named = "Fecha de Emision") final Date polizaFechaEmision) {
setPolizaFechaEmision(polizaFechaEmision);
return this;
}
public Date default0ActualizarPolizaFechaEmision() {
return getPolizaFechaEmision();
}
// Actualizar polizaFechaVigencia
@SuppressWarnings("deprecation")
public PolizaAutomotor actualizarPolizaFechaVigencia(
@ParameterLayout(named = "Fecha de Vigencia") final Date polizaFechaVigencia) {
polizaFechaVigencia.setHours(12);
polizaFechaVigencia.setSeconds(1);
setPolizaFechaVigencia(polizaFechaVigencia);
polizaEstado.actualizarEstado(this);
return this;
}
public Date default0ActualizarPolizaFechaVigencia() {
return getPolizaFechaVigencia();
}
@SuppressWarnings("deprecation")
public String validateActualizarPolizaFechaVigencia(final Date polizaFechaVigencia) {
polizaFechaVigencia.setHours(12);
polizaFechaVigencia.setSeconds(1);
for (Vehiculo vehiculo : this.getRiesgoAutomotorListaVehiculos()) {
if (validarModificarFechaVigencia(vehiculo, polizaFechaVigencia, this) == false) {
return "ERROR: vehiculo existente en otra poliza vigente";
}
}
if (polizaFechaVigencia.after(this.getPolizaFechaVencimiento())) {
return "La fecha de vigencia es mayor a la de vencimiento";
}
return "";
}
// polizaFechaVencimiento
@SuppressWarnings("deprecation")
public PolizaAutomotor actualizarPolizaFechaVencimiento(
@ParameterLayout(named = "Fecha de Vencimiento") final Date polizaFechaVencimiento) {
polizaFechaVencimiento.setHours(12);
setPolizaFechaVencimiento(polizaFechaVencimiento);
polizaEstado.actualizarEstado(this);
return this;
}
public Date default0ActualizarPolizaFechaVencimiento() {
return getPolizaFechaVencimiento();
}
@SuppressWarnings("deprecation")
public String validateActualizarPolizaFechaVencimiento(final Date polizaFechaVencimiento) {
polizaFechaVencimiento.setHours(12);
for (Vehiculo vehiculo : this.getRiesgoAutomotorListaVehiculos()) {
if (validarModificarFechaVencimiento(vehiculo, polizaFechaVencimiento, this) == false) {
return "ERROR: vehiculo existente en otra poliza vigente";
}
}
if (this.getPolizaFechaVigencia().after(polizaFechaVencimiento)) {
return "La fecha de vencimiento es menor a la de vigencia";
}
return "";
}
// polizaPago
public PolizaAutomotor actualizarPolizaPago(
@ParameterLayout(named = "Tipo de Pago") final TipoPago polizaTipoDePago,
@Nullable @ParameterLayout(named = "Detalle del Pago") @Parameter(optionality = Optionality.OPTIONAL) final DetalleTipoPago polizaPago) {
setPolizaTipoDePago(polizaTipoDePago);
setPolizaPago(polizaPago);
return this;
}
@SuppressWarnings("unchecked")
public List<DetalleTipoPago> choices1ActualizarPolizaPago(final TipoPago polizaTipoDePago,
final DetalleTipoPago polizaPago) {
return detalleTipoPagoMenu.buscarPorTipoDePagoCombo(polizaTipoDePago);
}
public TipoPago default0ActualizarPolizaPago() {
return getPolizaTipoDePago();
}
public DetalleTipoPago default1ActualizarPolizaPago() {
return getPolizaPago();
}
// polizaFechaBaja
public PolizaAutomotor actualizarPolizaFechaBaja(
@ParameterLayout(named = "Fecha de Baja") final Date polizaFechaBaja) {
setPolizaFechaBaja(polizaFechaBaja);
return this;
}
public Date default0ActualizarPolizaFechaBaja() {
return getPolizaFechaBaja();
}
// polizaMotivoBaja
public PolizaAutomotor actualizarPolizaMotivoBaja(
@ParameterLayout(named = "Motivo de la Baja") final String polizaMotivoBaja) {
setPolizaMotivoBaja(polizaMotivoBaja);
return this;
}
public String default0ActualizarPolizaMotivoBaja() {
return getPolizaMotivoBaja();
}
// polizaImporteTotal
public PolizaAutomotor actualizarPolizaImporteTotal(
@ParameterLayout(named = "Importe Total") final double polizaImporteTotal) {
setPolizaImporteTotal(polizaImporteTotal);
return this;
}
public double default0ActualizarPolizaImporteTotal() {
return getPolizaImporteTotal();
}
// polizaRenovacion
@ActionLayout(named = "Actualizar Renovacion")
public PolizaAutomotor actualizarPolizaRenovacion(
@ParameterLayout(named = "Renovacion") final Poliza polizaRenovacion) {
setPolizaRenovacion(polizaRenovacion);
polizaEstado.actualizarEstado(this);
return this;
}
public List<Poliza> choices0ActualizarPolizaRenovacion() {
return polizasRepository.listar();
}
public Poliza default0ActualizarPolizaRenovacion() {
return getPolizaRenovacion();
}
public PolizaAutomotor borrarPolizaRenovacion() {
setPolizaRenovacion(null);
polizaEstado.actualizarEstado(this);
return this;
}
// endregion
// acciones
@Action(invokeOn = InvokeOn.OBJECT_ONLY)
@ActionLayout(named = "Emitir Renovacion")
public PolizaAutomotor renovacion(@ParameterLayout(named = "Número") final String polizaNumero,
@ParameterLayout(named = "Cliente") final Persona polizaCliente,
@ParameterLayout(named = "Compañia") final Compania polizaCompania,
@ParameterLayout(named = "Tipo de Cobertura") final TipoDeCobertura riesgoAutomotorTiposDeCoberturas,
@ParameterLayout(named = "Fecha Emision") final Date polizaFechaEmision,
@ParameterLayout(named = "Fecha Vigencia") final Date polizaFechaVigencia,
@ParameterLayout(named = "Fecha Vencimiento") final Date polizaFechaVencimiento,
@ParameterLayout(named = "Tipo de Pago") final TipoPago polizaTipoDePago,
@Nullable @ParameterLayout(named = "Detalle del Pago") @Parameter(optionality = Optionality.OPTIONAL) final DetalleTipoPago polizaPago,
@ParameterLayout(named = "Precio Total") final double polizaImporteTotal) {
List<Vehiculo> riesgoAutomotorListaVehiculos = new ArrayList<>();
riesgoAutomotorListaVehiculos = this.getRiesgoAutomotorListaVehiculos();
List<Adjunto> riesgoAutomotorListaAdjunto = new ArrayList<>();
riesgoAutomotorListaAdjunto = this.getRiesgoAutomotorAdjunto();
Mail.enviarMailPoliza(polizaCliente);
return riesgoAutomotoresRepository.renovacion(polizaNumero, polizaCliente, polizaCompania,
riesgoAutomotorListaVehiculos, riesgoAutomotorTiposDeCoberturas, polizaFechaEmision,
polizaFechaVigencia, polizaFechaVencimiento, polizaTipoDePago, polizaPago, polizaImporteTotal,
riesgoAutomotorListaAdjunto, this);
}
@SuppressWarnings("deprecation")
public String validateRenovacion(final String polizaNumero, final Persona polizaCliente,
final Compania polizaCompania, final TipoDeCobertura riesgoAutomotorTiposDeCoberturas,
final Date polizaFechaEmision, final Date polizaFechaVigencia, final Date polizaFechaVencimiento,
final TipoPago polizaTipoDePago, final DetalleTipoPago polizaPago, final double polizaImporteTotal) {
polizaFechaVigencia.setHours(12);
polizaFechaVigencia.setSeconds(1);
polizaFechaVencimiento.setHours(12);
if (polizaFechaVigencia.after(polizaFechaVencimiento)) {
return "La fecha de vigencia es mayor a la de vencimiento";
}
for (Vehiculo vehiculo : this.getRiesgoAutomotorListaVehiculos()) {
if (riesgoAutomotoresRepository.validar(vehiculo, polizaFechaVigencia) == false) {
return "ERROR: vehiculo existente en otra poliza vigente";
}
}
return "";
}
public List<Persona> choices1Renovacion() {
return personaRepository.listarActivos();
}
public List<Compania> choices2Renovacion() {
return companiaRepository.listarActivos();
}
public List<TipoDeCobertura> choices3Renovacion() {
return tiposDeCoberturasRepository.listarActivos();
}
@SuppressWarnings("unchecked")
public List<DetalleTipoPago> choices8Renovacion(final String polizaNumero, final Persona polizaCliente,
final Compania polizaCompania, final TipoDeCobertura riesgoAutomotorTiposDeCoberturas,
final Date polizaFechaEmision, final Date polizaFechaVigencia, final Date polizaFechaVencimiento,
final TipoPago polizaTipoDePago, final DetalleTipoPago polizaPago, final double polizaImporteTotal) {
return detalleTipoPagoMenu.buscarPorTipoDePagoCombo(polizaTipoDePago);
}
public Persona default1Renovacion() {
return getPolizaCliente();
}
public Compania default2Renovacion() {
return getPolizaCompania();
}
public TipoDeCobertura default3Renovacion() {
return getRiesgoAutomotorTipoDeCobertura();
}
public TipoPago default7Renovacion() {
return getPolizaTipoDePago();
}
public DetalleTipoPago default8Renovacion() {
return getPolizaPago();
}
@ActionLayout(named = "Crear y Agregar Vehiculo")
public PolizaAutomotor crearVehiculo(@ParameterLayout(named = "Dominio") final String vehiculoDominio,
@ParameterLayout(named = "Año") final int vehiculoAnio,
@ParameterLayout(named = "Numero de Motor") final String vehiculoNumeroMotor,
@ParameterLayout(named = "Numero de Chasis") final String vehiculoNumeroChasis,
@ParameterLayout(named = "Modelo") final Modelo vehiculoModelo) {
this.getRiesgoAutomotorListaVehiculos().add(vehiculosRepository.crear(vehiculoDominio, vehiculoAnio,
vehiculoNumeroMotor, vehiculoNumeroChasis, vehiculoModelo));
this.setRiesgoAutomotorListaVehiculos(this.getRiesgoAutomotorListaVehiculos());
return this;
}
public Collection<Integer> choices1CrearVehiculo() {
ArrayList<Integer> numbers = new ArrayList<Integer>();
Calendar hoy = Calendar.getInstance();
int año = hoy.get(Calendar.YEAR);
for (int i = 1980; i <= año; i++) {
numbers.add(i);
}
return numbers;
}
public List<Modelo> choices4CrearVehiculo() {
return modeloRepository.listarActivos();
}
public PolizaAutomotor agregarVehiculo(@ParameterLayout(named = "Vehiculo") final Vehiculo riesgoAutomorVehiculo) {
boolean validador = riesgoAutomotoresRepository.validar(riesgoAutomorVehiculo, this.getPolizaFechaVigencia());
if (validador) {
if (this.getRiesgoAutomotorListaVehiculos().contains(riesgoAutomorVehiculo)) {
messageService.warnUser("ERROR: El vehiculo ya está agregado en la lista");
} else {
this.getRiesgoAutomotorListaVehiculos().add(riesgoAutomorVehiculo);
this.setRiesgoAutomotorListaVehiculos(this.getRiesgoAutomotorListaVehiculos());
}
} else {
messageService.warnUser("ERROR: vehiculo existente en otra poliza vigente");
}
return this;
}
public List<Vehiculo> choices0AgregarVehiculo() {
return vehiculosRepository.listarActivos();
}
@ActionLayout(cssClassFa = "fa-car")
public PolizaAutomotor modificarVehiculo(
@ParameterLayout(named = "Vehiculo a añadir") Vehiculo riesgoAutomotorVehiculoNuevo,
@ParameterLayout(named = "Vehiculo a quitar") Vehiculo riesgoAutomotorVehiculoViejo) {
Iterator<Vehiculo> it = getRiesgoAutomotorListaVehiculos().iterator();
if (riesgoAutomotorVehiculoNuevo.equals(riesgoAutomotorVehiculoViejo)) {
messageService.warnUser("ERROR: el vehiculo a agregar y el vehiculo a quitar son el mismo");
} else {
if (this.getRiesgoAutomotorListaVehiculos().contains(riesgoAutomotorVehiculoNuevo)) {
messageService.warnUser("ERROR: El vehiculo que quiere agregar ya está agregado en la lista");
} else {
while (it.hasNext()) {
Vehiculo lista = it.next();
if (lista.equals(riesgoAutomotorVehiculoViejo)) {
it.remove();
this.getRiesgoAutomotorListaVehiculos().add(riesgoAutomotorVehiculoNuevo);
this.setRiesgoAutomotorListaVehiculos(this.getRiesgoAutomotorListaVehiculos());
}
}
}
}
return this;
}
public List<Vehiculo> choices0ModificarVehiculo() {
return vehiculosRepository.listarActivos();
}
public List<Vehiculo> choices1ModificarVehiculo() {
return getRiesgoAutomotorListaVehiculos();
}
public PolizaAutomotor quitarVehiculo(@ParameterLayout(named = "Vehiculo") Vehiculo riesgoAutomotorVehiculo) {
Iterator<Vehiculo> it = getRiesgoAutomotorListaVehiculos().iterator();
while (it.hasNext()) {
Vehiculo lista = it.next();
if (lista.equals(riesgoAutomotorVehiculo))
it.remove();
}
return this;
}
public List<Vehiculo> choices0QuitarVehiculo() {
return getRiesgoAutomotorListaVehiculos();
}
@ActionLayout(named = "Crear y Agregar Adjunto")
public PolizaAutomotor crearAdjunto(
@ParameterLayout(named = "Descripcion") final String riesgoAutomotorAdjuntoDescripcion,
@ParameterLayout(named = "Imagen") final Blob riesgoAutomorAdjunto) {
this.getRiesgoAutomotorAdjunto()
.add(adjuntoRepository.crear(riesgoAutomotorAdjuntoDescripcion, riesgoAutomorAdjunto));
this.setRiesgoAutomotorAdjunto(this.getRiesgoAutomotorAdjunto());
return this;
}
@ActionLayout(named = "Agregar adjunto")
public PolizaAutomotor agregarAdjunto(@ParameterLayout(named = "Adjunto") final Adjunto riesgoAutomotorAdjunto) {
if (this.getRiesgoAutomotorAdjunto().contains(riesgoAutomotorAdjunto)) {
messageService.warnUser("ERROR: La imagen ya está agregada en la lista");
} else {
this.getRiesgoAutomotorAdjunto().add(riesgoAutomotorAdjunto);
this.setRiesgoAutomotorAdjunto(this.getRiesgoAutomotorAdjunto());
}
return this;
}
public List<Adjunto> choices0AgregarAdjunto() {
return adjuntoRepository.listarActivos();
}
public PolizaAutomotor quitarAdjunto(@ParameterLayout(named = "Imagen") Adjunto adjunto) {
Iterator<Adjunto> it = getRiesgoAutomotorAdjunto().iterator();
while (it.hasNext()) {
Adjunto lista = it.next();
if (lista.equals(adjunto))
it.remove();
}
return this;
}
public List<Adjunto> choices0QuitarAdjunto() {
return getRiesgoAutomotorAdjunto();
}
@ActionLayout(hidden = Where.EVERYWHERE)
public boolean validarModificarFechaVigencia(Vehiculo vehiculo, Date fechaVigencia,
PolizaAutomotor riesgoAutomotor) {
boolean validador = true;
List<PolizaAutomotor> listaPolizas = riesgoAutomotoresRepository.listarPorEstado(Estado.vigente);
listaPolizas.addAll(riesgoAutomotoresRepository.listarPorEstado(Estado.previgente));
for (PolizaAutomotor r : listaPolizas) {
if (r != riesgoAutomotor) {
for (Vehiculo v : r.getRiesgoAutomotorListaVehiculos()) {
if (vehiculo.equals(v)) {
if ((fechaVigencia.before(r.getPolizaFechaVencimiento()))
& (this.getPolizaFechaVencimiento().after(r.getPolizaFechaVigencia()))) {
validador = false;
}
}
}
}
}
return validador;
}
@ActionLayout(hidden = Where.EVERYWHERE)
public boolean validarModificarFechaVencimiento(Vehiculo vehiculo, Date fechaVencimiento,
PolizaAutomotor riesgoAutomotor) {
boolean validador = true;
List<PolizaAutomotor> listaPolizas = riesgoAutomotoresRepository.listarPorEstado(Estado.vigente);
listaPolizas.addAll(riesgoAutomotoresRepository.listarPorEstado(Estado.previgente));
for (PolizaAutomotor r : listaPolizas) {
if (r != riesgoAutomotor) {
for (Vehiculo v : r.getRiesgoAutomotorListaVehiculos()) {
if (vehiculo.equals(v)) {
if ((fechaVencimiento.after(r.getPolizaFechaVigencia()))
& (this.getPolizaFechaVigencia().before(r.getPolizaFechaVencimiento()))) {
validador = false;
}
}
}
}
}
return validador;
}
public Blob imprimirPoliza() throws JRException, IOException {
List<Object> objectsReport = new ArrayList<Object>();
PolizaAutomotorReporte polizaAutomotorReporte = new PolizaAutomotorReporte();
polizaAutomotorReporte.setPolizaCliente(getPolizaCliente().toString());
polizaAutomotorReporte.setPolizaNumero(getPolizaNumero());
polizaAutomotorReporte.setPolizaCompania(getPolizaCompania().getCompaniaNombre());
polizaAutomotorReporte.setPolizaFechaEmision(getPolizaFechaEmision());
polizaAutomotorReporte.setPolizaFechaVigencia(getPolizaFechaVigencia());
polizaAutomotorReporte.setPolizaFechaVencimiento(getPolizaFechaVencimiento());
polizaAutomotorReporte
.setRiesgoAutomotorTipoDeCobertura(getRiesgoAutomotorTipoDeCobertura().getTipoDeCoberturaNombre());
polizaAutomotorReporte.setPolizaImporteTotal(getPolizaImporteTotal());
polizaAutomotorReporte.setPolizaEstado(getPolizaEstado().toString());
objectsReport.add(polizaAutomotorReporte);
String jrxml = "PolizaAutomotor.jrxml";
String nombreArchivo = "PolizaAutomotor_" + getPolizaCliente().toString().replaceAll("\\s", "_") + "_"
+ getPolizaNumero();
return ReporteRepository.imprimirReporteIndividual(objectsReport, jrxml, nombreArchivo);
}
// region > toString, compareTo
@Override
public String toString() {
return "Poliza Automotor Numero: " + getPolizaNumero();
}
// endregion
// region > injected dependencies
@Inject
RepositoryService repositoryService;
@Inject
TitleService titleService;
@Inject
MessageService messageService;
@Inject
PersonaRepository personaRepository;
@Inject
VehiculoRepository vehiculosRepository;
@Inject
DetalleTipoPagoRepository detalleTipoPagosRepository;
@Inject
CompaniaRepository companiaRepository;
@Inject
TipoDeCoberturaRepository tiposDeCoberturasRepository;
@Inject
PolizaRepository polizasRepository;
@Inject
PolizaAutomotoresRepository riesgoAutomotoresRepository;
@Inject
DetalleTipoPagoMenu detalleTipoPagoMenu;
@Inject
AdjuntoRepository adjuntoRepository;
@Inject
ModeloRepository modeloRepository;
// endregion
}
|
puneetarora2000/adkworks | HumiTemp/src/net/cattaka/android/humitemp/util/GraphDrawer.java |
package net.cattaka.android.humitemp.util;
import java.util.List;
import net.cattaka.android.humitemp.util.CtkCanvasUtil.Gravity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
public class GraphDrawer {
public static class GraphAreaInfo {
public float paddingTop;
public float paddingBottom;
public float paddingLeft;
public float paddingRight;
public float graphWidth;
public float graphHeight;
public float minX;
public float maxX;
public float minY;
public float maxY;
public String unitX;
public String unitY;
public float scaleY1 = 1;
public float scaleY2 = 1;
public float textSize;
}
public static class GridInfo {
public GridLine gridLine;
public String label;
public String label2;
public float value;
public int labelColor = Color.BLACK;
public GridInfo() {
}
public GridInfo(GridLine gridLine, String label, String label2, float value, int labelColor) {
super();
this.gridLine = gridLine;
this.label = label;
this.label2 = label2;
this.value = value;
this.labelColor = labelColor;
}
}
public enum GridLine {
LINE, DASHED, NONE
};
public static class GraphValue {
public float startX;
public float endX;
// public float startY;
public float endY1;
public float endY2;
public int count;
}
public static class GraphLabels {
public String title;
public String appName;
public String counts;
}
public static void createGraph(Canvas canvas, GraphAreaInfo gaInfo, List<GridInfo> gixList,
List<GridInfo> giyList, List<GraphValue> gvList) {
Paint gridLinePaint = new Paint();
Paint gridDashedLinePaint = new Paint();
Paint barPaint1 = new Paint();
Paint barPaint2 = new Paint();
Paint labelPaint = new Paint();
Paint boldLabelPaint = new Paint();
gridLinePaint.setColor(Color.GRAY);
gridDashedLinePaint.setColor(Color.LTGRAY);
barPaint1.setColor(Color.BLUE);
barPaint1.setStyle(Paint.Style.FILL);
barPaint2.setColor(Color.RED);
barPaint2.setStyle(Paint.Style.FILL);
labelPaint.setTextSize(gaInfo.textSize);
labelPaint.setAntiAlias(true);
boldLabelPaint.setFakeBoldText(true);
boldLabelPaint.setTextSize(gaInfo.textSize);
boldLabelPaint.setAntiAlias(true);
// Y軸のグリッドを書く
for (GridInfo giy : giyList) {
float y = gaInfo.paddingTop + gaInfo.graphHeight - gaInfo.graphHeight
* (giy.value - gaInfo.minY) / (gaInfo.maxY - gaInfo.minY);
if (giy.label != null) {
labelPaint.setColor(giy.labelColor);
CtkCanvasUtil.drawText(canvas, labelPaint, gaInfo.paddingLeft, y, giy.label,
Gravity.GRAVITY_CENTER, Gravity.GRAVITY_RIGHT);
}
if (giy.label2 != null) {
labelPaint.setColor(giy.labelColor);
CtkCanvasUtil.drawText(canvas, labelPaint, gaInfo.paddingLeft + gaInfo.graphWidth,
y, giy.label2, Gravity.GRAVITY_CENTER, Gravity.GRAVITY_LEFT);
}
if (giy.gridLine == GridLine.LINE) {
canvas.drawLine(gaInfo.paddingLeft, y, gaInfo.paddingLeft + gaInfo.graphWidth, y,
gridLinePaint);
}
if (giy.gridLine == GridLine.DASHED) {
canvas.drawLine(gaInfo.paddingLeft, y, gaInfo.paddingLeft + gaInfo.graphWidth, y,
gridDashedLinePaint);
}
}
// X軸のグリッドを書く
for (GridInfo gix : gixList) {
float x = gaInfo.paddingLeft + gaInfo.graphWidth * (gix.value - gaInfo.minX)
/ (gaInfo.maxX - gaInfo.minX);
if (gix.label != null) {
labelPaint.setColor(gix.labelColor);
CtkCanvasUtil.drawText(canvas, labelPaint, x, gaInfo.paddingTop
+ gaInfo.graphHeight, gix.label, Gravity.GRAVITY_TOP,
Gravity.GRAVITY_CENTER);
}
if (gix.gridLine == GridLine.LINE) {
canvas.drawLine(x, gaInfo.paddingTop, x, gaInfo.paddingTop + gaInfo.graphHeight,
gridLinePaint);
}
if (gix.gridLine == GridLine.DASHED) {
canvas.drawLine(x, gaInfo.paddingTop, x, gaInfo.paddingTop + gaInfo.graphHeight,
gridDashedLinePaint);
}
}
// 値を描画する
GraphValue lastGv = gvList.get(0);
for (int i = 1; i < gvList.size(); i++) {
GraphValue nextGv = gvList.get(i);
{
float sx = gaInfo.paddingLeft
+ (gaInfo.graphWidth * (lastGv.startX - gaInfo.minX) / (gaInfo.maxX - gaInfo.minX));
float sy = gaInfo.paddingTop
+ gaInfo.graphHeight
- (gaInfo.graphHeight * (lastGv.endY1 - gaInfo.minY) / (gaInfo.maxY - gaInfo.minY))
- 1;
float ex = gaInfo.paddingLeft
+ (gaInfo.graphWidth * (nextGv.startX - gaInfo.minX) / (gaInfo.maxX - gaInfo.minX));
float ey = gaInfo.paddingTop
+ gaInfo.graphHeight
- (gaInfo.graphHeight * (nextGv.endY1 - gaInfo.minY) / (gaInfo.maxY - gaInfo.minY))
- 1;
canvas.drawLine(sx, sy, ex, ey, barPaint1);
}
{
float sx = gaInfo.paddingLeft
+ (gaInfo.graphWidth * (lastGv.startX - gaInfo.minX) / (gaInfo.maxX - gaInfo.minX));
float sy = gaInfo.paddingTop
+ gaInfo.graphHeight
- (gaInfo.graphHeight * (lastGv.endY2 - gaInfo.minY) / (gaInfo.maxY - gaInfo.minY))
- 1;
float ex = gaInfo.paddingLeft
+ (gaInfo.graphWidth * (nextGv.startX - gaInfo.minX) / (gaInfo.maxX - gaInfo.minX));
float ey = gaInfo.paddingTop
+ gaInfo.graphHeight
- (gaInfo.graphHeight * (nextGv.endY2 - gaInfo.minY) / (gaInfo.maxY - gaInfo.minY))
- 1;
canvas.drawLine(sx, sy, ex, ey, barPaint2);
}
lastGv = nextGv;
}
// XY軸の単位を描画
{
labelPaint.setColor(Color.BLACK);
CtkCanvasUtil.drawText(canvas, boldLabelPaint, gaInfo.paddingLeft + gaInfo.graphWidth
+ gaInfo.textSize, gaInfo.paddingTop + gaInfo.graphHeight + gaInfo.textSize,
gaInfo.unitX, Gravity.GRAVITY_TOP, Gravity.GRAVITY_RIGHT);
CtkCanvasUtil.drawText(canvas, boldLabelPaint, gaInfo.paddingLeft - gaInfo.textSize,
gaInfo.paddingTop - gaInfo.textSize / 2f, gaInfo.unitY, Gravity.GRAVITY_BOTTOM,
Gravity.GRAVITY_LEFT);
}
}
}
|
gina-alaska/gina-catalog | test/controllers/api/map_layers_controller_test.rb | require 'test_helper'
class Api::MapLayersControllerTest < ActionController::TestCase
def test_index
get :index, format: 'json'
assert_response :success
end
end
|
openedx/paragon | icons/es5/AirlineSeatFlatAngled.js | <reponame>openedx/paragon<filename>icons/es5/AirlineSeatFlatAngled.js<gh_stars>1-10
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
import * as React from "react";
function SvgAirlineSeatFlatAngled(props) {
return /*#__PURE__*/React.createElement("svg", _extends({
xmlns: "http://www.w3.org/2000/svg",
width: 24,
height: 24,
viewBox: "0 0 24 24"
}, props), /*#__PURE__*/React.createElement("path", {
d: "M21.56 16.18L9.2 11.71l2.08-5.66 12.35 4.47-2.07 5.66zM1.5 12.14L8 14.48V19h8v-1.63L20.52 19l.69-1.89-19.02-6.86-.69 1.89zm5.8-1.94a3.01 3.01 0 001.41-4A3.005 3.005 0 004.7 4.8a2.99 2.99 0 00-1.4 4 2.99 2.99 0 004 1.4z"
}));
}
export default SvgAirlineSeatFlatAngled; |
danghica/mokapot | mokapot/src/benchmark/java/xyz/acygn/mokapot/benchmarksuite/programs/sort/benchmarks/SortLocalBenchmark.java | package xyz.acygn.mokapot.benchmarksuite.programs.sort.benchmarks;
import java.io.IOException;
import java.rmi.NotBoundException;
import java.util.List;
import xyz.acygn.mokapot.benchmarksuite.benchmark.RemoteProcess;
import xyz.acygn.mokapot.benchmarksuite.programs.sort.HelperImpl;
import xyz.acygn.mokapot.benchmarksuite.programs.sort.SorterImpl;
public class SortLocalBenchmark extends SortBenchmark {
@Override
public ExampleType getType() {
return ExampleType.LOCAL;
}
@Override
public void distribute() throws IOException {
if (listToBeSorted == null) {
listToBeSorted = this.generateListOfRandomNumbers();
}
s = new SorterImpl<Integer>();
for (int i = 0; i < this.getNumberOfRequiredPeers(); i++) {
s.addHelper(new HelperImpl());
}
s.addElements((List<Integer>)listToBeSorted.clone());
}
@Override
public void stop() throws IOException, NotBoundException {
super.stop();
}
}
|
rolandomar/stheno | euryale/src/org/cracs/euryale/qos/medusa/medusa.cpp | <gh_stars>1-10
/*
* Copyright 2012 <NAME>, CRACS & INESC-TEC, DCC/FCUP
*
* 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.
*
*/
#include <euryale/qos/medusa/MedusadCore.h>
#include <malloc.h>
#include <euryale/common/Backtrace.h>
int main(int argc, char** argv) {
try {
bool remove = false;
if (argc > 1) {
if (strcmp(argv[1], "-r") == 0) {
remove = true;
}else{
ACE_DEBUG((LM_DEBUG, ACE_TEXT("Error starting medusad, wrong argument! ('medusad -r' for removal, or 'medusad' for server startup)\n")));
exit(-1);
}
}
MedusadCore hadesd;
hadesd.init(remove);
if (!remove) {
ACE_DEBUG((LM_DEBUG, ACE_TEXT("Starting medusad...\n")));
hadesd.start();
} else {
ACE_DEBUG((LM_DEBUG, ACE_TEXT("Removing cgroup files...\n")));
hadesd.remove();
}
} catch (CgroupException& ex) {
ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)Ex=%s\n"), ex.toString().c_str()));
ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)End\n")));
Backtrace::backstrace();
}
return 0;
}
|
postillonmedia/app | src/components/steady/states/loggedOut/index.js | import { compose } from 'recompose';
import { ThemeManager, connectStyle } from '@postillon/react-native-theme';
import { i18n } from '@postillon/react-native-i18n';
import { Themes } from './../../../../constants/themes';
import styles from './styles';
import SteadyLoggedOutView from './SteadyLoggedOutView';
ThemeManager.addStyleSheet(styles.darkStyles, 'steady.logged.out', Themes.DARK);
ThemeManager.addStyleSheet(styles.defaultStyles, 'steady.logged.out', Themes.DEFAULT);
export default compose(
i18n('steady'),
connectStyle('steady.logged.out'),
)(SteadyLoggedOutView); |
kubeform/provider-google-api | apis/monitoring/v1alpha1/notification_channel_types.go | /*
Copyright AppsCode Inc. and 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.
*/
// Code generated by Kubeform. DO NOT EDIT.
package v1alpha1
import (
base "kubeform.dev/apimachinery/api/v1alpha1"
core "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kmapi "kmodules.xyz/client-go/api/v1"
"sigs.k8s.io/cli-utils/pkg/kstatus/status"
)
// +genclient
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase`
type NotificationChannel struct {
metav1.TypeMeta `json:",inline,omitempty"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec NotificationChannelSpec `json:"spec,omitempty"`
Status NotificationChannelStatus `json:"status,omitempty"`
}
type NotificationChannelSpecSensitiveLabels struct {
// An authorization token for a notification channel. Channel types that support this field include: slack
// +optional
AuthToken *string `json:"-" sensitive:"true" tf:"auth_token"`
// An password for a notification channel. Channel types that support this field include: webhook_basicauth
// +optional
Password *string `json:"-" sensitive:"true" tf:"password"`
// An servicekey token for a notification channel. Channel types that support this field include: pagerduty
// +optional
ServiceKey *string `json:"-" sensitive:"true" tf:"service_key"`
}
type NotificationChannelSpec struct {
State *NotificationChannelSpecResource `json:"state,omitempty" tf:"-"`
Resource NotificationChannelSpecResource `json:"resource" tf:"resource"`
UpdatePolicy base.UpdatePolicy `json:"updatePolicy,omitempty" tf:"-"`
TerminationPolicy base.TerminationPolicy `json:"terminationPolicy,omitempty" tf:"-"`
ProviderRef core.LocalObjectReference `json:"providerRef" tf:"-"`
SecretRef *core.LocalObjectReference `json:"secretRef,omitempty" tf:"-"`
BackendRef *core.LocalObjectReference `json:"backendRef,omitempty" tf:"-"`
}
type NotificationChannelSpecResource struct {
Timeouts *base.ResourceTimeout `json:"timeouts,omitempty" tf:"timeouts"`
ID string `json:"id,omitempty" tf:"id,omitempty"`
// An optional human-readable description of this notification channel. This description may provide additional details, beyond the display name, for the channel. This may not exceed 1024 Unicode characters.
// +optional
Description *string `json:"description,omitempty" tf:"description"`
// An optional human-readable name for this notification channel. It is recommended that you specify a non-empty and unique name in order to make it easier to identify the channels in your project, though this is not enforced. The display name is limited to 512 Unicode characters.
// +optional
DisplayName *string `json:"displayName,omitempty" tf:"display_name"`
// Whether notifications are forwarded to the described channel. This makes it possible to disable delivery of notifications to a particular channel without removing the channel from all alerting policies that reference the channel. This is a more convenient approach when the change is temporary and you want to receive notifications from the same set of alerting policies on the channel at some point in the future.
// +optional
Enabled *bool `json:"enabled,omitempty" tf:"enabled"`
// Configuration fields that define the channel and its behavior. The
// permissible and required labels are specified in the
// NotificationChannelDescriptor corresponding to the type field.
//
// Labels with sensitive data are obfuscated by the API and therefore Terraform cannot
// determine if there are upstream changes to these fields. They can also be configured via
// the sensitive_labels block, but cannot be configured in both places.
// +optional
Labels *map[string]string `json:"labels,omitempty" tf:"labels"`
// The full REST resource name for this channel. The syntax is:
// projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]
// The [CHANNEL_ID] is automatically assigned by the server on creation.
// +optional
Name *string `json:"name,omitempty" tf:"name"`
// +optional
Project *string `json:"project,omitempty" tf:"project"`
// Different notification type behaviors are configured primarily using the the 'labels' field on this
// resource. This block contains the labels which contain secrets or passwords so that they can be marked
// sensitive and hidden from plan output. The name of the field, eg: password, will be the key
// in the 'labels' map in the api request.
//
// Credentials may not be specified in both locations and will cause an error. Changing from one location
// to a different credential configuration in the config will require an apply to update state.
// +optional
SensitiveLabels *NotificationChannelSpecSensitiveLabels `json:"sensitiveLabels,omitempty" tf:"sensitive_labels"`
// The type of the notification channel. This field matches the value of the NotificationChannelDescriptor.type field. See https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannelDescriptors/list to get the list of valid values such as "email", "slack", etc...
Type *string `json:"type" tf:"type"`
// User-supplied key/value data that does not need to conform to the corresponding NotificationChannelDescriptor's schema, unlike the labels field. This field is intended to be used for organizing and identifying the NotificationChannel objects.The field can contain up to 64 entries. Each key and value is limited to 63 Unicode characters or 128 bytes, whichever is smaller. Labels and values can contain only lowercase letters, numerals, underscores, and dashes. Keys must begin with a letter.
// +optional
UserLabels *map[string]string `json:"userLabels,omitempty" tf:"user_labels"`
// Indicates whether this channel has been verified or not. On a ListNotificationChannels or GetNotificationChannel operation, this field is expected to be populated.If the value is UNVERIFIED, then it indicates that the channel is non-functioning (it both requires verification and lacks verification); otherwise, it is assumed that the channel works.If the channel is neither VERIFIED nor UNVERIFIED, it implies that the channel is of a type that does not require verification or that this specific channel has been exempted from verification because it was created prior to verification being required for channels of this type.This field cannot be modified using a standard UpdateNotificationChannel operation. To change the value of this field, you must call VerifyNotificationChannel.
// +optional
VerificationStatus *string `json:"verificationStatus,omitempty" tf:"verification_status"`
}
type NotificationChannelStatus struct {
// Resource generation, which is updated on mutation by the API Server.
// +optional
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
// +optional
Phase status.Status `json:"phase,omitempty"`
// +optional
Conditions []kmapi.Condition `json:"conditions,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// NotificationChannelList is a list of NotificationChannels
type NotificationChannelList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
// Items is a list of NotificationChannel CRD objects
Items []NotificationChannel `json:"items,omitempty"`
}
|
HenryssonDaniel/teacup-java-core | src/test/java/io/github/henryssondaniel/teacup/core/assertion/AbstractCharSequenceAssertTest.java | <filename>src/test/java/io/github/henryssondaniel/teacup/core/assertion/AbstractCharSequenceAssertTest.java<gh_stars>0
package io.github.henryssondaniel.teacup.core.assertion;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Locale;
import org.junit.jupiter.api.Test;
class AbstractCharSequenceAssertTest {
private static final String REGEX = ".*en.*";
private static final String SEQUENCE = "sequence";
private static final String SEQUENCE_END = "nce";
private static final String SEQUENCE_LONG = "sequencelongerSequence";
private static final String SEQUENCE_SPACE = "sequence ";
private static final String SEQUENCE_START = "seq";
private static final CharSequence XML =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading></note>";
private final TestGenericCharSequenceAssert testAbstractCharSequenceAssert =
new TestAbstractCharSequenceAssert();
@Test
void contains() {
testAbstractCharSequenceAssert.contains(SEQUENCE).verify(SEQUENCE_LONG);
}
@Test
void containsFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> testAbstractCharSequenceAssert.contains(SEQUENCE_LONG).verify(SEQUENCE));
}
@Test
void containsIgnoringCase() {
testAbstractCharSequenceAssert
.containsIgnoringCase(SEQUENCE.toUpperCase(Locale.getDefault()))
.verify(SEQUENCE_LONG);
}
@Test
void containsIgnoringCaseFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.containsIgnoringCase(SEQUENCE_LONG)
.verify(SEQUENCE));
}
@Test
void containsOnlyOnce() {
testAbstractCharSequenceAssert.containsOnlyOnce(SEQUENCE).verify(SEQUENCE_LONG);
}
@Test
void containsOnlyOnceFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> testAbstractCharSequenceAssert.containsOnlyOnce("e").verify(SEQUENCE));
}
@Test
void containsPattern() {
testAbstractCharSequenceAssert.containsPattern(SEQUENCE).verify(SEQUENCE_LONG);
}
@Test
void containsPatternFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> testAbstractCharSequenceAssert.containsPattern(SEQUENCE_LONG).verify(SEQUENCE));
}
@Test
void containsSequence() {
testAbstractCharSequenceAssert.containsSequence(SEQUENCE).verify(SEQUENCE_LONG);
}
@Test
void containsSequenceFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> testAbstractCharSequenceAssert.containsSequence(SEQUENCE_LONG).verify(SEQUENCE));
}
@Test
void containsSubsequence() {
testAbstractCharSequenceAssert.containsSubsequence(SEQUENCE).verify(SEQUENCE_LONG);
}
@Test
void containsSubsequenceFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert.containsSubsequence(SEQUENCE_LONG).verify(SEQUENCE));
}
@Test
void doesNotContain() {
testAbstractCharSequenceAssert.doesNotContain(SEQUENCE_LONG).verify(SEQUENCE);
}
@Test
void doesNotContainFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> testAbstractCharSequenceAssert.doesNotContain(SEQUENCE).verify(SEQUENCE_LONG));
}
@Test
void doesNotContainPattern() {
testAbstractCharSequenceAssert.doesNotContainPattern(SEQUENCE_LONG).verify(SEQUENCE);
}
@Test
void doesNotContainPatternFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.doesNotContainPattern(SEQUENCE)
.verify(SEQUENCE_LONG));
}
@Test
void doesNotEndWith() {
testAbstractCharSequenceAssert.doesNotEndWith(SEQUENCE).verify(SEQUENCE_LONG);
}
@Test
void doesNotEndWithFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> testAbstractCharSequenceAssert.doesNotEndWith(SEQUENCE_END).verify(SEQUENCE));
}
@Test
void doesNotMatch() {
testAbstractCharSequenceAssert.doesNotMatch(SEQUENCE).verify(SEQUENCE_LONG);
}
@Test
void doesNotMatchFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> testAbstractCharSequenceAssert.doesNotMatch(REGEX).verify(SEQUENCE));
}
@Test
void doesNotStartWith() {
testAbstractCharSequenceAssert.doesNotStartWith(SEQUENCE_LONG).verify(SEQUENCE);
}
@Test
void doesNotStartWithFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> testAbstractCharSequenceAssert.doesNotStartWith(SEQUENCE).verify(SEQUENCE_LONG));
}
@Test
void endsWith() {
testAbstractCharSequenceAssert.endsWith(SEQUENCE_END).verify(SEQUENCE);
}
@Test
void endsWithFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> testAbstractCharSequenceAssert.endsWith(SEQUENCE).verify(SEQUENCE_END));
}
@Test
void hasSameSizeAs() {
testAbstractCharSequenceAssert.hasSameSizeAs("abcdefgh").verify(SEQUENCE);
}
@Test
void hasSameSizeAsFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> testAbstractCharSequenceAssert.hasSameSizeAs("abcdefghi").verify(SEQUENCE));
}
@Test
void isEqualToIgnoringCase() {
testAbstractCharSequenceAssert
.isEqualToIgnoringCase(SEQUENCE.toLowerCase(Locale.getDefault()))
.verify(SEQUENCE);
}
@Test
void isEqualToIgnoringCaseFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.isEqualToIgnoringCase(SEQUENCE)
.verify(SEQUENCE_LONG));
}
@Test
void isEqualToIgnoringNewLines() {
testAbstractCharSequenceAssert
.isEqualToIgnoringNewLines(SEQUENCE)
.verify(SEQUENCE + System.lineSeparator());
}
@Test
void isEqualToIgnoringNewLinesFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.isEqualToIgnoringNewLines(SEQUENCE)
.verify(SEQUENCE_LONG));
}
@Test
void isEqualToIgnoringWhitespace() {
testAbstractCharSequenceAssert.isEqualToIgnoringWhitespace(SEQUENCE).verify(SEQUENCE_SPACE);
}
@Test
void isEqualToIgnoringWhitespaceFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.isEqualToIgnoringWhitespace(SEQUENCE_LONG)
.verify(SEQUENCE_SPACE));
}
@Test
void isEqualToNormalizingNewlines() {
testAbstractCharSequenceAssert.isEqualToNormalizingNewlines(SEQUENCE).verify(SEQUENCE);
}
@Test
void isEqualToNormalizingNewlinesFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.isEqualToNormalizingNewlines(SEQUENCE)
.verify(SEQUENCE_LONG));
}
@Test
void isEqualToNormalizingWhitespace() {
testAbstractCharSequenceAssert.isEqualToNormalizingWhitespace(SEQUENCE).verify(SEQUENCE);
}
@Test
void isEqualToNormalizingWhitespaceFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.isEqualToNormalizingWhitespace(SEQUENCE)
.verify(SEQUENCE_LONG));
}
@Test
void isNotEqualToIgnoringCase() {
testAbstractCharSequenceAssert.isNotEqualToIgnoringCase(SEQUENCE).verify(SEQUENCE_LONG);
}
@Test
void isNotEqualToIgnoringCaseFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.isNotEqualToIgnoringCase(SEQUENCE)
.verify(SEQUENCE.toLowerCase(Locale.getDefault())));
}
@Test
void isNotEqualToIgnoringWhitespace() {
testAbstractCharSequenceAssert
.isNotEqualToIgnoringWhitespace(SEQUENCE_SPACE)
.verify(SEQUENCE_LONG);
}
@Test
void isNotEqualToIgnoringWhitespaceFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.isNotEqualToIgnoringWhitespace(SEQUENCE_SPACE)
.verify(SEQUENCE));
}
@Test
void isNotEqualToNormalizingWhitespace() {
testAbstractCharSequenceAssert
.isNotEqualToNormalizingWhitespace(SEQUENCE)
.verify(SEQUENCE_LONG);
}
@Test
void isNotEqualToNormalizingWhitespaceFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.isNotEqualToNormalizingWhitespace(SEQUENCE)
.verify(SEQUENCE));
}
@Test
void isSubstringOf() {
testAbstractCharSequenceAssert.isSubstringOf(SEQUENCE_LONG).verify(SEQUENCE_END);
}
@Test
void isSubstringOfFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> testAbstractCharSequenceAssert.isSubstringOf(SEQUENCE_END).verify(SEQUENCE_LONG));
}
@Test
void isXmlEqualTo() {
testAbstractCharSequenceAssert
.isXmlEqualTo(XML)
.verify(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<note>"
+ " <to>Tove</to>"
+ " <from>Jani</from>"
+ " <heading>Reminder</heading>"
+ "</note>");
}
@Test
void isXmlEqualToFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() ->
testAbstractCharSequenceAssert
.isXmlEqualTo(XML)
.verify(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<note>"
+ " <from>Jani</from>"
+ " <heading>Reminder</heading>"
+ "</note>"));
}
@Test
void matches() {
testAbstractCharSequenceAssert.matches(REGEX).verify(SEQUENCE);
}
@Test
void matchesFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> testAbstractCharSequenceAssert.matches(SEQUENCE).verify(REGEX));
}
@Test
void startsWith() {
testAbstractCharSequenceAssert.startsWith(SEQUENCE_START).verify(SEQUENCE);
}
@Test
void startsWithFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> testAbstractCharSequenceAssert.startsWith(SEQUENCE).verify(SEQUENCE_START));
}
private interface TestGenericCharSequenceAssert
extends GenericCharSequenceAssert<String, TestGenericCharSequenceAssert> {}
private static final class TestAbstractCharSequenceAssert
extends AbstractCharSequenceAssert<String, TestGenericCharSequenceAssert>
implements TestGenericCharSequenceAssert {}
}
|
sjyothi54/gatsby-theme-newrelic | packages/gatsby-theme-newrelic/src/components/SEO.js | import React from 'react';
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';
import { graphql, useStaticQuery } from 'gatsby';
import useLocale from '../hooks/useLocale';
import path from 'path';
const SEO = ({ title, location, type, children }) => {
const {
site: { siteMetadata },
allLocale: { nodes: locales },
} = useStaticQuery(graphql`
query {
site {
siteMetadata {
defaultTitle: title
titleTemplate
siteUrl
}
}
allLocale {
nodes {
locale
hrefLang
isDefault
}
}
}
`);
const locale = useLocale();
const defaultLocale = locales.find(({ isDefault }) => isDefault);
const { defaultTitle, titleTemplate, siteUrl } = siteMetadata;
const template = title ? titleTemplate : '%s';
const subPath =
locale.locale === defaultLocale.locale
? location.pathname
: location.pathname.replace(new RegExp(`^\\/${locale.locale}`), '/');
const getSwiftypeSiteType = () => {
if (type) {
return type;
}
const hostname = new URL(siteUrl).hostname;
const nrSubDomain = /.*\.newrelic\.com/.test(hostname)
? hostname.split('.')[0]
: null;
const localeString = locale.isDefault ? '' : `-${locale.locale}`;
return nrSubDomain ? nrSubDomain.concat(localeString) : null;
};
const siteLinkScript = () => {
const { pathname } = location;
const homepage = '/';
if (pathname === homepage && siteUrl) {
return (
<script type="application/ld+json">
{`{
"@context": "https://schema.org",
"@type": "WebSite",
"url": "${siteUrl}",
"potentialAction": [{
"@type": "SearchAction",
"target": {
"@type": "EntryPoint",
"urlTemplate": "${siteUrl}/?q={search_term_string}"
},
"query-input": "required name=search_term_string"
}]
}`}
</script>
);
}
};
return (
<Helmet titleTemplate={template}>
<html lang={locale.hrefLang} />
<title>{title || defaultTitle}</title>
<link rel="canonical" href={new URL(location.pathname, siteUrl).href} />
{locales.map(({ hrefLang, isDefault, locale }) => {
const url = new URL(
path.join(isDefault ? '/' : locale, subPath),
siteUrl
);
return (
<link
key={locale}
rel="alternate"
href={url.href}
hrefLang={hrefLang}
/>
);
})}
{getSwiftypeSiteType() && (
<meta
className="swiftype"
name="type"
data-type="enum"
content={getSwiftypeSiteType()}
/>
)}
{siteLinkScript()}
{children}
</Helmet>
);
};
SEO.propTypes = {
title: PropTypes.string,
location: PropTypes.shape({
pathname: PropTypes.string,
}).isRequired,
type: PropTypes.string,
children: PropTypes.node,
};
export default SEO;
|
dujianxin/Windows-universal-samples | Samples/ComplexInk/cpp/pch.h | //
// Header for standard system include files.
//
#pragma once
#include <collection.h>
#include <ppltasks.h>
#include <wrl.h>
#include <wrl/client.h>
#include <d3d11_2.h>
#include <d2d1_2.h>
#include <d2d1effects_1.h>
#include <dwrite_2.h>
#include <wincodec.h>
#include <DirectXColors.h>
#include <DirectXMath.h>
#include <memory>
#include <agile.h>
#include <concrt.h>
#include "App.xaml.h"
#include <dxgi.h>
#include <dxgi1_2.h>
#include <d2d1_1.h>
#include <d3d11.h>
#include <d2d1.h>
#include <vector>
#include <debugapi.h>
#include <d3d11_1.h>
#include <dwrite.h>
#include "windows.ui.xaml.media.dxinterop.h"
const Windows::UI::Color CanvasBackgroundColor = Windows::UI::Colors::CornflowerBlue; |
leapframework/framework | base/lang/src/main/java/leap/lang/el/ElConstantField.java | <reponame>leapframework/framework<gh_stars>10-100
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leap.lang.el;
import java.util.Map;
import java.util.WeakHashMap;
import leap.lang.Args;
import leap.lang.reflect.ReflectField;
public class ElConstantField implements ElProperty {
private static final Object lock = new Object();
private static final Map<Class<?>, Map<String, ElConstantField>> constants =
new WeakHashMap<Class<?>, Map<String,ElConstantField>>();
public static ElConstantField of(ReflectField field) {
if(!field.isFinal()){
return null;
}
Class<?> cls = field.getDeclaringClass();
String name = field.getName();
synchronized (lock) {
Map<String, ElConstantField> cache = constants.get(cls);
if(null == cache){
cache = new WeakHashMap<String, ElConstantField>();
constants.put(cls, cache);
}
ElConstantField f = cache.get(name);
if(null == f){
f = new ElConstantField(field);
cache.put(name, f);
}
return f;
}
}
private final Object value;
private ElConstantField(ReflectField field) {
Args.assertTrue(field.isStatic() && field.isFinal(),"Must be static final field");
this.value = field.getValue(null);
}
@Override
public Object getValue(ElEvalContext context, Object instance) throws Throwable {
return value;
}
}
|
protegeproject/webprotege-owlapi-jackson | src/main/java/edu/stanford/protege/webprotege/jackson/OWLHasKeyAxiomImplMixin.java | <reponame>protegeproject/webprotege-owlapi-jackson
package edu.stanford.protege.webprotege.jackson;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.Nulls;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLPropertyExpression;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Set;
/**
* <NAME>
* Stanford Center for Biomedical Informatics Research
* 2021-09-17
*/
@JsonTypeName("HasKey")
public class OWLHasKeyAxiomImplMixin {
public OWLHasKeyAxiomImplMixin(@JsonProperty("classExpression") @Nonnull OWLClassExpression expression,
@JsonProperty("propertyExpressions") @Nonnull Set<? extends OWLPropertyExpression> propertyExpressions,
@JsonProperty(value = "annotations", defaultValue = "[]") @JsonSetter(nulls = Nulls.AS_EMPTY) @Nonnull Collection<? extends OWLAnnotation> annotations) {
}
}
|
Kelly9373/main | src/main/java/seedu/address/logic/parser/DeleteCommandParser.java | <filename>src/main/java/seedu/address/logic/parser/DeleteCommandParser.java
package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_PASSWORD;
import static seedu.address.logic.parser.CliSyntax.PREFIX_INDEX;
import static seedu.address.logic.parser.CliSyntax.PREFIX_PASSWORD;
import java.util.stream.Stream;
import seedu.address.logic.commands.DeleteCommand;
import seedu.address.logic.parser.exceptions.ParseException;
/**
* Parses input arguments and creates a new DeleteCommand object
*/
public class DeleteCommandParser implements Parser<DeleteCommand> {
private static String PASSWORD = "<PASSWORD>"; // Currently hard-coded. To add command that allows setting of password.
/**
* Parses the given {@code String} of arguments in the context of the DeleteCommand
* and returns an DeleteCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public DeleteCommand parse(String args) throws ParseException {
ArgumentMultimap argMultimap =
ArgumentTokenizer.tokenize(args, PREFIX_INDEX, PREFIX_PASSWORD);
if (!arePrefixesPresent(argMultimap, PREFIX_INDEX, PREFIX_PASSWORD)
|| !argMultimap.getPreamble().isEmpty()) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
if (!PASSWORD.equals(argMultimap.getValue(PREFIX_PASSWORD).get())) {
throw new ParseException(String.format(MESSAGE_INVALID_PASSWORD, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(ParserUtil.parseIndex(argMultimap.getValue(PREFIX_INDEX).get()));
}
/**
* Returns true if none of the prefixes contains empty {@code Optional} values in the given
* {@code ArgumentMultimap}.
*/
private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) {
return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent());
}
}
|
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism | Variant Programs/2-2/18/consignor/Limiter.java | <gh_stars>0
package consignor;
import spooler.AlterPlanner;
import spooler.GrrProgrammer;
import spooler.March;
import spooler.OberProgrammer;
import spooler.TreatedSynchronization;
import spooler.Workspace;
import spooler.PapsOrganizer;
import sim.ActMock;
import java.io.IOException;
import java.util.*;
public class Limiter {
private java.util.ArrayDeque<Workspace> performance;
private java.util.LinkedList<March> mechanism;
public static int DeploymentMinutes;
public Limiter() {
this.performance = new java.util.ArrayDeque<>();
spooler.Workspace scheduling = new spooler.PapsOrganizer();
spooler.Workspace oxime = new spooler.OberProgrammer();
spooler.Workspace operated = new spooler.TreatedSynchronization();
spooler.Workspace grr = new spooler.GrrProgrammer();
spooler.Workspace com = new spooler.AlterPlanner();
this.performance.addLast(scheduling);
this.performance.addLast(oxime);
this.performance.addLast(operated);
this.performance.addLast(com);
this.performance.addLast(grr);
}
public void solidifyingOperations(java.util.LinkedList<March> methods) {
this.mechanism = methods;
}
public void adjustDispatchedMonth(int assignThing) {
this.DeploymentMinutes = assignThing;
}
public void leadCoordinator() {
for (spooler.Workspace waffen : performance) {
waffen.kickoffSpooler();
while (waffen.goIsMoving()) {
if (waffen.makeUndertakenMarchDimensions() == mechanism.size()) {
waffen.occlusionDebugging();
} else {
java.util.LinkedList<March> fromOperations = new java.util.LinkedList<>();
for (spooler.March vig : mechanism) {
if (vig.produceComingNow() == waffen.findActualRetick() + 1) {
fromOperations.add(new spooler.March(vig));
}
}
java.util.Collections.sort(fromOperations);
while (!fromOperations.isEmpty()) {
waffen.outgrowthSucceeding(fromOperations.removeFirst());
}
waffen.markAfootDials(waffen.findActualRetick() + 1);
waffen.addTock();
}
}
}
this.printableRecap();
}
public void printableRecap() {
try {
ActMock.SupplyDocumentation.write("Summary\n");
System.out.println("Summary");
java.lang.String letterhead =
java.lang.String.format(
"%-9s%23s%26s", "Algorithm", "Average Waiting Time", "Average Turnaround Time");
ActMock.SupplyDocumentation.write(letterhead + "\n");
System.out.println(letterhead);
for (spooler.Workspace fh : performance) {
java.lang.String excerpts =
java.lang.String.format(
"%-9s%23.2f%26.2f",
fh.spoolerDistinguish(),
fh.generateFairPostponeYear(),
fh.generateFairRecoveryYear());
ActMock.SupplyDocumentation.write(excerpts + "\n");
System.out.println(excerpts);
}
ActMock.SupplyDocumentation.close();
} catch (java.io.IOException adult) {
System.out.println("Unable to write summary to file.");
}
}
}
|
auto-flow/autoflow | autoflow/workflow/components/regression/catboost.py | from copy import deepcopy
from typing import Dict
import numpy as np
from autoflow.data_container import DataFrameContainer
from autoflow.workflow.components.iter_algo import LgbmIterativeMixIn
from autoflow.workflow.components.regression_base import AutoFlowRegressionAlgorithm
__all__ = ["CatBoostRegressor"]
class CatBoostRegressor(AutoFlowRegressionAlgorithm):
class__ = "CatBoostRegressor"
module__ = "catboost"
boost_model = True
tree_model = True
support_early_stopping = True
def core_fit(self, estimator, X, y=None, X_valid=None, y_valid=None, X_test=None,
y_test=None, feature_groups=None, **kwargs):
categorical_features_indices = None # get_categorical_features_indices(X)
if (X_valid is not None) and (y_valid is not None):
eval_set = (X_valid, y_valid)
else:
eval_set = None
return self.component.fit(
X, y, cat_features=categorical_features_indices,
eval_set=eval_set, silent=True, **kwargs
)
def after_process_hyperparams(self, hyperparams) -> Dict:
hyperparams = deepcopy(hyperparams)
if "n_jobs" in hyperparams:
hyperparams["thread_count"] = hyperparams.pop("n_jobs")
return hyperparams
def before_fit_X(self, X: DataFrameContainer):
X = super(CatBoostRegressor, self).before_fit_X(X)
if X is None:
return None
return np.array(X)
|
TaraBryn/testable-projects-fcc | cypress/integration/test-testable-projects.spec.js | /* global cy */
const projectPaths = require('../fixtures/project-fix.json');
describe('Test all projects', () => {
const project = Object.entries(projectPaths);
for (const [projectName, projectPath] of project) {
it('project ' + projectName + ' should work correctly', () => {
cy.checkProjectTests(projectPath);
});
}
});
|
SINTEF/simapy | src/sima/riflex/blueprints/sncurve.py | #
# Generated with SNCurveBlueprint
from dmt.blueprint import Blueprint
from dmt.dimension import Dimension
from dmt.attribute import Attribute
from dmt.enum_attribute import EnumAttribute
from dmt.blueprint_attribute import BlueprintAttribute
from sima.sima.blueprints.namedobject import NamedObjectBlueprint
class SNCurveBlueprint(NamedObjectBlueprint):
""""""
def __init__(self, name="SNCurve", package_path="sima/riflex", description=""):
super().__init__(name,package_path,description)
self.attributes.append(Attribute("name","string","",default=""))
self.attributes.append(Attribute("description","string","",default=""))
self.attributes.append(Attribute("_id","string","",default=""))
self.attributes.append(BlueprintAttribute("scriptableValues","sima/sima/ScriptableValue","",True,Dimension("*")))
self.attributes.append(EnumAttribute("fatigueLimitIndicator","sima/riflex/FatigueLimitIndicator","Fatigue limit indicator"))
self.attributes.append(Attribute("fatigueLimit","number","Point where SN curve becomes horizontal. Stresses below this line will not contribute to fatigue damage.",default=0.0))
self.attributes.append(Attribute("referenceThickness","number","Reference thickness for thickness correction. A value of zero will give no thickness correction.",default=0.0))
self.attributes.append(Attribute("thicknessCorrectionExponent","number","Exponent for thickness correction",default=0.0))
self.attributes.append(Attribute("firstSlope","number","Slope of the SN curve - m",default=0.0))
self.attributes.append(Attribute("constant","number","Constant defining the SN curve. First segment or total curve - logC (for a SN-curve given in MPa)",default=0.0))
self.attributes.append(BlueprintAttribute("curveItems","sima/riflex/SNCurveItem","",True,Dimension("*"))) |
er3n/project4 | src/main/java/tr/com/heartsapiens/tedis/aop/DBLog.java | <filename>src/main/java/tr/com/heartsapiens/tedis/aop/DBLog.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tr.com.heartsapiens.tedis.aop;
/**
*
* @author ersin
*/
public class DBLog {
// kayıt bazında update, delete logu
}
|
crazypoo/PTools | PooToolsSource/PooTools_Example-Bridging-Header.h | //
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "NSString+Regulars.h"
#import "UIButton+ImageTitleSpacing.h"
#import <WZLBadge/UIView+WZLBadge.h>
#import <SDWebImage/UIButton+WebCache.h>
#import "DOGobalFileManager.h"
|
xjie06109334/SOP | sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/service/param/ServiceInstanceParam.java | <gh_stars>1-10
package com.gitee.sop.adminserver.api.service.param;
import com.gitee.easyopen.doc.annotation.ApiDocField;
import com.gitee.easyopen.util.CopyUtil;
import com.gitee.sop.adminserver.bean.ServiceInstance;
import lombok.Data;
import javax.validation.constraints.NotBlank;
/**
* @author tanghc
*/
@Data
public class ServiceInstanceParam {
@ApiDocField(description = "serviceId")
@NotBlank(message = "serviceId不能为空")
private String serviceId;
@ApiDocField(description = "instanceId")
@NotBlank(message = "instanceId不能为空")
private String instanceId;
/**
* ip
*/
@ApiDocField(description = "ip")
private String ip;
/**
* port
*/
@ApiDocField(description = "port")
private int port;
/**
* 服务状态,UP:已上线,OUT_OF_SERVICE:已下线
*/
@ApiDocField(description = "status")
private String status;
public ServiceInstance buildServiceInstance() {
ServiceInstance serviceInstance = new ServiceInstance();
CopyUtil.copyPropertiesIgnoreNull(this, serviceInstance);
return serviceInstance;
}
}
|
kkevn/LEDsign | app/src/main/java/com/kkevn/ledsign/ui/settings/SettingsFragment.java | /**
* SettingsFragment is the fragment containing the list of changeable application preferences.
*
* @author <NAME>
*/
package com.kkevn.ledsign.ui.settings;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import com.kkevn.ledsign.R;
public class SettingsFragment extends Fragment {
/**
* Returns a view that contains the layout of this fragment that includes a list of changeable
* preferences.
*
* @param {LayoutInflater} inflater: LayoutInflater object used to inflate the layout.
* @param {ViewGroup} container: Parent view that this fragment's UI should attach to.
* @param {Bundle} savedInstanceState: Bundle object containing activity's previous state.
*
* @return {View} View containing list of preferences.
*/
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate the fragment's layout
View root = inflater.inflate(R.layout.fragment_settings, container, false);
// place the FrameLayout containing the list of preferences into this fragment
getFragmentManager().beginTransaction().replace(R.id.fl_settings, new SettingsPreferenceFragment()).commit();
// return this populated view
return root;
}
} |
robatipoor/paste-file | src/main/java/org/robatipoor/pastefile/requests/AccessRequest.java | package org.robatipoor.pastefile.requests;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonAlias;
import org.robatipoor.pastefile.models.AccessType;
/**
* AccessRequest
*/
public class AccessRequest {
private String username;
@JsonAlias("access_type")
private AccessType accessType = AccessType.READ;
public AccessRequest() {
}
public AccessRequest(String username, AccessType accessType) {
this.username = username;
if (accessType != null) {
this.accessType = accessType;
}
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public AccessType getAccessType() {
return this.accessType;
}
public void setAccessType(AccessType accessType) {
this.accessType = accessType;
}
public AccessRequest username(String username) {
this.username = username;
return this;
}
public AccessRequest accessType(AccessType accessType) {
this.accessType = accessType;
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof AccessRequest)) {
return false;
}
AccessRequest accessRequest = (AccessRequest) o;
return Objects.equals(username, accessRequest.username) && Objects.equals(accessType, accessRequest.accessType);
}
@Override
public int hashCode() {
return Objects.hash(username, accessType);
}
@Override
public String toString() {
return "{" + " username='" + getUsername() + "'" + ", accessType='" + getAccessType() + "'" + "}";
}
} |
arsummers/python-data-structures-and-algorithms | challenges/count_triplets/test_count_triplets.py | import pytest
from count_triplets import count_triplets
def test_exists():
assert count_triplets
def test_two():
arr = [1, 2, 2, 4]
r = 2
expected = 2
actual = count_triplets(arr, r)
assert expected == actual
#2 triplets at [0, 1, 3], [0 2, 3]
def test_three():
arr = [1, 3, 9, 9, 27, 81]
r = 3
expected = 6
actual = count_triplets(arr, r)
assert expected == actual
def test_five():
arr = [1, 5, 5, 25, 125]
r = 5
expected = 4
actual = count_triplets(arr, r)
assert expected == actual |
zvr/Online-Self-Certification-Web-App | src/org/openchain/certification/UserSession.java | /**
* Copyright (c) 2016 Source Auditor 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 org.openchain.certification;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletConfig;
import org.apache.log4j.Logger;
import org.openchain.certification.dbdao.SurveyDatabase;
import org.openchain.certification.dbdao.SurveyDbDao;
import org.openchain.certification.dbdao.SurveyResponseDao;
import org.openchain.certification.dbdao.UserDb;
import org.openchain.certification.model.Answer;
import org.openchain.certification.model.Question;
import org.openchain.certification.model.QuestionException;
import org.openchain.certification.model.QuestionTypeException;
import org.openchain.certification.model.SubQuestion;
import org.openchain.certification.model.SubQuestionAnswers;
import org.openchain.certification.model.SurveyResponse;
import org.openchain.certification.model.SurveyResponseException;
import org.openchain.certification.model.User;
import org.openchain.certification.model.YesNoAnswer;
import org.openchain.certification.model.YesNoAnswerWithEvidence;
import org.openchain.certification.model.YesNoQuestion;
import org.openchain.certification.model.YesNoQuestion.YesNo;
import org.openchain.certification.model.YesNoQuestionWithEvidence;
import org.openchain.certification.utility.EmailUtilException;
import org.openchain.certification.utility.EmailUtility;
import org.openchain.certification.utility.PasswordUtil;
import com.sun.org.apache.xalan.internal.utils.Objects;
/**
* User information for the HTTP session
* @author <NAME>
*
*/
public class UserSession {
static final transient Logger logger = Logger.getLogger(UserSession.class);
private boolean loggedIn = false;
private String username;
private transient String password;
private String lastError;
private transient ServletConfig config;
private transient SurveyResponse surveyResponse = null;
private boolean admin = false;
private String address = null;
private String email = null;
private String name = null;
private String organization = null;
private boolean passwordReset = false;
private boolean namePermission = false;
private boolean emailPermission = false;
public UserSession(String username, String password, ServletConfig config) {
this(config);
this.username = username;
this.password = password;
this.loggedIn = false;
}
public UserSession(ServletConfig config) {
this.config = config;
this.loggedIn = false;
this.username = null;
this.password = <PASSWORD>;
this.admin = false;
this.address = null;
this.email = null;
this.name = null;
this.organization = null;
this.namePermission = false;
this.emailPermission = false;
}
static final int HOURS_FOR_VERIFICATION_EMAIL_EXPIRATION = 24;
/**
* @return a Date when the verification email is set to expire
*/
public static Date generateVerificationExpirationDate() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(cal.getTime().getTime()));
cal.add(Calendar.HOUR, HOURS_FOR_VERIFICATION_EMAIL_EXPIRATION);
return new Date(cal.getTime().getTime());
}
/**
* @param expiration Date of the expiration
* @return true if the expirate date has not passed
*/
public static boolean isValidExpirationDate(Date expiration) {
Date now = new Date();
return now.compareTo(expiration) < 0;
}
/**
* Complete the email verification process validating the verification information
* @param username Username
* @param uuid UUID generated for the verification email
* @param config
* @throws InvalidUserException
*/
public static void completeEmailVerification(String username, String uuid, ServletConfig config) throws InvalidUserException {
try {
User user = UserDb.getUserDb(config).getUser(username);
if (user == null) {
logger.error("NO user found for completing email verification - username "+username);
throw new InvalidUserException("User "+username+" not found. Could not complete registration.");
}
if (user.isVerified()) {
logger.warn("Attempting to verify an already verified user");
return;
}
if (!isValidExpirationDate(user.getVerificationExpirationDate())) {
logger.error("Expiration date for verification has passed for user "+username);
throw(new InvalidUserException("The verification has expired. Please resend the verification email. When logging in using your username and password, you will be prompted to resend the verification."));
}
if (!PasswordUtil.validate(uuid.toString(), user.getUuid())) {
logger.error("Verification tokens do not match for user "+username+". Supplied = "+uuid+", expected = "+user.getUuid());
throw(new InvalidUserException("Verification failed. Invalid registration ID. Please retry."));
}
UserDb.getUserDb(config).setVerified(username, true);
} catch (SQLException e) {
logger.error("Unexpected SQL exception completing the email verification",e);
throw(new InvalidUserException("Unexpected SQL exception completing verification. Please report this error to the OpenChain group"));
} catch (NoSuchAlgorithmException e) {
logger.error("Unexpected No Such Algorithm Exception completing the email verification",e);
throw(new InvalidUserException("Unexpected No Such Algorithm exception completing verification. Please report this error to the OpenChain group"));
} catch (InvalidKeySpecException e) {
logger.error("Unexpected Invalid Key Exception completing the email verification",e);
throw(new InvalidUserException("Unexpected Invalid Key exception completing verification. Please report this error to the OpenChain group"));
}
}
public void logout() {
this.loggedIn = false;
this.username = null;
this.password = <PASSWORD>;
this.admin = false;
this.address = null;
this.email = null;
this.name = null;
this.organization = null;
this.namePermission = false;
this.emailPermission = false;
}
/**
* @return true if the password is valid, but the user has not been registered
*/
public boolean isValidPasswordAndNotVerified() {
if (this.loggedIn) {
return false;
}
User user = null;
try {
user = UserDb.getUserDb(config).getUser(username);
} catch (SQLException e) {
this.lastError = "Unexpected SQL error. Please report this error to the OpenChain team: "+e.getMessage();
logger.error("SQL Exception logging in user",e);
return false;
}
if (user == null) {
this.lastError = "User "+username+" does not exist. Please review the username or sign up as a new user.";
return false;
}
if (user.isVerified()) {
return false;
}
try {
if (!PasswordUtil.validate(password, user.getPasswordToken())) {
this.lastError = "Passwords do not match. Please retry or reset your password";
return false;
}
} catch (NoSuchAlgorithmException e) {
logger.error("Unexpected No Such Algorithm error logging in user",e);
this.lastError = "Unexpected No Such Algorithm error. Please report this error to the OpenChain team";
return false;
} catch (InvalidKeySpecException e) {
this.lastError = "Unexpected Invalid Key Spec error. Please report this error to the OpenChain team";
logger.error("Unexpected Invalid Key Spec error logging in user",e);
return false;
}
return true;
}
/**
* Log the user in and populate the user data
* @return true if the login was successful
*/
public boolean login() {
this.loggedIn = false;
User user = null;
try {
user = UserDb.getUserDb(config).getUser(username);
} catch (SQLException e) {
this.lastError = "Unexpected SQL error. Please report this error to the OpenChain team: "+e.getMessage();
logger.error("SQL Exception logging in user",e);
return false;
}
if (user == null) {
this.lastError = "User "+username+" does not exist. Please review the username or sign up as a new user.";
return false;
}
if (!user.isVerified()) {
this.lastError = "This use has not been verified. Please check your email and click on the provided link to verify this user and email address";
return false;
}
if (user.isPasswordReset()) {
this.lastError = "A password reset is in process. Login is not allowed until the password has been reset.";
return false;
}
try {
if (!PasswordUtil.validate(password, user.getPasswordToken())) {
this.lastError = "Passwords do not match. Please retry or reset your password";
return false;
}
} catch (NoSuchAlgorithmException e) {
logger.error("Unexpected No Such Algorithm error logging in user",e);
this.lastError = "Unexpected No Such Algorithm error. Please report this error to the OpenChain team";
return false;
} catch (InvalidKeySpecException e) {
this.lastError = "Unexpected Invalid Key Spec error. Please report this error to the OpenChain team";
logger.error("Unexpected Invalid Key Spec error logging in user",e);
return false;
}
this.loggedIn = true;
this.admin = user.isAdmin();
this.address = user.getAddress();
this.email = user.getEmail();
this.name = user.getName();
this.organization = user.getOrganization();
this.namePermission = user.hasNamePermission();
this.emailPermission = user.hasEmailPermission();
return true;
}
public String getLastError() {
return this.lastError;
}
/**
* Sign up a new user
* @param Name of the user (common name, not the username)
* @param address Address of the user
* @param organization User organization
* @param email Email - must already be validated
* @param responseServletUrl The URL of the servlet to handle the email validation link
* @param namePermission If true, user has given permission to publish their name on the website
* @param emailPermission If true, user has given permission to publish their email address on the website
* @return
*/
public boolean signUp(String name, String address, String organization,
String email, String responseServletUrl, boolean namePermission,
boolean emailPermission) {
User user = null;
try {
user = UserDb.getUserDb(config).getUser(username);
if (user != null) {
this.lastError = "User "+username+" already exist. Please select a different unique username.";
return false;
}
user = new User();
user.setAddress(address);
user.setAdmin(false);
user.setEmail(email);
user.setName(name);
user.setOrganization(organization);
user.setPasswordReset(false);
user.setPasswordToken(PasswordUtil.getToken(this.password));
user.setUsername(this.username);
user.setVerified(false);
user.setNamePermission(namePermission);
user.setEmailPermission(emailPermission);
user.setVerificationExpirationDate(generateVerificationExpirationDate());
UUID uuid = UUID.randomUUID();
String hashedUuid = PasswordUtil.getToken(uuid.toString());
user.setUuid(hashedUuid);
UserDb.getUserDb(config).addUser(user);
EmailUtility.emailVerification(name, email, uuid, username, responseServletUrl, config);
return true;
} catch (SQLException e) {
this.lastError = "Unexpected SQL error. Please report this error to the OpenChain team: "+e.getMessage();
logger.error("SQL Exception signing up user",e);
return false;
} catch (NoSuchAlgorithmException e) {
logger.error("Unexpected No Such Algorithm error signing up user",e);
this.lastError = "Unexpected No Such Algorithm error. Please report this error to the OpenChain team";
return false;
} catch (InvalidKeySpecException e) {
logger.error("Unexpected Invalid Key Spec error signing up user",e);
this.lastError = "Unexpected Invalid Key Spec error. Please report this error to the OpenChain team";
return false;
} catch (EmailUtilException e) {
logger.error("Error emailing invitation",e);
this.lastError = "Unable to email the invitiation: "+e.getMessage();
return false;
} catch (InvalidUserException e) {
logger.error("Invalid user specified in add user request",e);
this.lastError = "Error adding user: "+e.getMessage();
return false;
}
}
public String getUsername() {
return this.username;
}
public boolean isLoggedIn() {
return this.loggedIn;
}
public SurveyResponse getSurveyResponse() throws SQLException, QuestionException, SurveyResponseException {
checkLoggedIn();
if (this.surveyResponse == null) {
_getSurveyResponse();
}
return this.surveyResponse;
}
private void _getSurveyResponse() throws SQLException, QuestionException, SurveyResponseException {
Connection con = SurveyDatabase.createConnection(config);
try {
SurveyResponseDao dao = new SurveyResponseDao(con);
this.surveyResponse = dao.getSurveyResponse(this.username, null);
if (this.surveyResponse == null) {
// Create one
this.surveyResponse = new SurveyResponse();
User user = UserDb.getUserDb(config).getUser(username);
surveyResponse.setResponder(user);
surveyResponse.setResponses(new HashMap<String, Answer>());
surveyResponse.setSpecVersion(dao.getLatestSpecVersion());
surveyResponse.setSurvey(SurveyDbDao.getSurvey(con, surveyResponse.getSpecVersion()));
con.commit();
dao.addSurveyResponse(surveyResponse);
}
} finally {
con.close();
}
}
private void checkLoggedIn() throws SurveyResponseException {
if (!this.isLoggedIn()) {
throw new SurveyResponseException("User is not logged in");
}
}
/**
* Update the answers from a list of response answers. This does NOT remove
* any already answered questions
* @param responses
* @throws SQLException
* @throws QuestionException
* @throws SurveyResponseException
*/
public void updateAnswers(List<ResponseAnswer> responses) throws SQLException, QuestionException, SurveyResponseException {
checkLoggedIn();
if (this.surveyResponse == null) {
_getSurveyResponse();
}
Map<String, Answer> currentResponses = this.surveyResponse.getResponses();
// Keep track of the subquestions found so that we can update the answers
for (ResponseAnswer response:responses) {
if (!response.isChecked()) {
continue;
}
Question question = this.surveyResponse.getSurvey().getQuestion(response.getQuestionNumber());
if (question != null && response.getValue() != null && !response.getValue().trim().isEmpty()) {
YesNo ynAnswer = null;
if (question instanceof YesNoQuestion) {
if (response.getValue() == null) {
logger.error("No answer provided for a yes/no question");
throw(new QuestionTypeException("No value specified for a yes/no question"));
}
if (response.getValue().toUpperCase().trim().equals("YES")) {
ynAnswer = YesNo.Yes;
} else if (response.getValue().toUpperCase().trim().equals("NO")) {
ynAnswer = YesNo.No;
} else if (response.getValue().toUpperCase().trim().equals("NA")) {
ynAnswer = YesNo.NotApplicable;
} else {
logger.error("Invalid yes no value: "+response.getValue());
throw(new QuestionTypeException("Invalid yes/no value: "+response.getValue()));
}
}
Answer answer;
if (question instanceof YesNoQuestionWithEvidence) {
answer = new YesNoAnswerWithEvidence(ynAnswer, response.getEvidence());
} else if (question instanceof YesNoQuestion) {
answer = new YesNoAnswer(ynAnswer);
} else if (question instanceof SubQuestion) {
answer = new SubQuestionAnswers();
} else {
logger.error("Invalid answer type for question "+response.getQuestionNumber());
throw(new QuestionTypeException("Invalid answer type for question "+response.getQuestionNumber()));
}
currentResponses.put(response.getQuestionNumber(), answer);
if (question.getSubQuestionNumber() != null) {
SubQuestionAnswers subQuestionAnswer = (SubQuestionAnswers)currentResponses.get(question.getSubQuestionNumber());
if (subQuestionAnswer == null) {
subQuestionAnswer = new SubQuestionAnswers();
currentResponses.put(question.getSubQuestionNumber(), subQuestionAnswer);
}
subQuestionAnswer.addSubAnswer(question.getNumber(), answer);
}
} else {
logger.warn("Skipping a response answer "+response.getQuestionNumber());
}
}
Connection con = SurveyDatabase.createConnection(config);
try {
SurveyResponseDao dao = new SurveyResponseDao(con);
dao.updateSurveyResponseAnswers(this.surveyResponse);
} finally {
con.close();
}
}
/**
* Final submission of questions
* @return true if successful; on fail, lasterror will contain the error message
* @throws SQLException
* @throws QuestionTypeException
* @throws SurveyResponseException
* @throws EmailUtilException
*/
public boolean finalSubmission() throws SQLException, SurveyResponseException, QuestionException, EmailUtilException {
checkLoggedIn();
Connection con = SurveyDatabase.createConnection(config);
_getSurveyResponse();
List<Question> invalidQuestions = this.surveyResponse.invalidAnswers();
if (invalidQuestions.size() > 0) {
StringBuilder er = new StringBuilder("Can not submit - the following question(s) either has missing answers or invalid answers: ");
er.append(invalidQuestions.get(0).getNumber());
for (int i = 1; i < invalidQuestions.size(); i++) {
er.append(", ");
er.append(invalidQuestions.get(i).getNumber());
}
this.lastError = er.toString();
return false;
}
this.surveyResponse.setSubmitted(true);
this.surveyResponse.setApproved(true);
this.surveyResponse.setRejected(false);
try {
SurveyResponseDao dao = new SurveyResponseDao(con);
dao.setSubmitted(username, this.surveyResponse.getSpecVersion(), true);
//NOTE: We automatically approve per openchain call on Monday Dec. 5
dao.setApproved(username, this.surveyResponse.getSpecVersion(), true);
dao.setRejected(username, this.surveyResponse.getSpecVersion(), false);
} finally {
con.close();
}
EmailUtility.emailCompleteSubmission(this.username,
this.surveyResponse.getResponder().getName(),
this.surveyResponse.getResponder().getEmail(),
this.surveyResponse.getSpecVersion(), config);
return true;
}
public boolean isAdmin() {
return this.admin;
}
/**
* Resend a verification email for the user specified
* @param username
* @param password
* @param responseServletUrl
* @return
*/
public boolean resendVerification(String username, String password, String responseServletUrl) {
this.username = username;
if (this.loggedIn) {
return false;
}
User user = null;
try {
user = UserDb.getUserDb(config).getUser(username);
} catch (SQLException e) {
this.lastError = "Unexpected SQL error. Please report this error to the OpenChain team: "+e.getMessage();
logger.error("SQL Exception logging in user",e);
return false;
}
if (user == null) {
this.lastError = "User "+username+" does not exist. Please review the username or sign up as a new user.";
return false;
}
if (user.isVerified()) {
return false;
}
try {
if (!PasswordUtil.validate(password, user.getPasswordToken())) {
this.lastError = "Passwords do not match. Please retry or reset your password";
return false;
}
} catch (NoSuchAlgorithmException e) {
logger.error("Unexpected No Such Algorithm error logging in user",e);
this.lastError = "Unexpected No Such Algorithm error. Please report this error to the OpenChain team";
return false;
} catch (InvalidKeySpecException e) {
this.lastError = "Unexpected Invalid Key Spec error. Please report this error to the OpenChain team";
logger.error("Unexpected Invalid Key Spec error logging in user",e);
return false;
}
UUID uuid = UUID.randomUUID();
String hashedUuid;
try {
hashedUuid = PasswordUtil.getToken(uuid.toString());
} catch (NoSuchAlgorithmException e) {
logger.error("Unexpected No Such Algorithm error logging in user",e);
this.lastError = "Unexpected No Such Algorithm error. Please report this error to the OpenChain team";
return false;
} catch (InvalidKeySpecException e) {
this.lastError = "Unexpected Invalid Key Spec error. Please report this error to the OpenChain team";
logger.error("Unexpected Invalid Key Spec error logging in user",e);
return false;
}
user.setUuid(hashedUuid);
user.setVerificationExpirationDate(generateVerificationExpirationDate());
try {
UserDb.getUserDb(config).updateUser(user);
} catch (SQLException e) {
this.lastError = "Unexpected SQL error. Please report this error to the OpenChain team: "+e.getMessage();
logger.error("SQL Exception updating user during re-verification",e);
return false;
} catch (InvalidUserException e) {
this.lastError = "Unexpected invalid user error. Please report this error to the OpenChain team: "+e.getMessage();
logger.error("Invalid user error in resending verification",e);
}
try {
EmailUtility.emailVerification(user.getName(), user.getEmail(),
uuid, username, responseServletUrl, config);
} catch (EmailUtilException e) {
logger.error("Error emailing invitation",e);
this.lastError = "Unable to re-email the invitiation: "+e.getMessage();
return false;
}
return true;
}
/**
* Delete all answers and start a new survey
* @throws SurveyResponseException
* @throws QuestionException
*/
public void resetAnswers() throws SurveyResponseException, QuestionException {
Connection con;
try {
con = SurveyDatabase.createConnection(config);
} catch (SQLException e) {
logger.error("Unable to get connection for resetting answers",e);
throw new SurveyResponseException("Unable to get connection for resetting answers. Please report this error to the OpenChain team",e);
}
try {
SurveyResponseDao dao = new SurveyResponseDao(con);
User saveUser = surveyResponse.getResponder();
dao.deleteSurveyResponseAnswers(this.surveyResponse);
this.surveyResponse = new SurveyResponse();
surveyResponse.setResponder(saveUser);
surveyResponse.setResponses(new HashMap<String, Answer>());
surveyResponse.setSpecVersion(dao.getLatestSpecVersion());
surveyResponse.setSurvey(SurveyDbDao.getSurvey(con, surveyResponse.getSpecVersion()));
con.commit();
dao.addSurveyResponse(surveyResponse);
} catch (SQLException e) {
logger.error("SQL Exception resetting answers",e);
throw new SurveyResponseException("Unexpectes SQL error resetting answers. Please report this error to the OpenChain team",e);
} finally {
try {
con.close();
} catch (SQLException e) {
logger.warn("Error closing connection",e);
}
}
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the organization
*/
public String getOrganization() {
return organization;
}
/**
* @return the namePermission
*/
public boolean hasNamePermission() {
return namePermission;
}
/**
* @return the emailPermission
*/
public boolean hasEmailPermission() {
return emailPermission;
}
/**
* @return the hoursForVerificationEmailExpiration
*/
public static int getHoursForVerificationEmailExpiration() {
return HOURS_FOR_VERIFICATION_EMAIL_EXPIRATION;
}
/**
* Update the User information
* @param newName
* @param newEmail
* @param newOrganization
* @param newAddress
* @param newPassword
* @param newNamePermission
* @param newEmailPermission
* @throws InvalidUserException
* @throws SQLException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws EmailUtilException
*/
public void updateUser(String newName, String newEmail, String newOrganization,
String newAddress, String newPassword, boolean newNamePermission,
boolean newEmailPermission) throws InvalidUserException, SQLException, NoSuchAlgorithmException, InvalidKeySpecException, EmailUtilException {
if (!loggedIn) {
this.lastError = "Can not update a user which is not logged in.";
throw new InvalidUserException(this.lastError);
}
User user = null;
try {
user = UserDb.getUserDb(config).getUser(username);
if (user == null) {
this.lastError = "User "+username+" no longer exist. Please report this error to the open chain team.";
throw new InvalidUserException(this.lastError);
}
boolean needUpdate = false;
if (!Objects.equals(newName, this.name)) {
user.setName(newName);
this.name = newName;
needUpdate = true;
}
if (!Objects.equals(newEmail, this.email)) {
this.email = newEmail;
user.setEmail(newEmail);
needUpdate = true;
}
if (!Objects.equals(newOrganization, this.organization)) {
this.organization = newOrganization;
user.setOrganization(newOrganization);
needUpdate = true;
}
if (newPassword != null && !Objects.equals(newPassword, this.password)) {
this.password = <PASSWORD>;
user.setPasswordToken(PasswordUtil.getToken(newPassword));
needUpdate = true;
}
if (!Objects.equals(newAddress, this.address)) {
this.address = newAddress;
user.setAddress(newAddress);
needUpdate = true;
}
if (user.hasEmailPermission() != newEmailPermission) {
this.emailPermission = newEmailPermission;
user.setEmailPermission(newEmailPermission);
needUpdate = true;
}
if (user.hasNamePermission() != newNamePermission) {
this.namePermission = newNamePermission;
user.setNamePermission(newNamePermission);
needUpdate = true;
}
if (needUpdate) {
UserDb.getUserDb(config).updateUser(user);
this.password = <PASSWORD>;
this.address = newAddress;
this.email = newEmail;
this.name = newName;
this.organization = newOrganization;
try {
EmailUtility.emailProfileUpdate(username, this.email, config);
}catch (EmailUtilException e) {
logger.warn("Error emailing profile update notice",e);
this.lastError = "Unable to email the for the profile update: "+e.getMessage();
}
}
} catch (SQLException e) {
this.lastError = "Unexpected SQL error. Please report this error to the OpenChain team: "+e.getMessage();
logger.error("SQL Exception signing up user",e);
throw e;
} catch (NoSuchAlgorithmException e) {
logger.error("Unexpected No Such Algorithm error signing up user",e);
this.lastError = "Unexpected No Such Algorithm error. Please report this error to the OpenChain team";
throw e;
} catch (InvalidKeySpecException e) {
logger.error("Unexpected Invalid Key Spec error signing up user",e);
this.lastError = "Unexpected Invalid Key Spec error. Please report this error to the OpenChain team";
throw e;
}
}
/**
* Set the password reset to in progress. Verifies the UUID, reset in progress and expiration date.
* @param uuid
* @return
* @throws SQLException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public boolean verifyPasswordReset(String uuid) throws SQLException, NoSuchAlgorithmException, InvalidKeySpecException {
User user = null;
try {
user = UserDb.getUserDb(config).getUser(username);
if (!user.isPasswordReset()) {
this.lastError = "Attempting to reset a password when a reset password email was not sent.";
return false;
}
if (!PasswordUtil.validate(uuid.toString(), user.getUuid())) {
logger.error("Password reset tokens do not match for user "+username+". Supplied = "+uuid+", expected = "+user.getUuid());
this.lastError = "Email password reset tokens does not match. Please re-send the password reset.";
return false;
}
if (!isValidExpirationDate(user.getVerificationExpirationDate())) {
logger.error("Expiration date for verification has passed for user "+username);
this.lastError = "The verification has expired. Please resend the verification email. When logging in using your username and password, you will be prompted to resend the verification.";
return false;
}
this.passwordReset = true;
return true;
} catch (SQLException e) {
logger.error("SQL Exception setting password reset",e);
this.lastError = "Unexpected SQL error. Please report this error to the OpenChain team: "+e.getMessage();
throw(e);
} catch (NoSuchAlgorithmException e) {
logger.error("Unexpected No Such Algorithm error signing up user",e);
this.lastError = "Unexpected No Such Algorithm error. Please report this error to the OpenChain team";
throw e;
} catch (InvalidKeySpecException e) {
logger.error("Unexpected Invalid Key Spec error signing up user",e);
this.lastError = "Unexpected Invalid Key Spec error. Please report this error to the OpenChain team";
throw e;
}
}
public boolean isPasswordReset() {
return this.passwordReset;
}
public boolean setPassword(String username, String password) {
if (!Objects.equals(username, this.username)) {
this.lastError = "Username for password reset does not match the username in the email reset.";
return false;
}
User user = null;
try {
user = UserDb.getUserDb(config).getUser(username);
if (!user.isPasswordReset()) {
this.lastError = "Attempting to reset a password when a reset password email was not sent.";
return false;
}
user.setPasswordReset(false);
user.setPasswordToken(PasswordUtil.getToken(password));
UserDb.getUserDb(config).updateUser(user);
this.passwordReset = false;
this.password = password;
return true;
} catch (SQLException e) {
logger.error("SQL Exception setting password reset",e);
this.lastError = "Unexpected SQL error. Please report this error to the OpenChain team: "+e.getMessage();
return false;
} catch (NoSuchAlgorithmException e) {
logger.error("Unexpected No Such Algorithm error signing up user",e);
this.lastError = "Unexpected No Such Algorithm error. Please report this error to the OpenChain team";
return false;
} catch (InvalidKeySpecException e) {
logger.error("Unexpected Invalid Key Spec error signing up user",e);
this.lastError = "Unexpected Invalid Key Spec error. Please report this error to the OpenChain team";
return false;
} catch (InvalidUserException e) {
logger.error("Unexpected Invalid User error signing up user",e);
this.lastError = "Unexpected Invalid User error. Please report this error to the OpenChain team";
return false;
}
}
/**
* unsubmits responses
* @throws SurveyResponseException
* @throws QuestionException
* @throws SQLException
* @throws EmailUtilException
*/
public void unsubmit() throws SQLException, QuestionException, SurveyResponseException, EmailUtilException {
checkLoggedIn();
Connection con = SurveyDatabase.createConnection(config);
_getSurveyResponse();
if (!this.surveyResponse.isSubmitted()) {
logger.warn("Attempting to unsubmit an unsubmitted response for user "+this.username);
return;
}
this.surveyResponse.setApproved(false);
this.surveyResponse.setRejected(false);
this.surveyResponse.setSubmitted(false);
try {
SurveyResponseDao dao = new SurveyResponseDao(con);
dao.setSubmitted(username, this.surveyResponse.getSpecVersion(), false);
dao.setApproved(username, this.surveyResponse.getSpecVersion(), false);
dao.setRejected(username, this.surveyResponse.getSpecVersion(), false);
} finally {
con.close();
}
EmailUtility.emailUnsubmit(this.username,
this.surveyResponse.getResponder().getName(),
this.surveyResponse.getResponder().getEmail(),
this.surveyResponse.getSpecVersion(), config);
}
}
|
raychorn/svn_Cordova_Code_Samples | mysoundboard/www/js/controllers.js | angular.module('mysoundboard.controllers', [])
.controller('HomeCtrl', function($scope, Sounds, $ionicPlatform) {
var getSounds = function() {
console.log('getSounds called');
Sounds.get().then(function(sounds) {
console.dir(sounds);
$scope.sounds = sounds;
});
}
$scope.$on('$ionicView.enter', function(){
console.log('enter');
getSounds();
});
$scope.play = function(x) {
console.log('play', x);
Sounds.play(x);
}
$scope.delete = function(x) {
console.log('delete', x);
Sounds.get().then(function(sounds) {
var toDie = sounds[x];
window.resolveLocalFileSystemURL(toDie.file, function(fe) {
fe.remove(function() {
Sounds.delete(x).then(function() {
getSounds();
});
}, function(err) {
console.log("err cleaning up file", err);
});
});
});
}
$scope.cordova = {loaded:false};
$ionicPlatform.ready(function() {
$scope.$apply(function() {
$scope.cordova.loaded = true;
});
});
})
.controller('RecordCtrl', function($scope, Sounds, $state, $ionicHistory) {
$scope.sound = {name:""};
$scope.saveSound = function() {
console.log('trying to save '+$scope.sound.name);
//Simple error checking
if($scope.sound.name === "") {
navigator.notification.alert("Name this sound first.", null, "Error");
return;
}
if(!$scope.sound.file) {
navigator.notification.alert("Record a sound first.", null, "Error");
return;
}
/*
begin the copy to persist location
first, this path below is persistent on both ios and and
*/
var loc = cordova.file.dataDirectory;
/*
but now we have an issue with file name. so let's use the existing extension,
but a unique filename based on seconds since epoch
*/
var extension = $scope.sound.file.split(".").pop();
var filepart = Date.now();
var filename = filepart + "." + extension;
console.log("new filename is "+filename);
window.resolveLocalFileSystemURL(loc, function(d) {
window.resolveLocalFileSystemURL($scope.sound.file, function(fe) {
fe.copyTo(d, filename, function(e) {
console.log('success inc opy');
console.dir(e);
$scope.sound.file = e.nativeURL;
$scope.sound.path = e.fullPath;
Sounds.save($scope.sound).then(function() {
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go("home");
});
}, function(e) {
console.log('error in coipy');console.dir(e);
});
}, function(e) {
console.log("error in inner bullcrap");
console.dir(e);
});
}, function(e) {
console.log('error in fs');console.dir(e);
});
}
var captureError = function(e) {
console.log('captureError' ,e);
}
var captureSuccess = function(e) {
console.log('captureSuccess');console.dir(e);
$scope.sound.file = e[0].localURL;
$scope.sound.filePath = e[0].fullPath;
}
$scope.record = function() {
navigator.device.capture.captureAudio(
captureSuccess,captureError,{duration:10});
}
$scope.play = function() {
if(!$scope.sound.file) {
navigator.notification.alert("Record a sound first.", null, "Error");
return;
}
var media = new Media($scope.sound.file, function(e) {
media.release();
}, function(err) {
console.log("media err", err);
});
media.play();
}
});
|
fmedisov/homefinance | web/src/main/java/ru/medisov/home_finance/web/view/CurrencyView.java | <reponame>fmedisov/homefinance<gh_stars>0
package ru.medisov.home_finance.web.view;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class CurrencyView {
private Long id;
private String name;
private String code;
private String symbol;
} |
anuartapia/genetic_algorithms | implementacion/src/test/PopulationTest.java | import gaframework.*;
public class PopulationTest {
public static void main(String[] args) {
}
}
|
danadi7/tp | src/main/java/seedu/schedar/logic/commands/RetrieveCommand.java | package seedu.schedar.logic.commands;
import static java.util.Objects.requireNonNull;
import seedu.schedar.logic.CommandHistory;
import seedu.schedar.logic.commands.exceptions.CommandException;
import seedu.schedar.model.Model;
import seedu.schedar.model.task.Task;
/**
* Retrieves the recently deleted Task.
* Only one task which is the most recently deleted can be retrieved.
*/
public class RetrieveCommand extends Command {
public static final String COMMAND_WORD = "retrieve";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Retrieves the recent deleted task to the task manager. ";
public static final String MESSAGE_SUCCESS = "The most recent deleted task has been added to the task list.";
public static final String MESSAGE_CANNOT_RETRIEVE = "There is no recent deleted task!";
public static final String MESSAGE_DUPLICATE_TASK = "Retrieve would result in duplicate tasks!";
/**
* Creates a RetrieveCommand to retrieve the most recently deleted task.
*/
public RetrieveCommand() {
}
@Override
public CommandResult execute(Model model, CommandHistory history) throws CommandException {
requireNonNull(model);
if (model.getRecentDeletedTask() == null) {
throw new CommandException(MESSAGE_CANNOT_RETRIEVE);
}
Task recentlyDeleted = model.getRecentDeletedTask();
if (model.hasTask(recentlyDeleted)) {
throw new CommandException(MESSAGE_DUPLICATE_TASK);
}
model.retrieveRecentDeletedTask();
model.commitTaskManager();
return new CommandResult(MESSAGE_SUCCESS + recentlyDeleted);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof RetrieveCommand); // instanceof handles nulls
}
}
|
ksn-nsk/product-catalog-import-tool | productImport/productImportHandler.go | package productImport
import (
"fmt"
"go.uber.org/dig"
"log"
"os"
"regexp"
"ts/adapters"
"ts/config"
"ts/productImport/mapping"
"ts/productImport/ontologyRead"
"ts/productImport/ontologyRead/models"
"ts/productImport/ontologyValidator"
"ts/productImport/reports"
"ts/productImport/tradeshiftImportHandler"
"ts/utils"
)
type ProductImportHandler struct {
config *config.Config
mapHandler mapping.MappingHandlerInterface
rulesHandler *ontologyRead.RulesHandler
handler adapters.HandlerInterface
validator ontologyValidator.ValidatorInterface
reports *reports.ReportsHandler
fileManager *adapters.FileManager
importHandler *tradeshiftImportHandler.TradeshiftHandler
}
type Deps struct {
dig.In
Config *config.Config
MapHandler mapping.MappingHandlerInterface
RulesHandler *ontologyRead.RulesHandler
Handler adapters.HandlerInterface
Validator ontologyValidator.ValidatorInterface
Reports *reports.ReportsHandler
FileManager *adapters.FileManager
ImportHandler *tradeshiftImportHandler.TradeshiftHandler
}
func NewProductImportHandler(deps Deps) *ProductImportHandler {
return &ProductImportHandler{
config: deps.Config,
mapHandler: deps.MapHandler,
rulesHandler: deps.RulesHandler,
handler: deps.Handler,
validator: deps.Validator,
reports: deps.Reports,
fileManager: deps.FileManager,
importHandler: deps.ImportHandler,
}
}
func (ph *ProductImportHandler) Run() {
//ontology
var rulesConfig *models.OntologyConfig
rulesConfig, err := ph.rulesHandler.InitRulesConfig()
if err != nil {
log.Fatalf("ontology was not specified: %v", err)
}
// mappings
columnMap := ph.mapHandler.Init(ph.config.ProductCatalog.MappingPath)
// feed
err = ph.processProducts(columnMap, rulesConfig)
if err != nil {
log.Println(err)
}
}
func (ph *ProductImportHandler) processProducts(columnMap map[string]string, rulesConfig *models.OntologyConfig) error {
// if something in progress
var processedSource []string
inProgress := adapters.GetFiles(ph.config.ProductCatalog.InProgressPath)
sources := adapters.GetFiles(ph.config.ProductCatalog.SourcePath)
// identify fitting report
if len(inProgress) > 0 {
for _, processingFile := range inProgress {
reportFile := findReport(processingFile, utils.SliceDiff(sources, processedSource))
if reportFile != "" {
processedSource = append(processedSource, reportFile)
ph.processFeed(
ph.config.ProductCatalog.InProgressPath+"/"+processingFile, //feed
ph.config.ProductCatalog.SourcePath+reportFile, //report
columnMap,
rulesConfig,
false,
)
} else {
log.Printf("You have the failed feed in progress '%v'. "+
"Please check the failure report in '%v', "+
"fill it with the data and appload to the '%v' folder.",
ph.config.ProductCatalog.InProgressPath+"/"+processingFile,
ph.config.ProductCatalog.FailResultPath,
ph.config.ProductCatalog.SourcePath)
}
}
} else if len(sources) == 0 {
return fmt.Errorf("SOURCE IS NOT FOUND")
}
for _, source := range sources {
if inArr, _ := utils.InArray(source, processedSource); !inArr {
ph.processFeed(
ph.config.ProductCatalog.SourcePath+source,
"",
columnMap,
rulesConfig,
true,
)
}
}
return nil
}
func (ph *ProductImportHandler) processFeed(
sourceFeedPath string,
validationReportPath string,
columnMap map[string]string,
ruleConfig *models.OntologyConfig,
isInitial bool,
) {
log.Println("_________________________________")
log.Printf("PROCESSING SOURCE: %v", sourceFeedPath)
var er error
if validationReportPath != "" {
log.Printf("EDITED REPORT: %v", validationReportPath)
if validationReportPath, er = adapters.MoveToPath(validationReportPath, ph.config.ProductCatalog.InProgressPath); er != nil {
log.Printf("ERROR COPYING THE '%v' FILE to the '%v' folder", validationReportPath, ph.config.ProductCatalog.InProgressPath)
}
}
if isInitial {
if sourceFeedPath, er = adapters.MoveToPath(sourceFeedPath, ph.config.ProductCatalog.InProgressPath); er != nil {
log.Printf("ERROR COPYING THE '%v' FILE to the '%v' folder", sourceFeedPath, ph.config.ProductCatalog.InProgressPath)
}
}
labels := ph.reports.Header
reportData := make([]*reports.Report, 0)
if validationReportPath != "" {
if _, err := os.Stat(validationReportPath); !os.IsNotExist(err) {
ph.handler.Init(ph.fileManager.GetFileType(validationReportPath))
reportDataSource := ph.handler.Parse(validationReportPath)
for _, line := range reportDataSource {
r := &reports.Report{
ProductId: fmt.Sprintf("%v", line[labels.ProductId]),
Name: fmt.Sprintf("%v", line[labels.Name]),
Category: fmt.Sprintf("%v", line[labels.Category]),
CategoryName: fmt.Sprintf("%v", line[labels.CategoryName]),
AttrName: fmt.Sprintf("%v", line[labels.AttrName]),
AttrValue: fmt.Sprintf("%v", line[labels.AttrValue]),
UoM: fmt.Sprintf("%v", line[labels.UoM]),
Errors: nil,
Description: fmt.Sprintf("%v", line[labels.Description]),
DataType: fmt.Sprintf("%v", line[labels.DataType]),
IsMandatory: fmt.Sprintf("%v", line[labels.IsMandatory]),
CodedVal: fmt.Sprintf("%v", line[labels.CodedVal]),
}
reportData = append(reportData, r)
}
}
}
// source
ph.handler.Init(ph.fileManager.GetFileType(sourceFeedPath))
parsedData := ph.handler.Parse(sourceFeedPath)
// validation feed
feed, hasErrors := ph.validator.Validate(struct {
Mapping map[string]string
Rules *models.OntologyConfig
Data []map[string]interface{}
Report []*reports.Report
}{
Mapping: columnMap,
Rules: ruleConfig,
Data: parsedData,
Report: reportData,
})
if !hasErrors {
log.Printf("SUCCESS: FILE IS VALID. Please check the '%s' folder", ph.config.ProductCatalog.SentPath)
if _, er = adapters.MoveToPath(sourceFeedPath, ph.config.ProductCatalog.SentPath); er != nil {
log.Printf("ERROR COPYING THE SOURCE FILE %v to the '%v' folder", sourceFeedPath, ph.config.ProductCatalog.SentPath)
}
if validationReportPath != "" {
if _, er = adapters.MoveToPath(validationReportPath, ph.config.ProductCatalog.SentPath); er != nil {
log.Printf("ERROR COPYING THE REPORT FILE %v to the '%v' folder", validationReportPath, ph.config.ProductCatalog.SentPath)
}
}
} else {
log.Printf("FAILURE: check the failure report in '%v', fill it with the data and upload to the '%v' folder.",
ph.config.ProductCatalog.ReportPath,
ph.config.ProductCatalog.SourcePath)
if validationReportPath != "" {
e := os.Remove(validationReportPath)
if e != nil {
log.Println(e)
}
}
}
cleanUpFailures(sourceFeedPath, ph.config.ProductCatalog.FailResultPath)
validationReportPath = ph.reports.WriteReport(sourceFeedPath, hasErrors, feed, parsedData, columnMap)
if !hasErrors {
log.Println("IMPORT FEED TO TRADESHIFT WAS STARTED")
er := ph.importHandler.ImportFeedToTradeshift(sourceFeedPath, validationReportPath)
if er != nil {
log.Printf("FAILED TO IMPORT VALID FEED TO TRADESHIFT. Reason: %v", er)
}
}
}
func findReport(inProgressFile string, sources []string) string {
report := ""
pattern := adapters.GetFileName(inProgressFile)
for _, source := range sources {
regexp, _ := regexp.Compile(`(-failures)`)
match := regexp.FindStringIndex(source)
if len(match) == 2 {
name := string(source[0:match[0]])
if name == pattern {
return source
}
}
}
return report
}
func cleanUpFailures(sourceFile string, folder string) {
reports := adapters.GetFiles(folder)
for _, source := range reports {
del := findReport(sourceFile, []string{source})
if del != "" {
e := os.Remove(folder + "/" + del)
if e != nil {
log.Println(e)
}
}
}
}
|
egg82/EventChain | Bukkit/src/main/java/ninja/egg82/events/internal/BukkitHandlerMapping.java | <reponame>egg82/EventChain<gh_stars>10-100
package ninja.egg82.events.internal;
import org.bukkit.event.Event;
import org.bukkit.event.EventPriority;
import org.jetbrains.annotations.NotNull;
import java.util.function.Function;
public class BukkitHandlerMapping<E extends Event, T> extends AbstractPriorityHandlerMapping<EventPriority, E, T> {
public BukkitHandlerMapping(@NotNull EventPriority priority, @NotNull Function<E, T> function) {
super(priority, function);
}
}
|
psiha/nt2 | modules/core/container/table/unit/predicates/issquare.cpp | <gh_stars>10-100
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <nt2/table.hpp>
#include <nt2/include/functions/issquare.hpp>
#include <nt2/include/functions/ones.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/basic.hpp>
NT2_TEST_CASE( fundamental_issquare )
{
NT2_TEST( nt2::issquare('e') );
NT2_TEST( nt2::issquare(1) );
NT2_TEST( nt2::issquare(1.) );
NT2_TEST( nt2::issquare(1.f) );
}
NT2_TEST_CASE( container_issquare )
{
NT2_TEST( nt2::issquare( nt2::ones(4) ) );
NT2_TEST( nt2::issquare( nt2::ones(4,4)) );
NT2_TEST( !nt2::issquare( nt2::ones(4,1,1)) );
NT2_TEST( !nt2::issquare( nt2::ones(4,1,4,1)) );
NT2_TEST( !nt2::issquare( nt2::ones(4,1,1,4)) );
NT2_TEST( !nt2::issquare( nt2::ones(2,3)) );
NT2_TEST( !nt2::issquare( nt2::ones(3,1,2)) );
NT2_TEST( !nt2::issquare( nt2::ones(3,3,1,9)) );
}
|
mythnc/online-judge-solved-lists | UVa/UVa231/231_v2.c | <reponame>mythnc/online-judge-solved-lists
/* ACM 231 Testing the CATCHER
* mythnc
* 2012/01/15 21:19:58
* run time: 0.004
*/
#include <stdio.h>
#define MAXM 10000
void input(void);
int lds(void);
void binsearch(int, int, int);
int n;
int v[MAXM];
int catcher[MAXM];
int main(void)
{
int set, data;
set = 0;
while (scanf("%d", &data) && data != -1) {
catcher[0] = data;
if (set > 0)
putchar('\n');
printf("Test #%d:\n", ++set);
input();
printf(" maximum possible interceptions: %d\n",
lds());
}
return 0;
}
/* input: receive input data
* and return the number of missile */
void input(void)
{
n = 1;
while (scanf("%d", &catcher[n]) && catcher[n] != -1)
n++;
}
/* lds: return the longest decrement subsequence length */
int lds(void)
{
int len, i, j;
len = 0;
v[len++] = catcher[n - 1];
for (i = n - 2; i > -1; i--)
if (catcher[i] > v[len - 1])
v[len++] = catcher[i];
else
binsearch(0, len, i);
return len;
}
void binsearch(int begin, int end, int index)
{
int mid;
while (begin <= end) {
mid = (begin + end) / 2;
if (v[mid] == catcher[index])
return;
else if (v[mid] > catcher[index])
end = mid - 1;
else
begin = mid + 1;
}
mid = (begin + end) / 2;
if (mid == 0 && index == n - 2)
v[0] = catcher[index];
else
v[mid + 1] = catcher[index];
}
|
touchhome/touchhome-bundle | zigbee/src/main/java/org/touchhome/bundle/zigbee/setting/ZigBeeDiscoveryDurationSetting.java | package org.touchhome.bundle.zigbee.setting;
import org.touchhome.bundle.api.setting.SettingPluginSlider;
public class ZigBeeDiscoveryDurationSetting implements SettingPluginSlider {
@Override
public Integer getMin() {
return 60;
}
@Override
public Integer getMax() {
return 254;
}
@Override
public int defaultValue() {
return 254;
}
@Override
public int order() {
return 200;
}
@Override
public boolean isReverted() {
return true;
}
}
|
mleitejunior/code-team-2020 | solutions/marcelo_leite/URI1002.java | <gh_stars>1-10
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
double N = 3.14159d;
double raio = sc.nextDouble();
System.out.println("A=" + String.format("%.4f", + N * raio * raio));
}
}
|
cmstar/go-logx | stdlogger_test.go | package logx
import (
"bytes"
"log"
"testing"
"github.com/stretchr/testify/assert"
)
func TestStdLogger(t *testing.T) {
buf := new(bytes.Buffer)
underlyingLogger := log.New(buf, "", 0)
stdLogger := NewStdLogger(underlyingLogger)
type args struct {
level Level
message string
keyValues []interface{}
want string
}
tests := []struct {
name string
args args
}{
{"empty", args{
level: LevelDebug,
message: "",
keyValues: []interface{}{},
want: "DEBUG \n",
}},
{"simple", args{
level: LevelInfo,
message: "simple",
keyValues: []interface{}{},
want: "INFO simple\n",
}},
{"keyvalue", args{
level: LevelWarn,
message: "msg",
keyValues: []interface{}{
"k1", 1,
"k2", "v2",
},
want: "WARN msg k1=1 k2=v2\n",
}},
{"keyvalue-odd", args{
level: LevelWarn,
message: "msg",
keyValues: []interface{}{
"k1", 1,
"k2", "v2",
"v3",
},
want: "WARN msg k1=1 k2=v2 UNKNOWN=v3\n",
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
buf.Reset()
err := stdLogger.LogFn(tt.args.level, func() (message string, keyValues []interface{}) {
return tt.args.message, tt.args.keyValues
})
assert.NoError(t, err)
msg := buf.String()
assert.Equal(t, tt.args.want, msg)
})
}
}
|
dev-alissonalves/python-codes | scripts/4-condidionais-python/condicionais-aninhadas-python/ex036.py | # -*- coding: UTF-8 -*-
#Exercício Python 36: Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.
#CÓDIGO DE CORES PARA EXERCÍCIOS
#\033[32m
from time import sleep
print("\n\033[;;44m-=-=--=-=- |SISTEMA DE CRÉDITO IMOBILIÁRIO| -=-=--=-=-\033[m")
print("--"*28)
print("#"*10 +" \033[;31;mDIGITE AS INFORMAÇÕES PARA CONSULTA\033[m " +"#"*10)
valor_imovel = float(input("\nQUAL O VALOR ESTIMADO DO IMÓVEL A SER ADQUIRIDO? R$ - "))
salario_comprador = float(input("QUAL O VALOR BRUTO DO SEU SALÁRIO? R$ - "))
anos_financiamento = int(input("EM QUANTOS ANOS O SENHOR DESEJA QUITAR A CASA? "))
print("\n")
print("#"*15 +" \033[;;44mPROCESSANDO... \033[m " +"#"*15)
print("\n")
sleep(3)
percentualValido = (salario_comprador * 30)/100
valor_prestacao = valor_imovel/(anos_financiamento*12)
if valor_prestacao > percentualValido:
print("\n\033[;;41m### RENDA INCOMPATÍVEL - EMPRÉSTIMO NEGADO! ###\033[m\n")
print(f"A SUA PRESTAÇÃO DE R$: {valor_prestacao:.2f} É MAIOR QUE R$: {percentualValido:.2f} QUE CORRESPONDE A 30 % DO SEU SALÁRIO.\n")
print("#"*15 +" \033[;;44mFINALIZANDO... \033[m " +"#"*15)
sleep(3)
print("\033[;;44m-=-=--=-=- |SISTEMA DE CRÉDITO IMOBILIÁRIO| -=-=--=-=-\033[m\n")
sleep(3)
exit()
else:
print("\033[1;31;42m###### RENDA COMPATÍVEL - EMPRÉSTIMO APROVADO! ######\033[m")
print(f"SUA PARCELA MENSAL SERÁ DE: R$ {valor_prestacao:.2f} EM {anos_financiamento} ANOS.")
operacao = int(input("\n[DIGITE (1) PARA ACEITAR O EMPRÉSTIMO]\n[DIGITE (0) PARA REJEITAR E SAIR DO SISTEMA] - "))
if operacao == 1:
print("\n")
print("#"*15 +" \033[;;44mPROCESSANDO... \033[m " +"#"*15+"\n")
sleep(3)
print(f"\033[7mO valor de R$: {valor_imovel:.2f} está disponível para saque.\nProcure a agência do Banco do Brasil mais próxima.\033[m\n")
print("\033[;;44m-=-=--=-=- |SISTEMA DE CRÉDITO IMOBILIÁRIO| -=-=--=-=-\033[m\n")
else:
print("\n")
print("#"*15 +" \033[;;44mFINALIZANDO... \033[m " +"#"*15)
print("\n")
sleep(3)
print("\033[;;44m-=-=--=-=- |SISTEMA DE CRÉDITO IMOBILIÁRIO| -=-=--=-=-\033[m\n")
sleep(3)
exit()
|
shekoocoder/telepathy | QtumJsIosServer/qtum-ios-develop/qtum wallet/Profile Flow/Contract/QStore/QStoreCoordinator.h | <reponame>shekoocoder/telepathy
//
// QStoreCoordinator.h
// qtum wallet
//
// Created by <NAME> on 09.08.17.
// Copyright © 2017 QTUM. All rights reserved.
//
#import "BaseCoordinator.h"
@interface QStoreCoordinator : BaseCoordinator <Coordinatorable>
@end
|
Tech-XCorp/visit-deps | windowsbuild/MSVC2017/ospray/1.6.1/include/ospray/visit/VisItImageComposite.h | // ======================================================================== //
// Copyright <NAME> //
// Scientific Computing and Image Institution //
// University of Utah //
// //
// 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. //
// ======================================================================== //
// this file will be installed so can expose new functions to the users
#pragma once
#ifdef _WIN32
# ifdef ospray_module_visit_common_EXPORTS
# define OSPRAY_MODULE_VISIT_COMMON_INTERFACE __declspec(dllexport)
# else
# define OSPRAY_MODULE_VISIT_COMMON_INTERFACE __declspec(dllimport)
# endif
#else
# define OSPRAY_MODULE_VISIT_COMMON_INTERFACE OSPRAY_SDK_INTERFACE
#endif
namespace ospray {
namespace visit {
extern "C" OSPRAY_MODULE_VISIT_COMMON_INTERFACE void Experiment();
extern "C" OSPRAY_MODULE_VISIT_COMMON_INTERFACE void CompositeBackground(int*, int*, int, int, float *,
unsigned char *, float *,
unsigned char *&);
extern "C" OSPRAY_MODULE_VISIT_COMMON_INTERFACE void BlendFrontToBack(const int *blendExtents,
const int *srcExtents,
const float *srcImage,
const int *dstExtents,
float *&dstImage);
extern "C" OSPRAY_MODULE_VISIT_COMMON_INTERFACE void BlendBackToFront(const int *blendExtents,
const int *srcExtents,
const float *srcImage,
const int *dstExtents,
float *&dstImage);
};
};
|
eyangch/competitive-programming | CSES/Introductory_Problems/creating_strings_i.cpp | #include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pii;
template <typename T1, typename T2>
ostream &operator <<(ostream &os, pair<T1, T2> p){os << p.first << " " << p.second; return os;}
template <typename T>
ostream &operator <<(ostream &os, vector<T> &v){for(T i : v)os << i << ", "; return os;}
template <typename T>
ostream &operator <<(ostream &os, set<T> s){for(T i : s) os << i << ", "; return os;}
template <typename T1, typename T2>
ostream &operator <<(ostream &os, map<T1, T2> m){for(pair<T1, T2> i : m) os << i << endl; return os;}
int N;
string s;
set<string> ans;
void dfs(int pos, string x){
if((int)x.length() == N){
ans.insert(x);
return;
}
for(int i = 0; i < N; i++){
if((pos&(1<<i))){
continue;
}
int tmpi = pos | (1<<i);
string tmp = x + s[i];
dfs(tmpi, tmp);
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> s;
N = (int)s.length();
dfs(0, "");
cout << ans.size() << endl;
for(string i : ans){
cout << i << endl;
}
return 0;
}
|
bmjames/intellij-haskforce | src/com/haskforce/parsing/srcExtsDatatypes/ImportSpecTopType.java | <filename>src/com/haskforce/parsing/srcExtsDatatypes/ImportSpecTopType.java<gh_stars>0
package com.haskforce.parsing.srcExtsDatatypes;
/**
* data ImportSpec l
* = IVar l (Name l) -- ^ variable
* | IAbs l (Name l) -- ^ @T@:
* -- the name of a class, datatype or type synonym.
* | IThingAll l (Name l) -- ^ @T(..)@:
* -- a class imported with all of its methods, or
* -- a datatype imported with all of its constructors.
* | IThingWith l (Name l) [CName l] -- ^ @T(C_1,...,C_n)@:
* -- a class imported with some of its methods, or
* -- a datatype imported with some of its constructors.
*/
public class ImportSpecTopType {
}
|
Hash-Checker/hash-checker | app/src/main/java/com/smlnskgmail/jaman/hashchecker/components/locale/api/Language.java | package com.smlnskgmail.jaman.hashchecker.components.locale.api;
import android.content.Context;
import androidx.annotation.NonNull;
import com.smlnskgmail.jaman.hashchecker.R;
import com.smlnskgmail.jaman.hashchecker.ui.bottomsheets.lists.ListItem;
public enum Language implements ListItem {
EN("English", "en"),
DE("Deutsch", "de"),
EL("Ελληνικά", "el"),
ES("Español", "es"),
FA("Farsi", "fa"),
FR("Français", "fr"),
HU("Hungarian", "hu"),
IT("Italiano", "it"),
IW("ברית", "iw"),
KO("한국어", "ko"),
NL("Nederlands", "nl"),
PL("Polski", "pl"),
PT("Português (Brasil)", "pt-rBR"),
RU("Русский", "ru"),
SV("Svenska", "sv"),
ZH("中文(简体)", "zh-rCN"),
VI("Tiếng Việt", "vi"),
JA("日本語", "ja");
private final String originalName;
private final String code;
Language(@NonNull String originalName, @NonNull String code) {
this.originalName = originalName;
this.code = code;
}
@NonNull
public String code() {
return code;
}
@NonNull
@Override
public String getTitle(@NonNull Context context) {
return originalName;
}
@Override
public int getPrimaryIconResId() {
return -1;
}
@Override
public int getAdditionalIconResId() {
return R.drawable.ic_done;
}
}
|
anatawa12/intellij-community | platform/core-impl/src/com/intellij/psi/impl/ResolveScopeManager.java | <reponame>anatawa12/intellij-community
// Copyright 2000-2021 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.impl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public abstract class ResolveScopeManager {
@NotNull
public abstract GlobalSearchScope getResolveScope(@NotNull PsiElement element);
@NotNull
public abstract GlobalSearchScope getDefaultResolveScope(@NotNull VirtualFile vFile);
@NotNull
public abstract GlobalSearchScope getUseScope(@NotNull PsiElement element);
@NotNull
public static ResolveScopeManager getInstance(@NotNull Project project) {
return project.getService(ResolveScopeManager.class);
}
@NotNull
public static GlobalSearchScope getElementUseScope(@NotNull PsiElement element) {
return getInstance(element.getProject()).getUseScope(element);
}
@NotNull
public static GlobalSearchScope getElementResolveScope(@NotNull PsiElement element) {
PsiFile file = element.getContainingFile();
if (file != null) {
return getInstance(file.getProject()).getResolveScope(file);
}
return getInstance(element.getProject()).getResolveScope(element);
}
}
|
yuvalbdgit/TEST | internal/commands/root.go | /*
Copyright (c) 2019 the Octant contributors. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package commands
import (
"fmt"
"log"
"os"
"github.com/spf13/cobra"
)
// Execute executes octant.
func Execute(version string, gitCommit string, buildTime string) {
// remove timestamp from log
log.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime))
rootCmd := newRoot(version, gitCommit, buildTime)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func newRoot(version string, gitCommit string, buildTime string) *cobra.Command {
rootCmd := newOctantCmd(version, gitCommit, buildTime)
rootCmd.AddCommand(newVersionCmd(version, gitCommit, buildTime))
return rootCmd
}
|
ro-msg-spring-training/online-shop-mariusfica10 | shop/src/main/java/ro/msg/learning/shop/controller/SupplierController.java | <gh_stars>0
package ro.msg.learning.shop.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import ro.msg.learning.shop.controller.dto.SupplierDTO;
import ro.msg.learning.shop.service.SupplierService;
@RestController
public class SupplierController {
@Autowired
SupplierService supplierService;
@RequestMapping(value="/suppliers", method = RequestMethod.GET)
public List<SupplierDTO> getSuppliers()
{
return supplierService.getSuppliers();
}
@RequestMapping(value="/suppliers/{id}", method = RequestMethod.GET)
public SupplierDTO getSupplierByID(@PathVariable int id)
{
return supplierService.getSupplierByID(id);
}
//POST
@RequestMapping(value="/suppliers/save", method= RequestMethod.POST)
public void saveSupplier(@RequestBody SupplierDTO supplierDTO)
{
supplierService.saveSupplier(supplierDTO);
}
}
|
gianpietro1/manageiq-providers-openstack | app/models/manageiq/providers/openstack/cloud_manager/cloud_resource_quota.rb | class ManageIQ::Providers::Openstack::CloudManager::CloudResourceQuota < ::CloudResourceQuota
private
# quota_used methods defined for each known quota type
# if no method is provided for a quota type, then -1 is returned by
# method_missing (see parent)
VMS_POWER_FILTER = "power_state != 'unknown'"
def cores_quota_used
Hardware.joins(:vm)
.where(:vms => {:cloud_tenant_id => cloud_tenant_id})
.where("vms.#{VMS_POWER_FILTER}")
.sum(:cpu_total_cores)
end
def instances_quota_used
cloud_tenant.vms.where(VMS_POWER_FILTER).count
end
def ram_quota_used
Hardware.joins(:vm)
.where(:vms => {:cloud_tenant_id => cloud_tenant_id})
.where("vms.#{VMS_POWER_FILTER}")
.sum(:memory_mb)
end
# nova
def floating_ips_quota_used
# in reality, nova should not use the same quota used value as neutron ...
# instead, if neutron is being used for networking (i.e., ems has network
# service available), then show 0
floatingip_quota_used
end
# neutron
def floatingip_quota_used
::FloatingIp.where(:cloud_tenant_id => cloud_tenant_id).count
end
# nova
def security_group_rules_quota_used
# in reality, nova should not use the same quota used value as neutron ...
# instead, if neutron is being used for networking (i.e., ems has network
# service available), then show 0
security_group_rule_quota_used
end
# neutron
def security_group_rule_quota_used
join = "inner join security_groups on security_groups.id = firewall_rules.resource_id "
join += "and firewall_rules.resource_type = 'SecurityGroup'"
FirewallRule.joins(join)
.where("security_groups.cloud_tenant_id" => cloud_tenant_id)
.count
end
# nova
def security_groups_quota_used
# in reality, nova should not use the same quota used value as neutron ...
# instead, if neutron is being used for networking (i.e., ems has network
# service available), then show 0
security_group_quota_used
end
# neutron
def security_group_quota_used
SecurityGroup.where(:cloud_tenant_id => cloud_tenant_id).count
end
def network_quota_used
CloudNetwork.where(:cloud_tenant_id => cloud_tenant_id).count
end
def subnet_quota_used
CloudSubnet.joins(:cloud_network).where("cloud_networks.cloud_tenant_id" => cloud_tenant_id).count
end
def port_quota_used
NetworkPort.where(:cloud_tenant_id => cloud_tenant_id).count
end
def volumes_quota_used
CloudVolume.where(:cloud_tenant_id => cloud_tenant_id).count
end
def gigabytes_quota_used
CloudVolume.where(:cloud_tenant_id => cloud_tenant_id)
.sum(:size) / 1_073_741_824
end
def per_volume_gigabytes_quota_used
max_used = CloudVolume.where(:cloud_tenant_id => cloud_tenant_id)
.maximum(:size)
max_used.nil? ? 0 : max_used / 1_073_741_824
end
def backups_quota_used
CloudVolumeBackup.joins(:cloud_volume)
.where("cloud_volumes.cloud_tenant_id" => cloud_tenant_id).count
end
def backup_gigabytes_quota_used
CloudVolumeBackup.joins(:cloud_volume)
.where("cloud_volumes.cloud_tenant_id" => cloud_tenant_id)
.sum(:size) / 1_073_741_824
end
def snapshots_quota_used
CloudVolumeSnapshot.where(:cloud_tenant_id => cloud_tenant_id).count
end
def ems
CloudTenant.find(cloud_tenant_id).ext_management_system
end
def key_pairs_quota_used
Authentication.where(:resource_id => ems.id,
:resource_type => 'ExtManagementSystem',
:type => ManageIQ::Providers::Openstack::CloudManager::AuthKeyPair.name).count
end
def router_quota_used
NetworkRouter.where(:cloud_tenant_id => cloud_tenant_id).count
end
end
|
billwert/azure-sdk-for-java | sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreResult.java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation.directconnectivity;
import com.azure.cosmos.CosmosException;
import com.azure.cosmos.implementation.Exceptions;
import com.azure.cosmos.implementation.HttpConstants;
import com.azure.cosmos.implementation.ISessionToken;
import com.azure.cosmos.implementation.InternalServerErrorException;
import com.azure.cosmos.implementation.RMResources;
import com.azure.cosmos.implementation.RequestChargeTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StoreResult {
private final static Logger logger = LoggerFactory.getLogger(StoreResult.class);
private final StoreResponse storeResponse;
private final CosmosException exception;
final public long lsn;
final public String partitionKeyRangeId;
final public long quorumAckedLSN;
final public long globalCommittedLSN;
final public long numberOfReadRegions;
final public long itemLSN;
final public ISessionToken sessionToken;
final public double requestCharge;
final public String activityId;
final public String correlatedActivityId;
final public int currentReplicaSetSize;
final public int currentWriteQuorum;
final public boolean isValid;
final public boolean isGoneException;
final public boolean isNotFoundException;
final public boolean isInvalidPartitionException;
final public Uri storePhysicalAddress;
final public boolean isThroughputControlRequestRateTooLargeException;
final public Double backendLatencyInMs;
public StoreResult(
StoreResponse storeResponse,
CosmosException exception,
String partitionKeyRangeId,
long lsn,
long quorumAckedLsn,
double requestCharge,
String activityId,
String correlatedActivityId,
int currentReplicaSetSize,
int currentWriteQuorum,
boolean isValid,
Uri storePhysicalAddress,
long globalCommittedLSN,
int numberOfReadRegions,
long itemLSN,
ISessionToken sessionToken,
Double backendLatencyInMs) {
this.storeResponse = storeResponse;
this.exception = exception;
this.partitionKeyRangeId = partitionKeyRangeId;
this.lsn = lsn;
this.quorumAckedLSN = quorumAckedLsn;
this.requestCharge = requestCharge;
this.activityId= activityId;
this.correlatedActivityId = correlatedActivityId;
this.currentReplicaSetSize = currentReplicaSetSize;
this.currentWriteQuorum = currentWriteQuorum;
this.isValid = isValid;
this.isGoneException = this.exception != null && this.exception.getStatusCode() == HttpConstants.StatusCodes.GONE;
this.isNotFoundException = this.exception != null && this.exception.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND;
this.isInvalidPartitionException = this.exception != null
&& Exceptions.isNameCacheStale(this.exception);
this.storePhysicalAddress = storePhysicalAddress;
this.globalCommittedLSN = globalCommittedLSN;
this.numberOfReadRegions = numberOfReadRegions;
this.itemLSN = itemLSN;
this.sessionToken = sessionToken;
this.isThroughputControlRequestRateTooLargeException = this.exception != null && Exceptions.isThroughputControlRequestRateTooLargeException(this.exception);
this.backendLatencyInMs = backendLatencyInMs;
}
public StoreResponse getStoreResponse() {
return storeResponse;
}
public CosmosException getException() throws InternalServerErrorException {
if (this.exception == null) {
String message = "Exception should be available but found none";
assert false : message;
logger.error(message);
throw new InternalServerErrorException(RMResources.InternalServerError);
}
return exception;
}
public StoreResponse toResponse() {
return toResponse(null);
}
public StoreResponse toResponse(RequestChargeTracker requestChargeTracker) {
if (!this.isValid) {
if (this.exception == null) {
logger.error("Exception not set for invalid response");
throw new InternalServerErrorException(RMResources.InternalServerError);
}
throw this.exception;
}
if (requestChargeTracker != null) {
StoreResult.setRequestCharge(this.storeResponse, this.exception, requestChargeTracker.getTotalRequestCharge());
}
if (this.exception != null) {
throw exception;
}
return this.storeResponse;
}
private static void setRequestCharge(StoreResponse response, CosmosException cosmosException, double totalRequestCharge) {
String totalRequestChargeString = Double.toString(totalRequestCharge);
if (cosmosException != null) {
cosmosException.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_CHARGE, totalRequestChargeString);
} else {
// Set total charge as final charge for the response.
response.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_CHARGE, totalRequestChargeString);
}
}
}
|
jordanblakey/react-ecosystem | dist/components/MessageBrowser/Sidebar.js | <reponame>jordanblakey/react-ecosystem
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Sidebar = undefined;
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Sidebar = exports.Sidebar = function Sidebar(props) {
var filterFlagged = props.filterFlagged,
updateFilterFlagged = props.updateFilterFlagged,
sentOrder = props.sentOrder,
updateSentOrder = props.updateSentOrder;
return _react2.default.createElement(
"div",
{ className: "content" },
_react2.default.createElement(
"h3",
null,
"Sidebar Tools"
),
_react2.default.createElement(
"label",
{ className: "label" },
"Sort By"
),
_react2.default.createElement(
"p",
{ className: "control" },
_react2.default.createElement(
"span",
{ className: "select" },
_react2.default.createElement(
"select",
{
value: sentOrder,
onChange: function onChange(_ref) {
var value = _ref.target.value;
return updateSentOrder(value);
}
},
_react2.default.createElement(
"option",
{ value: "DESC" },
"Most Recent"
),
_react2.default.createElement(
"option",
{ value: "ASC" },
"Least Recent"
)
)
)
),
_react2.default.createElement(
"label",
{ className: "label" },
"Filter By"
),
_react2.default.createElement(
"div",
null,
_react2.default.createElement(
"label",
{ className: "checkbox" },
_react2.default.createElement("input", {
type: "checkbox",
checked: filterFlagged,
onChange: function onChange(_ref2) {
var checked = _ref2.target.checked;
return updateFilterFlagged(checked);
}
}),
"Flagged"
)
),
_react2.default.createElement(
"div",
null,
_react2.default.createElement(
"label",
{ className: "checkbox is-disabled" },
_react2.default.createElement("input", { type: "checkbox", disabled: true }),
"Unread"
)
)
);
}; |
Tommsy64/ModularPowerArmor | src/main/java/com/github/lehjr/modularpowerarmor/client/model/item/PowerFist.java | package com.github.lehjr.modularpowerarmor.client.model.item;
public class PowerFist {
// TODO: try to restore original power fist model or else back to the same old same old
/*
https://github.com/MrJake222/AUNIS/blob/master/src/main/java/mrjake/aunis/item/PageNotebookBakedModel.java
https://github.com/MrJake222/AUNIS/blob/master/src/main/java/mrjake/aunis/item/renderer/PageNotebookTEISR.java
*/
} |
ScalablyTyped/SlinkyTyped | h/heremaps/src/main/scala/typingsSlinky/heremaps/H/ui/Pano.scala | <gh_stars>10-100
package typingsSlinky.heremaps.H.ui
import typingsSlinky.heremaps.H.service.MapType
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object Pano {
/**
* @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.RIGHT_BOTTOM
* @property mapTypes {H.service.MapTypes} - The map types to use
*/
@js.native
trait Options extends StObject {
var alignment: js.UndefOr[LayoutAlignment] = js.native
var mapTypes: MapType = js.native
}
object Options {
@scala.inline
def apply(mapTypes: MapType): Options = {
val __obj = js.Dynamic.literal(mapTypes = mapTypes.asInstanceOf[js.Any])
__obj.asInstanceOf[Options]
}
@scala.inline
implicit class OptionsMutableBuilder[Self <: Options] (val x: Self) extends AnyVal {
@scala.inline
def setAlignment(value: LayoutAlignment): Self = StObject.set(x, "alignment", value.asInstanceOf[js.Any])
@scala.inline
def setAlignmentUndefined: Self = StObject.set(x, "alignment", js.undefined)
@scala.inline
def setMapTypes(value: MapType): Self = StObject.set(x, "mapTypes", value.asInstanceOf[js.Any])
}
}
}
|
damirault/azure-sdk-for-c | sdk/core/az_core/src/az_http_header_validation_private.h | <gh_stars>0
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
/**
* @file az_http_header_validation_private.h
*
* @brief This header defines a bit array that is used to validate whenever or not an ASCII char is
* valid within an http header name.
*
*/
#ifndef _az_HTTP_HEADER_VALIDATION_PRIVATE_H
#define _az_HTTP_HEADER_VALIDATION_PRIVATE_H
#include <az_span.h>
#include <stdbool.h>
#include <stdint.h>
#include <_az_cfg_prefix.h>
// Bit array from ASCII to valid. Every zero in array means invalid character, while non-zeros
// return the valid character.
static const uint8_t az_http_valid_token[256] = {
0, // 0 -> null
0, // 1 -> start of heading
0, // 2 -> start of text
0, // 3 -> end of text
0, // 4 -> end of transmission
0, // 5 -> enquiry
0, // 6 -> acknowledge
0, // 7 -> bell
0, // 8 -> backspace
0, // 9 -> horizontal tab
0, // 10 -> new line
0, // 11 -> vertical tab
0, // 12 -> new page
0, // 13 -> carriage return
0, // 14 -> shift out
0, // 15 -> shift in
0, // 16 -> data link escape
0, // 17 -> device control 1
0, // 18 -> device control 2
0, // 19 -> device control 3
0, // 20 -> device control 4
0, // 21 -> negative acknowledge
0, // 22 -> synchronous idle
0, // 23 -> end of trans. block
0, // 24 -> cancel
0, // 25 -> end of medium
0, // 26 -> substitute
0, // 27 -> escape
0, // 28 -> file separator
0, // 29 -> group separator
0, // 30 -> record separator
0, // 31 -> unit separator
' ', // 32 -> space
'!', // 33 -> !
0, // 34 -> “
'#', // 35 -> #
'$', // 36 -> $
'%', // 37 -> %
'&', // 38 -> &
'\'', // 39 -> ‘
0, // 40 -> (
0, // 41 -> )
'*', // 42 -> *
'+', // 43 -> +
0, // 44 -> ,
'-', // 45 -> –
'.', // 46 -> .
0, // 47 -> /
'0', // 48 -> 0
'1', // 49 -> 1
'2', // 50 -> 2
'3', // 51 -> 3
'4', // 52 -> 4
'5', // 53 -> 5
'6', // 54 -> 6
'7', // 55 -> 7
'8', // 56 -> 8
'9', // 57 -> 9
0, // 58 -> :
0, // 59 -> ;
0, // 60 -> <
0, // 61 -> =
0, // 62 -> >
0, // 63 -> ?
0, // 64 -> @
'a', // 65 -> A
'b', // 66 -> B
'c', // 67 -> C
'd', // 68 -> D
'e', // 69 -> E
'f', // 70 -> F
'g', // 71 -> G
'h', // 72 -> H
'i', // 73 -> I
'j', // 74 -> J
'k', // 75 -> K
'l', // 76 -> L
'm', // 77 -> M
'n', // 78 -> N
'o', // 79 -> O
'p', // 80 -> P
'q', // 81 -> Q
'r', // 82 -> R
's', // 83 -> S
't', // 84 -> T
'u', // 85 -> U
'v', // 86 -> V
'w', // 87 -> W
'x', // 88 -> X
'y', // 89 -> Y
'z', // 90 -> Z
0, // 91 -> [
0, // 92 -> comment
0, // 93 -> ]
'^', // 94 -> ^
'_', // 95 -> _
'`', // 96 -> `
'a', // 97 -> a
'b', // 98 -> b
'c', // 99 -> c
'd', // 100 -> d
'e', // 101 -> e
'f', // 102 -> f
'g', // 103 -> g
'h', // 104 -> h
'i', // 105 -> i
'j', // 106 -> j
'k', // 107 -> k
'l', // 108 -> l
'm', // 109 -> m
'n', // 110 -> n
'o', // 111 -> o
'p', // 112 -> p
'q', // 113 -> q
'r', // 114 -> r
's', // 115 -> s
't', // 116 -> t
'u', // 117 -> u
'v', // 118 -> v
'w', // 119 -> w
'x', // 120 -> x
'y', // 121 -> y
'z', // 122 -> z
0, // 123 -> {
'|', // 124 -> |
0, // 125 -> }
'~', // 126 -> ~
0 // 127 -> DEL
// ...128-255 is all zeros (not valid) characters
};
#ifndef AZ_NO_PRECONDITION_CHECKING
/* This function is for httpRequest only to check header names are valid.
* Validation is a Precondition so this code would compile away if preconditions are OFF
*/
AZ_NODISCARD AZ_INLINE bool az_http_is_valid_header_name(az_span name)
{
uint8_t* name_ptr = az_span_ptr(name);
for (int32_t i = 0; i < az_span_size(name); i++)
{
uint8_t c = name_ptr[i];
if (az_http_valid_token[c] == 0)
{
return false;
}
}
return true;
}
#endif // AZ_NO_PRECONDITION_CHECKING
#include <_az_cfg_suffix.h>
#endif // _az_HTTP_HEADER_VALIDATION_PRIVATE_H
|
123FLO321/semantic-release-docker | test/unit/build-config.js | 'use strict'
const path = require('path')
const {test, threw} = require('tap')
const buildConfig = require('../../lib/build-config.js')
test('build-config', async (t) => {
t.testdir({
standard: {
'package.json': JSON.stringify({name: 'this-is-not-scoped'})
}
, scoped: {
'package.json': JSON.stringify({name: '@scope/this-is-scoped'})
}
, workspace: {
one: {
'package.json': JSON.stringify({name: '@internal/package'})
}
}
})
t.test('standard package', async (tt) => {
const config = await buildConfig('id', {
}, {
cwd: path.join(t.testdirName, 'standard')
})
tt.match(config, {
dockerfile: 'Dockerfile'
, publish: true
, nocache: false
, tags: ['latest', '{{major}}-latest', '{{version}}']
, args: {
SRC_DIRECTORY: 'standard'
, TARGET_PATH: '.'
, NPM_PACKAGE_NAME: 'this-is-not-scoped'
, NPM_PACKAGE_SCOPE: null
, CONFIG_NAME: 'this-is-not-scoped'
, CONFIG_PROJECT: null
}
, pkg: Object
, registry: null
, name: 'this-is-not-scoped'
, project: null
, build: 'id'
, context: '.'
})
})
t.test('nested workspace: target resolution', async (tt) => {
const config = await buildConfig('id', {
}, {
options: {
root: t.testdirName
}
, cwd: path.join(t.testdirName, 'workspace', 'one')
})
tt.match(config, {
dockerfile: 'Dockerfile'
, nocache: false
, publish: true
, tags: ['latest', '{{major}}-latest', '{{version}}']
, args: {
SRC_DIRECTORY: 'one'
, TARGET_PATH: 'workspace/one'
, NPM_PACKAGE_NAME: 'package'
, NPM_PACKAGE_SCOPE: 'internal'
, CONFIG_NAME: 'package'
, CONFIG_PROJECT: 'internal'
}
, pkg: Object
, registry: null
, name: 'package'
, project: 'internal'
, build: 'id'
, context: '.'
})
})
t.test('scoped package', async (tt) => {
{
const config = await buildConfig('id', {
}, {
cwd: path.join(t.testdirName, 'scoped')
})
tt.match(config, {
dockerfile: 'Dockerfile'
, nocache: false
, tags: ['latest', '{{major}}-latest', '{version}']
, args: {
SRC_DIRECTORY: 'scoped'
, TARGET_PATH: '.'
, NPM_PACKAGE_NAME: '@scope/this-is-scoped'
, NPM_PACKAGE_SCOPE: 'scope'
, CONFIG_NAME: 'this-is-scoped'
, CONFIG_PROJECT: 'scope'
}
, pkg: Object
, registry: null
, name: 'this-is-scoped'
, project: 'scope'
, build: 'id'
, context: '.'
})
}
{
const config = await buildConfig('id', {
dockerProject: 'kittens'
, dockerImage: 'override'
, dockerFile: 'Dockerfile.test'
, dockerPublish: false
}, {
cwd: path.join(t.testdirName, 'scoped')
})
tt.match(config, {
dockerfile: 'Dockerfile.test'
, publish: false
, nocache: false
, tags: ['latest', '{{major}}-latest', '{{version}}']
, args: {
SRC_DIRECTORY: 'scoped'
, TARGET_PATH: '.'
, NPM_PACKAGE_NAME: '@scope/this-is-scoped'
, NPM_PACKAGE_SCOPE: 'scope'
, CONFIG_NAME: 'override'
, CONFIG_PROJECT: 'kittens'
}
, pkg: Object
, registry: null
, name: 'override'
, project: 'kittens'
, build: 'id'
, context: '.'
})
}
{
const config = await buildConfig('id', {
dockerProject: null
, dockerImage: 'override'
, dockerFile: 'Dockerfile.test'
, dockerTags: 'latest,{{major}}-latest , fake, {{version}}'
}, {
cwd: path.join(t.testdirName, 'scoped')
})
tt.match(config, {
dockerfile: 'Dockerfile.test'
, nocache: false
, tags: ['latest', '{{major}}-latest', 'fake', '{{version}}']
, args: {
SRC_DIRECTORY: 'scoped'
, TARGET_PATH: '.'
, NPM_PACKAGE_NAME: '@scope/this-is-scoped'
, NPM_PACKAGE_SCOPE: 'scope'
, CONFIG_NAME: 'override'
, CONFIG_PROJECT: null
}
, pkg: Object
, registry: null
, name: 'override'
, project: null
, build: 'id'
, context: '.'
})
}
})
}).catch(threw)
|
fredsterorg/incubator-pinot | pinot-controller/src/main/java/org/apache/pinot/controller/ControllerStarter.java | <gh_stars>1000+
/**
* 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.pinot.controller;
import java.io.File;
import org.apache.pinot.spi.env.PinotConfiguration;
import org.apache.pinot.spi.utils.CommonConstants;
/**
* Default controller startable implementation. Contains methods to start and stop the controller
*/
public class ControllerStarter extends BaseControllerStarter {
public ControllerStarter() {
}
@Deprecated
public ControllerStarter(PinotConfiguration pinotConfiguration)
throws Exception {
init(pinotConfiguration);
}
public static ControllerStarter startDefault()
throws Exception {
return startDefault(null);
}
public static ControllerStarter startDefault(File webappPath)
throws Exception {
final ControllerConf conf = new ControllerConf();
conf.setControllerHost("localhost");
conf.setControllerPort("9000");
conf.setDataDir("/tmp/PinotController");
conf.setZkStr("localhost:2122");
conf.setHelixClusterName("quickstart");
if (webappPath == null) {
String path = ControllerStarter.class.getClassLoader().getResource("webapp").getFile();
if (!path.startsWith("file://")) {
path = "file://" + path;
}
conf.setQueryConsolePath(path);
} else {
conf.setQueryConsolePath("file://" + webappPath.getAbsolutePath());
}
conf.setControllerVipHost("localhost");
conf.setControllerVipProtocol(CommonConstants.HTTP_PROTOCOL);
conf.setRetentionControllerFrequencyInSeconds(3600 * 6);
conf.setOfflineSegmentIntervalCheckerFrequencyInSeconds(3600);
conf.setRealtimeSegmentValidationFrequencyInSeconds(3600);
conf.setBrokerResourceValidationFrequencyInSeconds(3600);
conf.setStatusCheckerFrequencyInSeconds(5 * 60);
conf.setSegmentRelocatorFrequencyInSeconds(3600);
conf.setStatusCheckerWaitForPushTimeInSeconds(10 * 60);
conf.setTenantIsolationEnabled(true);
final ControllerStarter starter = new ControllerStarter();
starter.init(conf);
starter.start();
return starter;
}
public static void main(String[] args)
throws Exception {
startDefault();
}
}
|
xwgoon/exercise | src/main/java/com/horstmann/corejava/v2ch03/xpath/MyTest.java | package com.horstmann.corejava.v2ch03.xpath;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPathConstants;
import java.util.StringJoiner;
public class MyTest {
public static void main(String[] args) {
// StringJoiner joiner = new StringJoiner(",", "{", "}");
// joiner.add("aa");
// joiner.add("bb");
// System.out.println(joiner);
try {
QName returnType = (QName) XPathConstants.class.getField("BOOLEAN").get(null);
System.out.println(returnType);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
}
|
RedBrumbler/virtuoso-codegen | include/VROSC/VRPlayer_OverrideControllerPrefab.hpp | <reponame>RedBrumbler/virtuoso-codegen<filename>include/VROSC/VRPlayer_OverrideControllerPrefab.hpp
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: VROSC.VRPlayer
#include "VROSC/VRPlayer.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: VROSC
namespace VROSC {
// Forward declaring type: InputDevice
class InputDevice;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::VRPlayer::OverrideControllerPrefab);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::VRPlayer::OverrideControllerPrefab*, "VROSC", "VRPlayer/OverrideControllerPrefab");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: VROSC.VRPlayer/VROSC.OverrideControllerPrefab
// [TokenAttribute] Offset: FFFFFFFF
class VRPlayer::OverrideControllerPrefab : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// public VROSC.VRPlayer/VROSC.ControllerType controllerType
// Size: 0x4
// Offset: 0x10
::VROSC::VRPlayer::ControllerType controllerType;
// Field size check
static_assert(sizeof(::VROSC::VRPlayer::ControllerType) == 0x4);
// Padding between fields: controllerType and: name
char __padding0[0x4] = {};
// public System.String name
// Size: 0x8
// Offset: 0x18
::StringW name;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// public VROSC.InputDevice leftPrefab
// Size: 0x8
// Offset: 0x20
::VROSC::InputDevice* leftPrefab;
// Field size check
static_assert(sizeof(::VROSC::InputDevice*) == 0x8);
// public VROSC.InputDevice rightPrefab
// Size: 0x8
// Offset: 0x28
::VROSC::InputDevice* rightPrefab;
// Field size check
static_assert(sizeof(::VROSC::InputDevice*) == 0x8);
public:
// Get instance field reference: public VROSC.VRPlayer/VROSC.ControllerType controllerType
::VROSC::VRPlayer::ControllerType& dyn_controllerType();
// Get instance field reference: public System.String name
::StringW& dyn_name();
// Get instance field reference: public VROSC.InputDevice leftPrefab
::VROSC::InputDevice*& dyn_leftPrefab();
// Get instance field reference: public VROSC.InputDevice rightPrefab
::VROSC::InputDevice*& dyn_rightPrefab();
// public System.Void .ctor()
// Offset: 0x1416DB8
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static VRPlayer::OverrideControllerPrefab* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::VRPlayer::OverrideControllerPrefab::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<VRPlayer::OverrideControllerPrefab*, creationType>()));
}
}; // VROSC.VRPlayer/VROSC.OverrideControllerPrefab
#pragma pack(pop)
static check_size<sizeof(VRPlayer::OverrideControllerPrefab), 40 + sizeof(::VROSC::InputDevice*)> __VROSC_VRPlayer_OverrideControllerPrefabSizeCheck;
static_assert(sizeof(VRPlayer::OverrideControllerPrefab) == 0x30);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::VRPlayer::OverrideControllerPrefab::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
aplocon/sis | core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/matrix/SolverTest.java | /*
* 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.sis.referencing.operation.matrix;
import java.util.Random;
import Jama.Matrix;
import org.apache.sis.test.DependsOn;
import org.apache.sis.test.DependsOnMethod;
import org.apache.sis.test.TestUtilities;
import org.apache.sis.test.TestCase;
import org.junit.Test;
import static java.lang.Double.NaN;
import static org.apache.sis.referencing.operation.matrix.MatrixTestCase.assertEqualsJAMA;
import static org.apache.sis.referencing.operation.matrix.MatrixTestCase.assertEqualsElements;
/**
* Tests the {@link Solver} class using <a href="http://math.nist.gov/javanumerics/jama">JAMA</a>
* as the reference implementation.
*
* <div class="section">Cyclic dependency</div>
* There is a cyclic test dependency since {@link GeneralMatrix} needs {@link Solver} for some operations,
* and conversely. To be more specific the dependency order is:
*
* <ol>
* <li>Simple {@link GeneralMatrix} methods (construction, get/set elements)</li>
* <li>{@link Solver}</li>
* <li>More complex {@code GeneralMatrix} methods (matrix inversion, solve)</li>
* </ol>
*
* We test {@code GeneralMatrix} before {@code Solver} since nothing could be done without
* the above-cited simple operations anyway.
*
* @author <NAME> (Geomatys)
* @version 0.4
* @since 0.4
* @module
*/
@DependsOn(GeneralMatrixTest.class) // See class javadoc
public final strictfp class SolverTest extends TestCase {
/**
* The tolerance threshold for this test case, which is {@value}. This value needs to be higher then the
* {@link MatrixTestCase#TOLERANCE} one because of the increased complexity of {@link Solver} operations.
*
* @see MatrixTestCase#TOLERANCE
* @see NonSquareMatrixTest#printStatistics()
*/
protected static final double TOLERANCE = 100 * MatrixTestCase.TOLERANCE;
/**
* The matrix to test.
*/
private MatrixSIS matrix;
/**
* A matrix to use as the reference implementation.
* Contains the same value than {@link #matrix}.
*/
private Matrix reference;
/**
* Initializes the {@link #matrix} and {@link #reference} matrices to random values.
*/
private void createMatrices(final int numRow, final int numCol, final Random random) {
matrix = new GeneralMatrix(numRow, numCol, false, 1);
reference = new Matrix(numRow, numCol);
for (int j=0; j<numRow; j++) {
for (int i=0; i<numCol; i++) {
final double e = random.nextDouble() * 1000;
matrix.setElement(j, i, e);
reference.set(j, i, e);
}
}
}
/**
* Tests the {@code Solver.solve(MatrixSIS, Matrix, int)} method.
*
* @throws NoninvertibleMatrixException if an unexpected error occurred while inverting the matrix.
*/
@Test
public void testSolve() throws NoninvertibleMatrixException {
final Random random;
if (MatrixTestCase.DETERMINIST) {
random = new Random(7671901444622173417L);
} else {
random = TestUtilities.createRandomNumberGenerator();
}
for (int k=0; k<MatrixTestCase.NUMBER_OF_REPETITIONS; k++) {
final int size = random.nextInt(16) + 1;
createMatrices(size, random.nextInt(16) + 1, random);
final Matrix referenceArg = this.reference;
final MatrixSIS matrixArg = this.matrix;
createMatrices(size, size, random);
final Matrix jama;
try {
jama = reference.solve(referenceArg);
} catch (RuntimeException e) {
out.println(e); // "Matrix is singular."
continue;
}
final MatrixSIS U = Solver.solve(matrix, matrixArg);
assertEqualsJAMA(jama, U, TOLERANCE);
}
}
/**
* Tests {@link Solver#inverse(org.opengis.referencing.operation.Matrix, boolean)}
* with a square matrix that contains a {@link Double#NaN} value.
*
* @throws NoninvertibleMatrixException if an unexpected error occurred while inverting the matrix.
*/
@Test
@DependsOnMethod("testSolve")
public void testInverseWithNaN() throws NoninvertibleMatrixException {
/*
* Just for making sure that our matrix is correct.
*/
matrix = Matrices.create(5, 5, new double[] {
20, 0, 0, 0, -3000,
0, -20, 0, 0, 4000,
0, 0, 0, 2, 20,
0, 0, 400, 0, 2000,
0, 0, 0, 0, 1
});
double[] expected = {
0.05, 0, 0, 0, 150,
0, -0.05, 0, 0, 200,
0, 0, 0, 0.0025, -5,
0, 0, 0.5, 0, -10,
0, 0, 0, 0, 1
};
MatrixSIS inverse = Solver.inverse(matrix, false);
assertEqualsElements(expected, 5, 5, inverse, TOLERANCE);
/*
* Set a scale factor to NaN. The translation term for the corresponding
* dimension become unknown, so it most become NaN in the inverse matrix.
*/
matrix = Matrices.create(5, 5, new double[] {
20, 0, 0, 0, -3000,
0, -20, 0, 0, 4000,
0, 0, 0, NaN, 20, // Translation is 20: can not be converted.
0, 0, 400, 0, 2000,
0, 0, 0, 0, 1
});
expected = new double[] {
0.05, 0, 0, 0, 150,
0, -0.05, 0, 0, 200,
0, 0, 0, 0.0025, -5,
0, 0, NaN, 0, NaN,
0, 0, 0, 0, 1
};
inverse = Solver.inverse(matrix, false);
assertEqualsElements(expected, 5, 5, inverse, TOLERANCE);
/*
* Set a scale factor to NaN with translation equals to 0.
* The zero value should be preserved, since 0 × any == 0
* (ignoring infinities).
*/
matrix = Matrices.create(5, 5, new double[] {
20, 0, 0, 0, -3000,
0, -20, 0, 0, 4000,
0, 0, 0, NaN, 0, // Translation is 0: should be preserved.
0, 0, 400, 0, 2000,
0, 0, 0, 0, 1
});
expected = new double[] {
0.05, 0, 0, 0, 150,
0, -0.05, 0, 0, 200,
0, 0, 0, 0.0025, -5,
0, 0, NaN, 0, 0,
0, 0, 0, 0, 1
};
inverse = Solver.inverse(matrix, false);
assertEqualsElements(expected, 5, 5, inverse, TOLERANCE);
/*
* Set a translation term to NaN. The translation should be NaN in
* the inverse matrix too, but the scale factor can still be compute.
*/
matrix = Matrices.create(5, 5, new double[] {
20, 0, 0, 0, -3000,
0, -20, 0, 0, 4000,
0, 0, 0, 2, NaN,
0, 0, 400, 0, 2000,
0, 0, 0, 0, 1
});
expected = new double[] {
0.05, 0, 0, 0, 150,
0, -0.05, 0, 0, 200,
0, 0, 0, 0.0025, -5,
0, 0, 0.5, 0, NaN,
0, 0, 0, 0, 1
};
inverse = Solver.inverse(matrix, false);
assertEqualsElements(expected, 5, 5, inverse, TOLERANCE);
}
}
|
jku-win-se/module-eer | org.module.eer.project/bundles/org.module.eer.jenetics/src/org/module/eer/jenetics/split/ff/CouplingFF.java | package org.module.eer.jenetics.split.ff;
import java.util.Iterator;
import java.util.function.Function;
import org.eclipse.emf.common.util.EList;
import org.module.eer.jenetics.config.utils.ModularizableElementUtils;
import org.module.eer.jenetics.utils.Cohesive;
import org.module.eer.mm.moduleeer.Aggregation;
import org.module.eer.mm.moduleeer.EntityType;
import org.module.eer.mm.moduleeer.Generalization;
import org.module.eer.mm.moduleeer.LinkToEntity;
import org.module.eer.mm.moduleeer.ModularizableElement;
import org.module.eer.mm.moduleeer.RelationshipType;
import org.module.eer.mm.moduleeer.procedure.AccessElement;
import org.module.eer.mm.moduleeer.procedure.Procedure;
import io.jenetics.BitChromosome;
import io.jenetics.EnumGene;
import io.jenetics.Genotype;
import io.jenetics.PermutationChromosome;
@SuppressWarnings("rawtypes")
public class CouplingFF implements Function<Genotype, Double>{
private EList<ModularizableElement> modularizableElements;
public CouplingFF(EList<ModularizableElement> modularizableElements) {
this.modularizableElements = modularizableElements;
}
@SuppressWarnings({ "unchecked" })
@Override
public Double apply(Genotype genotype) {
final PermutationChromosome<Integer> pc = (PermutationChromosome<Integer>) genotype.get(0);
final BitChromosome bc = (BitChromosome) genotype.get(1);
Cohesive cohesive = new Cohesive();
for (int i = 0; i < pc.length(); i++) {
EnumGene<Integer> enumGene = (EnumGene<Integer>) pc.get(i);
ModularizableElement element = this.modularizableElements.get(enumGene.alleleIndex());
craIndex(element, i, pc, bc, cohesive);
}
return (double) cohesive.getCoupling();
}
private void craIndex(ModularizableElement element, int position, PermutationChromosome<Integer> pc, BitChromosome bc,
Cohesive cohesive) {
//Generalizes
if (element instanceof EntityType) {
generalizesCRAIndex((EntityType) element, position, pc, bc, cohesive);
}
//RelationshipType
else if (element instanceof RelationshipType){
relationshipTypeCRAIndex((RelationshipType) element, position, pc, bc, cohesive);
}
//Procedure
else if (element instanceof Procedure) {
accessEntityTypeCRAIndex((Procedure) element, position, pc, bc, cohesive);
}
}
private void generalizesCRAIndex(EntityType currentEntityType, Integer position, PermutationChromosome<Integer> pc, BitChromosome bc,
Cohesive cohesive) {
Iterator<Generalization> itGeneralizations = currentEntityType.getGeneralizations().iterator();
while (itGeneralizations.hasNext()) {
EntityType relatedEntity = itGeneralizations.next().getEntity();
int entityTypeId = this.modularizableElements.indexOf(relatedEntity);
entityTypeCRAIndex(entityTypeId, position, pc, bc, cohesive);
}
}
private void relationshipTypeCRAIndex(RelationshipType relationshipType, Integer position, PermutationChromosome<Integer> pc, BitChromosome bc,
Cohesive cohesive) {
//Links to Entities
for (LinkToEntity linkToEntity : relationshipType.getLinksToEntities()) {
int entityTypeId = this.modularizableElements.indexOf(linkToEntity.getEntity());
entityTypeCRAIndex(entityTypeId, position, pc, bc, cohesive);
}
//Associations
for (LinkToEntity linkToEntity : relationshipType.getAssociations()) {
int entityTypeId = this.modularizableElements.indexOf(linkToEntity.getEntity());
entityTypeCRAIndex(entityTypeId, position, pc, bc, cohesive);
}
//Agreggations
for (Aggregation aggregation : relationshipType.getAggregations()) {
int relationshipTypeId = this.modularizableElements.indexOf(aggregation.getTo());
entityTypeCRAIndex(relationshipTypeId, position, pc, bc, cohesive);
}
//Generalizes
for (RelationshipType generalizeType : relationshipType.getGeneralizes()) {
int relationshipTypeId = this.modularizableElements.indexOf(generalizeType);
entityTypeCRAIndex(relationshipTypeId, position, pc, bc, cohesive);
}
}
private void accessEntityTypeCRAIndex(Procedure element, Integer position, PermutationChromosome<Integer> pc, BitChromosome bc,
Cohesive cohesive) {
for (AccessElement accessElement : element.getAccessElements()) {
int elementId = this.modularizableElements.indexOf(accessElement.getEntity());
entityTypeCRAIndex(elementId, position, pc, bc, cohesive);
}
}
private void entityTypeCRAIndex(int entityTypeId, int position, PermutationChromosome<Integer> pc, BitChromosome bc,
Cohesive cohesive) {
//Forward Search
boolean search = ModularizableElementUtils.belongsToTheSameModule(entityTypeId, position, pc, bc);
if (search == true)
cohesive.incrementCohesion(); //Cohesion
else {
cohesive.incrementCoupling(); //Cohesion
}
}
}
|
google-ar/chromium | net/cert/internal/trust_store.h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_CERT_INTERNAL_TRUST_STORE_H_
#define NET_CERT_INTERNAL_TRUST_STORE_H_
#include <vector>
#include "base/memory/ref_counted.h"
#include "net/base/net_export.h"
#include "net/cert/internal/parsed_certificate.h"
namespace net {
namespace der {
class Input;
}
// A TrustAnchor represents a trust anchor used during RFC 5280 path validation.
//
// At its core, each trust anchor has two parts:
// * Name
// * Public Key
//
// Optionally a trust anchor may contain:
// * An associated certificate (used when pretty-printing)
// * Mandatory trust anchor constraints
//
// Relationship between ParsedCertificate and TrustAnchor:
//
// For convenience trust anchors are often described using a
// (self-signed) certificate. TrustAnchor facilitates this by allowing
// construction of a TrustAnchor given a ParsedCertificate.
//
// When constructing a TrustAnchor from a certificate there are different
// interpretations for the meaning of properties other than the Subject and
// SPKI in the certificate.
//
// * CreateFromCertificateNoConstraints() -- Extracts the Subject and SPKI from
// the source certificate. ALL other information in the certificate is
// considered irrelevant during path validation.
//
// * CreateFromCertificateWithConstraints() -- Extracts the Subject and SPKI
// from the source certificate, and additionally interprets some properties of
// the source certificate as mandatory anchor constraints.
//
// Trust anchor constraints are described in more detail by RFC 5937. This
// implementation follows that description, and fixes
// "enforceTrustAnchorConstraints" to true.
class NET_EXPORT TrustAnchor : public base::RefCountedThreadSafe<TrustAnchor> {
public:
// Creates a TrustAnchor given a certificate. The ONLY parts of the
// certificate that are relevant to the resulting trust anchor are:
//
// * Subject
// * SPKI
//
// Everything else, including the source certiticate's expiration, basic
// constraints, policy constraints, etc is not used.
//
// This is the common interpretation for a trust anchor when given as a
// certificate.
static scoped_refptr<TrustAnchor> CreateFromCertificateNoConstraints(
scoped_refptr<ParsedCertificate> cert);
// Creates a TrustAnchor given a certificate. The resulting trust anchor is
// initialized using the source certificate's subject and SPKI as usual,
// however other parts of the certificate are applied as anchor constraints.
//
// The implementation matches the properties identified by RFC 5937,
// resulting in the following hodgepodge of enforcement on the source
// certificate:
//
// * Signature: No
// * Validity (expiration): No
// * Key usage: No
// * Extended key usage: No
// * Basic constraints: Yes, but only the pathlen (CA=false is accepted)
// * Name constraints: Yes
// * Certificate policies: Not currently, TODO(crbug.com/634453)
// * inhibitAnyPolicy: Not currently, TODO(crbug.com/634453)
// * PolicyConstraints: Not currently, TODO(crbug.com/634452)
//
// The presence of any other unrecognized extension marked as critical fails
// validation.
static scoped_refptr<TrustAnchor> CreateFromCertificateWithConstraints(
scoped_refptr<ParsedCertificate> cert);
der::Input spki() const;
der::Input normalized_subject() const;
// Returns the optional certificate representing this trust anchor.
// In the current implementation it will never return nullptr...
// however clients should be prepared to handle this case.
const scoped_refptr<ParsedCertificate>& cert() const;
// Returns true if the trust anchor has attached (mandatory) trust anchor
// constraints. This returns true when the anchor was constructed using
// CreateFromCertificateWithConstraints.
bool enforces_constraints() const { return enforces_constraints_; }
private:
friend class base::RefCountedThreadSafe<TrustAnchor>;
TrustAnchor(scoped_refptr<ParsedCertificate>, bool enforces_constraints);
~TrustAnchor();
scoped_refptr<ParsedCertificate> cert_;
bool enforces_constraints_ = false;
};
using TrustAnchors = std::vector<scoped_refptr<TrustAnchor>>;
// Interface for finding trust anchors.
class NET_EXPORT TrustStore {
public:
TrustStore();
virtual ~TrustStore();
// Appends the trust anchors that match |cert|'s issuer name to |*matches|.
// |cert| and |matches| must not be null.
virtual void FindTrustAnchorsForCert(
const scoped_refptr<ParsedCertificate>& cert,
TrustAnchors* matches) const = 0;
private:
DISALLOW_COPY_AND_ASSIGN(TrustStore);
};
} // namespace net
#endif // NET_CERT_INTERNAL_TRUST_STORE_H_
|
Kast0rTr0y/ao | activeobjects-integration-test/src/test/java/net/java/ao/it/TestSelectWithTableAlias.java | <filename>activeobjects-integration-test/src/test/java/net/java/ao/it/TestSelectWithTableAlias.java
package net.java.ao.it;
import net.java.ao.Entity;
import net.java.ao.EntityManager;
import net.java.ao.Preload;
import net.java.ao.Query;
import net.java.ao.test.ActiveObjectsIntegrationTest;
import net.java.ao.test.jdbc.Data;
import net.java.ao.test.jdbc.DatabaseUpdater;
import org.junit.Test;
import java.util.concurrent.Callable;
import static net.java.ao.it.TestSelectWithTableAlias.TestSelectWithTableAliasUpdater.DESCRIPTION;
import static net.java.ao.it.TestSelectWithTableAlias.TestSelectWithTableAliasUpdater.NAME;
import static org.junit.Assert.assertEquals;
@Data(TestSelectWithTableAlias.TestSelectWithTableAliasUpdater.class)
public final class TestSelectWithTableAlias extends ActiveObjectsIntegrationTest {
@Test
public void testSimpleQuery() throws Exception {
final TestEntity[] es = entityManager.find(TestEntity.class, Query.select().alias(TestEntity.class, "te"));
assertEquals(1, es.length);
checkSqlNotExecuted(new Callable<Void>() {
@Override
public Void call() throws Exception {
assertEquals(DESCRIPTION, es[0].getDescription());
return null;
}
});
}
@Test
public void testQueryWithJoin() throws Exception {
final String eIdColumn = getFieldName(TestEntity.class, "getID");
final String eDescriptionColumn = getFieldName(TestEntity.class, "getDescription");
final String oIdColumn = getFieldName(TestOtherEntity.class, "getID");
final String oNameColumn = getFieldName(TestOtherEntity.class, "getName");
final TestEntity[] es = entityManager.find(TestEntity.class, Query.select(eIdColumn + "," + eDescriptionColumn)
.alias(TestEntity.class, "e").alias(TestOtherEntity.class, "o")
.join(TestOtherEntity.class, "e." + eIdColumn + " = o." + oIdColumn)
.where("o." + oNameColumn + " = ?", NAME));
assertEquals(1, es.length);
checkSqlNotExecuted(new Callable<Void>() {
@Override
public Void call() throws Exception {
assertEquals(DESCRIPTION, es[0].getDescription());
return null;
}
});
}
@Preload("description")
public static interface TestEntity extends Entity {
String getDescription();
void setDescription(String description);
TestOtherEntity getOtherEntity();
void setOtherEntity(TestOtherEntity e);
}
public static interface TestOtherEntity extends Entity {
String getName();
void setName(String name);
}
public static final class TestSelectWithTableAliasUpdater implements DatabaseUpdater {
static final String NAME = "som-e-n-am--e";
static final String DESCRIPTION = "bla";
@Override
public void update(EntityManager entityManager) throws Exception {
entityManager.migrate(TestEntity.class, TestOtherEntity.class);
final TestOtherEntity o = entityManager.create(TestOtherEntity.class);
o.setName(NAME);
o.save();
final TestEntity e = entityManager.create(TestEntity.class);
e.setDescription(DESCRIPTION);
e.setOtherEntity(o);
e.save();
}
}
}
|
fengjixuchui/Reverse.Engineering.Engine | tests/pointer/ptr3.c | int main()
{
int a=1;
int b=2;
int c;
int *p;
int *q;
p = &a;
q = &b;
c = *p + *q;
return c;
}
|
lechium/tvOS124Headers | System/Library/Frameworks/CoreML.framework/MLModelErrorUtils.h | <reponame>lechium/tvOS124Headers<filename>System/Library/Frameworks/CoreML.framework/MLModelErrorUtils.h<gh_stars>1-10
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, August 24, 2019 at 9:45:05 PM Mountain Standard Time
* Operating System: Version 12.4 (Build 16M568)
* Image Source: /System/Library/Frameworks/CoreML.framework/CoreML
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@interface MLModelErrorUtils : NSObject
+(id)genericErrorWithString:(id)arg1 ;
+(id)featureTypeErrorWithString:(id)arg1 ;
+(id)errorWithCode:(long long)arg1 string:(id)arg2 ;
+(id)customLayerErrorWithUnderlyingError:(id)arg1 withString:(id)arg2 ;
+(id)errorWithCode:(long long)arg1 underlyingError:(id)arg2 string:(id)arg3 ;
+(id)errorWithCode:(long long)arg1 underlyingError:(id)arg2 format:(id)arg3 args:(char*)arg4 ;
+(id)errorWithCode:(long long)arg1 format:(id)arg2 args:(char*)arg3 ;
+(id)IOErrorWithString:(id)arg1 ;
@end
|
danielbairamian/RL-RL | rlbot/messages/flat/BallMaxSpeedOption.py | <reponame>danielbairamian/RL-RL
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: flat
class BallMaxSpeedOption(object):
Default = 0
Slow = 1
Fast = 2
Super_Fast = 3
|
Havoc-OS/androidprebuilts_go_linux-x86 | src/internal/x/crypto/poly1305/poly1305_test.go | <reponame>Havoc-OS/androidprebuilts_go_linux-x86<filename>src/internal/x/crypto/poly1305/poly1305_test.go<gh_stars>1000+
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package poly1305
import (
"encoding/hex"
"flag"
"testing"
"unsafe"
)
var stressFlag = flag.Bool("stress", false, "run slow stress tests")
type test struct {
in string
key string
tag string
}
func (t *test) Input() []byte {
in, err := hex.DecodeString(t.in)
if err != nil {
panic(err)
}
return in
}
func (t *test) Key() [32]byte {
buf, err := hex.DecodeString(t.key)
if err != nil {
panic(err)
}
var key [32]byte
copy(key[:], buf[:32])
return key
}
func (t *test) Tag() [16]byte {
buf, err := hex.DecodeString(t.tag)
if err != nil {
panic(err)
}
var tag [16]byte
copy(tag[:], buf[:16])
return tag
}
func testSum(t *testing.T, unaligned bool, sumImpl func(tag *[TagSize]byte, msg []byte, key *[32]byte)) {
var tag [16]byte
for i, v := range testData {
in := v.Input()
if unaligned {
in = unalignBytes(in)
}
key := v.Key()
sumImpl(&tag, in, &key)
if tag != v.Tag() {
t.Errorf("%d: expected %x, got %x", i, v.Tag(), tag[:])
}
}
}
func TestBurnin(t *testing.T) {
// This test can be used to sanity-check significant changes. It can
// take about many minutes to run, even on fast machines. It's disabled
// by default.
if !*stressFlag {
t.Skip("skipping without -stress")
}
var key [32]byte
var input [25]byte
var output [16]byte
for i := range key {
key[i] = 1
}
for i := range input {
input[i] = 2
}
for i := uint64(0); i < 1e10; i++ {
Sum(&output, input[:], &key)
copy(key[0:], output[:])
copy(key[16:], output[:])
copy(input[:], output[:])
copy(input[16:], output[:])
}
const expected = "5e3b866aea0b636d240c83c428f84bfa"
if got := hex.EncodeToString(output[:]); got != expected {
t.Errorf("expected %s, got %s", expected, got)
}
}
func TestSum(t *testing.T) { testSum(t, false, Sum) }
func TestSumUnaligned(t *testing.T) { testSum(t, true, Sum) }
func TestSumGeneric(t *testing.T) { testSum(t, false, sumGeneric) }
func TestSumGenericUnaligned(t *testing.T) { testSum(t, true, sumGeneric) }
func benchmark(b *testing.B, size int, unaligned bool) {
var out [16]byte
var key [32]byte
in := make([]byte, size)
if unaligned {
in = unalignBytes(in)
}
b.SetBytes(int64(len(in)))
b.ResetTimer()
for i := 0; i < b.N; i++ {
Sum(&out, in, &key)
}
}
func Benchmark64(b *testing.B) { benchmark(b, 64, false) }
func Benchmark1K(b *testing.B) { benchmark(b, 1024, false) }
func Benchmark64Unaligned(b *testing.B) { benchmark(b, 64, true) }
func Benchmark1KUnaligned(b *testing.B) { benchmark(b, 1024, true) }
func Benchmark2M(b *testing.B) { benchmark(b, 2097152, true) }
func unalignBytes(in []byte) []byte {
out := make([]byte, len(in)+1)
if uintptr(unsafe.Pointer(&out[0]))&(unsafe.Alignof(uint32(0))-1) == 0 {
out = out[1:]
} else {
out = out[:len(in)]
}
copy(out, in)
return out
}
|
fujaba/NetworkParser | src/javafx/de/uniks/networkparser/test/javafx/ApplicationTest.java | <reponame>fujaba/NetworkParser
package de.uniks.networkparser.test.javafx;
import de.uniks.networkparser.ext.SimpleController;
import de.uniks.networkparser.ext.javafx.ModelListenerFactory;
import de.uniks.networkparser.test.model.GUIEntity;
import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
public class ApplicationTest extends Application {
private static GUIEntity data = new GUIEntity();
public static void main(String[] args) throws Exception {
launch(args);
}
private TextField field;
@Override
public void start(Stage primaryStage) throws Exception {
SimpleController controller = SimpleController.create(primaryStage);
System.out.println(primaryStage);
VBox root=new VBox();
HBox box=new HBox();
Label label = new Label("Button has been clicked: ");
Label dataLabel = new Label();
dataLabel.setId(GUIEntity.PROPERTY_NUMBER);
box.getChildren().addAll(label, dataLabel);
dataLabel.setTextAlignment(TextAlignment.RIGHT);
// ModelListenerFactory.create(dataLabel, data, GUIEntity.PROPERTY_NUMBER);
ModelListenerFactory.create(dataLabel, data);
field = new TextField();
// TEST SIMPLE
ModelListenerFactory.create(field, data, GUIEntity.PROPERTY_NUMBER);
Button button = new Button("Clicke Me");
root.getChildren().addAll(box, field, button);
// controller.withIcon("de.uniks.networkparser.ext.javafx.dialog.JavaCup32.png");
controller.withIcon("dialog/JavaCup32.png", SimpleController.class);
controller.showTrayIcon();
controller.show(root);
// primaryStage.show();
}
}
|
FSchiltz/RawParser | Source/RawSpeed/parsers/FiffParser.h | <gh_stars>10-100
/*
RawSpeed - RAW file decoder.
Copyright (C) 2017 <NAME>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include "parsers/RawParser.h" // for RawParser
#include "tiff/TiffIFD.h" // for TiffRootIFDOwner
#include <memory> // for unique_ptr
namespace rawspeed {
class Buffer;
class CameraMetaData;
class RawDecoder;
class FiffParser final : public RawParser {
TiffRootIFDOwner rootIFD;
public:
explicit FiffParser(const Buffer* input);
void parseData();
std::unique_ptr<RawDecoder>
getDecoder(const CameraMetaData* meta = nullptr) override;
};
} // namespace rawspeed
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.