hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
7cdb279ea8b260171d679c5966e7796492bdba53 | 836 | package com.shura.im.client.service.impl.command;
import com.shura.im.client.component.ClientInfo;
import com.shura.im.client.service.EchoService;
import com.shura.im.client.service.InnerCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author: Garvey
* @Created: 2022/1/12
* @Description:
*/
@Service
public class EchoInfoCommand implements InnerCommand {
@Autowired
private ClientInfo clientInfo;
@Autowired
private EchoService echoService;
@Override
public void process(String msg) {
echoService.echo("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
echoService.echo("client info={}", clientInfo.get().getUserName());
echoService.echo("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
| 27.866667 | 77 | 0.643541 |
3a23a7a88052aa1ae0564123bb3cfb0cb9781edf | 1,685 | package uk.offtopica.addressutil.bitcoin;
import org.bouncycastle.jcajce.provider.digest.SHA256;
import java.util.Arrays;
public class BitcoinBase58CheckCodec extends BitcoinBase58Codec {
private static final int CHECKSUM_BYTES = 4;
@Override
public byte[] decode(String input) throws BitcoinBase58Exception {
byte[] decoded = super.decode(input);
if (decoded.length < CHECKSUM_BYTES) {
throw new BitcoinBase58Exception("Input too short");
}
byte[] data = Arrays.copyOfRange(decoded, 0, decoded.length - CHECKSUM_BYTES);
byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - CHECKSUM_BYTES, decoded.length);
SHA256.Digest sha256 = new SHA256.Digest();
byte[] dataHash = sha256.digest(data);
sha256.reset();
dataHash = sha256.digest(dataHash);
byte[] computedChecksum = Arrays.copyOfRange(dataHash, 0, CHECKSUM_BYTES);
if (!Arrays.equals(checksum, computedChecksum)) {
throw new BitcoinBase58Exception("Bad checksum");
}
return data;
}
@Override
public String encode(byte[] data) {
SHA256.Digest sha256 = new SHA256.Digest();
byte[] dataHash = sha256.digest(data);
sha256.reset();
dataHash = sha256.digest(dataHash);
byte[] checksum = Arrays.copyOfRange(dataHash, 0, CHECKSUM_BYTES);
// return base58(data || checksum)
byte[] concat = new byte[data.length + checksum.length];
System.arraycopy(data, 0, concat, 0, data.length);
System.arraycopy(checksum, 0, concat, data.length, checksum.length);
return super.encode(concat);
}
}
| 33.7 | 103 | 0.658754 |
b5ed8b4512c6d5e4de7e2eb48eb96cb9c36bb78a | 6,832 | /*
* ===========================================
* Java Pdf Extraction Decoding Access Library
* ===========================================
*
* Project Info: http://www.idrsolutions.com
* Help section for developers at http://www.idrsolutions.com/support/
*
* (C) Copyright 1997-2015 IDRsolutions and Contributors.
*
* This file is part of JPedal/JPDF2HTML5
*
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.1 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* ---------------
* S.java
* ---------------
*/
package org.jpedal.parser.shape;
import java.awt.*;
import java.awt.geom.Area;
import javafx.scene.shape.Path;
import org.jpedal.objects.GraphicsState;
import org.jpedal.objects.PdfShape;
import org.jpedal.parser.Cmd;
import org.jpedal.parser.ParserOptions;
import org.jpedal.render.BaseDisplay;
import org.jpedal.render.DynamicVectorRenderer;
public class S {
public static Shape execute(final boolean isLowerCase, final GraphicsState gs, final PdfShape currentDrawShape, final DynamicVectorRenderer current, final ParserOptions parserOptions) {
final boolean useJavaFX=parserOptions.useJavaFX();
final boolean renderPage=parserOptions.isRenderPage();
Shape currentShape=null;
if(parserOptions.isLayerVisible()){
//close for s command
if (isLowerCase) {
currentDrawShape.closeShape();
}
Path fxPath=null;
float realLineWidth=-1;
/**
* fx alternative
*/
if(useJavaFX){
fxPath=currentDrawShape.getPath();
}else {
currentShape = currentDrawShape.generateShapeFromPath(gs.CTM, gs.getLineWidth(), Cmd.S, current.getType());
if (currentDrawShape.adjustLineWidth()) {
gs.setLineWidth(0.6f);//0.6f because the scaling will multiply by 1.527 (we want the final value < 1)
}
if (currentShape != null) {
Rectangle bounds;//=currentShape.getBounds();
// System.out.println("S bounds="+bounds+" "+" "+gs.CTM[0][0]+" "+gs.CTM[0][1]+" "+gs.CTM[1][0]+" "+gs.CTM[1][1]);
//allow for tiny line with huge width to draw a line (see baseline_screens/14jan/Pages from FDB-B737-FRM_nowatermark.pdf)
if(1==2 && gs.CTM[0][0]<=1 && gs.CTM[1][1]<=1 && gs.getLineWidth()>30 && bounds.height==1 && (bounds.width==1 || bounds.width>4)){
realLineWidth=gs.getLineWidth();
final float scaledThickness=realLineWidth*gs.CTM[1][1];
final Rectangle current_path = new Rectangle(bounds.x,(int)(bounds.y-(scaledThickness/2)),bounds.width,(int)(scaledThickness));
currentShape=new Area(current_path);
// System.out.println("use "+current_path+" "+bounds.width+" "+realLineWidth);
gs.setLineWidth(1f);
}
}
}
boolean hasShape=currentShape!=null || fxPath!=null;
if(hasShape){ //allow for the odd combination of crop with zero size
final Area crop=gs.getClippingShape();
if(crop!=null && (crop.getBounds().getWidth()==0 || crop.getBounds().getHeight()==0 )){
currentShape=null;
fxPath=null;
hasShape=false;
}
}
if(hasShape){ //allow for the odd combination of f then S
//fix forSwing. (not required in HTML/SVG
//Alter to only check bounds <1 instead of <=1 for fedexLabelAM.pdf
if(currentShape!=null && currentShape.getBounds().getWidth()<1 && !BaseDisplay.isHTMLorSVG(current)) {// && currentGraphicsState.getLineWidth()<=1.0f){
currentShape=currentShape.getBounds2D();
}
//save for later
if (renderPage){
gs.setStrokeColor( gs.strokeColorSpace.getColor());
gs.setNonstrokeColor( gs.nonstrokeColorSpace.getColor());
gs.setFillType(GraphicsState.STROKE);
if(useJavaFX){
current.drawShape(fxPath,gs, Cmd.S);
}else{
current.drawShape(currentShape,gs, Cmd.S);
}
if(realLineWidth!=-1){
gs.setLineWidth(realLineWidth);
}
}
}
if(currentDrawShape.isClip()){
//<start-adobe>
if(useJavaFX) {
gs.updateClip(fxPath);
} else
//<end-adobe>
{
gs.updateClip(new Area(currentShape));
}
// if(formLevel==0){
// final int pageNum=parserOptions.getPageNumber();
//
// gs.checkWholePageClip(pageData.getMediaBoxHeight(pageNum)+pageData.getMediaBoxY(pageNum));
// }
//save for later
// if (renderPage){
// if(useJavaFX){
// current.drawClip(gs,defaultClip,false) ;
// }else{
// current.drawClip(gs,defaultClip,false) ;
// }
// }
}
}
//always reset flag
currentDrawShape.setClip(false);
currentDrawShape.resetPath(); // flush all path ops stored
return currentShape;
}
}
| 38.59887 | 189 | 0.506879 |
ea7e2ea6d2d6d60f77f3797831c5da6c021b0b1f | 544 | package com.example.service.business;
import com.example.service.RandomNumberGenerator;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
@Service
@ServiceQuality(ServiceQualityLevel.SECURE)
public class SecureRandomNumberGenerator implements RandomNumberGenerator {
private SecureRandom random = new SecureRandom();
@Override
public int generate(int min, int max) {
System.err.println("SecureRandomNumberGenerator::generate");
return random.nextInt(max - min + 1) + min;
}
}
| 28.631579 | 75 | 0.770221 |
a306170b6433ac4323aa91555d4878b446252553 | 2,071 | package com.my.project.redis;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.junit.*;
import redis.embedded.RedisServer;
import java.io.IOException;
import java.net.ServerSocket;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class LettuceTest {
private RedisClient client;
private StatefulRedisConnection<String, String> connection;
private RedisCommands<String, String> commands;
private static RedisServer server;
private static int PORT;
private static final String HOSTNAME = "127.0.0.1";
private static final String PASSWORD = "123456";
@BeforeClass
public static void beforeClass() throws IOException {
PORT = randomPort();
server = RedisServer.builder().port(PORT)
.setting("bind " + HOSTNAME)
.setting("requirepass " + PASSWORD)
.build();
server.start();
}
@AfterClass
public static void afterClass() {
server.stop();
}
@Before
public void before() {
this.client = RedisClient.create(RedisURI.builder()
.withPassword(PASSWORD)
.withHost(HOSTNAME)
.withPort(PORT)
.withDatabase(0).build());
this.connection = this.client.connect();
this.commands = this.connection.sync();
}
@After
public void after() {
this.connection.close();
this.client.shutdown();
}
@Test
public void testSetGetDel() {
String key = "name";
String value = "yang";
this.commands.set(key, value);
assertEquals(value, this.commands.get(key));
this.commands.del(key);
assertNull(this.commands.get(key));
}
private static Integer randomPort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
}
| 27.613333 | 63 | 0.636408 |
9014cdb130af2eaca51fdc2f6dff1608a83104a4 | 21,160 | package net.falappa.wwind.layers;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.event.SelectEvent;
import gov.nasa.worldwind.geom.LatLon;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.geom.Sector;
import gov.nasa.worldwind.layers.RenderableLayer;
import gov.nasa.worldwind.render.AnnotationAttributes;
import gov.nasa.worldwind.render.BasicShapeAttributes;
import gov.nasa.worldwind.render.GlobeAnnotation;
import gov.nasa.worldwind.render.Material;
import gov.nasa.worldwind.render.SurfaceCircle;
import gov.nasa.worldwind.render.SurfacePolygon;
import gov.nasa.worldwind.render.SurfaceQuad;
import gov.nasa.worldwind.render.SurfaceSector;
import gov.nasa.worldwind.render.SurfaceShape;
import java.awt.Color;
import java.awt.Insets;
import java.awt.Point;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.prefs.Preferences;
import net.falappa.prefs.PrefRestorable;
import net.falappa.wwind.utils.WWindUtils;
/**
* A WorldWind layer (<tt>RenderableLayer</tt> implementation) managing a set of surface shapes (polygons, polylines, circles, sectors and
* quads).
* <p>
* Each shape is identified by a literal name. All shapes inherit a set of layer wide attributes (color and opacity) that can be overridden
* shape by shape and optionally reset.
* <p>
* The layer also manages shapes mouse click selection and highlighting with an annotation (one at a time). Selection listeners can be
* registered to be notified of shape selection changes.
* <p>
* The layer offers other useful methods such as "flying to" and programatically highlighting a shape.
*
* @author Alessandro Falappa
*/
public class SurfShapesLayer extends RenderableLayer implements ShapeSelectionSource, SurfShapeLayer, PrefRestorable {
private static final float HIGHL_INSIDE_OPACITY = 0.7f;
private static final float NORM_INSIDE_OPACITY = 0.4f;
private static final String PROPERTY_SELECTION = "shapeSelection";
private final BasicShapeAttributes attr = new BasicShapeAttributes();
private final BasicShapeAttributes attrHigh = new BasicShapeAttributes();
private final HashMap<String, SurfaceShape> shapesById = new HashMap<>();
private final GlobeAnnotation popupAnnotation = new GlobeAnnotation("", Position.ZERO);
private WorldWindow wwd;
private SurfaceShape prevPopupShape;
private String highlightEvent = SelectEvent.LEFT_CLICK;
private boolean highlightingEnabled = true;
private boolean showAnnotation = true;
/**
* Initializing constructor.
* <p>
* Default color orange outline and translucent orange fill, black outline and translucent white highlight color.
*
* @param name the name of this layer
*/
public SurfShapesLayer(String name) {
// properties of layer
setName(name);
setEnabled(true);
// painting attributes for shapes
attr.setOutlineMaterial(Material.ORANGE);
attr.setOutlineWidth(1.5);
Material intMat = new Material(Color.ORANGE.brighter().brighter());
attr.setInteriorMaterial(intMat);
attr.setInteriorOpacity(NORM_INSIDE_OPACITY);
// painting attributes for hihglighted shapes
attrHigh.setOutlineMaterial(Material.BLACK);
attrHigh.setOutlineWidth(2);
attrHigh.setInteriorMaterial(Material.WHITE);
attrHigh.setInteriorOpacity(HIGHL_INSIDE_OPACITY);
// popup annotation attributes
AnnotationAttributes attrAnno = new AnnotationAttributes();
attrAnno.setAdjustWidthToText(AVKey.SIZE_FIT_TEXT);
attrAnno.setFrameShape(AVKey.SHAPE_RECTANGLE);
attrAnno.setCornerRadius(3);
attrAnno.setDrawOffset(new Point(0, 8));
attrAnno.setLeaderGapWidth(8);
attrAnno.setTextColor(Color.BLACK);
attrAnno.setBackgroundColor(new Color(1f, 1f, 1f, .85f));
attrAnno.setBorderColor(new Color(0xababab));
attrAnno.setInsets(new Insets(3, 3, 3, 3));
attrAnno.setVisible(false);
popupAnnotation.setAttributes(attrAnno);
popupAnnotation.setAlwaysOnTop(true);
addRenderable(popupAnnotation);
}
@Override
public void linkTo(WorldWindow wwd) {
this.wwd = wwd;
wwd.addSelectListener(this);
}
@Override
public void detach() {
wwd.removeSelectListener(this);
}
@Override
public void dispose() {
detach();
super.dispose();
}
@Override
public boolean isHighlightingEnabled() {
return highlightingEnabled;
}
@Override
public void setHighlightingEnabled(boolean highlightingEnabled) {
this.highlightingEnabled = highlightingEnabled;
// hide popup and clear highlighed object when disabling
if (!highlightingEnabled) {
popupAnnotation.getAttributes().setVisible(false);
if (prevPopupShape != null) {
prevPopupShape.setHighlighted(false);
}
wwd.redraw();
}
}
@Override
public boolean isShowAnnotation() {
return showAnnotation;
}
@Override
public void setShowAnnotation(boolean showAnnotation) {
this.showAnnotation = showAnnotation;
if (!showAnnotation) {
popupAnnotation.getAttributes().setVisible(false);
if (wwd != null) {
wwd.redraw();
}
}
}
@Override
public String getHighlightEvent() {
return highlightEvent;
}
@Override
public void setHighlightEvent(String highlightEvent) {
if (highlightEvent.equals(SelectEvent.LEFT_CLICK) || highlightEvent.equals(SelectEvent.LEFT_DOUBLE_CLICK) || highlightEvent.equals(
SelectEvent.RIGHT_CLICK)) {
this.highlightEvent = highlightEvent;
} else {
throw new IllegalArgumentException("Unsupported select event for highlighting!");
}
}
@Override
public Color getColor() {
return attr.getOutlineMaterial().getDiffuse();
}
@Override
public void setColor(Color col) {
attr.setOutlineMaterial(new Material(col));
attr.setInteriorMaterial(new Material(col.brighter().brighter()));
}
@Override
public void setOpacity(double opacity) {
super.setOpacity(opacity);
attr.setOutlineOpacity(opacity);
attr.setInteriorOpacity(NORM_INSIDE_OPACITY * opacity);
}
@Override
public Color getHighlightColor() {
return attrHigh.getOutlineMaterial().getDiffuse();
}
@Override
public void setHighlightColor(Color col) {
attrHigh.setOutlineMaterial(new Material(col));
attrHigh.setInteriorMaterial(new Material(col.brighter().brighter()));
}
/**
* Returns the current outline highlighting color.
*
* @return the current color
*/
public Color getHighlightOutlineColor() {
return attrHigh.getOutlineMaterial().getDiffuse();
}
/**
* Set the current outline highlighting color.
*
* @param col the new color
*/
public void setHighlightOutlineColor(Color col) {
attrHigh.setOutlineMaterial(new Material(col));
}
/**
* Returns the current fill highlighting color.
*
* @return the current color
*/
public Color getHighlightFillColor() {
return attrHigh.getInteriorMaterial().getDiffuse();
}
/**
* Set the current fill highlighting color.
*
* @param col the new color
*/
public void setHighlightFillColor(Color col) {
attrHigh.setInteriorMaterial(new Material(col));
}
@Override
public double getHighlightOpacity() {
return attrHigh.getOutlineOpacity();
}
@Override
public void setHighlightOpacity(double opacity) {
attrHigh.setOutlineOpacity(opacity);
attrHigh.setInteriorOpacity(HIGHL_INSIDE_OPACITY * opacity);
}
/**
* Adds or substitutes a named circular surface shape.
*
* @param lat center latitude in decimal degrees
* @param lon center longitude in decimal degrees
* @param rad radius in meters
* @param id the shape identifier
*/
public void addSurfCircle(double lat, double lon, double rad, String id) {
SurfaceCircle shape = new SurfaceCircle(attr, LatLon.fromDegrees(lat, lon), rad);
if (id != null) {
shape.setValue(AVKey.HOVER_TEXT, id);
}
//set this layer as custom property of the shape
shape.setValue(AVKey.LAYER, this);
SurfaceShape old = shapesById.put(id, shape);
if (old != null) {
removeRenderable(old);
}
addRenderable(shape);
}
/**
* Adds or substitutes a named polygonal surface shape.
*
* @param coords the points of the polygon outer boundary
* @param id the shape identifier
*/
public void addSurfPoly(List<LatLon> coords, String id) {
SurfacePolygon shape = new SurfacePolygon(coords);
shape.setAttributes(attr);
shape.setHighlightAttributes(attrHigh);
if (id != null) {
shape.setValue(AVKey.HOVER_TEXT, id);
}
//set this layer as custom property of the shape
shape.setValue(AVKey.LAYER, this);
// put in map removing existing shape with same id if needed
SurfaceShape old = shapesById.put(id, shape);
if (old != null) {
removeRenderable(old);
}
addRenderable(shape);
}
/**
* Adds or substitutes a named polygonal surface shape with holes.
* <p>
* Each boundary is a list of LatLon points. Should have at least two boundaries.
*
* @param boundaries a list of poligon boundaries, first is outer then one or more inner (holes)
* @param id the shape identifier
*/
public void addSurfPoly(String id, List<List<LatLon>> boundaries) {
if (boundaries.isEmpty()) {
return;
}
if (boundaries.size() == 1) {
addSurfPoly(boundaries.get(0), id);
} else {
SurfacePolygon shape = new SurfacePolygon(boundaries.get(0));
for (int i = 1; i < boundaries.size(); i++) {
shape.addInnerBoundary(boundaries.get(i));
}
shape.setAttributes(attr);
shape.setHighlightAttributes(attrHigh);
if (id != null) {
shape.setValue(AVKey.HOVER_TEXT, id);
}
//set this layer as custom property of the shape
shape.setValue(AVKey.LAYER, this);
// put in map removing existing shape with same id if needed
SurfaceShape old = shapesById.put(id, shape);
if (old != null) {
removeRenderable(old);
}
addRenderable(shape);
}
}
/**
* Adds or substitutes a named regular quadrilateral surface shape.
*
* @param lat center latitude in decimal degrees
* @param lon center longitude in decimal degrees
* @param w width in meters
* @param h height in meters
* @param id the shape identifier
*/
public void addSurfQuad(double lat, double lon, double w, double h, String id) {
SurfaceQuad shape = new SurfaceQuad(attr, LatLon.fromDegrees(lat, lon), w, h);
shape.setHighlightAttributes(attrHigh);
if (id != null) {
shape.setValue(AVKey.HOVER_TEXT, id);
}
//set this layer as custom property of the shape
shape.setValue(AVKey.LAYER, this);
SurfaceShape old = shapesById.put(id, shape);
if (old != null) {
removeRenderable(old);
}
addRenderable(shape);
}
/**
* Adds or substitutes a named lat lon range (sector) surface shape.
*
* @param minlat minimum latitude in decimal degrees
* @param minlon minimum longitude in decimal degrees
* @param maxlat maximum latitude in decimal degrees
* @param maxlon maximum longitude in decimal degrees
* @param id the shape identifier
*/
public void addSurfSect(double minlat, double minlon, double maxlat, double maxlon, String id) {
SurfaceSector shape = new SurfaceSector(attr, Sector.fromDegrees(minlat, maxlat, minlon, maxlon));
shape.setPathType(AVKey.LINEAR);
shape.setHighlightAttributes(attrHigh);
if (id != null) {
shape.setValue(AVKey.HOVER_TEXT, id);
}
//set this layer as custom property of the shape
shape.setValue(AVKey.LAYER, this);
SurfaceShape old = shapesById.put(id, shape);
if (old != null) {
removeRenderable(old);
}
addRenderable(shape);
}
@Override
public SurfaceShape getSurfShape(String id) throws NoSuchShapeException {
if (!shapesById.containsKey(id)) {
throw new NoSuchShapeException(String.format("No such shape: %s", id));
}
return shapesById.get(id);
}
/**
* Accessor for a named polygonal surface shape.
*
* @param id the shape identifier
* @return the requested shape or null if the shape was not a polygon
* @throws NoSuchShapeException if no shape with the given name exists
*/
public SurfacePolygon getSurfPoly(String id) throws NoSuchShapeException {
if (!shapesById.containsKey(id)) {
throw new NoSuchShapeException(String.format("No such shape: %s", id));
}
final SurfaceShape ret = shapesById.get(id);
return ret instanceof SurfacePolygon ? (SurfacePolygon) ret : null;
}
@Override
public void removeSurfShape(String id) throws NoSuchShapeException {
if (!shapesById.containsKey(id)) {
throw new NoSuchShapeException(String.format("No such shape: %s", id));
}
final SurfaceShape ret = shapesById.remove(id);
removeRenderable(ret);
}
@Override
public int getNumShapes() {
return getNumRenderables() - 1;
}
@Override
public void setSurfShapeColor(String id, Color col, double opacity) throws NoSuchShapeException {
SurfaceShape shape = getSurfShape(id);
BasicShapeAttributes newAttr = new BasicShapeAttributes(attr);
newAttr.setOutlineMaterial(new Material(col));
newAttr.setInteriorMaterial(new Material(col.brighter().brighter()));
newAttr.setOutlineOpacity(opacity);
newAttr.setInteriorOpacity(NORM_INSIDE_OPACITY * opacity);
shape.setAttributes(newAttr);
}
@Override
public void resetSurfShapeColor(String id) throws NoSuchShapeException {
SurfaceShape shape = getSurfShape(id);
shape.setAttributes(attr);
}
@Override
public void resetAllSurfShapeColors() {
for (SurfaceShape shp : shapesById.values()) {
shp.setAttributes(attr);
}
}
@Override
public void setSurfShapeVisible(String id, boolean flag) throws NoSuchShapeException {
SurfaceShape shape = getSurfShape(id);
shape.setVisible(flag);
}
@Override
public void flyToHiglhlightShape(String id, boolean fireEvent) throws NoSuchShapeException {
if (!shapesById.containsKey(id)) {
throw new NoSuchShapeException(String.format("No such shape: %s", id));
}
final SurfaceShape shape = shapesById.get(id);
WWindUtils.flyToObjects(wwd, Arrays.asList(shape));
internalHighlight(shape, fireEvent, true);
}
@Override
public void flyToShape(String id) throws NoSuchShapeException {
if (!shapesById.containsKey(id)) {
throw new NoSuchShapeException(String.format("No such shape: %s", id));
}
WWindUtils.flyToObjects(wwd, Arrays.asList(shapesById.get(id)));
}
@Override
public void highlightShape(String id, boolean fireEvent) throws NoSuchShapeException {
if (!shapesById.containsKey(id)) {
throw new NoSuchShapeException(String.format("No such shape: %s", id));
}
internalHighlight(shapesById.get(id), fireEvent, true);
}
@Override
public void clearHighlight(boolean fireEvent) {
if (prevPopupShape != null) {
String shpId = (String) prevPopupShape.getValue(AVKey.HOVER_TEXT);
// hide annotation and de-highlight
popupAnnotation.getAttributes().setVisible(false);
prevPopupShape.setHighlighted(false);
// forget previous highlighted shape and fire deselection event
prevPopupShape = null;
if (fireEvent) {
firePropertyChange(new PropertyChangeEvent(this, PROPERTY_SELECTION, shpId, null));
}
}
}
@Override
public void removeAllShapes() {
super.removeAllRenderables();
shapesById.clear();
// re-add the hidden notation
popupAnnotation.getAttributes().setVisible(false);
addRenderable(popupAnnotation);
}
@Override
public void removeAllRenderables() {
throw new IllegalStateException("Use removeAllShapes() method instead!");
}
/**
* Implementation of WorldWind selection API.
*
* @param event selection event
*/
@Override
public void selected(SelectEvent event) {
// short circuit exit if highlighting is not enabled
if (!highlightingEnabled) {
return;
}
if (event.getEventAction().equals(highlightEvent)) {
final Object topObject = event.getTopObject();
if (topObject instanceof SurfaceShape) {
SurfaceShape shape = (SurfaceShape) topObject;
final Object layer = shape.getValue(AVKey.LAYER);
if (layer instanceof SurfShapesLayer) {
SurfShapesLayer sl = (SurfShapesLayer) layer;
if (sl.getName().equals(getName())) {
internalHighlight(shape, true, false);
}
wwd.redraw();
}
}
}
}
@Override
public void addShapeSelectionListener(PropertyChangeListener listener) {
getChangeSupport().addPropertyChangeListener(PROPERTY_SELECTION, listener);
}
@Override
public void removeShapeSelectionListener(PropertyChangeListener listener) {
getChangeSupport().removePropertyChangeListener(PROPERTY_SELECTION, listener);
}
@Override
public PropertyChangeListener[] getShapeSelectionListeners() {
return getChangeSupport().getPropertyChangeListeners(PROPERTY_SELECTION);
}
@Override
public void loadPrefs(Preferences baseNode) {
// TODO loading from preferences
}
@Override
public void storePrefs(Preferences baseNode) {
// TODO storing to preferences
}
// manages change of attributes for highlighting, annotation bubble toggle, event firing
private void internalHighlight(SurfaceShape shape, boolean fireEvent, boolean noDeselect) {
if (!highlightingEnabled) {
return;
}
String shpId = (String) shape.getValue(AVKey.HOVER_TEXT);
// if annotation visible and same shape
if (shape.equals(prevPopupShape) && shape.isHighlighted()) {
if (!noDeselect) {
// hide annotation and de-highlight
popupAnnotation.getAttributes().setVisible(false);
shape.setHighlighted(false);
// forget previous highlighted shape and fire deselection event
prevPopupShape = null;
if (fireEvent) {
firePropertyChange(new PropertyChangeEvent(this, PROPERTY_SELECTION, shpId, null));
}
}
} else {
if (showAnnotation) {
// find shape centroid
final Sector boundingSector = Sector.boundingSector(shape.getLocations(wwd.getModel().getGlobe()));
Position centroid = new Position(boundingSector.getCentroid(), 0d);
// prepare and show annotation
popupAnnotation.setText(shpId);
popupAnnotation.setPosition(centroid);
popupAnnotation.getAttributes().setVisible(true);
}
// highlight shape
shape.setHighlighted(true);
if (prevPopupShape != null) {
// de-highlight previous shape and fire deselection event
prevPopupShape.setHighlighted(false);
if (fireEvent) {
firePropertyChange(new PropertyChangeEvent(this, PROPERTY_SELECTION, prevPopupShape.getValue(AVKey.HOVER_TEXT), shpId));
}
} else if (fireEvent) {
// fire event only
firePropertyChange(new PropertyChangeEvent(this, PROPERTY_SELECTION, null, shpId));
}
// remember shape
prevPopupShape = shape;
}
}
}
| 35.864407 | 140 | 0.646645 |
ac4652aeff284bad94bbb081d19452ea40f298b6 | 224 | package com.example.mymediaplayer.interfaces;
/**
* Created by hjz on 2016/10/2.
*/
public interface Constants {
long secondMillis=1000;
long minuteMillis=60*secondMillis;
long hourMillis=60*minuteMillis;
}
| 17.230769 | 45 | 0.727679 |
498dd28ac2d7a07f4d7c38a6cc82a1d3462f023c | 14,584 | /**
* Copyright 2013 52°North Initiative for Geospatial Open Source Software GmbH
*
* 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.n52.sir.xml.impl;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import net.opengis.sensorML.x101.AbstractProcessType;
import net.opengis.sensorML.x101.SensorMLDocument;
import net.opengis.sensorML.x101.SystemType;
import net.sf.saxon.lib.StandardErrorListener;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.n52.oss.sir.SMLConstants;
import org.n52.oss.sir.api.SirSensorDescription;
import org.n52.oss.sir.api.SirXmlSensorDescription;
import org.n52.oss.util.XmlTools;
import org.n52.sir.xml.ITransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import x0.oasisNamesTcEbxmlRegrepXsdRim3.RegistryPackageDocument;
import com.google.inject.Inject;
import com.google.inject.name.Named;
/**
*
* A transformer for the transformation of SensorML (http://www.opengeospatial.org/standards/sensorml)
* documents to a set of ebRIM (http://www.oasis-open.org/specs/index.php#ebxmlrimv3.0) ExtrinsicObjects
* according the the SensorML Profile for Discovery (Ongoing work, see OWS-6 SensorML Profile for Discovery
* Engineering Report, OGC 09-033 (http://portal.opengeospatial.org/files/?artifact_id=33284)).
*
* The transformation is based on the file {@link SMLtoEbRIMTransformer#TRANSFORMATION_FILE_NAME} and uses
* XSLT 2.0 (http://www.w3.org/TR/xslt20/).
*
* @author Daniel Nüst (d.nuest@52north.org)
*
*/
public class SMLtoEbRIMTransformer implements ITransformer {
/**
* Class catches {@link SAXParseException}s and is used during validated transformation.
*/
protected static class ParseExceptionHandler extends DefaultHandler {
@SuppressWarnings("synthetic-access")
@Override
public void error(SAXParseException spe) throws SAXException {
log.error(" [ParseExceptionHandler] SAXParseException error: " + spe.getMessage());
}
@SuppressWarnings("synthetic-access")
@Override
public void warning(SAXParseException spe) throws SAXException {
log.error(" [ParseExceptionHandler] SAXParseException warning: " + spe);
}
}
private static final String INDENT_OUTPUT_PROPERTY_VALUE = "yes";
private static Logger log = LoggerFactory.getLogger(SMLtoEbRIMTransformer.class);
private static TransformerFactory tFactory = TransformerFactory.newInstance();
public static final String TRANSFORMATION_FILE_NAME = "SensorML-to-ebRIM.xsl";
public static final Object TRANSFORMED_DOCS_LISTING_ELEMENT_AFTER = "</rim:RegistryObjectList>";
public static final Object TRANSFORMED_DOCS_LISTING_ELEMENT_BEFORE = "<rim:RegistryObjectList xmlns:rim=\"urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0\">";
private Transformer transformer;
private boolean validating = ITransformer.IS_VALIDATING_DEFAULT;
private StreamSource xsltSource;
/**
*
* @param xsltDir
* the directory with the XSLT transformation files needed
* @param validate
* validation of inputs and outputs
* @throws InstantiationError
*/
@Inject
public SMLtoEbRIMTransformer(@Named("oss.transform.xsltDir")
String xsltDir, @Named("oss.transform.validate")
boolean validate) throws InstantiationError {
this.validating = validate;
String path = xsltDir + TRANSFORMATION_FILE_NAME;
// http://stackoverflow.com/questions/3699860/resolving-relative-paths-when-loading-xslt-files
try (InputStream is = SMLtoEbRIMTransformer.class.getResourceAsStream(path);) {
if (is == null) {
log.error("Could not load resource stream from path {}", path);
return;
}
tFactory.setErrorListener(new LogErrorListener());
// URIResolver uriResolver = tFactory.getURIResolver();
ClasspathResourceURIResolver ur = new ClasspathResourceURIResolver(xsltDir);
tFactory.setURIResolver(ur);
log.debug("Loading transformation file from path: {}, is: {}, with URI resolver: {}", path, is, ur);
this.xsltSource = new StreamSource(is);
this.transformer = tFactory.newTransformer(this.xsltSource);
this.transformer.setOutputProperty(OutputKeys.INDENT, INDENT_OUTPUT_PROPERTY_VALUE);
this.transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
}
catch (Exception e) {
log.error("Could not create transformer, path: {}", path, e);
throw new InstantiationError("Could not instantiate Transformer from file " + this.xsltSource);
}
log.info("NEW {}", this);
}
/**
*
* Method does the actual transformation of the given SensorML document: a {@link DOMSource} is created
* and the transformation is writes to a {@link StringWriter}. The outpot is parsed as a
* {@link RegistryPackageDocument} and returned.
*
* @param smlDoc
* @return
* @throws XmlException
* @throws TransformerException
* @throws IOException
*/
private RegistryPackageDocument actualTransform(SensorMLDocument smlDoc) throws XmlException,
TransformerException,
IOException {
log.debug("Start transforming SensorMLDocument: {}", XmlTools.inspect(smlDoc));
// encapsulate input document in a Source
// Source input = new DOMSource(smlDoc.getDomNode());
// transform input to DOM Level 3 capable instance
// https://issues.apache.org/jira/browse/XMLBEANS-100
try (StringWriter sw = new StringWriter();) {
// trying to wrap in DOM 3 Object > NOT WORKING
/*
* Document inputDoc = (Document) smlDoc.getDomNode(); DocumentBuilder builder =
* DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document =
* builder.newDocument(); Node newRoot = document.importNode(inputDoc.getDocumentElement(), true);
* document.appendChild(newRoot); Source input = new DOMSource(document); StreamResult output =
* new StreamResult(sw);
*/
// do not use DOM at all:
StreamSource input = new StreamSource(smlDoc.newReader());
// do the transformation
StreamResult output = new StreamResult(sw);
this.transformer.transform(input, output);
// create output document
String outputString = output.getWriter().toString();
RegistryPackageDocument regPackDoc = RegistryPackageDocument.Factory.parse(outputString);
// clean up
input = null;
output = null;
outputString = null;
if (this.validating) {
if ( !regPackDoc.validate()) {
log.warn("Created RegistryPackageDocument is not valid! {}", XmlTools.inspect(regPackDoc));
}
}
log.debug("Finished transformation: {}", XmlTools.inspect(regPackDoc));
return regPackDoc;
}
}
@Override
public boolean isValidatingInputAndOutput() {
return this.validating;
}
@Override
public void setValidatingInputAndOutput(boolean b) {
this.validating = b;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("SensorMLToEbRIMTransformer [validating: ");
sb.append(this.validating);
sb.append(", xsltSource: ");
sb.append(this.xsltSource);
sb.append(", transformation file: ");
sb.append(TRANSFORMATION_FILE_NAME);
return sb.toString();
}
@Override
public XmlObject transform(SensorMLDocument smlDoc) throws XmlException, TransformerException, IOException {
return actualTransform(smlDoc);
}
@Override
public XmlObject transform(SirSensorDescription sensor) throws XmlException, TransformerException, IOException {
if (sensor instanceof SirXmlSensorDescription) {
SirXmlSensorDescription sensorDescription = (SirXmlSensorDescription) sensor;
XmlObject o = sensorDescription.getDescription();
if (o instanceof SystemType) {
SystemType st = (SystemType) o;
return transform(st);
}
else if (o instanceof SensorMLDocument) {
SensorMLDocument smlDoc = (SensorMLDocument) o;
return actualTransform(smlDoc);
}
return o;
}
log.error("'transform' can only handle SiXmlSensorDescriptions, because it requires the complete sensor description!");
return null;
}
@Override
public Result transform(Source input) throws TransformerException, FileNotFoundException {
if (this.validating) {
return validateAndTransform(new InputSource(input.getSystemId()));
}
log.debug("Transformation of {}", input.getSystemId());
ErrorListener errL = new StandardErrorListener();
this.transformer.setErrorListener(errL);
// create output string
StringWriter sw = new StringWriter();
StreamResult output = new StreamResult(sw);
// do transform
this.transformer.transform(input, output);
log.debug("Transformation Done.");
return output;
}
@Override
public Result transform(String file) throws FileNotFoundException, TransformerException {
StreamSource input = new StreamSource(file);
return transform(input);
}
@Override
public XmlObject transform(SystemType st) throws XmlException, TransformerException, IOException {
SensorMLDocument smlDoc = SensorMLDocument.Factory.newInstance();
AbstractProcessType abstractProcess = smlDoc.addNewSensorML().addNewMember().addNewProcess();
SystemType systemType = (SystemType) abstractProcess.substitute(new QName(SMLConstants.NAMESPACE, "System"),
SystemType.type);
systemType.set(st);
return actualTransform(smlDoc);
}
/**
*
* Method validates the documents during transformation and relies on SAX features (which must be
* installed, naturally).
*
* @param input
* @return
* @throws TransformerConfigurationException
*/
private Result validateAndTransform(InputSource input) throws TransformerConfigurationException {
// Since we're going to use a SAX feature, the transformer must support
// input in the form of a SAXSource.
if (tFactory.getFeature(SAXSource.FEATURE)) {
SAXParserFactory pfactory = SAXParserFactory.newInstance();
pfactory.setNamespaceAware(true);
// Turn on validation.
pfactory.setValidating(true);
// ...
pfactory.setXIncludeAware(true);
// pfactory.setSchema(schema)
// Get an XMLReader.
XMLReader reader;
try {
reader = pfactory.newSAXParser().getXMLReader();
}
catch (SAXException e) {
e.printStackTrace();
return null;
}
catch (ParserConfigurationException e) {
e.printStackTrace();
return null;
}
// Instantiate an error handler (see the Handler inner class below) that will report any
// errors or warnings that occur as the XMLReader is parsing the XML input.
ParseExceptionHandler handler = new ParseExceptionHandler();
reader.setErrorHandler(handler);
Transformer t = tFactory.newTransformer(this.xsltSource);
// Specify a SAXSource that takes both an XMLReader and a URL.
SAXSource source = new SAXSource(reader, input);
// Transform input to a string.
StringWriter sw = new StringWriter();
StreamResult output = new StreamResult(sw);
try {
t.transform(source, output);
}
catch (TransformerException te) {
// The TransformerException wraps someting other than a SAXParseException
// warning or error, either of which should be "caught" by the Handler.
log.error("Not a SAXParseException warning or error: {}", te);
}
log.info("=====Done=====");
return output;
}
log.error("TransformerFactory does not support required SAXSource.FEATURE");
throw new TransformerConfigurationException("TransformerFactory does not support required SAXSource.FEATURE");
}
@Override
public boolean acceptsInput(TransformableFormat input) {
return input.equals(TransformableFormat.SML);
}
@Override
public boolean producesOutput(TransformableFormat output) {
return output.equals(TransformableFormat.EBRIM);
}
}
| 37.782383 | 158 | 0.669707 |
e16127a0e0aa2ac2e442063652cb8365b16bcb79 | 3,462 | package moe.pixelgirl.wirelesscommunication.common.util;
import cofh.api.tileentity.ISecurable;
import cofh.core.block.TileCoFHBase;
import cofh.core.util.CoreUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import java.util.ArrayList;
/**
* WirelessCommunication
* moe.pixelgirl.wirelesscommunication.common.util
* Created by Pixel.
*/
public class BlockHelper {
public static ArrayList<ItemStack> dismantleBlock(EntityPlayer player, World world, int x, int y, int z, boolean returnDrops) {
int metadata = world.getBlockMetadata(x, y, z);
Block block = world.getBlock(x, y, z);
ItemStack droppedBlock = new ItemStack(block, 1, metadata);
world.setBlockToAir(x, y, z);
if(!returnDrops){
float f = 0.3F;
double x2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
double y2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
double z2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
EntityItem entity = new EntityItem(world, x + x2, y + y2, z + z2, droppedBlock);
entity.delayBeforeCanPickup = 10;
world.spawnEntityInWorld(entity);
CoreUtils.dismantleLog(player.getCommandSenderName(), block, metadata, x, y, z);
}
ArrayList<ItemStack> returnedItems = new ArrayList<ItemStack>();
returnedItems.add(droppedBlock);
return returnedItems;
}
public static ArrayList<ItemStack> dismantleBlock(EntityPlayer player, NBTTagCompound nbt, World world, int x, int y, int z, boolean returnDrops, boolean simulate) {
TileEntity tileEntity = world.getTileEntity(x, y, z);
Block block = world.getBlock(x, y, z);
int meta = world.getBlockMetadata(x, y, z);
ItemStack droppedBlock = new ItemStack(block, 1, meta);
if(nbt != null && !nbt.hasNoTags()){
droppedBlock.setTagCompound(nbt);
}
if(!simulate){
if(tileEntity instanceof TileCoFHBase){
((TileCoFHBase) tileEntity).blockDismantled();
}
world.setBlockToAir(x, y, z);
if (!returnDrops) {
float f = 0.3F;
double x2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
double y2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
double z2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
EntityItem item = new EntityItem(world, x + x2, y + y2, z + z2, droppedBlock);
item.delayBeforeCanPickup = 10;
if (tileEntity instanceof ISecurable && !((ISecurable) tileEntity).getAccess().isPublic()) {
item.func_145797_a(player.getCommandSenderName());
// set owner (not thrower) - ensures wrenching player can pick it up first
}
world.spawnEntityInWorld(item);
if (player != null) {
CoreUtils.dismantleLog(player.getCommandSenderName(), block, meta, x, y, z);
}
}
}
ArrayList<ItemStack> returnedItems = new ArrayList<ItemStack>();
returnedItems.add(droppedBlock);
return returnedItems;
}
}
| 42.740741 | 169 | 0.614674 |
b50658ff2929b2642baaadbb4684765e5d4eafa2 | 739 | package com.inepex.example.ContactManager.entity.kvo;
public class EmailAddressConsts {
public static final String descriptorName = "emailAddressDescriptor";
public static final String searchDescriptor = "emailAddressSearchDescriptor";
// field contsts
public static final String k_id = "id";
public static final String k_email = "email";
public static String k_id() {
return k_id;
}
public static String k_email() {
return k_email;
}
// search consts
public static final String s_id = "id";
public static final String s_email = "email";
public static String s_id() {
return s_id;
}
public static String s_email() {
return s_email;
}
} | 23.83871 | 81 | 0.667118 |
7228e64a5f845a90446757360112f892ae941c75 | 5,978 | package com.codingmore.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codingmore.dto.PostTagParam;
import com.codingmore.model.PostTag;
import com.codingmore.service.IPostTagRelationService;
import com.codingmore.service.IPostTagService;
import com.codingmore.service.RedisService;
import com.codingmore.webapi.ResultObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 标签表 前端控制器
* </p>
*
* @author 石磊
* @since 2021-09-12
*/
@Controller
@Api(tags = "标签")
@RequestMapping("/postTag")
public class PostTagController {
@Autowired
private IPostTagService postTagService;
@Autowired
private IPostTagRelationService postTagRelationService;
@Autowired
private RedisService redisService;
@RequestMapping(value = "/insert", method = RequestMethod.POST)
@ResponseBody
@ApiOperation("添加标签")
public ResultObject<String> insert(@Valid PostTagParam postATagParam) {
QueryWrapper<PostTag> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("description", postATagParam.getDescription());
int count = postTagService.count(queryWrapper);
if (count > 0) {
return ResultObject.failed("标签已存在");
}
PostTag postTag = new PostTag();
BeanUtils.copyProperties(postATagParam, postTag);
return ResultObject.success(postTagService.save(postTag) ? "添加成功" : "添加失败");
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ResponseBody
@ApiOperation("修改标签")
public ResultObject<String> update(@Valid PostTagParam postAddTagParam) {
if (postAddTagParam.getPostTagId() == null) {
return ResultObject.failed("标签id不能为空");
}
PostTag postTag = postTagService.getById(postAddTagParam.getPostTagId());
if (postTag == null) {
return ResultObject.failed("标签不存在");
}
QueryWrapper<PostTag> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("description", postAddTagParam.getDescription());
int count = postTagService.count(queryWrapper);
if (count > 0) {
return ResultObject.failed("标签名称已存在");
}
BeanUtils.copyProperties(postAddTagParam, postTag);
return ResultObject.success(postTagService.updateById(postTag) ? "修改成功" : "修改失败");
}
@RequestMapping(value = "/simpleTest", method = RequestMethod.POST)
@ResponseBody
@ApiOperation("修改标签/Redis 测试用")
// Spring Cache 测试代码
// @CachePut(value = "codingmore", key = "'codingmore:postags:'+#postAddTagParam.postTagId")
public ResultObject<PostTag> simpleTest(@Valid PostTagParam postAddTagParam) {
if (postAddTagParam.getPostTagId() == null) {
return ResultObject.failed("标签id不能为空");
}
PostTag postTag = postTagService.getById(postAddTagParam.getPostTagId());
if (postTag == null) {
return ResultObject.failed("标签不存在");
}
QueryWrapper<PostTag> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("description", postAddTagParam.getDescription());
int count = postTagService.count(queryWrapper);
if (count > 0) {
return ResultObject.failed("标签名称已存在");
}
BeanUtils.copyProperties(postAddTagParam, postTag);
boolean successFlag = postTagService.updateById(postTag);
String key = "redis:simple:" + postTag.getPostTagId();
redisService.set(key, postTag);
PostTag cachePostTag = (PostTag) redisService.get(key);
return ResultObject.success(cachePostTag);
}
@RequestMapping(value = "/getByPostId", method = RequestMethod.GET)
@ResponseBody
@ApiOperation("根据文章内容获取标签")
public ResultObject<List<PostTag>> getByPostId(long objectId) {
return ResultObject.success(postTagService.getByPostId(objectId));
}
@RequestMapping(value = "/getByName", method = RequestMethod.GET)
@ResponseBody
@ApiOperation("模糊匹配")
public ResultObject<List<PostTag>> getByName(String keyWord) {
QueryWrapper<PostTag> postTagQueryWrapper = new QueryWrapper<>();
postTagQueryWrapper.like("description", keyWord + "%");
return ResultObject.success(postTagService.list(postTagQueryWrapper));
}
@RequestMapping(value = "/delete", method = RequestMethod.GET)
@ResponseBody
@ApiOperation("删除")
public ResultObject<String> delete(Long postTagId) {
return ResultObject.success(postTagService.removeTag(postTagId) ? "删除成功" : "删除失败");
}
@RequestMapping(value = "/queryPageable", method = RequestMethod.GET)
@ResponseBody
@ApiOperation("分页查询")
public ResultObject<Map<String, Object>> queryPageable(long pageSize, long page, String tagName) {
Map<String, Object> map = new HashMap<>();
Page<PostTag> postTagPage = new Page<>(page, pageSize);
QueryWrapper<PostTag> postTagQueryWrapper = new QueryWrapper();
if (StringUtils.isNotBlank(tagName)) {
postTagQueryWrapper.like("description", "%" + tagName + "%");
}
IPage<PostTag> postTagIPage = postTagService.page(postTagPage, postTagQueryWrapper);
map.put("items", postTagIPage.getRecords());
map.put("total", postTagIPage.getTotal());
return ResultObject.success(map);
}
}
| 38.320513 | 102 | 0.700067 |
5f2d92b018edcf1156089862c305b1f54255b05b | 146 | /**
* @author Ryoka Kujo chunxiang.huang@mail.hypers.com
* @since 2020-01-14
*/
module com.hypers.internal.impl {
requires com.hypers.api;
}
| 18.25 | 53 | 0.69863 |
10f6890fbec2611bf57b71c84484b3753fc24df9 | 2,058 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.indexinglanguage.expressions;
import com.yahoo.document.DataType;
import com.yahoo.document.datatypes.StringFieldValue;
/**
* @author Simon Thoresen Hult
*/
public final class SubstringExpression extends Expression {
private final int from;
private final int to;
public SubstringExpression(int from, int to) {
super(DataType.STRING);
if (from < 0 || to < 0 || to < from) {
throw new IndexOutOfBoundsException();
}
this.from = from;
this.to = to;
}
public int getFrom() {
return from;
}
public int getTo() {
return to;
}
@Override
protected void doExecute(ExecutionContext context) {
String input = String.valueOf(context.getValue());
int len = input.length();
if (from >= len) {
input = "";
} else if (to >= len) {
input = input.substring(from);
} else {
input = input.substring(from, to);
}
context.setValue(new StringFieldValue(input));
}
@Override
protected void doVerify(VerificationContext context) {
context.setValueType(createdOutputType());
}
@Override
public DataType createdOutputType() {
return DataType.STRING;
}
@Override
public String toString() {
return "substring " + from + " " + to;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SubstringExpression)) {
return false;
}
SubstringExpression rhs = (SubstringExpression)obj;
if (from != rhs.from) {
return false;
}
if (to != rhs.to) {
return false;
}
return true;
}
@Override
public int hashCode() {
return getClass().hashCode() +
Integer.valueOf(from).hashCode() +
Integer.valueOf(to).hashCode();
}
}
| 24.795181 | 104 | 0.577745 |
0a83d7a5453b3bc351e1f96fc1102efa527f4510 | 22,429 | package com.bunq.sdk.security;
import com.bunq.sdk.context.ApiContext;
import com.bunq.sdk.exception.BunqException;
import com.bunq.sdk.exception.UncaughtExceptionError;
import com.bunq.sdk.http.BunqBasicHeader;
import com.bunq.sdk.http.BunqHeader;
import com.bunq.sdk.http.BunqRequestBuilder;
import com.bunq.sdk.http.HttpMethod;
import com.bunq.sdk.model.generated.object.Certificate;
import com.bunq.sdk.util.BunqUtil;
import okhttp3.Headers;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;
import org.apache.commons.io.FileUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Static lib containing methods for handling encryption.
*/
public final class SecurityUtils {
/**
* Error constants.
*/
private static final String ERROR_COULD_NOT_INITIALIZE_KEY_PAIR_GENERATOR =
"Could not initialize KeyPairGenerator.";
private static final String ERROR_PRIVATE_KEY_FORMAT_INVALID =
"Could not create a private key from \"%s\".";
private static final String ERROR_PUBLIC_KEY_FORMAT_INVALID =
"Could not create a public key from \"%s\".";
private static final String ERROR_COULD_NOT_INITIALIZE_SIGNATURE =
"Could not initialize Signature.";
private static final String ERROR_COULD_NOT_READ_FROM_FILE =
"Could not read from file %s.";
private static final String ERROR_KEY_PAIR_INVALID = "KeyPair seems to be invalid.";
private static final String ERROR_COULD_NOT_SIGN_DATA = "Could not sign data.";
private static final String ERROR_COULD_NOT_VERIFY_DATA = "Could not verify signed data.";
private static final String ERROR_CAN_NOT_GET_ENTITY_BODY_BYTES =
"Can't get body bytes of the entity.";
private static final String ERROR_RESPONSE_VERIFICATION_FAILED = "Response verification failed";
/**
* Constants to generate encryption keys.
*/
private static final String KEY_PAIR_GENERATOR_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
private static final int KEY_PAIR_GENERATOR_KEY_SIZE = 2048;
/**
* The MAC algorithm to use for calculating and verifying the HMAC.
*/
private static final String ALGORITHM_MAC = "HmacSHA1";
/**
* The {@link javax.crypto.Cipher} algorithm(s) to use to encrypt/decrypt the
* {@link javax.crypto.SecretKey} used to encrypt/decrypt the request/response body
* communicated through the key header.
*/
private static final String KEY_CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
/**
* The {@link javax.crypto.Cipher} algorithm(s) to use to encrypt/decrypt the request/response
* body.
*/
private static final String ALGORITHM_BODY_CIPHER = "AES/CBC/PKCS5PADDING";
/**
* The size of the encryption initialization vector (IV) to use (in bytes).
*/
private static final int INITIALIZATION_VECTOR_SIZE_BYTES = 128 / 8;
/**
* The key generation algorithm to use for generating the body {@link javax.crypto.Cipher}
* {@link javax.crypto.SecretKey}.
*/
private static final String ALGORITHM_KEY_GENERATION = "AES";
/**
* The size of the encryption {@link javax.crypto.SecretKey} to use (in bits) for generating
* the body {@link javax.crypto.Cipher} {@link javax.crypto.SecretKey}.
*/
private static final int KEY_SIZE = 256;
/**
* Newline and empty string specific to the purpose of this class.
*/
private static final String NEWLINE = "\n";
private static final String STRING_EMPTY = "";
/**
* Constants to format encryption keys.
*/
private static final String PUBLIC_KEY_START = "-----BEGIN PUBLIC KEY-----\n";
private static final String PUBLIC_KEY_END = "\n-----END PUBLIC KEY-----\n";
private static final String PUBLIC_KEY_FORMAT = PUBLIC_KEY_START + "%s" + PUBLIC_KEY_END;
private static final String PRIVATE_KEY_START = "-----BEGIN PRIVATE KEY-----\n";
private static final String PRIVATE_KEY_END = "\n-----END PRIVATE KEY-----\n";
private static final String PRIVATE_KEY_FORMAT = PRIVATE_KEY_START + "%s" + PRIVATE_KEY_END;
private static final int KEY_ENCODED_LINE_LENGTH = 64;
/**
* Length of an empty array.
*/
private static final int ARRAY_LENGTH_EMPTY = 0;
/**
* Delimiter constants for building the data to sign.
*/
private static final String DELIMITER_METHOD_PATH = " ";
/**
* The index of the first item in an array.
*/
private static final int INDEX_FIRST = 0;
/**
*
*/
private SecurityUtils() {
}
/**
* Generates a X509/PKCS8 Key Pair.
*
* @throws BunqException When could not initialize KeyPairGenerator.
*/
public static KeyPair generateKeyPair() throws BunqException {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_PAIR_GENERATOR_ALGORITHM);
generator.initialize(KEY_PAIR_GENERATOR_KEY_SIZE);
return generator.generateKeyPair();
} catch (NoSuchAlgorithmException exception) {
throw new BunqException(ERROR_COULD_NOT_INITIALIZE_KEY_PAIR_GENERATOR, exception);
}
}
public static String getPrivateKeyFormattedString(KeyPair keyPair) {
return getPrivateKeyFormattedString(keyPair.getPrivate());
}
/**
* @return The private key string formatted according to PKCS8 standard.
*/
private static String getPrivateKeyFormattedString(PrivateKey privateKey) {
byte[] encodedPrivateKey = privateKey.getEncoded();
String privateKeyString = DatatypeConverter.printBase64Binary(encodedPrivateKey);
return String.format(PRIVATE_KEY_FORMAT, privateKeyString);
}
/**
* @param publicKeyString X509 Public Key string
* @param privateKeyString PKCS8 Private Key string
*/
public static KeyPair createKeyPairFromFormattedStrings(String publicKeyString,
String privateKeyString) {
return new KeyPair(
createPublicKeyFromFormattedString(publicKeyString),
createPrivateKeyFromFormattedString(privateKeyString)
);
}
/**
* @param publicKeyString X509 Public Key string
*/
public static PublicKey createPublicKeyFromFormattedString(String publicKeyString) {
try {
X509EncodedKeySpec spec =
new X509EncodedKeySpec(getAllPublicKeyByteFromFormattedString(publicKeyString));
KeyFactory keyFactory = KeyFactory.getInstance(KEY_PAIR_GENERATOR_ALGORITHM);
return keyFactory.generatePublic(spec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException exception) {
throw new BunqException(String.format(ERROR_PUBLIC_KEY_FORMAT_INVALID, publicKeyString),
exception);
}
}
/**
* @param publicKeyString X509 Public Key string
*/
private static byte[] getAllPublicKeyByteFromFormattedString(String publicKeyString) {
publicKeyString = publicKeyString.replace(PUBLIC_KEY_START, STRING_EMPTY);
publicKeyString = publicKeyString.replace(PUBLIC_KEY_END, STRING_EMPTY);
publicKeyString = publicKeyString.replace(NEWLINE, STRING_EMPTY);
return DatatypeConverter.parseBase64Binary(publicKeyString);
}
/**
* @param privateKeyString PKCS8 Private Key string
*/
public static PrivateKey createPrivateKeyFromFormattedString(String privateKeyString) {
try {
PKCS8EncodedKeySpec spec =
new PKCS8EncodedKeySpec(getAllPrivateKeyByteFromFormattedString(privateKeyString));
KeyFactory keyFactory = KeyFactory.getInstance(KEY_PAIR_GENERATOR_ALGORITHM);
return keyFactory.generatePrivate(spec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException exception) {
throw new BunqException(String.format(ERROR_PRIVATE_KEY_FORMAT_INVALID, privateKeyString),
exception);
}
}
/**
* @param path File path to the private key file.
*/
public static PrivateKey getPrivateKeyFromFile(String path) {
try {
File keyFile = new File(path);
String keyString = FileUtils.readFileToString(keyFile);
return createPrivateKeyFromFormattedString(keyString);
} catch (IOException exception) {
throw new BunqException(
String.format(ERROR_COULD_NOT_READ_FROM_FILE, path),
exception
);
}
}
/**
* @param privateKeyString PKCS8 Private Key string
*/
private static byte[] getAllPrivateKeyByteFromFormattedString(String privateKeyString) {
privateKeyString = privateKeyString.replace(PRIVATE_KEY_START, STRING_EMPTY);
privateKeyString = privateKeyString.replace(PRIVATE_KEY_END, STRING_EMPTY);
privateKeyString = privateKeyString.replace(NEWLINE, STRING_EMPTY);
return DatatypeConverter.parseBase64Binary(privateKeyString);
}
public static String getPublicKeyFormattedString(KeyPair keyPair) {
return getPublicKeyFormattedString(keyPair.getPublic());
}
/**
* Creates a Public Key as a string formatted according to X509 standard.
*/
public static String getPublicKeyFormattedString(PublicKey publicKey) {
byte[] encodedPublicKey = publicKey.getEncoded();
String publicKeyString = DatatypeConverter.printBase64Binary(encodedPublicKey);
List<String> encodedKeyLines = BunqUtil.getChunksFromString(publicKeyString, KEY_ENCODED_LINE_LENGTH);
publicKeyString = String.join(NEWLINE, encodedKeyLines);
return String.format(PUBLIC_KEY_FORMAT, publicKeyString);
}
/**
* Encrypt the request, add the encrypted headers to the given header map. This method modifies
* the header map!
*/
public static byte[] encrypt(ApiContext apiContext, byte[] requestBytes,
Map<String, String> customHeaders) {
SecretKey key = generateEncryptionKey();
byte[] initializationVector = generateInitializationVector();
addHeaderClientEncryptionKey(apiContext, key, customHeaders);
addHeaderClientEncryptionIv(initializationVector, customHeaders);
requestBytes = encryptRequestBytes(requestBytes, key, initializationVector);
addHeaderClientEncryptionHmac(requestBytes, key, initializationVector, customHeaders);
return requestBytes;
}
private static SecretKey generateEncryptionKey() {
try {
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM_KEY_GENERATION);
keyGen.init(KEY_SIZE);
return keyGen.generateKey();
} catch (GeneralSecurityException exception) {
throw new BunqException(exception.getMessage());
}
}
private static byte[] generateInitializationVector() {
byte[] initializationVector = new byte[INITIALIZATION_VECTOR_SIZE_BYTES];
new SecureRandom().nextBytes(initializationVector);
return initializationVector;
}
private static void addHeaderClientEncryptionKey(
ApiContext apiContext,
SecretKey key,
Map<String, String> customHeaders
) {
try {
Cipher cipher = Cipher.getInstance(KEY_CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, apiContext.getInstallationContext().getPublicKeyServer());
byte[] keyEncrypted = cipher.doFinal(key.getEncoded());
String keyEncryptedEncoded = DatatypeConverter.printBase64Binary(keyEncrypted);
BunqHeader.CLIENT_ENCRYPTION_KEY.addTo(customHeaders, keyEncryptedEncoded);
} catch (GeneralSecurityException exception) {
throw new BunqException(exception.getMessage());
}
}
private static void addHeaderClientEncryptionIv(byte[] initializationVector, Map<String,
String> customHeaders) {
String initializationVectorEncoded = DatatypeConverter.printBase64Binary(initializationVector);
BunqHeader.CLIENT_ENCRYPTION_IV.addTo(customHeaders, initializationVectorEncoded);
}
private static byte[] encryptRequestBytes(byte[] requestBytes, SecretKey key,
byte[] initializationVector) {
if (requestBytes.length == 0) {
return requestBytes;
}
try {
Cipher cipher = Cipher.getInstance(ALGORITHM_BODY_CIPHER);
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(initializationVector));
return cipher.doFinal(requestBytes);
} catch (GeneralSecurityException exception) {
throw new BunqException(exception.getMessage());
}
}
private static void addHeaderClientEncryptionHmac(byte[] requestBytes,
SecretKey key, byte[] initializationVector, Map<String, String> customHeaders) {
try {
Mac mac = Mac.getInstance(ALGORITHM_MAC);
mac.init(key);
mac.update(initializationVector);
MacOutputStream outputStream = new MacOutputStream(mac);
BufferedSink bufferedSink = Okio.buffer(Okio.sink(outputStream));
bufferedSink.write(requestBytes);
bufferedSink.emit();
bufferedSink.flush();
bufferedSink.close();
byte[] hmac = mac.doFinal();
String hmacEncoded = DatatypeConverter.printBase64Binary(hmac);
BunqHeader.CLIENT_ENCRYPTION_HMAC.addTo(customHeaders, hmacEncoded);
} catch (GeneralSecurityException | IOException exception) {
throw new BunqException(exception.getMessage());
}
}
public static String generateSignature(BunqRequestBuilder requestBuilder, KeyPair keyPairClient) {
try {
byte[] allRequestBodyByte = getEntityBodyBytes(requestBuilder);
return SecurityUtils.signBase64(allRequestBodyByte, keyPairClient);
} catch (IOException exception) {
throw new UncaughtExceptionError(exception);
}
}
public static String generateSignature(String stringToSign, PrivateKey privateKey) {
byte[] rawBytes = stringToSign.getBytes();
return SecurityUtils.signBase64(rawBytes, privateKey);
}
private static byte[] getEntityBodyBytes(BunqRequestBuilder requestBuilder) throws IOException {
HttpMethod method = requestBuilder.getMethod();
if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.DELETE)) {
return new byte[ARRAY_LENGTH_EMPTY];
} else if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) {
return requestBuilder.getBody().getContent();
} else {
throw new IllegalStateException(ERROR_CAN_NOT_GET_ENTITY_BODY_BYTES);
}
}
/**
* Sings data, encodes it as base64 and returns the result.
*
* @return The Base64 representation of the signature.
* @throws BunqException When could not initialize signature.
* @throws BunqException When key pair is invalid.
* @throws BunqException When could not sign data.
* @throws BunqException When could not verify data.
*/
private static String signBase64(byte[] bytesToSign, KeyPair keyPair) throws BunqException {
Signature signature = getSignatureInstance();
initializeSignature(signature, keyPair);
byte[] dataBytesSigned = signDataWithSignature(signature, bytesToSign);
verifyDataSigned(signature, keyPair.getPublic(), bytesToSign, dataBytesSigned);
return DatatypeConverter.printBase64Binary(dataBytesSigned);
}
private static String signBase64(byte[] bytesToSign, PrivateKey privateKey) throws BunqException {
Signature signature = getSignatureInstance();
initializeSignature(signature, privateKey);
byte[] dataBytesSigned = signDataWithSignature(signature, bytesToSign);
return DatatypeConverter.printBase64Binary(dataBytesSigned);
}
private static Signature getSignatureInstance() throws BunqException {
try {
return Signature.getInstance(SIGNATURE_ALGORITHM);
} catch (NoSuchAlgorithmException exception) {
throw new BunqException(ERROR_COULD_NOT_INITIALIZE_SIGNATURE, exception);
}
}
private static void initializeSignature(Signature signature,
KeyPair keyPair) throws BunqException {
initializeSignature(signature, keyPair.getPrivate());
}
private static void initializeSignature(Signature signature,
PrivateKey privateKey) throws BunqException {
try {
signature.initSign(privateKey);
} catch (InvalidKeyException exception) {
throw new BunqException(ERROR_KEY_PAIR_INVALID, exception);
}
}
private static byte[] signDataWithSignature(Signature signature,
byte[] dataBytes) throws BunqException {
try {
signature.update(dataBytes);
return signature.sign();
} catch (SignatureException exception) {
throw new BunqException(ERROR_COULD_NOT_SIGN_DATA, exception);
}
}
private static void verifyDataSigned(Signature signature, PublicKey publicKey, byte[] dataBytes,
byte[] dataBytesSigned) throws BunqException {
if (SecurityUtils.isSignatureValid(signature, publicKey, dataBytes, dataBytesSigned)) {
// All good.
} else {
throw new BunqException(ERROR_RESPONSE_VERIFICATION_FAILED);
}
}
private static boolean isSignatureValid(Signature signature, PublicKey publicKey, byte[] dataBytes,
byte[] dataBytesSigned) throws BunqException {
try {
signature.initVerify(publicKey);
signature.update(dataBytes);
return signature.verify(dataBytesSigned);
} catch (GeneralSecurityException exception) {
throw new BunqException(ERROR_COULD_NOT_VERIFY_DATA, exception);
}
}
public static void validateResponseSignature(
int responseCode,
byte[] responseBodyBytes,
Response response,
PublicKey keyPublicServer
) {
byte[] responseBytes = getResponseBytes(
responseCode,
responseBodyBytes,
response.headers()
);
Signature signature = getSignatureInstance();
BunqBasicHeader serverSignature = BunqBasicHeader.get(BunqHeader.SERVER_SIGNATURE, response);
byte[] serverSignatureDecoded = DatatypeConverter.parseBase64Binary(
serverSignature.getValue()
);
if (SecurityUtils.isSignatureValid(signature, keyPublicServer, responseBytes, serverSignatureDecoded)) {
// Signature is valid headers + body signature.
} else if (SecurityUtils.isSignatureValid(signature, keyPublicServer, responseBodyBytes, serverSignatureDecoded)) {
// Signature is valid body signature.
} else {
throw new BunqException(ERROR_RESPONSE_VERIFICATION_FAILED);
}
}
private static byte[] getResponseBytes(
int responseCode,
byte[] responseBodyBytes,
Headers allHeader
) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
List<BunqBasicHeader> allResponseHeader = new ArrayList<>();
for (int i = INDEX_FIRST; i < allHeader.names().size(); i++) {
BunqHeader header = BunqHeader.parseHeaderOrNull(allHeader.name(i));
if (header != null && !BunqHeader.SERVER_SIGNATURE.equals(header)) {
allResponseHeader.add(new BunqBasicHeader(header, allHeader.get(allHeader.name(i))));
}
}
try {
outputStream.write(getResponseHeadBytes(responseCode, allResponseHeader));
outputStream.write(responseBodyBytes);
} catch (IOException exception) {
throw new UncaughtExceptionError(exception);
}
return outputStream.toByteArray();
}
public static String getCertificateChainString(Certificate[] allChainCertificate) {
StringBuilder chainString = new StringBuilder();
for (Certificate certificate : allChainCertificate) {
chainString.append(certificate.getCertificate());
chainString.append(NEWLINE);
}
return chainString.toString();
}
public static Certificate getCertificateFromFile(String path) throws IOException {
File certificateFile = new File(path);
if (certificateFile.exists()) {
Certificate certificate = new Certificate();
certificate.setCertificate(FileUtils.readFileToString(certificateFile, "UTF-8"));
return certificate;
} else {
throw new FileNotFoundException();
}
}
private static byte[] getResponseHeadBytes(int code, List<BunqBasicHeader> headers) {
String requestHeadString = code + NEWLINE +
generateResponseHeadersSortedString(headers) + NEWLINE + NEWLINE;
return requestHeadString.getBytes();
}
private static String generateResponseHeadersSortedString(List<BunqBasicHeader> headers) {
return BunqBasicHeader.collectForSigning(
headers,
BunqHeader.SERVER_SIGNATURE,
Collections.<BunqHeader>emptyList()
);
}
}
| 39.838366 | 134 | 0.677427 |
65afed3b09c473eafdc54dae10eb1293dc888741 | 1,153 | package com.hm.demo;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class AutomateInDifferentBrowser {
public static WebDriver driver;
public static void openFirefox() {
driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
driver.close();
System.out.println("firefox");
}
public static void openIE() {
System.setProperty("webdriver.ie.driver","lib//IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("https://www.google.com");
driver.manage().window().maximize();
driver.close();
System.out.println("IE");
}
public static void openChrome() {
System.setProperty("webdriver.chrome.driver","lib/chromedriver.exe");
driver= new ChromeDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
driver.close();
System.out.println("Chrome");
}
public static void main(String[] args) {
openFirefox();
openChrome();
openIE();
}
}
| 22.173077 | 74 | 0.701648 |
c9a76c90464488bc39582f431a34bd8e6c6368d5 | 2,561 | package wholemusic.web.controller;
import com.sun.media.jfxmediaimpl.MediaUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import wholemusic.core.api.MusicApi;
import wholemusic.core.api.MusicApiFactory;
import wholemusic.core.api.MusicProvider;
import wholemusic.core.model.Album;
import wholemusic.core.model.Song;
import wholemusic.core.util.SongUtils;
import wholemusic.web.util.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
@SuppressWarnings("unused")
@Controller
@RequestMapping("/disk")
public class DiskController {
@GetMapping(value = "/{providerName}/{albumId}/{songId}")
public ResponseEntity<Resource> downloadMusic(@PathVariable("providerName") String providerName, @PathVariable
("albumId") String albumId, @PathVariable("songId") String songId) throws IOException {
MusicProvider provider = MusicProvider.valueOf(providerName);
if (provider != null) {
MusicApi api = MusicApiFactory.create(provider);
if (api != null) {
Album album = api.getAlbumInfoByIdSync(albumId, true);
List<? extends Song> songs = album.getSongs();
for (Song song : songs) {
if (Objects.equals(song.getSongId(), songId)) {
File downloadDir = FileUtils.getDownloadDir(true);
String path = SongUtils.generateSongPath(album, song);
File file = new File(downloadDir, path);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf(MediaUtils.CONTENT_TYPE_MPA));
FileSystemResource fileSystemResource = new FileSystemResource(file);
// TODO: download/play: octet/mp3 and filename
return new ResponseEntity<>(fileSystemResource, headers, HttpStatus.OK);
}
}
}
}
return new ResponseEntity<>(null, null, HttpStatus.NOT_FOUND);
}
} | 44.929825 | 114 | 0.686451 |
cb78b1a3112008fa479cba7614745bc83409470f | 2,775 | package com.rlws.plant.commons.utils;
import java.io.*;
/**
* @author rlws
* @date 2020/2/24 10:59
*/
public class SerializeUtils {
/**
* 序列化某个类并返回序列化后的字符串
*
* @param obj 需要序列化的类
* @return 序列化后的字符串
*/
public static String serialize(Object obj) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(obj);
byte[] result = byteArrayOutputStream.toByteArray();
objectOutputStream.close();
byteArrayOutputStream.close();
return toHexString(result);
}
/**
* 将字符串反序列化为某个类
*
* @param str 需要反序列化的字符串
* @return 返回反序列化的类
* @throws IOException IO异常
* @throws ClassNotFoundException 类缺失异常
*/
public static Object unSerialize(String str) throws IOException, ClassNotFoundException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(toByteArray(str));
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Object object = objectInputStream.readObject();
objectInputStream.close();
byteArrayInputStream.close();
return object;
}
/**
* 字节数组转成16进制表示格式的字符串
*
* @param byteArray 需要转换的字节数组
* @return 16进制表示格式的字符串
*/
private static String toHexString(byte[] byteArray) {
if (byteArray == null || byteArray.length < 1) {
throw new IllegalArgumentException("this byteArray must not be null or empty");
}
StringBuilder hexString = new StringBuilder();
for (byte b : byteArray) {
//0-F前面补零
if ((b & 0xff) < 0x10) {
hexString.append("0");
}
hexString.append(Integer.toHexString(0xff & b));
}
return hexString.toString();
}
/**
* 将16进制表示格式的字符串转换成字节数组
*
* @param hexString 16进制表示格式的字符串
* @return 字节数组
*/
private static byte[] toByteArray(String hexString) {
if (hexString == null || hexString.trim().length() == 0) {
throw new IllegalArgumentException("this hexString must not be null or empty");
}
byte[] byteArray = new byte[hexString.length() / 2];
int k = 0;
//因为是16进制,最多只会占用4位,转换成字节需要两个16进制的字符,高位在先
for (int i = 0; i < byteArray.length; i++) {
byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
byteArray[i] = (byte) (high << 4 | low);
k += 2;
}
return byteArray;
}
}
| 32.267442 | 95 | 0.608288 |
fdf57c03865a9bfa9c35de6c4a5a06b665375482 | 5,135 | package slimeknights.mantle.recipe.crafting;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonObject;
import net.minecraft.world.inventory.CraftingContainer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.CraftingRecipe;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.world.item.crafting.ShapedRecipe;
import net.minecraft.world.item.crafting.ShapelessRecipe;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.GsonHelper;
import net.minecraft.core.NonNullList;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.Level;
import slimeknights.mantle.recipe.MantleRecipeSerializers;
import slimeknights.mantle.util.JsonHelper;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@SuppressWarnings("WeakerAccess")
public class ShapedFallbackRecipe extends ShapedRecipe {
/** Recipes to skip if they match */
private final List<ResourceLocation> alternatives;
private List<CraftingRecipe> alternativeCache;
/**
* Main constructor, creates a recipe from all parameters
* @param id Recipe ID
* @param group Recipe group
* @param width Recipe width
* @param height Recipe height
* @param ingredients Recipe input ingredients
* @param output Recipe output
* @param alternatives List of recipe names to fail this match if they match
*/
public ShapedFallbackRecipe(ResourceLocation id, String group, int width, int height, NonNullList<Ingredient> ingredients, ItemStack output, List<ResourceLocation> alternatives) {
super(id, group, width, height, ingredients, output);
this.alternatives = alternatives;
}
/**
* Creates a recipe using a shaped recipe as a base
* @param base Shaped recipe to copy data from
* @param alternatives List of recipe names to fail this match if they match
*/
public ShapedFallbackRecipe(ShapedRecipe base, List<ResourceLocation> alternatives) {
this(base.getId(), base.getGroup(), base.getWidth(), base.getHeight(), base.getIngredients(), base.getResultItem(), alternatives);
}
@Override
public boolean matches(CraftingContainer inv, Level world) {
// if this recipe does not match, fail it
if (!super.matches(inv, world)) {
return false;
}
// fetch all alternatives, fail if any match
// cache to save effort down the line
if (alternativeCache == null) {
RecipeManager manager = world.getRecipeManager();
alternativeCache = alternatives.stream()
.map(manager::byKey)
.filter(Optional::isPresent)
.map(Optional::get)
.filter(recipe -> {
// only allow exact shaped or shapeless match, prevent infinite recursion due to complex recipes
Class<?> clazz = recipe.getClass();
return clazz == ShapedRecipe.class || clazz == ShapelessRecipe.class;
})
.map(recipe -> (CraftingRecipe) recipe).collect(Collectors.toList());
}
// fail if any alterntaive matches
return this.alternativeCache.stream().noneMatch(recipe -> recipe.matches(inv, world));
}
@Override
public RecipeSerializer<?> getSerializer() {
return MantleRecipeSerializers.CRAFTING_SHAPED_FALLBACK;
}
public static class Serializer extends ShapedRecipe.Serializer {
@Override
public ShapedFallbackRecipe fromJson(ResourceLocation id, JsonObject json) {
ShapedRecipe base = super.fromJson(id, json);
List<ResourceLocation> alternatives = JsonHelper.parseList(json, "alternatives", (element, name) -> new ResourceLocation(GsonHelper.convertToString(element, name)));
return new ShapedFallbackRecipe(base, alternatives);
}
@Override
public ShapedFallbackRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buffer) {
ShapedRecipe base = super.fromNetwork(id, buffer);
assert base != null;
int size = buffer.readVarInt();
ImmutableList.Builder<ResourceLocation> builder = ImmutableList.builder();
for (int i = 0; i < size; i++) {
builder.add(buffer.readResourceLocation());
}
return new ShapedFallbackRecipe(base, builder.build());
}
@Override
public void toNetwork(FriendlyByteBuf buffer, ShapedRecipe recipe) {
// write base recipe
super.toNetwork(buffer, recipe);
// write extra data
assert recipe instanceof ShapedFallbackRecipe;
List<ResourceLocation> alternatives = ((ShapedFallbackRecipe) recipe).alternatives;
buffer.writeVarInt(alternatives.size());
for (ResourceLocation alternative : alternatives) {
buffer.writeResourceLocation(alternative);
}
}
}
}
| 42.438017 | 181 | 0.688413 |
a8d83d327968fba0e882ce7bcc36fc3d2cde812f | 1,956 | /*
* 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.metahut.starfish.ingestion.collector.hive;
import org.metahut.starfish.ingestion.collector.api.CollectorResult;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.thrift.TException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.List;
@Disabled
public class HiveCollectorAdapterTest {
@Test
public void testConnection() throws TException {
String metaUris = "thrift://xx.xx.xx.xx:9083,thrift://xx.xx.xx.xx:9083";
HiveCollectorAdapterParameter adapterParameter = new HiveCollectorAdapterParameter();
adapterParameter.setHiveMetastoreUris(metaUris);
HiveCollectorAdapter adapter = new HiveCollectorAdapter(adapterParameter);
CollectorResult collectorResult = adapter.testConnection();
Assertions.assertNotNull(collectorResult);
Assertions.assertTrue(collectorResult.getState());
IMetaStoreClient metaClient = adapter.getMetaClient();
List<String> allDatabases = metaClient.getAllDatabases();
Assertions.assertNotNull(allDatabases);
}
}
| 40.75 | 93 | 0.76227 |
83dd36261d298df4bf8c03f602a1d2a93143cdd2 | 4,027 | package com.muiz6.musicplayer.ui.main.home.library;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentFactory;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.tabs.TabLayoutMediator;
import com.muiz6.musicplayer.R;
import com.muiz6.musicplayer.databinding.FragmentLibraryBinding;
import javax.inject.Inject;
public class LibraryFragment extends Fragment {
private final FragmentFactory _fragmentFactory;
private final TabLayoutMediator.TabConfigurationStrategy _tabMediatorStrategy;
private final ViewModelProvider.Factory _viewModelFactory;
private FragmentLibraryBinding _binding;
private LibraryViewModel _viewModel;
@Inject
public LibraryFragment(FragmentFactory factory,
ViewModelProvider.Factory viewModelFactory,
TabLayoutMediator.TabConfigurationStrategy tabMediatorStrategy) {
_fragmentFactory = factory;
_viewModelFactory = viewModelFactory;
_tabMediatorStrategy = tabMediatorStrategy;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); // better to call here to avoid unexpected behaviour
_viewModel = new ViewModelProvider(this, _viewModelFactory).get(LibraryViewModel.class);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
getChildFragmentManager().setFragmentFactory(_fragmentFactory);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
_binding = FragmentLibraryBinding.inflate(inflater, container, false);
return _binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// setup toolbar
((AppCompatActivity) getActivity()).setSupportActionBar(_binding.libraryToolbar);
// final NavController navController = Navigation.findNavController(view);
// final AppBarConfiguration appBarConfiguration =
// new AppBarConfiguration.Builder(navController.getGraph()).build();
// NavigationUI.setupWithNavController(_binding.mainToolbar,
// navController,
// appBarConfiguration);
// setup tab layout
_binding.libraryViewPager.setAdapter(new LibraryPagerAdapter(this,
getActivity().getClassLoader(),
_fragmentFactory));
new TabLayoutMediator(_binding.libraryTabLayout,
_binding.libraryViewPager,
_tabMediatorStrategy).attach();
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_library, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_rescan_library) {
_viewModel.onRescanLibraryAction();
return true;
}
return NavigationUI.onNavDestinationSelected(item,
Navigation.findNavController(requireView()))
|| super.onOptionsItemSelected(item);
}
@Override
public void onDestroyView() {
super.onDestroyView();
_binding = null;
}
// private void _updateFromMetadata(MediaMetadataCompat metadata) {
//
// // todo: get height not working for some reason
// final int padding = (int) getResources().getDimension(R.dimen.padding_bottom_home_view_pager);
// _binding.mainViewPager.setPadding(_binding.mainViewPager.getPaddingStart(),
// _binding.mainViewPager.getPaddingTop(),
// _binding.mainViewPager.getPaddingEnd(),
// padding);
// }
}
| 33.280992 | 99 | 0.796126 |
531ac1b1d3fa4eae186217b49971ccf9c84a87fe | 1,120 | package com.ttnn.framework.ept.bean.config;
import java.io.Serializable;
import com.ttnn.framework.ept.SEPTConstants;
/**
* 提示信息配置
*
* @author Fcy
* @see <ept-config.xml>
* @since 1.1
* @version 1.3 模版升级
*/
public class MessageBean implements SEPTConstants,Serializable{
/**
*
*/
private static final long serialVersionUID = -8360213705915278873L;
/**
* 提示信息的名称标识
*/
private String name;
/**
* 提示信息具体内容
*/
private String value;
public String getName() {
return name;
}
public void setName(String fieldName) {
name = fieldName;
}
public String getValue() {
return value;
}
public void setValue(String fieldValue) {
value = fieldValue;
}
/**
* 参数替换
*
* @param args
* @return
*/
public String prepareMessage(String... args) {
if (args == null)
return value;
StringBuilder msgSB = new StringBuilder(100);
for (int i = 0; i < args.length; i++) {
value = value.replace("{" + i + "}", args[i]);
}
return msgSB.toString();
}
@Override
public String toString() {
return "MessageBean [name=" + name + ", value=" + value + "]";
}
}
| 16.470588 | 71 | 0.63125 |
adf78c4a9aedac0c07a5dea0f5aaa4ddfc3f8841 | 187 | package com.kotlin.inaction.chapter_9.java_generics.advance.advance_02;
/**
* @author wangzhichao
* @date 2019/11/01
*/
public interface Comparable<T> {
boolean compareTo(T t);
}
| 18.7 | 71 | 0.727273 |
5857dd0a8dcc3dcc0f1447ba6c5ea4772db6e9d3 | 1,049 | package com.slack.api.app_backend.outgoing_webhooks;
import lombok.extern.slf4j.Slf4j;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
@Slf4j
public class WebhookPayloadDetector {
public boolean isWebhook(String requestBody) {
if (requestBody == null) {
return false;
}
String[] pairs = requestBody.split("\\&");
for (String pair : pairs) {
String[] fields = pair.split("=");
if (fields.length == 2) {
try {
String name = URLDecoder.decode(fields[0].trim().replaceAll("\\n+", ""), "UTF-8");
String value = URLDecoder.decode(fields[1], "UTF-8");
if (name.equals("trigger_word")) {
return true;
}
} catch (UnsupportedEncodingException e) {
log.error("Failed to decode URL-encoded string values - {}", e.getMessage(), e);
}
}
}
return false;
}
}
| 30.852941 | 102 | 0.525262 |
7cae2abe745740a48475d79889b205fa145abf69 | 2,033 | package com.xavierlepretre.hackernewsbrowser;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import butterknife.InjectView;
import com.ycombinator.news.dto.StoryDTO;
import java.text.NumberFormat;
public class StoryView extends ItemView
{
@InjectView(android.R.id.title) TextView title;
@InjectView(android.R.id.text2) TextView score;
@InjectView(android.R.id.icon1) View commentIcon;
@InjectView(android.R.id.custom) TextView commentCount;
public StoryView(Context context)
{
super(context);
}
public StoryView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public StoryView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
@Override protected void onFinishInflate()
{
super.onFinishInflate();
commentIcon.setVisibility(VISIBLE);
commentCount.setVisibility(VISIBLE);
}
public void displayStory(@NonNull DTO story)
{
displayItem(story);
title.setText(story.title);
score.setText(story.score);
if (commentCount != null)
{
commentCount.setText(story.commentCount);
}
}
static class DTO extends ItemView.DTO
{
@NonNull final String title;
@NonNull final String score;
@NonNull final String commentCount;
DTO(@NonNull Context context, @NonNull StoryDTO storyDTO)
{
super(context, storyDTO);
this.title = storyDTO.getTitle();
this.score = NumberFormat.getIntegerInstance().format(storyDTO.getScore());
int count = storyDTO.getKids().size();
this.commentCount = String.format("%1$s (%2$s)",
NumberFormat.getInstance().format(count),
NumberFormat.getInstance().format(storyDTO.getDescendants()));
}
}
}
| 29.042857 | 87 | 0.657157 |
db1e55afa23b703700c9af56821124888f9842ef | 1,525 | package info.u_team.halloween_luckyblock.entity.render;
import com.mojang.blaze3d.matrix.MatrixStack;
import info.u_team.halloween_luckyblock.HalloweenLuckyBlockMod;
import info.u_team.halloween_luckyblock.entity.EntityVampire;
import info.u_team.halloween_luckyblock.entity.model.ModelVampire;
import net.minecraft.client.renderer.entity.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.api.distmarker.*;
@OnlyIn(Dist.CLIENT)
public class RenderVampire extends MobRenderer<EntityVampire, ModelVampire> {
public RenderVampire(EntityRendererManager rendermanager) {
super(rendermanager, new ModelVampire(), 0.25F);
}
@Override
protected void preRenderCallback(EntityVampire entitylivingbaseIn, MatrixStack matrixStackIn, float partialTickTime) {
matrixStackIn.scale(1.35F, 1.35F, 1.35F);
}
@Override
protected void applyRotations(EntityVampire entityLiving, MatrixStack matrixStackIn, float ageInTicks, float rotationYaw, float partialTicks) {
if (!entityLiving.getIsBatHanging()) {
matrixStackIn.translate(0.0F, MathHelper.cos(ageInTicks * 0.3F) * 0.1F, 0.0F);
} else {
matrixStackIn.translate(0.0F, -0.1F, 0.0F);
}
super.applyRotations(entityLiving, matrixStackIn, ageInTicks, rotationYaw, partialTicks);
}
@Override
public ResourceLocation getEntityTexture(EntityVampire entity) {
return new ResourceLocation(HalloweenLuckyBlockMod.MODID + ":textures/entity/vampire.png");
}
} | 39.102564 | 145 | 0.783607 |
9b8bb238933510125c92b7e241a5f7acbaed471c | 2,997 | package eu.lucaventuri.fibry.spring;
import eu.lucaventuri.common.Exceptions;
import eu.lucaventuri.fibry.ActorSystem;
import eu.lucaventuri.fibry.distributed.HttpChannel;
import eu.lucaventuri.fibry.distributed.JacksonSerDeser;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutionException;
@SpringBootApplication
public class ManualTestFibrySpring {
public static void main(String[] args) {
SpringApplication.run(ManualTestFibrySpring.class, args);
}
@PostConstruct
public void started() throws ExecutionException, InterruptedException {
new Thread(() -> {
ActorSystem.named("testActorGet").newActorWithReturn((String str) -> (str.toLowerCase() + "-GET"));
ActorSystem.named("testActorPut").newActorWithReturn((String str) -> str.toLowerCase() + "-PUT");
ActorSystem.named("testActorPost").newActorWithReturn((String str) -> str.toLowerCase() + "-POST");
ActorSystem.named("testActorSync").newSynchronousActorWithReturn((String str) -> str.toLowerCase() + "-SYNC");
Exceptions.silence(() -> {
String url = "http://localhost:8080/fibry/messages";
var channelGet = new HttpChannel(url, HttpChannel.HttpMethod.GET, null, null, false);
var channelPut = new HttpChannel(url, HttpChannel.HttpMethod.PUT, null, null, false);
var channelPost = new HttpChannel(url, HttpChannel.HttpMethod.POST, null, null, false);
var actorGet = ActorSystem.anonymous().newRemoteActorWithReturn("testActorGet", channelGet, new JacksonSerDeser<>(String.class));
var actorGet2 = ActorSystem.anonymous().newRemoteActor("testActorGet", channelGet, new JacksonSerDeser<>(String.class));
var actorPut = ActorSystem.anonymous().newRemoteActorWithReturn("testActorPut", channelPut, new JacksonSerDeser<>(String.class));
var actorPost = ActorSystem.anonymous().newRemoteActorWithReturn("testActorPost", channelPut, new JacksonSerDeser<>(String.class));
var actorSync = ActorSystem.anonymous().newRemoteActorWithReturn("testActorSync", channelPut, new JacksonSerDeser<>(String.class));
System.out.println("Waiting");
Thread.sleep(1000);
System.out.println("Sending messages");
System.out.println("Received: " + actorGet.sendMessageReturn("testMessageGet").get());
actorGet2.sendMessage("testMessageGet2");
System.out.println("Received: " + actorPut.sendMessageReturn("testMessagePut").get());
System.out.println("Received: " + actorPost.sendMessageReturn("testMessagePost").get());
System.out.println("Received: " + actorSync.sendMessageReturn("testMessageSync").get());
});
}).start();
}
}
| 58.764706 | 147 | 0.687354 |
d67b5b80ae875b309fb0a7dc1398f053f7cf86b6 | 1,209 | package cn.bitflash.service;
import cn.bitflash.bean.AdminRelationBean;
import cn.bitflash.bean.UserInfoBean;
import cn.bitflash.bean.UserRelationJoinNpcAndHlbean;
import cn.bitflash.entity.UserInvitationCodeEntity;
import cn.bitflash.entity.UserRelationEntity;
import com.baomidou.mybatisplus.service.IService;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author gaoyuguo
* @date 2018年9月22日
*/
public interface UserRelationService extends IService<UserRelationEntity> {
List<UserRelationEntity> selectTreeNodes(String uid);
Boolean insertTreeNode(String pid,String uid, String code);
List<UserRelationJoinNpcAndHlbean> selectTreeNood(String f_uid);
List<UserInfoBean> selectRelationAndMobileByCode(String code);
List<UserInvitationCodeEntity> selectUserInvitationCode(String str);
List<UserRelationEntity> selectUserRelationCode(@Param("code") String code);
List<AdminRelationBean> findTree();
AdminRelationBean findNode(String realname);
List<AdminRelationBean> findCode(String fatherCode,String uid);
}
| 30.225 | 80 | 0.80976 |
3b60bc321e2f645efb9ca3dff3799b56825bfe71 | 744 | package com.regitiny.catiny.advance.service.mapper;
import com.regitiny.catiny.advance.controller.model.FriendModel;
import com.regitiny.catiny.domain.Friend;
import com.regitiny.catiny.service.dto.FriendDTO;
import com.regitiny.catiny.service.mapper.EntityMapper;
import org.mapstruct.Mapper;
import java.util.List;
@Mapper(
componentModel = "spring",
uses = {}
)
public interface FriendAdvanceMapper extends EntityAdvanceMapper<FriendModel, FriendDTO>, EntityMapper<FriendDTO, Friend>
{
FriendDTO requestToDto(FriendModel.Request request);
List<FriendDTO> requestToDto(List<FriendModel.Request> request);
FriendModel.Response dtoToResponse(FriendDTO dto);
List<FriendModel.Response> dtoToResponse(List<FriendDTO> dto);
}
| 26.571429 | 121 | 0.806452 |
be9425dd6a24505568a24b060ed2719dc987c694 | 813 | package competitive.leetcode.hard.sort;
import java.util.Arrays;
public class WiggleSortII {
public void wiggleSort(int[] nums) {
int[] m = nums.clone();
Arrays.sort(m);
int j = 0;
int lastLow = nums.length%2 == 0 ? nums.length-2 : nums.length-1;
int lastHigh = nums.length%2 == 0 ? nums.length-1 : nums.length-2;
for (int i=lastLow; i>=0; i-=2) {
nums[i] = m[j++];
}
for (int i=lastHigh; i>=1; i-=2) {
nums[i] = m[j++];
}
}
public static void main(String[] args) {
// int[] matrix = new int[] {1,3,2,2,3,1};
int[] matrix = new int[] {4,5,5,6};
new WiggleSortII().wiggleSort(matrix);
System.out.println(Arrays.toString(matrix));
}
}
| 26.225806 | 75 | 0.504305 |
5365e2240614ac8a9be552e671b787c13db562aa | 1,061 | /*
Copyright (C) 2012 Anton Lobov <zhuravlik> <ahmad200512[at]yandex.ru>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301 USA
*/
package net.jell0wed.vix4j.vendors;
import com.sun.jna.Callback;
import com.sun.jna.Pointer;
public interface IVixEventProcCallback extends Callback {
void VixEventProc(int handle, int eventType, int moreEventInfo, Pointer clientData);
} | 39.296296 | 88 | 0.764373 |
1ad4923f0d362213587d6bb0f5d6c223ac8c95ec | 1,548 | package com.amsen.par.cewlrency.base.util;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
/**
* @author Pär Amsen 2016
*/
public class CurrencyUtil {
private static boolean isCurrencySymbolBeforeValueInLocale = format(Currency.getInstance("SEK"), 0).indexOf("SEK") == 0;
public static String format(Locale locale, Currency currency, double value) {
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
format.setCurrency(currency);
format.setMaximumFractionDigits(currency.getDefaultFractionDigits());
format.setGroupingUsed(true);
String formatted = format.format(value);
if(isCurrencySymbolBeforeValueInLocale && !formatted.contains(" ")) { //ensure space in formatted to avoid "SEK123" in favor of "SEK 123" for some locales
String symbol = formatted.substring(0, currency.getSymbol().length());
String valueString = formatted.substring(currency.getSymbol().length(), formatted.length());
return symbol + " " + valueString;
}
return formatted;
}
public static String format(Currency currency, double value) {
return format(Locale.getDefault(), currency, value);
}
/**
* Returns true if currency symbol is before the
* value in the current default locale. Ex:
*
* SEK123 == true
* 123SEK == false
*/
public static boolean isCurrencySymbolBeforeValueInLocale() {
return isCurrencySymbolBeforeValueInLocale;
}
}
| 33.652174 | 162 | 0.686047 |
0138d9fce5c8bb87a45f62a968a45b8792f45b06 | 686 | package io.sphere.sdk.carts.commands.updateactions;
import io.sphere.sdk.carts.Cart;
import io.sphere.sdk.commands.UpdateActionImpl;
/**
Sets the customer email.
{@doc.gen intro}
{@include.example io.sphere.sdk.carts.commands.CartUpdateCommandIntegrationTest#setCustomerEmail()}
*/
public final class SetCustomerEmail extends UpdateActionImpl<Cart> {
private final String email;
private SetCustomerEmail(final String email) {
super("setCustomerEmail");
this.email = email;
}
public static SetCustomerEmail of(final String email) {
return new SetCustomerEmail(email);
}
public String getEmail() {
return email;
}
}
| 23.655172 | 100 | 0.715743 |
70c0e35abe587614b310f86a9601c8e7ca943d6c | 551 | class Solution {
public void XXX(int[][] matrix) {
if(matrix.length>1) {
int i=0,j=matrix.length-1;
while(i<j) {
int k=j-i;//循环次数
int l=0;
//在当前矩阵圈中 由四角互换开始 进而通过循环顺时针将四边逐步互换
while(l<k) {
int temp=matrix[i][i+l];//
matrix[i][i+l]=matrix[j-l][i];
matrix[j-l][i]=matrix[j][j-l];
matrix[j][j-l]=matrix[i+l][j];
matrix[i+l][j]=temp;
l++;//进入下一次循环
}
i++;j--;//进入矩阵下一圈
}
}
}
}
| 23.956522 | 46 | 0.413793 |
b51a5ea03434b494372337db2e5e8f4620429f51 | 3,575 | // Copyright 2017 Archos SA
//
// 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.archos.mediascraper.themoviedb3;
import android.util.Log;
import com.archos.mediascraper.FileFetcher;
import com.archos.mediascraper.FileFetcher.FileFetchResult;
import com.archos.mediascraper.ScrapeStatus;
import com.archos.mediascraper.SearchResult;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* /3/search/movie
*
* Required Parameters
* api_key
* query CGI escaped string
*
* Optional Parameters
* page
* language ISO 639-1 code.
* include_adult Toggle the inclusion of adult titles.
* year Filter results to only include this value.
*/
public class SearchMovie {
private static final String TAG = SearchMovie.class.getSimpleName();
private static final boolean DBG = false;
private static final String METHOD = "search/movie";
private static final String KEY_QUERY = "query";
private static final String KEY_LANGUAGE = "language";
private static final String KEY_YEAR = "year";
public static SearchMovieResult search(String query, String language, String year, int resultLimit, FileFetcher fetcher) {
SearchMovieResult myResult = new SearchMovieResult();
FileFetchResult fileResult = getFile(query, language, year, fetcher);
if (fileResult.status != ScrapeStatus.OKAY) {
myResult.status = fileResult.status;
return myResult;
}
List<SearchResult> parserResult = null;
try {
parserResult = SearchMovieParser.getInstance().readJsonFile(fileResult.file, resultLimit);
myResult.result = parserResult;
if (parserResult.isEmpty()) {
// retry without year since some movies are tagged wrong
if (year != null) {
if (DBG) Log.d(TAG, "retrying search for '" + query + "' without year.");
return search(query, language, null, resultLimit, fetcher);
}
myResult.status = ScrapeStatus.NOT_FOUND;
} else {
myResult.status = ScrapeStatus.OKAY;
}
} catch (IOException e) {
if (DBG) Log.e(TAG, e.getMessage(), e);
myResult.result = SearchMovieResult.EMPTY_LIST;
myResult.status = ScrapeStatus.ERROR_PARSER;
myResult.reason = e;
}
return myResult;
}
private static FileFetchResult getFile(String query, String language, String year, FileFetcher fetcher) {
Map<String, String> queryParams = new HashMap<String, String>();
TheMovieDb3.putIfNonEmpty(queryParams, KEY_QUERY, query);
TheMovieDb3.putIfNonEmpty(queryParams, KEY_LANGUAGE, language);
TheMovieDb3.putIfNonEmpty(queryParams, KEY_YEAR, year);
String requestUrl = TheMovieDb3.buildUrl(queryParams, METHOD);
if (DBG) Log.d(TAG, "REQUEST: [" + requestUrl + "]");
return fetcher.getFile(requestUrl);
}
}
| 37.631579 | 126 | 0.671049 |
e9989c745479f9111324394e6a10a2b20aefee6f | 2,226 | /*
* Comb sort
*
* http://www.mmatsubara.com/developer/sort/
*
* Copyright (c) 2015 matsubara masakazu
* Released under the MIT license
* https://github.com/m-matsubara/sort/blob/master/LICENSE.txt
*/
package mmsort;
import java.util.Comparator;
public class CombSort implements ISortAlgorithm {
/**
* Comb sort
*
* コムソート
* @param array sort target / ソート対象
* @param from index of first element / ソート対象の開始位置
* @param to index of last element (exclusive) / ソート対象の終了位置 + 1
* @param comparator comparator of array element / 比較器
*/
public static final <T> void sortImpl(final T[] array, final int from, final int to, final Comparator<? super T> comparator)
{
final int range = to - from; // ソート範囲サイズ
// ソート対象配列サイズが3以下のときは特別扱い
if (range <= 1) {
return;
} else if (range == 2) {
if (comparator.compare(array[from + 1], array[from]) < 0) {
T work = array[from];
array[from] = array[from + 1];
array[from + 1] = work;
}
return;
} else if (range == 3) {
if (comparator.compare(array[from + 1], array[from]) < 0) {
T work = array[from];
array[from] = array[from + 1];
array[from + 1] = work;
}
if (comparator.compare(array[from + 2], array[from + 1]) < 0) {
T work = array[from + 1];
array[from + 1] = array[from + 2];
array[from + 2] = work;
if (comparator.compare(array[from + 1], array[from]) < 0) {
work = array[from];
array[from] = array[from + 1];
array[from + 1] = work;
}
}
return;
}
int gap = range;
boolean done = false;
while (!done || gap > 1) {
gap = gap * 10 / 13;
if (gap == 9 || gap == 10)
gap = 11;
else if (gap == 0)
gap = 1;
done = true;
for (int i = from; i + gap < to; i++) {
if (comparator.compare(array[i + gap], array[i]) < 0) {
final T work = array[i];
array[i] = array[i + gap];
array[i + gap] = work;
done = false;
}
}
}
}
@Override
public <T> void sort(final T[] array, final int from, final int to, final Comparator<? super T> comparator)
{
sortImpl(array, from, to, comparator);
}
@Override
public boolean isStable()
{
return false;
}
@Override
public String getName()
{
return "CombSort";
}
}
| 23.431579 | 125 | 0.592543 |
1a711adac9bde49cd70147a824941661f06ec9a8 | 2,333 | /**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.lang;
import java.math.BigDecimal;
/**
* BigDecimal工具类
* @author ThinkGem
* @version 2016年6月11日
*/
public class NumberUtils extends org.apache.commons.lang3.math.NumberUtils {
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1, double v2) {
return div(v1, v2, 10);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 格式化双精度,保留两个小数
* @return
*/
public static String formatDouble(Double b) {
BigDecimal bg = new BigDecimal(b);
return bg.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 百分比计算
* @return
*/
public static String formatScale(double one, long total) {
BigDecimal bg = new BigDecimal(one * 100 / total);
return bg.setScale(0, BigDecimal.ROUND_HALF_UP).toString();
}
}
| 24.302083 | 87 | 0.651093 |
900e2b731ab492ee9ceb7897709e95724da37e93 | 5,446 | package com.yhonatan.games.koidu.hands.extractors;
import com.yhonatan.games.koidu.cards.Card;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.List;
import java.util.stream.Stream;
import static com.yhonatan.games.koidu.cards.Card.ACE_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.ACE_HEART;
import static com.yhonatan.games.koidu.cards.Card.ACE_SPADE;
import static com.yhonatan.games.koidu.cards.Card.EIGHT_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.EIGHT_HEART;
import static com.yhonatan.games.koidu.cards.Card.EIGHT_SPADE;
import static com.yhonatan.games.koidu.cards.Card.FIVE_CLUB;
import static com.yhonatan.games.koidu.cards.Card.FIVE_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.FIVE_SPADE;
import static com.yhonatan.games.koidu.cards.Card.FOUR_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.FOUR_HEART;
import static com.yhonatan.games.koidu.cards.Card.FOUR_SPADE;
import static com.yhonatan.games.koidu.cards.Card.JACK_CLUB;
import static com.yhonatan.games.koidu.cards.Card.JACK_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.JACK_HEART;
import static com.yhonatan.games.koidu.cards.Card.JACK_SPADE;
import static com.yhonatan.games.koidu.cards.Card.KING_CLUB;
import static com.yhonatan.games.koidu.cards.Card.KING_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.KING_HEART;
import static com.yhonatan.games.koidu.cards.Card.KING_SPADE;
import static com.yhonatan.games.koidu.cards.Card.NINE_CLUB;
import static com.yhonatan.games.koidu.cards.Card.NINE_HEART;
import static com.yhonatan.games.koidu.cards.Card.NINE_SPADE;
import static com.yhonatan.games.koidu.cards.Card.QUEEN_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.QUEEN_HEART;
import static com.yhonatan.games.koidu.cards.Card.QUEEN_SPADE;
import static com.yhonatan.games.koidu.cards.Card.SEVEN_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.SEVEN_HEART;
import static com.yhonatan.games.koidu.cards.Card.SEVEN_SPADE;
import static com.yhonatan.games.koidu.cards.Card.SIX_CLUB;
import static com.yhonatan.games.koidu.cards.Card.SIX_HEART;
import static com.yhonatan.games.koidu.cards.Card.SIX_SPADE;
import static com.yhonatan.games.koidu.cards.Card.TEN_CLUB;
import static com.yhonatan.games.koidu.cards.Card.TEN_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.TEN_HEART;
import static com.yhonatan.games.koidu.cards.Card.TEN_SPADE;
import static com.yhonatan.games.koidu.cards.Card.THREE_CLUB;
import static com.yhonatan.games.koidu.cards.Card.THREE_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.THREE_HEART;
import static com.yhonatan.games.koidu.cards.Card.THREE_SPADE;
import static com.yhonatan.games.koidu.cards.Card.TWO_CLUB;
import static com.yhonatan.games.koidu.cards.Card.TWO_DIAMOND;
import static com.yhonatan.games.koidu.cards.Card.TWO_HEART;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class SuitCardListExtractorTest {
private SuitCardListExtractor suitCardListExtractor = new SuitCardListExtractor();
@ParameterizedTest
@MethodSource("getTestArguments")
void suitCardListExtractorReturnsHand(final List<Card> cardList, final List<Card> expectedHand) {
final List<Card> hand = suitCardListExtractor.extractHand(cardList);
assertThat(hand, is(expectedHand));
}
private static Stream<Arguments> getTestArguments() {
return Stream.of(
//Positive
Arguments.of(List.of(ACE_HEART, THREE_HEART, FOUR_HEART, SIX_HEART, KING_HEART), List.of(ACE_HEART, THREE_HEART, FOUR_HEART, SIX_HEART, KING_HEART)),
Arguments.of(List.of(SIX_SPADE, TEN_SPADE, JACK_SPADE, QUEEN_SPADE, KING_SPADE), List.of(SIX_SPADE, TEN_SPADE, JACK_SPADE, QUEEN_SPADE, KING_SPADE)),
Arguments.of(List.of(TWO_DIAMOND, FIVE_DIAMOND, TEN_DIAMOND, JACK_DIAMOND, QUEEN_DIAMOND), List.of(TWO_DIAMOND, FIVE_DIAMOND, TEN_DIAMOND, JACK_DIAMOND, QUEEN_DIAMOND)),
Arguments.of(List.of(TWO_CLUB, THREE_CLUB, KING_CLUB, JACK_CLUB, SIX_CLUB), List.of(TWO_CLUB, THREE_CLUB, KING_CLUB, JACK_CLUB, SIX_CLUB)),
//Negative
Arguments.of(List.of(THREE_SPADE, THREE_HEART, THREE_DIAMOND, SIX_HEART, KING_SPADE), List.of()),
Arguments.of(List.of(KING_HEART, TEN_SPADE, FOUR_DIAMOND, KING_CLUB, KING_SPADE), List.of()),
Arguments.of(List.of(JACK_CLUB, JACK_HEART, QUEEN_SPADE, QUEEN_HEART, QUEEN_DIAMOND), List.of()),
Arguments.of(List.of(FOUR_HEART, TWO_HEART, SIX_SPADE, SIX_HEART, SIX_CLUB), List.of()),
Arguments.of(List.of(TEN_CLUB, TEN_SPADE, TEN_HEART, THREE_CLUB, QUEEN_SPADE), List.of()),
Arguments.of(List.of(FIVE_DIAMOND, SEVEN_SPADE, THREE_SPADE, SEVEN_HEART, SEVEN_DIAMOND), List.of()),
Arguments.of(List.of(EIGHT_DIAMOND, EIGHT_SPADE, EIGHT_HEART, SIX_HEART, THREE_HEART), List.of()),
Arguments.of(List.of(FOUR_SPADE, JACK_HEART, ACE_SPADE, ACE_DIAMOND, ACE_HEART), List.of()),
Arguments.of(List.of(FIVE_CLUB, KING_DIAMOND, NINE_SPADE, NINE_CLUB, NINE_HEART), List.of()),
Arguments.of(List.of(FIVE_DIAMOND, FIVE_DIAMOND, THREE_SPADE, FIVE_SPADE, QUEEN_HEART), List.of())
);
}
} | 61.886364 | 185 | 0.774513 |
55b2204e250591424f65ea446c83ee289b5b18c3 | 1,921 | /*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.lealone.sql.ddl;
import org.lealone.common.exceptions.DbException;
import org.lealone.db.DbObjectType;
import org.lealone.db.api.ErrorCode;
import org.lealone.db.auth.Right;
import org.lealone.db.lock.DbObjectLock;
import org.lealone.db.schema.Schema;
import org.lealone.db.schema.TriggerObject;
import org.lealone.db.session.ServerSession;
import org.lealone.db.table.Table;
import org.lealone.sql.SQLStatement;
/**
* This class represents the statement
* DROP TRIGGER
*
* @author H2 Group
* @author zhh
*/
public class DropTrigger extends SchemaStatement {
private String triggerName;
private boolean ifExists;
public DropTrigger(ServerSession session, Schema schema) {
super(session, schema);
}
@Override
public int getType() {
return SQLStatement.DROP_TRIGGER;
}
public void setTriggerName(String triggerName) {
this.triggerName = triggerName;
}
public void setIfExists(boolean b) {
ifExists = b;
}
@Override
public boolean isIfDDL() {
return ifExists;
}
@Override
public int update() {
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.TRIGGER, session);
if (lock == null)
return -1;
TriggerObject trigger = schema.findTrigger(session, triggerName);
if (trigger == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.TRIGGER_NOT_FOUND_1, triggerName);
}
} else {
Table table = trigger.getTable();
session.getUser().checkRight(table, Right.ALL);
schema.remove(session, trigger, lock);
}
return 0;
}
}
| 26.315068 | 83 | 0.664758 |
1812bdf0ab0e522edec422115ea9afc6e6c63966 | 176 | package de.ngloader.timer.api.database.config;
import de.ngloader.timer.api.config.Config;
@Config(path = "database", name = "mongodb")
public class DatabaseConfigMongoDB {
} | 25.142857 | 46 | 0.772727 |
d29aee7a11aab5dc5fa5178b09b827a86b7ead7b | 530 | /**
* MIT License
*
* SPDX:MIT
*
* https://spdx.org/licenses/MIT
*
* See LICENSE.txt file in the top level directory.
*/
package com.zed5.localchat;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
| 19.62963 | 81 | 0.666038 |
cc55ac48c971137be0c10b2c497121bd26555223 | 3,030 | /**
This question is from https://leetcode.com/problems/binary-search-tree-iterator/
Difficulty: medium
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Example:
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // return 3
iterator.next(); // return 7
iterator.hasNext(); // return true
iterator.next(); // return 9
iterator.hasNext(); // return true
iterator.next(); // return 15
iterator.hasNext(); // return true
iterator.next(); // return 20
iterator.hasNext(); // return false
Note:
next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// Stack
// T:O(N), S:O(h), h: the height of tree, 57ms(94.00%)
class BSTIterator {
Stack<TreeNode> stack;
TreeNode current;
public BSTIterator(TreeNode root) {
stack = new Stack();
current = root;
while(current != null && current.left != null){
stack.push(current);
current = current.left;
}
}
/** @return the next smallest number */
public int next() {
int val = current.val;
if(current.right == null){
if(!stack.empty()){
current = stack.pop();
}else{
current = null;
}
}else{
current = current.right;
while(current.left != null){
stack.push(current);
current = current.left;
}
}
return val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(!stack.empty() || current != null) return true;
return false;
}
}
// flatten BST
// T:O(N), S:O(N), 117ms (5.58%);
class BSTIterator {
List<Integer> list;
int index;
public BSTIterator(TreeNode root) {
list = new LinkedList();
inorder(root);
index = 0;
}
/** @return the next smallest number */
public int next() {
int val = list.get(index);
index++;
return val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(index < list.size()) return true;
return false;
}
private void inorder(TreeNode root){
if(root == null) return;
inorder(root.left);
list.add(root.val);
inorder(root.right);
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/ | 24.047619 | 142 | 0.583498 |
7648a2564571093493741f409ab55d244de85338 | 1,131 | package com.github.sherter.jcon.examples.flowvisor;
import com.github.sherter.jcon.OFMessageSerializingConsumer;
import com.github.sherter.jcon.networking.Handler;
import java.util.function.Consumer;
import org.projectfloodlight.openflow.protocol.OFMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class GuestConnectionContext {
private static final Logger log = LoggerFactory.getLogger(GuestConnectionContext.class);
final Handler handler;
final Consumer<OFMessage> sender;
final SwitchConnectionContext switchConnectionContext;
final Slice slice;
GuestConnectionContext(
Handler controllerHandler, SwitchConnectionContext switchConnectionContext, Slice slice) {
this.handler = controllerHandler;
OFMessageSerializingConsumer serializingConsumer =
new OFMessageSerializingConsumer(bytes -> controllerHandler.send(bytes));
this.sender =
m -> {
log.info("sending to guest ({}): {}", handler.remoteAddress(), m);
serializingConsumer.accept(m);
};
this.switchConnectionContext = switchConnectionContext;
this.slice = slice;
}
}
| 34.272727 | 96 | 0.766578 |
30a7ec20095a5dd3fccf92b0502af08fbcff9a9f | 5,506 | package me.spypat.UltraHarcore.events;
import java.util.ArrayList;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import me.spypat.UltraHarcore.UltraHardcore;
public class InventoryClick implements Listener {
@EventHandler
public void onInventoryClick(InventoryClickEvent event){
if(event.getCurrentItem()==null){
return;
}
if(event.getCurrentItem().getType()==null){
return;
}
if(event.getCurrentItem().getType().equals(Material.STONE_PICKAXE)){
ItemStack is = event.getCurrentItem();
if(is.hasItemMeta()){
if(is.getItemMeta().hasDisplayName()){
if(is.getItemMeta().getDisplayName().equals(ChatColor.LIGHT_PURPLE+ "Beacon Pickaxe")){
event.setCancelled(true);
}
}
}
}
if(event
.getCurrentItem()
.getType()
.equals(Material.BEACON)){
if(event.getCurrentItem().hasItemMeta()){
if(event.getCurrentItem().getItemMeta().hasDisplayName()){
if(event.getCurrentItem().getItemMeta().getDisplayName().contains("'s")){
if(event.isLeftClick()){
if(event.getWhoClicked().hasPotionEffect(PotionEffectType.DOLPHINS_GRACE)&&event.getWhoClicked().hasPotionEffect(PotionEffectType.FIRE_RESISTANCE)){
event.getWhoClicked().removePotionEffect(PotionEffectType.DOLPHINS_GRACE);
event.getWhoClicked().removePotionEffect(PotionEffectType.HEALTH_BOOST);
event.getWhoClicked().removePotionEffect(PotionEffectType.FIRE_RESISTANCE);
event.getWhoClicked().removePotionEffect(PotionEffectType.SLOW_FALLING);
event.getWhoClicked().removePotionEffect(PotionEffectType.JUMP);
for(ItemStack is : event.getWhoClicked().getInventory().getStorageContents()){
if(is!=null){
if(is.hasItemMeta()){
if(is.getItemMeta().hasDisplayName()){
if(is.getItemMeta().getDisplayName().equals(ChatColor.LIGHT_PURPLE+ "Beacon Pickaxe")){
event.getWhoClicked().getInventory().removeItem(is);
}
}
}
}
}
}else{
if(event.getWhoClicked().getInventory().getItem(8)!=null){
event.getWhoClicked().sendMessage(ChatColor.RED+"Please Clear Your Far Right Hotbar Inventory Slot!");
event.setCancelled(true);
return;
}else{
PotionEffect jump = new PotionEffect(PotionEffectType.JUMP,Integer.MAX_VALUE,1,true);
PotionEffect fire = new PotionEffect(PotionEffectType.FIRE_RESISTANCE,Integer.MAX_VALUE,1,true);
PotionEffect slow_fall = new PotionEffect(PotionEffectType.SLOW_FALLING,Integer.MAX_VALUE,1,true);
PotionEffect dolphin_grace = new PotionEffect(PotionEffectType.DOLPHINS_GRACE,Integer.MAX_VALUE,1,true);
PotionEffect health = new PotionEffect(PotionEffectType.HEALTH_BOOST,Integer.MAX_VALUE,1,true);
ArrayList<PotionEffect> effects = new ArrayList<PotionEffect>();
effects.add(jump);
effects.add(fire);
effects.add(slow_fall);
effects.add(dolphin_grace);
effects.add(health);
event.getWhoClicked().addPotionEffects(effects);
ItemStack specialPick = new ItemStack(Material.STONE_PICKAXE);
ItemMeta pickMeta = specialPick.getItemMeta();
pickMeta.setUnbreakable(true);
pickMeta.addEnchant(Enchantment.DIG_SPEED, 4, true);
pickMeta.setDisplayName(ChatColor.LIGHT_PURPLE+"Beacon Pickaxe");
specialPick.setItemMeta(pickMeta);
//add check don't overwrite items
event.getWhoClicked().getInventory().setItem(8, specialPick);
}
}
}
if(event.isRightClick()){
Inventory heads = Bukkit.createInventory(null, 9, "Collected Beacons");
if(UltraHardcore.instance.hasBeacons((Player)event.getWhoClicked())){
for(UUID uuid : UltraHardcore.instance.getBeacons((Player)event.getWhoClicked())){
ItemStack beacon = new ItemStack(Material.BEACON);
ItemMeta meta = beacon.getItemMeta();
String name = null;
for(Player p2 : Bukkit.getOnlinePlayers()){
if(p2.getUniqueId().equals(uuid)){
name = p2.getName();
}
}
if(name==null){
name = Bukkit.getServer().getOfflinePlayer(uuid).getName();
}
meta.setDisplayName(ChatColor.BLUE+name+"'s" + ChatColor.GOLD+" Beacon");
ArrayList<String> lore = new ArrayList<String>();
lore.add(uuid.toString());
meta.setLore(lore);
meta.addEnchant(Enchantment.LUCK, 1, true);
beacon.setItemMeta(meta);
heads.addItem(beacon);
}
}
event.getWhoClicked().openInventory(heads);
}
event.setCancelled(true);
}
}
}
}
}
}
| 42.353846 | 158 | 0.640937 |
19ae45a18b3ffdd071e2c0ed590ae724a5123089 | 497 | package ua.gram.model.prototype.weapon;
import com.badlogic.gdx.graphics.Color;
/**
* @author Gram <gram7gram@gmail.com>
*/
public final class LaserWeaponPrototype extends WeaponPrototype {
public Color colorBack;
public Color colorOver;
public String startBack;
public String startOver;
public String middleBack;
public String middleOver;
public String endBack;
public String endOver;
@Override
public float getDuration() {
return -1;
}
}
| 21.608696 | 65 | 0.708249 |
3ea9612ed880d0af29c3c026b003df81464b5553 | 4,480 | /*
* 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.gbif.vocabulary.client;
import org.gbif.api.model.common.paging.PagingResponse;
import org.gbif.vocabulary.api.AddTagAction;
import org.gbif.vocabulary.api.ConceptListParams;
import org.gbif.vocabulary.api.ConceptView;
import org.gbif.vocabulary.api.DeprecateConceptAction;
import org.gbif.vocabulary.model.Concept;
import org.gbif.vocabulary.model.Tag;
import org.gbif.vocabulary.model.search.KeyNameResult;
import java.util.List;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@RequestMapping("vocabularies/{vocabularyName}/concepts")
public interface ConceptClient {
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
PagingResponse<ConceptView> listConcepts(
@PathVariable("vocabularyName") String vocabularyName,
@SpringQueryMap ConceptListParams params);
@GetMapping(value = "{name}", produces = MediaType.APPLICATION_JSON_VALUE)
ConceptView get(
@PathVariable("vocabularyName") String vocabularyName,
@PathVariable("name") String conceptName,
@RequestParam(value = "includeParents", required = false) boolean includeParents,
@RequestParam(value = "includeChildren", required = false) boolean includeChildren);
@PostMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
Concept create(
@PathVariable("vocabularyName") String vocabularyName, @RequestBody Concept concept);
@PutMapping(
value = "{name}",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
Concept update(
@PathVariable("vocabularyName") String vocabularyName,
@PathVariable("name") String conceptName,
@RequestBody Concept concept);
default Concept update(String vocabularyName, Concept concept) {
return update(vocabularyName, concept.getName(), concept);
}
@GetMapping(value = "suggest", produces = MediaType.APPLICATION_JSON_VALUE)
List<KeyNameResult> suggest(
@PathVariable("vocabularyName") String vocabularyName, @RequestParam("q") String query);
@PutMapping(value = "{name}/deprecate", consumes = MediaType.APPLICATION_JSON_VALUE)
void deprecate(
@PathVariable("vocabularyName") String vocabularyName,
@PathVariable("name") String conceptName,
@RequestBody DeprecateConceptAction deprecateConceptAction);
@DeleteMapping(value = "{name}/deprecate", consumes = MediaType.APPLICATION_JSON_VALUE)
void restoreDeprecated(
@PathVariable("vocabularyName") String vocabularyName,
@PathVariable("name") String conceptName,
@RequestParam(value = "restoreDeprecatedChildren", required = false)
boolean restoreDeprecatedChildren);
@GetMapping(value = "{name}/tags", produces = MediaType.APPLICATION_JSON_VALUE)
List<Tag> listTags(
@PathVariable("vocabularyName") String vocabularyName,
@PathVariable("name") String conceptName);
@PutMapping(value = "{name}/tags", consumes = MediaType.APPLICATION_JSON_VALUE)
void addTag(
@PathVariable("vocabularyName") String vocabularyName,
@PathVariable("name") String conceptName,
@RequestBody AddTagAction addTagAction);
@DeleteMapping("{name}/tags/{tagName}")
void removeTag(
@PathVariable("vocabularyName") String vocabularyName,
@PathVariable("name") String conceptName,
@PathVariable("tagName") String tagName);
}
| 42.264151 | 94 | 0.766964 |
2fc335e8224abd8ee39026cdd133e621b33d0aba | 3,699 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|segment
operator|.
name|test
operator|.
name|proxy
package|;
end_package
begin_import
import|import
name|io
operator|.
name|netty
operator|.
name|buffer
operator|.
name|ByteBuf
import|;
end_import
begin_import
import|import
name|io
operator|.
name|netty
operator|.
name|buffer
operator|.
name|Unpooled
import|;
end_import
begin_import
import|import
name|io
operator|.
name|netty
operator|.
name|channel
operator|.
name|ChannelHandlerContext
import|;
end_import
begin_import
import|import
name|io
operator|.
name|netty
operator|.
name|channel
operator|.
name|ChannelInboundHandlerAdapter
import|;
end_import
begin_class
class|class
name|SkipHandler
extends|extends
name|ChannelInboundHandlerAdapter
block|{
specifier|private
name|int
name|cur
decl_stmt|;
specifier|private
name|int
name|pos
decl_stmt|;
specifier|private
name|int
name|len
decl_stmt|;
name|SkipHandler
parameter_list|(
name|int
name|pos
parameter_list|,
name|int
name|len
parameter_list|)
block|{
name|this
operator|.
name|pos
operator|=
name|pos
expr_stmt|;
name|this
operator|.
name|len
operator|=
name|len
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|channelRead
parameter_list|(
name|ChannelHandlerContext
name|ctx
parameter_list|,
name|Object
name|msg
parameter_list|)
throws|throws
name|Exception
block|{
if|if
condition|(
name|msg
operator|instanceof
name|ByteBuf
condition|)
block|{
name|onByteBuf
argument_list|(
name|ctx
argument_list|,
operator|(
name|ByteBuf
operator|)
name|msg
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|ctx
operator|.
name|fireChannelRead
argument_list|(
name|msg
argument_list|)
expr_stmt|;
block|}
block|}
specifier|private
name|void
name|onByteBuf
parameter_list|(
name|ChannelHandlerContext
name|ctx
parameter_list|,
name|ByteBuf
name|in
parameter_list|)
block|{
name|ByteBuf
name|out
init|=
name|Unpooled
operator|.
name|buffer
argument_list|()
decl_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|in
operator|.
name|readableBytes
argument_list|()
condition|;
name|i
operator|++
control|)
block|{
if|if
condition|(
name|cur
operator|<
name|pos
operator|||
name|pos
operator|+
name|len
operator|<=
name|cur
condition|)
block|{
name|out
operator|.
name|writeByte
argument_list|(
name|in
operator|.
name|getByte
argument_list|(
name|i
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|cur
operator|++
expr_stmt|;
block|}
if|if
condition|(
name|out
operator|.
name|readableBytes
argument_list|()
operator|>
literal|0
condition|)
block|{
name|ctx
operator|.
name|fireChannelRead
argument_list|(
name|out
argument_list|)
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
| 14.975709 | 810 | 0.786429 |
40a5e4cb57c9b011df6c6386c7e3bfbd7ecfdf0a | 4,076 | package com.ovit.manager.modules.nswy.web.dictionaryManagement;
import com.ovit.manager.common.persistence.Page;
import com.ovit.manager.common.web.BaseController;
import com.ovit.manager.modules.nswy.entity.dictionaryManagement.DictionaryTown;
import com.ovit.manager.modules.nswy.service.dictionaryManagement.DictionaryTownService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("${adminPath}/nswy/dictionaryTown")
public class DictionaryTownController extends BaseController {
@Autowired
private DictionaryTownService dictionaryTownService;
@RequestMapping("/control")
public String findList(DictionaryTown dictionaryTown, Model model, HttpServletRequest request, HttpServletResponse response){
// Page<DictionaryTown> page = dictionaryTownService.findList(dictionaryTown,request,response);
List<DictionaryTown> page = dictionaryTownService.findList(dictionaryTown);
model.addAttribute("list",page);
return "modules/content/dictionaryManagement/dictionaryTownList";
}
@RequestMapping(value = "/add")
public String add(@RequestParam(value = "id") String id,@RequestParam(value = "level") Integer level, Model model){
model.addAttribute("pid",id);
model.addAttribute("level",level+1);
return "modules/content/dictionaryManagement/dictionaryTownAdd";
}
@RequestMapping(value = "/addPid")
public String addPid(@RequestParam(value = "pid") String pid,@RequestParam(value = "level") Integer level,Model model){
model.addAttribute("pid",pid);
model.addAttribute("level",level);
return "modules/content/dictionaryManagement/dictionaryTownAdd";
}
@RequestMapping(value = "/save")
public String saveTown( HttpServletRequest request,DictionaryTown dictionaryTown){
try {
String name = request.getParameter("name");
String pid = request.getParameter("pid");
String value = request.getParameter("value");
String remark = request.getParameter("remark");
Integer level = Integer.parseInt(request.getParameter("level"));
dictionaryTown.setId(UUID.randomUUID().toString().trim().replaceAll("-", ""));
dictionaryTown.setName(name);
dictionaryTown.setValue(value);
dictionaryTown.setRemark(remark);
dictionaryTown.setPid(pid);
dictionaryTown.setLevel(level);
dictionaryTownService.saveTown(dictionaryTown);
} catch (Exception e) {
System.out.println(e);
}
return "redirect:" + adminPath +"/nswy/dictionaryTown/control/";
}
@RequestMapping(value = "/update")
public String update(@RequestParam String id,Model model){
DictionaryTown dictionaryTown = new DictionaryTown();
dictionaryTown.setId(id);
List<DictionaryTown> dictionaryTowns = dictionaryTownService.findTownList(dictionaryTown);
model.addAttribute("dictionaryTown",dictionaryTowns.get(0));
return "modules/content/dictionaryManagement/dictionaryTownFrom";
}
@RequestMapping(value = "/updateTown")
public String updateTown( HttpServletRequest request,DictionaryTown dictionaryTown){
try {
dictionaryTownService.updateTown(dictionaryTown);
} catch (Exception e) {
System.out.println(e);
}
return "redirect:" + adminPath +"/nswy/dictionaryTown/control/";
}
@RequestMapping(value = "/delete")
public String deleteTown(@RequestParam String id){
dictionaryTownService.deleteTown(id);
return "redirect:" + adminPath +"/nswy/dictionaryTown/control/";
}
}
| 38.819048 | 129 | 0.713445 |
89ad88491517c6f4c4730861ff1df8c59d4bdb37 | 1,351 | package com.github.jayreturns.jbbedwars;
import com.github.jayreturns.jbbedwars.listener.BedDestroyListener;
import com.github.jayreturns.jbbedwars.listener.ClickShopkeeperListener;
import com.github.jayreturns.jbbedwars.listener.PlayerConnectionListener;
import com.github.jayreturns.jbbedwars.listener.ShopMenuListener;
import com.github.jayreturns.jbbedwars.shopkeeper.CreateShopkeeper;
import lombok.Getter;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import java.io.File;
public class JBBedwars extends JavaPlugin {
@Getter
private static JBBedwars instance;
@Override
public void onEnable() {
instance = this;
getLogger().info("Plugin activated");
//GameManager.maxPlayers = 8;
registerListeners();
registerCommands();
}
private void registerListeners() {
new PlayerConnectionListener(this);
new BedDestroyListener(this);
new ClickShopkeeperListener(this);
new ShopMenuListener(this);
}
private void registerCommands() {
getCommand("shopkeeper").setExecutor(new CreateShopkeeper());
}
// For Testing
public JBBedwars() {
super();
}
protected JBBedwars(JavaPluginLoader loader, PluginDescriptionFile descriptionFile, File dataFolder, File file) {
super(loader, descriptionFile, dataFolder, file);
}
}
| 25.490566 | 114 | 0.793486 |
36437d167c2f731b9d23ea4377e2772c2f6231e3 | 12,494 | package clients.symphony.api;
import clients.ISymClient;
import clients.symphony.api.constants.PodConstants;
import exceptions.SymClientException;
import exceptions.UnauthorizedException;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import lombok.*;
import model.UserPresence;
import model.UserPresenceCategory;
@RequiredArgsConstructor
public class PresenceClient extends APIClient {
private final ISymClient botClient;
/**
* Returns the online status of the specified user.
*
* @param userId The unique ID of the user.
* @param local true: Perform a local query and set the presence to OFFLINE for users who are not local to the calling
* user’s pod.
* @return a user presence status
* @since 1.47
*/
public UserPresence getUserPresence(@Nonnull Long userId, boolean local) throws SymClientException {
final Invocation.Builder builder = this.getTarget()
.path(PodConstants.GETUSERPRESENCE.replace("{uid}", Long.toString(userId)))
.queryParam("local", local)
.request(MediaType.APPLICATION_JSON)
.header("sessionToken", botClient.getSymAuth().getSessionToken());
try (final Response response = builder.get()) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
try {
handleError(response, botClient);
} catch (UnauthorizedException ex) {
return getUserPresence(userId, local);
}
return null;
}
return response.readEntity(UserPresence.class);
}
}
/**
* Returns the online status of the calling user.
*
* @return the calling user presence status
* @since 1.47
*/
public UserPresence getUserPresence() throws SymClientException {
final Invocation.Builder builder = this.getTarget()
.path(PodConstants.GET_OR_SET_PRESENCE)
.request(MediaType.APPLICATION_JSON)
.header("sessionToken", botClient.getSymAuth().getSessionToken());
try (final Response response = builder.get()) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
try {
handleError(response, botClient);
} catch (UnauthorizedException ex) {
return getUserPresence();
}
return null;
}
return response.readEntity(UserPresence.class);
}
}
/**
* Returns the presence of all users in a pod
* @param lastUserId Last user ID retrieved, used for paging. If provided, results skip users with IDs less than this
* parameter.
* @param limit Maximum number of records to return. The maximum supported value is 5000.
* @return a list of user presence
* @since 1.47
*/
public List<UserPresence> getAllPresence(@Nullable Long lastUserId, @Nullable Integer limit) throws SymClientException {
WebTarget target = this.getTarget();
if (lastUserId != null) {
target = target.queryParam("lastUserId", lastUserId);
}
if (limit != null) {
if (limit > 5000) {
throw new IllegalArgumentException("The maximum supported value for the limit is 5000.");
}
target = target.queryParam("limit", limit);
}
final Invocation.Builder builder = target.path(PodConstants.GET_ALL_PRESENCE)
.request(MediaType.APPLICATION_JSON)
.header("sessionToken", botClient.getSymAuth().getSessionToken());
try (final Response response = builder.get()) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
try {
handleError(response, botClient);
} catch (UnauthorizedException ex) {
return getAllPresence(lastUserId, limit);
}
return null;
}
return response.readEntity(new GenericType<List<UserPresence>>() {});
}
}
/**
* Sets the online status of the calling user.
*
* @param category he new presence state for the user. Possible values are AVAILABLE, BUSY, AWAY, ON_THE_PHONE, BE_RIGHT_BACK,
* IN_A_MEETING, OUT_OF_OFFICE, OFF_WORK.
* @return the online status of the calling user.
* @since 1.47
*/
public UserPresence setPresence(@Nonnull UserPresenceCategory category) throws SymClientException {
final Invocation.Builder builder = this.getTarget()
.path(PodConstants.GET_OR_SET_PRESENCE)
.request(MediaType.APPLICATION_JSON)
.header("sessionToken", botClient.getSymAuth().getSessionToken());
try (Response response = builder.post(Entity.entity(new Category(category), MediaType.APPLICATION_JSON))) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
try {
handleError(response, botClient);
} catch (UnauthorizedException ex) {
return setPresence(category);
}
return null;
}
return response.readEntity(UserPresence.class);
}
}
/**
* @deprecated Use {@link PresenceClient#setPresence(UserPresenceCategory)} instead.
* @param status Authenticated user presence status
* @return current user presence
*/
@Deprecated
public UserPresence setPresence(@Nonnull String status) throws SymClientException {
return this.setPresence(UserPresenceCategory.valueOf(status));
}
/**
* To get the presence state of external users, you must first register interest in those users using this endpoint.
*
* @param userIds A list of users whom you want to query the presence of, specified by their userId.
* @since 1.44
*/
public void registerInterestExtUser(@Nonnull List<Long> userIds) throws SymClientException {
final Invocation.Builder builder = this.getTarget()
.path(PodConstants.REGISTERPRESENCEINTEREST)
.request(MediaType.APPLICATION_JSON)
.header("sessionToken", botClient.getSymAuth().getSessionToken());
try (Response response = builder.post(Entity.entity(userIds, MediaType.APPLICATION_JSON))) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
try {
handleError(response, botClient);
} catch (UnauthorizedException ex) {
registerInterestExtUser(userIds);
}
}
}
}
/**
* Creates a new stream capturing online status changes ("presence feed") for the company (pod) and returns
* the ID of the new feed. The feed will return the presence of users whose presence status has changed since it
* was last read.
*
* @return a presence feed id
* @since 1.48
*/
public String createPresenceFeed() throws SymClientException {
final Invocation.Builder builder = this.getTarget()
.path(PodConstants.PRESENCE_FEED_CREATE)
.request(MediaType.APPLICATION_JSON)
.header("sessionToken", botClient.getSymAuth().getSessionToken());
try (Response response = builder.post(Entity.entity("{}", MediaType.APPLICATION_JSON))) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
try {
handleError(response, botClient);
} catch (UnauthorizedException ex) {
return this.createPresenceFeed();
}
return null;
}
return response.readEntity(PresenceFeedCreationResponse.class).getId();
}
}
/**
* Reads the specified presence feed that was created using the Create Presence feed endpoint.
* The feed returned includes the user presence statuses that have changed since they were last read.
*
* @param feedId Presence feed ID, obtained from Create Presence Feed.
* @return a list of user presence
* @since 1.48
*/
public List<UserPresence> readPresenceFeed(@Nonnull String feedId) throws SymClientException {
final Invocation.Builder builder = this.getTarget()
.path(PodConstants.PRESENCE_FEED_READ.replace("{feedId}", feedId))
.request(MediaType.APPLICATION_JSON)
.header("sessionToken", botClient.getSymAuth().getSessionToken());
try (Response response = builder.post(Entity.entity("{}", MediaType.APPLICATION_JSON))) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
try {
handleError(response, botClient);
} catch (UnauthorizedException ex) {
return this.readPresenceFeed(feedId);
}
return null;
}
return response.readEntity(new GenericType<List<UserPresence>>() {});
}
}
/**
* Deletes a presence status feed. This endpoint returns the ID of the deleted feed if the deletion is successful.
*
* @param feedId Presence feed ID, obtained from Create Presence Feed.
* @since 1.48
*/
public void deletePresenceFeed(@Nonnull String feedId) throws SymClientException {
final Invocation.Builder builder = this.getTarget()
.path(PodConstants.PRESENCE_FEED_DELETE.replace("{feedId}", feedId))
.request(MediaType.APPLICATION_JSON)
.header("sessionToken", botClient.getSymAuth().getSessionToken());
try (final Response response = builder.delete()) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
try {
handleError(response, botClient);
} catch (UnauthorizedException ex) {
this.deletePresenceFeed(feedId);
}
}
}
}
/**
* Sets the presence state of a another user.
*
* @param userId User ID as a decimal integer. Use this field to set the presence of a different user than the calling user.
* @param category Presence state to set.
* @return the user presence
* @since 1.49
*/
public UserPresence setOtherUserPresence(@Nonnull Long userId, @Nonnull UserPresenceCategory category)
throws SymClientException {
final Invocation.Builder builder = this.getTarget()
.path(PodConstants.SET_OTHER_USER_PRESENCE)
.request(MediaType.APPLICATION_JSON)
.header("sessionToken", this.botClient.getSymAuth().getSessionToken());
OtherUserPresenceRequest otherUserPresenceRequest = new OtherUserPresenceRequest(userId, category);
try (final Response response = builder.post(Entity.entity(otherUserPresenceRequest, MediaType.APPLICATION_JSON_TYPE))) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
try {
handleError(response, this.botClient);
} catch (UnauthorizedException ex) {
return this.setOtherUserPresence(userId, category);
}
return null;
}
return response.readEntity(UserPresence.class);
}
}
private WebTarget getTarget() {
return this.botClient.getPodClient().target(this.botClient.getConfig().getPodUrl());
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
private static class OtherUserPresenceRequest {
private Long userId;
private UserPresenceCategory category;
}
@Getter
@Setter
private static class PresenceFeedCreationResponse {
private String id;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
private static class Category {
private UserPresenceCategory category;
}
}
| 39.663492 | 130 | 0.628302 |
9263cbac9495add23195dd2646bddb64870d205e | 923 | package com.xiaomi.common.logger.thrift.mfs;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public enum a$a
{
private static final Map<String, a> c;
private final short d;
private final String e;
static
{
a[] arrayOfa = new a[2];
arrayOfa[0] = a;
arrayOfa[1] = b;
f = arrayOfa;
c = new HashMap();
Iterator localIterator = EnumSet.allOf(a.class).iterator();
while (localIterator.hasNext())
{
a locala = (a)localIterator.next();
c.put(locala.a(), locala);
}
}
private a$a(short paramShort, String paramString)
{
this.d = paramShort;
this.e = paramString;
}
public final String a()
{
return this.e;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.xiaomi.common.logger.thrift.mfs.a.a
* JD-Core Version: 0.6.0
*/ | 20.977273 | 83 | 0.63922 |
241812f18431a920f8f3c3f620f22acfff5cf962 | 1,672 | package com.divae.firstspirit;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static com.divae.firstspirit.Proxy.with;
import static java.lang.reflect.Modifier.PRIVATE;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class ProxyTest {
@Test(expected = InvocationTargetException.class)
public void testDefaultConstructor() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor<?> declaredConstructor = Proxy.class.getDeclaredConstructor();
assertThat(declaredConstructor.getModifiers(), is(PRIVATE));
declaredConstructor.setAccessible(true);
declaredConstructor.newInstance();
}
@Test
public void aTargetClass() throws Exception {
TestInterface test = () -> "test";
assertThat(Proxy.<TestInterface, Test2Interface>proxy(with(test, TestInterface.class).aTarget(Test2Interface.class)).getTest(), is("test"));
}
@Test
public void aTargetTClass() throws Exception {
TestInterface test = () -> "test";
Test2Interface target = () -> "targetTest";
assertThat(Proxy.<TestInterface, Test2Interface>proxy(with(test, TestInterface.class).aTarget(target, Test2Interface.class)).getTest(), is("test"));
assertThat(Proxy.<Test2Interface, TestInterface>proxy(with(target, Test2Interface.class).aTarget(TestInterface.class)).getTest(), is("targetTest"));
}
interface TestInterface {
String getTest();
}
interface Test2Interface {
String getTest();
}
} | 36.347826 | 156 | 0.727871 |
ceeb3a7bfd39ad6415c63a6b27c6fda71b655cdb | 2,949 | /*
* #%L
* Native ARchive plugin for Maven
* %%
* Copyright (C) 2002 - 2014 NAR Maven Plugin developers.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*
* 2014/09/18 Modified by Stephen Edwards:
* Make a public API for extracting NAR config
*/
package com.github.maven_nar;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Java specifications for NAR
*
* @author Mark Donszelmann
*/
public class Java {
/**
* Add Java includes to includepath
*
* @parameter default-value="false"
* @required
*/
private boolean include = false;
/**
* Java Include Paths, relative to a derived ${java.home}. Defaults to:
* "${java.home}/include" and "${java.home}/include/<i>os-specific</i>".
*
* @parameter default-value=""
*/
private List includePaths;
/**
* Add Java Runtime to linker
*
* @parameter default-value="false"
* @required
*/
private boolean link = false;
/**
* Relative path from derived ${java.home} to the java runtime to link with
* Defaults to Architecture-OS-Linker specific value. FIXME table missing
*
* @parameter default-value=""
*/
private String runtimeDirectory;
/**
* Name of the runtime
*
* @parameter default-value="jvm"
*/
private String runtime = "jvm";
private AbstractCompileMojo mojo;
public Java() {
}
public final void setAbstractCompileMojo(AbstractCompileMojo mojo) {
this.mojo = mojo;
}
public void setInclude(boolean include) {
this.include = include;
}
public final List /* <String> */getIncludePaths() throws MojoFailureException, MojoExecutionException {
List jIncludePaths = new ArrayList();
if (include) {
if (includePaths != null) {
for (Iterator i = includePaths.iterator(); i.hasNext();) {
String path = (String) i.next();
jIncludePaths.add(new File(mojo.getJavaHome(mojo.getAOL()), path).getPath());
}
} else {
String prefix = mojo.getAOL().getKey() + ".java.";
String includes = mojo.getNarProperties().getProperty(prefix + "include");
if (includes != null) {
String[] path = includes.split(";");
for (int i = 0; i < path.length; i++) {
jIncludePaths.add(new File(mojo.getJavaHome(mojo.getAOL()), path[i]).getPath());
}
}
}
}
return jIncludePaths;
}
}
| 25.868421 | 104 | 0.679891 |
ba93c2994fcb32304279e9d4ab1f949abb5e3835 | 3,289 | /**
* Copyright 2011-2019 Asakusa Framework Team.
*
* 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.asakusafw.dag.runtime.directio;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import com.asakusafw.dag.api.counter.CounterGroup;
import com.asakusafw.dag.api.counter.basic.BasicCounterGroupCategory;
import com.asakusafw.dag.api.counter.basic.StandardColumn;
import com.asakusafw.lang.utils.common.Arguments;
import com.asakusafw.lang.utils.common.Invariants;
import com.asakusafw.runtime.directio.Counter;
/**
* An implementation of {@link CounterGroup} for Direct I/O.
* @since 0.4.0
*/
public class DirectFileCounterGroup implements CounterGroup {
/**
* The {@link CounterGroup} category for Direct I/O file inputs.
*/
public static final Category<DirectFileCounterGroup> CATEGORY_INPUT = new BasicCounterGroupCategory<>(
"Direct I/O file input",
Scope.GRAPH,
Arrays.asList(StandardColumn.INPUT_FILE_SIZE, StandardColumn.INPUT_RECORD),
"directio-0-input", //$NON-NLS-1$
() -> new DirectFileCounterGroup(StandardColumn.INPUT_FILE_SIZE, StandardColumn.INPUT_RECORD));
/**
* The {@link CounterGroup} category for Direct I/O file outputs.
*/
public static final Category<DirectFileCounterGroup> CATEGORY_OUTPUT = new BasicCounterGroupCategory<>(
"Direct I/O file output",
Scope.GRAPH,
Arrays.asList(StandardColumn.OUTPUT_FILE_SIZE, StandardColumn.OUTPUT_RECORD),
"directio-1-output", //$NON-NLS-1$
() -> new DirectFileCounterGroup(StandardColumn.OUTPUT_FILE_SIZE, StandardColumn.OUTPUT_RECORD));
private final Map<Column, Counter> counters = new LinkedHashMap<>();
private final Counter fileSize = new Counter();
private final Counter recordCount = new Counter();
/**
* Creates a new instance.
* @param fileSize the file size in bytes
* @param recordCount the record count
*/
public DirectFileCounterGroup(Column fileSize, Column recordCount) {
Arguments.requireNonNull(fileSize);
Arguments.requireNonNull(recordCount);
counters.put(fileSize, this.fileSize);
counters.put(recordCount, this.recordCount);
}
@Override
public long getCount(Column column) {
Counter counter = counters.get(column);
Invariants.requireNonNull(counter);
return counter.get();
}
/**
* Returns the file size.
* @return the file size
*/
public Counter getFileSize() {
return fileSize;
}
/**
* Returns the record count.
* @return the record count
*/
public Counter getRecordCount() {
return recordCount;
}
}
| 34.260417 | 109 | 0.695652 |
fedc1c6966deedd8256ccd5aaba7bd5ece618e68 | 4,676 | package com.vimukti.accounter.web.client.core;
public class ClientTAXRateCalculation implements IAccounterCore {
/**
*
*/
private static final long serialVersionUID = 1L;
public long id;
/**
* The rate by which the total amount of the transaction is laid on.
*/
double vatAmount;
double lineTotal;
String vatItem;
long transactionDate;
long transactionItem;
boolean isVATGroupEntry;
ClientTAXAgency taxAgency;
double rate;
ClientVATReturnBox vatReturnBox;
ClientAccount purchaseLiabilityAccount;
ClientAccount salesLiabilityAccount;
ClientTAXReturn vatReturn;
private int version;
public ClientTAXRateCalculation() {
}
/**
* @return the clientVATReturn
*/
public ClientTAXReturn getClientVATReturn() {
return vatReturn;
}
/**
* @param clientVATReturn
* the clientVATReturn to set
*/
public void setClientVATReturn(ClientTAXReturn clientVATReturn) {
this.vatReturn = clientVATReturn;
}
/**
* @return the id
*/
public long getID() {
return id;
}
/**
* @param id
* the id to set
*/
public void setID(long id) {
this.id = id;
}
/**
* @return the vatAmount
*/
public double getVatAmount() {
return vatAmount;
}
/**
* @param vatAmount
* the vatAmount to set
*/
public void setVatAmount(double vatAmount) {
this.vatAmount = vatAmount;
}
/**
* @return the vatItem id=223774 pd=dhanush@123
*/
public String getVatItem() {
return vatItem;
}
/**
* @param vatItem
* the vatItem to set
*/
public void setVatItem(String vatItem) {
this.vatItem = vatItem;
}
/**
* @return the transactionDate
*/
public long getTransactionDate() {
return transactionDate;
}
/**
* @param transactionDate
* the transactionDate to set
*/
public void setTransactionDate(long transactionDate) {
this.transactionDate = transactionDate;
}
/**
* @return the transactionItem
*/
public long getTransactionItem() {
return transactionItem;
}
/**
* @param transactionItem
* the transactionItem to set
*/
public void setTransactionItem(long transactionItem) {
this.transactionItem = transactionItem;
}
/**
* @return the isVATGroupEntry
*/
public boolean isVATGroupEntry() {
return isVATGroupEntry;
}
/**
* @param isVATGroupEntry
* the isVATGroupEntry to set
*/
public void setVATGroupEntry(boolean isVATGroupEntry) {
this.isVATGroupEntry = isVATGroupEntry;
}
@Override
public String getDisplayName() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public AccounterCoreType getObjectType() {
return null;
}
public double getLineTotal() {
return lineTotal;
}
public void setLineTotal(double lineTotal) {
this.lineTotal = lineTotal;
}
public ClientTAXAgency getTaxAgency() {
return taxAgency;
}
public void setVatAgency(ClientTAXAgency taxAgency) {
this.taxAgency = taxAgency;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public ClientVATReturnBox getVatReturnBox() {
return vatReturnBox;
}
public void setVatReturnBox(ClientVATReturnBox vatReturnBox) {
this.vatReturnBox = vatReturnBox;
}
public ClientAccount getPurchaseLiabilityAccount() {
return purchaseLiabilityAccount;
}
public void setPurchaseLiabilityAccount(
ClientAccount purchaseLiabilityAccount) {
this.purchaseLiabilityAccount = purchaseLiabilityAccount;
}
public ClientAccount getSalesLiabilityAccount() {
return salesLiabilityAccount;
}
public void setSalesLiabilityAccount(ClientAccount salesLiabilityAccount) {
this.salesLiabilityAccount = salesLiabilityAccount;
}
// public ClientVATRateCalculation(String vatItem,
// String transactonItem) {
//
// this.transactionItem = transactonItem;
// this.vatItem = vatItem;
// this.vatAmount = transactonItem.getVATfraction();
// this.transactionDate = transactionItem.getTransaction().getDate();
//
// }
public ClientTAXRateCalculation clone() {
ClientTAXRateCalculation taxRateCalculation = (ClientTAXRateCalculation) this
.clone();
taxRateCalculation.purchaseLiabilityAccount = this.purchaseLiabilityAccount
.clone();
taxRateCalculation.salesLiabilityAccount = this.salesLiabilityAccount
.clone();
taxRateCalculation.taxAgency = this.taxAgency.clone();
taxRateCalculation.vatReturn = this.vatReturn.clone();
taxRateCalculation.vatReturnBox = this.vatReturnBox.clone();
return taxRateCalculation;
}
@Override
public int getVersion() {
return version;
}
@Override
public void setVersion(int version) {
this.version = version;
}
}
| 19.483333 | 79 | 0.71728 |
8a3486d3535581afb9b1902ead4b8cdd69bb745e | 1,839 | package net.xisberto.magicmuzei.model;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import com.google.android.apps.muzei.api.Artwork;
import com.orm.SugarRecord;
/**
* Represents information about a Wallpaper
*/
public class WallpaperInfo extends SugarRecord<WallpaperInfo> implements Parcelable {
public static final Creator<WallpaperInfo> CREATOR = new Creator<WallpaperInfo>() {
@Override
public WallpaperInfo createFromParcel(Parcel in) {
return new WallpaperInfo(in);
}
@Override
public WallpaperInfo[] newArray(int size) {
return new WallpaperInfo[size];
}
};
public String title;
public String author;
public String url;
public WallpaperInfo() {
}
public WallpaperInfo(String title, String author, String url) {
this.title = title;
this.author = author;
this.url = url;
}
protected WallpaperInfo(Parcel in) {
title = in.readString();
author = in.readString();
url = in.readString();
}
public static WallpaperInfo fromArtwork(@NonNull Artwork artwork) {
return new WallpaperInfo(
artwork.getTitle(),
artwork.getByline(),
artwork.getImageUri().toString());
}
public Artwork toArtwork() {
return new Artwork.Builder()
.title(title)
.byline(author)
.imageUri(Uri.parse(url))
.build();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(author);
dest.writeString(url);
}
}
| 25.541667 | 87 | 0.617183 |
76b1d747f769e40f7ae7907abb27dd37ee78b426 | 1,600 | package com.huotu.fanmore.pinkcatraiders.widget;
import android.os.CountDownTimer;
import android.widget.TextView;
import com.huotu.fanmore.pinkcatraiders.R;
public class CountDownTimerButton extends CountDownTimer
{
public interface CountDownFinishListener{
void finish();
}
TextView view;
String txt;
String formatTxt;
CountDownFinishListener finishListener=null;
public CountDownTimerButton(TextView view, String formatTxt, String txt, long millisInFuture, CountDownFinishListener listener) {
super(millisInFuture, 1000 );
this.view= view;
this.formatTxt = formatTxt;
this.txt = txt;
this.view.setText(txt);
this.view.setClickable(false);
//this.view.setBackgroundColor(Color.parseColor("#999999"));
this.view.setBackgroundResource(R.drawable.btn_mark_gray);
finishListener = listener;
}
@Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
String content = String.format(formatTxt, millisUntilFinished / 1000);
view.setText( content );
}
@Override
public void onFinish()
{
// TODO Auto-generated method stub
view.setClickable(true);
view.setText(txt);
//view.setBackgroundColor(Color.parseColor("#0096FF"));
view.setBackgroundResource(R.drawable.btn_login);
if( finishListener!=null){
finishListener.finish();
}
}
public void Stop(){
this.cancel();
}
}
| 27.118644 | 133 | 0.64875 |
ebcf543edaa58d3bbbf4abee52039f7c9dc1da60 | 1,996 | package foobank;
import java.io.IOException;
import java.net.URI;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import foobank.service.BankAccountServiceImpl;
/**
* Main class.
*
*/
public class Main {
// Base URI the Grizzly HTTP server will listen on
public static final String BASE_URI = System.getProperty("foobank.uri", "http://localhost:5617/foobank/");
static {
Logger logger = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler");
logger.setLevel(Level.FINE);
logger.setUseParentHandlers(false);
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.ALL);
logger.addHandler(consoleHandler);
}
/**
* Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
* @return Grizzly HTTP server.
*/
public static HttpServer startServer() {
// create a resource config that scans for JAX-RS resources and providers
// in foobank package
final ResourceConfig rc = new ResourceConfig().registerClasses(BankAccountServiceImpl.class);
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
/**
* Main method.
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
final HttpServer server = startServer();
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
System.in.read();
server.stop();
}
}
| 33.266667 | 110 | 0.693387 |
08d7632bd9962a3ba8fb2d1e95a63c01bff24c5c | 2,513 | /* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
public class Matrix {
// 向量点乘
public static double dot(double[] x, double[] y) {
double re = 0.0;
for (int i = 0; i < x.length; i++) {
re += x[i] * y[i];
}
return re;
}
// 矩阵相乘
public static double[][] mult(double[][] a, double[][] b) {
int m = a.length;
int n = a[0].length;
int p = b[0].length;
double[][] re = new double[m][p];
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < n; k++) {
re[i][j] += a[i][k] * b[k][j];
}
}
}
return re;
}
// 矩阵转置
public static double[][] transpose(double[][] a) {
int m = a.length;
int n = a[0].length;
double[][] re = new double[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
re[j][i] = a[i][j];
}
}
return re;
}
//矩阵与向量的乘积---线性方程组
public static double[] multLinear(double[][] a, double[] x) {
int m = a.length;
int n = x.length;
double[] re = new double[m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) re[i] += a[i][j] * x[j];
}
return re;
}
public static void main(String[] args) {
// test dot ///////////////////////////////
// double[] a = { 1, 2, 3 };
// double[] b = { -1, -1, -1 };
// double k = Matrix.dot(a, b);
// StdOut.print(k);
// test mult ///////////////////
// double[][] a = { { 1, 2, 3 }, { 2, 4, 6 } };
// double[][] b = { { 1, 1, }, { -1, -1 }, { 0, 0 } };
// double[][] k = Matrix.mult(a, b);
// System.out.print(k[1][0]);
// test transpose ///////////////////////////////////
// double[][] a = { { 1, 2, 3 }, { 2, 4, 6 } };
// double[][] k = Matrix.transpose(a);
// System.out.print(k[2][0]);
// test multLinear ///////////////////////////////////
double[][] a = { { 1, 2, 3 }, { 2, 4, 6 } };
double[] b = { 1, 1, 1 };
double[] k = Matrix.multLinear(a, b);
System.out.print(k[1]);
}
}
| 31.810127 | 80 | 0.339435 |
933770d4f89f1987bbf820ea08518fcc4a7eeeb7 | 1,316 | package io.ashimjk.spring.integration.sample;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.Pollers;
import org.springframework.integration.dsl.Transformers;
import org.springframework.integration.jdbc.JdbcPollingChannelAdapter;
import javax.sql.DataSource;
@Configuration
@EnableIntegration
@IntegrationComponentScan
public class InboundChannelAdaptersConfig {
private DataSource dataSource;
@Bean
public MessageSource<Object> jdbcMessageSource() {
return new JdbcPollingChannelAdapter(this.dataSource, "SELECT * FROM something");
}
@Bean
public IntegrationFlow pollingFlow() {
return IntegrationFlows.from(jdbcMessageSource(),
c -> c.poller(Pollers.fixedRate(100).maxMessagesPerPoll(1)))
.transform(Transformers.toJson())
.channel("furtherProcessChannel")
.get();
}
}
| 34.631579 | 89 | 0.777356 |
7a3a7c366aa3f0cb1dbcfbc43e78000b90f36ed1 | 3,049 | package com.hjcenry.kcp;
import com.hjcenry.codec.encode.IMessageEncoder;
import com.hjcenry.log.KtucpLog;
import com.hjcenry.threadpool.ITask;
import com.hjcenry.time.IKtucpTimeService;
import com.hjcenry.util.ReferenceCountUtil;
import com.hjcenry.fec.fec.Snmp;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import java.util.Queue;
/**
* Created by JinMiao
* 2018/9/11.
*/
public class WriteTask implements ITask {
protected static final Logger logger = KtucpLog.logger;
private final Uktucp uktucp;
private final IMessageEncoder messageEncoder;
private final IKtucpTimeService kcpTimeService;
public WriteTask(Uktucp uktucp, IMessageEncoder messageEncoder) {
this.uktucp = uktucp;
this.kcpTimeService = uktucp.getKcpTimeService();
this.messageEncoder = messageEncoder;
}
@Override
public void execute() {
Uktucp uktucp = this.uktucp;
try {
//查看连接状态
if (!uktucp.isActive()) {
return;
}
//从发送缓冲区到kcp缓冲区
Queue<Object> queue = uktucp.getWriteObjectQueue();
int writeCount = 0;
long writeBytes = 0;
while (uktucp.canSend(false)) {
Object object = queue.poll();
if (object == null) {
break;
}
ByteBuf byteBuf = null;
try {
if (this.messageEncoder == null) {
byteBuf = (ByteBuf) object;
} else {
// 消息编码
byteBuf = this.messageEncoder.encode(uktucp, object);
}
if (byteBuf == null) {
break;
}
writeCount++;
writeBytes += byteBuf.readableBytes();
// 发送
uktucp.send(byteBuf);
} catch (Exception e) {
uktucp.getKcpListener().handleException(e, uktucp);
return;
} finally {
// release
ReferenceCountUtil.release(byteBuf);
}
}
// 统计
Snmp.snmp.addBytesSent(writeBytes);
uktucp.getSnmp().addBytesSent(writeBytes);
if (uktucp.isControlWriteBufferSize()) {
uktucp.getWriteBufferIncr().addAndGet(writeCount);
}
//如果有发送 则检测时间
if (!uktucp.canSend(false) || (uktucp.checkFlush() && uktucp.isFastFlush())) {
long now = this.kcpTimeService.now();
long next = uktucp.flush(now);
uktucp.setTsUpdate(now + next);
}
} catch (Throwable e) {
e.printStackTrace();
uktucp.getKcpListener().handleException(e, uktucp);
} finally {
release();
}
}
public void release() {
uktucp.getWriteProcessing().set(false);
}
}
| 30.79798 | 90 | 0.518859 |
0c97547a8d2950f27478b606c4c35ffa41dd4dd4 | 286 | package com.augus.restTest.persistence.dao;
import com.augus.restTest.domain.Cliente;
import java.util.List;
public interface ClienteDao {
void save(Cliente cliente);
void update(Cliente cliente);
void delete(Long id);
Cliente findById(Long id);
List<Cliente> findAll();
}
| 15.052632 | 43 | 0.755245 |
acffbc34b037f7a48d6e18f6035c8f9405832382 | 5,201 | package com.knight.wanandroid.module_home.module_activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.knight.wanandroid.library_base.baseactivity.BaseDBActivity;
import com.knight.wanandroid.library_base.route.RoutePathActivity;
import com.knight.wanandroid.library_util.BlurBuilder;
import com.knight.wanandroid.library_util.ScreenUtils;
import com.knight.wanandroid.library_util.ViewSetUtils;
import com.knight.wanandroid.library_widget.SetInitCustomView;
import com.knight.wanandroid.library_widget.pagertransformer.CustPagerTransformer;
import com.knight.wanandroid.module_home.R;
import com.knight.wanandroid.module_home.databinding.HomeArticlesTabActivityBinding;
import com.knight.wanandroid.module_home.module_adapter.TopArticleAroundAdapter;
import com.knight.wanandroid.module_home.module_entity.TopArticleEntity;
import com.knight.wanandroid.module_home.module_fragment.HomeTopTabsFragment;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager2.widget.CompositePageTransformer;
import androidx.viewpager2.widget.ViewPager2;
/**
* @author created by knight
* @organize wanandroid
* @Date 2021/5/21 13:52
* @descript:
*/
@Route(path = RoutePathActivity.Home.HomeTopArticle)
public final class HomeArticlesTabActivity extends BaseDBActivity<HomeArticlesTabActivityBinding> {
private List<Fragment> mHomeTopTabsFragments = new ArrayList<>();
private List<TopArticleEntity> datas = new ArrayList<>();
private TopArticleAroundAdapter mTopArticleAroundAdapter;
private CompositePageTransformer mCompositePageTransformer;
@Override
public int layoutId() {
return R.layout.home_articles_tab_activity;
}
@Override
public void initView(Bundle savedInstanceState) {
mDatabind.setClick(new ProxyClick());
datas = (List<TopArticleEntity>) getIntent().getSerializableExtra("toparticles");
mDatabind.homeIv.setImageBitmap(BlurBuilder.blur(mDatabind.homeIv));
if(BlurBuilder.isBlurFlag()){
mDatabind.homeIv.setVisibility(View.VISIBLE);
}
for(int i = 0;i< datas.size();i++) {
mHomeTopTabsFragments.add(HomeTopTabsFragment.newInstance(datas.get(i)));
}
mTopArticleAroundAdapter = new TopArticleAroundAdapter(new ArrayList<>());
mTopArticleAroundAdapter.setNewInstance(datas);
mTopArticleAroundAdapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
mTopArticleAroundAdapter.setSelectItem(position);
mTopArticleAroundAdapter.notifyDataSetChanged();
mDatabind.homeArticleViewpager.setCurrentItem(position);
}
});
mCompositePageTransformer = ViewSetUtils.setViewPage2(mDatabind.homeArticleViewpager, ScreenUtils.dp2px(30),ScreenUtils.dp2px(0));
mCompositePageTransformer.addTransformer(new CustPagerTransformer(0.85f));
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
SetInitCustomView.initSwipeRecycleview(mDatabind.homeRvToparticles,linearLayoutManager,mTopArticleAroundAdapter,true);
ViewSetUtils.setViewPager2Init(this, mHomeTopTabsFragments, mDatabind.homeArticleViewpager, true);
mDatabind.homeArticleViewpager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
mTopArticleAroundAdapter.setSelectItem(position);
mTopArticleAroundAdapter.notifyDataSetChanged();
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
@Override
protected void setThemeColor(boolean isDarkMode) {
}
@Override
//安卓重写返回键事件
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK){
finish();
overridePendingTransition(R.anim.base_scalealpha_out, R.anim.base_scalealpha_slient);
}
return true;
}
@Override
public void finish(){
super.finish();
BlurBuilder.recycle();
}
public class ProxyClick{
public void backUpActivity(){
finish();
overridePendingTransition(R.anim.base_scalealpha_out, R.anim.base_scalealpha_slient);
}
}
}
| 37.15 | 138 | 0.735243 |
bee21ae3a0fff47dd11b88a5f3d74292b23601d1 | 826 | /*
* Copyright (c) 2012-2015 iWave Software LLC
* All Rights Reserved
*/
package com.emc.sa.service.vipr.file.tasks;
import java.net.URI;
import java.util.List;
import com.emc.sa.service.vipr.tasks.ViPRExecutionTask;
import com.emc.storageos.model.file.FileSystemExportParam;
public class GetNfsExportsForFileSystem extends ViPRExecutionTask<List<FileSystemExportParam>> {
private final URI fileSystemId;
public GetNfsExportsForFileSystem(String fileSystemId) {
this(uri(fileSystemId));
}
public GetNfsExportsForFileSystem(URI fileSystemId) {
this.fileSystemId = fileSystemId;
provideDetailArgs(fileSystemId);
}
@Override
public List<FileSystemExportParam> executeTask() throws Exception {
return getClient().fileSystems().getExports(fileSystemId);
}
}
| 27.533333 | 96 | 0.746973 |
cd7d8952988cc2d7f21659d960005890aa3a655b | 4,055 | package ai.databand;
import ai.databand.log.HistogramRequest;
import ai.databand.schema.DatasetOperationStatus;
import ai.databand.schema.DatasetOperationType;
import ai.databand.schema.TaskRun;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.spark.scheduler.SparkListenerStageCompleted;
import org.apache.spark.sql.Dataset;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* DBND run.
*/
public interface DbndRun {
/**
* Init run in DBND using pipeline root execution method pointcut.
*
* @param method
* @param args
*/
void init(Method method, Object[] args);
/**
* Start task in the run context.
*
* @param method
* @param args
*/
void startTask(Method method, Object[] args);
/**
* Set task state to 'error'.
*
* @param method
* @param error
*/
void errorTask(Method method, Throwable error);
/**
* Set task state to 'completed'.
*
* @param method
* @param result
*/
void completeTask(Method method, Object result);
/**
* Stop run. Set run state to 'completed'.
*/
void stop();
/**
* Stop run. Set run state to 'failed'.
*
* @param error
*/
void error(Throwable error);
/**
* Log metric and attach it to the current task.
*
* @param key
* @param value
*/
void logMetric(String key, Object value);
/**
* Log Spark dataframe
*
* @param key
* @param value
* @param histogramRequest
*/
void logDataframe(String key, Dataset<?> value, HistogramRequest histogramRequest);
/**
* Log histogram object.
*
* @param histogram
*/
void logHistogram(Map<String, Object> histogram);
/**
* Log dataset operations.
*
* @param operationPath
* @param operationType
* @param operationStatus
* @param valuePreview
* @param dataDimensions
* @param dataSchema
*/
void logDatasetOperation(String operationPath,
DatasetOperationType operationType,
DatasetOperationStatus operationStatus,
String valuePreview,
List<Long> dataDimensions,
Object dataSchema);
/**
* Log dataset operations.
*
* @param path
* @param type
* @param status
* @param data
* @param withPreview
* @param withSchema
*/
void logDatasetOperation(String path,
DatasetOperationType type,
DatasetOperationStatus status,
Dataset<?> data,
boolean withPreview,
boolean withSchema);
/**
* Log Deequ result
*
* @param dfName
* @param analyzerContext
*/
// void logDeequResult(String dfName, AnalyzerContext analyzerContext);
/**
* Log metrics batch and attach it to the current task.
*
* @param metrics
*/
void logMetrics(Map<String, Object> metrics);
/**
* Log metrics batch with source
*
* @param metrics
* @param source
*/
void logMetrics(Map<String, Object> metrics, String source);
/**
* Save log and attach it to the current task and all parent tasks.
*
* @param event
* @param formattedEvent
*/
void saveLog(LoggingEvent event, String formattedEvent);
/**
* Save spark metrics.
*
* @param event
*/
void saveSparkMetrics(SparkListenerStageCompleted event);
/**
* Extract task name either from method name or annotation value.
*
* @param method
* @return task name extracted from method.
*/
String getTaskName(Method method);
/**
* Override task run to avoid creating duplicate runs.
*
* @param taskRun task run
*/
void setDriverTask(TaskRun taskRun);
}
| 23.171429 | 87 | 0.575832 |
45356116477af7edf27ce50972ba91885d003435 | 939 | package com.google.opengse.testlet.HttpSession;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.io.IOException;
/**
* A servlet which stores a key/value pair in the session
* @author jennings
* Date: Jul 6, 2008
*/
public class SessionCookieTestlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
HttpSession session = request.getSession(true);
session.setAttribute("foo", "bar");
String shouldBeBar = (String)session.getAttribute("foo");
if ("bar".equals(shouldBeBar))
response.getWriter().println("PASSED");
else
response.getWriter().println("PASSED");
}
}
| 31.3 | 74 | 0.748669 |
939b8de500c162921007bbaa6de8907f4a6ad86c | 11,291 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.setupdesign.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Animatable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.net.Uri;
import android.os.Build.VERSION_CODES;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import androidx.annotation.VisibleForTesting;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.view.View;
import com.google.android.setupdesign.R;
import java.io.IOException;
/**
* A view for displaying videos in a continuous loop (without audio). This is typically used for
* animated illustrations.
*
* <p>The video can be specified using {@code app:sudVideo}, specifying the raw resource to the mp4
* video. Optionally, {@code app:sudLoopStartMs} can be used to specify which part of the video it
* should loop back to
*
* <p>For optimal file size, use avconv or other video compression tool to remove the unused audio
* track and reduce the size of your video asset: avconv -i [input file] -vcodec h264 -crf 20 -an
* [output_file]
*/
@TargetApi(VERSION_CODES.ICE_CREAM_SANDWICH)
public class IllustrationVideoView extends TextureView
implements Animatable,
SurfaceTextureListener,
OnPreparedListener,
OnSeekCompleteListener,
OnInfoListener,
OnErrorListener {
private static final String TAG = "IllustrationVideoView";
private float aspectRatio = 1.0f; // initial guess until we know
@Nullable // Can be null when media player fails to initialize
protected MediaPlayer mediaPlayer;
private @RawRes int videoResId = 0;
private String videoResPackageName;
@VisibleForTesting Surface surface;
private boolean prepared;
/**
* The visibility of this view as set by the user. This view combines this with {@link
* #isMediaPlayerLoading} to determine the final visibility.
*/
private int visibility = View.VISIBLE;
/**
* Whether the media player is loading. This is used to hide this view to avoid a flash with a
* color different from the background while the media player is trying to render the first frame.
* Note: if this TextureView is not visible, it will never load the surface texture, and never
* play the video.
*/
private boolean isMediaPlayerLoading = false;
public IllustrationVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a =
context.obtainStyledAttributes(attrs, R.styleable.SudIllustrationVideoView);
final int videoResId = a.getResourceId(R.styleable.SudIllustrationVideoView_sudVideo, 0);
a.recycle();
setVideoResource(videoResId);
// By default the video scales without interpolation, resulting in jagged edges in the
// video. This works around it by making the view go through scaling, which will apply
// anti-aliasing effects.
setScaleX(0.9999999f);
setScaleX(0.9999999f);
setSurfaceTextureListener(this);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (height < width * aspectRatio) {
// Height constraint is tighter. Need to scale down the width to fit aspect ratio.
width = (int) (height / aspectRatio);
} else {
// Width constraint is tighter. Need to scale down the height to fit aspect ratio.
height = (int) (width * aspectRatio);
}
super.onMeasure(
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
/**
* Set the video and video package name to be played by this view.
*
* @param videoResId Resource ID of the video, typically an MP4 under res/raw.
* @param videoResPackageName The package name of videoResId.
*/
public void setVideoResource(@RawRes int videoResId, String videoResPackageName) {
if (videoResId != this.videoResId
|| (videoResPackageName != null && !videoResPackageName.equals(this.videoResPackageName))) {
this.videoResId = videoResId;
this.videoResPackageName = videoResPackageName;
createMediaPlayer();
}
}
/**
* Set the video to be played by this view.
*
* @param resId Resource ID of the video, typically an MP4 under res/raw.
*/
public void setVideoResource(@RawRes int resId) {
setVideoResource(resId, getContext().getPackageName());
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (hasWindowFocus) {
start();
} else {
stop();
}
}
/**
* Creates a media player for the current URI. The media player will be started immediately if the
* view's window is visible. If there is an existing media player, it will be released.
*/
protected void createMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
}
if (surface == null || videoResId == 0) {
return;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setSurface(surface);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.setOnErrorListener(this);
setVideoResourceInternal(videoResId, videoResPackageName);
}
private void setVideoResourceInternal(@RawRes int videoRes, String videoResPackageName) {
Uri uri = Uri.parse("android.resource://" + videoResPackageName + "/" + videoRes);
try {
mediaPlayer.setDataSource(getContext(), uri, null);
mediaPlayer.prepareAsync();
} catch (IOException e) {
Log.wtf(TAG, "Unable to set data source", e);
}
}
protected void createSurface() {
if (surface != null) {
surface.release();
surface = null;
}
// Reattach only if it has been previously released
SurfaceTexture surfaceTexture = getSurfaceTexture();
if (surfaceTexture != null) {
setIsMediaPlayerLoading(true);
surface = new Surface(surfaceTexture);
}
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (visibility == View.VISIBLE) {
reattach();
} else {
release();
}
}
@Override
public void setVisibility(int visibility) {
this.visibility = visibility;
if (isMediaPlayerLoading && visibility == View.VISIBLE) {
visibility = View.INVISIBLE;
}
super.setVisibility(visibility);
}
private void setIsMediaPlayerLoading(boolean isMediaPlayerLoading) {
this.isMediaPlayerLoading = isMediaPlayerLoading;
setVisibility(this.visibility);
}
/**
* Whether the media player should play the video in a continuous loop. The default value is true.
*/
protected boolean shouldLoop() {
return true;
}
/**
* Release any resources used by this view. This is automatically called in
* onSurfaceTextureDestroyed so in most cases you don't have to call this.
*/
public void release() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
prepared = false;
}
if (surface != null) {
surface.release();
surface = null;
}
}
private void reattach() {
if (surface == null) {
initVideo();
}
}
private void initVideo() {
if (getWindowVisibility() != View.VISIBLE) {
return;
}
createSurface();
if (surface != null) {
createMediaPlayer();
} else {
// This can happen if this view hasn't been drawn yet
Log.i(TAG, "Surface is null");
}
}
protected void onRenderingStart() {}
/* SurfaceTextureListener methods */
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
setIsMediaPlayerLoading(true);
initVideo();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
release();
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {}
/* Animatable methods */
@Override
public void start() {
if (prepared && mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
@Override
public void stop() {
if (prepared && mediaPlayer != null) {
mediaPlayer.pause();
}
}
@Override
public boolean isRunning() {
return mediaPlayer != null && mediaPlayer.isPlaying();
}
/* MediaPlayer callbacks */
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
setIsMediaPlayerLoading(false);
onRenderingStart();
}
return false;
}
@Override
public void onPrepared(MediaPlayer mp) {
prepared = true;
mp.setLooping(shouldLoop());
float aspectRatio = 0.0f;
if (mp.getVideoWidth() > 0 && mp.getVideoHeight() > 0) {
aspectRatio = (float) mp.getVideoHeight() / mp.getVideoWidth();
} else {
Log.w(TAG, "Unexpected video size=" + mp.getVideoWidth() + "x" + mp.getVideoHeight());
}
if (Float.compare(this.aspectRatio, aspectRatio) != 0) {
this.aspectRatio = aspectRatio;
requestLayout();
}
if (getWindowVisibility() == View.VISIBLE) {
start();
}
}
@Override
public void onSeekComplete(MediaPlayer mp) {
if (isPrepared()) {
mp.start();
} else {
Log.wtf(TAG, "Seek complete but media player not prepared");
}
}
public int getCurrentPosition() {
return mediaPlayer == null ? 0 : mediaPlayer.getCurrentPosition();
}
protected boolean isPrepared() {
return prepared;
}
@Override
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
Log.w(TAG, "MediaPlayer error. what=" + what + " extra=" + extra);
return false;
}
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
protected float getAspectRatio() {
return aspectRatio;
}
}
| 29.713158 | 100 | 0.700469 |
9d70f39d2c2ebda27a90de0eadd5af8e5fc8c3c6 | 670 | package com.klkblake.mm.common;
import java.util.Arrays;
import static com.klkblake.mm.common.Util.max;
/**
* Created by kyle on 6/10/15.
*/
public class BooleanArray {
public boolean[] data = new boolean[16];
public int count = 0;
private void grow() {
data = Arrays.copyOf(data, data.length * 3 / 2);
}
public void add(boolean value) {
if (data.length == count) {
grow();
}
data[count++] = value;
}
public void set(int index, boolean value) {
while (index >= data.length) {
grow();
}
data[index] = value;
count = max(count, index + 1);
}
}
| 20.30303 | 56 | 0.549254 |
845a5fb5947ba1db7ff4e697f9afdefe1516bf49 | 2,768 | package com.redisgeek.function.acre.export;
import com.azure.core.credential.TokenCredential;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.profile.AzureProfile;
import com.azure.identity.AzureAuthorityHosts;
import com.azure.identity.EnvironmentCredentialBuilder;
import com.azure.resourcemanager.AzureResourceManager;
import com.azure.resourcemanager.redisenterprise.RedisEnterpriseManager;
import com.azure.resourcemanager.redisenterprise.models.Cluster;
import com.azure.resourcemanager.redisenterprise.models.Database;
import com.azure.resourcemanager.redisenterprise.models.ExportClusterParameters;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import java.util.Optional;
import java.util.function.Function;
@Component
public class Export implements Function<Mono<Optional<String>>, Mono<String>> {
@Value("${acre_id}")
private String acre_id;
@Value("${blobSas}")
private String blobSas;
@Value("${storageKey}")
private String storageKey;
@Value("${storageAccountName}")
private String storageAccountName;
@Value("${storageContainerName}")
private String storageContainerName;
public Mono<String> apply(Mono<Optional<String>> request) {
TokenCredential credential = new EnvironmentCredentialBuilder()
.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
.build();
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
RedisEnterpriseManager redisEnterpriseManager = RedisEnterpriseManager
.authenticate(credential, profile);
AzureResourceManager azure = AzureResourceManager
.authenticate(credential, profile)
.withDefaultSubscription();
String resourceGroupName = azure.genericResources().getById(acre_id).resourceGroupName();
Cluster cluster = redisEnterpriseManager.redisEnterprises().getById(acre_id);
Database database = redisEnterpriseManager.databases().getById(acre_id + "/databases/default");
String blobSasUri = String.format("https://%s.blob.core.windows.net/%s%s", storageAccountName, storageContainerName, blobSas);
ExportClusterParameters exportClusterParameters =
new ExportClusterParameters().withSasUri(blobSasUri + ";" + storageKey);
exportClusterParameters.validate();
redisEnterpriseManager
.databases()
.export(resourceGroupName, cluster.name(), database.name(), exportClusterParameters);
return Mono.just("Export Complete");
}
} | 45.377049 | 138 | 0.725795 |
c88512989e1d57d4adfc93a6a062ec3b654ced88 | 2,473 | // Copyright (c) 2020 Mobanisto UG (haftungsbeschränkt)
//
// This file is part of covid-plz.
//
// 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.
package de.mobanisto.covidplz;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import de.mobanisto.covidplz.mapping.Mapping;
import de.mobanisto.covidplz.mapping.PartialRsRelation;
import de.mobanisto.covidplz.model.Data;
public class ShowDataInfo
{
public void execute() throws IOException
{
Data data = new DataLoader().loadData();
Set<String> postalCodes = data.getPostalCodes();
System.out.println(String.format("Number of postal code regions: %d",
postalCodes.size()));
Set<String> rss = data.getRkiIdentifiers();
System.out.println(
String.format("Number of RKI regions: %d", rss.size()));
Mapping mapping = data.getMapping();
Map<String, List<PartialRsRelation>> codeToRKI = mapping.getCodeToRKI();
int n = codeToRKI.size();
int unambiguous = 0;
int ambiguous = 0;
for (String key : codeToRKI.keySet()) {
List<PartialRsRelation> rkis = codeToRKI.get(key);
if (rkis.size() == 1) {
unambiguous += 1;
} else {
ambiguous += 1;
}
}
System.out.println(String.format("Mapped unambiguously: %d/%d (%.1f%%)",
unambiguous, n, unambiguous / (double) n * 100));
System.out.println(String.format("Mapped ambiguously: %d/%d (%.1f%%)",
ambiguous, n, ambiguous / (double) n * 100));
}
}
| 34.347222 | 81 | 0.72503 |
c5ead66248ee3964a0e048f5f572fdb26dc634d5 | 1,240 | package io.bootique.rabbitmq.client;
import com.google.inject.Binder;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import io.bootique.ConfigModule;
import io.bootique.config.ConfigurationFactory;
import io.bootique.log.BootLogger;
import io.bootique.rabbitmq.client.channel.ChannelFactory;
import io.bootique.rabbitmq.client.connection.ConnectionFactory;
import io.bootique.shutdown.ShutdownManager;
public class RabbitMQModule extends ConfigModule {
@Override
public void configure(Binder binder) {
}
@Provides
@Singleton
RabbitMQFactory provideRabbitMQFactory(ConfigurationFactory configurationFactory) {
return configurationFactory.config(RabbitMQFactory.class, configPrefix);
}
@Provides
ConnectionFactory provideConnectionFactory(RabbitMQFactory rabbitMQFactory,
BootLogger bootLogger,
ShutdownManager shutdownManager) {
return rabbitMQFactory.createConnectionFactory(bootLogger, shutdownManager);
}
@Provides
ChannelFactory provideChannelFactory(RabbitMQFactory rabbitMQFactory) {
return rabbitMQFactory.createChannelFactory();
}
}
| 33.513514 | 87 | 0.73871 |
58b359e09a6c52b33fb588c3c1f4bbfd723e6f5a | 148 | package com.buggyapp.exceptions;
import com.buggyapp.util.FileUtil;
public class ExceptionThread extends Thread {
public void run() {
}
}
| 12.333333 | 45 | 0.736486 |
3470de9d8ab2c869730195098644ece68b358910 | 2,842 | /**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2019 AT&T Intellectual Property. 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.
* ============LICENSE_END=========================================================
*/
package org.onap.aai.restclient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
@Component(value = ClientType.AAI)
public class AAIRestClient extends TwoWaySSLRestClient {
private static Logger logger = LoggerFactory.getLogger(AAIRestClient.class);
@Value("${aai.base.url}")
private String baseUrl;
@Value("${aai.ssl.key-store}")
private String keystorePath;
@Value("${aai.ssl.trust-store}")
private String truststorePath;
@Value("${aai.ssl.key-store-password}")
private String keystorePassword;
@Value("${aai.ssl.trust-store-password}")
private String truststorePassword;
@Override
public String getBaseUrl() {
return baseUrl;
}
@Override
protected String getKeystorePath() {
return keystorePath;
}
@Override
protected String getTruststorePath() {
return truststorePath;
}
@Override
protected char[] getKeystorePassword() {
return keystorePassword.toCharArray();
}
@Override
protected char[] getTruststorePassword() {
return truststorePassword.toCharArray();
}
@Override
public MultiValueMap<String, String> getHeaders(Map<String, String> headers) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.add("Real-Time", "true");
headers.forEach(httpHeaders::add);
return httpHeaders;
}
}
| 31.230769 | 85 | 0.642153 |
492ff2dfab05914c79833976a14166d8b06505ca | 842 | package listDemo;
import java.util.ArrayList;
public class Demo1 {
public static void main(String[] args) {
//1.jkd1.5版本时候的集合
ArrayList list=new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add("1");
// System.out.println(list.toString());
//1. 查看集合中的元素
System.out.println(list);
// System.out.println(list.size());
// list.get()
//2.获取指定索引处元素的集合list.get(index)
Object obj=list.get(3);
if (obj instanceof Integer){
int num=(Integer)obj;
System.out.println(num*100);
}
Integer n=(Integer) list.get(1);//类型转换异常 下转型
//工作中:集合推荐大家使用同一种数据类型
//为了解决下转型带来的安全问题,在1.5版本提出了全新的概念,泛型:
//泛型:表示广泛的类型(通用类型的规范)
//语法: <任意类型><t=T><E><K,V>当自己定义泛型时建议用大写
}
}
| 26.3125 | 52 | 0.549881 |
4829fe5226007c814df613c0cbeddf6994f6f421 | 697 | package org.openapitools.api;
import org.openapitools.api.*;
import org.openapitools.model.*;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import java.util.List;
import org.openapitools.api.NotFoundException;
import java.io.InputStream;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.validation.constraints.*;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen", date = "2018-08-17T01:57:08.062Z[GMT]")
public abstract class DefaultApiService {
public abstract Response getIp( String format, String paramCallback,SecurityContext securityContext) throws NotFoundException;
}
| 33.190476 | 137 | 0.817791 |
977a6958f674cceb56c49d29080f7b8a8a4b5c5a | 899 | package com.kidand.algorithms.and.data.structures.datastructures.segmenttree.test;
import com.kidand.algorithms.and.data.structures.datastructures.segmenttree.SegmentTree;
/**
* ██╗ ██╗██╗██████╗ █████╗ ███╗ ██╗██████╗
* ██║ ██╔╝██║██╔══██╗██╔══██╗████╗ ██║██╔══██╗
* █████╔╝ ██║██║ ██║███████║██╔██╗ ██║██║ ██║
* ██╔═██╗ ██║██║ ██║██╔══██║██║╚██╗██║██║ ██║
* ██║ ██╗██║██████╔╝██║ ██║██║ ╚████║██████╔╝
* ╚═╝ ╚═╝╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝
*
* @description: TestSegmentTree
* @author: Kidand
* @date: 2020/1/17 10:31
* Copyright © 2019-Kidand.
*/
public class TestSegmentTree {
public static void main(String[] args) {
Integer[] nums = {-2, 0, 3, -5, 2, -1};
//Lamda
SegmentTree<Integer> segTree = new SegmentTree<>(nums, (a, b) -> a + b);
System.out.println(segTree);
System.out.println(segTree.query(2, 5));
}
}
| 32.107143 | 88 | 0.444939 |
7f2ce56dc0c289c6e410c812dcad6ae54134e34f | 3,198 | /*
* 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.trickl.crawler.parser.html;
import com.trickl.crawler.parser.xml.XmlParser;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.tidy.Tidy;
import org.apache.droids.exception.DroidsException;
import org.w3c.dom.Document;
public class JTidyDocumentBuilder implements DocumentBuilder {
private static final Logger logger = Logger.getLogger(JTidyDocumentBuilder.class.getCanonicalName());
private Tidy htmlParser;
private XmlParser xmlParser;
public JTidyDocumentBuilder() {
htmlParser = new Tidy();
// Defaults
htmlParser.setFixUri(true);
htmlParser.setTidyMark(false);
htmlParser.setXHTML(true);
htmlParser.setForceOutput(true);
htmlParser.setMakeClean(true);
htmlParser.setMakeBare(true);
htmlParser.setSmartIndent(false);
htmlParser.setIndentContent(false);
htmlParser.setIndentAttributes(false);
htmlParser.setHideComments(true);
htmlParser.setWraplen(0);
xmlParser = new XmlParser();
}
public void setXHTML(boolean xhtml) {
htmlParser.setXHTML(xhtml);
}
public void setXmlOut(boolean xmlOut) {
htmlParser.setXmlOut(xmlOut);
}
@Override
public Document build(InputStream stream) throws DroidsException {
Document document = null;
// Convert HTML to XML
try (ByteArrayOutputStream xmlOut = new ByteArrayOutputStream();
ByteArrayOutputStream errOut = new ByteArrayOutputStream();
PrintWriter errWriter = new PrintWriter(errOut)) {
htmlParser.setErrout(errWriter);
htmlParser.parse(stream, xmlOut);
if (logger.isLoggable(Level.FINEST) && errOut.size() > 0) {
logger.log(Level.FINEST, "JTidy encountered errors:{0}", errOut.toString());
}
// Parse into an XML DOM
try (ByteArrayInputStream xmlIn = new ByteArrayInputStream(xmlOut.toByteArray())) {
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "JTidy output: {0}", xmlOut.toString());
}
document = xmlParser.parse(xmlIn);
} catch (IOException ex) {
throw new DroidsException("Unable to close stream", ex);
}
} catch (IOException ex) {
throw new DroidsException("Unable to close stream", ex);
}
return document;
}
}
| 32.30303 | 104 | 0.671982 |
738301900875c2628409be3a29b9ac798c39fcac | 639 | package fr.insee.onyxia.api.services.control.xgenerated;
import fr.insee.onyxia.model.catalog.Config.Property;
public interface XGeneratedProvider {
public String getGroupId();
public String getAppId(String scopeName, XGeneratedContext.Scope scope, Property.XGenerated xGenerated);
public String getExternalDns(String scopeName, XGeneratedContext.Scope scope, Property.XGenerated xGenerated);
public String getInternalDns(String scopeName, XGeneratedContext.Scope scope, Property.XGenerated xGenerated);
public String getInitScript(String scopeName, XGeneratedContext.Scope scope, Property.XGenerated xGenerated);
}
| 49.153846 | 114 | 0.821596 |
18eb66b1292a4a9221f8e730cc931933eb9ef59b | 1,909 | package org.jetbrains.plugins.github.ui;
import com.intellij.ui.DocumentAdapter;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
/**
* @author oleg
* @date 10/22/10
*/
public class GithubSharePanel {
private JPanel myPanel;
private JTextField myRepositoryTextField;
private JCheckBox myPrivateCheckBox;
private JTextArea myDescriptionTextArea;
private JTextField myRemoteTextField;
private final GithubShareDialog myGithubShareDialog;
public GithubSharePanel(final GithubShareDialog githubShareDialog) {
myGithubShareDialog = githubShareDialog;
myPrivateCheckBox.setSelected(false);
DocumentAdapter changeListener = new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
myGithubShareDialog.updateOkButton();
}
};
myRepositoryTextField.getDocument().addDocumentListener(changeListener);
myRemoteTextField.getDocument().addDocumentListener(changeListener);
}
public JPanel getPanel() {
return myPanel;
}
public JComponent getPreferredFocusComponent() {
return myRepositoryTextField;
}
public String getRepositoryName() {
return myRepositoryTextField.getText().trim();
}
public void setRepositoryName(final String name) {
myRepositoryTextField.setText(name);
}
public String getRemoteName() {
return myRemoteTextField.getText().trim();
}
public void setRemoteName(final String name) {
myRemoteTextField.setText(name);
}
public boolean isPrivate() {
return myPrivateCheckBox.isSelected();
}
public String getDescription() {
return myDescriptionTextArea.getText().trim();
}
public void setPrivateRepoAvailable(final boolean privateRepoAllowed) {
if (!privateRepoAllowed) {
myPrivateCheckBox.setEnabled(false);
myPrivateCheckBox.setToolTipText("Your account doesn't support private repositories");
}
}
}
| 26.150685 | 92 | 0.750655 |
98162af7e0364b3595a13f6f756e13f67eac9631 | 465 | package org.geelato.core.meta.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Created by hongxq on 2016/8/17.
*/
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface DictDataSrc {
String group();
String code() default "code";
}
| 24.473684 | 59 | 0.769892 |
0045dddeb8161bf0caf9e4ec643daedc4e13dba6 | 2,810 | /**
* 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.pulsar.broker.loadbalance;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.apache.pulsar.broker.MultiBrokerBaseTest;
import org.apache.pulsar.broker.PulsarService;
import org.awaitility.Awaitility;
import org.testng.annotations.Test;
@Test(groups = "broker")
public class MultiBrokerLeaderElectionTest extends MultiBrokerBaseTest {
@Test
public void shouldElectOneLeader() {
int leaders = 0;
for (PulsarService broker : getAllBrokers()) {
if (broker.getLeaderElectionService().isLeader()) {
leaders++;
}
}
assertEquals(leaders, 1);
}
@Test
public void shouldAllBrokersKnowTheLeader() {
Awaitility.await().untilAsserted(() -> {
for (PulsarService broker : getAllBrokers()) {
Optional<LeaderBroker> currentLeader = broker.getLeaderElectionService().getCurrentLeader();
assertTrue(currentLeader.isPresent(), "Leader wasn't known on broker " + broker.getBrokerServiceUrl());
}
});
}
@Test
public void shouldAllBrokersBeAbleToGetTheLeader() {
Awaitility.await().untilAsserted(() -> {
LeaderBroker leader = null;
for (PulsarService broker : getAllBrokers()) {
Optional<LeaderBroker> currentLeader =
broker.getLeaderElectionService().readCurrentLeader().get(1, TimeUnit.SECONDS);
assertTrue(currentLeader.isPresent(), "Leader wasn't known on broker " + broker.getBrokerServiceUrl());
if (leader != null) {
assertEquals(currentLeader.get(), leader,
"Different leader on broker " + broker.getBrokerServiceUrl());
} else {
leader = currentLeader.get();
}
}
});
}
}
| 39.027778 | 119 | 0.658719 |
35cc14f530e6262a15982eef394d9f794f8e4c13 | 1,606 | package controllers.company;
import play.data.validation.ValidationError;
import java.util.ArrayList;
import java.util.List;
/**
* Backing class for the Company data form.
* Requirements:
* <ul>
* <li> All fields are public,
* <li> All fields are of type String or List[String].
* <li> A public no-arg constructor.
* <li> A validate() method that returns null or a List[ValidationError].
* </ul>
*
* @author Manuel de la Peña
* @generated
*/
public class CompanyFormData {
public String mvccVersion;
public String companyId;
public String accountId;
public String webId;
public String key;
public String mx;
public String homeURL;
public String logoId;
public String system;
public String maxUsers;
public String active;
public CompanyFormData() {
}
public CompanyFormData(
String mvccVersion,
String companyId,
String accountId,
String webId,
String key,
String mx,
String homeURL,
String logoId,
String system,
String maxUsers,
String active
) {
this.mvccVersion = mvccVersion;
this.companyId = companyId;
this.accountId = accountId;
this.webId = webId;
this.key = key;
this.mx = mx;
this.homeURL = homeURL;
this.logoId = logoId;
this.system = system;
this.maxUsers = maxUsers;
this.active = active;
}
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<>();
if (companyId == null || companyId.length() == 0) {
errors.add(new ValidationError("companyId", "No companyId was given."));
}
if(errors.size() > 0) {
return errors;
}
return null;
}
}
| 20.075 | 75 | 0.690535 |
32004ebe99e0724d126911ae618f5323b6f59ee4 | 533 | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n; i++) {
for(int j = i; j < n -1 ;j++) {
System.out.print(" ");
}
for(int k = 0; k < i+1 ;k++) {
System.out.print("#");
}
System.out.println();
}
}
}
| 22.208333 | 44 | 0.452158 |
1cdcc21cd99515f34a16d11ac1eeb46d5714c336 | 679 | package gos.assumption;
import java.io.Serializable;
public class Group implements Serializable {
private static final long serialVersionUID = -7961726924232057999L;
private Type type;
private String id;
public Group() {
this.type = null;
this.id = null;
}
public Group(Type type) {
this.type = type;
this.id = null;
}
public Group(Type type, String id) {
this.type = type;
this.id = id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| 16.166667 | 70 | 0.605302 |
a8e350ec9f602da5252568aee2e507349258b6c6 | 237 | package com.xeno.goo.entities;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.fluids.FluidStack;
public interface IGooContainingEntity extends ICapabilityProvider {
FluidStack goo();
}
| 26.333333 | 67 | 0.835443 |
396dc35aa479812bfae50fb5e6cbb0a205824db1 | 1,699 | package seedu.taskmaster.model.session;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.taskmaster.testutil.Assert.assertThrows;
import org.junit.jupiter.api.Test;
public class SessionNameTest {
@Test
public void constructor_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> new SessionName(null));
}
@Test
public void constructor_invalidName_throwsIllegalArgumentException() {
String invalidName = "";
assertThrows(IllegalArgumentException.class, () -> new SessionName(invalidName));
}
@Test
public void isValidName() {
// null name
assertThrows(NullPointerException.class, () -> SessionName.isValidName(null));
// invalid name
assertFalse(SessionName.isValidName("")); // empty string
assertFalse(SessionName.isValidName(" ")); // spaces only
assertFalse(SessionName.isValidName(" session")); // begins with space
assertFalse(SessionName.isValidName("^")); // only non-alphanumeric characters
assertFalse(SessionName.isValidName("Session*")); // contains non-alphanumeric characters
// valid name
assertTrue(SessionName.isValidName("new session")); // alphabets only
assertTrue(SessionName.isValidName("12345")); // numbers only
assertTrue(SessionName.isValidName("new session 1")); // alphanumeric characters
assertTrue(SessionName.isValidName("New Session")); // with capital letters
assertTrue(SessionName.isValidName("New Session With A Very Very Very Very Long Name")); // long names
}
}
| 40.452381 | 110 | 0.709829 |
30144624839caf2a751687e13e0ed589f2487d9b | 7,834 | package com.jhbim.bimvr.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jhbim.bimvr.dao.entity.pojo.User;
import com.jhbim.bimvr.dao.entity.vo.Result;
import com.jhbim.bimvr.dao.mapper.UserMapper;
import com.jhbim.bimvr.service.IUserService;
import com.jhbim.bimvr.system.enums.ResultStatusCode;
import com.jhbim.bimvr.system.shiro.LoginType;
import com.jhbim.bimvr.system.shiro.SMSConfig;
import com.jhbim.bimvr.system.shiro.UserToken;
import com.jhbim.bimvr.utils.MD5Util;
import com.jhbim.bimvr.utils.ShiroUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/${version}/user")
public class LoginController {
@Resource
IUserService userService;
@Resource
public RedisTemplate redisTemplate;
@Resource
UserMapper userMapper;
/**
* 用户密码登录
* @param username
* @param password
* @return
*/
@RequestMapping("/login")
public Result login(String username, String password,HttpServletRequest request){
//根据登录人的手机号查询他的所有的信息
User user = userMapper.getByPhone(username);
//判断是否注册过
if(user==null){
return new Result(ResultStatusCode.IS_NOT_EXIST); //登录失败
}
//登录成功
ServletContext application=request.getSession().getServletContext();
application.setAttribute("User_CompanyId",user.getCompanyId());
application.setAttribute("User_Phone",user.getPhone());
// Long usrcompanyid= (Long) application.getAttribute("User_CompanyId");
//注册的时候将密码加密 登录的时候跟MD5做匹配 登录成功
if(MD5Util.encrypt(password).equals(user.getPassword())){
UserToken token = new UserToken(LoginType.USER_PASSWORD, username, password);
return shiroLogin(token);
}
return new Result(ResultStatusCode.NOT_EXIST_USER_OR_ERROR_PWD);
}
/**
* 手机验证码登录
* 注:由于是demo演示,此处不添加发送验证码方法;
* 正常操作:发送验证码至手机并且将验证码存放在redis中,登录的时候比较用户穿过来的验证码和redis中存放的验证码
* @param
* @param
* @return
*/
@RequestMapping("/sendSmscode")
public String sendSms(String mobile){
String random= RandomStringUtils.randomNumeric(6);
System.out.println(mobile+"随机数:"+random);
//5分钟过期
redisTemplate.opsForValue().set(mobile,random+"",5, TimeUnit.MINUTES);
SMSConfig.send(mobile,random);
return "验证码发送成功";
}
/**
* 微信登录
* 注:由于是demo演示,此处只接收一个code参数(微信会生成一个code,然后通过code获取openid等信息)
* 其他根据个人实际情况添加参数
* @param code
* @return
*/
@RequestMapping("wechatLogin")
public Result wechatLogin(String code){
// 此处假装code分别是username、password
UserToken token = new UserToken(LoginType.WECHAT_LOGIN, code, code, code);
return shiroLogin(token);
}
public Result shiroLogin(UserToken token){
try {
//登录不在该处处理,交由shiro处理
Subject subject = SecurityUtils.getSubject();
subject.login(token);
if (subject.isAuthenticated()) {
JSON json = new JSONObject();
((JSONObject) json).put("token", subject.getSession().getId());
return new Result(ResultStatusCode.OK, json);
}else{
return new Result(ResultStatusCode.SHIRO_ERROR);
}
}catch (IncorrectCredentialsException | UnknownAccountException e){
e.printStackTrace();
return new Result(ResultStatusCode.NOT_EXIST_USER_OR_ERROR_PWD);
}catch (LockedAccountException e){
return new Result(ResultStatusCode.USER_FROZEN);
}catch (Exception e){
return new Result(ResultStatusCode.SYSTEM_ERR);
}
}
/**
* 退出登录
* @return
*/
@RequestMapping("/logout")
public Result logout(){
SecurityUtils.getSubject().logout();
return new Result(ResultStatusCode.OK);
}
/**
* 用户修改密码
*/
@RequestMapping("/changePwd")
public Result changePwd(String oldPwd, String newPwd) {
int result = userService.updatePwd(oldPwd, newPwd);
if (result==1) {
return new Result(ResultStatusCode.OK);
}else {
return new Result(ResultStatusCode.FAIL);
}
}
/**
* 判断手机号是否存在
* @param phone 手机号
* @return
*/
@RequestMapping("/register")
public Result register(String phone){
User user = userMapper.getByPhone(phone);
if(user!=null){
return new Result(ResultStatusCode.FAIL, "已注册");
}
return new Result(ResultStatusCode.NoRegiter);
}
/**
* 注册获取redis里面的验证码 判断是否一致 完成用户注册
* @param smsCode 验证码
* @param phone 手机号
* @return
*/
@RequestMapping("/RegistercheckSmsCode")
public Result checkSmsCode(String smsCode, String phone,String pwd){
Result result = new Result();
if(redisTemplate.opsForValue().get(phone)==null){
result.setCode(1);
result.setMsg("短信验证码输入超时!");
}else{
String code = redisTemplate.opsForValue().get(phone).toString();
if(!code.equals(smsCode)){
result.setCode(2);
result.setMsg("短信验证码错误!");
}else{
User user=new User();
user.setCompanyId(1L);
user.setRoleId(3L);
user.setPhone(phone);
String regex = "[a-z0-9A-Z]+$";
if(pwd.matches(regex)==false){
result.setCode(6);
result.setMsg("不合法的字符");
return result;
}else{
user.setPassword(MD5Util.encrypt(pwd));
userMapper.insertSelective(user);
}
return new Result(ResultStatusCode.RegiterSuccess);
}
}
return result;
}
/**
* 登录获取redis里面的验证码 判断是否一致 完成用户登录
* @param smsCode 验证码
* @param phone 手机号
* @param request
* @return
*/
@RequestMapping("/LogincheckSmsCode")
public Result LogincheckSmsCode(String smsCode, String phone, HttpServletRequest request){
Result result = new Result();
if(redisTemplate.opsForValue().get(phone)==null){
result.setCode(1);
result.setMsg("短信验证码输入超时!");
}else{
String code = redisTemplate.opsForValue().get(phone).toString();
if(!code.equals(smsCode)){
result.setCode(2);
result.setMsg("短信验证码错误!");
}else{
result.setCode(0);
result.setMsg("成功");
User user = userMapper.getByPhone(phone);
ServletContext application=request.getSession().getServletContext();
application.setAttribute("User_CompanyId",user.getCompanyId());
UserToken token = new UserToken(LoginType.USER_PHONE, phone, smsCode);
return shiroLogin(token);
}
}
return result;
}
}
| 33.33617 | 94 | 0.625862 |
ad29f66a09d690480eab1ba6481e139b9a06902f | 2,999 | /*
* Copyright 2018 Preferred.AI
*
* 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 ai.preferred.venom.storage;
import ai.preferred.venom.fetcher.Callback;
import ai.preferred.venom.request.Request;
import ai.preferred.venom.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
public class FakeFileManager implements FileManager {
private static final Logger LOGGER = LoggerFactory.getLogger(FileManager.class);
private final Callback callback;
private final Map<Request, Record> requestRecordMap;
private final AtomicBoolean closed = new AtomicBoolean(false);
public FakeFileManager() {
this(new HashMap<>());
}
public FakeFileManager(final Map<Request, Record> requestRecordMap) {
this.callback = new FileManagerCallback(this);
this.requestRecordMap = requestRecordMap;
}
@Override
public @NotNull Callback getCallback() {
return callback;
}
@Override
public @NotNull String put(@NotNull Request request, @NotNull Response response) {
requestRecordMap.put(request, StorageRecord.builder().build());
LOGGER.info("Put called for request: {}", request.getUrl());
return "true";
}
@Override
public @NotNull Record get(Object id) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public @NotNull Record get(@NotNull Request request) throws StorageException {
for (Map.Entry<Request, Record> requestRecordEntry : requestRecordMap.entrySet()) {
final Request trueRequest = requestRecordEntry.getKey();
if (trueRequest == null) {
throw new StorageException("Throw code captured.");
}
if (trueRequest.getUrl().equals(request.getUrl())
&& trueRequest.getMethod() == trueRequest.getMethod()
&& trueRequest.getHeaders().equals(request.getHeaders())) {
if ((trueRequest.getBody() != null && request.getBody() != null
&& trueRequest.getBody().equals(request.getBody()))
|| (trueRequest.getBody() == null && request.getBody() == null)) {
return requestRecordEntry.getValue();
}
}
}
LOGGER.info("Get return none for request: {}", request.getUrl());
return null;
}
@Override
public void close() {
closed.set(true);
}
public boolean getClosed() {
return closed.get();
}
}
| 30.602041 | 87 | 0.707236 |
cfec603c294343bfcb58cf8cad66a359dbc8e681 | 483 | package com.nowellpoint.client.sforce.model.sobject;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NamedLayoutInfo implements Serializable {
private static final long serialVersionUID = -7984076664176001329L;
private String name;
public NamedLayoutInfo() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | 19.32 | 68 | 0.772257 |
12562956339486407dbf27bdaaa95bd53eb946ec | 1,089 | /*
* 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 net.billylieurance.euclidparallel;
/**
*
* @author wlieurance
*/
public class Distance implements Comparable<Distance> {
private String id;
private int distance;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
@Override
public int compareTo(Distance o) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (distance < o.getDistance()) {
return BEFORE;
} else if (distance > o.getDistance()) {
return AFTER;
}
return EQUAL;
}
@Override
public String toString(){
return "{ id : " + id + ", distance : " + distance + "}";
}
}
| 20.54717 | 79 | 0.575758 |
ed89f70927f6b5265ce0f83cd8d69557800b4f48 | 10,993 | package com.ebstrada.formreturn.manager.logic.export.image;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import com.ebstrada.formreturn.api.messaging.MessageNotification;
import com.ebstrada.formreturn.manager.gef.util.Localizer;
import com.ebstrada.formreturn.manager.persistence.jpa.Form;
import com.ebstrada.formreturn.manager.persistence.jpa.FormPage;
import com.ebstrada.formreturn.manager.persistence.jpa.ProcessedImage;
import com.ebstrada.formreturn.manager.persistence.jpa.Publication;
import com.ebstrada.formreturn.manager.util.Misc;
import com.ebstrada.formreturn.manager.ui.Main;
public class ImageExporter {
private MessageNotification messageNotification;
private ArrayList<Long> publicationIds;
private EntityManager entityManager;
private ImageExportPreferences imageExportPreferences;
private PDDocument doc;
private PDRectangle pageRectangle;
public ImageExporter(ArrayList<Long> publicationIds,
ImageExportPreferences imageExportPreferences) {
this.publicationIds = publicationIds;
this.imageExportPreferences = imageExportPreferences;
}
public void setMessageNotification(MessageNotification messageNotification) {
this.messageNotification = messageNotification;
}
private EntityManager getEntityManager() {
if (this.entityManager == null) {
if (com.ebstrada.formreturn.manager.ui.Main.getInstance() != null) {
return Main.getInstance().getJPAConfiguration().getEntityManager();
} else {
return com.ebstrada.formreturn.server.Main.getInstance().getJPAConfiguration()
.getEntityManager();
}
} else {
return this.entityManager;
}
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void export() throws Exception {
this.pageRectangle = getPDRectangle();
try {
if (getCollation() == Collation.ALL_IMAGES_TOGETHER) {
this.doc = new PDDocument();
}
for (Long publicationId : publicationIds) {
exportPublication(publicationId);
}
} catch (Exception ex) {
throw ex;
} finally {
if (getCollation() == Collation.ALL_IMAGES_TOGETHER) {
if (doc.getNumberOfPages() > 0) {
this.doc.save(getFile());
}
}
if (this.entityManager != null && this.entityManager.isOpen()) {
this.entityManager.close();
}
}
}
private File getFile() {
String fileStr = imageExportPreferences.getFile();
if (imageExportPreferences.isTimestampFilenamePrefix()) {
fileStr = Misc.getTimestampPrefixedFilename(fileStr);
}
return new File(fileStr);
}
private Collation getCollation() {
return imageExportPreferences.getCollation();
}
private void setMessage(String message) {
if (messageNotification == null) {
return;
}
messageNotification.setMessage(message);
}
private void exportPublication(Long publicationId) throws Exception {
this.entityManager = getEntityManager();
if (this.entityManager == null) {
throw new Exception(Localizer.localize("Util", "NullEntityManager"));
}
Publication publication = this.entityManager.find(Publication.class, publicationId);
if (publication == null) {
throw new PublicationNotFoundException();
}
setMessage(Localizer.localize("Util", "LoadingFormRecordsMessage"));
List<Form> forms = publication.getFormCollection();
if (forms == null || forms.size() <= 0) {
throw new PublicationContainsNoFormsException();
}
int formCount = forms.size();
int formNumber = 1;
for (Form form : forms) {
if (getCollation() == Collation.FORM_IMAGES_TOGETHER) {
doc = new PDDocument();
}
int formPageNumber = 1;
for (FormPage formPage : form.getFormPageCollection()) {
String processingMsg = Localizer.localize("Util", "ExportingFormImageMessage");
setMessage(String.format(processingMsg, formNumber, formPageNumber, formCount));
List<ProcessedImage> processedImages = formPage.getProcessedImageCollection();
if (processedImages == null || processedImages.size() <= 0) {
formPageNumber++;
continue;
}
// write raw image
if ((getCollation() == Collation.IMAGES_ONLY) && (getOverlay() == null
|| getOverlay().size() <= 0)) {
writeFormPagePNGFile(formPage, getFormPagePNGFile(getFile(), formPage));
// write image and overlay to PDF
} else {
if (getCollation() == Collation.IMAGES_ONLY) {
doc = new PDDocument();
}
ImageOverlay imageOverlay =
new ImageOverlay(formPage, doc, pageRectangle, this.imageExportPreferences);
writeFormPage(formPage, imageOverlay);
imageOverlay.closeContentStream();
if (getCollation() == Collation.IMAGES_ONLY) {
if (doc.getNumberOfPages() > 0) {
doc.save(getFormPageImageFile(getFile(), formPage));
}
}
}
formPageNumber++;
}
formNumber++;
if (getCollation() == Collation.FORM_IMAGES_TOGETHER) {
if (doc.getNumberOfPages() > 0) {
doc.save(getFormImageFile(getFile(), form));
}
}
}
}
private void writeFormPagePNGFile(FormPage formPage, File formPageImageFile)
throws IOException {
List<ProcessedImage> processedImages = formPage.getProcessedImageCollection();
if (processedImages == null || processedImages.size() <= 0) {
return;
}
ProcessedImage processedImage = processedImages.get(processedImages.size() - 1);
byte[] data = processedImage.getProcessedImageData();
FileOutputStream tfos = null;
BufferedOutputStream bos = null;
try {
tfos = new FileOutputStream(formPageImageFile);
bos = new BufferedOutputStream(tfos);
bos.write(data);
} catch (IOException e) {
throw e;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
Misc.printStackTrace(e);
}
}
if (tfos != null) {
tfos.close();
}
}
}
private ArrayList<Overlay> getOverlay() {
return this.imageExportPreferences.getOverlay();
}
private void writeFormPage(FormPage formPage, ImageOverlay imageOverlay) throws Exception {
List<ProcessedImage> processedImages = formPage.getProcessedImageCollection();
if (processedImages == null || processedImages.size() <= 0) {
return;
}
ProcessedImage processedImage = processedImages.get(processedImages.size() - 1);
collateImageToPDFStream(processedImage, imageOverlay, pageRectangle);
}
private PDRectangle getPDRectangle() {
return this.imageExportPreferences.getPDRectangle();
}
private File getFormImageFile(File directory, Form form) throws IOException {
File f = new File(
directory.getCanonicalPath() + File.separator + parsePrefix(getImageFilePrefix(), form)
+ ".pdf");
try {
f.getCanonicalPath();
return f;
} catch (IOException e) {
throw e;
}
}
private File getFormPageImageFile(File directory, FormPage formPage) throws IOException {
File f = new File(
directory.getCanonicalPath() + File.separator + parsePrefix(getImageFilePrefix(),
formPage) + ".pdf");
try {
f.getCanonicalPath();
return f;
} catch (IOException e) {
throw e;
}
}
private File getFormPagePNGFile(File directory, FormPage formPage) throws IOException {
File f = new File(
directory.getCanonicalPath() + File.separator + parsePrefix(getImageFilePrefix(),
formPage) + ".png");
try {
f.getCanonicalPath();
return f;
} catch (IOException e) {
throw e;
}
}
private String getImageFilePrefix() {
return this.imageExportPreferences.getImageFilePrefix();
}
private String parsePrefix(String filenamePrefix, Form form) {
Map<String, String> recordMap = new HashMap<String, String>();
recordMap = Misc.getFullRecordMap(form);
String prefix = Misc.parseFields(filenamePrefix, recordMap);
if (prefix.length() <= 0) {
prefix = form.getFormId() + "";
}
return prefix;
}
private String parsePrefix(String filenamePrefix, FormPage formPage) {
Map<String, String> recordMap = new HashMap<String, String>();
recordMap = Misc.getFullRecordMap(formPage);
String prefix = Misc.parseFields(filenamePrefix, recordMap);
if (prefix.length() <= 0) {
prefix = formPage.getFormPageId() + "";
}
return prefix;
}
private void collateImageToPDFStream(ProcessedImage processedImage, ImageOverlay imageOverlay,
PDRectangle pageRectangle) throws Exception {
isInterrupted();
imageOverlay.drawImage(processedImage, pageRectangle);
imageOverlay.drawHeader();
if (this.imageExportPreferences.getOverlay().contains(Overlay.SOURCE_DATA)) {
imageOverlay.drawSourceData(this.entityManager);
}
if (this.imageExportPreferences.getOverlay().contains(Overlay.CAPTURED_DATA)) {
imageOverlay.drawCapturedData(this.entityManager);
}
}
private void isInterrupted() throws Exception {
if (messageNotification == null) {
return;
}
if (messageNotification.isInterrupted()) {
throw messageNotification.getException();
}
}
}
| 32.814925 | 100 | 0.602656 |
ad0e61874ce8c10300f0238e432835665bf0cbe8 | 1,337 | import java.util.ArrayList;
import java.util.LinkedList;
public class Tree234 {
static class Node234 {
private ArrayList<Integer> values = new ArrayList<Integer>(3);
private ArrayList<Integer> indexes = new ArrayList<Integer>(3);
private ArrayList<Node234> children = new ArrayList<Node234>(4);
private Node234 parent;
public Node234(int value, int index_in_array) {
values.add(value);
indexes.add(index_in_array);
parent = null;
}
public int getValue(int i) {
return values.get(i);
}
public int getIndex(int i) {
return indexes.get(i);
}
public Node234 getChild(int i) {
return children.get(i);
}
public int getType() {
return values.size() + 1;
}
public boolean isLeaf() {
return children.isEmpty();
}
// Insertar valor en una hoja
public int insert(int value, int index) {
for(int i = 0; i < values.size(); i ++) {
if(value < values.get(i)) {
values.add(i, value);
indexes.add(i, index);
return i;
}
}
values.add(value);
indexes.add(index);
return values.size() - 1;
}
}
Node234 createTree234(int[] array) {
return null;
}
public static void main(String[] args) {
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// int aPasar = 1 + (int) (27 * Math.random());
// System.out.println(aPasar);
}
}
| 20.257576 | 66 | 0.62528 |
3d08eb5ce13b92e204f2a021ad5afb61b0943de8 | 293 | package individual.cy.learn.pattern.behavioral.iterator;
/**
* @author mystic
*/
public interface Iterator {
/**
* has next()
*
* @return true or false
*/
boolean hasNext();
/**
* next obj
*
* @return next Object
*/
Object next();
}
| 13.952381 | 56 | 0.52901 |
fc0373b7b26d84ab048f050cc044670dd0795c16 | 92 | package me.eluch.libgdx.DoJuMu.game.doodle;
public enum DoodleGenderType {
MALE, FEMALE
}
| 15.333333 | 43 | 0.782609 |
cd1f261ee0bccd497367229059790e83bac60b19 | 1,073 | package com.trubru.brewbro.recipedetails;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import static com.trubru.brewbro.addeditrecipe.AddEditRecipeActivity.ADD_EDIT_RESULT_OK;
/**
* Created by Kolin on 2/4/2018.
*/
public class RecipeDetailsActivity extends AppCompatActivity implements RecipeDetailsNavigator {
public static final String EXTRA_RECIPE_ID = "RECIPE_ID";
public static final int DELETE_RESULT_OK = RESULT_FIRST_USER + 2;
public static final int EDIT_RESULT_OK = RESULT_FIRST_USER + 3;
private RecipeDetailsViewModel mRecipeDetailsViewModel;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EDIT_RECIPE) {
// If the task was edited successfully, go back to the list.
if (resultCode == ADD_EDIT_RESULT_OK) {
// If the result comes from the add/edit screen, it's an edit.
setResult(EDIT_RESULT_OK);
finish();
}
}
}
}
| 27.512821 | 96 | 0.699907 |
4c6d28d5537cbbcc4ba20968ba4c86e0446aa768 | 6,196 | //! \file ViewFactory.java
//! \brief 基于普通View类的绘图测试视图类
// Copyright (c) 2012-2013, https://github.com/rhcad/touchvg
package vgdemo.testview;
import java.util.ArrayList;
import java.util.List;
//! 测试视图的构造列表类
public class ViewFactory {
public static class DummyItem {
public String id;
public int flags;
public String title;
public DummyItem(String id, int flags, String title) {
this.id = id;
this.flags = flags;
this.title = title;
}
@Override
public String toString() {
return title;
}
}
public static List<DummyItem> ITEMS = new ArrayList<DummyItem>();
static {
addItem("vgdemo.testview.view.GraphView1", 1<<1, "GraphView splines");
addItem("vgdemo.testview.view.GraphView1", 32|(1<<1), "GraphView draw");
addItem("vgdemo.testview.view.GraphView1", 2<<1, "GraphView line");
addItem("vgdemo.testview.view.GraphView1", 3<<1, "GraphView lines");
addItem("vgdemo.testview.view.GraphView1", 32|1, "GraphView select");
addItem("vgdemo.testview.view.TestMagnifier1", 1, "TestMagnifier");
addItem("vgdemo.testview.view.TestMagnifier1", 16|1, "TestMagnifier, 2 views");
addItem("vgdemo.testview.view.LargeView1", 1<<1, "Scroll GraphView splines");
addItem("vgdemo.testview.view.LargeView1", 2<<1, "Scroll GraphView line");
addItem("vgdemo.testview.view.LargeView1", 32|1, "Scroll GraphView select");
addItem("vgdemo.testview.view.GraphView", 0, "TestOneView");
addItem("vgdemo.testview.view.TestDoubleViews", 1|0, "TestOneSurfaceView");
addItem("vgdemo.testview.view.TestDoubleViews", 1|0|0x100000, "TestOneSurfaceView, back");
addItem("vgdemo.testview.view.GraphViewCached", 0, "GraphViewCached");
addItem("vgdemo.testview.view.TestDoubleViews", 0|2, "Test2Views, std view+view");
addItem("vgdemo.testview.view.TestDoubleViews", 1|2, "Test2Views, top surface+view");
addItem("vgdemo.testview.view.TestDoubleViews", 0|4, "Test2Views, std view+surface");
addItem("vgdemo.testview.view.TestDoubleViews", 1|4, "Test2Views, top surface+surface");
addItem("vgdemo.testview.view.TestDoubleViews", 1|2|0x100000, "Test2Views, back surface+view");
addItem("vgdemo.testview.view.TestDoubleViews", 1|4|0x100000, "Test2Views, back surface+surface");
addItem("vgdemo.testview.view.TestDoubleViews", 8|4, "Test2Views, cachedview+surface");
addItem("vgdemo.testview.view.TestDoubleViews", 8|2, "Test2Views, cachedview+view");
addItem("vgdemo.testview.view.LargeView2", 0|2, "Test2Views, scroll view+view");
addItem("vgdemo.testview.view.LargeView2", 1|2, "Test2Views, scroll surface+view");
addItem("vgdemo.testview.view.LargeView2", 0|4, "Test2Views, scroll view+surface");
addItem("vgdemo.testview.view.LargeView2", 1|4, "Test2Views, scroll surface+surface");
addItem("vgdemo.testview.view.LargeView2", 0|0, "TestOneView, scroll");
addItem("vgdemo.testview.view.LargeView2", 1|0, "TestOneSurfaceView, scroll");
addItem("vgdemo.testview.view.TestDoubleViews", 1|2|0x100000, "Test2Views, scroll back surface+view");
addItem("vgdemo.testview.view.TestDoubleViews", 1|4|0x100000, "Test2Views, scroll back surface+surface");
addItem("vgdemo.testview.view.LargeView2", 8|4, "Test2Views, scroll cachedview+surface");
addItem("vgdemo.testview.view.LargeView2", 8|2, "Test2Views, scroll cachedview+surface");
addItem("vgdemo.testview.canvas.GraphView1", 0x01, "testRect");
addItem("vgdemo.testview.canvas.GraphView1", 0x02, "testLine");
addItem("vgdemo.testview.canvas.GraphView1", 0x04, "testTextAt");
addItem("vgdemo.testview.canvas.GraphView1", 0x08, "testEllipse");
addItem("vgdemo.testview.canvas.GraphView1", 0x10, "testQuadBezier");
addItem("vgdemo.testview.canvas.GraphView1", 0x20, "testCubicBezier");
addItem("vgdemo.testview.canvas.GraphView1", 0x40, "testPolygon");
addItem("vgdemo.testview.canvas.GraphView1", 0x80|0x40|0x02, "testClearRect");
addItem("vgdemo.testview.canvas.GraphView1", 0x100, "testClipPath");
addItem("vgdemo.testview.canvas.GraphView1", 0x200, "testHandle");
addItem("vgdemo.testview.canvas.GraphView2", 0x400, "testDynCurves");
addItem("vgdemo.testview.canvas.SurfaceView1", 0x20, "testCubicBezier in SurfaceView");
addItem("vgdemo.testview.canvas.SurfaceView1", 0x80|0x40|0x02, "testClearRect in SurfaceView");
addItem("vgdemo.testview.canvas.SurfaceView2", 0x20, "testCubicBezier in SurfaceView with thread");
addItem("vgdemo.testview.canvas.SurfaceView2", 0x02, "testLine in SurfaceView with thread");
addItem("vgdemo.testview.canvas.SurfaceView2", 0x400, "testDynCurves in SurfaceView with touch");
addItem("vgdemo.testview.canvas.SurfaceView3", 0x400, "testDynCurves in SurfaceView with thread");
addItem("vgdemo.testview.canvas.SurfaceView3", 0x400|0x1000, "testDynCurves(OPAQUE) with thread");
addItem("vgdemo.testview.canvas.LargeView1", 0x04|0x10000, "testTextAt in large view");
addItem("vgdemo.testview.canvas.LargeView1", 0x04|0x20000, "testTextAt in large surface view");
addItem("vgdemo.testview.canvas.LargeView1", 0x20|0x10000, "testCubicBezier in large view");
addItem("vgdemo.testview.canvas.LargeView1", 0x20|0x20000, "testCubicBezier in large surface view");
addItem("vgdemo.testview.canvas.LargeView1", 0x200|0x10000, "testHandle in large view");
addItem("vgdemo.testview.canvas.LargeView1", 0x200|0x20000, "testHandle in large surface view");
addItem("vgdemo.testview.canvas.LargeView1", 0x400|0x10000, "testDynCurves in large view");
addItem("vgdemo.testview.canvas.LargeView1", 0x400|0x20000, "testDynCurves in large surface view");
}
private static void addItem(String id, int flags, String title) {
ITEMS.add(new DummyItem(id, flags, title));
}
}
| 59.576923 | 113 | 0.684958 |
fbd17ddc475680993c3e08dc05de9c5cdc1be963 | 10,736 | package org.csu.mypetstore.persistence.impl;
import org.csu.mypetstore.persistence.OrderDAO;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.persistence.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class OrderDAOImpl implements OrderDAO {
private static final String getOrderSQL = "SELECT " +
"BILLADDR1 AS billAddress1," +
"BILLADDR2 AS billAddress2," +
"BILLCITY," +
"BILLCOUNTRY," +
"BILLSTATE," +
"BILLTOFIRSTNAME," +
"BILLTOLASTNAME," +
"BILLZIP," +
"SHIPADDR1 AS shipAddress1," +
"SHIPADDR2 AS shipAddress2," +
"SHIPCITY," +
"SHIPCOUNTRY," +
"SHIPSTATE," +
"SHIPTOFIRSTNAME," +
"SHIPTOLASTNAME," +
"SHIPZIP," +
"CARDTYPE," +
"COURIER," +
"CREDITCARD," +
"EXPRDATE AS expiryDate," +
"LOCALE," +
"ORDERDATE," +
"ORDERS.ORDERID," +
"TOTALPRICE," +
"USERID AS username," +
"STATUS " +
"FROM ORDERS, ORDERSTATUS " +
"WHERE ORDERS.ORDERID = ? " +
"AND ORDERS.ORDERID = ORDERSTATUS.ORDERID";
private static final String getOrdersByUsernameSQL = "SELECT " +
"BILLADDR1 AS billAddress1," +
"BILLADDR2 AS billAddress2," +
"BILLCITY," +
"BILLCOUNTRY," +
"BILLSTATE," +
"BILLTOFIRSTNAME," +
"BILLTOLASTNAME," +
"BILLZIP," +
"SHIPADDR1 AS shipAddress1," +
"SHIPADDR2 AS shipAddress2," +
"SHIPCITY," +
"SHIPCOUNTRY," +
"SHIPSTATE," +
"SHIPTOFIRSTNAME," +
"SHIPTOLASTNAME," +
"SHIPZIP," +
"CARDTYPE," +
"COURIER," +
"CREDITCARD," +
"EXPRDATE AS expiryDate," +
"LOCALE," +
"ORDERDATE," +
"ORDERS.ORDERID," +
"TOTALPRICE," +
"USERID AS username," +
"STATUS " +
"FROM ORDERS, ORDERSTATUS " +
"WHERE ORDERS.USERID = ? " +
"AND ORDERS.ORDERID = ORDERSTATUS.ORDERID " +
"ORDER BY ORDERDATE DESC";
private static final String insertOrderSQL = "INSERT INTO ORDERS " +
"(ORDERID, USERID, ORDERDATE, SHIPADDR1, SHIPADDR2, SHIPCITY, SHIPSTATE," +
" SHIPZIP, SHIPCOUNTRY, BILLADDR1, BILLADDR2, BILLCITY, BILLSTATE," +
" BILLZIP, BILLCOUNTRY, COURIER, TOTALPRICE, BILLTOFIRSTNAME, BILLTOLASTNAME, " +
" SHIPTOFIRSTNAME, SHIPTOLASTNAME, CREDITCARD, EXPRDATE, CARDTYPE, LOCALE)" +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
// private static final String insertOrderStatusSQL = "INSERT INTO ORDERSTATUS " +
// "(ORDERID, LINENUM, TIMESTAMP, STATUS) " +
// "VALUES (?, ?, ?, ?)";
public List<Order> getOrdersByUsername(String username) {
List<Order> orderList = new ArrayList<Order>();
try{
Connection connection = DBUtil.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(getOrdersByUsernameSQL);
preparedStatement.setString(1, username);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
Order order = new Order();
order.setBillAddress1(resultSet.getString(1));
order.setBillAddress2(resultSet.getString(2));
order.setBillCity(resultSet.getString(3));
order.setBillCountry(resultSet.getString(4));
order.setBillState(resultSet.getString(5));
order.setBillToFirstName(resultSet.getString(6));
order.setBillToLastName(resultSet.getString(7));
order.setBillZip(resultSet.getString(8));
order.setShipAddress1(resultSet.getString(9));
order.setShipAddress2(resultSet.getString(10));
order.setShipCity(resultSet.getString(11));
order.setShipCountry(resultSet.getString(12));
order.setShipState(resultSet.getString(13));
order.setShipToFirstName(resultSet.getString(14));
order.setShipToLastName(resultSet.getString(15));
order.setShipZip(resultSet.getString(16));
order.setCardType(resultSet.getString(17));
order.setCourier(resultSet.getString(18));
order.setCreditCard(resultSet.getString(19));
order.setExpiryDate(resultSet.getString(20));
order.setLocale(resultSet.getString(21));
order.setOrderDate(resultSet.getTimestamp(22));
order.setOrderId(resultSet.getInt(23));
order.setTotalPrice(resultSet.getBigDecimal(24));
order.setUsername(resultSet.getString(25));
order.setStatus(resultSet.getString(26));
orderList.add(order);
}
DBUtil.closeResultSet(resultSet);
DBUtil.closePreparedStatement(preparedStatement);
DBUtil.closeConnection(connection);
}catch (Exception e){
e.printStackTrace();
}
return orderList;
};
public Order getOrder(int orderId) {
Order order = null;
try{
Connection connection = DBUtil.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(getOrderSQL);
preparedStatement.setInt(1, orderId);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
order = new Order();
order.setBillAddress1(resultSet.getString(1));
order.setBillAddress2(resultSet.getString(2));
order.setBillCity(resultSet.getString(3));
order.setBillCountry(resultSet.getString(4));
order.setBillState(resultSet.getString(5));
order.setBillToFirstName(resultSet.getString(6));
order.setBillToLastName(resultSet.getString(7));
order.setBillZip(resultSet.getString(8));
order.setShipAddress1(resultSet.getString(9));
order.setShipAddress2(resultSet.getString(10));
order.setShipCity(resultSet.getString(11));
order.setShipCountry(resultSet.getString(12));
order.setShipState(resultSet.getString(13));
order.setShipToFirstName(resultSet.getString(14));
order.setShipToLastName(resultSet.getString(15));
order.setShipZip(resultSet.getString(16));
order.setCardType(resultSet.getString(17));
order.setCourier(resultSet.getString(18));
order.setCreditCard(resultSet.getString(19));
order.setExpiryDate(resultSet.getString(20));
order.setLocale(resultSet.getString(21));
order.setOrderDate(resultSet.getTimestamp(22));
order.setOrderId(resultSet.getInt(23));
order.setTotalPrice(resultSet.getBigDecimal(24));
order.setUsername(resultSet.getString(25));
order.setStatus(resultSet.getString(26));
}
DBUtil.closeResultSet(resultSet);
DBUtil.closePreparedStatement(preparedStatement);
DBUtil.closeConnection(connection);
}catch (Exception e){
e.printStackTrace();
}
return order;
}
public void insertOrder(Order order) {
try{
Connection connection = DBUtil.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(insertOrderSQL);
preparedStatement.setInt(1, order.getOrderId() );
preparedStatement.setString(2, order.getUsername());
preparedStatement.setTimestamp(3, new Timestamp(order.getOrderDate().getTime()));
preparedStatement.setString(4, order.getShipAddress1());
preparedStatement.setString(5, order.getShipAddress2());
preparedStatement.setString(6, order.getShipCity());
preparedStatement.setString(7, order.getShipState());
preparedStatement.setString(8, order.getShipZip());
preparedStatement.setString(9, order.getShipCountry());
preparedStatement.setString(10, order.getBillAddress1());
preparedStatement.setString(11, order.getBillAddress2());
preparedStatement.setString(12, order.getBillCity());
preparedStatement.setString(13, order.getBillState());
preparedStatement.setString(14, order.getBillZip());
preparedStatement.setString(15, order.getBillCountry());
preparedStatement.setString(16, order.getCourier());
preparedStatement.setBigDecimal(17, order.getTotalPrice());
preparedStatement.setString(18, order.getBillToFirstName());
preparedStatement.setString(19, order.getBillToLastName());
preparedStatement.setString(20, order.getShipToFirstName());
preparedStatement.setString(21, order.getShipToLastName());
preparedStatement.setString(22, order.getCreditCard());
preparedStatement.setString(23, order.getExpiryDate());
preparedStatement.setString(24, order.getCardType());
preparedStatement.setString(25, order.getLocale());
preparedStatement.executeUpdate();
DBUtil.closePreparedStatement(preparedStatement);
DBUtil.closeConnection(connection);
}catch (Exception e){
e.printStackTrace();
}
}
// public void insertOrderStatus(Order order) {
// try{
// Connection connection = DBUtil.getConnection();
// PreparedStatement preparedStatement = connection.prepareStatement(insertOrderStatusSQL);
// preparedStatement.setInt(1, order.getOrderId());
// preparedStatement.setInt(2, order.getLineItems().size());
// preparedStatement.setTimestamp(3, new Timestamp(order.getOrderDate().getTime()));
// preparedStatement.setString(4, order.getStatus());
//
// preparedStatement.executeUpdate();
// DBUtil.closePreparedStatement(preparedStatement);
// DBUtil.closeConnection(connection);
// }catch (Exception e){
// e.printStackTrace();
// }
// }
}
| 46.47619 | 102 | 0.591189 |
260b8df9f05586d77f0ab01f8692ca81c30a5aff | 352 | package fr.insee.arc.core.exception;
public class MissingChildMarkupException extends Exception {
/**
*
*/
private static final long serialVersionUID = 6301161908387897576L;
public MissingChildMarkupException(String markup) {
super(String.format("the child markup %s does no exist in the format file", markup));
}
}
| 23.466667 | 86 | 0.713068 |
ac011e799e65fb3f0d0eb16309abb1b36db5d21c | 1,394 | package candra.bukupengeluaran.Modules.Wireframe;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import candra.bukupengeluaran.Views.Activities.CurrencyActivity;
import candra.bukupengeluaran.Views.Activities.HomeActivity;
import candra.bukupengeluaran.Views.Activities.PrivacyPolicyActivity;
/**
* Created by Candra Triyadi on 06/10/2017.
*/
public class Wireframe {
private Wireframe(){
}
private static class SingleTonHelper{
private static final Wireframe INSTANCE = new Wireframe();
}
public static Wireframe getInstance() {
return SingleTonHelper.INSTANCE;
}
public void toHomeView(Context context){
Intent intent = new Intent(context, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
((Activity)context).finish();
}
public void toPrivacyPolicyView(Context context){
Intent intent = new Intent(context, PrivacyPolicyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public void toCurrencyView(Context context){
Intent intent = new Intent(context, CurrencyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
| 29.659574 | 88 | 0.733142 |
78effb15ff40f4701b66235f5bd03e6980fad83d | 11,654 | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003-2005 University of Maryland
*
* 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.1 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.Type;
import org.apache.bcel.generic.TypedInstruction;
import edu.umd.cs.findbugs.ResourceCollection;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.RepositoryLookupFailureCallback;
import edu.umd.cs.findbugs.ba.ResourceTracker;
import edu.umd.cs.findbugs.ba.ResourceValueFrame;
import edu.umd.cs.findbugs.ba.ResourceValueFrameModelingVisitor;
/**
* Resource tracker which determines where streams are created, and how they are
* used within the method.
*
* @author David Hovemeyer
*/
public class StreamResourceTracker implements ResourceTracker<Stream> {
private StreamFactory[] streamFactoryList;
private RepositoryLookupFailureCallback lookupFailureCallback;
private ResourceCollection<Stream> resourceCollection;
/**
* Map of locations where streams are opened to the actual Stream objects.
*/
private Map<Location, Stream> streamOpenLocationMap;
/**
* Set of all open locations and escapes of uninteresting streams.
*/
// private HashSet<Location> uninterestingStreamEscapeSet;
private HashSet<Stream> uninterestingStreamEscapeSet;
/**
* Set of all (potential) stream escapes.
*/
private TreeSet<StreamEscape> streamEscapeSet;
/**
* Map of individual streams to equivalence classes. Any time a stream "A"
* is wrapped with a stream "B", "A" and "B" belong to the same equivalence
* class. If any stream in an equivalence class is closed, then we consider
* all of the streams in the equivalence class as having been closed.
*/
private Map<Stream, StreamEquivalenceClass> streamEquivalenceMap;
/**
* Constructor.
*
* @param streamFactoryList
* array of StreamFactory objects which determine where streams
* are created
* @param lookupFailureCallback
* used when class hierarchy lookups fail
*/
// @SuppressWarnings("EI2")
public StreamResourceTracker(StreamFactory[] streamFactoryList, RepositoryLookupFailureCallback lookupFailureCallback) {
this.streamFactoryList = streamFactoryList;
this.lookupFailureCallback = lookupFailureCallback;
this.streamOpenLocationMap = new HashMap<Location, Stream>();
this.uninterestingStreamEscapeSet = new HashSet<Stream>();
this.streamEscapeSet = new TreeSet<StreamEscape>();
this.streamEquivalenceMap = new HashMap<Stream, StreamEquivalenceClass>();
}
/**
* Set the precomputed ResourceCollection for the method.
*/
public void setResourceCollection(ResourceCollection<Stream> resourceCollection) {
this.resourceCollection = resourceCollection;
}
/**
* Indicate that a stream escapes at the given target Location.
*
* @param source
* the Stream that is escaping
* @param target
* the target Location (where the stream escapes)
*/
public void addStreamEscape(Stream source, Location target) {
StreamEscape streamEscape = new StreamEscape(source, target);
streamEscapeSet.add(streamEscape);
if (FindOpenStream.DEBUG)
System.out.println("Adding potential stream escape " + streamEscape);
}
/**
* Transitively mark all streams into which uninteresting streams (such as
* System.out) escape. This handles the rule that wrapping an uninteresting
* stream makes the wrapper uninteresting as well.
*/
public void markTransitiveUninterestingStreamEscapes() {
// Eliminate all stream escapes where the target isn't really
// a stream open location point.
for (Iterator<StreamEscape> i = streamEscapeSet.iterator(); i.hasNext();) {
StreamEscape streamEscape = i.next();
if (!isStreamOpenLocation(streamEscape.target)) {
if (FindOpenStream.DEBUG)
System.out.println("Eliminating false stream escape " + streamEscape);
i.remove();
}
}
// Build initial stream equivalence classes.
// Each stream starts out in its own separate
// equivalence class.
for (Iterator<Stream> i = resourceCollection.resourceIterator(); i.hasNext();) {
Stream stream = i.next();
StreamEquivalenceClass equivalenceClass = new StreamEquivalenceClass();
equivalenceClass.addMember(stream);
streamEquivalenceMap.put(stream, equivalenceClass);
}
// Starting with the set of uninteresting stream open location points,
// propagate all uninteresting stream escapes. Iterate until there
// is no change. This also builds the map of stream equivalence classes.
Set<Stream> orig = new HashSet<Stream>();
do {
orig.clear();
orig.addAll(uninterestingStreamEscapeSet);
for (StreamEscape streamEscape : streamEscapeSet) {
if (isUninterestingStreamEscape(streamEscape.source)) {
if (FindOpenStream.DEBUG)
System.out.println("Propagating stream escape " + streamEscape);
Stream target = streamOpenLocationMap.get(streamEscape.target);
if (target == null)
throw new IllegalStateException();
uninterestingStreamEscapeSet.add(target);
// Combine equivalence classes for source and target
StreamEquivalenceClass sourceClass = streamEquivalenceMap.get(streamEscape.source);
StreamEquivalenceClass targetClass = streamEquivalenceMap.get(target);
if (sourceClass != targetClass) {
sourceClass.addAll(targetClass);
for (Iterator<Stream> j = targetClass.memberIterator(); j.hasNext();) {
Stream stream = j.next();
streamEquivalenceMap.put(stream, sourceClass);
}
}
}
}
} while (!orig.equals(uninterestingStreamEscapeSet));
}
/**
* Determine if an uninteresting stream escapes at given location.
* markTransitiveUninterestingStreamEscapes() should be called first.
*
* @param stream
* the stream
* @return true if an uninteresting stream escapes at the location
*/
public boolean isUninterestingStreamEscape(Stream stream) {
return uninterestingStreamEscapeSet.contains(stream);
}
/**
* Indicate that a stream is constructed at this Location.
*
* @param streamOpenLocation
* the Location
* @param stream
* the Stream opened at this Location
*/
public void addStreamOpenLocation(Location streamOpenLocation, Stream stream) {
if (FindOpenStream.DEBUG)
System.out.println("Stream open location at " + streamOpenLocation);
streamOpenLocationMap.put(streamOpenLocation, stream);
if (stream.isUninteresting())
uninterestingStreamEscapeSet.add(stream);
}
/**
* Get the equivalence class for given stream. May only be called if
* markTransitiveUninterestingStreamEscapes() has been called.
*
* @param stream
* the stream
* @return the set containing the equivalence class for the given stream
*/
public StreamEquivalenceClass getStreamEquivalenceClass(Stream stream) {
return streamEquivalenceMap.get(stream);
}
/**
* Determine if given Location is a stream open location point.
*
* @param location
* the Location
*/
private boolean isStreamOpenLocation(Location location) {
return streamOpenLocationMap.get(location) != null;
}
public Stream isResourceCreation(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg) {
// Use precomputed map of Locations to Stream creations,
// if present. Note that we don't care about preexisting
// resources here.
if (resourceCollection != null)
return resourceCollection.getCreatedResource(new Location(handle, basicBlock));
Instruction ins = handle.getInstruction();
if (!(ins instanceof TypedInstruction))
return null;
Type type = ((TypedInstruction) ins).getType(cpg);
if (!(type instanceof ObjectType))
return null;
Location location = new Location(handle, basicBlock);
// All StreamFactories are given an opportunity to
// look at the location and possibly identify a created stream.
for (StreamFactory aStreamFactoryList : streamFactoryList) {
Stream stream = aStreamFactoryList.createStream(location, (ObjectType) type, cpg, lookupFailureCallback);
if (stream != null)
return stream;
}
return null;
}
public boolean isResourceOpen(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg, Stream resource,
ResourceValueFrame frame) {
return resource.isStreamOpen(basicBlock, handle, cpg, frame);
}
public boolean isResourceClose(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg, Stream resource,
ResourceValueFrame frame) {
return resource.isStreamClose(basicBlock, handle, cpg, frame, lookupFailureCallback);
}
public boolean mightCloseResource(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg)
throws DataflowAnalysisException {
return Stream.mightCloseStream(basicBlock, handle, cpg);
}
public ResourceValueFrameModelingVisitor createVisitor(Stream resource, ConstantPoolGen cpg) {
return new StreamFrameModelingVisitor(cpg, this, resource);
}
public boolean ignoreImplicitExceptions(Stream resource) {
return resource.ignoreImplicitExceptions();
}
public boolean ignoreExceptionEdge(Edge edge, Stream resource, ConstantPoolGen cpg) {
return false;
}
public boolean isParamInstance(Stream resource, int slot) {
return resource.getInstanceParam() == slot;
}
}
// vim:ts=3
| 39.239057 | 124 | 0.674876 |
1ba3aec5235255f47509481b3da2cf1f0e6e9e80 | 1,584 | /*
* Copyright 2021 Shulie Technology, Co.Ltd
* Email: shulie@shulie.io
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shulie.surge.data.deploy.pradar.link.parse;
import java.util.List;
import io.shulie.surge.data.deploy.pradar.link.model.ShadowBizTableModel;
import io.shulie.surge.data.deploy.pradar.link.model.ShadowDatabaseModel;
public class ShadowDatabaseParseResult {
private ShadowDatabaseModel databaseModel;
private List<ShadowBizTableModel> tableModelList;
public ShadowDatabaseParseResult(ShadowDatabaseModel databaseModel, List<ShadowBizTableModel> tableModelList) {
this.databaseModel = databaseModel;
this.tableModelList = tableModelList;
}
public ShadowDatabaseModel getDatabaseModel() {
return databaseModel;
}
public void setDatabaseModel(ShadowDatabaseModel databaseModel) {
this.databaseModel = databaseModel;
}
public List<ShadowBizTableModel> getTableModelList() {
return tableModelList;
}
public void setTableModelList(List<ShadowBizTableModel> tableModelList) {
this.tableModelList = tableModelList;
}
}
| 32.326531 | 115 | 0.750631 |