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
ffb8f9bd5baca7d8f5da95c4d3dfc4e13fe6807f
2,997
package epl.eval.values; import epl.eval.operations.arithmetic.*; import epl.eval.operations.comparators.*; public record NumberValue(double number) implements Value, Addition, Subtraction, Multiplication, Division, Modulo, Greater, GreaterEqual, Less, LessEqual, Equal, Unequal { @Override public String toString() { return Double.toString(this.number); } @Override public Value add(Value value) { if(value instanceof NumberValue n) { return new NumberValue(this.number + n.number); } return unsupported(value); } @Override public Value sub(Value value) { if(value instanceof NumberValue n) { return new NumberValue(this.number - n.number); } return unsupported(value); } @Override public Value mul(Value value) { if(value instanceof NumberValue n) { return new NumberValue(this.number * n.number); } return unsupported(value); } @Override public Value div(Value value) { if(value instanceof NumberValue n) { return new NumberValue(this.number / n.number); } return unsupported(value); } @Override public Value mod(Value value) { if(value instanceof NumberValue n) { return new NumberValue(this.number % n.number); } return unsupported(value); } @Override public Value gre(Value value) { if(value instanceof NumberValue n) { return new BooleanValue(this.number > n.number); } return unsupported(value); } @Override public Value geq(Value value) { if(value instanceof NumberValue n) { return new BooleanValue(this.number >= n.number); } return unsupported(value); } @Override public Value les(Value value) { if(value instanceof NumberValue n) { return new BooleanValue(this.number < n.number); } return unsupported(value); } @Override public Value leq(Value value) { if(value instanceof NumberValue n) { return new BooleanValue(this.number <= n.number); } return unsupported(value); } @Override public Value eq(Value value) { if(value instanceof NumberValue n) { return new BooleanValue(this.number == n.number); } return unsupported(value); } @Override public Value ueq(Value value) { if(value instanceof NumberValue n) { return new BooleanValue(this.number == n.number); } return unsupported(value); } private Value unsupported(Value value) { throw new RuntimeException("Unsupported operation of types " + this.getClass().getName() + " and " + value.getClass().getName()); } }
23.232558
170
0.57958
4166fea84c9c0d5419033a1d68cb89fe2c89ff1c
1,337
/* * Copyright (c) 2013-2015. Urban Airship and Contributors */ package com.urbanairship.api.push.model.notification.actions; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.urbanairship.api.push.model.PushModelObject; public final class RemoveTagAction extends PushModelObject implements Action<TagActionData> { private final TagActionData tagData; public RemoveTagAction(TagActionData tagData) { Preconditions.checkNotNull(tagData, "tagData should not be null."); this.tagData = tagData; } @Override public int hashCode() { return Objects.hashCode(tagData); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final RemoveTagAction other = (RemoveTagAction) obj; return Objects.equal(this.tagData, other.tagData); } @Override public TagActionData getValue() { return tagData; } @Override public ActionType getActionType() { return ActionType.REMOVE_TAG; } @Override public String toString() { return "RemoveTagAction{" + "tagData=" + tagData + '}'; } }
24.309091
93
0.634256
190ea17042272831a02e326c7dd4cccac8614194
2,327
package com.BUPTJuniorTeam.filemanager.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileOperation { public static boolean copyDir(File sourceDir, File targetDir) { if (!sourceDir.exists()) return false; File[] fileList = sourceDir.listFiles(); if (!targetDir.exists()) { targetDir.mkdirs(); } for (File file : fileList) { if (file.isDirectory()) { if (!copyDir(file, new File(targetDir.getAbsolutePath() + "/" + file.getName()))) return false; } else { if (!copyFile(file, new File(targetDir.getAbsolutePath() + "/" + file.getName()))) return false; } } return true; } public static boolean copyFile(File source, File target) { try { InputStream streamFrom = new FileInputStream(source); OutputStream streamTo = new FileOutputStream(target); byte buffer[]=new byte[1024]; int len; while ((len= streamFrom.read(buffer)) > 0){ streamTo.write(buffer, 0, len); } streamFrom.close(); streamTo.close(); return true; } catch (IOException e) { e.printStackTrace(); } return false; } public static boolean copyFiletoDir(File sourceFile, File targetDir) { if (!targetDir.exists()) { targetDir.mkdirs(); } File targetFile = new File(targetDir.getAbsolutePath() + "/" + sourceFile.getName()); return copyFile(sourceFile, targetFile); } public static boolean deleteDir(File dir) { File[] files = dir.listFiles(); for (File file: files) { if (file.isDirectory()) { if (!deleteDir(new File(dir.getAbsolutePath() + "/" + file.getName()))) return false; } else { if (!deleteFile(file)) return false; } } return dir.delete(); } public static boolean deleteFile(File file) { return file.delete(); } }
29.455696
98
0.543189
e127abb025cc2b6c2cb48d8b4c4ae50714de892c
1,165
package models.team; import com.avaje.ebean.Model; import play.data.validation.Constraints; import play.data.validation.ValidationError; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity public class Team extends Model { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; @Constraints.Required(message = "No se puede crear equipo sin nombre") @Column(unique = true) String name; @ManyToMany List<Player> players; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Player> getPlayers() { return players; } public void setPlayers(List<Player> players) { this.players = players; } public List<ValidationError> validate() { List<ValidationError> errors = new ArrayList<>(); if (players == null) errors.add(new ValidationError("players", "Player list cannot be null")); return errors.isEmpty() ? null : errors; } }
21.981132
102
0.642918
ba82e41dda6e865b54f6ab521a754633d43aa9a9
6,043
package com.shemich.mariobros.Screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Screen; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.maps.MapObject; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.*; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.StretchViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.shemich.mariobros.MarioBros; import com.shemich.mariobros.Scenes.Hud; import com.shemich.mariobros.Sprites.Goomba; import com.shemich.mariobros.Sprites.Mario; import com.shemich.mariobros.Tools.B2WorldCreator; import com.shemich.mariobros.Tools.WorldContactListener; public class PlayScreen implements Screen { //Референсы для нашей игры, ... private MarioBros game; private TextureAtlas atlas; //базовые переменные playscreen private OrthographicCamera gamecam; private Viewport gamePort; private Hud hud; //Tiled map variables private TmxMapLoader mapLoader; private TiledMap map; private OrthogonalTiledMapRenderer renderer; //Box2d variables private World world; private Box2DDebugRenderer b2dr; //sprites private Mario player; private Goomba goomba; private Music music; public PlayScreen(MarioBros game) { atlas = new TextureAtlas("Mario_and_Enemies.atlas"); this.game = game; //создает камеру для приследования марио через мир gamecam = new OrthographicCamera(); //создает fitviewport для поддержки виртуального //соотношения сторон, несмотря на соотношение сторон экрана gamePort = new FitViewport(MarioBros.V_WIDTH / MarioBros.PPM,MarioBros.V_HEIGHT / MarioBros.PPM,gamecam); //создает HUD hud = new Hud(game.batch); //load our map and setup our renderer mapLoader = new TmxMapLoader(); map = mapLoader.load("level1.tmx"); renderer = new OrthogonalTiledMapRenderer(map, 1 / MarioBros.PPM); //initially set our gamcam to be centered correctly at the start of the map gamecam.position.set(gamePort.getWorldWidth() / 2, gamePort.getWorldHeight() / 2, 0 ); //создает наш Box2D мир, устанавливаем нет гравитации в X, -10 world = new World(new Vector2(0,-10),true); //allows for debug lines of our box2d world b2dr = new Box2DDebugRenderer(); new B2WorldCreator(this); //create mario in our game world player = new Mario(this); world.setContactListener(new WorldContactListener()); music = MarioBros.manager.get("audio/music/mario_music.ogg", Music.class); music.setLooping(true); music.play(); goomba = new Goomba(this,.32f,.32f); } public TextureAtlas getAtlas() { return atlas; } @Override public void show() { } public void handleInput(float dt) { if (Gdx.input.isKeyJustPressed(Input.Keys.UP)) player.b2body.applyLinearImpulse(new Vector2(0,4f), player.b2body.getWorldCenter(),true); if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) && player.b2body.getLinearVelocity().x <= 2) { player.b2body.applyLinearImpulse(new Vector2(0.1f,0),player.b2body.getWorldCenter(), true ); } if (Gdx.input.isKeyPressed(Input.Keys.LEFT) && player.b2body.getLinearVelocity().x >= -2) { player.b2body.applyLinearImpulse(new Vector2(-0.1f, 0), player.b2body.getWorldCenter(), true); } } public void update(float dt) { //handle user input first handleInput(dt); world.step(1/60f,6,2); player.update(dt); goomba.update(dt); hud.update(dt); gamecam.position.x = player.b2body.getPosition().x; //gamecam.position.y = player.b2body.getPosition().y; //обновляет нашу геймкамеру с корректными кооридантами после изменений gamecam.update(); //говорит нашему renderer отрисовывать только то что камера видит renderer.setView(gamecam); } @Override public void render(float delta) { update(delta); Gdx.gl.glClearColor(1, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); //render our game map renderer.render(); //render our Box2DDebugLines b2dr.render(world,gamecam.combined); game.batch.setProjectionMatrix(gamecam.combined); game.batch.begin(); player.draw(game.batch); goomba.draw(game.batch); game.batch.end(); //Set our batch to now draw what the Hud camera sees. game.batch.setProjectionMatrix(hud.stage.getCamera().combined); hud.stage.draw(); } @Override public void resize(int width, int height) { //update our game viewport gamePort.update(width, height); } public TiledMap getMap() { return map; } public World getWorld(){ return world; } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { map.dispose(); renderer.dispose(); world.dispose(); b2dr.dispose(); hud.dispose(); } }
30.675127
114
0.651663
08f85d0f49ed7248fbf8197c7937e54e8e2ab45e
466
package io.youcham.modules.sys.service; import com.baomidou.mybatisplus.service.IService; import io.youcham.common.utils.PageUtils; import io.youcham.modules.sys.entity.SysExportParameterEntity; import java.util.Map; /** * 导出参数 * * @author youcham * @email http://www.youcham.com/ * @date 2018-10-11 11:56:57 */ public interface SysExportParameterService extends IService<SysExportParameterEntity> { PageUtils queryPage(Map<String, Object> params); }
22.190476
87
0.76824
1d96f228fb71b84e46db736e7fa1226c28e7f69c
4,277
/* ******************************************************************************************************* Copyright (c) 2015 EXILANT Technologies Private Limited 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 com.exilant.exility.core; class CheckBoxField extends AbstractInputField { boolean checkedValueIsTheDefault; String checkedValue; String uncheckedValue; boolean isChecked; String tableName; CheckBoxField() { this.checkedValueIsTheDefault = false; this.checkedValue = null; this.uncheckedValue = null; this.isChecked = false; this.tableName = null; } void setTableName(final String tableName) { this.tableName = tableName; } @Override void fieldToHtml(final StringBuilder sbf, final PageGeneratorContext pageContext) { final AbstractDataType dt = DataTypes.getDataType(this.dataType, null); if (dt.getValueType() != DataValueType.BOOLEAN && !this.name.endsWith("Delete")) { Spit.out("ERROR:" + this.name + " is a check box but its data type is not Boolean. Some features will not work properly."); } sbf.append("\n<input type=\"checkbox\" "); super.addMyAttributes(sbf, pageContext); if (this.checkedValue != null) { sbf.append(" value = \"").append(this.checkedValue).append("\" "); } if (this.checkedValueIsTheDefault) { sbf.append(" checked = \"checked\" "); } sbf.append("/>"); final String lbl = this.getLabelToUse(pageContext); final String layoutType = pageContext.getLayoutType(); if (layoutType != null && layoutType.equals("5") && lbl != null) { sbf.append("\n<label for=\"").append(this.name).append("\" "); if (this.hoverText != null) { sbf.append("title=\"").append(this.hoverText).append("\" "); } sbf.append(">").append(lbl).append("</label>"); } } @Override public void initialize() { super.initialize(); if (this.checkedValueIsTheDefault) { this.isChecked = true; } BooleanDataType dt = null; try { dt = (BooleanDataType)DataTypes.getDataType(this.dataType, null); } catch (Exception e) { Spit.out("Field " + this.name + " does not have a valid boolean data type associates with that. Check box WILL NOT be initialized with the rigth default"); } if (this.defaultValue == null) { if (this.checkedValueIsTheDefault) { if (this.checkedValue != null) { this.defaultValue = this.checkedValue; } else if (dt != null) { this.defaultValue = dt.trueValue; } } else if (this.uncheckedValue != null) { this.defaultValue = this.uncheckedValue; } else if (dt != null) { this.defaultValue = dt.falseValue; } Spit.out("A default value of " + this.defaultValue + " is set to " + this.name); } } }
42.77
167
0.595745
119ed41a6618f889348003b258d3ed2baf9f7054
1,263
//package com.mmzs.springboot.s00.application.controller; // //import org.springframework.scheduling.annotation.Async; //import org.springframework.scheduling.annotation.EnableAsync; //import org.springframework.scheduling.annotation.EnableScheduling; //import org.springframework.scheduling.annotation.Scheduled; //import org.springframework.stereotype.Component; //import java.time.LocalDateTime; // // ////@Component注解用于对那些比较中立的类进行注释; ////相对与在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller 对分层中的类进行注释 //@Component //@EnableScheduling // 1.开启定时任务 //@EnableAsync // 2.开启多线程 //public class MultithreadScheduleTask { // // @Async // @Scheduled(fixedDelay = 1000) //间隔1秒 // public void first() throws InterruptedException { // System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName()); // System.out.println(); // Thread.sleep(1000 * 10); // } // // @Async // @Scheduled(fixedDelay = 2000) // public void second() { // System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName()); // System.out.println(); // } // }
38.272727
134
0.657165
40f148c2b7e2877fb2648997589ba51f850e0d4f
4,046
// Copyright 2009-2013 The Apache Software Foundation // // 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.apache.tapestry5.integration.app1; import org.apache.tapestry5.internal.TapestryInternalUtils; import org.apache.tapestry5.test.TapestryRunnerConstants; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.net.URL; public class AssetTests extends App1TestCase { @DataProvider private Object[][] asset_data() { return new Object[][]{ {"icon", "src/test/app1/images/tapestry_banner.gif"}, {"button", "src/test/resources/org/apache/tapestry5/integration/app1/pages/nested/tapestry-button.png"}, {"viaContext", "src/test/app1/images/asf_logo_wide.gif"}, {"meta", "src/test/resources/META-INF/assets/tapestry.png"}, {"templatemeta", "src/test/resources/META-INF/assets/plugin.png"}}; } @Test(dataProvider = "asset_data") public void assets(String id, String localPath) throws Exception { openLinks("AssetDemo"); // Test for https://issues.apache.org/jira/browse/TAPESTRY-1935 // assertSourcePresent("<link href=\"/css/app.css\" rel=\"stylesheet\" type=\"text/css\">"); // Read the byte stream for the asset and compare to the real copy. String assetURL = getAttribute(String.format("//img[@id='%s']/@src", id)); compareDownloadedAsset(assetURL, localPath); } // TAP5-1515 @Test public void external_url_asset_bindings() { openLinks("AssetDemo"); assertEquals("http://cdnjs.cloudflare.com/ajax/libs/d3/3.0.0/d3.js", getText("httpAsset")); assertEquals("https://cdnjs.cloudflare.com/ajax/libs/d3/3.0.0/d3.js", getText("httpsAsset")); assertEquals("http://cdnjs.cloudflare.com/ajax/libs/d3/3.0.0/d3.js", getText("protocolRelativeAsset")); assertEquals("ftp://cdnjs.cloudflare.com/ajax/libs/d3/3.0.0/d3.js", getText("ftpAsset")); // check whether externaly @Import'ed d3 works assertTrue(isElementPresent("css=svg")); } // TAP5-2185 @Test public void redirection_of_requests_to_assets_with_wrong_checksums() { openLinks("AssetDemo"); // paragraph is rendered with display="none" and the javascript asset changes it to display="block" // without the fix, selenium timesout because the javascript code that sets the condition // used by tapestry testing code to know when the page is finished loading is never invoked. assertTrue(isVisible("assetWithWrongChecksum")); } private void compareDownloadedAsset(String assetURL, String localPath) throws Exception { // Strip off the leading slash URL url = new URL(getBaseURL() + assetURL.substring(1)); byte[] downloaded = readContent(url); File local = new File(TapestryRunnerConstants.MODULE_BASE_DIR, localPath); byte[] actual = readContent(local.toURL()); assertEquals(downloaded, actual); } private byte[] readContent(URL url) throws Exception { InputStream is = new BufferedInputStream(url.openStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); TapestryInternalUtils.copy(is, os); os.close(); is.close(); return os.toByteArray(); } }
35.80531
120
0.679684
6c060a872c23803a408c39c547899fe9189ecce4
6,627
/** * Package: MAG - VistA Imaging WARNING: Per VHA Directive 2004-038, this routine should not be modified. Date Created: Site Name: Washington OI Field Office, Silver Spring, MD Developer: vhaiswlouthj Description: ;; +--------------------------------------------------------------------+ ;; Property of the US Government. ;; No permission to copy or redistribute this software is given. ;; Use of unreleased versions of this software requires the user ;; to execute a written test agreement with the VistA Imaging ;; Development Office of the Department of Veterans Affairs, ;; telephone (301) 734-0100. ;; ;; The Food and Drug Administration classifies this software as ;; a Class II medical device. As such, it may not be changed ;; in any way. Modifications to this software may result in an ;; adulterated medical device under 21CFR820, the use of which ;; is considered to be a violation of US Federal Statutes. ;; +--------------------------------------------------------------------+ */ package gov.va.med.imaging.router.commands.vistarad; import gov.va.med.RoutingToken; import gov.va.med.imaging.core.annotations.routerfacade.RouterCommandExecution; import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException; import gov.va.med.imaging.core.interfaces.exceptions.MethodException; import gov.va.med.imaging.exchange.business.vistarad.ExamSite; import gov.va.med.imaging.transactioncontext.TransactionContext; import gov.va.med.imaging.transactioncontext.TransactionContextFactory; /** * * Does not get fully loaded exams, only shallow exams * * A command to get a List of Exam instances: * 1.) from a single Site * 2.) related to a single patient * 3.) meeting the criteria of the given StudyFilter instance * * @author vhaiswlouthj * */ @RouterCommandExecution(asynchronous=true, distributable=false) public class GetExamSiteBySiteNumberCommandImpl extends AbstractExamCommandImpl<ExamSite> { private static final long serialVersionUID = 5473568262532356886L; private final RoutingToken routingToken; private final String patientIcn; private final Boolean forceRefresh; private final Boolean forceImagesFromJb; /** * * @param site * @param patientIcn * @param fullyLoadExams * @param forceRefresh True to force the data to come from the datasource and not the cache. False to allow the data to come from the cache */ public GetExamSiteBySiteNumberCommandImpl(RoutingToken routingToken, String patientIcn, Boolean forceRefresh, Boolean forceImagesFromJb) { super(); this.routingToken = routingToken; this.patientIcn = patientIcn; this.forceRefresh = forceRefresh; this.forceImagesFromJb = forceImagesFromJb; } public RoutingToken getRoutingToken() { return this.routingToken; } public String getPatientIcn() { return this.patientIcn; } /** * @return the forceRefresh */ public Boolean isForceRefresh() { return forceRefresh; } // public Site getSite() // { // if((this.site == null) && (this.siteNumber != null)) // { // try // { // CommandContext context = getCommandContext(); // this.site = context.getSite(this.siteNumber.getSiteNumber()).getSite(); // } // catch(MethodException mX) // { // getLogger().error("Error getting site from site number '" + siteNumber + "'", mX); // this.site = null; // // set site number to null to prevent trying again (since it won't work!) // this.siteNumber = null; // } // } // return this.site; // } // public String getSiteNumber() // { // return getSite().getSiteNumber(); // } public Boolean isForceImagesFromJb() { return forceImagesFromJb; } /* (non-Javadoc) * @see gov.va.med.imaging.core.router.AsynchronousCommandProcessor#callInTransactionContext() */ @Override public ExamSite callSynchronouslyInTransactionContext() throws MethodException, ConnectionException { getLogger().info("Getting exam site for site '" + this.getRoutingToken() + "' for patient '" + getPatientIcn() + ", forceRefresh=" + isForceRefresh() + "."); TransactionContext transactionContext = TransactionContextFactory.get(); transactionContext.setServicedSource(this.getRoutingToken().toRoutingTokenString()); ExamSite examSite = this.getExamSite(this.getRoutingToken(), this.getPatientIcn(), false, this.isForceRefresh(), isForceImagesFromJb()); return examSite; } @Override protected boolean areClassSpecificFieldsEqual(Object obj) { // Perform cast for subsequent tests final GetExamSiteBySiteNumberCommandImpl other = (GetExamSiteBySiteNumberCommandImpl) obj; // Check the patient id and siteNumber boolean allEqual = true; allEqual = allEqual && areFieldsEqual(this.getPatientIcn(), other.getPatientIcn()); allEqual = allEqual && areFieldsEqual(this.getRoutingToken(), other.getRoutingToken()); allEqual = allEqual && areFieldsEqual(this.forceRefresh, other.forceRefresh); allEqual = allEqual && areFieldsEqual(this.forceImagesFromJb, other.forceImagesFromJb); return allEqual; } /* (non-Javadoc) * @see gov.va.med.imaging.core.router.AsynchronousCommandProcessor#parameterToString() */ @Override protected String parameterToString() { StringBuffer sb = new StringBuffer(); sb.append(this.getRoutingToken()); sb.append(','); sb.append(this.getPatientIcn()); sb.append(','); sb.append(this.isForceRefresh()); sb.append(','); sb.append(this.isForceImagesFromJb()); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.forceRefresh ? 1231 : 1237); result = prime * result + ((this.patientIcn == null) ? 0 : this.patientIcn.hashCode()); result = prime * result + ((this.routingToken == null) ? 0 : this.routingToken.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final GetExamSiteBySiteNumberCommandImpl other = (GetExamSiteBySiteNumberCommandImpl) obj; if (this.forceRefresh != other.forceRefresh) return false; if (this.patientIcn == null) { if (other.patientIcn != null) return false; } else if (!this.patientIcn.equals(other.patientIcn)) return false; if (this.routingToken == null) { if (other.routingToken != null) return false; } else if (!this.routingToken.equals(other.routingToken)) return false; return true; } }
30.823256
159
0.700015
dcfb070e833818975843f1c2980e23903b7b4671
2,100
/***************************************************************** * 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.cayenne.configuration.rop.client; import org.apache.cayenne.configuration.CayenneRuntime; import org.apache.cayenne.di.Module; import org.apache.cayenne.remote.ClientConnection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import static java.util.Arrays.asList; /** * A user application entry point to Cayenne stack on the ROP client. * * @since 3.1 * @since 4.0 preferred way to create this class is with {@link ClientRuntime#builder()} method. */ public class ClientRuntime extends CayenneRuntime { /** * @since 4.0 moved from deprecated ClientLocalRuntime class */ public static final String CLIENT_SERVER_CHANNEL_KEY = "client-server-channel"; /** * Creates new builder of client runtime * @return client runtime builder * * @since 4.0 */ public static ClientRuntimeBuilder builder() { return new ClientRuntimeBuilder(); } /** * @since 4.0 */ protected ClientRuntime(Collection<Module> modules) { super(modules); } public ClientConnection getConnection() { return injector.getInstance(ClientConnection.class); } }
31.343284
96
0.699048
f19f2c8a9d712ee2fd207fab9a8b079db99f293a
9,614
package com.berry_med.spo2.bluetooth; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; import java.util.List; public class BluetoothLeService extends Service { public static final String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE"; public static final String ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED"; public static final String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED"; public static final String ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED"; public static final String ACTION_SPO2_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_SPO2_DATA_AVAILABLE"; public static final String EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA"; private static final int STATE_CONNECTED = 2; private static final int STATE_CONNECTING = 1; private static final int STATE_DISCONNECTED = 0; /* access modifiers changed from: private */ public static final String TAG = BluetoothLeService.class.getSimpleName(); private static final int TRANSFER_PACKAGE_SIZE = 10; private byte[] buf = new byte[10]; private int bufIndex = 0; private final IBinder mBinder = new LocalBinder(); private BluetoothAdapter mBluetoothAdapter; private String mBluetoothDeviceAddress; /* access modifiers changed from: private */ public BluetoothGatt mBluetoothGatt; private BluetoothManager mBluetoothManager; /* access modifiers changed from: private */ public int mConnectionState = 0; private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == 2) { String intentAction = BluetoothLeService.ACTION_GATT_CONNECTED; BluetoothLeService.this.mConnectionState = 2; BluetoothLeService.this.broadcastUpdate(intentAction); Log.i(BluetoothLeService.TAG, "Connected to GATT server."); Log.i(BluetoothLeService.TAG, "Attempting to start service discovery:" + BluetoothLeService.this.mBluetoothGatt.discoverServices()); } else if (newState == 0) { String intentAction2 = BluetoothLeService.ACTION_GATT_DISCONNECTED; BluetoothLeService.this.mConnectionState = 0; Log.i(BluetoothLeService.TAG, "Disconnected from GATT server."); BluetoothLeService.this.broadcastUpdate(intentAction2); } } public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == 0) { BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED); } else { Log.w(BluetoothLeService.TAG, "onServicesDiscovered received: " + status); } } public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == 0) { BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_DATA_AVAILABLE, characteristic); } } public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_SPO2_DATA_AVAILABLE, characteristic); } }; public class LocalBinder extends Binder { public LocalBinder() { } /* access modifiers changed from: 0000 */ public BluetoothLeService getService() { return BluetoothLeService.this; } } /* access modifiers changed from: private */ public void broadcastUpdate(String action) { sendBroadcast(new Intent(action)); } /* access modifiers changed from: private */ public void broadcastUpdate(String action, BluetoothGattCharacteristic characteristic) { Intent intent = new Intent(action); if (Const.UUID_CHARACTER_RECEIVE.equals(characteristic.getUuid())) { for (byte b : characteristic.getValue()) { this.buf[this.bufIndex] = b; this.bufIndex++; if (this.bufIndex == this.buf.length) { intent.putExtra(EXTRA_DATA, this.buf); sendBroadcast(intent); this.bufIndex = 0; } } return; } byte[] data = characteristic.getValue(); if (data != null && data.length > 0) { new StringBuilder(data.length); intent.putExtra(EXTRA_DATA, new String(data)); sendBroadcast(intent); } } public IBinder onBind(Intent intent) { return this.mBinder; } public boolean onUnbind(Intent intent) { close(); return super.onUnbind(intent); } public boolean initialize() { if (this.mBluetoothManager == null) { this.mBluetoothManager = (BluetoothManager) getSystemService("bluetooth"); if (this.mBluetoothManager == null) { Log.e(TAG, "Unable to initialize BluetoothManager."); return false; } } this.mBluetoothAdapter = this.mBluetoothManager.getAdapter(); if (this.mBluetoothAdapter != null) { return true; } Log.e(TAG, "Unable to obtain a BluetoothAdapter."); return false; } public boolean connect(String address) { if (this.mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } else if (this.mBluetoothDeviceAddress == null || !address.equals(this.mBluetoothDeviceAddress) || this.mBluetoothGatt == null) { BluetoothDevice device = this.mBluetoothAdapter.getRemoteDevice(address); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } this.mBluetoothGatt = device.connectGatt(this, false, this.mGattCallback); Log.d(TAG, "Trying to create a new connection."); this.mBluetoothDeviceAddress = address; this.mConnectionState = 1; return true; } else { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (!this.mBluetoothGatt.connect()) { return false; } this.mConnectionState = 1; return true; } } public void disconnect() { if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); } else { this.mBluetoothGatt.disconnect(); } } public void close() { if (this.mBluetoothGatt != null) { this.mBluetoothGatt.close(); this.mBluetoothGatt = null; } } public void readCharacteristic(BluetoothGattCharacteristic characteristic) { if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); } else { this.mBluetoothGatt.readCharacteristic(characteristic); } } public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { if (this.mBluetoothAdapter == null || this.mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } this.mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); if (Const.UUID_CHARACTER_RECEIVE.equals(characteristic.getUuid())) { BluetoothGattDescriptor descriptor = characteristic.getDescriptor(Const.UUID_CLIENT_CHARACTER_CONFIG); if (enabled) { descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); } else { descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE); } this.mBluetoothGatt.writeDescriptor(descriptor); } } public List<BluetoothGattService> getSupportedGattServices() { if (this.mBluetoothGatt == null) { return null; } return this.mBluetoothGatt.getServices(); } public void write(BluetoothGattCharacteristic ch, byte[] bytes) { int byteOffset = 0; while (bytes.length - byteOffset > 10) { byte[] b = new byte[10]; System.arraycopy(bytes, byteOffset, b, 0, 10); ch.setValue(b); this.mBluetoothGatt.writeCharacteristic(ch); byteOffset += 10; } if (bytes.length - byteOffset != 0) { byte[] b2 = new byte[(bytes.length - byteOffset)]; System.arraycopy(bytes, byteOffset, b2, 0, bytes.length - byteOffset); ch.setValue(b2); this.mBluetoothGatt.writeCharacteristic(ch); } } }
41.8
148
0.648429
454566fe8222684e39f8c40ad3e2714c4ed32699
3,346
package net.minecraft.world.level.block.state.properties; import net.minecraft.sounds.SoundEffect; import net.minecraft.sounds.SoundEffects; import net.minecraft.tags.Tag; import net.minecraft.tags.TagsBlock; import net.minecraft.util.INamable; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.material.Material; public enum BlockPropertyInstrument implements INamable { HARP("harp", SoundEffects.BLOCK_NOTE_BLOCK_HARP), BASEDRUM("basedrum", SoundEffects.BLOCK_NOTE_BLOCK_BASEDRUM), SNARE("snare", SoundEffects.BLOCK_NOTE_BLOCK_SNARE), HAT("hat", SoundEffects.BLOCK_NOTE_BLOCK_HAT), BASS("bass", SoundEffects.BLOCK_NOTE_BLOCK_BASS), FLUTE("flute", SoundEffects.BLOCK_NOTE_BLOCK_FLUTE), BELL("bell", SoundEffects.BLOCK_NOTE_BLOCK_BELL), GUITAR("guitar", SoundEffects.BLOCK_NOTE_BLOCK_GUITAR), CHIME("chime", SoundEffects.BLOCK_NOTE_BLOCK_CHIME), XYLOPHONE("xylophone", SoundEffects.BLOCK_NOTE_BLOCK_XYLOPHONE), IRON_XYLOPHONE("iron_xylophone", SoundEffects.BLOCK_NOTE_BLOCK_IRON_XYLOPHONE), COW_BELL("cow_bell", SoundEffects.BLOCK_NOTE_BLOCK_COW_BELL), DIDGERIDOO("didgeridoo", SoundEffects.BLOCK_NOTE_BLOCK_DIDGERIDOO), BIT("bit", SoundEffects.BLOCK_NOTE_BLOCK_BIT), BANJO("banjo", SoundEffects.BLOCK_NOTE_BLOCK_BANJO), PLING("pling", SoundEffects.BLOCK_NOTE_BLOCK_PLING); private final String q; private final SoundEffect r; private BlockPropertyInstrument(String s, SoundEffect soundeffect) { this.q = s; this.r = soundeffect; } @Override public String getName() { return this.q; } public SoundEffect b() { return this.r; } public static BlockPropertyInstrument a(IBlockData iblockdata) { if (iblockdata.a(Blocks.CLAY)) { return BlockPropertyInstrument.FLUTE; } else if (iblockdata.a(Blocks.GOLD_BLOCK)) { return BlockPropertyInstrument.BELL; } else if (iblockdata.a((Tag) TagsBlock.WOOL)) { return BlockPropertyInstrument.GUITAR; } else if (iblockdata.a(Blocks.PACKED_ICE)) { return BlockPropertyInstrument.CHIME; } else if (iblockdata.a(Blocks.BONE_BLOCK)) { return BlockPropertyInstrument.XYLOPHONE; } else if (iblockdata.a(Blocks.IRON_BLOCK)) { return BlockPropertyInstrument.IRON_XYLOPHONE; } else if (iblockdata.a(Blocks.SOUL_SAND)) { return BlockPropertyInstrument.COW_BELL; } else if (iblockdata.a(Blocks.PUMPKIN)) { return BlockPropertyInstrument.DIDGERIDOO; } else if (iblockdata.a(Blocks.EMERALD_BLOCK)) { return BlockPropertyInstrument.BIT; } else if (iblockdata.a(Blocks.HAY_BLOCK)) { return BlockPropertyInstrument.BANJO; } else if (iblockdata.a(Blocks.GLOWSTONE)) { return BlockPropertyInstrument.PLING; } else { Material material = iblockdata.getMaterial(); return material == Material.STONE ? BlockPropertyInstrument.BASEDRUM : (material == Material.SAND ? BlockPropertyInstrument.SNARE : (material == Material.SHATTERABLE ? BlockPropertyInstrument.HAT : (material != Material.WOOD && material != Material.NETHER_WOOD ? BlockPropertyInstrument.HARP : BlockPropertyInstrument.BASS))); } } }
53.111111
905
0.728332
08b8035a2fc489316cdcfe8ef5db01348f370fda
890
package com.hashedin.redmask.config; import freemarker.template.Configuration; import freemarker.template.TemplateExceptionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TemplateConfiguration { private static final Logger log = LoggerFactory.getLogger(TemplateConfiguration.class); // Path is src/main/resources/templates private static final String TEMPLATE_DIR = "/templates/"; private static final String UTF_8 = "UTF-8"; private final Configuration config; public TemplateConfiguration() { Configuration cfg = new Configuration(Configuration.VERSION_2_3_29); cfg.setClassForTemplateLoading(this.getClass(), TEMPLATE_DIR); cfg.setDefaultEncoding(UTF_8); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); this.config = cfg; } public Configuration getConfig() { return config; } }
27.8125
89
0.783146
dd880178849dc60258db558f492f717d3fdf11fc
2,827
/* * Copyright 2016 Codnos Ltd. * * 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.codnos.dbgp.api; import com.codnos.dbgp.internal.impl.DBGpEngineImpl; import com.codnos.dbgp.internal.impl.DBGpIdeImpl; import com.codnos.dbgp.internal.impl.StatusChangeHandlerFactory; public class DBGpFactory { public static DBGpIdeBuilder ide() { return new DBGpIdeBuilder(); } public static DBGpEngineBuilder engine() { return new DBGpEngineBuilder(); } public static class DBGpIdeBuilder { private int port; private DebuggerIde debuggerIde; public DBGpIdeBuilder withPort(int port) { this.port = port; return this; } public DBGpIdeBuilder withDebuggerIde(DebuggerIde debuggerIde) { this.debuggerIde = debuggerIde; return this; } public DBGpIde build() { validate("port", port); validate("debuggerIde", debuggerIde); return new DBGpIdeImpl(port, debuggerIde); } } public static class DBGpEngineBuilder { private int port; private DebuggerEngine debuggerEngine; private StatusChangeHandlerFactory statusChangeHandlerFactory = new StatusChangeHandlerFactory(); public DBGpEngineBuilder withPort(int port) { this.port = port; return this; } public DBGpEngineBuilder withDebuggerEngine(DebuggerEngine debuggerEngine) { this.debuggerEngine = debuggerEngine; return this; } DBGpEngineBuilder withStatusChangeHandlerFactory(StatusChangeHandlerFactory statusChangeHandlerFactory) { this.statusChangeHandlerFactory = statusChangeHandlerFactory; return this; } public DBGpEngine build() { validate("port", port); validate("debuggerEngine", debuggerEngine); validate("statusChangeHandlerFactory", statusChangeHandlerFactory); return new DBGpEngineImpl(port, debuggerEngine, statusChangeHandlerFactory); } } private static void validate(String field, Object value) { if (value == null) { throw new IllegalStateException("Field " + field + " was not set but is required!"); } } }
32.494253
113
0.6682
ef0197d675d22c97f8babe91f724be129250a0e1
3,336
/* * This file is a part of the SchemaSpy project (http://schemaspy.org). * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2014 John Currier * * SchemaSpy 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. * * SchemaSpy 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 org.schemaspy.view; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; import org.schemaspy.DbAnalyzer; import org.schemaspy.model.Database; import org.schemaspy.model.ForeignKeyConstraint; import org.schemaspy.model.Table; import org.schemaspy.model.TableColumn; /** * This page lists all of the 'things that might not be quite right' * about the schema. * * @author John Currier */ public class HtmlAnomaliesPage extends HtmlFormatter { private static HtmlAnomaliesPage instance = new HtmlAnomaliesPage(); /** * Singleton: Don't allow instantiation */ private HtmlAnomaliesPage() { } /** * Singleton accessor * * @return the singleton instance */ public static HtmlAnomaliesPage getInstance() { return instance; } public void write(Database database, Collection<Table> tables, List<? extends ForeignKeyConstraint> impliedConstraints, File outputDir) throws IOException { HashMap<String, Object> scopes = new HashMap<String, Object>(); List<Table> unIndexedTables = DbAnalyzer.getTablesWithoutIndexes(new HashSet<Table>(tables)); List<ForeignKeyConstraint> impliedConstraintColumns = impliedConstraints.stream().filter(c -> !c.getChildTable().isView()).collect(Collectors.toList()); List<Table> oneColumnTables = DbAnalyzer.getTablesWithOneColumn(tables).stream().filter(t -> !t.isView()).collect(Collectors.toList()); List<Table> incrementingColumnNames = DbAnalyzer.getTablesWithIncrementingColumnNames(tables).stream().filter(t -> !t.isView()).collect(Collectors.toList()); List<TableColumn> uniqueNullables = DbAnalyzer.getDefaultNullStringColumns(new HashSet<Table>(tables)); scopes.put("displayNumRows", (displayNumRows ? new Object() : null)); scopes.put("impliedConstraints", impliedConstraintColumns); scopes.put("unIndexedTables", unIndexedTables); scopes.put("oneColumnTables", oneColumnTables); scopes.put("incrementingColumnNames", incrementingColumnNames); scopes.put("uniqueNullables", uniqueNullables); MustacheWriter mw = new MustacheWriter( outputDir, scopes, getPathToRoot(), database.getName(), false); mw.write("anomalies.html", "anomalies.html", "anomalies.js"); } }
42.769231
166
0.732314
399ea61d6c20fd4b576417999bd1acf3c9470468
1,222
package org.github.dtsopensource.admin.exception; /** * @author ligaofeng 2016年12月23日 下午1:34:26 */ public class DTSAdminException extends Exception { private static final long serialVersionUID = 674322939576507543L; /** * init BizException */ public DTSAdminException() { super(); } /** * init BizException * * @param message */ public DTSAdminException(String message) { super(message); } /** * init BizException * * @param message * @param cause */ public DTSAdminException(String message, Throwable cause) { super(message, cause); } /** * init BizException * * @param cause */ public DTSAdminException(Throwable cause) { super(cause); } /** * init BizException * * @param message * @param cause * @param enableSuppression * @param writableStackTrace */ public DTSAdminException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
21.068966
119
0.580196
49930bf09e7f9099a510d52f1dc0138055494e83
954
import java.awt.Color; import java.awt.Image; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; public class Logica { private JPanel panel; private ImageIcon image; private JLabel label; public Logica(){ } public JPanel panel(int x, int y, int ancho, int largo, Color color){ panel = new JPanel(); panel.setBounds(x, y, ancho, largo); panel.setLayout(null); panel.setBackground(color); return panel; } public JLabel icon(String ruta, int x, int y, int width, int height){ image = new ImageIcon(getClass().getResource(ruta)); Icon imageScaled = new ImageIcon(image.getImage().getScaledInstance(width, height,Image.SCALE_DEFAULT)); label = new JLabel(); label.setSize(width, height); label.setLocation(x, y); label.setIcon(imageScaled); return label; } }
29.8125
112
0.649895
ee87a7106ada5895b42f77e3b7a8d4b6ed7864d4
1,348
package org.redquark.algorithms.algorithms.sort; public class CountingSort implements Sort<Integer> { /** * @param data - array to be sorted * @return sorted array */ @Override public Integer[] sort(Integer[] data) { if (data == null || data.length == 0) { return null; } // Length of the array int n = data.length; // Find the maximum and minimum values in the array int max = data[0]; int min = data[0]; for (int i = 1; i < n; i++) { if (data[i] > max) { max = data[i]; } if (data[i] < min) { min = data[i]; } } // Range of the values int range = max - min + 1; // Count array int[] count = new int[range]; // Output array int[] output = new int[n]; // Fill the count array for (int datum : data) { count[datum - min]++; } for (int i = 1; i < range; i++) { count[i] += count[i - 1]; } for (int i = n - 1; i >= 0; i--) { output[count[data[i] - min] - 1] = data[i]; count[data[i] - min]--; } for (int i = 0; i < n; i++) { data[i] = output[i]; } return data; } }
26.431373
59
0.4273
40dc2cee6c347a41305443b281e2780777f45309
3,877
package rw.ac.rca.termOneExam.utils; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import rw.ac.rca.termOneExam.domain.City; import rw.ac.rca.termOneExam.repository.ICityRepository; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @RunWith(MockitoJUnitRunner.class) public class CityUtilTest { @Mock private ICityRepository cityRepositoryMock; List<City> mock = mock(List.class); @Test public void noCityWithWeatherMoreThan40CelsiusTest_success(){ Boolean citiesWithWeatherGreater40Checker = false; when(cityRepositoryMock.findAll()).thenReturn(Arrays.asList(new City("Kigali",10), new City("Musanze",10))); for (City city: cityRepositoryMock.findAll()) if(city.getWeather() > 40) citiesWithWeatherGreater40Checker = true; assertEquals(false, citiesWithWeatherGreater40Checker); } @Test public void noCityWithWeatherMoreThan40CelsiusTest_Failed(){ Boolean citiesWithWeatherGreater40Checker = false; when(cityRepositoryMock.findAll()).thenReturn(Arrays.asList(new City("Kigali",10), new City("Musanze",10), new City("Kayonza",50))); for (City city: cityRepositoryMock.findAll()) if(city.getWeather() > 40) citiesWithWeatherGreater40Checker = true; assertEquals(true, citiesWithWeatherGreater40Checker); } @Test public void containsKigaliAndMusanzeCitiesTest_success(){ Boolean containsCityMUSANZE = false; Boolean containsCityKIGALI = false; when(cityRepositoryMock.findAll()).thenReturn(Arrays.asList(new City("Kigali",10), new City("Musanze",10))); for (City city: cityRepositoryMock.findAll()){ if(city.getName().equals("Kigali") ) { containsCityKIGALI = true; } if(city.getName() == "Musanze") { containsCityMUSANZE = true; } } assertEquals(true, containsCityKIGALI); assertEquals(true, containsCityMUSANZE); } @Test public void testSpying() { ArrayList<City> arrayListSpy = spy(ArrayList.class); arrayListSpy.add(new City("Kigali",30)); System.out.println(arrayListSpy.get(0));//Test0 System.out.println(arrayListSpy.size());//1 assertEquals(1,arrayListSpy.size()); arrayListSpy.add(new City("Kamonyi",30)); arrayListSpy.add(new City("Kayonza",20)); System.out.println(arrayListSpy.size());//3 assertEquals(3,arrayListSpy.size()); when(arrayListSpy.size()).thenReturn(5); System.out.println(arrayListSpy.size());//5 assertEquals(5,arrayListSpy.size()); arrayListSpy.add(new City("Nyamagabe",30)); System.out.println(arrayListSpy.size());//5 assertEquals(5,arrayListSpy.size()); } @Test public void testMocking() { ArrayList<City> arrayListMock = mock(ArrayList.class); System.out.println(arrayListMock.get(0));//null System.out.println(arrayListMock.size());//0 assertEquals(0,arrayListMock.size()); arrayListMock.add(new City("Kigali",30)); arrayListMock.add(new City("Kayonza",20)); System.out.println(arrayListMock.size());//0 assertEquals(0,arrayListMock.size()); when(arrayListMock.size()).thenReturn(5); System.out.println(arrayListMock.size());//5 assertEquals(5,arrayListMock.size()); } }
28.29927
91
0.630642
0f29cd838ad2adc89e7065b38010e244898e53cc
1,881
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package jsinterop.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * JsFunction marks a functional interface as being the definition of a JavaScript function. * * <p>There are some limitations exists on JsFunction to make them practical and efficient: * * <ul> * <li>A JsFunction interface cannot extend any other interfaces. * <li>A class may not implement more than one JsFunction interface. * <li>A class that implements a JsFunction type cannot be a {@link JsType} (directly or * indirectly). * <li>Fields and defender methods of the interfaces should be marked with {@link JsOverlay} and * cannot be overridden by the implementations. * </ul> * * <p>As a best practice, we also recommend marking JsFunction interfaces with FunctionalInterface * to get improved checking in IDEs. * * <p><b>Instanceof and Castability:</b> * * <p>Instanceof and casting for JsFunction is effectively a JavaScript <tt>'typeof'</tt> check to * determine if the instance is a function. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented public @interface JsFunction {}
37.62
98
0.751196
2f8a346d92c6a2f87b88f51acd61abc39ca46108
2,972
/** * 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 net.java.html.json; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.List; import org.netbeans.html.context.spi.Contexts; import org.netbeans.html.context.spi.Contexts.Id; import org.netbeans.html.json.spi.Technology; /** Represents a property in a class defined with {@link Model} annotation. * * @author Jaroslav Tulach */ @Retention(RetentionPolicy.SOURCE) @Target({}) public @interface Property { /** Name of the property. Will be used to define proper getter and setter * in the associated class. * * @return valid java identifier */ String name(); /** Type of the property. Can either be primitive type (like <code>int.class</code>, * <code>double.class</code>, etc.), {@link String}, {@link Enum enum} or complex model * class (defined by {@link Model} property). * * @return the class of the property */ Class<?> type(); /** Is this property an array of the {@link #type()} or a single value? * If the property is an array, only its getter (returning mutable {@link List} of * the boxed {@link #type()}) is generated. * * @return true, if this property is supposed to represent an array of values */ boolean array() default false; /** Can the value of the property be mutated without restriction or not. * If a property is defined as <em>not mutable</em>, it defines * semi-immutable value that can only be changed in construction time * before the object is passed to underlying {@link Technology}. * Attempts to modify the object later yield {@link IllegalStateException}. * * Technologies may decide to represent such non-mutable * property in more effective way - for * example Knockout Java Bindings technology (with {@link Id id} "ko4j") * uses plain JavaScript value (number, string, array, boolean) rather * than classical observable. * * @return false if the value cannot change after its <em>first use</em> * @since 1.3 */ boolean mutable() default true; }
39.105263
91
0.69852
0b21108f98d01b4e0b92840a126add8390b95ea3
2,795
package cn.ieclipse.smartim.actions; import cn.ieclipse.smartim.SmartClient; import cn.ieclipse.smartim.callback.impl.DefaultLoginCallback; import cn.ieclipse.smartim.views.IMPanel; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.ui.MessageDialogBuilder; import icons.SmartIcons; /** * Created by Jamling on 2017/7/11. */ public class LoginAction extends IMPanelAction { public LoginAction(IMPanel panel) { super(panel, "Login", "Click to login", SmartIcons.signin); } @Override public void actionPerformed(AnActionEvent anActionEvent) { SmartClient client = imPanel.getClient(); boolean ok = true; if (client.isLogin()) { ok = MessageDialogBuilder.yesNo("", "您已处于登录状态,确定要重新登录吗?").show() == 0; } if (ok) { client.setLoginCallback(new MyLoginCallback(client, imPanel)); new Thread() { @Override public void run() { client.login(); } }.start(); } else { imPanel.initContacts(); } // // LoginDialog dialog = new LoginDialog(client); // dialog.setSize(200, 240); // dialog.setLocationRelativeTo(null); // dialog.pack(); // dialog.setVisible(true); // LOG.info("login : " + client.isLogin()); // if (client.isLogin()) { // new LoadThread(client).start(); // } else { // //fillTestData(client); // } } // private void fillTestData(SmartClient client) { // client.categories = new ArrayList<>(); // for (int i = 0; i < 5; i++) { // Category c = new Category(); // c.setName("Cate " + i); // client.categories.add(c); // for (int j = 0; j < 5; j++) { // Friend f = new Friend(); // f.setMarkname("friend " + j); // c.addFriend(f); // } // } // client.groups = new ArrayList<>(); // Group g = new Group(); // g.setName("Group 0"); // client.groups.add(g); // smartPanel.updateContact(); // } public static class MyLoginCallback extends DefaultLoginCallback { private SmartClient client; private IMPanel panel; private MyLoginCallback(SmartClient client, IMPanel panel) { this.client = client; this.panel = panel; } @Override protected void onLoginFinish(boolean success, Exception e) { super.onLoginFinish(success, e); panel.initContacts(); } } }
33.674699
82
0.526297
5106ac59fa3f943a592b3144b8d03f1492df0523
2,727
package com.stylefeng.guns.rest.modular.user.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil; import com.stylefeng.guns.rest.modular.user.bean.UserAuthRequest; import com.stylefeng.guns.rest.modular.user.service.IMtimeUserTService; import com.stylefeng.guns.rest.modular.user.vo.StatusDataAndMsg; import com.stylefeng.guns.rest.modular.user.vo.TokenAndRandomkey; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author YangShuo * @date 2019-07-16 23:34 * * 用户登录验证入口 */ @RestController public class UserAuthController { @Autowired private JwtTokenUtil jwtTokenUtil; @Reference(check = false) IMtimeUserTService userTService; @RequestMapping(value = "/auth", method = RequestMethod.POST, params = {"userName","password"}) public StatusDataAndMsg userLogin(UserAuthRequest authRequest){ StatusDataAndMsg<Object> statusDataAndMsg = new StatusDataAndMsg<>(); //1.判断用户名和密码都正确 boolean validate = userTService.validate(authRequest); if (validate){ //2.在网关产生token try { String username = authRequest.getUserName(); final String randomKey = jwtTokenUtil.getRandomKey(); final String token = jwtTokenUtil.generateToken(username, randomKey); TokenAndRandomkey tokenAndRandomkey = new TokenAndRandomkey(); tokenAndRandomkey.setToken(token); tokenAndRandomkey.setRandomKey(randomKey); statusDataAndMsg.setData(tokenAndRandomkey); statusDataAndMsg.setStatus(0); /* 3.1 生成token成功后,在返回token时将token存入redis里(给用户退出功能使用), * 并将用户关键信息(如uuid)的json格式数据存入redis(给其他需要用户其他信息如uuid的模块使用)。 * */ //将token存入redis里, String: key=usernameToken, value=token String userTokenKey = username + "Token"; userTService.jedisStoreToken(userTokenKey,token); //将该用户的信息查出并存入redis, String: key=username, value=用户信息的json格式数据 userTService.jedisStoreUserMsg(username); }catch (Exception e){ //3.2 产生token失败 statusDataAndMsg.setStatus(999); statusDataAndMsg.setMsg("系统出现异常,请联系管理员"); } }else { //用户名或密码错误 statusDataAndMsg.setStatus(1); statusDataAndMsg.setMsg("用户名或密码错误"); } return statusDataAndMsg; } }
38.408451
99
0.673634
e1e6188c65c84554455d7c7b0e1d16f00f573b1e
4,882
package com.assetco.hotspots.optimization; import com.assetco.search.results.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.util.*; import static com.assetco.hotspots.optimization.TestHelper.*; import static org.junit.jupiter.api.Assertions.*; public class BugsTest { private SearchResults searchResults; private SearchResultHotspotOptimizer optimizer; @BeforeEach public void setup() { searchResults = new SearchResults(); optimizer = new SearchResultHotspotOptimizer(); } @Test public void precedingPartnerWithLongTrailingAssetsDoesNotWin() { var partnerVendor = makeVendor(AssetVendorRelationshipLevel.Partner); var anotherPartnerVendor = makeVendor(AssetVendorRelationshipLevel.Partner); var missing = givenAssetInResultsWithVendor(partnerVendor); var assetFromAnother = givenAssetInResultsWithVendor(anotherPartnerVendor); List<Asset> expected = new ArrayList<>(); expected.add(missing); expected.add(givenAssetInResultsWithVendor(partnerVendor)); expected.add(givenAssetInResultsWithVendor(partnerVendor)); expected.add(givenAssetInResultsWithVendor(partnerVendor)); expected.add(givenAssetInResultsWithVendor(partnerVendor)); whenOptimize(); thenHotspotHasExactly(HotspotKey.Showcase, expected); } @Test public void lowRankedAssetsAlmostNeverHighlighted() { var vendor = makeVendor(AssetVendorRelationshipLevel.Basic); var topic1 = anyTopic(); var topic2 = anyTopic(); optimizer.setHotTopics(() -> Arrays.asList(topic1, topic2)); var expectedAssets = givenAssetsWithTopics(vendor, 2, topic2); givenAssetsWithTopics(vendor, 3, topic1); expectedAssets.add(givenAssetWithTopics(vendor, topic2)); whenOptimize(); thenHotspotHas(HotspotKey.Highlight, expectedAssets); } @Test public void itemsWithSellRatesLastDayLastMonthShouldTakeOneSlot() { var vendor = makeVendor(AssetVendorRelationshipLevel.Basic); var asset = new Asset(string(), string(), URI(), URI(), getPurchaseInfo(50000, 50000), getPurchaseInfo(4000, 4000), setOfTopics(), vendor); searchResults.addFound(asset); whenOptimize(); thenHotspotHasExactly(HotspotKey.HighValue, Arrays.asList(asset)); } private void thenHotspotHasExactly(HotspotKey showcase, List<Asset> expected) { Hotspot hotspot = searchResults.getHotspot(showcase); Asset[] fromHotspot = hotspot.getMembers().toArray(new Asset[0]); Asset[] fromExpected = expected.toArray(new Asset[0]); assertArrayEquals(fromExpected, fromHotspot); } private void thenHotspotHas(HotspotKey hotspotKey, List<Asset> expectedAssets) { for (var expectedAsset : expectedAssets) { assertTrue(searchResults.getHotspot(hotspotKey).getMembers().contains(expectedAsset)); } } private void thenHotspotDoesNotHave(HotspotKey showcase, Asset... assets) { Hotspot hotspot = searchResults.getHotspot(showcase); List<Asset> members = hotspot.getMembers(); for (Asset asset : assets) { assertFalse(members.contains(asset)); } } private void whenOptimize() { optimizer.optimize(searchResults); } private Asset givenAssetInResultsWithVendor(AssetVendor vendor) { Asset asset = new Asset(string(), string(), URI(), URI(), assetPurchaseInfo(), assetPurchaseInfo(), setOfTopics(), vendor); searchResults.addFound(asset); return asset; } private List<Asset> givenAssetsWithTopics(AssetVendor vendor, int count, AssetTopic... topics) { var result = new ArrayList<Asset>(); for (var i = 0; i < count; ++i) { result.add(givenAssetWithTopics(vendor, topics)); } return result; } private Asset givenAssetWithTopics(AssetVendor vendor, AssetTopic... topics) { var actualTopics = new ArrayList<AssetTopic>(); for (var topic : topics) { actualTopics.add(new AssetTopic(topic.getId(), topic.getDisplayName())); } var result = new Asset(string(), string(), URI(), URI(), assetPurchaseInfo(), assetPurchaseInfo(), actualTopics, vendor); searchResults.addFound(result); return result; } private AssetVendor makeVendor(AssetVendorRelationshipLevel relationshipLevel) { return new AssetVendor(string(), string(), relationshipLevel, anyLong()); } private AssetPurchaseInfo getPurchaseInfo(int timesShown, int timesPurchased) { return new AssetPurchaseInfo(timesShown, timesPurchased, new Money(new BigDecimal("0")), new Money(new BigDecimal("0"))); } }
38.440945
131
0.690496
a9213bc6ede94b6e3e076392206cc7d196a44e56
2,577
package tonyusamples.hockey2; import android.graphics.Color; import android.util.Log; import jp.tonyumakkii.tonyusample.R; import tonyu.kernel.TGL; import tonyu.kernel.TonyuGraphicsFileManager; import tonyu.kernel.TonyuPage; public class PageIndex extends TonyuPage { @Override public void open(TonyuPage oldPage) { // 前のページが無しまたはこのページと同じ場合、画像・音の読み込みをしない if (oldPage == null || oldPage.getClass() != this.getClass()) { // 画像読み込み // TGL.grManager.addBitmapFileTonyu("ball", R.drawable.ball); TGL.grManager.addBitmapFileTonyu("table", R.drawable.table); TGL.grManager.addBitmapFileTonyu("tokuten", R.drawable.tokuten); // グローバル変数設定 GLB.pat_table = getPatNo("table"); GLB.pat_tokuten = getPatNo("tokuten"); // マップ読み込み // TGL.map.loadMapDataRes(R.raw.hockey2index); // サウンド読み込み // TGL.mplayer.addResSE("bound", R.raw.bound); TGL.mplayer.addResSE("shot", R.raw.shot); TGL.mplayer.addResSE("in", R.raw.in); TGL.mplayer.addResSE("jingle", R.raw.jingle); TGL.mplayer.addResBGM("bgm", R.raw.bgm); } TGL.screenManager.moveCursor(-9999, -9999); TGL.screenWidth = 560; TGL.screenHeight = 384; TGL.map.setVisible(1); //TGL.screenWidth = 1280; //TGL.screenHeight = 720; //TGL.screenWidth = 1920; //TGL.screenHeight = 1080; //TGL.screenWidth = 3840; //TGL.screenHeight = 2160; GLB.player = (Player) appear(new Player(79, 314, 5)); GLB.ball = (Ball) appear(new Ball(112, 186, 20)); GLB.racket = (Racket) appear(new Racket(113, 219, 17)); GLB.tokuten = (Tokuten) appear(new Tokuten(314, 38, GLB.pat_tokuten+0, 0, 0, 0, 255, 1)); GLB.tokuten_1 = (Tokuten) appear(new Tokuten(278, 38, GLB.pat_tokuten+0, 0, 0, 0, 255, 1)); GLB.tokuten_2 = (Tokuten) appear(new Tokuten(218, 38, GLB.pat_tokuten+0, 0, 0, 0, 255, 1)); GLB.tokuten.nextInc = 10; GLB.tokuten.next = GLB.tokuten_1; GLB.tokuten_1.nextInc = 6; GLB.tokuten_1.next = GLB.tokuten_2; GLB.tokuten_2.nextInc = 10; GLB.pass = (Pass) appear(new Pass(-39, 55, GLB.pat_table+20)); GLB.lap1 = (Lap) appear(new Lap(219, 74, "1st:", Color.WHITE, 15)); GLB.lap2 = (Lap) appear(new Lap(215, 97, "2nd:", Color.WHITE, 15)); GLB.lap3 = (Lap) appear(new Lap(200, 119, "Final :", Color.WHITE, 15)); } @Override public void close(TonyuPage newPage) { // 新しいページへ移行する時、画像・音のデータをクリアする if (newPage.getClass() != this.getClass()) { TGL.grManager.clearBitmap(); TGL.mplayer.clearBGM(); TGL.mplayer.clearSE(); Log.v("loadRes", ""+ newPage.getClass() +" "+ this.getClass()); } } }
32.620253
93
0.666279
c5599eb0ae8bddc8bb5133ab10373db27d5071e5
9,433
/* * 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.beam.sdk.extensions.euphoria.core.translate; import static java.util.Objects.requireNonNull; import org.apache.beam.sdk.extensions.euphoria.core.client.accumulators.AccumulatorProvider; import org.apache.beam.sdk.extensions.euphoria.core.client.functional.BinaryFunctor; import org.apache.beam.sdk.extensions.euphoria.core.client.operator.Join; import org.apache.beam.sdk.extensions.euphoria.core.translate.collector.AdaptableCollector; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.join.CoGbkResult; import org.apache.beam.sdk.transforms.join.CoGroupByKey; import org.apache.beam.sdk.transforms.join.KeyedPCollectionTuple; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.TupleTag; import org.checkerframework.checker.nullness.qual.Nullable; /** {@link OperatorTranslator Translator } for Euphoria {@link Join} operator. */ public class JoinTranslator<LeftT, RightT, KeyT, OutputT> extends AbstractJoinTranslator<LeftT, RightT, KeyT, OutputT> { private abstract static class JoinFn<LeftT, RightT, KeyT, OutputT> extends DoFn<KV<KeyT, CoGbkResult>, KV<KeyT, OutputT>> { private final BinaryFunctor<LeftT, RightT, OutputT> joiner; private final TupleTag<LeftT> leftTag; private final TupleTag<RightT> rightTag; private final AdaptableCollector<KV<KeyT, CoGbkResult>, KV<KeyT, OutputT>, OutputT> resultsCollector; JoinFn( BinaryFunctor<LeftT, RightT, OutputT> joiner, TupleTag<LeftT> leftTag, TupleTag<RightT> rightTag, @Nullable String operatorName, AccumulatorProvider accumulatorProvider) { this.joiner = joiner; this.leftTag = leftTag; this.rightTag = rightTag; this.resultsCollector = new AdaptableCollector<>( accumulatorProvider, operatorName, ((ctx, elem) -> ctx.output(KV.of(ctx.element().getKey(), elem)))); } @ProcessElement @SuppressWarnings("unused") public final void processElement(@Element KV<KeyT, CoGbkResult> element, ProcessContext ctx) { getCollector().setProcessContext(ctx); doJoin( requireNonNull(element.getValue()).getAll(leftTag), requireNonNull(element.getValue()).getAll(rightTag)); } abstract void doJoin(Iterable<LeftT> left, Iterable<RightT> right); abstract String getFnName(); BinaryFunctor<LeftT, RightT, OutputT> getJoiner() { return joiner; } AdaptableCollector<KV<KeyT, CoGbkResult>, KV<KeyT, OutputT>, OutputT> getCollector() { return resultsCollector; } } private static class InnerJoinFn<LeftT, RightT, KeyT, OutputT> extends JoinFn<LeftT, RightT, KeyT, OutputT> { InnerJoinFn( BinaryFunctor<LeftT, RightT, OutputT> joiner, TupleTag<LeftT> leftTag, TupleTag<RightT> rightTag, @Nullable String operatorName, AccumulatorProvider accumulatorProvider) { super(joiner, leftTag, rightTag, operatorName, accumulatorProvider); } @Override protected void doJoin(Iterable<LeftT> left, Iterable<RightT> right) { for (LeftT leftItem : left) { for (RightT rightItem : right) { getJoiner().apply(leftItem, rightItem, getCollector()); } } } @Override String getFnName() { return "inner-join"; } } private static class FullJoinFn<LeftT, RightT, K, OutputT> extends JoinFn<LeftT, RightT, K, OutputT> { FullJoinFn( BinaryFunctor<LeftT, RightT, OutputT> joiner, TupleTag<LeftT> leftTag, TupleTag<RightT> rightTag, @Nullable String operatorName, AccumulatorProvider accumulatorProvider) { super(joiner, leftTag, rightTag, operatorName, accumulatorProvider); } @Override void doJoin(Iterable<LeftT> left, Iterable<RightT> right) { final boolean leftHasValues = left.iterator().hasNext(); final boolean rightHasValues = right.iterator().hasNext(); if (leftHasValues && rightHasValues) { for (RightT rightValue : right) { for (LeftT leftValue : left) { getJoiner().apply(leftValue, rightValue, getCollector()); } } } else if (leftHasValues) { for (LeftT leftValue : left) { getJoiner().apply(leftValue, null, getCollector()); } } else if (rightHasValues) { for (RightT rightValue : right) { getJoiner().apply(null, rightValue, getCollector()); } } } @Override public String getFnName() { return "full-join"; } } private static class LeftOuterJoinFn<LeftT, RightT, K, OutputT> extends JoinFn<LeftT, RightT, K, OutputT> { LeftOuterJoinFn( BinaryFunctor<LeftT, RightT, OutputT> joiner, TupleTag<LeftT> leftTag, TupleTag<RightT> rightTag, @Nullable String operatorName, AccumulatorProvider accumulatorProvider) { super(joiner, leftTag, rightTag, operatorName, accumulatorProvider); } @Override void doJoin(Iterable<LeftT> left, Iterable<RightT> right) { for (LeftT leftValue : left) { if (right.iterator().hasNext()) { for (RightT rightValue : right) { getJoiner().apply(leftValue, rightValue, getCollector()); } } else { getJoiner().apply(leftValue, null, getCollector()); } } } @Override public String getFnName() { return "left-outer-join"; } } private static class RightOuterJoinFn<LeftT, RightT, K, OutputT> extends JoinFn<LeftT, RightT, K, OutputT> { RightOuterJoinFn( BinaryFunctor<LeftT, RightT, OutputT> joiner, TupleTag<LeftT> leftTag, TupleTag<RightT> rightTag, @Nullable String operatorName, AccumulatorProvider accumulatorProvider) { super(joiner, leftTag, rightTag, operatorName, accumulatorProvider); } @Override void doJoin(Iterable<LeftT> left, Iterable<RightT> right) { for (RightT rightValue : right) { if (left.iterator().hasNext()) { for (LeftT leftValue : left) { getJoiner().apply(leftValue, rightValue, getCollector()); } } else { getJoiner().apply(null, rightValue, getCollector()); } } } @Override public String getFnName() { return "::right-outer-join"; } } private static <KeyT, LeftT, RightT, OutputT> JoinFn<LeftT, RightT, KeyT, OutputT> getJoinFn( Join<LeftT, RightT, KeyT, OutputT> operator, TupleTag<LeftT> leftTag, TupleTag<RightT> rightTag, AccumulatorProvider accumulators) { final BinaryFunctor<LeftT, RightT, OutputT> joiner = operator.getJoiner(); switch (operator.getType()) { case INNER: return new InnerJoinFn<>( joiner, leftTag, rightTag, operator.getName().orElse(null), accumulators); case LEFT: return new LeftOuterJoinFn<>( joiner, leftTag, rightTag, operator.getName().orElse(null), accumulators); case RIGHT: return new RightOuterJoinFn<>( joiner, leftTag, rightTag, operator.getName().orElse(null), accumulators); case FULL: return new FullJoinFn<>( joiner, leftTag, rightTag, operator.getName().orElse(null), accumulators); default: throw new UnsupportedOperationException( String.format( "Cannot translate Euphoria '%s' operator to Beam transformations." + " Given join type '%s' is not supported.", Join.class.getSimpleName(), operator.getType())); } } @Override PCollection<KV<KeyT, OutputT>> translate( Join<LeftT, RightT, KeyT, OutputT> operator, PCollection<LeftT> left, PCollection<KV<KeyT, LeftT>> leftKeyed, PCollection<RightT> reight, PCollection<KV<KeyT, RightT>> rightKeyed) { final AccumulatorProvider accumulators = new LazyAccumulatorProvider(AccumulatorProvider.of(leftKeyed.getPipeline())); final TupleTag<LeftT> leftTag = new TupleTag<>(); final TupleTag<RightT> rightTag = new TupleTag<>(); final JoinFn<LeftT, RightT, KeyT, OutputT> joinFn = getJoinFn(operator, leftTag, rightTag, accumulators); return KeyedPCollectionTuple.of(leftTag, leftKeyed) .and(rightTag, rightKeyed) .apply("co-group-by-key", CoGroupByKey.create()) .apply(joinFn.getFnName(), ParDo.of(joinFn)); } }
35.86692
98
0.669882
e8dc9670946887605d110d81baad2f4473642f59
176
package core.ppu; /** * Represent the possible mirroring mode */ public enum Mirror { HARDWARE, HORIZONTAL, VERTICAL, ONE_SCREEN_LOW, ONE_SCREEN_HIGH, }
13.538462
40
0.670455
4f71fd9f0e5f05a0f62e0fbedc8d73e33f397caf
12,802
/* * RDFpro - An extensible tool for building stream-oriented RDF processing libraries. * * Written in 2014 by Francesco Corcoglioniti with support by Marco Amadori, Michele Mostarda, * Alessio Palmero Aprosio and Marco Rospocher. Contact info on http://rdfpro.fbk.eu/ * * To the extent possible under law, the authors have dedicated all copyright and related and * neighboring rights to this software to the public domain worldwide. This software is * distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along with this software. * If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ package eu.fbk.rdfpro.tool; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import javax.annotation.Nullable; import org.slf4j.Logger; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.UnsynchronizedAppenderBase; import ch.qos.logback.core.encoder.Encoder; import ch.qos.logback.core.pattern.CompositeConverter; import ch.qos.logback.core.pattern.color.ANSIConstants; import ch.qos.logback.core.spi.DeferredProcessingAware; import ch.qos.logback.core.status.ErrorStatus; public final class Logging { private static final boolean ANSI_ENABLED = "true".equalsIgnoreCase(System .getenv("RDFPRO_ANSI_ENABLED")); private static final String SET_DEFAULT_COLOR = ANSIConstants.ESC_START + "0;" + ANSIConstants.DEFAULT_FG + ANSIConstants.ESC_END; private static String format(final String text, @Nullable final String ansiCode) { if (ansiCode == null) { return text; } else { final StringBuilder builder = new StringBuilder(text.length() + 16); builder.append(ANSIConstants.ESC_START); builder.append(ansiCode); builder.append(ANSIConstants.ESC_END); builder.append(text); builder.append(SET_DEFAULT_COLOR); return builder.toString(); } } public static void setLevel(final Logger logger, final String level) { final Level l = Level.valueOf(level); ((ch.qos.logback.classic.Logger) logger).setLevel(l); } public static final class NormalConverter extends CompositeConverter<ILoggingEvent> { @Override protected String transform(final ILoggingEvent event, final String in) { if (ANSI_ENABLED) { final int levelCode = event.getLevel().toInt(); if (levelCode == ch.qos.logback.classic.Level.ERROR_INT) { return format(in, ANSIConstants.RED_FG); } else if (levelCode == ch.qos.logback.classic.Level.WARN_INT) { return format(in, ANSIConstants.MAGENTA_FG); } } return format(in, null); } } public static final class BoldConverter extends CompositeConverter<ILoggingEvent> { @Override protected String transform(final ILoggingEvent event, final String in) { if (ANSI_ENABLED) { final int levelCode = event.getLevel().toInt(); if (levelCode == ch.qos.logback.classic.Level.ERROR_INT) { return format(in, ANSIConstants.BOLD + ANSIConstants.RED_FG); } else if (levelCode == ch.qos.logback.classic.Level.WARN_INT) { return format(in, ANSIConstants.BOLD + ANSIConstants.MAGENTA_FG); } else { return format(in, ANSIConstants.BOLD + ANSIConstants.DEFAULT_FG); } } return format(in, null); } } public static final class StatusAppender<E> extends UnsynchronizedAppenderBase<E> { private static final int MAX_STATUS_LENGTH = 256; private Encoder<E> encoder; public synchronized Encoder<E> getEncoder() { return this.encoder; } public synchronized void setEncoder(final Encoder<E> encoder) { if (isStarted()) { addStatus(new ErrorStatus("Cannot configure appender named \"" + this.name + "\" after it has been started.", this)); } this.encoder = encoder; } @Override public synchronized void start() { // Abort if already started if (this.started) { return; } // Abort with error if there is no encoder attached to the appender if (this.encoder == null) { addStatus(new ErrorStatus("No encoder set for the appender named \"" + this.name + "\".", this)); return; } // Abort if there is no console attached to the process or cannot enable on Windows if (System.console() == null || !ANSI_ENABLED) { return; } // Setup streams required for generating and displaying status information final PrintStream out = System.out; final StatusAcceptorStream acceptor = new StatusAcceptorStream(out); final OutputStream generator = new StatusGeneratorStream(acceptor); try { // Setup encoder. On success, replace System.out and start the appender this.encoder.init(generator); System.setOut(new PrintStream(acceptor)); super.start(); } catch (final IOException ex) { addStatus(new ErrorStatus("Failed to initialize encoder for appender named \"" + this.name + "\".", this, ex)); } } @Override public synchronized void stop() { if (!isStarted()) { return; } try { this.encoder.close(); // no need to restore System.out (due to buffering, better not to do that) } catch (final IOException ex) { addStatus(new ErrorStatus("Failed to write footer for appender named \"" + this.name + "\".", this, ex)); } finally { super.stop(); } } @Override protected synchronized void append(final E event) { if (!isStarted()) { return; } try { if (event instanceof DeferredProcessingAware) { ((DeferredProcessingAware) event).prepareForDeferredProcessing(); } this.encoder.doEncode(event); } catch (final IOException ex) { stop(); addStatus(new ErrorStatus("IO failure in appender named \"" + this.name + "\".", this, ex)); } } private static final class StatusAcceptorStream extends FilterOutputStream { private static final int ESC = 27; private byte[] status; private boolean statusEnabled; public StatusAcceptorStream(final OutputStream stream) { super(stream); this.status = null; this.statusEnabled = true; } @Override public synchronized void write(final int b) throws IOException { enableStatus(false); this.out.write(b); enableStatus(b == '\n'); } @Override public synchronized void write(final byte[] b) throws IOException { enableStatus(false); super.write(b); enableStatus(b[b.length - 1] == '\n'); } @Override public synchronized void write(final byte[] b, final int off, final int len) throws IOException { enableStatus(false); super.write(b, off, len); enableStatus(len > 0 && b[off + len - 1] == '\n'); } synchronized void setStatus(final byte[] status) { final boolean oldEnabled = this.statusEnabled; enableStatus(false); this.status = status; enableStatus(oldEnabled); } private void enableStatus(final boolean enabled) { try { if (enabled == this.statusEnabled) { return; } this.statusEnabled = enabled; if (this.status == null) { return; } else if (enabled) { final int length = Math.min(this.status.length, MAX_STATUS_LENGTH); this.out.write(this.status, 0, length); this.out.write('\n'); // move cursor out of the way and cause flush } else { final int length = Math.min(this.status.length, MAX_STATUS_LENGTH); int newlines = 1; for (int i = 0; i < length; ++i) { if (this.status[i] == '\n') { ++newlines; } } // move cursor up of # lines previously written this.out.write(ESC); this.out.write('['); this.out.write(Integer.toString(newlines).getBytes()); this.out.write('A'); // we emit a newline to move cursor down one line and to column 1, then we // move up one line, being sure to end up in column 1 this.out.write('\n'); this.out.write(ESC); this.out.write('['); this.out.write('1'); this.out.write('A'); // discard everything after the cursor; due to trick above we also discard // text entered by the user (but not newline - they can be managed by // saving and restoring cursor position, but many terminals do not handle // these calls) this.out.write(ESC); this.out.write('['); this.out.write('0'); this.out.write('J'); } } catch (final Throwable ex) { if (ex instanceof Error) { throw (Error) ex; } else if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException(ex); } } } } private static final class StatusGeneratorStream extends OutputStream { private final StatusAcceptorStream stream; private final byte[] buffer; private int offset; public StatusGeneratorStream(final StatusAcceptorStream stream) { this.stream = stream; this.buffer = new byte[MAX_STATUS_LENGTH]; this.offset = 0; } @Override public void write(final int b) throws IOException { int emitCount = -1; if (b == '\n') { if (this.offset < MAX_STATUS_LENGTH) { emitCount = this.offset; } this.offset = 0; } else if (this.offset < MAX_STATUS_LENGTH) { this.buffer[this.offset++] = (byte) b; if (this.offset == MAX_STATUS_LENGTH) { emitCount = this.offset; } } if (emitCount >= 0) { final byte[] status = new byte[emitCount]; System.arraycopy(this.buffer, 0, status, 0, emitCount); this.stream.setStatus(status); } } @Override public void write(final byte[] b) throws IOException { for (int i = 0; i < b.length; ++i) { write(b[i]); } } @Override public void write(final byte[] b, final int off, final int len) throws IOException { final int to = off + len; for (int i = off; i < to; ++i) { write(b[i]); } } } } }
38.10119
98
0.519684
a63cbe6c440be24b34f589577bc4f87615d39177
1,426
package com.alexsnowm.grocerycomparer.models.forms; import com.alexsnowm.grocerycomparer.models.ItemMeasure; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.Digits; import java.math.BigDecimal; public class CreateItemForm { @NotBlank(message = "Name required") private String itemName; @Digits(integer = 6, fraction = 2, message = "Enter number to no more than 2 decimal places") private BigDecimal priceNumber; private ItemMeasure measure; private String priceAisle; private String itemNotes; public CreateItemForm() { } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public BigDecimal getPriceNumber() { return priceNumber; } public void setPriceNumber(BigDecimal priceNumber) { this.priceNumber = priceNumber; } public ItemMeasure getMeasure() { return measure; } public void setMeasure(ItemMeasure measure) { this.measure = measure; } public String getPriceAisle() { return priceAisle; } public void setPriceAisle(String priceAisle) { this.priceAisle = priceAisle; } public String getItemNotes() { return itemNotes; } public void setItemNotes(String itemNotes) { this.itemNotes = itemNotes; } }
22.28125
97
0.679523
fbffaa0d275724e52cabef0f95af574fbb52bad8
927
public abstract class BD extends Livre { // dessinateur de la BD private String dessinateur; /** * Constructeur de BD qui initialise l'attribut dessinateur * et les attributs titre et auteur grâce à l'appel de super, * les instances de BD sont donc aussi dotées de l'identifiant * unique "numero" * * @param titre titre de la BD * @param scenariste auteur de la BD * @param dess dessinateur de la BD **/ public BD(String titre, String scenariste, String dess) { super(titre,scenariste); dessinateur = dess; } /** * Méthode permettant de retourner le dessinateur d'une BD * * @return dessinateur de la BD **/ public String getDessinateur() { return dessinateur; } /** * Méthode permettant de renvoyer une chaine de caractère * permettant l'affichage d'un objet BD * * @return chaine permettant l'affichage **/ public String toString() { return(super.toString()+";"+dessinateur); } }
22.609756
63
0.707659
2bc5ecf19d4511ccb84c97403edfe21b55a6f2ca
303
package com.tonghoangvu.lhufriendsbackend.common; import lombok.Getter; import org.jetbrains.annotations.Contract; @Getter public enum Const { MAX_STUDENTS_PER_REQUEST(100); private final int intValue; @Contract(pure = true) Const(int value) { this.intValue = value; } }
17.823529
49
0.712871
73c21345677cc474beff179d01e904f010bc0b0a
4,159
/** */ package Gtm.impl; import Gtm.GtmPackage; import Gtm.LegacySeparateContractSeries; import Gtm.LegacySeparateContractSeriesList; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Legacy Separate Contract Series List</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link Gtm.impl.LegacySeparateContractSeriesListImpl#getSeparateContractSeries <em>Separate Contract Series</em>}</li> * </ul> * * @generated */ public class LegacySeparateContractSeriesListImpl extends MinimalEObjectImpl.Container implements LegacySeparateContractSeriesList { /** * The cached value of the '{@link #getSeparateContractSeries() <em>Separate Contract Series</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSeparateContractSeries() * @generated * @ordered */ protected EList<LegacySeparateContractSeries> separateContractSeries; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected LegacySeparateContractSeriesListImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return GtmPackage.Literals.LEGACY_SEPARATE_CONTRACT_SERIES_LIST; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<LegacySeparateContractSeries> getSeparateContractSeries() { if (separateContractSeries == null) { separateContractSeries = new EObjectContainmentEList<LegacySeparateContractSeries>(LegacySeparateContractSeries.class, this, GtmPackage.LEGACY_SEPARATE_CONTRACT_SERIES_LIST__SEPARATE_CONTRACT_SERIES); } return separateContractSeries; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case GtmPackage.LEGACY_SEPARATE_CONTRACT_SERIES_LIST__SEPARATE_CONTRACT_SERIES: return ((InternalEList<?>)getSeparateContractSeries()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case GtmPackage.LEGACY_SEPARATE_CONTRACT_SERIES_LIST__SEPARATE_CONTRACT_SERIES: return getSeparateContractSeries(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case GtmPackage.LEGACY_SEPARATE_CONTRACT_SERIES_LIST__SEPARATE_CONTRACT_SERIES: getSeparateContractSeries().clear(); getSeparateContractSeries().addAll((Collection<? extends LegacySeparateContractSeries>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case GtmPackage.LEGACY_SEPARATE_CONTRACT_SERIES_LIST__SEPARATE_CONTRACT_SERIES: getSeparateContractSeries().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case GtmPackage.LEGACY_SEPARATE_CONTRACT_SERIES_LIST__SEPARATE_CONTRACT_SERIES: return separateContractSeries != null && !separateContractSeries.isEmpty(); } return super.eIsSet(featureID); } } //LegacySeparateContractSeriesListImpl
27.183007
203
0.719644
f4ba0aef419311188250a0ea21e58a7a0ffaf323
311
package im.turms.turms.pojo.dto; import lombok.Data; import java.util.Date; @Data public class UpdateGroupDTO { Date muteEndDate; String name; String url; String intro; String announcement; Integer minimumScore; Long typeId; Long successorId; Boolean quitAfterTransfer; }
16.368421
32
0.707395
dd1445f7de9bc773c1690cda916496b33faf0f12
1,068
package repository; import io.ebean.PagedList; import io.ebean.ExpressionList; import java.util.Map; import java.util.List; import javax.inject.Inject; import models.ConductaDetalle; import play.db.ebean.EbeanConfig; public class ConductaDetalleRepository extends BaseRepository{ private static final String FIELD = "conducta"; @Inject public ConductaDetalleRepository(EbeanConfig ebeanConfig) { super(ebeanConfig, ConductaDetalle.class); } public PagedList<ConductaDetalle> page(int page, int pageSize, String sortBy, String order, String filter) { String[] fields = {FIELD}; return super.page(page, pageSize, sortBy, order, filter, fields); } public Map<String, String> options() { ExpressionList<ConductaDetalle> exp = super.getEbeanServer().find(ConductaDetalle.class).where(); exp.orderBy(FIELD); return super.options(exp, "id", FIELD); } public List<ConductaDetalle> list() { return super.list(super.getEbeanServer().find(ConductaDetalle.class).where()); } }
31.411765
112
0.716292
03ae4ef26d54e0a7b56b2889abde7f16c94a105b
1,232
package com.ctrip.framework.apollo.demo.spring.xmlConfigDemo.refresh; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.demo.spring.xmlConfigDemo.bean.XmlBean; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import com.ctrip.framework.apollo.spring.annotation.ApolloConfig; import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; /** * @author Jason Song([email protected]) */ public class ManualRefreshUtil { private static final Logger logger = LoggerFactory.getLogger(ManualRefreshUtil.class); @ApolloConfig private Config config; @Autowired private XmlBean xmlBean; @ApolloConfigChangeListener private void onChange(ConfigChangeEvent changeEvent) { if (changeEvent.isChanged("timeout")) { logger.info("Manually refreshing xmlBean.timeout"); xmlBean.setTimeout(config.getIntProperty("timeout", xmlBean.getTimeout())); } if (changeEvent.isChanged("batch")) { logger.info("Manually refreshing xmlBean.batch"); xmlBean.setBatch(config.getIntProperty("batch", xmlBean.getBatch())); } } }
32.421053
88
0.777597
f0b97d02cd7022eaf831c3e51246eb881ff72a29
782
package com.tiecode.platform.jstub.util; /** * bundle key constants * @author Scave */ public interface BundleKey { /** * help */ String help_head = "help_head"; String usage = "help_usage"; String help_options_head = "help_options_head"; String help_out = "help_out"; String help_level = "help_level"; String help_level0 = "help_level0"; String help_level1 = "help_level1"; String help_level2 = "help_level2"; String help_command = "help_command"; /** * errors */ String no_error = "no_error"; String file_error = "file_error"; String out_error = "out_error"; String out_must_error = "out_must_error"; String level_error = "level_error"; String level_param_error = "level_param_error"; }
25.225806
51
0.662404
f1cd921525db630ba2ccc79a31ca3937545accd2
40,436
/* * Copyright 2021 AT&T * * 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.att.aro.ui.view.menu.file; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Optional; import java.util.ResourceBundle; import java.util.TreeMap; import javax.swing.BorderFactory; import javax.swing.BoundedRangeModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.jfree.ui.tabbedui.VerticalLayout; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.util.CollectionUtils; import com.att.aro.core.AROConfig; import com.att.aro.core.commandline.IExternalProcessRunner; import com.att.aro.core.commandline.impl.ExternalProcessRunnerImpl; import com.att.aro.core.fileio.IFileManager; import com.att.aro.core.fileio.impl.FileManagerImpl; import com.att.aro.core.packetanalysis.pojo.TimeRange; import com.att.aro.core.packetanalysis.pojo.TimeRange.TimeRangeType; import com.att.aro.core.peripheral.ITimeRangeReadWrite; import com.att.aro.core.peripheral.impl.TimeRangeReadWrite; import com.att.aro.core.peripheral.pojo.TraceTimeRange; import com.att.aro.core.util.StringParse; import com.att.aro.core.util.Util; import com.att.aro.core.video.pojo.Orientation; import com.att.aro.core.videoanalysis.videoframe.FrameReceiver; import com.att.aro.core.videoanalysis.videoframe.FrameRequest; import com.att.aro.core.videoanalysis.videoframe.FrameRequest.JobType; import com.att.aro.core.videoanalysis.videoframe.FrameStatus; import com.att.aro.core.videoanalysis.videoframe.VideoFrameExtractor; import com.att.aro.ui.commonui.ImagePanel; import com.att.aro.ui.utils.ResourceBundleHelper; import lombok.Getter; import lombok.Setter; public class TimeRangeEditorDialog extends JDialog implements FrameReceiver{ private static final Logger LOG = LogManager.getLogger(TimeRangeEditorDialog.class.getName()); private static final long serialVersionUID = 1L; private static final ResourceBundle resourceBundle = ResourceBundleHelper.getDefaultBundle(); private int frameImagePanelPanelLandscape = 380; private int frameImagePanelPanelPortrait = 240; private static final int SLIDER_SENSITIVITY = 25; private ApplicationContext context = new AnnotationConfigApplicationContext(AROConfig.class); private IFileManager fileManager = context.getBean(FileManagerImpl.class); private VideoFrameExtractor videoFrameExtractor = context.getBean("videoFrameExtractor", VideoFrameExtractor.class); private ITimeRangeReadWrite timeRangeReadWrite = context.getBean("timeRangeReadWrite", TimeRangeReadWrite.class); private IExternalProcessRunner externalProcessRunner = context.getBean(ExternalProcessRunnerImpl.class); private File traceFolder; @Getter private TraceTimeRange traceTimeRange; @Getter private TimeRange timeRange; private double deviceVideoDuration; private double initialDeviceVideoOffset; @Getter @Setter private Dimension deviceScreenDimension; private int deviceVideoWidth; private int deviceVideoHeight; private Orientation deviceOrientation; private double deviceVideoRatio; private int fWidth; private int fHeight; private double extractedFPS = 30; private Double deviceVideoNbFrames; private TreeMap<Double, BufferedImage> frameMap = new TreeMap<>(); private FrameImagePanel startImagePanel; private FrameImagePanel endImagePanel; private JTextField configNameField = new JTextField(); private JComboBox<TimeRangeType> autoLaunchComboBox = new JComboBox<TimeRangeType>(); private JTextField startAnalysisTextField = new JTextField(); private JTextField endAnalysisTextField = new JTextField(); private JSlider startSlider = new JSlider(); private JSlider endSlider = new JSlider(); private JPanel editorJPanel; private JPanel chooserJPanel; private Dimension editorDimension; private Dimension chooserDimension; @Getter @Setter private boolean continueWithAnalyze = false; private JPanel editButtonPanel; private int dialogHeight; private int dialogWidth; private JDialog splash; private JTextField sliderAlert; private FontRenderContext frc; private double getStartAnalysis() { return StringParse.stringToDouble(startAnalysisTextField.getText(), 0); } private double getEndAnalysis() { return StringParse.stringToDouble(endAnalysisTextField.getText(), 0); } public TimeRangeEditorDialog(File traceFolder, boolean analyzeOnExit, JDialog splash) throws Exception { LOG.debug("TimeRangeDialog :" + traceFolder.toString()); this.splash = splash; this.traceFolder = traceFolder; autoLaunchComboBox.addItem(TimeRangeType.DEFAULT); autoLaunchComboBox.addItem(TimeRangeType.MANUAL); autoLaunchComboBox.getSize(); autoLaunchComboBox.setPreferredSize(new Dimension(getStringFontWidth(autoLaunchComboBox.getFont(), TimeRangeType.DEFAULT.toString()), autoLaunchComboBox.getSize().height)); autoLaunchComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TimeRange originalDefault; if (TimeRangeType.DEFAULT.equals(autoLaunchComboBox.getSelectedItem()) && (originalDefault = locateEntryWithAutoLaunch()) != null) { // the actual swap of DEFAULT will happen in saveTraceTimeRange() LOG.debug(String.format("%s will be changed from DEFAULT to MANUAL", originalDefault.toString())); } } }); setContinueWithAnalyze(analyzeOnExit); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { destroy(); super.windowClosing(e); } }); initialize(); editorDimension = calculateEditorDimension(); pack(); setResizable(true); Runnable doMore = () -> { try { doMore(); } catch (Exception e1) { LOG.error(e1); } }; new Thread(doMore,"doTheRest").start(); } public Dimension calculateEditorDimension() { //determine size for the editor Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int minLandscapeH = 438; int minLandscapeW = 893; int minPortraitH = 585; int minPortraitW = 893; if (Util.isWindowsOS()) { minLandscapeH = 430; minLandscapeW = 831; minPortraitH = 573; minPortraitW = 813; } else if (Util.isMacOS()) { minLandscapeH = 398; minLandscapeW = 815; minPortraitH = 539; minPortraitW = 751; } if (deviceOrientation == Orientation.LANDSCAPE) { // max based on screen size dialogHeight = (int) (screenSize.height / 3.000); dialogWidth = (int) (dialogHeight * 2.065); // enforce a minimum size dialogHeight = dialogHeight < minLandscapeH ? minLandscapeH : dialogHeight; dialogWidth = dialogWidth < minLandscapeW ? minLandscapeW : dialogWidth; } else { // max based on screen size dialogHeight = (int) (screenSize.height / 2.330); dialogWidth = (int) (dialogHeight * 1.398); // enforce a minimum size dialogHeight = dialogHeight < minPortraitH ? minPortraitH : dialogHeight; dialogWidth = dialogWidth < minPortraitW ? minPortraitW : dialogWidth; } LOG.debug(deviceOrientation); LOG.debug("Computer Screen Size:" + screenSize); return new Dimension(dialogWidth, dialogHeight); } public void doMore() throws Exception { setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); if ((traceTimeRange = loadTraceTimeRange()) != null) { chooser(false); chooserDimension = getSize(); } else { createEntry(); editorDimension = new Dimension(getSize()); } if (splash != null) { splash.dispose(); splash = null; } } private void chooser(Boolean needUpdate) { setTitle("Time Range Chooser"); if (needUpdate) { chooserJPanel = null; } if (editorJPanel != null && editorJPanel.isVisible()) { editorJPanel.setVisible(false); } if (chooserJPanel == null) { add(chooserJPanel = createChooserDialog()); chooserJPanel.setSize(new Dimension(830, Util.getAdjustedHeight(386))); chooserDimension = chooserJPanel.getSize(); } chooserJPanel.setVisible(true); setPreferredSize(chooserDimension); pack(); } void createEntry() { configNameField.setText(""); autoLaunchComboBox.setSelectedItem(TimeRangeType.MANUAL); setTitle("Time Range Setup"); if (editorJPanel == null) { add(editorJPanel = createEditorDialog()); } if (editorDimension != null) { setPreferredSize(editorDimension); } editorJPanel.setVisible(true); pack(); } public void edit(TimeRange timeRange) { if (chooserJPanel != null && chooserJPanel.isVisible()) { chooserJPanel.setVisible(false); } setTitle("Time Range Editor"); if (editorJPanel == null) { add(editorJPanel = createEditorDialog()); } loadFields(timeRange); if (editorDimension != null) { setPreferredSize(editorDimension); } editorJPanel.setVisible(true); pack(); startSlider.setValue((int) (getStartAnalysis() * SLIDER_SENSITIVITY)); endSlider.setValue((int) (getEndAnalysis() * SLIDER_SENSITIVITY)); } public void cancel() { timeRange = null; setContinueWithAnalyze(false); } public void delete(TimeRange timeRange) { if (traceTimeRange != null && !CollectionUtils.isEmpty(traceTimeRange.getTimeRangeList())) { traceTimeRange.getTimeRangeList().remove(timeRange); try { timeRangeReadWrite.save(traceFolder, traceTimeRange); } catch (Exception e) { LOG.error("Failed to save time-range.json, ", e); } } if (traceTimeRange == null || traceTimeRange.getTimeRangeList().isEmpty()) { createEntry(); } else { chooser(true); } } private JPanel createChooserDialog() { JPanel chooserPanel = new TimeRangeChooser(this, traceTimeRange); return chooserPanel; } // dialog private JPanel createEditorDialog() { if (editorJPanel == null) { editorJPanel = new JPanel(); editorJPanel.setLayout(new VerticalLayout()); editorJPanel.add(createContentPanel()); } editorJPanel.setVisible(true); return editorJPanel; } private Component createContentPanel() { JPanel contentPane = new JPanel(new VerticalLayout()); contentPane.add(getFrameViews()); contentPane.add(buildConfigGroup()); contentPane.add(createEditButtonPane()); return contentPane; } /** * Count entries set to TimeRangeType.DEFAULT * * @return count */ protected long countEntriesWithAutoLaunch(String excludeItem) { if (traceTimeRange == null || configNameField == null || configNameField.getText() == null) { return 0; } return traceTimeRange.getTimeRangeList().stream() .filter(a -> a.getTimeRangeType().equals(TimeRangeType.DEFAULT)) .filter(p -> !p.getTitle().equals(excludeItem)) .count(); } protected TimeRange locateEntryWithAutoLaunch() { if (traceTimeRange == null || configNameField == null || configNameField.getText() == null) { return null; } Optional<TimeRange> foundEntry = traceTimeRange.getTimeRangeList().stream() .filter(a -> a.getTimeRangeType().equals(TimeRangeType.DEFAULT)) .filter(p -> !p.getTitle().equals(configNameField.getText())) .findFirst(); return foundEntry.isPresent() ? foundEntry.get() : null; } private boolean collisionTest(String title) { if (traceTimeRange == null) { return false; } return traceTimeRange.getTimeRangeList().stream() .filter(p -> p.getTitle().equals(title)).findFirst().isPresent(); } private TimeRange locateTimeRange(String title) { if (traceTimeRange != null && !CollectionUtils.isEmpty(traceTimeRange.getTimeRangeList())) { Optional<TimeRange> trSection = traceTimeRange.getTimeRangeList().stream() .filter(p -> p.getTitle().equals(configNameField.getText())).findFirst(); if (trSection.isPresent()) { return trSection.get(); } } return null; } private TraceTimeRange loadTraceTimeRange() { return timeRangeReadWrite.readData(traceFolder); } private void loadFields(TimeRange timeRange) { configNameField .setText(timeRange.getTitle()); startAnalysisTextField .setText(String.format("% 8.03f", timeRange.getBeginTime())); endAnalysisTextField .setText(String.format("% 8.03f", timeRange.getEndTime())); autoLaunchComboBox .setSelectedItem(timeRange.getTimeRangeType()); } private TimeRange saveTraceTimeRange() { if (traceTimeRange == null) { traceTimeRange = new TraceTimeRange(); } if (traceTimeRange.getTimeRangeList().isEmpty()) { timeRange = new TimeRange("FULL", TimeRangeType.DEFAULT, 0, deviceVideoDuration); traceTimeRange.getTimeRangeList().add(timeRange); } LOG.debug("Save trace range: " + traceTimeRange); TimeRange timeRange = null; if (autoLaunchComboBox.getSelectedItem().equals(TimeRangeType.DEFAULT)) { TimeRange prevDefaultTimeRange = locateEntryWithAutoLaunch(); if (prevDefaultTimeRange!=null && !prevDefaultTimeRange.getTitle().equals(configNameField.getText())) { prevDefaultTimeRange.setTimeRangeType(TimeRangeType.MANUAL); } } try { timeRange = locateTimeRange(configNameField.getText()); if (timeRange == null) { timeRange = new TimeRange(); traceTimeRange.getTimeRangeList().add(timeRange); } timeRange = loadTimeRange(timeRange); timeRangeReadWrite.save(traceFolder, traceTimeRange); } catch (Exception e) { LOG.error("Failed to save TimeRange data:", e); } return timeRange; } private TimeRange loadTimeRange(TimeRange timeRange) { if (timeRange == null) { timeRange = new TimeRange(); } timeRange.setTitle(configNameField.getText()); timeRange.setBeginTime(Double.valueOf(startAnalysisTextField.getText())); timeRange.setEndTime(Double.valueOf(endAnalysisTextField.getText())); timeRange.setTimeRangeType((TimeRangeType) autoLaunchComboBox.getSelectedItem()); return timeRange; } private boolean validateInput() { return (!StringUtils.isEmpty(configNameField.getText()) && !StringUtils.isEmpty(startAnalysisTextField.getText()) && !StringUtils.isEmpty(endAnalysisTextField.getText()) && autoLaunchComboBox.getSelectedItem() != null && validateTimeSpan() > 0); } private double validateTimeSpan() { TimeRange temp = null; temp = loadTimeRange(temp); return (temp.getEndTime() - temp.getBeginTime()); } // actions protected void analyze(TimeRange timeRangeObj) { if (timeRangeObj == null || !StringUtils.isEmpty(timeRangeObj.getTitle())) { this.timeRange = timeRangeObj; } else if (StringUtils.isEmpty(timeRangeObj.getTitle())) { timeRangeObj.setTitle("Manual"); this.timeRange = timeRangeObj; } LOG.debug("analyze " + timeRangeObj); setContinueWithAnalyze(true); } // top of Dialog private Component getFrameViews() { JPanel framePanel = new JPanel(new FlowLayout()); Image image = (new ImageIcon(getClass().getResource(ResourceBundleHelper.getImageString("ImageBasePath") + ResourceBundleHelper.getImageString("Image.blackScreen")))) .getImage(); startImagePanel = new FrameImagePanel(image, deviceOrientation); endImagePanel = new FrameImagePanel(image, deviceOrientation); framePanel.add(createFramePanel(startImagePanel, startAnalysisTextField, "Start analysis:", 0, startSlider)); framePanel.add(createFramePanel(endImagePanel, endAnalysisTextField, "End analysis:", deviceVideoDuration, endSlider)); startSlider.addChangeListener(createTimeRangeSliderListener(startImagePanel, startAnalysisTextField, endSlider, startSlider, true)); endSlider.addChangeListener(createTimeRangeSliderListener(endImagePanel, endAnalysisTextField, startSlider, endSlider ,false)); return framePanel; } /** * Builds a Panel with * a image frame for images * and below that a Slider and time in seconds display * * FocusListener requires two JTextFields being used, one of which must be named startAnalysisTextField * * @param imagePanel * @param textField * @param textFieldLabel * @param position * @return JPanel */ private JPanel createFramePanel(FrameImagePanel imagePanel, JTextField textField, String textFieldLabel, double position, JSlider slider) { JPanel panel = new JPanel(new VerticalLayout()); imagePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JPanel tsp = new JPanel(new FlowLayout()); int max = (int) Math.ceil(deviceVideoDuration) * SLIDER_SENSITIVITY; int posIndex = (int) Math.ceil(position) * SLIDER_SENSITIVITY; tsp.add(configureSlider(slider, JSlider.HORIZONTAL, 0, max , posIndex)); tsp.add(wrapAndLabelComponent(textField, textFieldLabel, 100)); setTimeJTextField(textField, position); textField.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { Double value = StringParse.stringToDouble(textField.getText(), 0); if (textField == startAnalysisTextField) { Double endTime = getEndAnalysis(); value = value > endTime ? endTime : value; } else { Double startTime = getStartAnalysis(); value = value < startTime ? startTime : value; } setTimeJTextField(textField, value); slider.setValue((int) (value * SLIDER_SENSITIVITY)); } @Override public void focusGained(FocusEvent e) {} }); panel.add(imagePanel); panel.add(tsp); return panel; } private ChangeListener createTimeRangeSliderListener(FrameImagePanel imagePanel, JTextField timeField, JSlider sliderAssociate, JSlider thisSlider, boolean placement) { return new ChangeListener() { JSlider oSlider = sliderAssociate; boolean high = placement; @Override public void stateChanged(ChangeEvent e) { int value = ((JSlider) e.getSource()).getValue(); if (!high) { if (value < oSlider.getValue()) { setSliderAlert(oSlider.getValue()-value); } else { clearSliderAlert(); } } else { if (value > oSlider.getValue()) { setSliderAlert(value - oSlider.getValue()); } else { clearSliderAlert(); } } imagePanel.setSeconds(value); imagePanel.setImage(requestFrame(imagePanel.getSeconds())); setTimeJTextField(timeField, imagePanel.getSeconds()); timeField.revalidate(); } }; } private void clearSliderAlert() { sliderAlert.setVisible(false); sliderAlert.setText(""); } private void setSliderAlert(int secondsOfOverlap) { sliderAlert.setVisible(true); sliderAlert.setText("WARNING overlap"); this.validate(); pack(); } public void show(double timeStamp, Double key, Double priorKey, double priorGap, double frameNumber) { LOG.debug(String.format("\ntimeStamp: %.3f, key: %.3f, frameNumber: %.3f, priorKey: %.3f, priorGap: %.3f", timeStamp, key, frameNumber, priorKey, priorGap)); } private double calcFrameToSeconds(double frameNumber) { return (frameNumber / extractedFPS); } public void setTimeJTextField(JTextField timeField, double timestamp) { timeField.setText(String.format("% 8.03f", timestamp)); } /** * Configure a slider object * * @param slider * @param orientation * @param minValue * @param maxValue * @param value * @return */ public JSlider configureSlider(JSlider slider, int orientation, int minValue, int maxValue, int value) { BoundedRangeModel sliderModel = slider.getModel(); sliderModel.setMinimum(minValue); sliderModel.setMaximum(maxValue); sliderModel.setValue(value); slider.setOrientation(orientation); slider.setPaintLabels(true); slider.setPaintTicks(true); return slider; } private JPanel buildConfigGroup() { JPanel framePanel = new JPanel(new FlowLayout()); configNameField.setSize(new Dimension(200, 20)); framePanel.add(wrapAndLabelComponent((sliderAlert = new JTextField("")), "", 200)); sliderAlert.setVisible(false); sliderAlert.setDisabledTextColor(Color.RED); sliderAlert.setFont(new Font("Dialog", Font.BOLD, 14)); sliderAlert.setEditable(false); sliderAlert.setBackground(Color.LIGHT_GRAY); framePanel.add(wrapAndLabelComponent(configNameField, "Configuration name:", 200)); framePanel.add(wrapAndLabelComponent(autoLaunchComboBox, "Auto Launch:", 110)); configNameField.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { if (collisionTest(configNameField.getText())) { int actionCode = ask(); if (actionCode != 0) { configNameField.grabFocus(); } else { if (startAnalysisTextField.getText().isEmpty() && endAnalysisTextField.getText().isEmpty()) { TimeRange timeRange = locateTimeRange(configNameField.getText()); if (timeRange != null) { startAnalysisTextField.setText(timeRange.getBeginTime().toString()); endAnalysisTextField.setText(timeRange.getEndTime().toString()); autoLaunchComboBox.getModel().setSelectedItem(timeRange.getTimeRangeType()); } } } } } @Override public void focusGained(FocusEvent e) {} }); return framePanel; } private JPanel wrapAndLabelComponent(Component component, String fieldLabel, int width) { JPanel panel = new JPanel(new BorderLayout()); component.setPreferredSize(new Dimension(width, Util.getAdjustedHeight((int) component.getPreferredSize().getHeight()))); panel.add(new JLabel(fieldLabel), BorderLayout.WEST); panel.add(component, BorderLayout.EAST); return panel; } /** * 0 = Yes * 1 = No * 2 = Cancel * * @return */ protected int ask() { int answer = JOptionPane.showConfirmDialog((Component) this, "Replace " + configNameField.getText() + "?"); return answer; } protected void userErrorMessage(String message) { JOptionPane.showMessageDialog((Component) this, message); } class FrameImagePanel extends JPanel { private static final long serialVersionUID = 1L; Image image; private int imageWidth = frameImagePanelPanelLandscape; private int imageHeight = (int)(imageWidth * deviceVideoRatio); private double seconds; private Dimension dimn; private ImagePanel imagePanel; private Orientation orientation; @Override public String toString() { StringBuilder out = new StringBuilder("FrameImagePanel"); if (dimn != null) { out.append(String.format("\n Dimensions: w=%d, h=%d", dimn.width, dimn.height)); out.append(String.format("\n Orientation: %s", orientation)); out.append(String.format("\n seconds: %.0f", seconds)); } return out.toString(); } public FrameImagePanel(Image image, Orientation orientation) { configure(image, orientation); } public void configure(Image image, Orientation orientation) { this.orientation = orientation; imagePanel = new ImagePanel(image); if (orientation.equals(Orientation.LANDSCAPE)) { imageWidth = frameImagePanelPanelLandscape; imageHeight = (int) (imageWidth * deviceVideoRatio); dimn = new Dimension((int) (frameImagePanelPanelLandscape), (int) (frameImagePanelPanelLandscape * deviceVideoRatio)); } else { imageWidth = frameImagePanelPanelPortrait; imageHeight = (int) (frameImagePanelPanelPortrait * deviceVideoRatio); dimn = new Dimension((int) (frameImagePanelPanelPortrait), (int) (frameImagePanelPanelPortrait * deviceVideoRatio)); } imagePanel.setPreferredSize(dimn); imagePanel.setMinimumSize(dimn); imagePanel.setMaximumSize(dimn); imagePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); add(imagePanel); } public void setImage(BufferedImage bImage) { if (bImage != null) { if (isLandscape()) { imagePanel.setImage(bImage.getScaledInstance(imageWidth, imageHeight, Image.SCALE_DEFAULT)); } else { imagePanel.setImage(bImage.getScaledInstance((int) (dimn.height/deviceVideoRatio), (int) (dimn.height), Image.SCALE_DEFAULT)); } repaint(); } } private boolean isLandscape() { return orientation.equals(Orientation.LANDSCAPE); } public double getSeconds() { return seconds; } public void setSeconds(int value) { seconds = (double)value / SLIDER_SENSITIVITY; } public void updateFrame() { Double key = seconds >= initialDeviceVideoOffset ? ((seconds - initialDeviceVideoOffset) * extractedFPS) : 0; Double priorKey = getFloorKey(key, 0D); Double nextKey = getCeilingKey(key, -1D); Double closestKey; closestKey = (key - priorKey < nextKey - key) ? priorKey : nextKey; BufferedImage tempImage = frameMap.get(closestKey); if (tempImage != null) { setImage(tempImage); } } } /** * retrieve a frame based on seconds * deviceFrameRate * * @param videoEvent * @return */ private BufferedImage requestFrame(double timeStamp) { BufferedImage frame = null; if (!CollectionUtils.isEmpty(frameMap)) { Double key = timeStamp >= initialDeviceVideoOffset ? ((timeStamp - initialDeviceVideoOffset) * extractedFPS) : 0; Double priorKey = getFloorKey(key, 0D); Double nextKey = getCeilingKey(key, -1D); Double closeKey; double priorGap = 100; double nextGap = 100; double frameNumber = -1; if (priorKey == null || (priorGap = key - priorKey) > 10) { show(timeStamp, key, priorKey, priorGap, frameNumber); frameNumber = (key - (priorGap > 99 ? 100 : priorGap)); collectFrames(new FrameRequest(JobType.COLLECT_FRAMES, calcFrameToSeconds(frameNumber), (int) (nextGap > 100 ? 100 : nextGap), key, this)); } if (nextKey == null || (nextGap = nextKey - key) > 10) { collectFrames(new FrameRequest(JobType.COLLECT_FRAMES , timeStamp , (int) (nextGap > 100 ? 100 : nextGap) // number of frames being requested , key , this )); } priorKey = getFloorKey(key, 0D); nextKey = getCeilingKey(key, -1D); closeKey = (priorGap < nextGap) ? priorKey : nextKey; frame = frameMap.get(closeKey); } return frame; } @Override public void receiveResults(Class<?> sender, FrameStatus result) { LOG.info(String.format("%s :%s, results:%s", sender.getSimpleName(), result.isSuccess() ? "received" : "nothing", result.getAddedCount())); if (result.isSuccess() || result.getAddedCount() > 0) { if (result.getFrameRequest().getTargetFrame() != null) { // checks if need to Recover from missing frames FrameRequest frameRequest = result.getFrameRequest(); int frameOffset; if (Math.abs((frameOffset = frameRequest.getTargetFrame().intValue() - result.getFirstFrame())) > 1) { Double frameKey = Math.floor(frameRequest.getTargetFrame()); Double ceiling = frameMap.ceilingKey(Math.floor(frameRequest.getTargetFrame())); Double floor = frameMap.floorKey(Math.floor(frameRequest.getTargetFrame())); if (!frameKey.equals(ceiling) && !frameKey.equals(floor)) { frameOffset = frameRequest.getTargetFrame().intValue() - result.getFirstFrame(); frameRequest.setStartTimeStamp(result.getFrameRequest().getStartTimeStamp() - frameOffset / extractedFPS); frameRequest.setTryCount(frameRequest.getTryCount() + 1); collectFrames(frameRequest); } } } if (startImagePanel != null) { startImagePanel.updateFrame(); if (endImagePanel != null) { endImagePanel.updateFrame(); } } } else { LOG.error("failed frame request:" + result); } } /** * Get the ceiling key, with provisions for a defaultKey. the defaultKey has a magic value of -1D which causes lastKey to be sent if ceilingKey is null * * @param key * @param defaultKey * @return ceilingKey, or defaultKey or lastKey() */ public Double getCeilingKey(Double key, Double defaultKey) { Double foundKey = frameMap.ceilingKey(key); if (foundKey == null) { foundKey = defaultKey == -1D ? frameMap.lastKey() : defaultKey; } return foundKey; } public Double getFloorKey(Double key, Double defaultKey) { Double foundKey = frameMap.floorKey(key); if (foundKey == null) { return defaultKey; } return foundKey; } // button panel & ActionListener private Component createEditButtonPane() { if (editButtonPanel == null) { editButtonPanel = new JPanel(new BorderLayout()); editButtonPanel.setPreferredSize(new Dimension(Util.getAdjustedWidth(600), Util.getAdjustedHeight(40))); JPanel btnPanel = new JPanel(); btnPanel.setLayout(new FlowLayout()); // build the 'Save' JButton btnPanel.add(buildButton("Save")); btnPanel.add(buildButton("Save & Analyze")); btnPanel.add(buildButton("Analyze")); btnPanel.add(buildButton("Cancel")); btnPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); editButtonPanel.add(btnPanel, BorderLayout.EAST); } return editButtonPanel; } private JButton buildButton(String buttonName) { JButton button = new JButton(buttonName); button.setFont(new Font("Dialog", Font.BOLD, 14)); button.setPreferredSize(new Dimension(Util.getAdjustedWidth(140),Util.getAdjustedHeight(20))); button.addActionListener(createButtonListener()); return button; } public ActionListener createButtonListener() { return new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String button = e.getActionCommand(); LOG.debug("Selected: " + button); switch (button) { case "Save": editorDimension = getSize(); // Landscape [width=856,height=425], Portrait if (validateInput()) { cleanup(); saveTraceTimeRange(); chooser(false); } else { explainWhyCannotSave(); } break; case "Save & Analyze": if (validateInput()) { cleanup(); analyze(saveTraceTimeRange()); destroy(); } else { explainWhyCannotSave(); } break; case "Analyze": if (!StringUtils.isEmpty(startAnalysisTextField.getText()) && !StringUtils.isEmpty(endAnalysisTextField.getText()) && validateTimeSpan() > 0) { timeRange = loadTimeRange(null); timeRange.setTimeRangeType(TimeRangeType.MANUAL); analyze(timeRange); } else { explainWhyCannotUse(); break; } destroy(); break; case "Cancel": LOG.debug("Editor Size:" + getSize()); if (chooserJPanel != null && traceTimeRange != null && !traceTimeRange.getTimeRangeList().isEmpty()) { chooser(false); } else { cancel(); destroy(); } break; default: destroy(); break; } } }; } private void explainWhyCannotSave() { if (configNameField.getText().isEmpty()) { userErrorMessage("Invalid: cannot be saved without a name"); } explainWhyCannotUse(); } private void explainWhyCannotUse() { double validation = validateTimeSpan(); if (validation == 0) { userErrorMessage("Invalid: Time range is zero, there can be nothing to analyze"); } else if (validation < 0) { userErrorMessage("Invalid: Time range is negative, start must be before the end"); } else { userErrorMessage("Invalid settings"); } } void destroy() { cleanup(); dispose(); System.gc(); } public void cleanup() { if (videoFrameExtractor != null) { LOG.debug("shutdown videoFrameExtractor"); videoFrameExtractor.shutdown(); } } private boolean initialize() throws Exception{ if (traceFolder.exists()) { File videoFrameFolder = fileManager.createFile(traceFolder, "tempVideoFrameFolder"); fileManager.mkDir(videoFrameFolder); FileUtils.cleanDirectory(videoFrameFolder); loadVideoData(videoFrameFolder); return true; } return false; } /** * Determine width needed for a given font and string * * @param font * @param string * @return */ private int getStringFontWidth(Font font, String string) { if (frc == null) { AffineTransform affinetransform = new AffineTransform(); frc = new FontRenderContext(affinetransform, true, true); } return (int) (font.getStringBounds(string, frc).getWidth()); } /** * extract video data via ffprobe * * @param deviceVideoPath * @return ffprobe results * @throws Exception */ private String extractDeviceVideoInfo(File deviceVideoPath) throws Exception { String cmd = String.format("%s -i \"%s\" %s", Util.getFFPROBE(), deviceVideoPath, " -v quiet -show_entries stream=height,width,nb_frames,duration,codec_name"); String results = externalProcessRunner.executeCmd(cmd, true, true); results = results.replaceAll("[\n\r]", " ").replaceAll(" ", " ").replaceAll("] ", "]").replaceAll(" \\[", "\\["); if (!results.contains("STREAM")) { throw new Exception("Error executing ffprobe <" + cmd + ">" + results); } return results; } /** * <pre> * Locate the video with the longest duration, video.mov or video.mp4. * Extract duration, width & height * Calculate deviceOrientation, deviceVideoRatio * Assign frameImagePanelPanelPortrait value * * @param videoFrameFolder * @throws Exception */ private void loadVideoData(File videoFrameFolder) throws Exception { File movVideoPath = fileManager.createFile(traceFolder, resourceBundle.getString("video.videoDisplayFile")); File mp4VideoPath = fileManager.createFile(traceFolder, resourceBundle.getString("video.videoFileOnDevice")); File deviceVideoPath = null; Double durationMP4 = 0D; String resultsMP4 = null; Double durationMOV = 0D; String resultsMOV = null; if (mp4VideoPath.exists()) { resultsMP4 = extractDeviceVideoInfo(mp4VideoPath); durationMP4 = StringParse.findLabeledDoubleFromString("duration=", " ", resultsMP4); } if (movVideoPath.exists()) { resultsMOV = extractDeviceVideoInfo(movVideoPath); durationMOV = StringParse.findLabeledDoubleFromString("duration=", " ", resultsMOV); } String results; if (durationMOV - 30 > durationMP4) { results = resultsMOV; deviceVideoPath = movVideoPath; frameImagePanelPanelPortrait = 165; } else { results = resultsMP4; deviceVideoPath = mp4VideoPath; frameImagePanelPanelPortrait = 195; } if (!deviceVideoPath.exists()) { throw new Exception("No Device Video file"); } String streamSection; String fieldString = "[STREAM]"; String delimiter = "\\[/STREAM\\]"; results = results.replaceAll(fieldString + " ", fieldString).replaceAll(" " + delimiter, delimiter); while (StringUtils.isNotEmpty(streamSection = StringParse.findLabeledDataFromString(fieldString, delimiter, results))) { results = results.substring(fieldString.length() * 2 + 1 + streamSection.length()); Double height = StringParse.findLabeledDoubleFromString("height=", " ", streamSection); if (height == null) { // only video has dimensions such as height & width continue; } else { Double width = StringParse.findLabeledDoubleFromString("width=", " ", streamSection); if (width == null) { continue; } deviceVideoDuration = StringParse.findLabeledDoubleFromString("duration=", " ", streamSection); initialDeviceVideoOffset = 0; // we have a video stream deviceVideoWidth = width.intValue(); deviceVideoHeight = height.intValue(); if (height < width) { deviceOrientation = Orientation.LANDSCAPE; deviceVideoRatio = height / width; } else { deviceOrientation = Orientation.PORTRAIT; deviceVideoRatio = width / height; } deviceVideoRatio = height / width; fHeight = 853; fWidth = (int) ((double) fHeight / deviceVideoRatio); } deviceVideoNbFrames = StringParse.findLabeledDoubleFromString("nb_frames=", " ", streamSection); Double duration = StringParse.findLabeledDoubleFromString("duration=", " ", streamSection); if (duration != null) { deviceVideoDuration = duration; } } try { videoFrameExtractor.initialize(videoFrameFolder.toString(), deviceVideoPath.toString(), frameMap, fWidth, fHeight); extractedFPS = calculateFPS(30); preloadFrames(100, this); } catch (Exception e) { LOG.error("VideoFrameExtractor Exception:" + e.getMessage()); } initialDeviceVideoOffset = getTrafficTime(); LOG.info("videoDuration :" + deviceVideoDuration); LOG.info("videoOffset :" + initialDeviceVideoOffset); LOG.info(String.format("h:w = %d:%d", deviceVideoHeight, deviceVideoWidth)); LOG.info("duration:" + deviceVideoDuration); LOG.info("nb_frames:" + deviceVideoNbFrames); } private double getTrafficTime() { return (getVideoTime() - getTraceTime()) / 1000; } private double getVideoTime() { String[] timeArray; double vTime0 = 0; File timeFile = fileManager.createFile(traceFolder, "video_time"); try { timeArray = fileManager.readAllLine(timeFile.toString()); if (timeArray[0].contains(" ")) { vTime0 = StringParse.stringToDouble(StringUtils.substringBefore(timeArray[0], " "), 0) * 1000; } else { vTime0 = StringParse.stringToDouble(timeArray[0], 0) * 1000; } } catch (IOException e) { LOG.error("Failed to obtain video time.", e); } return vTime0; } private double getTraceTime() { String[] timeArray; Double time0 = 0D; File timeFile = fileManager.createFile(traceFolder, "time"); try { timeArray = fileManager.readAllLine(timeFile.toString()); time0 = StringParse.stringToDouble(timeArray[1], 0)*1000; } catch (IOException e) { LOG.error("Failed to obtain trace time.", e); } return time0; } /** * Calculate output frames per second * * @param frameMap * @return fps */ private double calculateFPS(double defaultValue) { if (deviceVideoDuration > 0) { collectFrames(new FrameRequest(FrameRequest.JobType.COLLECT_FRAMES, 0, 1, 0D, null)); collectFrames(new FrameRequest(FrameRequest.JobType.COLLECT_FRAMES, deviceVideoDuration / 2, 1, null, null)); while (frameMap.size() < 2) { try { Thread.sleep(1000); } catch (InterruptedException e) { LOG.info("Interrupted :" + e.getMessage()); } } Double frame; if ((frame = frameMap.lastEntry().getKey()) > 0) { return frame / (deviceVideoDuration / 2); } } return defaultValue; } /** * Collect frames from startTime for a given count of frames. Frames are added to a TreeMap<Double, BufferedImage> frameMap * * Note: If a startTime is calculated to retrieve a specific frame this can fail if the ffmpeg fails to extract one or more frames depending on the state of the * video file. If accuracy is important, the results should be examined, and adjustments should be made to handle missing frames. Usually this results in * pulling frames beyond the target. * * @param startTime * @param frameCount * @param resultSubscriber * to receive results */ private void collectFrames(FrameRequest frameRequest) { try { videoFrameExtractor.addJob(frameRequest); } catch (Exception e) { LOG.error("VideoFrameExtractor Exception:" + e.getMessage()); return; } } /** * Extracts 1 frame every frameSkip count. Results depend on the video. Do not depend on the frame skip to be an exact amount. * * @param frameSkip * @param frameReceiver * @throws Exception */ public void preloadFrames(int frameSkip, FrameReceiver frameReceiver) throws Exception { videoFrameExtractor.addJob(new FrameRequest(JobType.PRELOAD, 0, frameSkip, null, frameReceiver)); } }
32.768233
174
0.720398
a0fa10b69f11ecacc06941f4ce4ad128414b000b
5,694
package tk.playerforcehd.chat.config.mysql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import tk.playerforcehd.chat.annotation.type.Getter; import tk.playerforcehd.chat.annotation.type.Setter; import tk.playerforcehd.chat.exception.manager.DatabaseErrorManager; import tk.playerforcehd.chat.start.Main; public class MySQL { /** * The DatabaseErrorManager handles every exception which get thrown by the MySQL classes */ public DatabaseErrorManager databaseErrorManager; /** * The created instance of this class; */ protected static MySQL mysqlInstance; /** * The address of the MySQL Server, default is 127.0.0.1 (localhost) */ private String address; /** * The port of the MySQL Server, default is 3306 */ private String port; /** * The Database where the server saves his data */ private String database; /** * The MySQL user which is used to login, default is root */ private String user; /** * The password of the MySQL Database */ private String password; /** * The instance of the MySQL Connection, needed to communicate with the MySQL Database */ protected Connection connection; public MySQL() { mysqlInstance = this; databaseErrorManager = new DatabaseErrorManager(Main.getMainInstance()); readProperties(); } /** * Reads the server.properties file and set the connection data */ private void readProperties(){ this.address = Main.getMainInstance().getServer_properties().get("mysql_ip").toString(); this.port = Main.getMainInstance().getServer_properties().get("mysql_port").toString(); this.database = Main.getMainInstance().getServer_properties().get("mysql_database").toString(); this.user = Main.getMainInstance().getServer_properties().get("mysql_user").toString(); this.password = Main.getMainInstance().getServer_properties().get("mysql_password").toString(); } /** * Connects to the database with the given fields */ public void connect(){ if(!isConnected()){ try { Main.getMainInstance().getLogger().info("Connecting to the database..."); connection = DriverManager.getConnection("jdbc:mysql://" + address + ":" + port + "/" + database,user,password); Main.getMainInstance().getLogger().info("Succesfully Connected to the database!"); } catch (SQLException e) { Main.getMainInstance().getLogger().severe("Can't connect to the database, the server will Shutdown NOW!"); Main.getMainInstance().getLogger().severe("Read the Stacktrace to see what has went wrong!"); databaseErrorManager.throwException(e, false); } } } /** * Closing the connection to the Database if a connection is open */ public void disconnect(){ if(isConnected()){ try { Main.getMainInstance().getLogger().info("Disconnecting from the database..."); connection.close(); Main.getMainInstance().getLogger().info("Succesfully Disconnected from the database"); } catch (SQLException e) { databaseErrorManager.throwException(e, false); } } } /** * Reconnect to the server with the given Database settings */ public void reconnect(){ if(isConnected()){ try { Main.getMainInstance().getLogger().info("Reconnecting..."); if(isConnected()){ Main.getMainInstance().getLogger().info("Server is connected to a database, closing connection..."); connection.close(); Main.getMainInstance().getLogger().info("The connection has been succesfully closed!"); } Main.getMainInstance().getLogger().info("Connecting to the Database..."); connection = DriverManager.getConnection("jdbc:mysql://" + address + ":" + port + "/" + database,user,password); Main.getMainInstance().getLogger().info("Connected to the database!"); Main.getMainInstance().getLogger().info("Succesfully reconnected to the database"); } catch (SQLException e){ Main.getMainInstance().getLogger().severe("Can't connect to the database, the server will Shutdown NOW!"); Main.getMainInstance().getLogger().severe("Read the Stacktrace to see what has went wrong!"); databaseErrorManager.throwException(e, false); } } } /** * Checks if the connection stands * @return true if it is connected -> false if not */ public boolean isConnected(){ return (connection == null ? false : true); } /** * Creates a ResultSet with the given String and returns it * @param qry the querry which returns the result * @return the ResultSet of the querry Command */ @Getter public ResultSet getResult(String qry){ if(isConnected()){ try{ return connection.createStatement().executeQuery(qry); }catch(SQLException e){ e.printStackTrace(); } } return null; } @Getter public String getAddress() { return address; } @Setter public void setAddress(String address) { this.address = address; } @Getter public String getPort() { return port; } @Setter public void setPort(String port) { this.port = port; } @Getter public String getDatabase() { return database; } @Setter public void setDatabase(String database) { this.database = database; } @Getter public String getUser() { return user; } @Setter public void setUser(String user) { this.user = user; } @Getter public String getPassword() { return password; } @Setter public void setPassword(String password) { this.password = password; } @Getter public Connection getConnection() { return connection; } @Getter public static MySQL getMysqlInstance() { return mysqlInstance; } @Getter public DatabaseErrorManager getDatabaseErrorManager() { return databaseErrorManager; } }
25.881818
116
0.705479
1e0dff1f92ce8ba5f68184537f5013406823c9e3
2,826
package eu.bcvsolutions.idm.acc.sync; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Description; import org.springframework.stereotype.Component; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto; import eu.bcvsolutions.idm.core.api.event.CoreEvent.CoreEventType; import eu.bcvsolutions.idm.core.api.event.CoreEventProcessor; import eu.bcvsolutions.idm.core.api.event.DefaultEventResult; import eu.bcvsolutions.idm.core.api.event.EntityEvent; import eu.bcvsolutions.idm.core.api.event.EventResult; import eu.bcvsolutions.idm.core.api.event.processor.IdentityProcessor; import eu.bcvsolutions.idm.core.api.service.IdmAutomaticRoleAttributeService; import eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService; import eu.bcvsolutions.idm.core.model.event.IdentityEvent.IdentityEventType; /** * Processor save at the end (current) identity role after all identity event types. * The behavior is used for check start automatic role recalculation in identity synchronization. * * @author Ondrej Kopr <[email protected]> * */ @Component @Description("Temporary save identity current roles.") public class TestIdentityProcessor extends CoreEventProcessor<IdmIdentityDto> implements IdentityProcessor { private Map<String, List<IdmIdentityRoleDto>> roles = null; private boolean enabled = false; private final IdmIdentityRoleService identityRoleService; @Autowired public TestIdentityProcessor( IdmAutomaticRoleAttributeService automaticRoleAttributeService, IdmIdentityRoleService identityRoleService) { super(IdentityEventType.UPDATE, IdentityEventType.CREATE, CoreEventType.EAV_SAVE); // this.identityRoleService = identityRoleService; } @Override public EventResult<IdmIdentityDto> process(EntityEvent<IdmIdentityDto> event) { IdmIdentityDto identity = event.getContent(); // if (this.enabled) { this.addOrReplaceIdentityRoles(identity); } // return new DefaultEventResult<>(event, this); } private void addOrReplaceIdentityRoles(IdmIdentityDto identity) { if (this.roles == null) { roles = new HashMap<>(); } // List<IdmIdentityRoleDto> identityRoles = identityRoleService.findAllByIdentity(identity.getId()); roles.put(identity.getUsername(), identityRoles); } @Override public int getOrder() { // end return Integer.MAX_VALUE; } public void enable() { this.enabled = true; } public void disable() { this.roles = null; this.enabled = false; } public List<IdmIdentityRoleDto> getRolesByUsername(String username) { return this.roles.get(username); } public Map<String, List<IdmIdentityRoleDto>> getRoles() { return roles; } }
30.717391
108
0.788393
b973803f31829b4dc29092d687eca713b432206e
19,347
/* * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.mediafilter; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dspace.app.mediafilter.service.MediaFilterService; import org.dspace.authorize.service.AuthorizeService; import org.dspace.content.Bitstream; import org.dspace.content.BitstreamFormat; import org.dspace.content.Bundle; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DCDate; import org.dspace.content.Item; import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BundleService; import org.dspace.content.service.CollectionService; import org.dspace.content.service.CommunityService; import org.dspace.content.service.ItemService; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.SelfNamedPlugin; import org.dspace.eperson.Group; import org.dspace.eperson.service.GroupService; import org.dspace.services.ConfigurationService; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; /** * MediaFilterManager is the class that invokes the media/format filters over the * repository's content. A few command line flags affect the operation of the * MFM: -v verbose outputs all extracted text to STDOUT; -f force forces all * bitstreams to be processed, even if they have been before; -n noindex does not * recreate index after processing bitstreams; -i [identifier] limits processing * scope to a community, collection or item; and -m [max] limits processing to a * maximum number of items. */ public class MediaFilterServiceImpl implements MediaFilterService, InitializingBean { @Autowired(required = true) protected AuthorizeService authorizeService; @Autowired(required = true) protected BitstreamFormatService bitstreamFormatService; @Autowired(required = true) protected BitstreamService bitstreamService; @Autowired(required = true) protected BundleService bundleService; @Autowired(required = true) protected CollectionService collectionService; @Autowired(required = true) protected CommunityService communityService; @Autowired(required = true) protected GroupService groupService; @Autowired(required = true) protected ItemService itemService; @Autowired(required = true) protected ConfigurationService configurationService; protected int max2Process = Integer.MAX_VALUE; // maximum number items to process protected int processed = 0; // number items processed protected Item currentItem = null; // current item being processed protected List<FormatFilter> filterClasses = null; protected Map<String, List<String>> filterFormats = new HashMap<>(); protected List<String> skipList = null; //list of identifiers to skip during processing protected final List<String> publicFiltersClasses = new ArrayList<>(); protected boolean isVerbose = false; protected boolean isQuiet = false; protected boolean isForce = false; // default to not forced protected MediaFilterServiceImpl() { } @Override public void afterPropertiesSet() throws Exception { String[] publicPermissionFilters = configurationService .getArrayProperty("filter.org.dspace.app.mediafilter.publicPermission"); if (publicPermissionFilters != null) { for (String filter : publicPermissionFilters) { publicFiltersClasses.add(filter.trim()); } } } @Override public void applyFiltersAllItems(Context context) throws Exception { if (skipList != null) { //if a skip-list exists, we need to filter community-by-community //so we can respect what is in the skip-list List<Community> topLevelCommunities = communityService.findAllTop(context); for (Community topLevelCommunity : topLevelCommunities) { applyFiltersCommunity(context, topLevelCommunity); } } else { //otherwise, just find every item and process Iterator<Item> itemIterator = itemService.findAll(context); while (itemIterator.hasNext() && processed < max2Process) { applyFiltersItem(context, itemIterator.next()); } } } @Override public void applyFiltersCommunity(Context context, Community community) throws Exception { //only apply filters if community not in skip-list if (!inSkipList(community.getHandle())) { List<Community> subcommunities = community.getSubcommunities(); for (Community subcommunity : subcommunities) { applyFiltersCommunity(context, subcommunity); } List<Collection> collections = community.getCollections(); for (Collection collection : collections) { applyFiltersCollection(context, collection); } } } @Override public void applyFiltersCollection(Context context, Collection collection) throws Exception { //only apply filters if collection not in skip-list if (!inSkipList(collection.getHandle())) { Iterator<Item> itemIterator = itemService.findAllByCollection(context, collection); while (itemIterator.hasNext() && processed < max2Process) { applyFiltersItem(context, itemIterator.next()); } } } @Override public void applyFiltersItem(Context c, Item item) throws Exception { //only apply filters if item not in skip-list if (!inSkipList(item.getHandle())) { //cache this item in MediaFilterManager //so it can be accessed by MediaFilters as necessary currentItem = item; if (filterItem(c, item)) { // increment processed count ++processed; } // clear item objects from context cache and internal cache c.uncacheEntity(currentItem); currentItem = null; } } @Override public boolean filterItem(Context context, Item myItem) throws Exception { // get 'original' bundles List<Bundle> myBundles = itemService.getBundles(myItem, "ORIGINAL"); boolean done = false; for (Bundle myBundle : myBundles) { // now look at all of the bitstreams List<Bitstream> myBitstreams = myBundle.getBitstreams(); for (Bitstream myBitstream : myBitstreams) { done |= filterBitstream(context, myItem, myBitstream); } } return done; } @Override public boolean filterBitstream(Context context, Item myItem, Bitstream myBitstream) throws Exception { boolean filtered = false; // iterate through filter classes. A single format may be actioned // by more than one filter for (FormatFilter filterClass : filterClasses) { //List fmts = (List)filterFormats.get(filterClasses[i].getClass().getName()); String pluginName = null; //if this filter class is a SelfNamedPlugin, //its list of supported formats is different for //differently named "plugin" if (SelfNamedPlugin.class.isAssignableFrom(filterClass.getClass())) { //get plugin instance name for this media filter pluginName = ((SelfNamedPlugin) filterClass).getPluginInstanceName(); } //Get list of supported formats for the filter (and possibly named plugin) //For SelfNamedPlugins, map key is: // <class-name><separator><plugin-name> //For other MediaFilters, map key is just: // <class-name> List<String> fmts = filterFormats.get(filterClass.getClass().getName() + (pluginName != null ? FILTER_PLUGIN_SEPARATOR + pluginName : "")); if (fmts.contains(myBitstream.getFormat(context).getShortDescription())) { try { // only update item if bitstream not skipped if (processBitstream(context, myItem, myBitstream, filterClass)) { itemService.update(context, myItem); // Make sure new bitstream has a sequence // number filtered = true; } } catch (Exception e) { String handle = myItem.getHandle(); List<Bundle> bundles = myBitstream.getBundles(); long size = myBitstream.getSizeBytes(); String checksum = myBitstream.getChecksum() + " (" + myBitstream.getChecksumAlgorithm() + ")"; int assetstore = myBitstream.getStoreNumber(); // Printout helpful information to find the errored bitstream. System.out.println("ERROR filtering, skipping bitstream:\n"); System.out.println("\tItem Handle: " + handle); for (Bundle bundle : bundles) { System.out.println("\tBundle Name: " + bundle.getName()); } System.out.println("\tFile Size: " + size); System.out.println("\tChecksum: " + checksum); System.out.println("\tAsset Store: " + assetstore); System.out.println(e); e.printStackTrace(); } } else if (filterClass instanceof SelfRegisterInputFormats) { // Filter implements self registration, so check to see if it should be applied // given the formats it claims to support SelfRegisterInputFormats srif = (SelfRegisterInputFormats) filterClass; boolean applyFilter = false; // Check MIME type String[] mimeTypes = srif.getInputMIMETypes(); if (mimeTypes != null) { for (String mimeType : mimeTypes) { if (mimeType.equalsIgnoreCase(myBitstream.getFormat(context).getMIMEType())) { applyFilter = true; } } } // Check description if (!applyFilter) { String[] descriptions = srif.getInputDescriptions(); if (descriptions != null) { for (String desc : descriptions) { if (desc.equalsIgnoreCase(myBitstream.getFormat(context).getShortDescription())) { applyFilter = true; } } } } // Check extensions if (!applyFilter) { String[] extensions = srif.getInputExtensions(); if (extensions != null) { for (String ext : extensions) { List<String> formatExtensions = myBitstream.getFormat(context).getExtensions(); if (formatExtensions != null && formatExtensions.contains(ext)) { applyFilter = true; } } } } // Filter claims to handle this type of file, so attempt to apply it if (applyFilter) { try { // only update item if bitstream not skipped if (processBitstream(context, myItem, myBitstream, filterClass)) { itemService.update(context, myItem); // Make sure new bitstream has a sequence // number filtered = true; } } catch (Exception e) { System.out.println("ERROR filtering, skipping bitstream #" + myBitstream.getID() + " " + e); e.printStackTrace(); } } } } return filtered; } @Override public boolean processBitstream(Context context, Item item, Bitstream source, FormatFilter formatFilter) throws Exception { //do pre-processing of this bitstream, and if it fails, skip this bitstream! if (!formatFilter.preProcessBitstream(context, item, source, isVerbose)) { return false; } boolean overWrite = isForce; // get bitstream filename, calculate destination filename String newName = formatFilter.getFilteredName(source.getName()); // check if destination bitstream exists Bundle existingBundle = null; Bitstream existingBitstream = null; List<Bundle> bundles = itemService.getBundles(item, formatFilter.getBundleName()); if (bundles.size() > 0) { // only finds the last match (FIXME?) for (Bundle bundle : bundles) { List<Bitstream> bitstreams = bundle.getBitstreams(); for (Bitstream bitstream : bitstreams) { if (bitstream.getName().trim().equals(newName.trim())) { existingBundle = bundle; existingBitstream = bitstream; } } } } // if exists and overwrite = false, exit if (!overWrite && (existingBitstream != null)) { if (!isQuiet) { System.out.println("SKIPPED: bitstream " + source.getID() + " (item: " + item.getHandle() + ") because '" + newName + "' already exists"); } return false; } if (isVerbose) { System.out.println("PROCESSING: bitstream " + source.getID() + " (item: " + item.getHandle() + ")"); } System.out.println("File: " + newName); // start filtering of the bitstream, using try with resource to close all InputStreams properly try ( // get the source stream InputStream srcStream = bitstreamService.retrieve(context, source); // filter the source stream to produce the destination stream // this is the hard work, check for OutOfMemoryErrors at the end of the try clause. InputStream destStream = formatFilter.getDestinationStream(item, srcStream, isVerbose); ) { if (destStream == null) { if (!isQuiet) { System.out.println("SKIPPED: bitstream " + source.getID() + " (item: " + item.getHandle() + ") because filtering was unsuccessful"); } return false; } Bundle targetBundle; // bundle we're modifying if (bundles.size() < 1) { // create new bundle if needed targetBundle = bundleService.create(context, item, formatFilter.getBundleName()); } else { // take the first match as we already looked out for the correct bundle name targetBundle = bundles.get(0); } // create bitstream to store the filter result Bitstream b = bitstreamService.create(context, targetBundle, destStream); // set the name, source and description of the bitstream b.setName(context, newName); b.setSource(context, "Written by FormatFilter " + formatFilter.getClass().getName() + " on " + DCDate.getCurrent() + " (GMT)."); b.setDescription(context, formatFilter.getDescription()); // Set the format of the bitstream BitstreamFormat bf = bitstreamFormatService.findByShortDescription(context, formatFilter.getFormatString()); bitstreamService.setFormat(context, b, bf); bitstreamService.update(context, b); //Set permissions on the derivative bitstream //- First remove any existing policies authorizeService.removeAllPolicies(context, b); //- Determine if this is a public-derivative format if (publicFiltersClasses.contains(formatFilter.getClass().getSimpleName())) { //- Set derivative bitstream to be publicly accessible Group anonymous = groupService.findByName(context, Group.ANONYMOUS); authorizeService.addPolicy(context, b, Constants.READ, anonymous); } else { //- Inherit policies from the source bitstream authorizeService.inheritPolicies(context, source, b); } //do post-processing of the generated bitstream formatFilter.postProcessBitstream(context, item, b); } catch (OutOfMemoryError oome) { System.out.println("!!! OutOfMemoryError !!!"); } // fixme - set date? // we are overwriting, so remove old bitstream if (existingBitstream != null) { bundleService.removeBitstream(context, existingBundle, existingBitstream); } if (!isQuiet) { System.out.println("FILTERED: bitstream " + source.getID() + " (item: " + item.getHandle() + ") and created '" + newName + "'"); } return true; } @Override public Item getCurrentItem() { return currentItem; } @Override public boolean inSkipList(String identifier) { if (skipList != null && skipList.contains(identifier)) { if (!isQuiet) { System.out.println("SKIP-LIST: skipped bitstreams within identifier " + identifier); } return true; } else { return false; } } @Override public void setVerbose(boolean isVerbose) { this.isVerbose = isVerbose; } @Override public void setQuiet(boolean isQuiet) { this.isQuiet = isQuiet; } @Override public void setForce(boolean isForce) { this.isForce = isForce; } @Override public void setMax2Process(int max2Process) { this.max2Process = max2Process; } @Override public void setFilterClasses(List<FormatFilter> filterClasses) { this.filterClasses = filterClasses; } @Override public void setSkipList(List<String> skipList) { this.skipList = skipList; } @Override public void setFilterFormats(Map<String, List<String>> filterFormats) { this.filterFormats = filterFormats; } }
40.816456
120
0.59141
12af94e2f18c16aa415101beedabafa1f86f7d7b
5,925
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.cloud.storage; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assume.assumeThat; import com.google.api.core.ApiClock; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.conformance.storage.v1.SigningV4Test; import com.google.cloud.conformance.storage.v1.TestFile; import com.google.cloud.storage.Storage.SignUrlOption; import com.google.cloud.storage.testing.RemoteStorageHelper; import com.google.protobuf.Timestamp; import com.google.protobuf.util.JsonFormat; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class V4SigningTest { private static final String SERVICE_ACCOUNT_JSON_RESOURCE = "com/google/cloud/conformance/storage/v1/test_service_account.not-a-test.json"; private static final String TEST_DATA_JSON_RESOURCE = "com/google/cloud/conformance/storage/v1/v4_signatures.json"; private static class FakeClock implements ApiClock { private final AtomicLong currentNanoTime; public FakeClock(Timestamp timestamp) { this.currentNanoTime = new AtomicLong( TimeUnit.NANOSECONDS.convert(timestamp.getSeconds(), TimeUnit.SECONDS) + timestamp.getNanos()); } public long nanoTime() { return this.currentNanoTime.get(); } public long millisTime() { return TimeUnit.MILLISECONDS.convert(this.nanoTime(), TimeUnit.NANOSECONDS); } } @Rule public TestName testName = new TestName(); private final SigningV4Test testData; private final ServiceAccountCredentials serviceAccountCredentials; /** * @param testData The serialized test data representing the test case. * @param serviceAccountCredentials The credentials to use in this test. * @param description Not used by the test, but used by the parameterized test runner as the name * of the test. */ public V4SigningTest( SigningV4Test testData, ServiceAccountCredentials serviceAccountCredentials, @SuppressWarnings("unused") String description) { this.testData = testData; this.serviceAccountCredentials = serviceAccountCredentials; } @Test public void test() { assumeThat( "Test skipped until b/136171758 is resolved", testName.getMethodName(), is(not("test[Headers should be trimmed]"))); Storage storage = RemoteStorageHelper.create() .getOptions() .toBuilder() .setCredentials(serviceAccountCredentials) .setClock(new FakeClock(testData.getTimestamp())) .build() .getService(); BlobInfo blob = BlobInfo.newBuilder(testData.getBucket(), testData.getObject()).build(); final String signedUrl = storage .signUrl( blob, testData.getExpiration(), TimeUnit.SECONDS, SignUrlOption.httpMethod(HttpMethod.valueOf(testData.getMethod())), SignUrlOption.withExtHeaders(testData.getHeadersMap()), SignUrlOption.withV4Signature()) .toString(); assertEquals(testData.getExpectedUrl(), signedUrl); } /** * Attempt to load all of the tests and return a {@code Collection<Object[]>} representing the set * of tests. Each entry in the returned collection is the set of parameters to the constructor of * this test class. * * <p>The results of this method will then be ran by JUnit's Parameterized test runner */ @Parameters(name = "{2}") public static Collection<Object[]> testCases() throws IOException { final ClassLoader cl = Thread.currentThread().getContextClassLoader(); final InputStream credentialsStream = cl.getResourceAsStream(SERVICE_ACCOUNT_JSON_RESOURCE); assertNotNull( String.format("Unable to load service account json: %s", SERVICE_ACCOUNT_JSON_RESOURCE), credentialsStream); final InputStream dataJson = cl.getResourceAsStream(TEST_DATA_JSON_RESOURCE); assertNotNull( String.format("Unable to load test definition: %s", TEST_DATA_JSON_RESOURCE), dataJson); final ServiceAccountCredentials serviceAccountCredentials = ServiceAccountCredentials.fromStream(credentialsStream); final InputStreamReader reader = new InputStreamReader(dataJson); final TestFile.Builder testBuilder = TestFile.newBuilder(); JsonFormat.parser().merge(reader, testBuilder); final TestFile testFile = testBuilder.build(); final List<SigningV4Test> tests = testFile.getSigningV4TestsList(); final ArrayList<Object[]> data = new ArrayList<>(tests.size()); for (SigningV4Test test : tests) { data.add(new Object[] {test, serviceAccountCredentials, test.getDescription()}); } return data; } }
36.801242
100
0.726751
9d71e659b21c770db8c044a64f8bb52fcf6ab403
13,059
package de.crunc.jackson.datatype.vertx.parser; import org.junit.Test; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import static com.fasterxml.jackson.core.JsonToken.*; import static de.crunc.jackson.datatype.vertx.JsonArrayBuilder.array; import static de.crunc.jackson.datatype.vertx.JsonObjectBuilder.object; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /** * Unit test for {@link JsonObjectCursor}. * * @author Hauke Jaeger, [email protected] */ public class JsonObjectCursorTest { private JsonObjectCursor cursor; @Test public void getParentShouldReturnNullWithoutParent() { cursor = new JsonObjectCursor(object().build(), null); assertThat(cursor.getParent(), is(nullValue())); } @Test public void getParentShouldReturnParent() { AbstractTreeCursor<Object> parent = new JsonObjectCursor(object().build(), null); cursor = new JsonObjectCursor(object().build(), parent); assertThat(cursor.getParent(), is(sameInstance(parent))); } @Test public void shouldTraverseBooleanTrue() { cursor = new JsonObjectCursor(object() .put("BooleanTrue", true) .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("BooleanTrue")); assertThat((Boolean) cursor.currentElement(), is(true)); assertThat(cursor.nextToken(), is(VALUE_TRUE)); assertThat(cursor.getCurrentName(), is("BooleanTrue")); assertThat((Boolean) cursor.currentElement(), is(true)); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void shouldTraverseBooleanFalse() { cursor = new JsonObjectCursor(object() .put("BooleanFalse", false) .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("BooleanFalse")); assertThat((Boolean) cursor.currentElement(), is(false)); assertThat(cursor.nextToken(), is(VALUE_FALSE)); assertThat(cursor.getCurrentName(), is("BooleanFalse")); assertThat((Boolean) cursor.currentElement(), is(false)); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void shouldTraverseInteger() { cursor = new JsonObjectCursor(object() .put("Integer", 42) .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("Integer")); assertThat((Integer) cursor.currentElement(), is(42)); assertThat(cursor.nextToken(), is(VALUE_NUMBER_INT)); assertThat(cursor.getCurrentName(), is("Integer")); assertThat((Integer) cursor.currentElement(), is(42)); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void shouldTraverseLong() { cursor = new JsonObjectCursor(object() .put("Long", 42L) .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("Long")); assertThat((Long) cursor.currentElement(), is(42L)); assertThat(cursor.nextToken(), is(VALUE_NUMBER_INT)); assertThat(cursor.getCurrentName(), is("Long")); assertThat((Long) cursor.currentElement(), is(42L)); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void shouldTraverseFloat() { cursor = new JsonObjectCursor(object() .put("Float", 13.37f) .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("Float")); assertThat((Float) cursor.currentElement(), is(13.37f)); assertThat(cursor.nextToken(), is(VALUE_NUMBER_FLOAT)); assertThat(cursor.getCurrentName(), is("Float")); assertThat((Float) cursor.currentElement(), is(13.37f)); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void shouldTraverseDouble() { cursor = new JsonObjectCursor(object() .put("Double", 13.37) .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("Double")); assertThat((Double) cursor.currentElement(), is(13.37)); assertThat(cursor.nextToken(), is(VALUE_NUMBER_FLOAT)); assertThat(cursor.getCurrentName(), is("Double")); assertThat((Double) cursor.currentElement(), is(13.37)); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void shouldTraverseNull() { cursor = new JsonObjectCursor(object() .putNull("null") .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("null")); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(VALUE_NULL)); assertThat(cursor.getCurrentName(), is("null")); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void shouldTraverseObject() { cursor = new JsonObjectCursor(object() .put("object", object()) .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("object")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.nextToken(), is(START_OBJECT)); assertThat(cursor.getCurrentName(), is("object")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void shouldTraverseArray() { cursor = new JsonObjectCursor(object() .put("array", array()) .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("array")); assertThat(cursor.currentElement(), is(instanceOf(JsonArray.class))); assertThat(cursor.nextToken(), is(START_ARRAY)); assertThat(cursor.getCurrentName(), is("array")); assertThat(cursor.currentElement(), is(instanceOf(JsonArray.class))); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void shouldTraverseMultipleObjects() { cursor = new JsonObjectCursor(object() .put("object1", object()) .put("object2", object()) .put("object3", object()) .build(), null); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), startsWith("object")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.nextToken(), is(START_OBJECT)); assertThat(cursor.getCurrentName(), startsWith("object")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), startsWith("object")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.nextToken(), is(START_OBJECT)); assertThat(cursor.getCurrentName(), startsWith("object")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), startsWith("object")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.nextToken(), is(START_OBJECT)); assertThat(cursor.getCurrentName(), startsWith("object")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); } @Test public void currentHasChildrenShouldSucceedForNonEmptyChildObject() { cursor = new JsonObjectCursor(object() .put("childObject", object() .put("foo", "bar")) .build(), null); assertThat(cursor.currentHasChildren(), is(false)); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("childObject")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.currentHasChildren(), is(true)); assertThat(cursor.nextToken(), is(START_OBJECT)); assertThat(cursor.getCurrentName(), is("childObject")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.currentHasChildren(), is(true)); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.currentHasChildren(), is(false)); } @Test public void currentHasChildrenShouldSucceedForEmptyChildObject() { cursor = new JsonObjectCursor(object() .put("childObject", object()) .build(), null); assertThat(cursor.currentHasChildren(), is(false)); assertThat(cursor.nextToken(), is(FIELD_NAME)); assertThat(cursor.getCurrentName(), is("childObject")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.currentHasChildren(), is(false)); assertThat(cursor.nextToken(), is(START_OBJECT)); assertThat(cursor.getCurrentName(), is("childObject")); assertThat(cursor.currentElement(), is(instanceOf(JsonObject.class))); assertThat(cursor.currentHasChildren(), is(false)); assertThat(cursor.nextToken(), is(nullValue())); assertThat(cursor.getCurrentName(), is(nullValue())); assertThat(cursor.currentElement(), is(nullValue())); assertThat(cursor.currentHasChildren(), is(false)); } }
40.181538
90
0.625316
e5ab8072412bf638d06a2de4f6752e4989910bab
9,251
/* * This file is generated by jOOQ. */ package org.jease.entity.tables.records; import org.jease.entity.tables.Users; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record8; import org.jooq.Row8; import org.jooq.impl.UpdatableRecordImpl; import javax.annotation.Generated; import java.sql.Timestamp; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.11.1" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class UsersRecord extends UpdatableRecordImpl<UsersRecord> implements Record8<Integer, Integer, Integer, String, String, Integer, Timestamp, Byte> { private static final long serialVersionUID = 1507409437; /** * Setter for <code>jease.users.id</code>. */ public void setId(Integer value) { set(0, value); } /** * Getter for <code>jease.users.id</code>. */ public Integer getId() { return (Integer) get(0); } /** * Setter for <code>jease.users.name</code>. */ public void setName(Integer value) { set(1, value); } /** * Getter for <code>jease.users.name</code>. */ public Integer getName() { return (Integer) get(1); } /** * Setter for <code>jease.users.login</code>. */ public void setLogin(Integer value) { set(2, value); } /** * Getter for <code>jease.users.login</code>. */ public Integer getLogin() { return (Integer) get(2); } /** * Setter for <code>jease.users.email</code>. */ public void setEmail(String value) { set(3, value); } /** * Getter for <code>jease.users.email</code>. */ public String getEmail() { return (String) get(3); } /** * Setter for <code>jease.users.password</code>. */ public void setPassword(String value) { set(4, value); } /** * Getter for <code>jease.users.password</code>. */ public String getPassword() { return (String) get(4); } /** * Setter for <code>jease.users.roleID</code>. */ public void setRoleid(Integer value) { set(5, value); } /** * Getter for <code>jease.users.roleID</code>. */ public Integer getRoleid() { return (Integer) get(5); } /** * Setter for <code>jease.users.lastSession</code>. */ public void setLastsession(Timestamp value) { set(6, value); } /** * Getter for <code>jease.users.lastSession</code>. */ public Timestamp getLastsession() { return (Timestamp) get(6); } /** * Setter for <code>jease.users.disabled</code>. */ public void setDisabled(Byte value) { set(7, value); } /** * Getter for <code>jease.users.disabled</code>. */ public Byte getDisabled() { return (Byte) get(7); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record8 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row8<Integer, Integer, Integer, String, String, Integer, Timestamp, Byte> fieldsRow() { return (Row8) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row8<Integer, Integer, Integer, String, String, Integer, Timestamp, Byte> valuesRow() { return (Row8) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Integer> field1() { return Users.USERS.ID; } /** * {@inheritDoc} */ @Override public Field<Integer> field2() { return Users.USERS.NAME; } /** * {@inheritDoc} */ @Override public Field<Integer> field3() { return Users.USERS.LOGIN; } /** * {@inheritDoc} */ @Override public Field<String> field4() { return Users.USERS.EMAIL; } /** * {@inheritDoc} */ @Override public Field<String> field5() { return Users.USERS.PASSWORD; } /** * {@inheritDoc} */ @Override public Field<Integer> field6() { return Users.USERS.ROLEID; } /** * {@inheritDoc} */ @Override public Field<Timestamp> field7() { return Users.USERS.LASTSESSION; } /** * {@inheritDoc} */ @Override public Field<Byte> field8() { return Users.USERS.DISABLED; } /** * {@inheritDoc} */ @Override public Integer component1() { return getId(); } /** * {@inheritDoc} */ @Override public Integer component2() { return getName(); } /** * {@inheritDoc} */ @Override public Integer component3() { return getLogin(); } /** * {@inheritDoc} */ @Override public String component4() { return getEmail(); } /** * {@inheritDoc} */ @Override public String component5() { return getPassword(); } /** * {@inheritDoc} */ @Override public Integer component6() { return getRoleid(); } /** * {@inheritDoc} */ @Override public Timestamp component7() { return getLastsession(); } /** * {@inheritDoc} */ @Override public Byte component8() { return getDisabled(); } /** * {@inheritDoc} */ @Override public Integer value1() { return getId(); } /** * {@inheritDoc} */ @Override public Integer value2() { return getName(); } /** * {@inheritDoc} */ @Override public Integer value3() { return getLogin(); } /** * {@inheritDoc} */ @Override public String value4() { return getEmail(); } /** * {@inheritDoc} */ @Override public String value5() { return getPassword(); } /** * {@inheritDoc} */ @Override public Integer value6() { return getRoleid(); } /** * {@inheritDoc} */ @Override public Timestamp value7() { return getLastsession(); } /** * {@inheritDoc} */ @Override public Byte value8() { return getDisabled(); } /** * {@inheritDoc} */ @Override public UsersRecord value1(Integer value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public UsersRecord value2(Integer value) { setName(value); return this; } /** * {@inheritDoc} */ @Override public UsersRecord value3(Integer value) { setLogin(value); return this; } /** * {@inheritDoc} */ @Override public UsersRecord value4(String value) { setEmail(value); return this; } /** * {@inheritDoc} */ @Override public UsersRecord value5(String value) { setPassword(value); return this; } /** * {@inheritDoc} */ @Override public UsersRecord value6(Integer value) { setRoleid(value); return this; } /** * {@inheritDoc} */ @Override public UsersRecord value7(Timestamp value) { setLastsession(value); return this; } /** * {@inheritDoc} */ @Override public UsersRecord value8(Byte value) { setDisabled(value); return this; } /** * {@inheritDoc} */ @Override public UsersRecord values(Integer value1, Integer value2, Integer value3, String value4, String value5, Integer value6, Timestamp value7, Byte value8) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); value7(value7); value8(value8); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached UsersRecord */ public UsersRecord() { super(Users.USERS); } /** * Create a detached, initialised UsersRecord */ public UsersRecord(Integer id, Integer name, Integer login, String email, String password, Integer roleid, Timestamp lastsession, Byte disabled) { super(Users.USERS); set(0, id); set(1, name); set(2, login); set(3, email); set(4, password); set(5, roleid); set(6, lastsession); set(7, disabled); } }
19.113636
156
0.498757
6c1cb820a30665c01bab3baa2b0458a95112ffc2
4,671
/* * (c) Copyright 2021 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.dialogue.annotations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.palantir.dialogue.Deserializer; import com.palantir.dialogue.Response; import com.palantir.dialogue.TypeMarker; import java.io.Closeable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public final class ErrorHandlingDeserializerFactoryTest { @Mock private ErrorDecoder errorDecoder; @Mock private DeserializerFactory<Object> delegateDeserializerFactory; @Mock private Deserializer<Integer> integerDelegateDeserializer; @Mock private Response response; private ErrorHandlingDeserializerFactory<Object> errorHandlingDeserializerFactory; private final TypeMarker<Integer> integerTypeMarker = new TypeMarker<>() {}; @BeforeEach public void beforeEach() { errorHandlingDeserializerFactory = new ErrorHandlingDeserializerFactory<>(delegateDeserializerFactory, errorDecoder); } @AfterEach public void afterEach() { verifyNoMoreInteractions(integerDelegateDeserializer, delegateDeserializerFactory, errorDecoder, response); } @Test public void testOnErrorCallsErrorDecoder() { RuntimeException runtimeException = new RuntimeException(); when(errorDecoder.isError(response)).thenReturn(true); when(errorDecoder.decode(response)).thenReturn(runtimeException); Deserializer<Integer> integerDeserializer = expectIntegerDeserializer(); assertThatThrownBy(() -> integerDeserializer.deserialize(response)).isEqualTo(runtimeException); verify(response).close(); } @Test public void testOnSuccessCallsDeserializer() { int toReturn = 1; when(errorDecoder.isError(response)).thenReturn(false); when(integerDelegateDeserializer.deserialize(response)).thenReturn(toReturn); Deserializer<Integer> integerDeserializer = expectIntegerDeserializer(); assertThat(integerDeserializer.deserialize(response)).isEqualTo(toReturn); verify(response).close(); } interface MyCloseableType extends Closeable {} @Test public void testOnSuccessDoesNotCloseIfTypeCloseable() { TypeMarker<MyCloseableType> myCloseableTypeTypeMarker = new TypeMarker<MyCloseableType>() {}; MyCloseableType toReturn = mock(MyCloseableType.class); when(errorDecoder.isError(response)).thenReturn(false); Deserializer<MyCloseableType> myCloseableTypeDelegateDeserializer = mock(Deserializer.class); when(myCloseableTypeDelegateDeserializer.deserialize(response)).thenReturn(toReturn); Deserializer<MyCloseableType> myCloseableTypeDeserializer = expectDeserializer(myCloseableTypeTypeMarker, myCloseableTypeDelegateDeserializer); assertThat(myCloseableTypeDeserializer.deserialize(response)).isEqualTo(toReturn); verify(response, never()).close(); } private Deserializer<Integer> expectIntegerDeserializer() { when(delegateDeserializerFactory.deserializerFor(integerTypeMarker)).thenReturn(integerDelegateDeserializer); return errorHandlingDeserializerFactory.deserializerFor(integerTypeMarker); } private <T> Deserializer<T> expectDeserializer(TypeMarker<T> typeMarker, Deserializer<T> delegateDeserializer) { when(delegateDeserializerFactory.deserializerFor(typeMarker)).thenReturn(delegateDeserializer); return errorHandlingDeserializerFactory.deserializerFor(typeMarker); } }
39.584746
117
0.766859
b55007066844999becbd7b8cec484dca85bcc831
3,107
package com.ipusoft.sim.http; import android.widget.Toast; import com.ipusoft.context.AppContext; import com.ipusoft.context.IpuSoftSDK; import com.ipusoft.context.bean.SimRiskControlBean; import com.ipusoft.context.manager.PhoneManager; import com.ipusoft.http.RequestMap; import com.ipusoft.sim.component.IAlertDialog; import com.ipusoft.sim.iface.OnSimCallPhoneResultListener; import com.ipusoft.sim.iface.SimConstant; import com.ipusoft.sim.module.SimService; /** * author : GWFan * time : 5/14/21 10:18 AM * desc : */ public class SimHttp { private static final String TAG = "SimHttp"; private SimHttp() { } private static class SimHttpHolder { private static final SimHttp INSTANCE = new SimHttp(); } public static SimHttp getInstance() { return SimHttpHolder.INSTANCE; } /** * 主卡外呼风控查询,由调用者处理查询结果 */ public void callPhoneBySim(String phone, OnSimCallPhoneResultListener<SimRiskControlBean> listener) { RequestMap requestMap = RequestMap.getRequestMap(); requestMap.put("phone", phone); SimService.getInstance() .simCallPhone(requestMap, SimRiskControlBean.class, listener); } /** * SDK自动处理查询结果:受风控,Dialog提示,否则,直接外呼 * * @param phone */ public void callPhoneBySim(String phone) { RequestMap requestMap = RequestMap.getRequestMap(); requestMap.put("phone", phone); SimService.getInstance() .simCallPhone(requestMap, SimRiskControlBean.class, new OnSimCallPhoneResultListener<SimRiskControlBean>() { @Override public void onSucceed(SimRiskControlBean simRiskControlBean) { int type = simRiskControlBean.getType(); if (SimConstant.TYPE_1 == type || SimConstant.TYPE_2 == type) { showRiskControlDialog(simRiskControlBean); } else { PhoneManager.callPhoneBySim(phone, simRiskControlBean.getCallTime()); } } @Override public void onFailure(Throwable throwable) { Toast.makeText(IpuSoftSDK.getAppContext(), "查询出错", Toast.LENGTH_SHORT).show(); } }); } /** * 风控提示的Dialog * * @param simRiskControlBean */ private static void showRiskControlDialog(SimRiskControlBean simRiskControlBean) { int type = simRiskControlBean.getType(); String msg = simRiskControlBean.getMsg(); String phone = simRiskControlBean.getPhone(); IAlertDialog.getInstance(AppContext.getActivityContext()) .setMsg(msg) .setShowCancelBtn(type == 2) .setConfirmText(type == 1 ? "好的" : "") .setOnConfirmClickListener(() -> { if (type == 2) { PhoneManager.callPhoneBySim(phone, simRiskControlBean.getCallTime()); } }).show(); } }
33.771739
124
0.60412
3c50a5920e766eccad6572ebc724de67a6c22b72
960
/* * Copyright HZCW (He Zhong Chuang Wei) Technologies Co.,Ltd. 2013-2015. All rights reserved. * * */ package com.weheros.platform.infrastructure.filesystem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.weheros.platform.infrastructure.datasystem.InitializeApplicationDataAndParameters; /** * @ClassName: FileSystemAccessFactory * @Description: 构建filesystemaccess * @author Administrator * @date 2013年11月6日 下午2:59:48 */ @Component public class FileSystemAccessFactory { @Autowired InitializeApplicationDataAndParameters initialization; public IFileSystemAccess buildFileSystemAccess(){ IFileSystemAccess filesystem=null; if("local".equals(initialization.getAppconfig().getFileSystemAccess())){ filesystem=new LocalFileSystemAccess(); }else{ filesystem=new FastDFSFilesystemAccess(); } return filesystem; } }
26.666667
94
0.7625
71c484d9538fed21c8c15e9fd3321eb0ca2b2a74
17,140
package com.example.cdm.huntfun.MineActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.cdm.huntfun.R; import com.example.cdm.huntfun.pojo.Constent; import com.example.cdm.huntfun.pojo.Flage; import com.example.cdm.huntfun.pojo.Sport; import com.example.cdm.huntfun.pojo.SysOut; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; public class MySport extends AppCompatActivity implements AbsListView.OnScrollListener{ /** * 我发布的活动 */ List<Sport> sportList = new ArrayList<Sport>(); int page=1;//初始拿第一页的数据 int sign=1;//设置刷新时不触发点击事件标志 private ListView my_sport; BaseAdapter adapter; Sport sport; private RefreshableView refresh; private int lastIndex; private Button bt; private ProgressBar pg; // 设置一个最大的数据条数,超过即不再加载 Handler handler1,handler2; private RadioButton sport_back; private View jiazai; View moreView; private RelativeLayout mysport; private RelativeLayout v3; // private ProgressBar pro; private RefreshableView refreshable_view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_sport); SysOut.getInstance().addActivity(this); my_sport = ((ListView) findViewById(R.id.my_sport));//listView refresh = ((RefreshableView) findViewById(R.id.refreshable_view));//刷新控件 sport_back = ((RadioButton) findViewById(R.id.sport_back));//返回 // pro = ((ProgressBar) findViewById(R.id.pro)); refreshable_view = ((RefreshableView) findViewById(R.id.refreshable_view)); moreView = LayoutInflater.from(this).inflate(R.layout.moredata,null); bt = (Button) moreView.findViewById(R.id.bt_load);//加载更多数据 pg = (ProgressBar) moreView.findViewById(R.id.pg);//上拉加载更多数据 v3 = ((RelativeLayout) findViewById(R.id.v3)); // jiazai = LayoutInflater.from(this).inflate(R.layout.jiazai,null); // // mysport = ((RelativeLayout) findViewById(R.id.mysport)); click(); initDate();//开始加载界面数据 } private void initDate() { setadapter(); my_sport.addFooterView(moreView); my_sport.setAdapter(adapter); // Handler handler = new Handler(); // handler.postDelayed(new Runnable() { // @Override // public void run() { // // } // },2000); geconnection(page); } private void click() { //添加下拉刷新事件 my_sport.setOnScrollListener(this); sport_back.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { finish(); } }); //上拉刷新 refresh.setOnRefreshListener(new RefreshableView.PullToRefreshListener() { @Override public void onRefresh() { sign=0; refresh.postDelayed(new Runnable() { @Override public void run() { // for (int i=0;i<sportList.size();i++){ // sportList.removeAll(sportList); // } sportList.clear(); page = 1; setadapter(); geconnection(page); my_sport.setAdapter(adapter); refresh.finishRefreshing(); sign=1; } },3000); } },0); //加载更多数据 bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(),"加载数据", Toast.LENGTH_LONG).show(); pg.setVisibility(View.VISIBLE);// 将进度条可见 bt.setVisibility(View.GONE);// 按钮不可见 handler1 = new Handler(); handler1.postDelayed(new Runnable() { @Override public void run() { loadMoreDate();// 加载更多数据 bt.setVisibility(View.VISIBLE); pg.setVisibility(View.GONE); // adapter.notifyDataSetChanged(); } },2000); } }); if(sign!=0){ my_sport.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Sport sport = sportList.get(position); Gson gson = new Gson(); String gg = gson.toJson(sport); Intent intent = new Intent(MySport.this,SingleInfo.class); intent.putExtra("sport",gg); startActivity(intent); } }); } //长按点击获取item的数据 // my_sport.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { // private TextView sportId; // @Override // public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { // if (sign!=0){ // sportId = ((TextView) view.findViewById(R.id.sportId)); // // System.out.println(position+"======position"); // // final String sportid = sportId.getText().toString(); // // AlertDialog.Builder dialog = new AlertDialog.Builder(MySport.this); // // dialog.setNegativeButton("删除", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // Toast.makeText(getApplication(),"已删除",Toast.LENGTH_SHORT).show(); //// delect(sportid); // } // }); // dialog.setPositiveButton("修改", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // Sport_key.Sport sport = sportList.get(position); // // Gson gson = new Gson(); // String gg = gson.toJson(sport); // Intent intent = new Intent(MySport.this,ChangeSport.class); // intent.putExtra("sport",gg); // startActivity(intent); // // } // }); // // dialog.show(); // } // return false; // } // }); } private void delect(String sportid) { Flage.FLAG = 1; RequestParams rp = new RequestParams(Constent.URL+"huntfunService/delectCollection?sportId="+sportid+"&flag="+ Flage.FLAG); x.http().get(rp, new Callback.CacheCallback<String>() { @Override public boolean onCache(String result) { return false; } @Override public void onSuccess(String result) { sportList.clear(); page = 1; setadapter(); geconnection(page); my_sport.setAdapter(adapter); } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); } private void setadapter() { adapter = new BaseAdapter() { private Button change; private Button delect; private TextView miaoshu; private TextView money; private TextView sportId; private ImageView img; private TextView sportName; private TextView Uname; private TextView timeEnd; private TextView timeBegin; private TextView place; private TextView num; @Override public int getCount() { return sportList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view1 =View.inflate(getApplication(), R.layout.listview_sport_layout,null); Uname = ((TextView) view1.findViewById(R.id.Uname)); sportName = ((TextView) view1.findViewById(R.id.sportName)); timeEnd = ((TextView) view1.findViewById(R.id.timeEnd)); timeBegin = ((TextView) view1.findViewById(R.id.timeBegin)); place = ((TextView) view1.findViewById(R.id.place)); num = ((TextView) view1.findViewById(R.id.num)); img = ((ImageView) view1.findViewById(R.id.listview_image)); sportId = ((TextView) view1.findViewById(R.id.sportId)); money = ((TextView) view1.findViewById(R.id.money)); miaoshu = ((TextView) view1.findViewById(R.id.miaoshu)); delect = ((Button) view1.findViewById(R.id.delect)); change = ((Button) view1.findViewById(R.id.change)); final String sportid = sportId.getText().toString(); change.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Sport sport = sportList.get(position); Gson gson = new Gson(); String gg = gson.toJson(sport); Intent intent = new Intent(MySport.this,ChangeSport.class); intent.putExtra("sport",gg); startActivity(intent); } }); delect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { AlertDialog.Builder dialog = new AlertDialog.Builder(MySport.this); dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplication(),"已删除",Toast.LENGTH_SHORT).show(); sportId = ((TextView) v.findViewById(R.id.sportId)); delect(sportid); } }); dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dialog.show(); } }); final Sport sport = sportList.get(position); String imgs=sport.getImg(); x.image().bind(img,Constent.URL+"huntfunService/image/" + imgs + ""); // thread(img,imgs); try { Uname.setText("发布人:"+ URLDecoder.decode(sport.getUname(),"utf-8")); sportName.setText(URLDecoder.decode(sport.getSportName(),"utf-8")); place.setText("地点:"+URLDecoder.decode(sport.getPlace(),"utf-8")); miaoshu.setText("描述:"+URLDecoder.decode(sport.getTheme(),"utf-8")); miaoshu.setTextColor(Color.BLACK); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } sportId.setText(sport.getId()+""); timeBegin.setText("开始时间:"+sport.getTimeBegin()); timeEnd.setText("结束时间:"+sport.getTimeEnd()); num.setText("人数:"+sport.getNum()); money.setText("¥"+sport.getMoney()+""); return view1; } }; } private void loadMoreDate() { page = page+1; geconnection(page); } private void geconnection(int page) { RequestParams params = new RequestParams(Constent.URL+"huntfunService/mySport?page="+page+""); x.http().get(params, new Callback.CacheCallback<String>() { @Override public void onSuccess(String result) { Gson gson = new Gson(); Type type = new TypeToken<List<Sport>>(){}.getType(); sportList = gson.fromJson(result,type); adapter.notifyDataSetChanged(); } @Override public void onError(Throwable ex, boolean isOnCallback) { Toast.makeText(getApplicationContext(),ex.getMessage(),Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } @Override public boolean onCache(String result) { return false; } }); } private void thread(final ImageView imageView, final String imgs) { final Bitmap[] bitmap = {null}; final Bitmap[] finalBitmap = {bitmap[0]}; final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: imageView.setImageBitmap(finalBitmap[0]); break; case 2: break; } } }; new Thread() { @Override public void run() { try { URL url = new URL(Constent.URL+"huntfunService/image/" + imgs + ""); InputStream inputStream = url.openStream(); finalBitmap[0] = BitmapFactory.decodeStream(inputStream); handler.sendEmptyMessage(1); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && lastIndex == sportList.size()+1) { // Toast.makeText(getActivity(), sportList.size() + "", Toast.LENGTH_LONG).show(); Toast.makeText(getApplicationContext(),"加载数据",Toast.LENGTH_LONG).show(); // 当滑到底部时自动加载 pg.setVisibility(View.VISIBLE); bt.setVisibility(View.GONE); handler2 = new Handler(); handler2.postDelayed(new Runnable() { @Override public void run() { loadMoreDate(); bt.setVisibility(View.VISIBLE); pg.setVisibility(View.GONE); } }, 3000); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { lastIndex = firstVisibleItem+visibleItemCount; } }
34.979592
131
0.535589
993983a657ec30348930f61352532651ce3e751c
1,767
package club.easyutils.weprogram.config; /*- * Starttag * easy weprogram * # * Copyright (C) 2020 easy weprogram * # * 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. * Endtag */ import club.easyutils.weprogram.util.ConfigUtil; import lombok.AllArgsConstructor; @AllArgsConstructor public enum QrCodeConfig { /** * 获取小程序二维码,适用于需要的码数量较少的业务场景。通过该接口生成的小程序码,永久有效,有数量限制 * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html */ QR_CODE_CREATE("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN"), /** * 获取小程序码,适用于需要的码数量较少的业务场景。通过该接口生成的小程序码,永久有效,有数量限制 * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html */ QR_CODE_GET("https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN"), /** * 获取小程序码,适用于需要的码数量极多的业务场景。通过该接口生成的小程序码,永久有效,数量暂无限制。 * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html */ QR_CODE_UNLIMITED("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN"); private String url; public String getUrl() { return ConfigUtil.converter(url); } }
34.647059
110
0.730617
1728d326c5eb7772a80f1d0408e712022b7014bc
3,438
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.messaging.servicebus.administration.models; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; /** * Tests for {@link SqlRuleFilter}. */ class SqlRuleFilterTest { @Test void testConstructor() { // Arrange final String expectedToString = "SqlRuleFilter: some-expression"; final String expectedSqlExpression = "some-expression"; // Act final SqlRuleFilter actual = new SqlRuleFilter("some-expression"); // Assert assertEquals(expectedSqlExpression, actual.getSqlExpression()); assert (actual.getParameters().isEmpty()); assertNull(actual.getCompatibilityLevel()); assertNull(actual.isPreprocessingRequired()); final String toString = actual.toString(); assertNotNull(toString); assertEquals(expectedToString, toString); } @Test void testEqualsAndHashCode() { final SqlRuleFilter someFilter = new SqlRuleFilter("some-expression"); final SqlRuleFilter otherFilter = new SqlRuleFilter("other-expression"); assertNotEquals(someFilter, otherFilter); assertNotEquals(someFilter.hashCode(), otherFilter.hashCode()); final SqlRuleFilter similarFilter = new SqlRuleFilter("some-expression"); assertEquals(someFilter, similarFilter); assertEquals(someFilter.hashCode(), similarFilter.hashCode()); final SqlRuleFilter filter = new SqlRuleFilter("some-expression", "some-compatibility-level", true); assertNotEquals(filter, someFilter); assertEquals(filter.hashCode(), someFilter.hashCode()); final SqlRuleFilter differentCompatibilityFilter = new SqlRuleFilter("some-expression", "other-compatibility-level", true); assertNotEquals(filter, differentCompatibilityFilter); assertEquals(filter.hashCode(), differentCompatibilityFilter.hashCode()); final SqlRuleFilter differentPreprocessingFilter = new SqlRuleFilter("some-expression", "some-compatibility-level", false); assertNotEquals(filter, differentPreprocessingFilter); assertEquals(filter.hashCode(), differentPreprocessingFilter.hashCode()); final SqlRuleFilter allSameFilter = new SqlRuleFilter("some-expression", "some-compatibility-level", true); assertEquals(filter, allSameFilter); } @Test void testEqualsAndHashCodeTrueAndFalseFilters() { final TrueRuleFilter trueRuleFilter = new TrueRuleFilter(); final TrueRuleFilter otherTrueRuleFilter = new TrueRuleFilter(); assertEquals(trueRuleFilter, otherTrueRuleFilter); assertEquals(trueRuleFilter.hashCode(), otherTrueRuleFilter.hashCode()); final FalseRuleFilter falseRuleFilter = new FalseRuleFilter(); final FalseRuleFilter otherFalseRuleFilter = new FalseRuleFilter(); assertEquals(falseRuleFilter, otherFalseRuleFilter); assertEquals(falseRuleFilter.hashCode(), otherFalseRuleFilter.hashCode()); assertNotEquals(trueRuleFilter.hashCode(), falseRuleFilter.hashCode()); } }
41.421687
95
0.72164
cc9300cb8a35a19cab34af7b70cd93877c162866
299
package cola; public interface COLAInsert<K extends Comparable<K>, V> { /** * Inserts a new element into this COLA (main memory) data structure * * @param key The key of the element * @param value The value of the element */ void insertElement(K key, V value); }
23
72
0.64214
0e6e2c356023df862c05322658472c81340c5e8f
487
package dao.Interface; import model.OperaMetadati; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; public interface OperaInfoInterface { int OperaInfoQuery(OperaMetadati opera) throws SQLException; void DeleteOpera(OperaMetadati delopera) throws SQLException; void UploadImageQuery(String nome, String path,String tit) throws SQLException; ArrayList<OperaMetadati> LoadOpera() throws SQLException; }
24.35
83
0.804928
6e2559f009d7a4685d702cf2ea0340b37d409afa
827
package org.springframework.demo.lifecycle.lifecycle1; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * @version 1.0 * @project: spring * @package: org.springframework.demo.lifecycle.lifecycle1 * @author:admin * @createTime 2021/09/30 15:55:20 */ public class LifeCycleMain { public static void main(String[] args) { System.out.println(" -- Bean创建开始 --"); AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class); System.out.println(" -- Bean创建完成 --"); Juice juice = (Juice) ac.getBean("juice"); System.out.println("juice = " + juice); /*Coffee coffee = ac.getBean(Coffee.class); System.out.println("coffee = " + coffee);*/ System.out.println(" -- Bean销毁开始 --"); ac.close(); System.out.println(" -- Bean销毁完成 --"); } }
27.566667
95
0.706167
12c1dcb2e59add84a30637bc45b31b4cc7efddee
216
package me.philippheuer.twitch4j.model; import java.util.List; import lombok.Data; /** * Model representing a list of chat rooms. */ @Data public class ChatRoomList { /** * Data */ List<ChatRoom> rooms; }
12.705882
43
0.689815
01218fb37d0d94927479d69def1eea30192fb8bd
2,824
/* * Copyright (c) 2013, tamacat.org * All rights reserved. */ package org.tamacat.httpd.auth; import java.util.Hashtable; import javax.naming.AuthenticationException; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import org.apache.http.protocol.HttpContext; import org.tamacat.httpd.exception.ServiceUnavailableException; import org.tamacat.httpd.exception.UnauthorizedException; public class LdapAuthComponent<T extends AuthUser> extends AbstractAuthComponent<T> { protected String DEFAULT_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory"; protected static String DEFAULT_LDAP_VERSION = "3"; protected static String DEFAULT_SECURITY_AUTHENTICATION = "simple"; protected Hashtable<String, String> env = new Hashtable<>(); protected String baseDN; public LdapAuthComponent() { setContextFactory(DEFAULT_CONTEXT_FACTORY); setLdapVersion(DEFAULT_LDAP_VERSION); setSecurityAuthentication(DEFAULT_SECURITY_AUTHENTICATION); } public void setBaseDN(String baseDN) { this.baseDN = baseDN; } public void setContextFactory(String contextFactory) { env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory); } //(ldap://localhost/dc=example,dc=com) public void setProviderUrl(String providerUrl) { env.put(Context.PROVIDER_URL, providerUrl); } public void setSecurityAuthentication(String securityAuthentication) { env.put(Context.SECURITY_AUTHENTICATION, securityAuthentication); } public void setLdapVersion(String ldapVersion) { env.put("java.naming.ldap.version", ldapVersion); } protected DirContext getDirContext(String uid, String password) { try { @SuppressWarnings({ "rawtypes", "unchecked" }) Hashtable<String, String> search = (Hashtable)env.clone(); search.put(Context.SECURITY_PRINCIPAL , "uid="+uid+","+baseDN); search.put(Context.SECURITY_CREDENTIALS , password); return new InitialDirContext(search); } catch (AuthenticationException e) { throw new UnauthorizedException(e.getMessage()); } catch (NamingException e) { throw new ServiceUnavailableException(e); } } @Override public T getAuthUser(String id, HttpContext context) { //getDirContext().search(name, filterExpr, filterArgs, cons); return null; } @Override public boolean check(String id, String pass, HttpContext context) { if (id != null && pass != null) { try { DirContext dc = getDirContext(id, pass); close(dc); return true; } catch (UnauthorizedException e) { return false; } } return false; } protected void close(DirContext dc) { try { if (dc != null) dc.close(); } catch (NamingException e) { } } }
29.726316
86
0.728045
694ebb1d1966f9191d3e7173d6ce36be8db5d2d0
421
package com.epam.training.miservices.services.drugs.repository; import com.epam.training.miservices.services.drugs.model.Symptom; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.util.Optional; public interface SymptomRepository extends CrudRepository<Symptom, Long> { Optional<Symptom> findSymptomByName(@Param("name") String name); }
35.083333
74
0.826603
363becc21f05a9a20628c56e441e70e6ed14595c
16,085
/* * 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.netbeans.modules.web.project.ui; import java.awt.Image; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.Action; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectManager; import org.netbeans.api.project.ProjectUtils; import org.netbeans.api.project.SourceGroup; import org.netbeans.api.project.Sources; import org.netbeans.api.queries.VisibilityQuery; import org.netbeans.modules.java.api.common.ant.UpdateHelper; import org.netbeans.modules.java.api.common.project.ui.ProjectUISupport; import org.netbeans.modules.web.api.webmodule.WebProjectConstants; import org.netbeans.modules.web.project.WebProject; import org.netbeans.modules.web.project.ui.customizer.WebProjectProperties; import org.netbeans.spi.project.support.ant.PropertyEvaluator; import org.netbeans.spi.project.ui.support.CommonProjectActions; import org.netbeans.spi.project.ui.support.NodeFactory; import org.netbeans.spi.project.ui.support.NodeList; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.actions.FileSystemAction; import org.openide.actions.FindAction; import org.openide.actions.PasteAction; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.ChangeableDataFilter; import org.openide.loaders.DataFolder; import org.openide.loaders.DataObject; import org.openide.nodes.FilterNode; import org.openide.nodes.Node; import org.openide.util.ChangeSupport; import org.openide.util.Exceptions; import org.openide.util.ImageUtilities; import org.openide.util.Mutex; import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; import org.openide.util.WeakListeners; import org.openide.util.actions.SystemAction; import org.openide.util.datatransfer.PasteType; /** * * @author mkleint */ @NodeFactory.Registration(projectType="org-netbeans-modules-web-project",position=100) public final class DocBaseNodeFactory implements NodeFactory { /** Creates a new instance of LibrariesNodeFactory */ public DocBaseNodeFactory() { } private static RequestProcessor RP = new RequestProcessor(); public NodeList createNodes(Project p) { WebProject project = p.getLookup().lookup(WebProject.class); assert project != null; return new DocBaseNodeList(project); } private static class DocBaseNodeList implements NodeList<String>, PropertyChangeListener { private static final String DOC_BASE = "docBase"; //NOI18N private static final String WEB_INF = "webInf"; //NOI18N private final WebProject project; private final ChangeSupport changeSupport = new ChangeSupport(this); private final PropertyEvaluator evaluator; private final UpdateHelper helper; private SourceGroup webDocRoot; DocBaseNodeList(WebProject proj) { project = proj; evaluator = project.evaluator(); helper = project.getUpdateHelper(); Sources s = project.getLookup().lookup(Sources.class); assert s != null; // assert s.getSourceGroups(WebProjectConstants.TYPE_DOC_ROOT).length > 0; if(s.getSourceGroups(WebProjectConstants.TYPE_DOC_ROOT).length > 0) { webDocRoot = s.getSourceGroups(WebProjectConstants.TYPE_DOC_ROOT)[0]; } else { String name = ProjectUtils.getInformation( proj ).getDisplayName(); NotifyDescriptor nd = new NotifyDescriptor.Message(NbBundle.getMessage(DocBaseNodeList.class, "LBL_No_Source_Groups_Found", name), NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } } public List<String> keys() { FolderHolder nodeFolders = getNodeFolders(); List<String> result = new ArrayList<String>(); result.add(DOC_BASE + getFolderPath(nodeFolders.getWebDocBaseDir())); if (!nodeFolders.hasCorrectStructure()) { result.add(WEB_INF + getFolderPath(nodeFolders.getWebInfDir())); } return result; } public void addChangeListener(ChangeListener l) { changeSupport.addChangeListener(l); } public void removeChangeListener(ChangeListener l) { changeSupport.removeChangeListener(l); } public Node node(String key) { FolderHolder nodeFolders = getNodeFolders(); if (key.startsWith(DOC_BASE)) { FileObject webDocBaseDir = nodeFolders.getWebDocBaseDir(); DataFolder webFolder = getFolder(webDocBaseDir); if (webFolder != null) { return new DocBaseNode(webFolder, project, new VisibilityQueryDataFilter(webDocRoot)); } return null; } else if (key.startsWith(WEB_INF)) { if (nodeFolders.hasCorrectStructure()) { return null; } FileObject webInfDir = nodeFolders.getWebInfDir(); DataFolder webInfFolder = getFolder(webInfDir); if (webInfFolder != null) { return new WebInfNode(webInfFolder, project, new VisibilityQueryDataFilter(null)); } return null; } assert false: "No node for key: " + key; // NOI18N return null; } public void addNotify() { evaluator.addPropertyChangeListener(this); } public void removeNotify() { evaluator.removePropertyChangeListener(this); } public void propertyChange(PropertyChangeEvent evt) { // The caller holds ProjectManager.mutex() read lock // #197171 - changeSupport used to fire change in AWT thread which // does not work in following scenario: when project properties has // been changed and are being saved the write lock on ProjectManager // can be hold for long time. And that prevents getNodeFolders() // method in this class from being executed (in response to change). Therefore I posted // below fireChange to background thread rather then AWT thread: RP.post(new Runnable() { public void run() { changeSupport.fireChange(); } }); } private DataFolder getFolder(FileObject folder) { if (folder != null) { return DataFolder.findFolder(folder); } return null; } // # 114402 private String getFolderPath(FileObject folder) { if (folder == null) { return ""; } return folder.getPath(); } private FileObject getFileObject(String propName) { String foName = evaluator.getProperty(propName); if (foName == null) { return null; } FileObject fo = helper.getAntProjectHelper().resolveFileObject(foName); // when the project is deleted externally, the sources change could // trigger a call to thid method before the project directory is // notified about the deletion - invalid FileObject-s could be returned return fo != null && fo.isValid() ? fo : null; } private FolderHolder getNodeFolders() { return ProjectManager.mutex().readAccess(new Mutex.Action<FolderHolder>() { public FolderHolder run() { FileObject webDocBaseDir = getFileObject(WebProjectProperties.WEB_DOCBASE_DIR); FileObject webInf = getFileObject(WebProjectProperties.WEBINF_DIR); return new FolderHolder(webDocBaseDir, webInf); } }); } private static final class FolderHolder { private final FileObject webDocBaseDir; private final FileObject webInfDir; public FolderHolder(FileObject webDocBaseDir, FileObject webInfDir) { this.webDocBaseDir = webDocBaseDir; this.webInfDir = webInfDir; } public FileObject getWebDocBaseDir() { return webDocBaseDir; } public FileObject getWebInfDir() { return webInfDir; } /** * Return <code>true</code> if <tt>WEB-INF<tt> folder * is located inside <tt>web</tt> folder. * Return <code>false</code> if any of these folders * is <code>null</code>. */ public boolean hasCorrectStructure() { if (webDocBaseDir == null || webInfDir == null) { return false; } return FileUtil.isParentOf(webDocBaseDir, webInfDir); } } } private static final class DocBaseNode extends BaseNode { DocBaseNode (DataFolder folder, WebProject project, VisibilityQueryDataFilter filter) { super(folder, project, filter); } @Override public String getDisplayName () { return NbBundle.getMessage(DocBaseNodeFactory.class, "LBL_Node_DocBase"); //NOI18N } } private static final class WebInfNode extends BaseNode { WebInfNode (DataFolder folder, WebProject project, VisibilityQueryDataFilter filter) { super (folder, project, filter); } @Override public String getDisplayName() { return NbBundle.getMessage(DocBaseNodeFactory.class, "LBL_Node_WebInf"); //NOI18N } } private abstract static class BaseNode extends FilterNode { private static Image WEB_PAGES_BADGE = ImageUtilities.loadImage( "org/netbeans/modules/web/project/ui/resources/webPagesBadge.gif" ); //NOI18N /** * The MIME type of Java files. */ private static final String JAVA_MIME_TYPE = "text/x-java"; //NO18N private Action actions[]; protected final WebProject project; BaseNode(final DataFolder folder, WebProject project, VisibilityQueryDataFilter filter) { super(folder.getNodeDelegate(), folder.createNodeChildren(filter)); this.project = project; } @Override public Image getIcon(int type) { return computeIcon(false, type); } @Override public Image getOpenedIcon(int type) { return computeIcon(true, type); } private Node getDataFolderNodeDelegate() { return getLookup().lookup(DataFolder.class).getNodeDelegate(); } private Image computeIcon(boolean opened, int type) { Image image; image = opened ? getDataFolderNodeDelegate().getOpenedIcon(type) : getDataFolderNodeDelegate().getIcon(type); image = ImageUtilities.mergeImages(image, WEB_PAGES_BADGE, 7, 7); return image; } @Override public boolean canRename() { return false; } @Override public Action[] getActions(boolean context) { if (actions == null) { actions = new Action[9]; actions[0] = CommonProjectActions.newFileAction(); actions[1] = null; actions[2] = SystemAction.get(FindAction.class); actions[3] = null; actions[4] = SystemAction.get(PasteAction.class); actions[5] = null; actions[6] = SystemAction.get(FileSystemAction.class); actions[7] = null; actions[8] = ProjectUISupport.createPreselectPropertiesAction(project, "Sources", null); //NOI18N } return actions; } @Override public PasteType getDropType(Transferable t, int action, int index) { try { if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){ Object data = t.getTransferData(DataFlavor.javaFileListFlavor); if (data != null) { List list = (List) data; for (Object each : list) { File f = FileUtil.normalizeFile((File) each); FileObject file = FileUtil.toFileObject(f); if (file != null && JAVA_MIME_TYPE.equals(file.getMIMEType())) { //NO18N // don't allow java files, see #119968 return null; } } } } } catch (UnsupportedFlavorException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return super.getDropType(t, action, index); } } static final class VisibilityQueryDataFilter implements ChangeListener, ChangeableDataFilter, PropertyChangeListener { private static final long serialVersionUID = 1L; private final ChangeSupport changeSupport = new ChangeSupport(this); private final SourceGroup sourceGroup; public VisibilityQueryDataFilter(SourceGroup sourceGroup) { this.sourceGroup = sourceGroup; if (this.sourceGroup != null) { this.sourceGroup.addPropertyChangeListener(this); } VisibilityQuery defaultQuery = VisibilityQuery.getDefault(); defaultQuery.addChangeListener(WeakListeners.change(this, defaultQuery)); } public boolean acceptDataObject(DataObject obj) { FileObject fo = obj.getPrimaryFile(); return (sourceGroup == null || sourceGroup.contains(fo)) && VisibilityQuery.getDefault().isVisible(fo); } public void stateChanged( ChangeEvent e) { changeSupport.fireChange(); } public void addChangeListener( ChangeListener listener ) { changeSupport.addChangeListener(listener); } public void removeChangeListener( ChangeListener listener ) { changeSupport.removeChangeListener(listener); } public void propertyChange(PropertyChangeEvent arg0) { changeSupport.fireChange(); } } }
39.327628
185
0.614921
4fab1fffca2afd69e4c9aa2883e4b895e75cd029
4,080
package io.advantageous.qbit.kvstore; import io.advantageous.qbit.QBit; import io.advantageous.qbit.json.JsonMapper; import io.advantageous.qbit.kvstore.impl.StringDecoderEncoderKeyValueStore; import io.advantageous.qbit.kvstore.lowlevel.LowLevelKeyValueStoreService; import io.advantageous.qbit.reactive.Reactor; import io.advantageous.qbit.reactive.ReactorBuilder; import java.util.List; /** * ***JsonKeyValueStoreServiceBuilder*** produces `StringDecoderEncoderKeyValueStore` * that can serialize/parse object to/for Java/JSON. * You don't typically use the `StringDecoderEncoderKeyValueStore` directly but you could. * Instead you use it in conjunction with the ***JsonKeyValueStoreServiceBuilder*** which constructs * `StringDecoderEncoderKeyValueStore` that do JSON encoding and decoding. * <h1>Example using JsonKeyValueStoreServiceBuilder</h1> * <pre> * <code> * private JsonKeyValueStoreServiceBuilder jsonKeyValueStoreServiceBuilder; * private LowLevelLocalKeyValueStoreService localKeyValueStoreService = ...; * private KeyValueStoreService&gt;Todo&lt; keyValueStoreService; * jsonKeyValueStoreServiceBuilder.setLowLevelKeyValueStoreService(localKeyValueStoreService); * keyValueStoreService = jsonKeyValueStoreServiceBuilder.buildKeyValueStore(Todo.class); * keyValueStoreService.put("key", new Todo("value")); * * </code> * </pre> * <p> * Essentially `JsonKeyValueStoreServiceBuilder` can turn a `LowLevelLocalKeyValueStoreService` * into a KeyValueStoreService&gt;Todo&lt; (object store). */ public class JsonKeyValueStoreServiceBuilder { private LowLevelKeyValueStoreService lowLevelKeyValueStoreService; private JsonMapper jsonMapper; private Reactor reactor; /** * Create a new builder * * @return new builder */ public static JsonKeyValueStoreServiceBuilder jsonKeyValueStoreServiceBuilder() { return new JsonKeyValueStoreServiceBuilder(); } public Reactor getReactor() { if (reactor == null) { reactor = ReactorBuilder.reactorBuilder().build(); } return reactor; } public JsonKeyValueStoreServiceBuilder setReactor(Reactor reactor) { this.reactor = reactor; return this; } public JsonMapper getJsonMapper() { if (jsonMapper == null) { jsonMapper = QBit.factory().createJsonMapper(); } return jsonMapper; } public JsonKeyValueStoreServiceBuilder setJsonMapper(JsonMapper jsonMapper) { this.jsonMapper = jsonMapper; return this; } public LowLevelKeyValueStoreService getLowLevelKeyValueStoreService() { return lowLevelKeyValueStoreService; } public JsonKeyValueStoreServiceBuilder setLowLevelKeyValueStoreService(LowLevelKeyValueStoreService lowLevelKeyValueStoreService) { this.lowLevelKeyValueStoreService = lowLevelKeyValueStoreService; return this; } /** * @param componentClass component class type * @param <T> T * @return new kv store that works with lists of componentClass instances */ public <T> StringDecoderEncoderKeyValueStore<List<T>> buildKeyListOfValueStore(final Class<T> componentClass) { final JsonMapper jsonMapper = getJsonMapper(); return new StringDecoderEncoderKeyValueStore<>( json -> jsonMapper.fromJsonArray(json, componentClass), jsonMapper::toJson, this.getLowLevelKeyValueStoreService(), getReactor()); } /** * @param componentClass component class type * @param <T> T * @return new kv store that works with componentClass instances */ public <T> StringDecoderEncoderKeyValueStore<T> buildKeyValueStore(final Class<T> componentClass) { final JsonMapper jsonMapper = getJsonMapper(); return new StringDecoderEncoderKeyValueStore<>( json -> jsonMapper.fromJson(json, componentClass), jsonMapper::toJson, this.getLowLevelKeyValueStoreService(), getReactor()); } }
35.789474
135
0.726225
8eb584a980ed54b87f8cea1444590b1448c1e638
8,898
package br.univali.cc.programacao.noaa.ui.gerenciador.control; import br.univali.cc.programacao.noaa.model.RegistroAtmosferico; import br.univali.cc.programacao.noaa.model.Satelite; import br.univali.cc.programacao.noaa.persistencia.GerenciadorDeBanco; import br.univali.cc.programacao.noaa.ui.gerenciador.NOAADaemon; import br.univali.cc.programacao.noaa.ui.gerenciador.NOAAServico; import br.univali.cc.programacao.noaa.ui.model.Alerta; import java.net.URL; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.CheckBox; import javafx.scene.control.MenuItem; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyCode; public class SatelitesController extends AbstractNOAAController implements Initializable { @FXML private TableView<Satelite> tabelaSatelites; private ObservableList<Satelite> satelites; @FXML private MenuItem cLimparSelecao; @FXML private TableView<RegistroAtmosferico> tabelaRegistros; private ObservableList<RegistroAtmosferico> registros; private FilteredList<RegistroAtmosferico> registrosFiltrados; @FXML private CheckBox tAutoAtualizar; private GerenciadorDeBanco gdb; @Override public void initialize(URL location, ResourceBundle resources) { try { this.gdb = new GerenciadorDeBanco(); } catch (ClassNotFoundException ex) { Alerta.mostrar("Driver JDBC não encontrado.", "Não foi possível inicializar o driver JDBC.", Alert.AlertType.ERROR); } construirTabelaSatelites(); construirTabelaRegistros(); setupServicos(); setupEventos(); } private void setupServicos() { this.tAutoAtualizar.setSelected(true); NOAADaemon.getInstancia().add("Satélites", new NOAAServico(() -> { this.atualizarSatelites(); this.atualizarRegistrosAtmosfericos(); this.atualizarStatus(); }, 0, 2500, false)); } private void setupEventos() { cLimparSelecao.setOnAction(e -> this.tabelaSatelites.getSelectionModel().clearSelection()); tabelaRegistros.setOnMouseClicked(e -> { NOAADaemon.getInstancia().get("Satélites").desabilitar(); tAutoAtualizar.setSelected(false); }); tabelaRegistros.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.DELETE) { try { gdb.deletarRegistroAtmosferico(tabelaRegistros.getSelectionModel().getSelectedItem()); atualizarRegistrosAtmosfericos(); } catch (NullPointerException ex) { Alerta.mostrar("Seleção vazia", "Não há o que ser deletado.", Alert.AlertType.WARNING); } catch (SQLException ex) { Alerta.mostrar("Erro ao deletar registro Atmosférico", ex.getMessage(), Alert.AlertType.ERROR); } } }); tAutoAtualizar.setOnAction(e -> { if (tAutoAtualizar.isSelected()) NOAADaemon.getInstancia().get("Satélites").habilitar(); else NOAADaemon.getInstancia().get("Satélites").desabilitar(); }); } private void atualizarStatus() { String status; if (this.registros.size() == this.registrosFiltrados.size()) { status = "Carregou " + this.registros.size() + " registros atmosféricos de " + this.satelites.size() + " satélites"; } else { status = "Mostrando " + this.registrosFiltrados.size() + " de " + this.registros.size() + " registros atmosféricos"; } this.main.definirStatus(status); } private <D, T> TableColumn<D, T> construirColuna(String cabecalho, String propriedade, double largura) { TableColumn<D, T> coluna = new TableColumn<>(cabecalho); coluna.setMinWidth(largura); coluna.setCellValueFactory(new PropertyValueFactory<>(propriedade)); return coluna; } private void construirModeloTabelaSatelites() { this.satelites = FXCollections.observableArrayList(); } private void construirTabelaSatelites() { construirModeloTabelaSatelites(); TableColumn<Satelite, Integer> id = construirColuna("Id", "id", 15); TableColumn<Satelite, String> nome = construirColuna("Nome", "nome", 75); TableColumn<Satelite, Double> latitude = construirColuna("Latitude", "latitude", 50); TableColumn<Satelite, Double> longitude = construirColuna("Longitude", "longitude", 50); TableColumn<Satelite, Double> bateria = construirColuna("Bateria", "bateria", 50); TableColumn<Satelite, LocalDateTime> data = construirColuna("Data de Lançamento", "dataLancamento", 100); this.tabelaSatelites.getColumns().addAll(id, nome, latitude, longitude, bateria, data); this.tabelaSatelites.setItems(satelites); } public void atualizarSatelites() { try { // Pegar satélite selecionado antes de limpar int selecionado = -1; if (this.tabelaSatelites.getSelectionModel().getSelectedItem() != null) selecionado = this.tabelaSatelites.getSelectionModel().getSelectedItem().getId(); satelites.clear(); // Consultar novos satélites gdb.consultarSatelite().stream().forEach(s -> satelites.add(s)); // Reselecionar antigo satélite if (selecionado > -1) { for (Satelite s : this.satelites) { if (selecionado == s.getId()) { this.tabelaSatelites.getSelectionModel().select(s); break; } } } } catch (SQLException ex) { Alerta.mostrar("Erro ao consultar satélites", ex.getMessage(), Alert.AlertType.ERROR); } } private void construirModeloRegistros() { this.registros = FXCollections.observableArrayList(); this.registrosFiltrados = new FilteredList<>(registros); this.tabelaSatelites.getSelectionModel().selectedItemProperty().addListener((obs, antigo, novo) -> { if (novo != null) this.registrosFiltrados.setPredicate(r -> r.getIdSatelite() == novo.getId()); else this.registrosFiltrados.setPredicate(r -> true); this.atualizarStatus(); }); } private void construirTabelaRegistros() { construirModeloRegistros(); TableColumn<RegistroAtmosferico, Integer> id = construirColuna("Id", "id", 15); TableColumn<RegistroAtmosferico, Integer> idSatelite = construirColuna("Satélite", "idSatelite", 40); TableColumn<RegistroAtmosferico, Double> temperatura = construirColuna("Temperatura em °C", "temperatura", 50); TableColumn<RegistroAtmosferico, Double> pressao = construirColuna("Pressão em hPa", "pressao", 50); TableColumn<RegistroAtmosferico, Double> densidade = construirColuna("Densidade em kg/m³", "densidade", 50); TableColumn<RegistroAtmosferico, Double> vento = construirColuna("Vento em m/s", "vento", 50); TableColumn<RegistroAtmosferico, Double> dirVento = construirColuna("° Direção Vento", "direcaoVento", 50); TableColumn<RegistroAtmosferico, Double> bateria = construirColuna("Bateria em %", "bateria", 50); TableColumn<RegistroAtmosferico, LocalDateTime> data = construirColuna("Data", "data", 100); this.tabelaRegistros.getColumns().addAll(idSatelite, id, temperatura, pressao, densidade, vento, dirVento, bateria, data); this.tabelaRegistros.setItems(registrosFiltrados); } public void atualizarRegistrosAtmosfericos() { try { registros.clear(); gdb.consultarRegistrosAtmosfericosDec().stream().forEach(r -> registros.add(r)); } catch (SQLException ex) { Alerta.mostrar("Erro ao consultar registros atmosféricos", ex.getMessage(), Alert.AlertType.ERROR); } } @Override public void ativar() { this.atualizarStatus(); NOAADaemon.getInstancia().get("Satélites").habilitar(); } @Override public void desativar() { NOAADaemon.getInstancia().get("Satélites").desabilitar(); } }
40.081081
130
0.644302
2459ac1421d43c068d9f7cea5bd578c6f3665a7d
702
package org.quickstart.javase.io.nio.sample; // $Id$ import java.nio.ByteBuffer; public class CreateBuffer { static public void main(String args[]) throws Exception { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put((byte) 'a'); buffer.put((byte) 'b'); buffer.put((byte) 'c'); buffer.flip(); buffer.clear(); buffer.compact(); buffer.mark();//保存当前的position到mark,mark默认是-1 buffer.reset();//恢复position到之前的mark,如果mark=-1,说明没有执行过mark(),会报错InvalidMarkException System.out.println((char) buffer.get()); System.out.println((char) buffer.get()); System.out.println((char) buffer.get()); } }
26
91
0.622507
475da13f79659651c8967780664bba1336ed5b6d
360
package test; public class Sample152 { public static void main(String[] args) { Boat[] boats; boats = new Boat[2]; boats[0] = new Boat(); boats[0].setSeatColor(50,"Green"); boats[1] = new QuickBoat(); boats[1].setSeatColor(44,"Yellow"); for ( int i=0; i < boats.length ; i++){ boats[i].show(); } } }
16.363636
43
0.544444
0b3b286559ca4ed17d5504cf41a20634712ddc92
485
package week1.day1.assignments; public class FibonacciSeries { // Goal: To find Fibonacci Series for a given range public static void main(String[] args) { int range=8,firstNum=0,secNum=1,sum; System.out.println(firstNum); System.out.println(secNum); for(int i=2;i<=range;i++)//if i iterate from 1 ,i get 9 rows o/p as per pseudo assignment { sum=firstNum+secNum; firstNum=secNum; secNum=sum; System.out.println(sum); } } }
24.25
92
0.653608
df6344cf37ea6b5cb50cf40e56823f405e47cf01
12,799
package li.tengfei.apng.opt.optimizer; import li.tengfei.apng.base.PngStream; import li.tengfei.apng.ext.DIntWriter; import li.tengfei.apng.opt.builder.AngChunkData; import li.tengfei.apng.opt.builder.AngData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.zip.CRC32; import static li.tengfei.apng.base.ApngConst.*; import static li.tengfei.apng.base.DInt.*; /** * Use patch chunk to reduce file size * * @author ltf * @since 16/12/11, 下午2:17 */ public class PatchOptimizer implements AngOptimizer { private static final Logger log = LoggerFactory.getLogger(PatchOptimizer.class); private CRC32 crc = new CRC32(); /** * DInt bytes cost for value v */ private static int dIntCost(int v) { if (v <= MAX_1_BYTE_DINT_VALUE) return 1; else if (v <= MAX_2_BYTE_DINT_VALUE) return 2; else if (v <= MAX_3_BYTE_DINT_VALUE) return 3; else if (v <= MAX_4_BYTE_DINT_VALUE) return 4; throw new IllegalStateException("not supported DInt value"); } @Override public AngData optimize(AngData ang) { List<PatchItem> patches = genPatchs(ang); // List<Integer> delChunkIndexes = new ArrayList<>(); // patches = mergePatches(patches, delChunkIndexes); return applyPatches(ang, patches); } private AngData applyPatches(AngData ang, List<PatchItem> patches) { AngData optAng = new AngData(); int chunkIdx = 0; int patchIdx = 0; int allPatchSize = 0; int allOrigSize = 0; List<PatchItem> framePatches = new ArrayList<>(); for (AngChunkData chunk : ang.getChunks()) { if ((chunk.getTypeCode() == CODE_IDAT || chunk.getTypeCode() == CODE_fdAT) && framePatches.size() > 0) { // combine to a patch chunk int defSize = 0; int dataSize = 0; int hashSize = 0; for (PatchItem patch : framePatches) { defSize += patch.defData.length; dataSize += patch.data.length; hashSize += dIntCost(patch.typeHash); } int headersLen = hashSize + defSize; int chunkBodySize = dIntCost(headersLen) + headersLen + dataSize; byte[] data = new byte[4 + 4 + chunkBodySize + 4]; // write chunk bodySize PngStream.intToArray(chunkBodySize, data, 0); // write chunk typeCode PngStream.intToArray(CODE_paCH, data, 4); DIntWriter dInt = new DIntWriter(); int offset = 8; // write HeadersLen dInt.setValue(headersLen); offset += dInt.write(data, offset); // write all Headers for (PatchItem patch : framePatches) { // write typeHash dInt.setValue(patch.typeHash); offset += dInt.write(data, offset); // write defs data System.arraycopy(patch.defData, 0, data, offset, patch.defData.length); offset += patch.defData.length; } // write all datas for (PatchItem patch : framePatches) { // write data System.arraycopy(patch.data, 0, data, offset, patch.data.length); offset += patch.data.length; } // write chunk CRC crc.reset(); crc.update(data, 4, 4 + chunkBodySize); PngStream.intToArray((int) crc.getValue(), data, offset); AngChunkData patchChunk = new AngChunkData(data, CODE_paCH, chunk.getFrameIndex()); optAng.addChunk(patchChunk); framePatches.clear(); allPatchSize += data.length; } if (patchIdx >= patches.size() || chunkIdx < patches.get(patchIdx).chunkIndex) { optAng.addChunk(chunk); } else { framePatches.add(patches.get(patchIdx)); allOrigSize += chunk.getData().length; patchIdx++; } chunkIdx++; } log.debug(String.format("PatchOptimize Result: OrigSize: %d, PatchSize: %d, saved: %d", allOrigSize, allPatchSize, allPatchSize - allOrigSize)); return optAng; } // /** // * merge same type chunk patch in one frame // */ // private List<PatchItem> mergePatches(List<PatchItem> patches, List<Integer> delChunkIndexes) { // ArrayList<PatchItem> optPatches = new ArrayList<>(); // // // // return optPatches; // } /** * generate patches for the ang */ private List<PatchItem> genPatchs(AngData ang) { HashMap<Integer, AngChunkData> existsChunks = new HashMap<>(); ArrayList<PatchItem> patchItems = new ArrayList<>(); for (int i = 0; i < ang.getChunks().size(); i++) { AngChunkData chunk = ang.getChunks().get(i); if (!ChunkTypeHelper.canUsePatch(chunk.getTypeCode())) continue; AngChunkData pre = existsChunks.get(chunk.getTypeCode()); if (pre != null) { PatchItem patchItem = calculatePatch(pre.getData(), chunk.getData(), chunk.getTypeCode() == CODE_IHDR); if (patchItem != null) { patchItem.chunkIndex = i; patchItem.frameIndex = chunk.getFrameIndex(); patchItem.typeCode = chunk.getTypeCode(); patchItem.typeHash = ChunkTypeHelper.getTypeHash(patchItem.typeCode, existsChunks.keySet()); patchItems.add(patchItem); } } // update chunk status to current existsChunks.put(chunk.getTypeCode(), chunk); } return patchItems; } /** * calculate a patch for previous chunk and current chunk */ private PatchItem calculatePatch(final byte[] preData, final byte[] curData, boolean isIHDR) { ArrayList<PatchItemBlock> blocks = new ArrayList<>(); // get all different data blocks int lastDiffPos = -1; // <0 means not init for (int i = 0; i < curData.length; i++) { if ((i < preData.length && curData[i] == preData[i]) // normal chunk || (isIHDR && ((i >= 8 && i < 16) || (i >= 21 && i < 25)))) { // IHDR chunk // same data if (lastDiffPos >= 0) { blocks.add(new PatchItemBlock(lastDiffPos, i - lastDiffPos)); lastDiffPos = -1; } } else { // different data if (lastDiffPos < 0) lastDiffPos = i; } } if (lastDiffPos >= 0) { blocks.add(new PatchItemBlock(lastDiffPos, curData.length - lastDiffPos)); } // add delete block if data size reduced if (curData.length < preData.length) { int delSize = preData.length - curData.length; while (delSize > 0) { int ds = delSize < 65535 ? delSize : 65535; delSize -= ds; blocks.add(new PatchItemBlock(curData.length, 2).setDeletePatch(ds)); } } if (blocks.size() == 0) throw new IllegalStateException("Why are same data chunks appears? is processInherit() not run?"); // optimize blocks blocks = optimizeBlocks(blocks); // prepare data by blocks definition int defSize = 0; int dataSize = 0; int itemCount = 0; for (PatchItemBlock block : blocks) { dataSize += block.dataSize; defSize += block.costBytesCount - block.dataSize; itemCount++; } int noHashCost = dataSize + defSize + dIntCost(itemCount); // select use patch or not conditions if (noHashCost >= curData.length - 13) return null; // log.debug(String.format("noHashCost: %d, curDataLength: %d, saved: %d", // noHashCost, curData.length, noHashCost - curData.length)); PatchItem patchItem = new PatchItem(); patchItem.defData = new byte[defSize + dIntCost(itemCount)]; patchItem.data = new byte[dataSize]; int defOff = 0; int dataOff = 0; DIntWriter dInt = new DIntWriter(); // write ItemsCount first dInt.setValue(itemCount); defOff += dInt.write(patchItem.defData, defOff); for (PatchItemBlock block : blocks) { // write def : dstOffset dInt.setValue(block.dstOffset); defOff += dInt.write(patchItem.defData, defOff); if (block.isDeletePatch) { // write def : dataSize == 0 for DELETE patch dInt.setValue(0); defOff += dInt.write(patchItem.defData, defOff); // write data, 2 byte BIG-ENDIAN unsigned word to specified bytes count to delete patchItem.data[dataOff] = (byte) (block.deleteSize >> 8 & 0xFF); patchItem.data[dataOff + 1] = (byte) (block.deleteSize & 0xFF); // log.debug(String.format("dstOff: %d, delSize: %d, srcOff: %d", // block.dstOffset, block.deleteSize, dataOff)); dataOff += 2; } else { // write def : dataSize dInt.setValue(block.dataSize); defOff += dInt.write(patchItem.defData, defOff); // write data System.arraycopy(curData, block.dstOffset, patchItem.data, dataOff, block.dataSize); // log.debug(String.format("dstOff: %d, dataSize: %d, srcOff: %d", // block.dstOffset, block.dataSize, dataOff)); dataOff += block.dataSize; } } return patchItem; } /** * optimize patch blocks for size and performance */ private ArrayList<PatchItemBlock> optimizeBlocks(ArrayList<PatchItemBlock> blocks) { ArrayList<PatchItemBlock> optBlocks = new ArrayList<>(); PatchItemBlock preBlock = null; for (PatchItemBlock block : blocks) { if (block.isDeletePatch) { if (preBlock != null) { optBlocks.add(preBlock); preBlock = null; } optBlocks.add(block); continue; } if (preBlock == null) { preBlock = block; } else { int newSize = block.dstOffset - preBlock.dstOffset + block.dataSize; int newCost = PatchItemBlock.calBlockCost(preBlock.dstOffset, newSize); if (newCost <= preBlock.costBytesCount + block.costBytesCount) { preBlock = new PatchItemBlock(preBlock.dstOffset, newSize, newCost); } else { optBlocks.add(preBlock); preBlock = block; } } } if (preBlock != null) { optBlocks.add(preBlock); } return optBlocks; } private static class PatchItem { int chunkIndex; int frameIndex; int typeCode; int typeHash; byte[] defData; // definition data as Items in patch Header byte[] data; // raw data to copy } private static class PatchItemBlock { private int dstOffset; private int dataSize; private boolean isDeletePatch; private int deleteSize; private int costBytesCount; // all bytes count to implement this patch block PatchItemBlock(int dstOffset, int dataSize) { this.dstOffset = dstOffset; this.dataSize = dataSize; this.costBytesCount = calBlockCost(dstOffset, dataSize); } PatchItemBlock(int dstOffset, int dataSize, int costBytesCount) { this.dstOffset = dstOffset; this.dataSize = dataSize; this.costBytesCount = costBytesCount; } /** * calculate bytes cost for PatchItemBlock */ static int calBlockCost(int offset, int dataSize) { return dIntCost(offset) + dIntCost(dataSize) + dataSize; } PatchItemBlock setDeletePatch(int deleteSize) { isDeletePatch = true; dataSize = 2; this.costBytesCount = calBlockCost(dstOffset, 2); this.deleteSize = deleteSize; return this; } } }
35.952247
119
0.549652
5bca22885d4fbe813a2e8840029e6f545c35a6fe
614
package com.zhaolin81.spring.framework.configproperties.annotation.properties; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Created by zhaolin on 4/18/2018. */ @ConfigurationProperties(prefix = "test",locations = "classpath:test.properties") public class AppConfigProperties { private String data; private int num; public String getData() { return data; } public void setData(String data) { this.data = data; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } }
21.172414
81
0.67101
9b5513aeee1ef6f2160cbf00790fd0f63905c282
10,546
/* * Copyright (C) 2016 University of Freiburg. * * 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 hybrid.generationExecution; import java.sql.ResultSet; import java.util.ArrayList; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.DataFrame; import org.apache.spark.sql.SQLContext; import data.structures.QueryStruct; import data.structures.ResultStruct; import executor.AppSpark; public class KleeneSmartSPARK { public static String finalQuery; public static String createTableQuery; public static String baseQuery = ""; static ResultSet results = null; public static String temporaryQuery; static int numberOfLines; static String whereExp = ""; static DataFrame resultFrame = null; static JavaSparkContext ctx = AppSpark.ctx; static SQLContext sqlContext = AppSpark.sqlContext; /** * Scalable Smart SPARK implementation of Transitive closure. * * @param oldTableName * @param newTableName * @param joinOnExpression * @param kleeneType * @param selectionPart * @param kleeneDepth1 */ public static void CreateQuery(String[] oldTableName, String newTableName, ArrayList<String> joinOnExpression, String kleeneType, String[] selectionPart, int kleeneDepth1) { String tableShortForm = oldTableName[0].substring(0, 2); String sel1, sel2, sel3, sel1l, sel2l, sel3l, sel1q, sel2q, sel3q; String join = ""; String topQueryPart = ""; int stepCounter = 1; tableInitialization(oldTableName, tableShortForm, joinOnExpression, selectionPart); numberOfLines = 1; // while (numberOfLines > 0) { for (int z = 1; z <= 4; z++) { stepCounter++; if (selectionPart[0].equals("1")) { sel1 = "deltaQ." + selectionPart[1]; sel1l = "deltaP" + Integer.toString(stepCounter - 1) + "." + selectionPart[1]; sel1q = "de1." + selectionPart[1]; } else { sel1 = "deltaP" + Integer.toString(stepCounter - 1) + "." + selectionPart[1]; sel1l = "deltaQ." + selectionPart[1]; sel1q = "de2." + selectionPart[1]; } if (selectionPart[2].equals("1")) { sel2 = "deltaQ." + selectionPart[3]; sel2l = "deltaP" + Integer.toString(stepCounter - 1) + "." + selectionPart[3]; sel2q = "de1." + selectionPart[3]; } else { sel2 = "deltaP" + Integer.toString(stepCounter - 1) + "." + selectionPart[3]; sel2l = "deltaQ." + selectionPart[3]; sel2q = "de2." + selectionPart[3]; } if (selectionPart[4].equals("1")) { sel3 = "deltaQ." + selectionPart[5]; sel3l = "deltaP" + Integer.toString(stepCounter - 1) + "." + selectionPart[5]; sel3q = "de1." + selectionPart[5]; } else { sel3 = "deltaP" + Integer.toString(stepCounter - 1) + "." + selectionPart[5]; sel3l = "deltaQ." + selectionPart[5]; sel3q = "de2." + selectionPart[5]; } // Right Kleene Closure if (kleeneType.equals("right")) { topQueryPart = "SELECT DISTINCT " + sel1 + " AS subject, " + sel2 + " AS predicate, " + sel3 + " AS object" + " FROM deltaQ" + " JOIN deltaP" + Integer.toString(stepCounter - 1) + " ON "; for (int k = 0; k < joinOnExpression.size(); k = k + 3) { if (k > 0) join = join + " AND "; if (joinOnExpression.get(k).toString().substring(2, 3).equals("1")) { join = join + " deltaQ" + joinOnExpression.get(k).toString().substring(3); } else { join = join + " deltaP" + Integer.toString(stepCounter - 1) + joinOnExpression.get(k).toString().substring(3); } join = join + " " + joinOnExpression.get(k + 1) + " "; if (joinOnExpression.get(k + 2).toString().substring(2, 3).equals("1")) { join = join + " deltaQ" + joinOnExpression.get(k + 2).toString().substring(3); } else { join = join + " deltaP" + Integer.toString(stepCounter - 1) + joinOnExpression.get(k + 2).toString().substring(3); } } // Left Kleene Closure } else if (kleeneType.equals("left")) { topQueryPart = "SELECT DISTINCT " + sel1l + " AS subject, " + sel2l + " AS predicate, " + sel3l + " AS object" + " FROM deltaQ" + " JOIN deltaP" + Integer.toString(stepCounter - 1) + " ON "; for (int k = 0; k < joinOnExpression.size(); k = k + 3) { if (k > 0) join = join + " AND "; if (joinOnExpression.get(k).toString().substring(2, 3).equals("1")) { join = join + " deltaP" + Integer.toString(stepCounter - 1) + joinOnExpression.get(k).toString().substring(3); } else { join = join + " deltaQ" + joinOnExpression.get(k).toString().substring(3); } join = join + " " + joinOnExpression.get(k + 1) + " "; if (joinOnExpression.get(k + 2).toString().substring(2, 3).equals("1")) { join = join + " deltaP" + Integer.toString(stepCounter - 1) + joinOnExpression.get(k + 2).toString().substring(3); } else { join = join + " deltaQ" + joinOnExpression.get(k + 2).toString().substring(3); } } } String insertDeltaP = topQueryPart + join; insertDeltaP = insertDeltaP + " UNION SELECT subject, predicate, object FROM deltaP" + Integer.toString(stepCounter - 1); insertDeltaP = insertDeltaP + " UNION SELECT subject, predicate, object FROM deltaQ"; resultFrame = sqlContext.sql(insertDeltaP); resultFrame.cache().registerTempTable("deltaP" + stepCounter); baseQuery = baseQuery + insertDeltaP + "\n"; String KhardCode = ""; if (kleeneType.equals("right")) { KhardCode = "SELECT DISTINCT dp.subject AS subject, dp.predicate AS predicate, gq.object AS object " + " FROM (SELECT DISTINCT p.subject as subject , p.predicate as predicate" + " , p.object as object FROM deltaP" + stepCounter + " p JOIN " + " (SELECT DISTINCT deltaQ.object as object FROM deltaQ) l " + " ON p.object = l.object) dp" + " JOIN (SELECT DISTINCT p.subject as subject, p.predicate as predicate, p.object as object " + " from colleagues_10p p JOIN (SELECT DISTINCT subject as subject FROM deltaQ ) q " + " ON p.subject=q.subject ) gq " + " ON dp.object = gq.subject AND dp.predicate = gq.predicate"; } else if (kleeneType.equals("left")) { KhardCode = "SELECT DISTINCT dp.subject AS subject, dp.predicate AS predicate, gq.object AS object " + " FROM (SELECT DISTINCT p.subject as subject, p.predicate as predicate " + " , p.object as object FROM deltaP" + stepCounter + " p JOIN " + " (SELECT DISTINCT deltaQ.subject as subject FROM deltaQ) l " + " ON p.subject = l.subject ) gq" + " JOIN (SELECT DISTINCT p.subject as subject, p.predicate as predicate, p.object as object " + " from colleagues_10p p JOIN (SELECT DISTINCT object as object FROM deltaQ ) q " + " ON p.object = q.object ) dp " + " ON dp.object = gq.subject AND dp.predicate = gq.predicate"; } resultFrame = sqlContext.sql(KhardCode); resultFrame.cache().registerTempTable("deltaK"); String PiHardCode = "" + " SELECT subject, predicate, object from deltaP" + stepCounter + " UNION select subject, predicate," + " object from deltaQ" + " UNION select subject, predicate, object FROM deltaP" + (stepCounter - 1); resultFrame = sqlContext.sql(PiHardCode); resultFrame.cache().registerTempTable("deltaP" + stepCounter); String QHardCode = "SELECT k.subject as subject, k.predicate as predicate, k.object as object" + " FROM deltaK k LEFT OUTER JOIN " + " (SELECT subject, predicate, object FROM deltaP" + stepCounter + " ) p" + " ON k.subject = p.subject AND k.object= p.object" + " AND k.predicate = p.predicate WHERE p.object IS NULL"; resultFrame = sqlContext.sql(QHardCode); resultFrame.cache().registerTempTable("deltaQ"); join = ""; } System.out.println("###Loop Finished"); temporaryQuery = "SELECT subject AS subject, predicate as predicate, object AS object from deltaP" + Integer.toString(stepCounter); if (kleeneDepth1 == -10) { temporaryQuery = temporaryQuery.substring(90); } resultFrame = sqlContext.sql(temporaryQuery); baseQuery = baseQuery + temporaryQuery + "\n"; QueryStruct.fillStructure(oldTableName, newTableName, baseQuery, "none", "none"); ResultStruct.fillStructureSpark(resultFrame); } /** * Initialization steps. * @param oldTableName * @param tableShortForm * @param joinOnExpression * @param selectionPart */ static void tableInitialization(String[] oldTableName, String tableShortForm, ArrayList<String> joinOnExpression, String[] selectionPart) { String createDeltaP1 = "SELECT subject, predicate, object FROM " + oldTableName[0]; resultFrame = sqlContext.sql(createDeltaP1); resultFrame.registerTempTable("deltaP1"); baseQuery = createDeltaP1 + "\n"; String firstJoinAndIntersection = "SELECT joinTable.subject AS subject, " + " joinTable.predicate AS predicate," + " joinTable.object AS object " + " FROM (SELECT DISTINCT " + tableShortForm + selectionPart[0] + "." + selectionPart[1] + " AS subject, " + tableShortForm + selectionPart[2] + "." + selectionPart[3] + " AS predicate, " + tableShortForm + selectionPart[4] + "." + selectionPart[5] + " AS object" + " FROM " + oldTableName[0] + " " + tableShortForm + 1 + " JOIN " + oldTableName[0] + " " + tableShortForm + 2 + " ON " + joinOnExpression.get(0) + " " + joinOnExpression.get(1) + " " + joinOnExpression.get(2); if (joinOnExpression.size() > 3) { for (int i = 3; i < joinOnExpression.size(); i = i + 3) { firstJoinAndIntersection = firstJoinAndIntersection + " AND " + joinOnExpression.get(i) + " " + joinOnExpression.get(i + 1) + " " + joinOnExpression.get(i + 2); } } firstJoinAndIntersection = firstJoinAndIntersection + " ) joinTable" + " LEFT OUTER JOIN " + oldTableName[0] + " t1 " + " ON t1.subject = joinTable.subject AND t1.predicate = joinTable.predicate" + " AND t1.object = joinTable.object WHERE t1.predicate IS NULL"; resultFrame = sqlContext.sql(firstJoinAndIntersection); resultFrame.registerTempTable("deltaQ"); baseQuery = baseQuery + firstJoinAndIntersection + "\n"; } }
39.498127
114
0.662716
1077e408c7d8a8bae807d6a1dc70d2857701a08e
670
package leetcode.Easy; /** * Problem Url: https://leetcode.com/problems/valid-palindrome-ii */ public class ValidPalindromeIi { public boolean validPalindrome(String s) { int i = 0, j = s.length() - 1; while(i < j) { if(s.charAt(i) != s.charAt(j)) { return isPalindrome(s, i, j - 1) || isPalindrome(s, i + 1, j); } i++;j--; } return true; } private boolean isPalindrome(String s, int i, int j) { while(i < j) { if(s.charAt(i) != s.charAt(j)) { return false; } i++;j--; } return true; } }
22.333333
78
0.464179
105458d4811a83590f5f305ba0044e53954d1019
22,773
/* * Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending */ package io.deephaven.grpc_api.console; import com.google.rpc.Code; import io.deephaven.configuration.Configuration; import io.deephaven.db.plot.FigureWidget; import io.deephaven.db.tables.Table; import io.deephaven.db.util.DelegatingScriptSession; import io.deephaven.db.util.ExportedObjectType; import io.deephaven.db.util.NoLanguageDeephavenSession; import io.deephaven.db.util.ScriptSession; import io.deephaven.db.util.VariableProvider; import io.deephaven.db.v2.DynamicNode; import io.deephaven.figures.FigureWidgetTranslator; import io.deephaven.grpc_api.session.SessionCloseableObserver; import io.deephaven.grpc_api.session.SessionService; import io.deephaven.grpc_api.session.SessionState; import io.deephaven.grpc_api.session.SessionState.ExportBuilder; import io.deephaven.grpc_api.session.TicketRouter; import io.deephaven.grpc_api.util.GrpcUtil; import io.deephaven.internal.log.LoggerFactory; import io.deephaven.io.logger.LogBuffer; import io.deephaven.io.logger.LogBufferRecord; import io.deephaven.io.logger.LogBufferRecordListener; import io.deephaven.io.logger.Logger; import io.deephaven.lang.completion.ChunkerCompleter; import io.deephaven.lang.completion.CompletionLookups; import io.deephaven.lang.parse.CompletionParser; import io.deephaven.lang.parse.LspTools; import io.deephaven.lang.parse.ParsedDocument; import io.deephaven.lang.shared.lsp.CompletionCancelled; import io.deephaven.proto.backplane.grpc.Ticket; import io.deephaven.proto.backplane.script.grpc.*; import io.grpc.stub.StreamObserver; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import static io.deephaven.grpc_api.util.GrpcUtil.safelyExecute; import static io.deephaven.grpc_api.util.GrpcUtil.safelyExecuteLocked; @Singleton public class ConsoleServiceGrpcImpl extends ConsoleServiceGrpc.ConsoleServiceImplBase { private static final Logger log = LoggerFactory.getLogger(ConsoleServiceGrpcImpl.class); public static final String WORKER_CONSOLE_TYPE = Configuration.getInstance().getStringWithDefault("deephaven.console.type", "python"); public static final boolean REMOTE_CONSOLE_DISABLED = Configuration.getInstance().getBooleanWithDefault("deephaven.console.disable", false); private final Map<String, Provider<ScriptSession>> scriptTypes; private final TicketRouter ticketRouter; private final SessionService sessionService; private final LogBuffer logBuffer; private final Map<SessionState, CompletionParser> parsers = new ConcurrentHashMap<>(); private final GlobalSessionProvider globalSessionProvider; @Inject public ConsoleServiceGrpcImpl(final Map<String, Provider<ScriptSession>> scriptTypes, final TicketRouter ticketRouter, final SessionService sessionService, final LogBuffer logBuffer, final GlobalSessionProvider globalSessionProvider) { this.scriptTypes = scriptTypes; this.ticketRouter = ticketRouter; this.sessionService = sessionService; this.logBuffer = logBuffer; this.globalSessionProvider = globalSessionProvider; if (!scriptTypes.containsKey(WORKER_CONSOLE_TYPE)) { throw new IllegalArgumentException("Console type not found: " + WORKER_CONSOLE_TYPE); } } public void initializeGlobalScriptSession() { globalSessionProvider.initializeGlobalScriptSession(scriptTypes.get(WORKER_CONSOLE_TYPE).get()); } @Override public void getConsoleTypes(final GetConsoleTypesRequest request, final StreamObserver<GetConsoleTypesResponse> responseObserver) { GrpcUtil.rpcWrapper(log, responseObserver, () -> { if (!REMOTE_CONSOLE_DISABLED) { // TODO (#702): initially show all console types; the first console determines the global console type // thereafter responseObserver.onNext(GetConsoleTypesResponse.newBuilder() .addConsoleTypes(WORKER_CONSOLE_TYPE) .build()); } responseObserver.onCompleted(); }); } @Override public void startConsole(StartConsoleRequest request, StreamObserver<StartConsoleResponse> responseObserver) { GrpcUtil.rpcWrapper(log, responseObserver, () -> { SessionState session = sessionService.getCurrentSession(); if (REMOTE_CONSOLE_DISABLED) { responseObserver .onError(GrpcUtil.statusRuntimeException(Code.FAILED_PRECONDITION, "Remote console disabled")); return; } // TODO auth hook, ensure the user can do this (owner of worker or admin) // session.getAuthContext().requirePrivilege(CreateConsole); // TODO (#702): initially global session will be null; set it here if applicable final String sessionType = request.getSessionType(); if (!scriptTypes.containsKey(sessionType)) { throw GrpcUtil.statusRuntimeException(Code.FAILED_PRECONDITION, "session type '" + sessionType + "' is not supported"); } session.newExport(request.getResultId(), "resultId") .onError(responseObserver) .submit(() -> { final ScriptSession scriptSession; if (sessionType.equals(WORKER_CONSOLE_TYPE)) { scriptSession = new DelegatingScriptSession(globalSessionProvider.getGlobalSession()); } else { scriptSession = new NoLanguageDeephavenSession(sessionType); log.error().append("Session type '" + sessionType + "' is disabled." + "Use the session type '" + WORKER_CONSOLE_TYPE + "' instead.").endl(); } safelyExecute(() -> { responseObserver.onNext(StartConsoleResponse.newBuilder() .setResultId(request.getResultId()) .build()); responseObserver.onCompleted(); }); return scriptSession; }); }); } @Override public void subscribeToLogs(LogSubscriptionRequest request, StreamObserver<LogSubscriptionData> responseObserver) { GrpcUtil.rpcWrapper(log, responseObserver, () -> { if (REMOTE_CONSOLE_DISABLED) { responseObserver .onError(GrpcUtil.statusRuntimeException(Code.FAILED_PRECONDITION, "Remote console disabled")); return; } SessionState session = sessionService.getCurrentSession(); // if that didn't fail, we at least are authenticated, but possibly not authorized // TODO auth hook, ensure the user can do this (owner of worker or admin). same rights as creating a console // session.getAuthContext().requirePrivilege(LogBuffer); logBuffer.subscribe(new LogBufferStreamAdapter(session, request, responseObserver)); }); } @Override public void executeCommand(ExecuteCommandRequest request, StreamObserver<ExecuteCommandResponse> responseObserver) { GrpcUtil.rpcWrapper(log, responseObserver, () -> { final SessionState session = sessionService.getCurrentSession(); final Ticket consoleId = request.getConsoleId(); if (consoleId.getTicket().isEmpty()) { throw GrpcUtil.statusRuntimeException(Code.FAILED_PRECONDITION, "No consoleId supplied"); } SessionState.ExportObject<ScriptSession> exportedConsole = ticketRouter.resolve(session, consoleId, "consoleId"); session.nonExport() .requiresSerialQueue() .require(exportedConsole) .onError(responseObserver) .submit(() -> { ScriptSession scriptSession = exportedConsole.get(); // produce a diff ExecuteCommandResponse.Builder diff = ExecuteCommandResponse.newBuilder(); ScriptSession.Changes changes = scriptSession.evaluateScript(request.getCode()); changes.created.entrySet() .forEach(entry -> diff.addCreated(makeVariableDefinition(entry))); changes.updated.entrySet() .forEach(entry -> diff.addUpdated(makeVariableDefinition(entry))); changes.removed.entrySet() .forEach(entry -> diff.addRemoved(makeVariableDefinition(entry))); responseObserver.onNext(diff.build()); responseObserver.onCompleted(); }); }); } private static VariableDefinition makeVariableDefinition(Map.Entry<String, ExportedObjectType> entry) { return VariableDefinition.newBuilder().setTitle(entry.getKey()).setType(entry.getValue().name()) .setId(ScopeTicketResolver.ticketForName(entry.getKey())).build(); } @Override public void cancelCommand(CancelCommandRequest request, StreamObserver<CancelCommandResponse> responseObserver) { // TODO not yet implemented, need a way to handle stopping a command in a consistent way super.cancelCommand(request, responseObserver); } @Override public void bindTableToVariable(BindTableToVariableRequest request, StreamObserver<BindTableToVariableResponse> responseObserver) { GrpcUtil.rpcWrapper(log, responseObserver, () -> { final SessionState session = sessionService.getCurrentSession(); Ticket tableId = request.getTableId(); if (tableId.getTicket().isEmpty()) { throw GrpcUtil.statusRuntimeException(Code.FAILED_PRECONDITION, "No source tableId supplied"); } final SessionState.ExportObject<Table> exportedTable = ticketRouter.resolve(session, tableId, "tableId"); final SessionState.ExportObject<ScriptSession> exportedConsole; ExportBuilder<?> exportBuilder = session.nonExport() .requiresSerialQueue() .onError(responseObserver); if (request.hasConsoleId()) { exportedConsole = ticketRouter.resolve(session, request.getConsoleId(), "consoleId"); exportBuilder.require(exportedTable, exportedConsole); } else { exportedConsole = null; exportBuilder.require(exportedTable); } exportBuilder.submit(() -> { ScriptSession scriptSession = exportedConsole != null ? exportedConsole.get() : globalSessionProvider.getGlobalSession(); Table table = exportedTable.get(); scriptSession.setVariable(request.getVariableName(), table); if (DynamicNode.notDynamicOrIsRefreshing(table)) { scriptSession.manage(table); } responseObserver.onNext(BindTableToVariableResponse.getDefaultInstance()); responseObserver.onCompleted(); }); }); } private CompletionParser ensureParserForSession(SessionState session) { return parsers.computeIfAbsent(session, s -> { CompletionParser parser = new CompletionParser(); s.addOnCloseCallback(() -> { parsers.remove(s); parser.close(); }); return parser; }); } @Override public StreamObserver<AutoCompleteRequest> autoCompleteStream( StreamObserver<AutoCompleteResponse> responseObserver) { return GrpcUtil.rpcWrapper(log, responseObserver, () -> { final SessionState session = sessionService.getCurrentSession(); CompletionParser parser = ensureParserForSession(session); return new StreamObserver<AutoCompleteRequest>() { @Override public void onNext(AutoCompleteRequest value) { switch (value.getRequestCase()) { case OPEN_DOCUMENT: { final TextDocumentItem doc = value.getOpenDocument().getTextDocument(); parser.open(doc.getText(), doc.getUri(), Integer.toString(doc.getVersion())); break; } case CHANGE_DOCUMENT: { ChangeDocumentRequest request = value.getChangeDocument(); final VersionedTextDocumentIdentifier text = request.getTextDocument(); parser.update(text.getUri(), Integer.toString(text.getVersion()), request.getContentChangesList()); break; } case GET_COMPLETION_ITEMS: { GetCompletionItemsRequest request = value.getGetCompletionItems(); SessionState.ExportObject<ScriptSession> exportedConsole = session.getExport(request.getConsoleId(), "consoleId"); session.nonExport() .require(exportedConsole) .onError(responseObserver) .submit(() -> { final VersionedTextDocumentIdentifier doc = request.getTextDocument(); ScriptSession scriptSession = exportedConsole.get(); final VariableProvider vars = scriptSession.getVariableProvider(); final CompletionLookups h = CompletionLookups.preload(scriptSession); // The only stateful part of a completer is the CompletionLookups, which are // already once-per-session-cached // so, we'll just create a new completer for each request. No need to hang onto // these guys. final ChunkerCompleter completer = new ChunkerCompleter(log, vars, h); final ParsedDocument parsed; try { parsed = parser.finish(doc.getUri()); } catch (CompletionCancelled exception) { if (log.isTraceEnabled()) { log.trace().append("Completion canceled").append(exception).endl(); } safelyExecuteLocked(responseObserver, () -> responseObserver.onNext(AutoCompleteResponse.newBuilder() .setCompletionItems(GetCompletionItemsResponse.newBuilder() .setSuccess(false) .setRequestId(request.getRequestId())) .build())); return; } int offset = LspTools.getOffsetFromPosition(parsed.getSource(), request.getPosition()); final Collection<CompletionItem.Builder> results = completer.runCompletion(parsed, request.getPosition(), offset); final GetCompletionItemsResponse mangledResults = GetCompletionItemsResponse.newBuilder() .setSuccess(true) .setRequestId(request.getRequestId()) .addAllItems(results.stream().map( // insertTextFormat is a default we used to set in // constructor; // for now, we'll just process the objects before // sending back to client item -> item.setInsertTextFormat(2).build()) .collect(Collectors.toSet())) .build(); safelyExecuteLocked(responseObserver, () -> responseObserver.onNext(AutoCompleteResponse.newBuilder() .setCompletionItems(mangledResults) .build())); }); break; } case CLOSE_DOCUMENT: { CloseDocumentRequest request = value.getCloseDocument(); parser.remove(request.getTextDocument().getUri()); break; } case REQUEST_NOT_SET: { throw GrpcUtil.statusRuntimeException(Code.INVALID_ARGUMENT, "Autocomplete command missing request"); } } } @Override public void onError(Throwable t) { // ignore, client doesn't need us, will be cleaned up later } @Override public void onCompleted() { // just hang up too, browser will reconnect if interested synchronized (responseObserver) { responseObserver.onCompleted(); } } }; }); } @Override public void fetchFigure(FetchFigureRequest request, StreamObserver<FetchFigureResponse> responseObserver) { GrpcUtil.rpcWrapper(log, responseObserver, () -> { final SessionState session = sessionService.getCurrentSession(); if (request.getSourceId().getTicket().isEmpty()) { throw GrpcUtil.statusRuntimeException(Code.FAILED_PRECONDITION, "No sourceId supplied"); } final SessionState.ExportObject<Object> figure = ticketRouter.resolve( session, request.getSourceId(), "sourceId"); session.nonExport() .require(figure) .onError(responseObserver) .submit(() -> { Object result = figure.get(); if (!(result instanceof FigureWidget)) { final String name = ticketRouter.getLogNameFor(request.getSourceId(), "sourceId"); throw GrpcUtil.statusRuntimeException(Code.NOT_FOUND, "Value bound to ticket " + name + " is not a FigureWidget"); } FigureWidget widget = (FigureWidget) result; FigureDescriptor translated = FigureWidgetTranslator.translate(widget, session); responseObserver .onNext(FetchFigureResponse.newBuilder().setFigureDescriptor(translated).build()); responseObserver.onCompleted(); }); }); } private static class LogBufferStreamAdapter extends SessionCloseableObserver<LogSubscriptionData> implements LogBufferRecordListener { private final LogSubscriptionRequest request; public LogBufferStreamAdapter( final SessionState session, final LogSubscriptionRequest request, final StreamObserver<LogSubscriptionData> responseObserver) { super(session, responseObserver); this.request = request; } @Override public void record(LogBufferRecord record) { // only pass levels the client wants if (request.getLevelsCount() != 0 && !request.getLevelsList().contains(record.getLevel().getName())) { return; } // since the subscribe() method auto-replays all existing logs, filter to just once this // consumer probably hasn't seen if (record.getTimestampMicros() < request.getLastSeenLogTimestamp()) { return; } // TODO this is not a good implementation, just a quick one, but it does appear to be safe, // since LogBuffer is synchronized on access to the listeners. We're on the same thread // as all other log receivers and try { LogSubscriptionData payload = LogSubscriptionData.newBuilder() .setMicros(record.getTimestampMicros()) .setLogLevel(record.getLevel().getName()) // this could be done on either side, doing it here because its a weird charset and we should // own that .setMessage(record.getDataString()) .build(); synchronized (responseObserver) { responseObserver.onNext(payload); } } catch (Throwable ignored) { // we are ignoring exceptions here deliberately, and just shutting down close(); } } } }
50.606667
120
0.560049
bb976c04e147c59218c87a278f308df84630d49e
6,689
package authoringEnvironment.pathing; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.geometry.Pos; import javafx.scene.Group; import javafx.scene.image.ImageView; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.CubicCurve; import javafx.scene.shape.Line; import javafx.scene.shape.Rectangle; import javafx.scene.shape.StrokeLineCap; import javafx.scene.text.Text; import authoringEnvironment.InstanceManager; import authoringEnvironment.Variables; import authoringEnvironment.objects.Coordinate; import authoringEnvironment.objects.GameObject; import authoringEnvironment.objects.TileMap; import authoringEnvironment.util.Screenshot; /** * PathView displays the path consisting of anchors, curves (bound lines), and adds them to the parent * * @author Callie Mao * */ public class PathView extends GameObject { private static final double CONTROL_POINT_LOCATION_MULTIPLIER = 0.2; private static final int DEFAULT_STROKE_WIDTH = 4; private static final double MAP_OPACITY_ACTIVATED = 0.2; private static final String NUMBER_ANCHOR_POINTS = "\nNumber of anchor points: "; private TileMap myParent; private int numPoints; private Anchor mostRecentPoint; private List<Anchor> myAnchors; private Group myRoot; public PathView (TileMap parent) { myAnchors = new ArrayList<Anchor>(); myParent = parent; numPoints = 0; myRoot = new Group(); Rectangle pathModeOverlay = new Rectangle(parent.getWidth(), parent.getHeight()); pathModeOverlay.setOpacity(MAP_OPACITY_ACTIVATED); StackPane.setAlignment(pathModeOverlay, Pos.CENTER); myRoot.getChildren().add(pathModeOverlay); myParent.getRoot().getChildren().addAll(myRoot); } public int getNumPoints () { return numPoints; } public boolean areAnchorsSelected () { for (Anchor anchor : myAnchors) { if (anchor.isSelected()) return true; } return false; } public void addAnchor (double startX, double startY) { DoubleProperty startXProperty = new SimpleDoubleProperty(startX); DoubleProperty startYProperty = new SimpleDoubleProperty(startY); Anchor anchor = new Anchor(Color.PALEGREEN, startXProperty, startYProperty, myParent.getWidth(), myParent.getHeight()); myParent.getRoot().getChildren().add(anchor); if (numPoints > 0) { createCurve(mostRecentPoint, anchor); } Text num = new Text(Integer.toString(numPoints)); num.xProperty().bind(anchor.centerXProperty()); num.yProperty().bind(anchor.centerYProperty()); myRoot.getChildren().add(num); mostRecentPoint = anchor; myAnchors.add(anchor); numPoints++; } public void createCurve (Anchor start, Anchor end) { CubicCurve curve = createStartingCurve(start.getCenterX(), start.getCenterY(), end.getCenterX(), end.getCenterY()); Line controlLine1 = new BoundLine(curve.controlX1Property(), curve.controlY1Property(), curve.startXProperty(), curve.startYProperty()); Line controlLine2 = new BoundLine(curve.controlX2Property(), curve.controlY2Property(), curve.endXProperty(), curve.endYProperty()); Anchor control1 = new Anchor(Color.GOLD, curve.controlX1Property(), curve.controlY1Property(), myParent.getWidth(), myParent.getHeight()); Anchor control2 = new Anchor(Color.GOLDENROD, curve.controlX2Property(), curve.controlY2Property(), myParent.getWidth(), myParent.getHeight()); curve.startXProperty().bind(start.centerXProperty()); curve.endXProperty().bind(end.centerXProperty()); curve.startYProperty().bind(start.centerYProperty()); curve.endYProperty().bind(end.centerYProperty()); myAnchors.add(control1); myAnchors.add(control2); Group path = new Group(controlLine1, controlLine2, curve, start, control1, control2, end); myRoot.getChildren().add(path); } private CubicCurve createStartingCurve (double startX, double startY, double endX, double endY) { CubicCurve curve = new CubicCurve(); double xDiff = endX - startX; double yDiff = endY - startY; double controlX1 = startX + xDiff * CONTROL_POINT_LOCATION_MULTIPLIER; double controlY1 = startY + yDiff * CONTROL_POINT_LOCATION_MULTIPLIER; double controlX2 = endX - xDiff * CONTROL_POINT_LOCATION_MULTIPLIER; double controlY2 = endY - yDiff * CONTROL_POINT_LOCATION_MULTIPLIER; curve.setStartX(startX); curve.setStartY(startY); curve.setControlX1(controlX1); curve.setControlY1(controlY1); curve.setControlX2(controlX2); curve.setControlY2(controlY2); curve.setEndX(endX); curve.setEndY(endY); curve.setStroke(Color.FORESTGREEN); curve.setStrokeWidth(DEFAULT_STROKE_WIDTH); curve.setStrokeLineCap(StrokeLineCap.ROUND); curve.setFill(Color.TRANSPARENT); return curve; } public Map<String, Object> save () { List<Coordinate> anchorCoordinates = new ArrayList<Coordinate>(); for (Anchor anchor : myAnchors) { anchorCoordinates.add(anchor.getCoordinates()); } ImageView image = Screenshot.snap(myParent); setImageView(image); Map<String, Object> settings = new HashMap<String, Object>(); settings.put(InstanceManager.NAME_KEY, getName()); settings.put(Variables.PARAMETER_CURVES_COORDINATES, anchorCoordinates); settings.put(InstanceManager.PART_TYPE_KEY, InstanceManager.PATH_PARTNAME); return settings; } protected String getToolTipInfo () { String info = Variables.EMPTY_STRING; info += Variables.NAME_HEADER + getName(); info += NUMBER_ANCHOR_POINTS + numPoints; return info; } @Override public Group getRoot () { return myRoot; } @Override public double getWidth () { return myParent.getWidth(); } @Override public double getHeight () { return myParent.getHeight(); } }
33.954315
102
0.660786
ce65b9a3ee33f55353ed1eb129f90daaf18b17ad
7,757
package com.ogu.mobileproject; import androidx.appcompat.app.AppCompatActivity; import android.app.DatePickerDialog; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.VideoView; import java.util.Calendar; public class MainPageActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener { VideoView videoView; Button btnAddress,btnStart,btnEnd,btnPet,btnHostBul,btnProfile,btnHostArayanlar,btnCikis; Spinner spAddress,spPet; int flag; String[] cities ={"Adana","Adıyaman", "Afyon", "Ağrı", "Amasya", "Ankara", "Antalya", "Artvin", "Aydın", "Balıkesir","Bilecik", "Bingöl", "Bitlis", "Bolu", "Burdur", "Bursa", "Çanakkale", "Çankırı", "Çorum","Denizli","Diyarbakır", "Edirne", "Elazığ", "Erzincan", "Erzurum ", "Eskişehir", "Gaziantep", "Giresun","Gümüşhane", "Hakkari", "Hatay", "Isparta", "Mersin", "İstanbul", "İzmir", "Kars", "Kastamonu", "Kayseri","Kırklareli", "Kırşehir", "Kocaeli", "Konya", "Kütahya ", "Malatya", "Manisa", "Kahramanmaraş", "Mardin", "Muğla", "Muş", "Nevşehir", "Niğde", "Ordu", "Rize", "Sakarya", "Samsun", "Siirt", "Sinop", "Sivas", "Tekirdağ", "Tokat", "Trabzon ", "Tunceli", "Şanlıurfa", "Uşak", "Van", "Yozgat", "Zonguldak", "Aksaray", "Bayburt ", "Karaman", "Kırıkkale", "Batman", "Şırnak", "Bartın", "Ardahan", "Iğdır", "Yalova", "Karabük ", "Kilis", "Osmaniye ", "Düzce"}; String[] pets ={"Köpek", "Kedi","Kuş", "Balık"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_page); videoView=findViewById(R.id.videoView); btnAddress=findViewById(R.id.btnAddress); btnStart=findViewById(R.id.btnStartDate); btnEnd=findViewById(R.id.btnEndDate); btnPet=findViewById(R.id.btnPet); btnProfile=findViewById(R.id.btnProfile); btnHostBul=findViewById(R.id.btnHostBul); btnHostArayanlar=findViewById(R.id.btnHostAra); spAddress=findViewById(R.id.spAddress); spPet=findViewById(R.id.spPet); btnCikis=findViewById(R.id.btnCikis); ArrayAdapter<String> cityAdapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, cities); ArrayAdapter<String> petAdapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, pets); spAddress.setAdapter(cityAdapter); spPet.setAdapter(petAdapter); btnStart.setBackgroundColor(Color.WHITE); btnEnd.setBackgroundColor(Color.WHITE); btnAddress.setBackgroundColor(Color.WHITE); btnPet.setBackgroundColor(Color.WHITE); btnHostBul.setBackgroundColor(Color.rgb(255,127,0)); String str = "https://petsurfer.com/video.mp4"; Uri uri = Uri.parse(str); videoView.setVideoURI(uri); videoView.requestFocus(); videoView.start(); videoView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT)); videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.setLooping(true); } }); btnAddress.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { spAddress.performClick(); } }); btnPet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { spPet.performClick(); } }); btnCikis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getApplicationContext(), login.class); startActivity(intent); } }); spAddress.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { btnAddress.setText(parent.getItemAtPosition(position).toString()); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); btnProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(getApplicationContext(), ProfileActivity.class); startActivity(intent); } }); btnHostArayanlar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(getApplicationContext(), HostArayanlar.class); startActivity(intent); } }); btnHostBul.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = getSharedPreferences("Search", MODE_PRIVATE).edit(); editor.clear(); editor.putString("startDate",btnStart.getText().toString()); editor.putString("endDate",btnEnd.getText().toString()); editor.putString("address",btnAddress.getText().toString()); editor.putString("animal",btnPet.getText().toString()); editor.apply(); Intent intent=new Intent(getApplicationContext(), Hostlar.class); startActivity(intent); } }); spPet.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { btnPet.setText(parent.getItemAtPosition(position).toString()); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void selectStartDate(View view) { flag=1; showDatePickerDialog(); } public void selectEndDate(View view) { flag=2; showDatePickerDialog(); } public void showDatePickerDialog(){ DatePickerDialog datePickerDialog = new DatePickerDialog( this, this, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); datePickerDialog.show(); } @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { String monthParse=String.valueOf(month+1); String dayParse=String.valueOf(dayOfMonth); if(month+1<10){ monthParse="0"+String.valueOf(month+1); } if(dayOfMonth<10){ dayParse="0"+String.valueOf(dayOfMonth); } String date = year + "-" +monthParse + "-" + dayParse; if(flag==1){ btnStart.setText(date); } else if(flag==2) { btnEnd.setText(date); } } }
39.984536
144
0.622019
1963bdc2cc0f2b0dad6281de426603f2a75d9559
1,174
package cn.licoy.encryptbody.util; import cn.licoy.encryptbody.enums.SHAEncryptType; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * <p>SHA加密工具类</p> * @author licoy.cn * @version 2018/9/5 */ public class SHAEncryptUtil { /** * SHA加密公共方法 * @param string 目标字符串 * @param type 加密类型 {@link SHAEncryptType} */ public static String encrypt(String string,SHAEncryptType type) { if (string==null || "".equals(string.trim())) return ""; if (type==null) type = SHAEncryptType.SHA256; try { MessageDigest md5 = MessageDigest.getInstance(type.value); byte[] bytes = md5.digest((string).getBytes()); StringBuilder result = new StringBuilder(); for (byte b : bytes) { String temp = Integer.toHexString(b & 0xff); if (temp.length() == 1) { temp = "0" + temp; } result.append(temp); } return result.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } }
26.088889
70
0.562181
6ab0896d8af1a60402a640bfbb5de2c189eaea46
507
package com.mediscreen.patients.api.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Value; import lombok.With; @Builder(builderClassName = "Builder", toBuilder = true) @Value @With @AllArgsConstructor(onConstructor = @__(@Deprecated)) // intended to be used only by tools (MapStruct, Jackson, etc) public class Country { /** * The lower-case ISO 3166-1 alpha-2 country code. */ String code; /** * The full country name. */ String name; }
22.043478
116
0.69428
7570fae563ac4d1aac326736d0a1473df7183356
2,106
/* * 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 android.support.wear.widget.drawer; import android.support.annotation.RestrictTo; import android.support.annotation.RestrictTo.Scope; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.OnScrollListener; import android.support.wear.widget.drawer.FlingWatcherFactory.FlingListener; import android.support.wear.widget.drawer.FlingWatcherFactory.FlingWatcher; import java.lang.ref.WeakReference; /** * {@link FlingWatcher} implementation for {@link RecyclerView RecyclerViews}. Detects the end of * a Fling by waiting until the scroll state becomes idle. * * @hide */ @RestrictTo(Scope.LIBRARY_GROUP) class RecyclerViewFlingWatcher extends OnScrollListener implements FlingWatcher { private final FlingListener mListener; private final WeakReference<RecyclerView> mRecyclerView; RecyclerViewFlingWatcher(FlingListener listener, RecyclerView view) { mListener = listener; mRecyclerView = new WeakReference<>(view); } @Override public void watch() { RecyclerView recyclerView = mRecyclerView.get(); if (recyclerView != null) { recyclerView.addOnScrollListener(this); } } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { mListener.onFlingComplete(recyclerView); recyclerView.removeOnScrollListener(this); } } }
34.52459
97
0.743115
bac7f1bea177d1e22f4249afbd12806b64def032
4,192
package mjj.cma.hitnrun.GameEngine; import android.view.MotionEvent; import android.view.View; import java.util.List; public class MultiTouchHandler implements TouchHandler, View.OnTouchListener { private boolean[] isTouched = new boolean[20]; private int[] touchX = new int[20]; private int[] touchY = new int[20]; private List<TouchEvent> touchEventBuffer; private TouchEventPool touchEventPool; public MultiTouchHandler(View view, List<TouchEvent> touchEventBuffer, TouchEventPool touchEventPool) { view.setOnTouchListener(this); this.touchEventBuffer = touchEventBuffer; this.touchEventPool = touchEventPool; } @Override public synchronized boolean isTouchDown(int pointer) { if (pointer < 0 || pointer >= 20) return false; else return isTouched[pointer]; } @Override public synchronized int getTouchX(int pointer) { if (pointer < 0 || pointer >= 20) return -42; else return touchX[pointer]; } @Override public synchronized int getTouchY(int pointer) { if (pointer < 0 || pointer >= 20) return -42; else return touchY[pointer]; } @Override public boolean onTouch(View v, MotionEvent event) { synchronized (touchEventPool) { TouchEvent touchEvent = null; int action = event.getAction() & MotionEvent.ACTION_MASK; int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; int pointerId = event.getPointerId(pointerIndex); switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: touchEvent = touchEventPool.obtain(); touchEvent.type = TouchEvent.TouchEventType.Down; touchEvent.pointer = pointerId; touchX[pointerId] = (int) event.getX(pointerIndex); touchEvent.x = touchX[pointerId]; touchY[pointerId] = (int) event.getY(pointerIndex); touchEvent.y = touchY[pointerId]; isTouched[pointerId] = true; touchEventBuffer.add(touchEvent); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_CANCEL: touchEvent = touchEventPool.obtain(); touchEvent.type = TouchEvent.TouchEventType.Up; touchEvent.pointer = pointerId; touchX[pointerId] = (int) event.getX(pointerIndex); touchEvent.x = touchX[pointerId]; touchY[pointerId] = (int) event.getY(pointerIndex); touchEvent.y = touchY[pointerId]; isTouched[pointerId] = false; touchEventBuffer.add(touchEvent); break; case MotionEvent.ACTION_MOVE: int pointerCount = event.getPointerCount(); for (int i = 0;i < pointerCount; i++) { touchEvent = touchEventPool.obtain(); touchEvent.type = TouchEvent.TouchEventType.Dragged; pointerIndex = i; pointerId = event.getPointerId(pointerIndex); touchEvent.pointer = pointerId; touchEvent.x = touchX[pointerId] = (int) event.getX(pointerIndex); touchEvent.y = touchY[pointerId] = (int) event.getY(pointerIndex); touchEventBuffer.add(touchEvent); } break; } } return true; } }
33.536
133
0.524571
0285ba5e1eb082916a783db1e62df27e1b65e2a1
686
package ru.job4j.switcher; /** * SwitcherThread * * @author Ksenya Kaysheva ([email protected]) * @version $Id$ * @since 0.1 */ public class SwitcherThread extends Thread { private Switcher switcher; private int digit; public SwitcherThread(Switcher switcher, int digit) { this.switcher = switcher; this.digit = digit; } @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { switcher.addDigit(digit); } catch (InterruptedException ie) { ie.printStackTrace(); Thread.currentThread().interrupt(); } } } }
21.4375
57
0.571429
f5b2bf5e1be937431bedf159de0f7974b10dcccd
1,555
package com.containers.container.domain.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.containers.container.domain.exception.NegocioException; import com.containers.container.domain.model.Clientes; import com.containers.container.domain.repository.ClientesRepository; @Service public class CadastroClientesService { // @Autowired // private EmpresasRepository empresaRepository; @Autowired private ClientesRepository clienteRepository; /* public Clientes criar(Clientes cliente) { Empresas empresa = empresaRepository.findById(cliente.getEmpresa().getId()) .orElseThrow(() -> new EntidadeNaoEncontradaException("Cliente não encontrado")); cliente.setEmpresa(empresa); // cliente.setEmail(email); // cliente.setNome(nome); // cliente.setTelefone(telefone); // cliente.setCpf(cpf); return clienteRepository.save(cliente); } */ public void finalizar(Long clienteId) { Clientes cliente = buscar(clienteId); clienteRepository.save(cliente); } private Clientes buscar(Long clienteId) { return clienteRepository.findById(clienteId) .orElseThrow(() -> new NegocioException("Empresa não encontrada")); } public Clientes salvar(Clientes cliente) { Clientes clienteExiste = clienteRepository.findByEmail(cliente.getEmail()); if (clienteExiste != null && !clienteExiste.equals(cliente)) { throw new NegocioException("Já existe uma empresa cadastrado com este e-mail."); } return clienteRepository.save(cliente); } }
28.796296
86
0.773633
58b970752a5d470860be74f480c62ac400189a10
803
package io.gravitee.resource.cache.rediscache; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; public class RedisTest1 { private Jedis jedis; @Before public void setUpCache() { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //set the data in redis string jedis.set("tutorial-name", "Redis tutorial"); // Get the stored data and print it System.out.println("Stored string in redis:: "+ jedis.get("tutorial-name")); } @Test public void testConnection() { assertEquals(true, jedis.isConnected()); // jedis.set("localhost", "127.0.0.1"); // jedis.get("localhost"); } }
25.903226
83
0.686177
f6ada114e77d642add1308ec4cb93bd97b0d4867
152,098
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: packimports(3) // Source File Name: SKDEditConstraint_Stub.java package com.ibm.tivoli.maximo.skd.app.virtual; import java.lang.reflect.Method; import java.rmi.RemoteException; import java.rmi.UnexpectedException; import java.rmi.server.*; import java.util.*; import psdi.mbo.*; import psdi.security.UserInfo; import psdi.txn.MXTransaction; import psdi.util.*; // Referenced classes of package com.ibm.tivoli.maximo.skd.app.virtual: // SKDEditConstraintRemote public final class SKDEditConstraint_Stub extends RemoteStub implements SKDEditConstraintRemote, NonPersistentMboRemote, MboRemote { public SKDEditConstraint_Stub(RemoteRef remoteref) { super(remoteref); } public void add() throws RemoteException, MXException { try { super.ref.invoke(this, $method_add_0, null, 0x6749c29a5e0a9973L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void addMboSetForRequiredCheck(MboSetRemote mbosetremote) throws RemoteException { try { super.ref.invoke(this, $method_addMboSetForRequiredCheck_1, new Object[] { mbosetremote }, 0xb5e99da1ad7d9609L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void addToDeleteForInsertList(String s) throws RemoteException { try { super.ref.invoke(this, $method_addToDeleteForInsertList_2, new Object[] { s }, 0xa3a1f2d3f47f6d9bL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboRemote blindCopy(MboSetRemote mbosetremote) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_blindCopy_3, new Object[] { mbosetremote }, 0xc83af2cedd35733cL); return (MboRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void checkMethodAccess(String s) throws RemoteException, MXException { try { super.ref.invoke(this, $method_checkMethodAccess_4, new Object[] { s }, 0x79b683fcdec5d69dL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } static Class _mthclass$(String s) { try { return Class.forName(s); } catch(ClassNotFoundException classnotfoundexception) { throw new NoClassDefFoundError(classnotfoundexception.getMessage()); } } public void clear() throws RemoteException, MXException { try { super.ref.invoke(this, $method_clear_5, null, 0x98428fc5bfb912f5L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboRemote copy() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_copy_6, null, 0x66195ed5a800d43aL); return (MboRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboRemote copy(MboSetRemote mbosetremote) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_copy_7, new Object[] { mbosetremote }, 0xc6dbdaecec183e5dL); return (MboRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboRemote copy(MboSetRemote mbosetremote, long l) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_copy_8, new Object[] { mbosetremote, new Long(l) }, 0x55392bc3a4b41450L); return (MboRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboRemote copyFake(MboSetRemote mbosetremote) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_copyFake_9, new Object[] { mbosetremote }, 0xe632bb35f4042faL); return (MboRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void copyValue(MboRemote mboremote, String s, String s1, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_copyValue_10, new Object[] { mboremote, s, s1, new Long(l) }, 0x1c92d46e4605fe28L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void copyValue(MboRemote mboremote, String as[], String as1[], long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_copyValue_11, new Object[] { mboremote, as, as1, new Long(l) }, 0xb18b1214277a2bbL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboRemote createComm() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_createComm_12, null, 0x5895303c90239847L); return (MboRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void delete() throws RemoteException, MXException { try { super.ref.invoke(this, $method_delete_13, null, 0x4cab97a58e40e30aL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void delete(long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_delete_14, new Object[] { new Long(l) }, 0xc43201bb54694ee6L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboRemote duplicate() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_duplicate_15, null, 0x10f946a96654345bL); return (MboRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean evaluateCondition(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_evaluateCondition_16, new Object[] { s }, 0x7044b51580631abfL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public HashMap evaluateCtrlConditions(HashSet hashset) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_evaluateCtrlConditions_17, new Object[] { hashset }, 0xf0995791a7fa9d3eL); return (HashMap)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public HashMap evaluateCtrlConditions(HashSet hashset, String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_evaluateCtrlConditions_18, new Object[] { hashset, s }, 0xa3a40170a8e99252L); return (HashMap)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean excludeObjectForPropagate(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_excludeObjectForPropagate_19, new Object[] { s }, 0x287c0543c139c0e6L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void generateAutoKey() throws RemoteException, MXException { try { super.ref.invoke(this, $method_generateAutoKey_20, null, 0x1cba5591f2557f28L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean getBoolean(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getBoolean_21, new Object[] { s }, 0xe93a05915d3787cfL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public byte getByte(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getByte_22, new Object[] { s }, 0x2beff28ad9d4b6afL); return ((Byte)obj).byteValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public byte[] getBytes(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getBytes_23, new Object[] { s }, 0xd59b64efb2c65f25L); return (byte[])obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public Object[] getCommLogOwnerNameAndUniqueId() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getCommLogOwnerNameAndUniqueId_24, null, 0x165b269de6ed1ce7L); return (Object[])obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public Object getDatabaseValue(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getDatabaseValue_25, new Object[] { s }, 0xdd3c434e57379d42L); return obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public Date getDate(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getDate_26, new Object[] { s }, 0x5a1771df885620L); return (Date)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public Vector getDeleteForInsertList() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getDeleteForInsertList_27, null, 0xa4540446ed0136b2L); return (Vector)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public int getDocLinksCount() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getDocLinksCount_28, null, 0x21005263373d9a4cL); return ((Integer)obj).intValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String[] getDomainIDs(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getDomainIDs_29, new Object[] { s }, 0xb548f55a7317a91dL); return (String[])obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public double getDouble(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getDouble_30, new Object[] { s }, 0x9cf59b24e2f96e00L); return ((Double)obj).doubleValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote getExistingMboSet(String s) throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getExistingMboSet_31, new Object[] { s }, 0xdf775a4f6e45e01eL); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public long getFlags() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getFlags_32, null, 0x7b4132761a4c3aa8L); return ((Long)obj).longValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public float getFloat(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getFloat_33, new Object[] { s }, 0xc04518f13d0d5402L); return ((Float)obj).floatValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MaxType getInitialValue(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getInitialValue_34, new Object[] { s }, 0xc6476e27765fac55L); return (MaxType)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getInsertCompanySetId() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getInsertCompanySetId_35, null, 0x5003ad50d7c78d4bL); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getInsertItemSetId() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getInsertItemSetId_36, null, 0x5969122207966feL); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getInsertOrganization() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getInsertOrganization_37, null, 0x18aac90dc397f34bL); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getInsertSite() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getInsertSite_38, null, 0x19f00633ecb0a4e7L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public int getInt(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getInt_39, new Object[] { s }, 0x5aecea2bfdc0a509L); return ((Integer)obj).intValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public KeyValue getKeyValue() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getKeyValue_40, null, 0x19e1ed789c8c28b4L); return (KeyValue)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getLinesRelationship() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getLinesRelationship_41, null, 0x6961b92b382e419eL); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote getList(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getList_42, new Object[] { s }, 0xeefa36ddd714cd51L); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public long getLong(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getLong_43, new Object[] { s }, 0xf96c396d0804bf0L); return ((Long)obj).longValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MXTransaction getMXTransaction() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getMXTransaction_44, null, 0x4e16163bc0a1eb36L); return (MXTransaction)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getMatchingAttr(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMatchingAttr_45, new Object[] { s }, 0xfad38590b70f94eeL); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getMatchingAttr(String s, String s1) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMatchingAttr_46, new Object[] { s, s1 }, 0x7b0877d9b2623aaeL); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public Object[] getMatchingAttrs(String s, String s1) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMatchingAttrs_47, new Object[] { s, s1 }, 0x9bf15d77d318684fL); return (Object[])obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MaxMessage getMaxMessage(String s, String s1) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMaxMessage_48, new Object[] { s, s1 }, 0xe76d1ca694a8a253L); return (MaxMessage)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboData getMboData(String as[]) throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getMboData_49, new Object[] { as }, 0xb9f8f354e53efb74L); return (MboData)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public Vector getMboDataSet(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboDataSet_50, new Object[] { s }, 0x991374cc4f953ce7L); return (Vector)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MaxType getMboInitialValue(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboInitialValue_51, new Object[] { s }, 0x3ab3244bc86233faL); return (MaxType)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public List getMboList(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboList_52, new Object[] { s }, 0x16a4d8243839f2b7L); return (List)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote getMboSet(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboSet_53, new Object[] { s }, 0x3c68bcd82a6f274bL); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote getMboSet(String s, String s1) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboSet_54, new Object[] { s, s1 }, 0xf1e4177b3613e0aeL); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote getMboSet(String s, String s1, String s2) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboSet_55, new Object[] { s, s1, s2 }, 0xd9c777a9e7146583L); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboValueData getMboValueData(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboValueData_56, new Object[] { s }, 0xe18de0e50627dd74L); return (MboValueData)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboValueData getMboValueData(String s, boolean flag) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboValueData_57, new Object[] { s, flag ? Boolean.TRUE : Boolean.FALSE }, 0xd2cc37324302ab64L); return (MboValueData)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboValueData[] getMboValueData(String as[]) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboValueData_58, new Object[] { as }, 0xd5b8028b7eb8e4a8L); return (MboValueData[])obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboValueInfoStatic getMboValueInfoStatic(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboValueInfoStatic_59, new Object[] { s }, 0xc3ef8a793a0590f9L); return (MboValueInfoStatic)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboValueInfoStatic[] getMboValueInfoStatic(String as[]) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getMboValueInfoStatic_60, new Object[] { as }, 0xfda4802acffc6145L); return (MboValueInfoStatic[])obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getMessage(String s, String s1) throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getMessage_61, new Object[] { s, s1 }, 0xb8fc271bd83eaf93L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getMessage(String s, String s1, Object obj) throws RemoteException { try { Object obj1 = super.ref.invoke(this, $method_getMessage_62, new Object[] { s, s1, obj }, 0x456c577220b6fd64L); return (String)obj1; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getMessage(String s, String s1, Object aobj[]) throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getMessage_63, new Object[] { s, s1, aobj }, 0xb78c7648915b9578L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getMessage(MXException mxexception) throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getMessage_64, new Object[] { mxexception }, 0xc30bda921ed593fbL); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getName() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getName_65, null, 0x57aafb80745d9046L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getOrgForGL(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getOrgForGL_66, new Object[] { s }, 0xfbdef2e1b2e866f1L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getOrgSiteForMaxvar(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getOrgSiteForMaxvar_67, new Object[] { s }, 0x5465f2b82d66c8a5L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboRemote getOwner() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getOwner_68, null, 0x1fc88db7d13ffc97L); return (MboRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean getPropagateKeyFlag() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getPropagateKeyFlag_69, null, 0xb32470b8db6fb963L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getRecordIdentifer() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getRecordIdentifer_70, null, 0x9eb131a372a768c2L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String[] getSiteOrg() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getSiteOrg_71, null, 0x4f7af51063d9f896L); return (String[])obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getString(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getString_72, new Object[] { s }, 0x46515a53daaf0d59L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getString(String s, String s1) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getString_73, new Object[] { s, s1 }, 0x40f7a25dbd2068c8L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getStringInBaseLanguage(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getStringInBaseLanguage_74, new Object[] { s }, 0xe956a9bf08082f37L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getStringInSpecificLocale(String s, Locale locale, TimeZone timezone) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getStringInSpecificLocale_75, new Object[] { s, locale, timezone }, 0x74192668863db14eL); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getStringTransparent(String s, String s1) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getStringTransparent_76, new Object[] { s, s1 }, 0xccb6db5d8582bcc8L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote getThisMboSet() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getThisMboSet_77, null, 0x87e9757284752dc3L); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getUniqueIDName() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getUniqueIDName_78, null, 0xc32d9b94b797ea84L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public long getUniqueIDValue() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getUniqueIDValue_79, null, 0x21a1f8fab4520e85L); return ((Long)obj).longValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public UserInfo getUserInfo() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_getUserInfo_80, null, 0xa47b362578c46913L); return (UserInfo)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public String getUserName() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_getUserName_81, null, 0x6b5be85d8410cc2L); return (String)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean hasHierarchyLink() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_hasHierarchyLink_82, null, 0xb60bad33a76178beL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isAutoKeyed(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_isAutoKeyed_83, new Object[] { s }, 0xf3cc796ed199f55eL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isBasedOn(String s) throws RemoteException { try { Object obj = super.ref.invoke(this, $method_isBasedOn_84, new Object[] { s }, 0x560f6ed66c10afbaL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isFlagSet(long l) throws RemoteException { try { Object obj = super.ref.invoke(this, $method_isFlagSet_85, new Object[] { new Long(l) }, 0x9da1803fc3bb3fafL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isForDM() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_isForDM_86, null, 0x27dfb2841844c6cdL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isModified() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_isModified_87, null, 0x4f389a2eb8d3a2adL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isModified(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_isModified_88, new Object[] { s }, 0x3fa28467200239caL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isNew() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_isNew_89, null, 0x59695bdf263c3969L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isNull(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_isNull_90, new Object[] { s }, 0xbe9a50811c07d0e5L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isSelected() throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_isSelected_91, null, 0x3b19194797e3f887L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean isZombie() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_isZombie_92, null, 0x3676eeabd5c52054L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void propagateKeyValue(String s, String s1) throws RemoteException, MXException { try { super.ref.invoke(this, $method_propagateKeyValue_93, new Object[] { s, s1 }, 0x51051a6e338344f9L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void rollbackToCheckpoint() throws RemoteException, MXException { try { super.ref.invoke(this, $method_rollbackToCheckpoint_94, null, 0x43c59ba7e1ce7961L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void select() throws RemoteException, MXException { try { super.ref.invoke(this, $method_select_95, null, 0xeb3e1a5088a80f46L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setApplicationError(String s, ApplicationError applicationerror) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setApplicationError_96, new Object[] { s, applicationerror }, 0x57e1d69e173108f8L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setApplicationRequired(String s, boolean flag) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setApplicationRequired_97, new Object[] { s, flag ? Boolean.TRUE : Boolean.FALSE }, 0x7e412bc067e58f83L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setCopyDefaults() throws RemoteException, MXException { try { super.ref.invoke(this, $method_setCopyDefaults_98, null, 0x853f6f0b3430beb7L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setDeleted(boolean flag) throws RemoteException { try { super.ref.invoke(this, $method_setDeleted_99, new Object[] { flag ? Boolean.TRUE : Boolean.FALSE }, 0xe94456ecd31b2370L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setESigFieldModified(boolean flag) throws RemoteException { try { super.ref.invoke(this, $method_setESigFieldModified_100, new Object[] { flag ? Boolean.TRUE : Boolean.FALSE }, 0xbad7af4e8f9d556eL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFieldFlag(String s, long l, boolean flag) throws RemoteException { try { super.ref.invoke(this, $method_setFieldFlag_101, new Object[] { s, new Long(l), flag ? Boolean.TRUE : Boolean.FALSE }, 0xb3434ce0cd823ea8L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFieldFlag(String s, long l, boolean flag, MXException mxexception) throws RemoteException { try { super.ref.invoke(this, $method_setFieldFlag_102, new Object[] { s, new Long(l), flag ? Boolean.TRUE : Boolean.FALSE, mxexception }, 0x5015a7b6b907a0d2L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFieldFlag(String as[], long l, boolean flag) throws RemoteException { try { super.ref.invoke(this, $method_setFieldFlag_103, new Object[] { as, new Long(l), flag ? Boolean.TRUE : Boolean.FALSE }, 0xb52501be391f8ac7L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFieldFlag(String as[], long l, boolean flag, MXException mxexception) throws RemoteException { try { super.ref.invoke(this, $method_setFieldFlag_104, new Object[] { as, new Long(l), flag ? Boolean.TRUE : Boolean.FALSE, mxexception }, 0xeeb7f2168953cd7cL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFieldFlag(String as[], boolean flag, long l, boolean flag1) throws RemoteException { try { super.ref.invoke(this, $method_setFieldFlag_105, new Object[] { as, flag ? Boolean.TRUE : Boolean.FALSE, new Long(l), flag1 ? Boolean.TRUE : Boolean.FALSE }, 0x1470a5cc23457ea4L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFieldFlag(String as[], boolean flag, long l, boolean flag1, MXException mxexception) throws RemoteException { try { super.ref.invoke(this, $method_setFieldFlag_106, new Object[] { as, flag ? Boolean.TRUE : Boolean.FALSE, new Long(l), flag1 ? Boolean.TRUE : Boolean.FALSE, mxexception }, 0xef36c4c0b82d3b5cL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFieldFlags(String s, long l) throws RemoteException { try { super.ref.invoke(this, $method_setFieldFlags_107, new Object[] { s, new Long(l) }, 0x161535ab1e656966L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFlag(long l, boolean flag) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setFlag_108, new Object[] { new Long(l), flag ? Boolean.TRUE : Boolean.FALSE }, 0x71244dd35a8b1156L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFlag(long l, boolean flag, MXException mxexception) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setFlag_109, new Object[] { new Long(l), flag ? Boolean.TRUE : Boolean.FALSE, mxexception }, 0xf81d9ab0e895941bL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception1) { throw mxexception1; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setFlags(long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setFlags_110, new Object[] { new Long(l) }, 0x770060303ea2e67fL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setForDM(boolean flag) throws RemoteException { try { super.ref.invoke(this, $method_setForDM_111, new Object[] { flag ? Boolean.TRUE : Boolean.FALSE }, 0xff7c1f95a4a9c28dL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setMLValue(String s, String s1, String s2, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setMLValue_112, new Object[] { s, s1, s2, new Long(l) }, 0x5a06ad2a822a7f6cL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setModified(boolean flag) throws RemoteException { try { super.ref.invoke(this, $method_setModified_113, new Object[] { flag ? Boolean.TRUE : Boolean.FALSE }, 0xe1c54feb23f93776L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setNewMbo(boolean flag) throws RemoteException { try { super.ref.invoke(this, $method_setNewMbo_114, new Object[] { flag ? Boolean.TRUE : Boolean.FALSE }, 0x8c627182753e03f7L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setPropagateKeyFlag(boolean flag) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setPropagateKeyFlag_115, new Object[] { flag ? Boolean.TRUE : Boolean.FALSE }, 0x8cad4ce8f33491adL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setPropagateKeyFlag(String as[], boolean flag) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setPropagateKeyFlag_116, new Object[] { as, flag ? Boolean.TRUE : Boolean.FALSE }, 0xd65fbef6ef485b4cL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setReferencedMbo(String s, Mbo mbo) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setReferencedMbo_117, new Object[] { s, mbo }, 0x9d94b9f601642780L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, byte byte0) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_118, new Object[] { s, new Byte(byte0) }, 0x2d6355541fad504eL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, byte byte0, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_119, new Object[] { s, new Byte(byte0), new Long(l) }, 0xfc9d307dd36ca2f0L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, double d) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_120, new Object[] { s, new Double(d) }, 0x9791e4ccb4fde4e5L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, double d, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_121, new Object[] { s, new Double(d), new Long(l) }, 0xfda995212571a508L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, float f) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_122, new Object[] { s, new Float(f) }, 0xd8ed0447a00be3dcL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, float f, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_123, new Object[] { s, new Float(f), new Long(l) }, 0x637e4d6ddcc69cb5L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, int i) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_124, new Object[] { s, new Integer(i) }, 0x7ad2c6abc5b498e5L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, int i, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_125, new Object[] { s, new Integer(i), new Long(l) }, 0x376cbbfddb82bb6aL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_126, new Object[] { s, new Long(l) }, 0x7fd358283c002704L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, long l, long l1) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_127, new Object[] { s, new Long(l), new Long(l1) }, 0x5f0b86ab48ed6566L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, String s1) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_128, new Object[] { s, s1 }, 0xd8fb081e0d5b6d6dL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, String s1, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_129, new Object[] { s, s1, new Long(l) }, 0xc4dc351851510ae7L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, Date date) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_130, new Object[] { s, date }, 0xdb7db314fcdcdfe7L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, Date date, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_131, new Object[] { s, date, new Long(l) }, 0x6e9ef406351a23dcL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, MboRemote mboremote) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_132, new Object[] { s, mboremote }, 0xcdc17b80e71b87b8L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, MboSetRemote mbosetremote) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_133, new Object[] { s, mbosetremote }, 0xcee96756ce084a4dL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, MaxType maxtype, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_134, new Object[] { s, maxtype, new Long(l) }, 0xf80ed1b166c03499L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, short word0) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_135, new Object[] { s, new Short(word0) }, 0xf7c811c0bf753aefL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, short word0, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_136, new Object[] { s, new Short(word0), new Long(l) }, 0xa91a2fcec40d56e3L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, boolean flag) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_137, new Object[] { s, flag ? Boolean.TRUE : Boolean.FALSE }, 0x45408a6c31ce37c7L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, boolean flag, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_138, new Object[] { s, flag ? Boolean.TRUE : Boolean.FALSE, new Long(l) }, 0x724e315b463c27f7L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, byte abyte0[]) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_139, new Object[] { s, abyte0 }, 0xb6d921948b94b5e4L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValue(String s, byte abyte0[], long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValue_140, new Object[] { s, abyte0, new Long(l) }, 0xf2db19b82c5c1d2L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValueNull(String s) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValueNull_141, new Object[] { s }, 0xfaf7eb3d18a18b76L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void setValueNull(String s, long l) throws RemoteException, MXException { try { super.ref.invoke(this, $method_setValueNull_142, new Object[] { s, new Long(l) }, 0x533f38da5a58a82eL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void sigOptionAccessAuthorized(String s) throws RemoteException, MXException { try { super.ref.invoke(this, $method_sigOptionAccessAuthorized_143, new Object[] { s }, 0x3c90cde925c7013bL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean sigopGranted(String s) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_sigopGranted_144, new Object[] { s }, 0x2579f697776cdad1L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean sigopGranted(String s, String s1) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_sigopGranted_145, new Object[] { s, s1 }, 0x4a5a2aede9b16adL); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public HashMap sigopGranted(Set set) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_sigopGranted_146, new Object[] { set }, 0x50ef6814fd294e76L); return (HashMap)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote smartFill(String s, String s1, boolean flag) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_smartFill_147, new Object[] { s, s1, flag ? Boolean.TRUE : Boolean.FALSE }, 0xf30535e791d02bc2L); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote smartFind(String s, String s1, String s2, boolean flag) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_smartFind_148, new Object[] { s, s1, s2, flag ? Boolean.TRUE : Boolean.FALSE }, 0xebcad48523503c55L); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote smartFind(String s, String s1, boolean flag) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_smartFind_149, new Object[] { s, s1, flag ? Boolean.TRUE : Boolean.FALSE }, 0x88c1f9b7d418726L); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote smartFindByObjectName(String s, String s1, String s2, boolean flag) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_smartFindByObjectName_150, new Object[] { s, s1, s2, flag ? Boolean.TRUE : Boolean.FALSE }, 0x7f50d546200aa042L); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote smartFindByObjectName(String s, String s1, String s2, boolean flag, String as[][]) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_smartFindByObjectName_151, new Object[] { s, s1, s2, flag ? Boolean.TRUE : Boolean.FALSE, as }, 0xbd0c2c47174bf13eL); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public MboSetRemote smartFindByObjectNameDirect(String s, String s1, String s2, boolean flag) throws RemoteException, MXException { try { Object obj = super.ref.invoke(this, $method_smartFindByObjectNameDirect_152, new Object[] { s, s1, s2, flag ? Boolean.TRUE : Boolean.FALSE }, 0xa3da416a4d04115eL); return (MboSetRemote)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void startCheckpoint() throws RemoteException, MXException { try { super.ref.invoke(this, $method_startCheckpoint_153, null, 0x707ba8f759a8a21fL); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean thisToBeUpdated() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_thisToBeUpdated_154, null, 0x6eb10c508aebf685L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean toBeAdded() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_toBeAdded_155, null, 0x89e8c5e2b14c7053L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean toBeDeleted() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_toBeDeleted_156, null, 0x5ba55962b4f9d419L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean toBeSaved() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_toBeSaved_157, null, 0xc3d81d241c9847b4L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean toBeUpdated() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_toBeUpdated_158, null, 0x6bdd17cc12a0b157L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public boolean toBeValidated() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_toBeValidated_159, null, 0xa98b943ad32bf736L); return ((Boolean)obj).booleanValue(); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void undelete() throws RemoteException, MXException { try { super.ref.invoke(this, $method_undelete_160, null, 0xd01d0306941bd640L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void unselect() throws RemoteException, MXException { try { super.ref.invoke(this, $method_unselect_161, null, 0xc7fd3073d99343a0L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public void validate() throws RemoteException, MXException { try { super.ref.invoke(this, $method_validate_162, null, 0x8bdd6a44fb1e3cf7L); } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(MXException mxexception) { throw mxexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } public Hashtable validateAttributes() throws RemoteException { try { Object obj = super.ref.invoke(this, $method_validateAttributes_163, null, 0x586e745d27292ec0L); return (Hashtable)obj; } catch(RuntimeException runtimeexception) { throw runtimeexception; } catch(RemoteException remoteexception) { throw remoteexception; } catch(Exception exception) { throw new UnexpectedException("undeclared checked exception", exception); } } private static final long serialVersionUID = 2L; private static Method $method_add_0; private static Method $method_addMboSetForRequiredCheck_1; private static Method $method_addToDeleteForInsertList_2; private static Method $method_blindCopy_3; private static Method $method_checkMethodAccess_4; private static Method $method_clear_5; private static Method $method_copy_6; private static Method $method_copy_7; private static Method $method_copy_8; private static Method $method_copyFake_9; private static Method $method_copyValue_10; private static Method $method_copyValue_11; private static Method $method_createComm_12; private static Method $method_delete_13; private static Method $method_delete_14; private static Method $method_duplicate_15; private static Method $method_evaluateCondition_16; private static Method $method_evaluateCtrlConditions_17; private static Method $method_evaluateCtrlConditions_18; private static Method $method_excludeObjectForPropagate_19; private static Method $method_generateAutoKey_20; private static Method $method_getBoolean_21; private static Method $method_getByte_22; private static Method $method_getBytes_23; private static Method $method_getCommLogOwnerNameAndUniqueId_24; private static Method $method_getDatabaseValue_25; private static Method $method_getDate_26; private static Method $method_getDeleteForInsertList_27; private static Method $method_getDocLinksCount_28; private static Method $method_getDomainIDs_29; private static Method $method_getDouble_30; private static Method $method_getExistingMboSet_31; private static Method $method_getFlags_32; private static Method $method_getFloat_33; private static Method $method_getInitialValue_34; private static Method $method_getInsertCompanySetId_35; private static Method $method_getInsertItemSetId_36; private static Method $method_getInsertOrganization_37; private static Method $method_getInsertSite_38; private static Method $method_getInt_39; private static Method $method_getKeyValue_40; private static Method $method_getLinesRelationship_41; private static Method $method_getList_42; private static Method $method_getLong_43; private static Method $method_getMXTransaction_44; private static Method $method_getMatchingAttr_45; private static Method $method_getMatchingAttr_46; private static Method $method_getMatchingAttrs_47; private static Method $method_getMaxMessage_48; private static Method $method_getMboData_49; private static Method $method_getMboDataSet_50; private static Method $method_getMboInitialValue_51; private static Method $method_getMboList_52; private static Method $method_getMboSet_53; private static Method $method_getMboSet_54; private static Method $method_getMboSet_55; private static Method $method_getMboValueData_56; private static Method $method_getMboValueData_57; private static Method $method_getMboValueData_58; private static Method $method_getMboValueInfoStatic_59; private static Method $method_getMboValueInfoStatic_60; private static Method $method_getMessage_61; private static Method $method_getMessage_62; private static Method $method_getMessage_63; private static Method $method_getMessage_64; private static Method $method_getName_65; private static Method $method_getOrgForGL_66; private static Method $method_getOrgSiteForMaxvar_67; private static Method $method_getOwner_68; private static Method $method_getPropagateKeyFlag_69; private static Method $method_getRecordIdentifer_70; private static Method $method_getSiteOrg_71; private static Method $method_getString_72; private static Method $method_getString_73; private static Method $method_getStringInBaseLanguage_74; private static Method $method_getStringInSpecificLocale_75; private static Method $method_getStringTransparent_76; private static Method $method_getThisMboSet_77; private static Method $method_getUniqueIDName_78; private static Method $method_getUniqueIDValue_79; private static Method $method_getUserInfo_80; private static Method $method_getUserName_81; private static Method $method_hasHierarchyLink_82; private static Method $method_isAutoKeyed_83; private static Method $method_isBasedOn_84; private static Method $method_isFlagSet_85; private static Method $method_isForDM_86; private static Method $method_isModified_87; private static Method $method_isModified_88; private static Method $method_isNew_89; private static Method $method_isNull_90; private static Method $method_isSelected_91; private static Method $method_isZombie_92; private static Method $method_propagateKeyValue_93; private static Method $method_rollbackToCheckpoint_94; private static Method $method_select_95; private static Method $method_setApplicationError_96; private static Method $method_setApplicationRequired_97; private static Method $method_setCopyDefaults_98; private static Method $method_setDeleted_99; private static Method $method_setESigFieldModified_100; private static Method $method_setFieldFlag_101; private static Method $method_setFieldFlag_102; private static Method $method_setFieldFlag_103; private static Method $method_setFieldFlag_104; private static Method $method_setFieldFlag_105; private static Method $method_setFieldFlag_106; private static Method $method_setFieldFlags_107; private static Method $method_setFlag_108; private static Method $method_setFlag_109; private static Method $method_setFlags_110; private static Method $method_setForDM_111; private static Method $method_setMLValue_112; private static Method $method_setModified_113; private static Method $method_setNewMbo_114; private static Method $method_setPropagateKeyFlag_115; private static Method $method_setPropagateKeyFlag_116; private static Method $method_setReferencedMbo_117; private static Method $method_setValue_118; private static Method $method_setValue_119; private static Method $method_setValue_120; private static Method $method_setValue_121; private static Method $method_setValue_122; private static Method $method_setValue_123; private static Method $method_setValue_124; private static Method $method_setValue_125; private static Method $method_setValue_126; private static Method $method_setValue_127; private static Method $method_setValue_128; private static Method $method_setValue_129; private static Method $method_setValue_130; private static Method $method_setValue_131; private static Method $method_setValue_132; private static Method $method_setValue_133; private static Method $method_setValue_134; private static Method $method_setValue_135; private static Method $method_setValue_136; private static Method $method_setValue_137; private static Method $method_setValue_138; private static Method $method_setValue_139; private static Method $method_setValue_140; private static Method $method_setValueNull_141; private static Method $method_setValueNull_142; private static Method $method_sigOptionAccessAuthorized_143; private static Method $method_sigopGranted_144; private static Method $method_sigopGranted_145; private static Method $method_sigopGranted_146; private static Method $method_smartFill_147; private static Method $method_smartFind_148; private static Method $method_smartFind_149; private static Method $method_smartFindByObjectName_150; private static Method $method_smartFindByObjectName_151; private static Method $method_smartFindByObjectNameDirect_152; private static Method $method_startCheckpoint_153; private static Method $method_thisToBeUpdated_154; private static Method $method_toBeAdded_155; private static Method $method_toBeDeleted_156; private static Method $method_toBeSaved_157; private static Method $method_toBeUpdated_158; private static Method $method_toBeValidated_159; private static Method $method_undelete_160; private static Method $method_unselect_161; private static Method $method_validate_162; private static Method $method_validateAttributes_163; static { try { $method_add_0 = (psdi.mbo.MboRemote.class).getMethod("add", new Class[0]); $method_addMboSetForRequiredCheck_1 = (psdi.mbo.MboRemote.class).getMethod("addMboSetForRequiredCheck", new Class[] { psdi.mbo.MboSetRemote.class }); $method_addToDeleteForInsertList_2 = (psdi.mbo.MboRemote.class).getMethod("addToDeleteForInsertList", new Class[] { java.lang.String.class }); $method_blindCopy_3 = (psdi.mbo.MboRemote.class).getMethod("blindCopy", new Class[] { psdi.mbo.MboSetRemote.class }); $method_checkMethodAccess_4 = (psdi.mbo.MboRemote.class).getMethod("checkMethodAccess", new Class[] { java.lang.String.class }); $method_clear_5 = (psdi.mbo.MboRemote.class).getMethod("clear", new Class[0]); $method_copy_6 = (psdi.mbo.MboRemote.class).getMethod("copy", new Class[0]); $method_copy_7 = (psdi.mbo.MboRemote.class).getMethod("copy", new Class[] { psdi.mbo.MboSetRemote.class }); $method_copy_8 = (psdi.mbo.MboRemote.class).getMethod("copy", new Class[] { psdi.mbo.MboSetRemote.class, Long.TYPE }); $method_copyFake_9 = (psdi.mbo.MboRemote.class).getMethod("copyFake", new Class[] { psdi.mbo.MboSetRemote.class }); $method_copyValue_10 = (psdi.mbo.MboRemote.class).getMethod("copyValue", new Class[] { psdi.mbo.MboRemote.class, java.lang.String.class, java.lang.String.class, Long.TYPE }); $method_copyValue_11 = (psdi.mbo.MboRemote.class).getMethod("copyValue", new Class[] { psdi.mbo.MboRemote.class, java.lang.String[].class, java.lang.String[].class, Long.TYPE }); $method_createComm_12 = (psdi.mbo.MboRemote.class).getMethod("createComm", new Class[0]); $method_delete_13 = (psdi.mbo.MboRemote.class).getMethod("delete", new Class[0]); $method_delete_14 = (psdi.mbo.MboRemote.class).getMethod("delete", new Class[] { Long.TYPE }); $method_duplicate_15 = (psdi.mbo.MboRemote.class).getMethod("duplicate", new Class[0]); $method_evaluateCondition_16 = (psdi.mbo.MboRemote.class).getMethod("evaluateCondition", new Class[] { java.lang.String.class }); $method_evaluateCtrlConditions_17 = (psdi.mbo.MboRemote.class).getMethod("evaluateCtrlConditions", new Class[] { java.util.HashSet.class }); $method_evaluateCtrlConditions_18 = (psdi.mbo.MboRemote.class).getMethod("evaluateCtrlConditions", new Class[] { java.util.HashSet.class, java.lang.String.class }); $method_excludeObjectForPropagate_19 = (psdi.mbo.MboRemote.class).getMethod("excludeObjectForPropagate", new Class[] { java.lang.String.class }); $method_generateAutoKey_20 = (psdi.mbo.MboRemote.class).getMethod("generateAutoKey", new Class[0]); $method_getBoolean_21 = (psdi.mbo.MboRemote.class).getMethod("getBoolean", new Class[] { java.lang.String.class }); $method_getByte_22 = (psdi.mbo.MboRemote.class).getMethod("getByte", new Class[] { java.lang.String.class }); $method_getBytes_23 = (psdi.mbo.MboRemote.class).getMethod("getBytes", new Class[] { java.lang.String.class }); $method_getCommLogOwnerNameAndUniqueId_24 = (psdi.mbo.MboRemote.class).getMethod("getCommLogOwnerNameAndUniqueId", new Class[0]); $method_getDatabaseValue_25 = (psdi.mbo.MboRemote.class).getMethod("getDatabaseValue", new Class[] { java.lang.String.class }); $method_getDate_26 = (psdi.mbo.MboRemote.class).getMethod("getDate", new Class[] { java.lang.String.class }); $method_getDeleteForInsertList_27 = (psdi.mbo.MboRemote.class).getMethod("getDeleteForInsertList", new Class[0]); $method_getDocLinksCount_28 = (psdi.mbo.MboRemote.class).getMethod("getDocLinksCount", new Class[0]); $method_getDomainIDs_29 = (psdi.mbo.MboRemote.class).getMethod("getDomainIDs", new Class[] { java.lang.String.class }); $method_getDouble_30 = (psdi.mbo.MboRemote.class).getMethod("getDouble", new Class[] { java.lang.String.class }); $method_getExistingMboSet_31 = (psdi.mbo.MboRemote.class).getMethod("getExistingMboSet", new Class[] { java.lang.String.class }); $method_getFlags_32 = (psdi.mbo.MboRemote.class).getMethod("getFlags", new Class[0]); $method_getFloat_33 = (psdi.mbo.MboRemote.class).getMethod("getFloat", new Class[] { java.lang.String.class }); $method_getInitialValue_34 = (psdi.mbo.MboRemote.class).getMethod("getInitialValue", new Class[] { java.lang.String.class }); $method_getInsertCompanySetId_35 = (psdi.mbo.MboRemote.class).getMethod("getInsertCompanySetId", new Class[0]); $method_getInsertItemSetId_36 = (psdi.mbo.MboRemote.class).getMethod("getInsertItemSetId", new Class[0]); $method_getInsertOrganization_37 = (psdi.mbo.MboRemote.class).getMethod("getInsertOrganization", new Class[0]); $method_getInsertSite_38 = (psdi.mbo.MboRemote.class).getMethod("getInsertSite", new Class[0]); $method_getInt_39 = (psdi.mbo.MboRemote.class).getMethod("getInt", new Class[] { java.lang.String.class }); $method_getKeyValue_40 = (psdi.mbo.MboRemote.class).getMethod("getKeyValue", new Class[0]); $method_getLinesRelationship_41 = (psdi.mbo.MboRemote.class).getMethod("getLinesRelationship", new Class[0]); $method_getList_42 = (psdi.mbo.MboRemote.class).getMethod("getList", new Class[] { java.lang.String.class }); $method_getLong_43 = (psdi.mbo.MboRemote.class).getMethod("getLong", new Class[] { java.lang.String.class }); $method_getMXTransaction_44 = (psdi.mbo.MboRemote.class).getMethod("getMXTransaction", new Class[0]); $method_getMatchingAttr_45 = (psdi.mbo.MboRemote.class).getMethod("getMatchingAttr", new Class[] { java.lang.String.class }); $method_getMatchingAttr_46 = (psdi.mbo.MboRemote.class).getMethod("getMatchingAttr", new Class[] { java.lang.String.class, java.lang.String.class }); $method_getMatchingAttrs_47 = (psdi.mbo.MboRemote.class).getMethod("getMatchingAttrs", new Class[] { java.lang.String.class, java.lang.String.class }); $method_getMaxMessage_48 = (psdi.mbo.MboRemote.class).getMethod("getMaxMessage", new Class[] { java.lang.String.class, java.lang.String.class }); $method_getMboData_49 = (psdi.mbo.MboRemote.class).getMethod("getMboData", new Class[] { java.lang.String[].class }); $method_getMboDataSet_50 = (psdi.mbo.MboRemote.class).getMethod("getMboDataSet", new Class[] { java.lang.String.class }); $method_getMboInitialValue_51 = (psdi.mbo.MboRemote.class).getMethod("getMboInitialValue", new Class[] { java.lang.String.class }); $method_getMboList_52 = (psdi.mbo.MboRemote.class).getMethod("getMboList", new Class[] { java.lang.String.class }); $method_getMboSet_53 = (psdi.mbo.MboRemote.class).getMethod("getMboSet", new Class[] { java.lang.String.class }); $method_getMboSet_54 = (psdi.mbo.MboRemote.class).getMethod("getMboSet", new Class[] { java.lang.String.class, java.lang.String.class }); $method_getMboSet_55 = (psdi.mbo.MboRemote.class).getMethod("getMboSet", new Class[] { java.lang.String.class, java.lang.String.class, java.lang.String.class }); $method_getMboValueData_56 = (psdi.mbo.MboRemote.class).getMethod("getMboValueData", new Class[] { java.lang.String.class }); $method_getMboValueData_57 = (psdi.mbo.MboRemote.class).getMethod("getMboValueData", new Class[] { java.lang.String.class, Boolean.TYPE }); $method_getMboValueData_58 = (psdi.mbo.MboRemote.class).getMethod("getMboValueData", new Class[] { java.lang.String[].class }); $method_getMboValueInfoStatic_59 = (psdi.mbo.MboRemote.class).getMethod("getMboValueInfoStatic", new Class[] { java.lang.String.class }); $method_getMboValueInfoStatic_60 = (psdi.mbo.MboRemote.class).getMethod("getMboValueInfoStatic", new Class[] { java.lang.String[].class }); $method_getMessage_61 = (psdi.mbo.MboRemote.class).getMethod("getMessage", new Class[] { java.lang.String.class, java.lang.String.class }); $method_getMessage_62 = (psdi.mbo.MboRemote.class).getMethod("getMessage", new Class[] { java.lang.String.class, java.lang.String.class, java.lang.Object.class }); $method_getMessage_63 = (psdi.mbo.MboRemote.class).getMethod("getMessage", new Class[] { java.lang.String.class, java.lang.String.class, java.lang.Object[].class }); $method_getMessage_64 = (psdi.mbo.MboRemote.class).getMethod("getMessage", new Class[] { psdi.util.MXException.class }); $method_getName_65 = (psdi.mbo.MboRemote.class).getMethod("getName", new Class[0]); $method_getOrgForGL_66 = (psdi.mbo.MboRemote.class).getMethod("getOrgForGL", new Class[] { java.lang.String.class }); $method_getOrgSiteForMaxvar_67 = (psdi.mbo.MboRemote.class).getMethod("getOrgSiteForMaxvar", new Class[] { java.lang.String.class }); $method_getOwner_68 = (psdi.mbo.MboRemote.class).getMethod("getOwner", new Class[0]); $method_getPropagateKeyFlag_69 = (psdi.mbo.MboRemote.class).getMethod("getPropagateKeyFlag", new Class[0]); $method_getRecordIdentifer_70 = (psdi.mbo.MboRemote.class).getMethod("getRecordIdentifer", new Class[0]); $method_getSiteOrg_71 = (psdi.mbo.MboRemote.class).getMethod("getSiteOrg", new Class[0]); $method_getString_72 = (psdi.mbo.MboRemote.class).getMethod("getString", new Class[] { java.lang.String.class }); $method_getString_73 = (psdi.mbo.MboRemote.class).getMethod("getString", new Class[] { java.lang.String.class, java.lang.String.class }); $method_getStringInBaseLanguage_74 = (psdi.mbo.MboRemote.class).getMethod("getStringInBaseLanguage", new Class[] { java.lang.String.class }); $method_getStringInSpecificLocale_75 = (psdi.mbo.MboRemote.class).getMethod("getStringInSpecificLocale", new Class[] { java.lang.String.class, java.util.Locale.class, java.util.TimeZone.class }); $method_getStringTransparent_76 = (psdi.mbo.MboRemote.class).getMethod("getStringTransparent", new Class[] { java.lang.String.class, java.lang.String.class }); $method_getThisMboSet_77 = (psdi.mbo.MboRemote.class).getMethod("getThisMboSet", new Class[0]); $method_getUniqueIDName_78 = (psdi.mbo.MboRemote.class).getMethod("getUniqueIDName", new Class[0]); $method_getUniqueIDValue_79 = (psdi.mbo.MboRemote.class).getMethod("getUniqueIDValue", new Class[0]); $method_getUserInfo_80 = (psdi.mbo.MboRemote.class).getMethod("getUserInfo", new Class[0]); $method_getUserName_81 = (psdi.mbo.MboRemote.class).getMethod("getUserName", new Class[0]); $method_hasHierarchyLink_82 = (psdi.mbo.MboRemote.class).getMethod("hasHierarchyLink", new Class[0]); $method_isAutoKeyed_83 = (psdi.mbo.MboRemote.class).getMethod("isAutoKeyed", new Class[] { java.lang.String.class }); $method_isBasedOn_84 = (psdi.mbo.MboRemote.class).getMethod("isBasedOn", new Class[] { java.lang.String.class }); $method_isFlagSet_85 = (psdi.mbo.MboRemote.class).getMethod("isFlagSet", new Class[] { Long.TYPE }); $method_isForDM_86 = (psdi.mbo.MboRemote.class).getMethod("isForDM", new Class[0]); $method_isModified_87 = (psdi.mbo.MboRemote.class).getMethod("isModified", new Class[0]); $method_isModified_88 = (psdi.mbo.MboRemote.class).getMethod("isModified", new Class[] { java.lang.String.class }); $method_isNew_89 = (psdi.mbo.MboRemote.class).getMethod("isNew", new Class[0]); $method_isNull_90 = (psdi.mbo.MboRemote.class).getMethod("isNull", new Class[] { java.lang.String.class }); $method_isSelected_91 = (psdi.mbo.MboRemote.class).getMethod("isSelected", new Class[0]); $method_isZombie_92 = (psdi.mbo.MboRemote.class).getMethod("isZombie", new Class[0]); $method_propagateKeyValue_93 = (psdi.mbo.MboRemote.class).getMethod("propagateKeyValue", new Class[] { java.lang.String.class, java.lang.String.class }); $method_rollbackToCheckpoint_94 = (psdi.mbo.MboRemote.class).getMethod("rollbackToCheckpoint", new Class[0]); $method_select_95 = (psdi.mbo.MboRemote.class).getMethod("select", new Class[0]); $method_setApplicationError_96 = (psdi.mbo.MboRemote.class).getMethod("setApplicationError", new Class[] { java.lang.String.class, psdi.util.ApplicationError.class }); $method_setApplicationRequired_97 = (psdi.mbo.MboRemote.class).getMethod("setApplicationRequired", new Class[] { java.lang.String.class, Boolean.TYPE }); $method_setCopyDefaults_98 = (psdi.mbo.MboRemote.class).getMethod("setCopyDefaults", new Class[0]); $method_setDeleted_99 = (psdi.mbo.MboRemote.class).getMethod("setDeleted", new Class[] { Boolean.TYPE }); $method_setESigFieldModified_100 = (psdi.mbo.MboRemote.class).getMethod("setESigFieldModified", new Class[] { Boolean.TYPE }); $method_setFieldFlag_101 = (psdi.mbo.MboRemote.class).getMethod("setFieldFlag", new Class[] { java.lang.String.class, Long.TYPE, Boolean.TYPE }); $method_setFieldFlag_102 = (psdi.mbo.MboRemote.class).getMethod("setFieldFlag", new Class[] { java.lang.String.class, Long.TYPE, Boolean.TYPE, psdi.util.MXException.class }); $method_setFieldFlag_103 = (psdi.mbo.MboRemote.class).getMethod("setFieldFlag", new Class[] { java.lang.String[].class, Long.TYPE, Boolean.TYPE }); $method_setFieldFlag_104 = (psdi.mbo.MboRemote.class).getMethod("setFieldFlag", new Class[] { java.lang.String[].class, Long.TYPE, Boolean.TYPE, psdi.util.MXException.class }); $method_setFieldFlag_105 = (psdi.mbo.MboRemote.class).getMethod("setFieldFlag", new Class[] { java.lang.String[].class, Boolean.TYPE, Long.TYPE, Boolean.TYPE }); $method_setFieldFlag_106 = (psdi.mbo.MboRemote.class).getMethod("setFieldFlag", new Class[] { java.lang.String[].class, Boolean.TYPE, Long.TYPE, Boolean.TYPE, psdi.util.MXException.class }); $method_setFieldFlags_107 = (psdi.mbo.MboRemote.class).getMethod("setFieldFlags", new Class[] { java.lang.String.class, Long.TYPE }); $method_setFlag_108 = (psdi.mbo.MboRemote.class).getMethod("setFlag", new Class[] { Long.TYPE, Boolean.TYPE }); $method_setFlag_109 = (psdi.mbo.MboRemote.class).getMethod("setFlag", new Class[] { Long.TYPE, Boolean.TYPE, psdi.util.MXException.class }); $method_setFlags_110 = (psdi.mbo.MboRemote.class).getMethod("setFlags", new Class[] { Long.TYPE }); $method_setForDM_111 = (psdi.mbo.MboRemote.class).getMethod("setForDM", new Class[] { Boolean.TYPE }); $method_setMLValue_112 = (psdi.mbo.MboRemote.class).getMethod("setMLValue", new Class[] { java.lang.String.class, java.lang.String.class, java.lang.String.class, Long.TYPE }); $method_setModified_113 = (psdi.mbo.MboRemote.class).getMethod("setModified", new Class[] { Boolean.TYPE }); $method_setNewMbo_114 = (psdi.mbo.MboRemote.class).getMethod("setNewMbo", new Class[] { Boolean.TYPE }); $method_setPropagateKeyFlag_115 = (psdi.mbo.MboRemote.class).getMethod("setPropagateKeyFlag", new Class[] { Boolean.TYPE }); $method_setPropagateKeyFlag_116 = (psdi.mbo.MboRemote.class).getMethod("setPropagateKeyFlag", new Class[] { java.lang.String[].class, Boolean.TYPE }); $method_setReferencedMbo_117 = (psdi.mbo.MboRemote.class).getMethod("setReferencedMbo", new Class[] { java.lang.String.class, psdi.mbo.Mbo.class }); $method_setValue_118 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Byte.TYPE }); $method_setValue_119 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Byte.TYPE, Long.TYPE }); $method_setValue_120 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Double.TYPE }); $method_setValue_121 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Double.TYPE, Long.TYPE }); $method_setValue_122 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Float.TYPE }); $method_setValue_123 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Float.TYPE, Long.TYPE }); $method_setValue_124 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Integer.TYPE }); $method_setValue_125 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Integer.TYPE, Long.TYPE }); $method_setValue_126 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Long.TYPE }); $method_setValue_127 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Long.TYPE, Long.TYPE }); $method_setValue_128 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, java.lang.String.class }); $method_setValue_129 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, java.lang.String.class, Long.TYPE }); $method_setValue_130 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, java.util.Date.class }); $method_setValue_131 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, java.util.Date.class, Long.TYPE }); $method_setValue_132 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, psdi.mbo.MboRemote.class }); $method_setValue_133 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, psdi.mbo.MboSetRemote.class }); $method_setValue_134 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, psdi.util.MaxType.class, Long.TYPE }); $method_setValue_135 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Short.TYPE }); $method_setValue_136 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Short.TYPE, Long.TYPE }); $method_setValue_137 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Boolean.TYPE }); $method_setValue_138 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, Boolean.TYPE, Long.TYPE }); $method_setValue_139 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, byte[].class }); $method_setValue_140 = (psdi.mbo.MboRemote.class).getMethod("setValue", new Class[] { java.lang.String.class, byte[].class, Long.TYPE }); $method_setValueNull_141 = (psdi.mbo.MboRemote.class).getMethod("setValueNull", new Class[] { java.lang.String.class }); $method_setValueNull_142 = (psdi.mbo.MboRemote.class).getMethod("setValueNull", new Class[] { java.lang.String.class, Long.TYPE }); $method_sigOptionAccessAuthorized_143 = (psdi.mbo.MboRemote.class).getMethod("sigOptionAccessAuthorized", new Class[] { java.lang.String.class }); $method_sigopGranted_144 = (psdi.mbo.MboRemote.class).getMethod("sigopGranted", new Class[] { java.lang.String.class }); $method_sigopGranted_145 = (psdi.mbo.MboRemote.class).getMethod("sigopGranted", new Class[] { java.lang.String.class, java.lang.String.class }); $method_sigopGranted_146 = (psdi.mbo.MboRemote.class).getMethod("sigopGranted", new Class[] { java.util.Set.class }); $method_smartFill_147 = (psdi.mbo.MboRemote.class).getMethod("smartFill", new Class[] { java.lang.String.class, java.lang.String.class, Boolean.TYPE }); $method_smartFind_148 = (psdi.mbo.MboRemote.class).getMethod("smartFind", new Class[] { java.lang.String.class, java.lang.String.class, java.lang.String.class, Boolean.TYPE }); $method_smartFind_149 = (psdi.mbo.MboRemote.class).getMethod("smartFind", new Class[] { java.lang.String.class, java.lang.String.class, Boolean.TYPE }); $method_smartFindByObjectName_150 = (psdi.mbo.MboRemote.class).getMethod("smartFindByObjectName", new Class[] { java.lang.String.class, java.lang.String.class, java.lang.String.class, Boolean.TYPE }); $method_smartFindByObjectName_151 = (psdi.mbo.MboRemote.class).getMethod("smartFindByObjectName", new Class[] { java.lang.String.class, java.lang.String.class, java.lang.String.class, Boolean.TYPE, java.lang.String[][].class }); $method_smartFindByObjectNameDirect_152 = (psdi.mbo.MboRemote.class).getMethod("smartFindByObjectNameDirect", new Class[] { java.lang.String.class, java.lang.String.class, java.lang.String.class, Boolean.TYPE }); $method_startCheckpoint_153 = (psdi.mbo.MboRemote.class).getMethod("startCheckpoint", new Class[0]); $method_thisToBeUpdated_154 = (psdi.mbo.MboRemote.class).getMethod("thisToBeUpdated", new Class[0]); $method_toBeAdded_155 = (psdi.mbo.MboRemote.class).getMethod("toBeAdded", new Class[0]); $method_toBeDeleted_156 = (psdi.mbo.MboRemote.class).getMethod("toBeDeleted", new Class[0]); $method_toBeSaved_157 = (psdi.mbo.MboRemote.class).getMethod("toBeSaved", new Class[0]); $method_toBeUpdated_158 = (psdi.mbo.MboRemote.class).getMethod("toBeUpdated", new Class[0]); $method_toBeValidated_159 = (psdi.mbo.MboRemote.class).getMethod("toBeValidated", new Class[0]); $method_undelete_160 = (psdi.mbo.MboRemote.class).getMethod("undelete", new Class[0]); $method_unselect_161 = (psdi.mbo.MboRemote.class).getMethod("unselect", new Class[0]); $method_validate_162 = (psdi.mbo.MboRemote.class).getMethod("validate", new Class[0]); $method_validateAttributes_163 = (psdi.mbo.MboRemote.class).getMethod("validateAttributes", new Class[0]); } catch(NoSuchMethodException _ex) { throw new NoSuchMethodError("stub class initialization failed"); } } }
31.129349
141
0.577121
5875148f510e605605cdf22510a4beccba459279
3,052
package BL.Communication; import BL.Client.ClientSystem; import DL.Game.Referee; import DL.Team.Members.TeamUser; import DL.Team.Page.Page; import DL.Team.Page.TeamPage; import DL.Team.Team; import DL.Users.Fan; import DL.Users.User; import DL.Users.UserComplaint; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CommunicationComplaintUnitStub extends ClientServerCommunication { private List<User> users; private List<UserComplaint> userComplaints; private HashMap<String,List> queryToList; public CommunicationComplaintUnitStub() { users = new ArrayList<>(); userComplaints = new ArrayList<>(); } @Override public List query(String queryName, Map<String, Object> parameters) { if(queryName.equals("UserByUserName")) { List<User> result = new ArrayList<>(); for(User user : users) { if(user.getUsername().equals(parameters.get("username"))) { result.add(user); } } return result; } else if(queryName.equals("UserComplaintsByUser")) { List<List<UserComplaint>> result = new ArrayList<>(); for(User user : users) { if(user.getUsername().equals(((User)(parameters.get("user"))).getUsername())) { result.add(user.getUserComplaintsOwner()); } } return result; } return null; } @Override public boolean update(String queryName, Map<String, Object> parameters) { if(queryName.equals("UserSetComment")) { UserComplaint currUc = null; for(UserComplaint uc : userComplaints) { if(uc.getMessage().equals(parameters.get("msg"))) { currUc = uc; } } if(currUc != null) { currUc.setResponse((String)parameters.get("comment")); return true; } } return false; } @Override public boolean insert(Object toInsert) { if(toInsert instanceof User) { users.add((User)toInsert); return true; } else if(toInsert instanceof UserComplaint) { userComplaints.add((UserComplaint)toInsert); return true; } return false; } @Override public boolean delete(Object toDelete) { return false; } @Override public boolean transaction(List<SystemRequest> requests) { return false; } private User getUserByUsernameFromDB(String username) { for(User user : users) { if(user.getUsername().equals(username)) { return user; } } return null; } }
22.441176
93
0.540301
56f2b0370610623b0519665c5c6a7dbca3666b54
1,193
/* * 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 cst_3513_fall_2017; /** * * @author drcho_000 */ public class perfectNumber { public static void main(String[] args) { System.out.println("The four perfect number less than 10,000: "); int sum; // Holds the sum of the positive divisors // Find all perfect numbers less than 10,000 for (int i = 1; i < 10000; i++){ sum = 0; // Reset Accmulator to 0 for (int k = 1; k < i; k++) { //Test for divisor if (i % k == 0) sum += k; } // Test if sum of all positive divisors are equal to number if (i == sum) System.out.printf("%20d\n", i); // for (int number = 1; number <= 10000; number++) { //boolean isPerfectNumber = i == sum; //} } } }
29.097561
80
0.461861
2fbe72cd454afdc0db55222c70988ebe7eff230b
3,830
/* * Copyright 2021 German Vekhorev (DarksideCode) * * 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 me.darksidecode.accesswarden.core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; public final class AccessWardenCore { private AccessWardenCore() {} private static final Logger log = LoggerFactory.getLogger(AccessWardenCore.class); public static void main(String[] args) { log.info("=============================== access-warden-core ==============================="); log.info("Configuring"); if (args.length == 0) { helpAndQuit(); return; } StringBuilder pathBuilder = new StringBuilder(); for (int i = 0; i < args.length; i++) { if (i != 0) pathBuilder.append(' '); pathBuilder.append(args[i]); } File jarFile = new File(pathBuilder.toString()); log.info("Input jar file: {}", jarFile.getAbsolutePath()); if (jarFile.isFile()) { if (transform(jarFile)) log.info("Success"); else log.error("Something went wrong"); } else log.error("The specified file either does not exist or is a directory"); log.info("Bye"); } private static void helpAndQuit() { log.error("Please specify path to the input jar file as a command argument."); System.exit(1); } public static boolean transform(File jarFile) { if (jarFile == null) throw new NullPointerException("jarFile cannot be null"); if (!jarFile.isFile()) throw new IllegalArgumentException("not a file"); try { JarTransformer transformer = new JarTransformer(jarFile); checkedRun(transformer); log.info("Finished transformation in file '{}'", jarFile.getAbsolutePath()); return true; } catch (Exception ex) { log.error("Failed to transform the specified jar file: {}", ex.getMessage()); return false; } } private static void checkedRun(JarTransformer transformer) { checkedRead (transformer); checkedApply(transformer); checkedSave (transformer); transformer.close(); } private static void checkedRead(JarTransformer transformer) { transformer.read(); if (transformer.state() == JarTransformer.State.ERROR) { transformer.close(); throw new RuntimeException("internal JarTransformer error: read()"); } } private static void checkedApply(JarTransformer transformer) { transformer.apply(); if (transformer.state() == JarTransformer.State.ERROR) { transformer.close(); throw new RuntimeException("internal JarTransformer error: apply()"); } } private static void checkedSave(JarTransformer transformer) { transformer.save(); if (transformer.state() == JarTransformer.State.ERROR) { transformer.close(); throw new RuntimeException("internal JarTransformer error: save()"); } } }
31.916667
104
0.591645
191e8d9f0cad98fd82ddd19fa2b0187681e26bce
6,085
/* * 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.netbeans.modules.javascript.karma.util; import java.awt.EventQueue; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.api.annotations.common.CheckForNull; import org.netbeans.api.project.Project; import org.netbeans.modules.javascript.karma.preferences.KarmaPreferences; import org.netbeans.modules.web.browser.api.WebBrowser; import org.netbeans.modules.web.browser.api.WebBrowsers; import org.netbeans.modules.web.clientproject.api.network.NetworkSupport; import org.openide.filesystems.FileUtil; import org.openide.filesystems.MIMEResolver; @MIMEResolver.Registration(displayName = "karma.conf.js", resource = "../resources/karmaconf-resolver.xml", position = 126) public final class KarmaUtils { private static final Logger LOGGER = Logger.getLogger(KarmaUtils.class.getName()); private static final FilenameFilter KARMA_CONFIG_FILTER = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("karma") // NOI18N && name.endsWith(".conf.js"); // NOI18N } }; private static final FilenameFilter JS_FILES_FILTER = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".js"); // NOI18N } }; private KarmaUtils() { } @CheckForNull public static String readContent(URL url) { assert !EventQueue.isDispatchThread(); try { Path tmpFile = Files.createTempFile("nb-karma-url-", ".html"); // NOI18N try { NetworkSupport.download(url.toExternalForm(), tmpFile.toFile()); return new String(Files.readAllBytes(tmpFile), StandardCharsets.UTF_8); } finally { Files.delete(tmpFile); } } catch (IOException ex) { LOGGER.log(Level.INFO, null, ex); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } return null; } public static List<WebBrowser> getDebugBrowsers() { List<WebBrowser> browsers = new ArrayList<>(); for (WebBrowser browser : WebBrowsers.getInstance().getAll(false, false, false, true)) { if (browser.isEmbedded()) { continue; } if (browser.getBrowserFamily().isMobile()) { continue; } if (!browser.hasNetBeansIntegration()) { continue; } browsers.add(browser); } return browsers; } @CheckForNull public static WebBrowser getPreferredDebugBrowser() { for (WebBrowser browser : getDebugBrowsers()) { return browser; } return null; } public static File getKarmaConfigDir(Project project) { // prefer directory for current karma config file String karmaConfig = KarmaPreferences.getConfig(project); if (karmaConfig != null) { File karmaConfigFile = new File(karmaConfig); if (karmaConfigFile.isFile()) { return karmaConfigFile.getParentFile(); } } // simply return project directory return FileUtil.toFile(project.getProjectDirectory()); } public static List<File> findJsFiles(File dir) { assert dir != null; // #241556 if (!dir.isDirectory()) { return Collections.emptyList(); } File[] jsFiles = dir.listFiles(JS_FILES_FILTER); if (jsFiles == null) { return Collections.emptyList(); } return Arrays.asList(jsFiles); } public static List<File> findKarmaConfigs(File configDir) { assert configDir != null; // #241556 if (!configDir.isDirectory()) { return Collections.emptyList(); } File[] configs = configDir.listFiles(KARMA_CONFIG_FILTER); if (configs == null) { return Collections.emptyList(); } return Arrays.asList(configs); } /** * Tries to find the "best" Karma config file. */ @CheckForNull public static File findKarmaConfig(File configDir) { List<File> karmaConfigs = findKarmaConfigs(configDir); int indexOf = karmaConfigs.indexOf(new File(configDir, "karma.conf.js")); // NOI18N if (indexOf != -1) { return karmaConfigs.get(indexOf); } File firstConfig = null; for (File config : karmaConfigs) { if (firstConfig == null) { firstConfig = config; } String configName = config.getName().toLowerCase(); if (configName.contains("share") // NOI18N || configName.contains("common")) { // NOI18N continue; } return config; } return firstConfig; } }
34.378531
123
0.631717
ec37a66bb21eece169ccf06e0ecfc239f314a079
199
package com.main.model; public class Link_json { private Link Link; public void setLink(Link Link) { this.Link = Link; } public Link getLink() { return Link; } }
16.583333
36
0.592965
5ebaf459ca39ae49914116f2f49326e69ec921dc
1,372
// @formatter:off /* * --------------------------------------------------------- * Copyright(C) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. See License.txt in the project root. * --------------------------------------------------------- * * --------------------------------------------------------- * Generated file, DO NOT EDIT * --------------------------------------------------------- * * See following wiki page for instructions on how to regenerate: * https://vsowiki.com/index.php?title=Rest_Client_Generation */ package com.microsoft.alm.visualstudio.services.extensionmanagement.webapi; /** */ public enum ExtensionFlags { /** * A built-in extension is installed for all VSTS accounts by default */ BUILT_IN(1), /** * The extension comes from a fully-trusted publisher */ TRUSTED(2), ; private int value; private ExtensionFlags(final int value) { this.value = value; } public int getValue() { return value; } @Override public String toString() { final String name = super.toString(); if (name.equals("BUILT_IN")) { //$NON-NLS-1$ return "builtIn"; //$NON-NLS-1$ } if (name.equals("TRUSTED")) { //$NON-NLS-1$ return "trusted"; //$NON-NLS-1$ } return null; } }
23.655172
75
0.505831
1e3cb94c2c8e305abb067851b18c734a4dc32715
1,218
package almartapps.studytodo.data.DAO; import java.util.List; import almartapps.studytodo.data.exceptions.ObjectNotExistsException; public interface GenericDAO<T> { /** * Retrieve a single object of a certain class, given its id. * @param id the id of the object to be fetched * @return the object demanded * @throws ObjectNotExistsException if the object is not inserted in the database */ public T get(long id) throws ObjectNotExistsException; /** * Retrieve all objects of a certain class. * @return a list of all the objects of the type currently stored */ public List<T> getAll(); /** * Inserts an object of a certain class in the database. * @param object the object to be inserted * @return the object that was inserted, with its ID set if it wasn't set */ public T insert(T object); /** * Deletes an object of a certain class stored in the database. * @param object the object to be deleted * @return <code>true</code> if the object was deleted, <code>false</code> otherwise */ public boolean delete(T object); /** * Deletes all objects of a certain class stored in the database. * @return the number of objects deleted */ public int deleteAll(); }
28.325581
85
0.715928
cb8e5741b956d80b1b3649792ae42a454b9c4af4
6,871
package io.github.bleoo.ysp; import android.app.Activity; import android.content.Context; import android.graphics.PixelFormat; import android.hardware.Camera; import android.hardware.SensorManager; import android.os.Environment; import android.util.Log; import android.view.OrientationEventListener; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.ViewGroup; import com.blankj.utilcode.util.FileIOUtils; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; /** * Created by bleoo on 2017/8/22. */ public class Camera1 implements SurfaceHolder.Callback { public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()); Activity mActivity; Camera mCamera; SurfaceView mSurfaceView; SurfaceHolder mSurfaceHolder; boolean isPreview; MyOrientationEventListener mOrientationEventListener; MyFaceDetectionListener mFaceDetectionListener; public Camera1(Activity activity){ mActivity = activity; mOrientationEventListener = new MyOrientationEventListener(mActivity, SensorManager.SENSOR_DELAY_NORMAL); mSurfaceView = new SurfaceView(mActivity); mSurfaceView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mSurfaceHolder = mSurfaceView.getHolder(); } public void open(int CameraNO){ if (mOrientationEventListener.canDetectOrientation()) { mOrientationEventListener.enable(); } if (mCamera == null) { mCamera = Camera.open(CameraNO); mSurfaceHolder.addCallback(this); } if (!isPreview) { mCamera.startPreview(); // startFaceDetection(); isPreview = true; } } public void release() { mOrientationEventListener.disable(); if (mCamera != null) { // 若摄像头正在工作,先停止它 mCamera.stopPreview(); //如果注册了此回调,在release之前调用,否则release之后还回调,crash mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } isPreview = false; } public void focus(){ if (mCamera != null && isPreview) { mCamera.autoFocus(null); } } public void takePicture(){ if (mCamera != null && isPreview) { mCamera.takePicture(null, null, (bytes, camera1) -> { new Thread(() -> FileIOUtils.writeFileFromBytesByStream( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + SIMPLE_DATE_FORMAT.format(new Date()) + ".jpeg", bytes)).start(); mSurfaceView.postDelayed(() -> mCamera.startPreview(), 1500); }); } } public void startFaceDetection() { // Try starting Face Detection Camera.Parameters params = mCamera.getParameters(); // start face detection only *after* preview has started if (params.getMaxNumDetectedFaces() > 0) { if (mFaceDetectionListener == null) { mFaceDetectionListener = new MyFaceDetectionListener(); } mCamera.setFaceDetectionListener(mFaceDetectionListener); // camera supports face detection, so can start it: mCamera.startFaceDetection(); } } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { Camera.Parameters parameters = mCamera.getParameters(); // 选择合适的预览尺寸 List<Camera.Size> sizeList = parameters.getSupportedPreviewSizes(); int previewWidth = sizeList.get(0).width; int previewHeight = sizeList.get(0).height; // 如果sizeList只有一个我们也没有必要做什么了,因为就他一个别无选择 if (sizeList.size() > 1) { Iterator<Camera.Size> itor = sizeList.iterator(); while (itor.hasNext()) { Camera.Size cur = itor.next(); if (cur.width >= previewWidth && cur.height >= previewHeight) { previewWidth = cur.width; previewHeight = cur.height; } } } parameters.setPreviewSize(previewWidth, previewHeight); //获得摄像区域的大小 parameters.setPictureSize(previewWidth, previewHeight); // 每秒从摄像头捕获帧画面 parameters.setPreviewFrameRate(30); // 设置照片的输出格式 jpg 照片质量 parameters.setPictureFormat(PixelFormat.JPEG); parameters.setJpegQuality(85); parameters.setRotation(270); mCamera.setParameters(parameters); CameraUtil.setCameraDisplayOrientation(mActivity, 0, mCamera); try { mCamera.setPreviewDisplay(surfaceHolder); } catch (IOException e) { e.printStackTrace(); } mCamera.startPreview(); mCamera.startFaceDetection(); isPreview = true; } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { release(); } /** * 方向传感器事件监听器 */ private class MyOrientationEventListener extends OrientationEventListener { public MyOrientationEventListener(Context context, int rate) { super(context, rate); } @Override public void onOrientationChanged(int orientation) { if (orientation == ORIENTATION_UNKNOWN || mCamera == null) return; Camera.Parameters parameters = mCamera.getParameters(); Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(0, info); orientation = (orientation + 45) / 90 * 90; int rotation = 0; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { rotation = (info.orientation - orientation + 360) % 360; } else { // back-facing camera rotation = (info.orientation + orientation) % 360; } parameters.setRotation(rotation); mCamera.setParameters(parameters); } } /** * 人脸识别监听器 */ private class MyFaceDetectionListener implements Camera.FaceDetectionListener { @Override public void onFaceDetection(Camera.Face[] faces, Camera camera) { if (faces.length > 0) { Log.d("FaceDetection", "face detected: " + faces.length + " Face 1 Location X: " + faces[0].rect.centerX() + "Y: " + faces[0].rect.centerY()); } } } }
34.014851
139
0.620434
c79dd51f7e894d909e14a1afe9f20e845ce803ec
1,759
/** * File: IntervalAnnotation.java Copyright (c) 2010 phyokyaw This program is * free software; you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation; * either version 2 of the License, or (at your option) any later version. This * program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA */ package synergyviewcore.annotations.model; import javax.persistence.Entity; import synergyviewcore.util.DateTimeHelper; /** * The Class IntervalAnnotation. * * @author phyokyaw */ @Entity public class IntervalAnnotation extends Annotation { /** The Constant PROP_DURATION. */ public static final String PROP_DURATION = "duration"; /** The duration. */ private long duration; /** * Gets the duration. * * @return the duration */ public long getDuration() { return duration; } /** * Gets the formatted duration. * * @return the formatted duration */ public String getFormattedDuration() { return DateTimeHelper.getHMSFromMilliFormatted(duration); } /** * Sets the duration. * * @param duration * the duration to set */ public void setDuration(long duration) { this.firePropertyChange(PROP_DURATION, this.duration, this.duration = duration); } }
27.920635
81
0.696987
8923ce6905821edef88a7fa1351cf0e9efe4c2cb
616
package com.luckynick.shared.model; import com.luckynick.custom.Device; import com.luckynick.shared.IOClassHandling; import com.luckynick.shared.SharedUtils; import java.util.Date; /** * Not serialized independently, but inside of test result */ @IOClassHandling(sendViaNetwork = true, dataStorage = SharedUtils.DataStorage.NONE) public class SendSessionSummary { public Device summarySource; /** * Depending on role of device which sent this summary (sender/receiver), * it is either sent or decoded data */ public SendParameters sendParameters; public long sessionStartDate; }
26.782609
83
0.758117
c7c6934ad9224324e8ef86711477bd2693ea5157
69
package ru.otus.l6.annotations.common.simple; @C public class D { }
11.5
45
0.73913
db92f9f288d95258e66cc02bbdf28bfb61a408df
438
package com.mycompany.app.dp.behaviouralPattern.templatePattern; public class Chess extends Game { @Override void initialize() { System.out.println("Chess Game Initialized! Start playing."); } @Override void start() { System.out.println("Game Started. Welcome to in the chess game!"); } @Override void end() { System.out.println("Game Finished!"); } }
19.909091
74
0.60274
e5687f939ed0d47e69d997fef79b3eff66f22178
2,421
package seedu.address.model.item.field; import static java.util.Objects.requireNonNull; import static seedu.address.commons.util.AppUtil.checkArgument; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Represents an Item's time (start/end date) in the address book. * Guarantees: immutable; is valid as declared in {@link #isValidTime(String)} */ public class Time implements Comparable<Time> { public static final String MESSAGE_CONSTRAINTS = "Time should be in the format MM-yyyy"; public static final String VALIDATION_REGEX = "^(1[0-2]|0[1-9])-[0-9]{4}$"; public final String value; /** * Constructs a {@code Time}. * * @param time A valid time in format MM/yyyy. */ public Time(String time) { requireNonNull(time); checkArgument(isValidTime(time), MESSAGE_CONSTRAINTS); value = time; } /** * Returns true if a given string is a valid time. */ public static boolean isValidTime(String test) { return test.matches(VALIDATION_REGEX); } /** * Formats {@code Time} to "MMM yyyy" format. * @return formatted {@String}. */ public String format() { SimpleDateFormat parser = new SimpleDateFormat("MM-yyyy"); try { Date date = parser.parse(this.value); SimpleDateFormat formatter = new SimpleDateFormat("MMM yyyy"); return formatter.format(date); } catch (ParseException e) { return this.value; } } @Override public String toString() { return this.value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Time // instanceof handles nulls && value.equals(((Time) other).value)); // state check } /** * Compares this Time object with another Time object. */ public int compareTo(Time other) { SimpleDateFormat parser = new SimpleDateFormat("MM-yyyy"); try { Date thisTime = parser.parse(this.value); Date otherTime = parser.parse(other.toString()); return thisTime.compareTo(otherTime); } catch (ParseException e) { return 0; } } @Override public int hashCode() { return value.hashCode(); } }
28.821429
92
0.617513
850392cdf54802ad1483975f44f5826b01f5f50b
2,295
package com.funnyhatsoftware.spacedock.data; import java.util.ArrayList; import java.util.Comparator; import android.text.TextUtils; public class Flagship extends FlagshipBase { static class FlagshipComparator implements Comparator<Flagship> { @Override public int compare(Flagship o1, Flagship o2) { int factionCompare = o1.getFaction().compareTo(o2.getFaction()); if (factionCompare == 0) { int titleCompare = o1.getTitle().compareTo(o2.getTitle()); return titleCompare; } return factionCompare; } } String getName() { if (mFaction.equals("Independent")) { return mTitle; } return mFaction; } private boolean mIsPlaceholder = false; @Override public boolean isPlaceholder() { return mIsPlaceholder; } /*package*/ void setIsPlaceholder(boolean isPlaceholder) { mIsPlaceholder = isPlaceholder; } @Override public int getCost() { return 10; } // TODO: make this more elegant String getPlainDescription() { return "Flagship: " + mTitle; } public boolean compatibleWithFaction(String faction) { if (mFaction.equals("Independent")) { return true; } return mFaction.equals(faction); } public boolean compatibleWithShip(Ship targetShip) { return compatibleWithFaction(targetShip.getFaction()); } private static void addCap(ArrayList<String> caps, String label, int value) { if (value > 0) { String s = String.format("%s: %d", label, value); caps.add(s); } } public String getCapabilities() { ArrayList<String> caps = new ArrayList<String>(); addCap(caps, "Tech", getTech()); addCap(caps, "Weap", getWeapon()); addCap(caps, "Crew", getCrew()); addCap(caps, "Tale", getTalent()); addCap(caps, "Echo", getSensorEcho()); addCap(caps, "EvaM", getEvasiveManeuvers()); addCap(caps, "Scan", getScan()); addCap(caps, "Lock", getTargetLock()); addCap(caps, "BatS", getBattleStations()); addCap(caps, "Clk", getCloak()); return TextUtils.join(", ", caps); } }
28.333333
81
0.598257
62a023391212a6451f70a356c3be132bdcee1559
435
package com.tommeng.simplejackexample.model; public class MyColor implements BaseModel { private long id; private String title; private String hex; private String description; public long getId() { return id; } public String getTitle() { return title; } public String getHex() { return hex; } public String getDescription() { return description; } }
17.4
44
0.622989
7c9a1f7d70f85169fb1180d45bd9da8258b14693
231
class Solution { public int XXX(int n) { int last = 1,last2 = 1; for(int i = 2;i<=n;i++){ int t = last+last2; last2 = last; last = t; } return last; } }
17.769231
32
0.393939
555a650da955d5f10eec913a71eb269184005be8
1,900
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.shibboleth.handler; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; /** * * Initial date: 21.07.2017<br> * @author uhensler, [email protected], http://www.frentix.com * */ public class SchacGenderHandlerTest { private static final String OLAT_DEFAULT = "-"; private SchacGenderHandler sut = new SchacGenderHandler(); @Test public void parseShouldHandleMale() { String schacMale = "1"; String olatMale = "male"; String parsed = sut.parse(schacMale); assertThat(parsed).isEqualTo(olatMale); } @Test public void parseShouldHandleFemale() { String schacFemale = "2"; String olatFemale = "female"; String parsed = sut.parse(schacFemale); assertThat(parsed).isEqualTo(olatFemale); } @Test public void parseShouldHandleOther() { String randomValue = "abc"; String parsed = sut.parse(randomValue); assertThat(parsed).isEqualTo(OLAT_DEFAULT); } @Test public void parseShouldHandleNull() { String parsed = sut.parse(null); assertThat(parsed).isEqualTo(OLAT_DEFAULT); } }
26.027397
82
0.717895
53d42ecd82abcc4c400d05c3aa0277e993993c4e
3,040
package Math_Bit; import java.math.BigInteger; //https://www.geeksforgeeks.org/given-a-number-find-next-smallest-palindrome-larger-than-this-number/ //https://www.interviewbit.com/problems/next-smallest-palindrome/ public class NextPalindrome { public String solve(String A) { int n = A.length(); if (n == 1) { // Single Digits Case int ch = Integer.parseInt(A.charAt(0) + ""); if (ch < 9) { return (ch + 1) + ""; } return "11"; } int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = A.charAt(i) - '0'; // converting to int array } int mid = n / 2; int start = mid - 1; int end = (n % 2 == 0) ? mid : mid + 1; // Even length is mid, odd case is mid +1 while (start >= 0 && arr[start] == arr[end]) { // Find first different Digit between left and right start--; end++; } boolean isLeftSmaller = false; if (start < 0 || arr[start] < arr[end]) { isLeftSmaller = true; } while (start >= 0) { arr[end++] = arr[start--]; // copy all the left digits to right } int carry = 0; if (isLeftSmaller) { carry = 1; if (n % 2 == 1) { // odd case, update mid element only arr[mid] += 1; carry = arr[mid] / 10; arr[mid] %= 10; } // reset to start and end ptr start = mid - 1; end = (n % 2 == 0) ? mid : mid + 1; // propagate carry to both end till carry > 0 while (start >= 0 && carry > 0) { arr[start] = arr[start] + 1; carry = arr[start] / 10; arr[start] %= 10; arr[end] = arr[start]; // copy the same to right start--; end++; } } String res = ""; for (int i = 0; i < n; i++) { res += (arr[i] + ""); } if (carry > 0) { // Case when all 9, appending 1 either end. For Ex: 999 -> 1001 res = "1" + res.substring(0, n - 1) + "1"; } return res; } public String solve2(String num) { int len = num.length(); String left = num.substring(0, len / 2); String middle = num.substring(len / 2, len - len / 2); // empty in case of even or one character in case odd // length String right = num.substring(len - len / 2); if (right.compareTo(reverse(left)) < 0) { return left + middle + reverse(left); } String next = new BigInteger(left + middle).add(BigInteger.ONE).toString(); return next.substring(0, left.length() + middle.length()) + reverse(next).substring(middle.length()); } private static String reverse(String s) { return new StringBuilder(s).reverse().toString(); } }
34.157303
116
0.46875
db12c8ceb76f35c1ff5db46a4963276728b6ae9c
962
package net.bbo51dog.chocolat.compiler; import static org.junit.Assert.*; import net.bbo51dog.chocolat.compiler.code.CodeGenerator; import net.bbo51dog.chocolat.compiler.parser.node.Node; import net.bbo51dog.chocolat.compiler.parser.node.NonTerminalNode; import net.bbo51dog.chocolat.compiler.parser.node.NumNode; import org.junit.Test; public class CodeGeneratorTest { @Test public void codeGenerateTest() { Node node = new NonTerminalNode(Type.ADD, "+", new NumNode("1"), new NumNode("2")); String code = new CodeGenerator(node).generate(); String expected = ".intel_syntax noprefix\n" + ".global _main\n" + "_main:\n" + " push 1\n" + " push 2\n" + " pop rdi\n" + " pop rax\n" + " add rax, rdi\n" + " push rax\n" + " pop rax\n" + " ret"; assertEquals(expected, code); } }
30.0625
91
0.587318
cf97f49a8cd6bc6f517275e22a614fd0520dd5b3
2,514
/* * Copyright (c) 2020 XUENENG LU. All rights reserved. * * 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 blog.lohoknang.workflow.reactive; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.ParallelFlux; import reactor.util.context.Context; /** * @author <a herf="[email protected]">a9043</a> */ @Slf4j class WorkflowDefinitionFactoryTest { @Test void create() { Flux<String> source = Flux.just("videoA", "videoB", "videoC"); Flux<ParallelFlux<WorkUnit>> workflowDefinitionFlux = Flux.just( Flux.<WorkUnit>just( context -> context.put("workUnit1", "workUnit1") ).parallel(), Flux.<WorkUnit>just( context -> context.put("workUnit2A", "workUnit2A"), context -> context.put("workUnit2B", "workUnit2B"), context -> context.put("workUnit2C", "workUnit2C") ).parallel(), Flux.<WorkUnit>just( context -> context.put("workUnit3", "workUnit3") ).parallel() ); WorkflowDefinition workflowDefinition = new WorkflowDefinition("workflow", workflowDefinitionFlux); Flux<Context> contextFlux = WorkflowFactory.create(source, workflowDefinition); contextFlux .log() .subscribe(); } }
41.213115
107
0.666269
247138ff03db28747b1ef0fb9b6ab34e4fbd7046
2,947
package com.base.chat.fag; import com.base.chat.R; import com.base.chat.c.WeChatMomentContract; import com.base.chat.databinding.FagWechatmomentBinding; import com.base.chat.m.WeChatMomentModel; import com.base.chat.p.WeChatMomentPresenter; import com.base.comm_model.event.MainTitleEvent; import com.base.common.act.BaseFragment; import com.base.common.rxbus.RxBus2; import com.base.wedget.banner.BannerEntity; import com.base.wedget.banner.OnBannerImgSelectInterface; import java.util.ArrayList; import java.util.List; /** * 朋友圈 * Created by weikailiang on 2020/5/11. */ public class WeChatMomentFag extends BaseFragment<WeChatMomentPresenter,WeChatMomentModel> implements WeChatMomentContract.View{ private FagWechatmomentBinding mBinding; @Override protected void initPresenter() { mPresenter.setVM(this, mModel); } @Override public void showLoading() { } @Override public void stopLoading() { } @Override protected int getLayoutResource() { return R.layout.fag_wechatmoment; } @Override protected void init() { mBinding = (FagWechatmomentBinding) mRootBinding; RxBus2.getInstance().post(new MainTitleEvent(mContext.getString(R.string.wechat_title))); } @Override public void onHiddenChanged(boolean hidden) { if (!hidden){ RxBus2.getInstance().post(new MainTitleEvent(mContext.getString(R.string.wechat_title))); } } @Override protected void lazyLoad() { List<BannerEntity> list = new ArrayList<>(); BannerEntity entity = null; entity = new BannerEntity(); entity.setUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1589455087688&di=c7a937e857838819886b427886a70683&imgtype=0&src=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D1100172608%2C3877538389%26fm%3D214%26gp%3D0.jpg"); list.add(entity); entity = new BannerEntity(); entity.setUrl("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3404221704,526751635&fm=26&gp=0.jpg"); list.add(entity); entity = new BannerEntity(); entity.setUrl("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3404221704,526751635&fm=26&gp=0.jpg"); list.add(entity); entity = new BannerEntity(); entity.setUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1589455087688&di=c7a937e857838819886b427886a70683&imgtype=0&src=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D1100172608%2C3877538389%26fm%3D214%26gp%3D0.jpg"); list.add(entity); mBinding.banner.setmData(list); mBinding.banner.setOnBannerImgSelectInterface(new OnBannerImgSelectInterface() { @Override public void selectImage(int index) { } @Override public void onItemClick(BannerEntity entity, int index) { } }); } }
33.11236
250
0.701391
fa0605a16c16e01a112a1535c0d7cf2da883e4b0
4,092
/* * $Header: /home/cvspublic/jakarta-tomcat-4.0/catalina/src/share/org/apache/catalina/loader/Reloader.java,v 1.5 2001/07/22 20:25:10 pier Exp $ * $Revision: 1.5 $ * $Date: 2001/07/22 20:25:10 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.catalina.loader; /** * Internal interface that <code>ClassLoader</code> implementations may * optionally implement to support the auto-reload functionality of * the classloader associated with the context. * * @author Craig R. McClanahan * @version $Revision: 1.5 $ $Date: 2001/07/22 20:25:10 $ */ public interface Reloader { /** * Add a new repository to the set of places this ClassLoader can look for * classes to be loaded. * * @param repository Name of a source of classes to be loaded, such as a * directory pathname, a JAR file pathname, or a ZIP file pathname * * @exception IllegalArgumentException if the specified repository is * invalid or does not exist */ public void addRepository(String repository); /** * Return a String array of the current repositories for this class * loader. If there are no repositories, a zero-length array is * returned. */ public String[] findRepositories(); /** * Have one or more classes or resources been modified so that a reload * is appropriate? */ public boolean modified(); }
37.541284
143
0.695992
f66962417f440d868834bc8b6c35a93462e3c23b
2,510
package dosije; import java.util.Scanner; public class TestDosije { public static void main(String[] args) { /* System.out.println("------------------ PRAG ------------------"); Scanner sc = new Scanner(System.in); System.out.print("ime osobe: "); String ime = sc.next(); System.out.print("prezime osobe: "); String prezime = sc.next(); System.out.print("jmbg: "); String jmbg = sc.next(); sc.close(); System.out.println(); Dosije dosije = new Dosije(ime + " " + prezime, jmbg); System.out.println(dosije); System.out.println("------------------------------------------"); */ Scanner sc = new Scanner(System.in); System.out.println("Podaci o studentu:"); System.out.println("---------------------"); System.out.print("Ime_Prezime: "); String osoba = sc.next(); osoba = osoba.replace('_', ' '); System.out.print("jmbg: "); String jmbg = sc.next(); while(!Dosije.jesteJmbg(jmbg)) { System.out.print("jmbg: "); jmbg = sc.next(); } System.out.print("broj indeksa: "); int brIndeksa = sc.nextInt(); System.out.print("godina upisa: "); int godina = sc.nextInt(); System.out.print("studije (0-'Osnovne',1-'MSc',2-'PhD'): "); int studije = sc.nextInt(); Student student = new Student(osoba, jmbg, brIndeksa, godina, studije); System.out.println("\nPodaci o nastavniku:"); System.out.println("-------------------------"); System.out.print("Ime_Prezime: "); osoba = sc.next(); osoba = osoba.replace('_', ' '); System.out.print("jmbg: "); jmbg = sc.next(); while(Nastavnik.jmbgUDatum(jmbg) == null) { System.out.print("jmbg: "); jmbg = sc.next(); } System.out.print("radni odnos: "); int ugovor = sc.nextInt(); System.out.println("zvanje ('docent','vanredni','redovni'):"); String zvanje = sc.next(); while(!Nastavnik.ispravnoZvanje(zvanje)) { System.out.println("Neispravno zvanje, pokusaj ponovo!"); zvanje = sc.next(); } Nastavnik nastavnik = new Nastavnik(osoba, jmbg, ugovor, zvanje); System.out.println(); System.out.println(student); System.out.println("\n" + nastavnik); System.out.println("\nBroj studenata: " + Student.brStudenata()); System.out.print("\nstudije (0-'Osnovne',1-'MSc',2-'PhD'): "); studije = sc.nextInt(); Student studentK = new Student(student); studentK.setStudije(studije); System.out.println(); System.out.println(studentK); System.out.println("\nBroj studenata: " + Student.brStudenata()); sc.close(); } }
29.880952
74
0.605578