language
stringclasses
5 values
text
stringlengths
15
988k
Java
public class CellMap extends SurfaceView implements SurfaceHolder.Callback { private static Bitmap bmLargeImage; private static Bitmap yourBitmap; private static int displayWidth; private static int displayHeight; private static int dWidth = 480; private static int dHeight = 854; float[] pts = new float [400]; public static int _xcellSize; public static int _ycellSize; // HashMap, first level are the rows, second level are the columns private HashMap<Integer, HashMap<Integer, Cell>> _mapCells = new HashMap<Integer, HashMap<Integer, Cell>>(); private MapThread _mapThread; // variables we will use often private HashMap<Integer, Cell> _row; private Paint paint = new Paint(); // map size in cells public static int _mapSize = 10; // Offset to the upper left corner of the map private int _xOffset = 0; private int _yOffset = 0; private float _angle = 0; private int _mode = 0; Random gen = new Random(); // last touch point private float _xTouch = 0; private float _yTouch = 0; /** * Constructor, fills the map on creation. * * @param context */ public CellMap(Context context) { super(context); // if(_xOffset >= 0 && _yOffset >= 0 && _xOffset < (2500) && _yOffset < (2500)) bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image00); displayWidth = bmLargeImage.getWidth(); displayHeight = bmLargeImage.getHeight(); _xcellSize = displayWidth/_mapSize; _ycellSize = displayHeight/_mapSize; int x = 0; int y = 0; // fill the map with cells int id = 0; for (int i = 0; i < _mapSize; i++) { _row = new HashMap<Integer, Cell>(); y = i*_ycellSize; for (int j = 0; j < _mapSize; j++) { x = j*_xcellSize; yourBitmap = Bitmap.createBitmap(bmLargeImage,x,y,(_xcellSize), (_ycellSize)); _row.put(j, new Cell(id++,yourBitmap)); } _mapCells.put(i, _row); } for (int i = 0; i < 400; i = i+2) { pts[i] = i+6; if(i==0) pts[i+1] = dHeight/2+75; else { float num = gen.nextFloat(); int sum = (int) (pts[i-1]+gen.nextInt(3)); if(num < 0.75 && (sum < dHeight-60)) pts[i+1] = sum; else pts[i+1] = pts[i-1]-3; } } // register the view to the surfaceholder getHolder().addCallback(this); // set the thread - not yet started _mapThread = new MapThread(this); // secure the view is focusable setFocusable(true); } /** * Draw what we want to see. */ @Override public void onDraw(Canvas canvas) { // help variables int x = 0; int y = 0; canvas.save(); final android.graphics.Matrix matrix = canvas.getMatrix(); Camera camera = new Camera(); camera.save(); if(_mode == 2) camera.rotateX(55); //Applies a rotation transform around the X axis. camera.getMatrix(matrix); camera.applyToCanvas(canvas); // canvas.save(); canvas.rotate(_angle, dWidth/2, dHeight/4); for (int i = 0; i < _mapSize; i++) { // get the row _row = _mapCells.get(i); // calculate the correct y for the row y = i * _ycellSize - _yOffset; // go through the row for (int j = 0; j < _mapSize; j++) { // calculate the x coordinate for the columns x = j * _xcellSize - _xOffset; _row.get(j).draw(canvas, paint, x, y); } } canvas.restore(); matrix.preTranslate(-dWidth/2,-dHeight/2); matrix.postTranslate(dWidth/2,dHeight/2); camera.restore(); paint.setColor(Color.GREEN); // setting the marker canvas.drawCircle(dWidth/2-10, dHeight/4, 10, paint); Rect rect = new Rect(0,dHeight/2,dWidth,dHeight-40); paint.setColor(Color.WHITE); canvas.drawRect(rect, paint); paint.setColor(Color.BLUE); canvas.drawLine(5, dHeight/2+10, dWidth-30, dHeight/2+10, paint); canvas.drawLine(5, dHeight-20, dWidth-30, dHeight-20, paint); canvas.drawLine(5, dHeight/2+10, 5, dHeight-20, paint); canvas.drawLine(dWidth-30, dHeight/2+10, dWidth-30, dHeight-20, paint); paint.setStrokeWidth(4); canvas.drawLines(pts, paint); paint.setColor(Color.BLACK); paint.setTextSize(20); canvas.drawText("3.6 kt "+_xTouch+" degrees "+_yTouch+" degrees ", 5, dHeight/2, paint); float height = (pts[1]-dHeight/2)*200/ dHeight; canvas.drawText(""+height+" ft", 5, dHeight-40, paint); } /** * Handle touch event on the map. */ @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN){ _mode = (_mode + 1)%3; } return true; } public boolean onEvent(int xMove, int yMove, float angle, int shift) { if(shift==1){ if(xMove < 1625 && yMove < 2237) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image00); } else if(xMove < 1625 && yMove >= 2237 && yMove < 4474) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image01); } else if(xMove < 1625 && yMove >= 4474 && yMove < 6711) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image02); } else if(xMove < 1625 && yMove >= 6711 && yMove < 8948) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image03); } else if(xMove >= 1625 && xMove < 3250 && yMove < 2237) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image10); } else if(xMove >= 1625 && xMove < 3250 && yMove >= 2237 && yMove < 4474) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image11); } else if(xMove >= 1625 && xMove < 3250 && yMove >= 4474 && yMove < 6711) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image12); } else if(xMove >= 1625 && xMove < 3250 && yMove >= 6711 && yMove < 8948) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image13); } else if(xMove >= 3250 && xMove < 4875 && yMove < 2237) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image20); } else if(xMove >= 3250 && xMove < 4875 && yMove >= 2237 && yMove < 4474) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image21); } else if(xMove >= 3250 && xMove < 4875 && yMove >= 4474 && yMove < 6711) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image22); } else if(xMove >= 3250 && xMove < 4875 && yMove >= 6711 && yMove < 8948) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image23); } else if(xMove >= 4875 && xMove < 6500 && yMove < 2237) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image30); } else if(xMove >= 4875 && xMove < 6500 && yMove >= 2237 && yMove < 4474) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image31); } else if(xMove >= 4875 && xMove < 6500 && yMove >= 4474 && yMove < 6711) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image32); } else if(xMove >= 4875 && xMove < 6500 && yMove >= 6711 && yMove < 8948) { bmLargeImage = BitmapFactory.decodeResource(getResources(), R.drawable.image33); } displayWidth = bmLargeImage.getWidth(); displayHeight = bmLargeImage.getHeight(); _xcellSize = displayWidth/_mapSize; _ycellSize = displayHeight/_mapSize; int x = 0; int y = 0; int id = 0; for (int i = 0; i < _mapSize; i++) { _row = new HashMap<Integer, Cell>(); y = i*_ycellSize; for (int j = 0; j < _mapSize; j++) { x = j*_xcellSize; yourBitmap = Bitmap.createBitmap(bmLargeImage,x,y,(_xcellSize), (_ycellSize)); _row.put(j, new Cell(id++,yourBitmap)); } _mapCells.put(i, _row); } } _xTouch = (76.7833f - (xMove/6020.00f)*0.2639f); _yTouch = (34.8918f - (yMove/8094.00f)*0.2918f); _xOffset = xMove%1625; _yOffset = yMove%2237; if(_mode != 0) _angle = (angle)%360;// + angle; else _angle = 0; int i; for (i = 3; i < 400; i = i+2) { pts[i-2] = pts[i]; } float num = gen.nextFloat(); int sum = (int) (pts[i-2]+gen.nextInt(10)); if(num < 0.75 && (sum < dHeight-250)) pts[399] = sum; else pts[399] = pts[397]-3; return true; } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} /** * Called when surface created. * Starts the thread if not already running. */ public void surfaceCreated(SurfaceHolder holder) { if (!_mapThread.isAlive()) { _mapThread = new MapThread(this); } _mapThread._run = true; _mapThread.start(); } /** * Called when surface destroyed * Stops the thread. */ public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; _mapThread._run = false; while (retry) { try { _mapThread.join(); retry = false; } catch (InterruptedException e) { } } } }
Java
@SuppressWarnings("serial") public class MaF01 extends AbstractDoubleProblem { /** * Default constructor */ public MaF01() { this(12, 3) ; } /** * Creates a MaF01 problem instance * * @param numberOfVariables Number of variables * @param numberOfObjectives Number of objective functions */ public MaF01(Integer numberOfVariables, Integer numberOfObjectives) { setNumberOfVariables(numberOfVariables); setNumberOfObjectives(numberOfObjectives); setNumberOfConstraints(0); setName("MaF01"); List<Double> lower = new ArrayList<>(getNumberOfVariables()), upper = new ArrayList<>( getNumberOfVariables()); for (int var = 0; var < numberOfVariables; var++) { lower.add(0.0); upper.add(1.0); } setVariableBounds(lower, upper); } /** * Evaluates a solution * * @param solution The solution to evaluate */ @Override public void evaluate(DoubleSolution solution) { int numberOfVariables = solution.getNumberOfVariables(); int numberOfObjectives = solution.getNumberOfObjectives(); double[] x = new double[numberOfVariables]; double[] f = new double[numberOfObjectives]; for (int i = 0; i < numberOfVariables; i++) { x[i] = solution.getVariable(i); } double g = 0, subf1 = 1, subf3; for (int j = numberOfObjectives - 1; j < numberOfVariables; j++) { g += (Math.pow(x[j] - 0.5, 2)); } subf3 = 1 + g; f[numberOfObjectives - 1] = x[0] * subf3; for (int i = numberOfObjectives - 2; i > 0; i--) { subf1 *= x[numberOfObjectives - i - 2]; f[i] = subf3 * (1 - subf1 * (1 - x[numberOfObjectives - i - 1])); } f[0] = (1 - subf1 * x[numberOfObjectives - 2]) * subf3; for (int i = 0; i < numberOfObjectives; i++) { solution.setObjective(i, f[i]); } } }
Java
public class ModuleExtendedModelBuilderImpl implements ModelBuilderService { private static boolean is4OorBetter = GradleVersion.current().getBaseVersion().compareTo(GradleVersion.version("4.0")) >= 0; private static final String SOURCE_SETS_PROPERTY = "sourceSets"; private static final String TEST_SRC_DIRS_PROPERTY = "testSrcDirs"; @Override public boolean canBuild(String modelName) { return ModuleExtendedModel.class.getName().equals(modelName); } @Nullable @Override public Object buildAll(String modelName, Project project) { final String moduleName = project.getName(); final String moduleGroup = project.getGroup().toString(); final String moduleVersion = project.getVersion().toString(); final File buildDir = project.getBuildDir(); String javaSourceCompatibility = null; for (Task task : project.getTasks()) { if (task instanceof JavaCompile) { JavaCompile javaCompile = (JavaCompile)task; javaSourceCompatibility = javaCompile.getSourceCompatibility(); if(task.getName().equals("compileJava")) break; } } final ModuleExtendedModelImpl moduleVersionModel = new ModuleExtendedModelImpl(moduleName, moduleGroup, moduleVersion, buildDir, javaSourceCompatibility); final List<File> artifacts = new ArrayList<File>(); for (Task task : project.getTasks()) { if (task instanceof Jar) { Jar jar = (Jar)task; artifacts.add(jar.getArchivePath()); } } moduleVersionModel.setArtifacts(artifacts); final Set<String> sourceDirectories = new HashSet<String>(); final Set<String> testDirectories = new HashSet<String>(); final Set<String> resourceDirectories = new HashSet<String>(); final Set<String> testResourceDirectories = new HashSet<String>(); final List<File> testClassesDirs = new ArrayList<File>(); for (Task task : project.getTasks()) { if (task instanceof Test) { Test test = (Test)task; if (is4OorBetter) { testClassesDirs.addAll(test.getTestClassesDirs().getFiles()); } else { testClassesDirs.add(test.getTestClassesDir()); } if (test.hasProperty(TEST_SRC_DIRS_PROPERTY)) { Object testSrcDirs = test.property(TEST_SRC_DIRS_PROPERTY); if (testSrcDirs instanceof Iterable) { for (Object dir : Iterable.class.cast(testSrcDirs)) { addFilePath(testDirectories, dir); } } } } } IdeaCompilerOutputImpl compilerOutput = new IdeaCompilerOutputImpl(); if (project.hasProperty(SOURCE_SETS_PROPERTY)) { Object sourceSets = project.property(SOURCE_SETS_PROPERTY); if (sourceSets instanceof SourceSetContainer) { SourceSetContainer sourceSetContainer = (SourceSetContainer)sourceSets; for (SourceSet sourceSet : sourceSetContainer) { SourceSetOutput output = sourceSet.getOutput(); if (SourceSet.TEST_SOURCE_SET_NAME.equals(sourceSet.getName())) { if (is4OorBetter) { File firstClassesDir = CollectionUtils.findFirst(output.getClassesDirs().getFiles(), Specs.SATISFIES_ALL); compilerOutput.setTestClassesDir(firstClassesDir); } else { compilerOutput.setTestClassesDir(output.getClassesDir()); } compilerOutput.setTestResourcesDir(output.getResourcesDir()); } if (SourceSet.MAIN_SOURCE_SET_NAME.equals(sourceSet.getName())) { if (is4OorBetter) { File firstClassesDir = CollectionUtils.findFirst(output.getClassesDirs().getFiles(), Specs.SATISFIES_ALL); compilerOutput.setMainClassesDir(firstClassesDir); } else { compilerOutput.setMainClassesDir(output.getClassesDir()); } compilerOutput.setMainResourcesDir(output.getResourcesDir()); } for (File javaSrcDir : sourceSet.getAllJava().getSrcDirs()) { boolean isTestDir = isTestDir(sourceSet, testClassesDirs); addFilePath(isTestDir ? testDirectories : sourceDirectories, javaSrcDir); } for (File resourcesSrcDir : sourceSet.getResources().getSrcDirs()) { boolean isTestDir = isTestDir(sourceSet, testClassesDirs); addFilePath(isTestDir ? testResourceDirectories : resourceDirectories, resourcesSrcDir); } } } } File projectDir = project.getProjectDir(); IdeaContentRootImpl contentRoot = new IdeaContentRootImpl(projectDir); final Set<String> ideaSourceDirectories = new HashSet<String>(); final Set<String> ideaTestDirectories = new HashSet<String>(); final Set<String> ideaGeneratedDirectories = new HashSet<String>(); final Set<File> excludeDirectories = new HashSet<File>(); enrichDataFromIdeaPlugin(project, excludeDirectories, ideaSourceDirectories, ideaTestDirectories, ideaGeneratedDirectories); if (ideaSourceDirectories.isEmpty()) { sourceDirectories.clear(); resourceDirectories.clear(); } if (ideaTestDirectories.isEmpty()) { testDirectories.clear(); testResourceDirectories.clear(); } ideaSourceDirectories.removeAll(resourceDirectories); sourceDirectories.removeAll(ideaTestDirectories); sourceDirectories.addAll(ideaSourceDirectories); ideaTestDirectories.removeAll(testResourceDirectories); testDirectories.addAll(ideaTestDirectories); // ensure disjoint directories with different type resourceDirectories.removeAll(sourceDirectories); testDirectories.removeAll(sourceDirectories); testResourceDirectories.removeAll(testDirectories); for (String javaDir : sourceDirectories) { contentRoot.addSourceDirectory(new IdeaSourceDirectoryImpl(new File(javaDir), ideaGeneratedDirectories.contains(javaDir))); } for (String testDir : testDirectories) { contentRoot.addTestDirectory(new IdeaSourceDirectoryImpl(new File(testDir), ideaGeneratedDirectories.contains(testDir))); } for (String resourceDir : resourceDirectories) { contentRoot.addResourceDirectory(new IdeaSourceDirectoryImpl(new File(resourceDir))); } for (String testResourceDir : testResourceDirectories) { contentRoot.addTestResourceDirectory(new IdeaSourceDirectoryImpl(new File(testResourceDir))); } for (File excludeDir : excludeDirectories) { contentRoot.addExcludeDirectory(excludeDir); } moduleVersionModel.setContentRoots(Collections.<ExtIdeaContentRoot>singleton(contentRoot)); moduleVersionModel.setCompilerOutput(compilerOutput); ConfigurationContainer configurations = project.getConfigurations(); SortedMap<String, Configuration> configurationsByName = configurations.getAsMap(); Map<String, Set<File>> artifactsByConfiguration = new HashMap<String, Set<File>>(); for (Map.Entry<String, Configuration> configurationEntry : configurationsByName.entrySet()) { Set<File> files = configurationEntry.getValue().getAllArtifacts().getFiles().getFiles(); artifactsByConfiguration.put(configurationEntry.getKey(), files); } moduleVersionModel.setArtifactsByConfiguration(artifactsByConfiguration); return moduleVersionModel; } @NotNull @Override public ErrorMessageBuilder getErrorMessageBuilder(@NotNull Project project, @NotNull Exception e) { return ErrorMessageBuilder.create( project, e, "Other" ).withDescription("Unable to resolve all content root directories"); } private static boolean isTestDir(SourceSet sourceSet, List<File> testClassesDirs) { if (SourceSet.TEST_SOURCE_SET_NAME.equals(sourceSet.getName())) return true; if (SourceSet.MAIN_SOURCE_SET_NAME.equals(sourceSet.getName())) return false; File sourceSetClassesDir; if (is4OorBetter) { sourceSetClassesDir = CollectionUtils.findFirst(sourceSet.getOutput().getClassesDirs().getFiles(), Specs.SATISFIES_ALL); } else { sourceSetClassesDir = sourceSet.getOutput().getClassesDir(); } for (File testClassesDir : testClassesDirs) { do { if (sourceSetClassesDir.getPath().equals(testClassesDir.getPath())) return true; } while ((testClassesDir = testClassesDir.getParentFile()) != null); } return false; } private static void addFilePath(Set<String> filePathSet, Object file) { if (file instanceof File) { try { filePathSet.add(((File)file).getCanonicalPath()); } catch (IOException ignore) { } } } private static void enrichDataFromIdeaPlugin(Project project, Set<File> excludeDirectories, Set<String> javaDirectories, Set<String> testDirectories, Set<String> ideaGeneratedDirectories) { IdeaPlugin ideaPlugin = project.getPlugins().findPlugin(IdeaPlugin.class); if (ideaPlugin == null) return; IdeaModel ideaModel = ideaPlugin.getModel(); if (ideaModel == null || ideaModel.getModule() == null) return; for (File excludeDir : ideaModel.getModule().getExcludeDirs()) { excludeDirectories.add(excludeDir); } for (File file : ideaModel.getModule().getSourceDirs()) { javaDirectories.add(file.getPath()); } for (File file : ideaModel.getModule().getTestSourceDirs()) { testDirectories.add(file.getPath()); } if(GradleVersion.current().compareTo(GradleVersion.version("2.2")) >=0) { for (File file : ideaModel.getModule().getGeneratedSourceDirs()) { ideaGeneratedDirectories.add(file.getPath()); } } } }
Java
public class WebViewAsynchronousFindApisTest extends WebViewFindApisTestBase { @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindAllFinds() throws Throwable { assertEquals(4, findAllAsyncOnUiThread("wood")); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindAllDouble() throws Throwable { findAllAsyncOnUiThread("wood"); assertEquals(4, findAllAsyncOnUiThread("chuck")); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindAllDoubleNext() throws Throwable { assertEquals(4, findAllAsyncOnUiThread("wood")); assertEquals(4, findAllAsyncOnUiThread("wood")); assertEquals(2, findNextOnUiThread(true)); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindAllDoesNotFind() throws Throwable { assertEquals(0, findAllAsyncOnUiThread("foo")); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindAllEmptyPage() throws Throwable { assertEquals(0, findAllAsyncOnUiThread("foo")); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindAllEmptyString() throws Throwable { assertEquals(0, findAllAsyncOnUiThread("")); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindNextForward() throws Throwable { assertEquals(4, findAllAsyncOnUiThread("wood")); for (int i = 2; i <= 4; i++) { assertEquals(i - 1, findNextOnUiThread(true)); } assertEquals(0, findNextOnUiThread(true)); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindNextBackward() throws Throwable { assertEquals(4, findAllAsyncOnUiThread("wood")); for (int i = 4; i >= 1; i--) { assertEquals(i - 1, findNextOnUiThread(false)); } assertEquals(3, findNextOnUiThread(false)); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindNextBig() throws Throwable { assertEquals(4, findAllAsyncOnUiThread("wood")); assertEquals(1, findNextOnUiThread(true)); assertEquals(0, findNextOnUiThread(false)); assertEquals(3, findNextOnUiThread(false)); for (int i = 1; i <= 4; i++) { assertEquals(i - 1, findNextOnUiThread(true)); } assertEquals(0, findNextOnUiThread(true)); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindAllEmptyNext() throws Throwable { assertEquals(4, findAllAsyncOnUiThread("wood")); assertEquals(1, findNextOnUiThread(true)); assertEquals(0, findAllAsyncOnUiThread("")); assertEquals(0, findNextOnUiThread(true)); assertEquals(0, findAllAsyncOnUiThread("")); assertEquals(4, findAllAsyncOnUiThread("wood")); assertEquals(1, findNextOnUiThread(true)); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testClearMatches() throws Throwable { assertEquals(4, findAllAsyncOnUiThread("wood")); clearMatchesOnUiThread(); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testClearFindNext() throws Throwable { assertEquals(4, findAllAsyncOnUiThread("wood")); clearMatchesOnUiThread(); assertEquals(4, findAllAsyncOnUiThread("wood")); assertEquals(1, findNextOnUiThread(true)); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindEmptyNext() throws Throwable { assertEquals(0, findAllAsyncOnUiThread("")); assertEquals(0, findNextOnUiThread(true)); assertEquals(4, findAllAsyncOnUiThread("wood")); } @SmallTest @Feature({"AndroidWebView", "FindInPage"}) public void testFindNextFirst() throws Throwable { runTestOnUiThread(new Runnable() { @Override public void run() { contents().findNext(true); } }); assertEquals(4, findAllAsyncOnUiThread("wood")); assertEquals(1, findNextOnUiThread(true)); assertEquals(0, findNextOnUiThread(false)); assertEquals(3, findNextOnUiThread(false)); } }
Java
public class DataView extends AbstractDataTable { public static native DataView create(AbstractDataTable table) /*-{ return new $wnd.google.visualization.DataView(table); }-*/; protected DataView() { } public final native int getTableColumnIndex(int viewColumnIndex) /*-{ return this.getTableColumnIndex(viewColumnIndex); }-*/; public final native int getTableRowIndex(int viewRowIndex) /*-{ return this.getTableRowIndex(viewRowIndex); }-*/; public final native int getViewColumnIndex(int tableColumnIndex) /*-{ return this.getViewColumnIndex(tableColumnIndex); }-*/; public final native JsArrayInteger getViewColumns() /*-{ return this.getViewColumns(); }-*/; public final native int getViewRowIndex(int tableRowIndex) /*-{ return this.getViewRowIndex(tableRowIndex); }-*/; public final native JsArrayInteger getViewRows() /*-{ return this.getViewRows(); }-*/; public final void hideColumns(int[] columnIndices) { hideColumns(ArrayHelper.toJsArrayInteger(columnIndices)); } public final native void hideColumns(JsArrayInteger columnIndices) /*-{ this.hideColumns(columnIndices); }-*/; public final native void hideRows(int from, int to) /*-{ this.hideRows(from, to); }-*/; public final void hideRows(int[] rowsIndices) { hideRows(ArrayHelper.toJsArrayInteger(rowsIndices)); } public final native void hideRows(JsArrayInteger rowsIndices) /*-{ this.hideRows(rowsIndices); }-*/; public final void setColumns(int[] columnIndices) { setColumns(ArrayHelper.toJsArrayInteger(columnIndices)); } public final native void setColumns(JsArrayInteger columnIndices) /*-{ this.setColumns(columnIndices); }-*/; public final native void setRows(int from, int to) /*-{ this.setRows(from, to); }-*/; public final void setRows(int[] rowsIndices) { setRows(ArrayHelper.toJsArrayInteger(rowsIndices)); } public final native void setRows(JsArrayInteger rowsIndices) /*-{ this.setRows(rowsIndices); }-*/; }
Java
@Autonomous(name = "Release Autonomous", group = "Release Opmode") public class Auto extends LinearOpMode { HardwareRobot robot = new HardwareRobot(); private ElapsedTime runtime = new ElapsedTime(); static final double COUNTS_PER_MOTOR_REV = 1440 ; // eg: TETRIX Motor Encoder static final double DRIVE_GEAR_REDUCTION = 1 ; // This is < 1.0 if geared UP static final double WHEEL_DIAMETER_INCHES = 6.0 ; // For figuring circumference static final double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV * DRIVE_GEAR_REDUCTION) / (WHEEL_DIAMETER_INCHES * 3.1415); static final double DRIVE_SPEED = 0.3; static final double TURN_SPEED = 0.5; @Override public void runOpMode() throws InterruptedException { robot.init(hardwareMap); robot.resetEncoders(); telemetry.addData("Auto Alliance", robot.alliance); // telemetry.update(); waitForStart(); if(robot.alliance != AllianceColor.NULL) { switch(robot.autoMode){ case BEACON: beaconAutoMode(); break; case CORNER: cornerAutoMode(); break; case CAPBALL: capballAutoMode(); break; default: System.out.println("Automode does not exist"); } } } private void beaconAutoMode(){ encoderDrive(DRIVE_SPEED, 39, 39, 10); encoderDrive(DRIVE_SPEED, -5, -5, 10); if (robot.alliance == AllianceColor.RED) { encoderDrive(DRIVE_SPEED, -19, 19, 10); } else { encoderDrive(DRIVE_SPEED, 19, -19, 10); } encoderDrive(DRIVE_SPEED, 39.5, 39.5, 10); if (robot.alliance == AllianceColor.RED) { senseInDirection(Direction.RIGHT, 5); } else { senseInDirection(Direction.LEFT, 5); } encoderDrive(DRIVE_SPEED, -7, -7, 10); if (robot.alliance == AllianceColor.RED) { encoderDrive(DRIVE_SPEED, -19, 19, 10); } else { encoderDrive(DRIVE_SPEED, 19, -19, 10); } encoderDrive(DRIVE_SPEED, 45, 45, 10); } private void cornerAutoMode(){ encoderDrive(DRIVE_SPEED, 39, 39, 10); encoderDrive(DRIVE_SPEED, -5, -5, 10); robot.leftArmServo.setPosition(1); robot.rightArmServo.setPosition(1); if (robot.alliance == AllianceColor.RED) { encoderDrive(DRIVE_SPEED, -27, 27, 10); } else { encoderDrive(DRIVE_SPEED, 28, -28, 10); } robot.leftArmServo.setPosition(1); robot.rightArmServo.setPosition(1); encoderDrive(DRIVE_SPEED, 35, 35, 10); robot.leftArmServo.setPosition(1); robot.rightArmServo.setPosition(1); } private void capballAutoMode(){ encoderDrive(DRIVE_SPEED, 39, 39, 10); encoderDrive(DRIVE_SPEED, -38, -38, 10); } public void encoderDrive(double speed, double leftInches, double rightInches, double timeoutS) { int newLeftTarget; int newRightTarget; // Ensure that the opmode is still active if (opModeIsActive()) { if(rightInches < 0){ rightInches += .35d; }else if(rightInches > 0){ rightInches -= .35d; } // Determine new target position, and pass to motor controller newLeftTarget = robot.frontLeftMotor.getCurrentPosition() + (int)(leftInches * COUNTS_PER_INCH); newRightTarget = robot.frontRightMotor.getCurrentPosition() + (int)(rightInches * COUNTS_PER_INCH); robot.frontLeftMotor.setTargetPosition(newLeftTarget); robot.frontRightMotor.setTargetPosition(newRightTarget); // Turn On RUN_TO_POSITION robot.frontLeftMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.frontRightMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); // reset the timeout time and start motion. runtime.reset(); robot.frontLeftMotor.setPower(Math.abs(speed*robot.frontSpeedMultipler)); robot.frontRightMotor.setPower(Math.abs(speed*robot.frontSpeedMultipler)); robot.rearLeftMotor.setPower(Math.abs(speed)); robot.rearRightMotor.setPower(Math.abs(speed)); // keep looping while we are still active, and there is time left, and both motors are running. while (opModeIsActive() && (runtime.seconds() < timeoutS) && (robot.frontLeftMotor.isBusy() && robot.frontRightMotor.isBusy())) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d :%7d", newLeftTarget, newRightTarget); telemetry.addData("Path2", "Running at %7d :%7d", robot.frontLeftMotor.getCurrentPosition(), robot.frontRightMotor.getCurrentPosition()); telemetry.update(); } // Stop all motion; robot.frontLeftMotor.setPower(0); robot.frontRightMotor.setPower(0); robot.rearLeftMotor.setPower(0); robot.rearRightMotor.setPower(0); // Turn off RUN_TO_POSITION robot.frontLeftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.frontRightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); // sleep(250); // optional pause after each move } } void senseInDirection(Direction direction, int timeout){ int beaconsPressed = 0; ElapsedTime timer = new ElapsedTime(); double seconds = -1; boolean setSeconds = false; robot.enableColorSensorLED(false); while(beaconsPressed < 1){ telemetry.addData("LED is Enabled: ", robot.isLedOn); AllianceColor seenColor = AllianceColor.NULL; telemetry.update(); if(!robot.isLedOn){ if(direction == Direction.LEFT){ robot.strafeLeft(0.35f); }else if(direction == Direction.RIGHT){ robot.strafeRight(0.35f); }else{ robot.stop(); break; } } float red = robot.colorSensor.red(); float blue = robot.colorSensor.blue(); float green = robot.colorSensor.green(); if(setSeconds){ seconds = timer.seconds(); telemetry.addData("Seconds Since Activation: ", seconds); telemetry.update(); } if(seconds > 2 || seconds == -1) { if ((red > blue) && !robot.isLedOn && robot.alliance != AllianceColor.RED) { seenColor = AllianceColor.RED; } if(red > blue && robot.alliance == AllianceColor.RED){ seenColor = AllianceColor.NULL; } if ((blue > red) && !robot.isLedOn && robot.alliance != AllianceColor.BLUE) { seenColor = AllianceColor.BLUE; } if(blue > red && robot.alliance == AllianceColor.BLUE){ seenColor = AllianceColor.NULL; } switch (robot.alliance) { case RED: if ((red > blue) && !robot.isLedOn) { robot.enableColorSensorLED(true); } break; case BLUE: if ((blue > red) && !robot.isLedOn) { robot.enableColorSensorLED(true); } break; case NULL: break; } setSeconds = false; seconds = -1; } if(robot.isLedOn){ if(red == 0 && blue == 0 && green == 0){ //Move a little and go forward to press button if(seenColor == AllianceColor.NULL) { robot.strafeForTime(direction, (float) DRIVE_SPEED, .15f); }else{ robot.strafeForTime(direction, (float) DRIVE_SPEED, .10f); } encoderDrive(.1, 7, 7, 10); encoderDrive(.1, -7, -7, 10); beaconsPressed += 1; timer.reset(); setSeconds = true; //After, turn led off if(beaconsPressed == 1) { if(robot.alliance == AllianceColor.RED) { robot.rotateRightSideForTime(-0.1f, .65f); }else if(robot.alliance == AllianceColor.BLUE){ robot.rotateLeftSideForTime(-0.1f, .65f); } } robot.enableColorSensorLED(false); } } } robot.isSensing = false; } }
Java
@SuppressWarnings({"unchecked","rawtypes"}) public class GenCharClass extends StdCharClass { protected String ID="GenCharClass"; protected Integer[] nameLevels={Integer.valueOf(0)}; protected String baseClass="Commoner"; protected String hitPointsFormula="((@x6<@x7)/3)+(1*(1?6))"; protected String manaFormula="((@x4<@x5)/6)+(1*(1?3))"; protected String movementFormula="5*((@x2<@x3)/18)"; protected int levelCap=-1; protected int bonusPracLevel=0; protected int bonusAttackLevel=0; protected int attackAttribute=CharStats.STAT_STRENGTH; protected int pracsFirstLevel=5; protected int trainsFirstLevel=3; protected int levelsPerBonusDamage=10; protected int allowedArmorLevel=CharClass.ARMOR_ANY; protected String otherLimitations=""; protected String otherBonuses=""; protected String qualifications=""; protected String[] xtraValues=null; protected SubClassRule subClassRule=SubClassRule.BASEONLY; protected int selectability=0; @Override public String getManaFormula(){return manaFormula; } @Override public String getHitPointsFormula(){return hitPointsFormula; } @Override public SubClassRule getSubClassRule() { return subClassRule; } @Override public int getLevelCap() {return levelCap;} protected int maxNonCraftingSkills=CMProps.getIntVar(CMProps.Int.MAXNONCRAFTINGSKILLS); protected int maxCraftingSkills=CMProps.getIntVar(CMProps.Int.MAXCRAFTINGSKILLS); protected int maxCommonSkills=CMProps.getIntVar(CMProps.Int.MAXCOMMONSKILLS); protected int maxLanguages=CMProps.getIntVar(CMProps.Int.MAXLANGUAGES); @Override public int maxNonCraftingSkills() { return maxNonCraftingSkills;} @Override public int maxCraftingSkills() { return maxCraftingSkills;} @Override public int maxCommonSkills() { return maxCommonSkills;} @Override public int maxLanguages() { return maxLanguages;} // IS *only* used by stdcharclass for weaponliminatations, buildDisallowedWeaponClasses, buildRequiredWeaponMaterials @Override public int allowedWeaponLevel(){return CharClass.WEAPONS_ANY;} private HashSet requiredWeaponMaterials=null; // set of Integer material masks @Override protected HashSet requiredWeaponMaterials(){return requiredWeaponMaterials;} protected int requiredArmorSourceMinor=-1; @Override public int requiredArmorSourceMinor(){return requiredArmorSourceMinor;} private String[] raceRequiredList=new String[0]; @Override public String[] getRequiredRaceList(){ return raceRequiredList; } private Pair<String,Integer>[] minimumStatRequirements=new Pair[0]; @Override public Pair<String,Integer>[] getMinimumStatRequirements() { return minimumStatRequirements; } protected HashSet disallowedWeaponSet=null; // set of Integers for weapon classes @Override protected HashSet disallowedWeaponClasses(MOB mob){return disallowedWeaponSet;} protected CharStats setStats=null; protected CharStats adjStats=null; protected PhyStats adjPStats=null; protected CharState adjState=null; protected CharState startAdjState=null; protected CharClass statBuddy=null; protected CharClass eventBuddy=null; protected int disableFlags=0; protected String startingMoney=""; @Override public boolean raceless(){return (disableFlags&CharClass.GENFLAG_NORACE)==CharClass.GENFLAG_NORACE;} @Override public boolean leveless(){return (disableFlags&CharClass.GENFLAG_NOLEVELS)==CharClass.GENFLAG_NOLEVELS;} @Override public boolean expless(){return (disableFlags&CharClass.GENFLAG_NOEXP)==CharClass.GENFLAG_NOEXP;} @Override public boolean showThinQualifyList(){return (disableFlags&CharClass.GENFLAG_THINQUALLIST)==CharClass.GENFLAG_THINQUALLIST;} @Override public String getStartingMoney() { return startingMoney; } //protected Vector outfitChoices=null; from stdcharclass -- but don't forget them! protected List<String>[] securityGroups=new List[0]; protected Integer[] securityGroupLevels={}; protected Map<Integer,CMSecurity.SecGroup> securityGroupCache=new Hashtable<Integer,CMSecurity.SecGroup>(); protected String helpEntry = ""; @Override public SecGroup getSecurityFlags(int classLevel) { if(securityGroups.length==0) return super.getSecurityFlags(classLevel); if(securityGroupCache.containsKey(Integer.valueOf(classLevel))) return securityGroupCache.get(Integer.valueOf(classLevel)); final List<String> allFlags=new ArrayList<String>(); for(int i=securityGroupLevels.length-1;i>=0;i--) if((classLevel>=securityGroupLevels[i].intValue()) &&(i<securityGroups.length)) allFlags.addAll(securityGroups[i]); final SecGroup g = CMSecurity.instance().createGroup("", allFlags); securityGroupCache.put(Integer.valueOf(classLevel),g); return g; } @Override public boolean isGeneric(){return true;} @Override public String ID(){return ID;} @Override public String name(){return names[0];} @Override public String name(int classLevel) { for(int i=nameLevels.length-1;i>=0;i--) if((classLevel>=nameLevels[i].intValue()) &&(i<names.length)) return names[i]; return names[0]; } @Override public String baseClass(){return baseClass;} @Override public int getBonusPracLevel(){return bonusPracLevel;} @Override public int getBonusAttackLevel(){return bonusAttackLevel;} @Override public int getAttackAttribute(){return attackAttribute;} @Override public int getPracsFirstLevel(){return pracsFirstLevel;} @Override public int getTrainsFirstLevel(){return trainsFirstLevel;} @Override public int getLevelsPerBonusDamage(){ return levelsPerBonusDamage;} @Override public String getMovementFormula(){return movementFormula;} @Override public int allowedArmorLevel(){return allowedArmorLevel;} @Override public String getOtherLimitsDesc(){return otherLimitations;} @Override public String getOtherBonusDesc(){return otherBonuses;} @Override public int availabilityCode(){return selectability;} public GenCharClass() { names=new String[1]; names[0]="genmob"; xtraValues=CMProps.getExtraStatCodesHolder(this); } @Override public String getWeaponLimitDesc() { final StringBuffer str=new StringBuffer(""); if((disallowedWeaponClasses(null)!=null)&&(disallowedWeaponClasses(null).size()>0)) { str.append(L("The following weapon types may not be used: ")); for(final Iterator i=disallowedWeaponClasses(null).iterator();i.hasNext();) { final Integer I=(Integer)i.next(); str.append(CMStrings.capitalizeAndLower(Weapon.CLASS_DESCS[I.intValue()])+" "); } str.append(". "); } if((requiredWeaponMaterials()!=null)&&(requiredWeaponMaterials().size()>0)) { str.append(L("Requires using weapons made of the following materials: ")); for(final Iterator i=requiredWeaponMaterials().iterator();i.hasNext();) { final Integer I=(Integer)i.next(); str.append(CMStrings.capitalizeAndLower(CMLib.materials().getMaterialDesc(I.intValue()))+" "); } str.append(". "); } if(str.length()==0) str.append(L("No limitations.")); return str.toString().trim(); } @Override public void cloneFix(CharClass C) { } @Override public CMObject newInstance(){try{return getClass().newInstance();}catch(final Exception e){return new GenCharClass();}} @Override public CMObject copyOf() { final GenCharClass E=new GenCharClass(); E.setClassParms(classParms()); return E; } public boolean loaded(){return true;} public void setLoaded(boolean truefalse){} @Override public boolean qualifiesForThisClass(MOB mob, boolean quiet) { if(!super.qualifiesForThisClass(mob,quiet)) return false; if(mob != null) { if((!mob.isMonster())&&(mob.basePhyStats().level()>0)) { if(!CMLib.masking().maskCheck(qualifications,mob,true)) { if(!quiet) mob.tell(L("You must meet the following qualifications to be a @x1:\n@x2",name(),getStatQualDesc())); return false; } } } return true; } @Override public String getStatQualDesc() { final String superQual=super.getStatQualDesc(); if((qualifications!=null)&&(qualifications.length()>0)) return superQual+", "+CMLib.masking().maskDesc(qualifications); return superQual; } protected String getCharClassLocatorID(CharClass C) { if(C==null) return ""; if(C.isGeneric()) return C.ID(); if(C==CMClass.getCharClass(C.ID())) return C.ID(); return C.getClass().getName(); } @Override public void affectPhyStats(Physical affected, PhyStats affectableStats) { if(adjPStats!=null) { affectableStats.setAbility(affectableStats.ability()+adjPStats.ability()); affectableStats.setArmor(affectableStats.armor()+adjPStats.armor()); affectableStats.setAttackAdjustment(affectableStats.attackAdjustment()+adjPStats.attackAdjustment()); affectableStats.setDamage(affectableStats.damage()+adjPStats.damage()); affectableStats.setDisposition(affectableStats.disposition()|adjPStats.disposition()); affectableStats.setHeight(affectableStats.height()+adjPStats.height()); affectableStats.setLevel(affectableStats.level()+adjPStats.level()); affectableStats.setSensesMask(affectableStats.sensesMask()|adjPStats.sensesMask()); affectableStats.setSpeed(affectableStats.speed()+adjPStats.speed()); affectableStats.setWeight(affectableStats.weight()+adjPStats.weight()); } if(statBuddy!=null) statBuddy.affectPhyStats(affected,affectableStats); } @Override public boolean tick(Tickable myChar, int tickID) { if(eventBuddy!=null) if(!eventBuddy.tick(myChar,tickID)) return false; return super.tick(myChar, tickID); } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if(eventBuddy!=null) eventBuddy.executeMsg(myHost, msg); super.executeMsg(myHost, msg); } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((eventBuddy!=null) &&(!eventBuddy.okMessage(myHost, msg))) return false; return super.okMessage(myHost, msg); } @Override public void affectCharStats(MOB affectedMob, CharStats affectableStats) { if(adjStats!=null) for(final int i: CharStats.CODES.ALLCODES()) affectableStats.setStat(i,affectableStats.getStat(i)+adjStats.getStat(i)); if(setStats!=null) for(final int i: CharStats.CODES.ALLCODES()) if(setStats.getStat(i)!=0) affectableStats.setStat(i,setStats.getStat(i)); if(statBuddy!=null) statBuddy.affectCharStats(affectedMob,affectableStats); } @Override public void affectCharState(MOB affectedMob, CharState affectableMaxState) { if(adjState!=null) { affectableMaxState.setFatigue(affectableMaxState.getFatigue()+adjState.getFatigue()); affectableMaxState.setHitPoints(affectableMaxState.getHitPoints()+adjState.getHitPoints()); affectableMaxState.setHunger(affectableMaxState.getHunger()+adjState.getHunger()); affectableMaxState.setMana(affectableMaxState.getMana()+adjState.getMana()); affectableMaxState.setMovement(affectableMaxState.getMovement()+adjState.getMovement()); affectableMaxState.setThirst(affectableMaxState.getThirst()+adjState.getThirst()); } if(statBuddy!=null) statBuddy.affectCharState(affectedMob,affectableMaxState); } @Override public String classParms() { final StringBuffer str=new StringBuffer(""); str.append("<CCLASS><ID>"+ID()+"</ID>"); for(int i=0;i<names.length;i++) { str.append(CMLib.xml().convertXMLtoTag("NAME"+i,names[i])); str.append(CMLib.xml().convertXMLtoTag("NAMELEVEL"+i,nameLevels[i].intValue())); } str.append(CMLib.xml().convertXMLtoTag("BASE",baseClass())); str.append(CMLib.xml().convertXMLtoTag("LVLPRAC",""+bonusPracLevel)); str.append(CMLib.xml().convertXMLtoTag("MANAFRM",""+manaFormula)); str.append(CMLib.xml().convertXMLtoTag("MVMTFRM",""+movementFormula)); str.append(CMLib.xml().convertXMLtoTag("HPFRM",""+hitPointsFormula)); str.append(CMLib.xml().convertXMLtoTag("LEVELCAP",""+levelCap)); str.append(CMLib.xml().convertXMLtoTag("LVLATT",""+bonusAttackLevel)); str.append(CMLib.xml().convertXMLtoTag("ATTATT",""+attackAttribute)); str.append(CMLib.xml().convertXMLtoTag("FSTPRAC",""+pracsFirstLevel)); str.append(CMLib.xml().convertXMLtoTag("FSTTRAN",""+trainsFirstLevel)); str.append(CMLib.xml().convertXMLtoTag("LVLDAM",""+levelsPerBonusDamage)); str.append(CMLib.xml().convertXMLtoTag("ARMOR",""+allowedArmorLevel)); str.append(CMLib.xml().convertXMLtoTag("STRLMT",otherLimitations)); str.append(CMLib.xml().convertXMLtoTag("STRBON",otherBonuses)); str.append(CMLib.xml().convertXMLtoTag("QUAL",qualifications)); str.append(CMLib.xml().convertXMLtoTag("PLAYER",""+selectability)); str.append(CMLib.xml().convertXMLtoTag("MAXNCS",""+maxNonCraftingSkills)); str.append(CMLib.xml().convertXMLtoTag("MAXCRS",""+maxCraftingSkills)); str.append(CMLib.xml().convertXMLtoTag("MAXCMS",""+maxCommonSkills)); str.append(CMLib.xml().convertXMLtoTag("MAXLGS",""+maxLanguages)); str.append(CMLib.xml().convertXMLtoTag("SUBRUL",subClassRule.toString())); str.append(CMLib.xml().convertXMLtoTag("RACQUAL",CMParms.toStringList(getRequiredRaceList()))); if(getMinimumStatRequirements().length==0) str.append("<MINSTATS />"); else { str.append("<MINSTATS>"); for(final Pair<String,Integer> stat : getMinimumStatRequirements()) str.append("<STAT NAME=\""+stat.first+"\" MIN="+stat.second.toString()+" />"); str.append("</MINSTATS>"); } str.append(CMLib.xml().convertXMLtoTag("HELP",CMLib.xml().parseOutAngleBrackets(helpEntry))); if(adjPStats==null) str.append("<ESTATS/>"); else str.append(CMLib.xml().convertXMLtoTag("ESTATS",CMLib.coffeeMaker().getPhyStatsStr(adjPStats))); if(adjStats==null) str.append("<ASTATS/>"); else str.append(CMLib.xml().convertXMLtoTag("ASTATS",CMLib.coffeeMaker().getCharStatsStr(adjStats))); if(setStats==null) str.append("<CSTATS/>"); else str.append(CMLib.xml().convertXMLtoTag("CSTATS",CMLib.coffeeMaker().getCharStatsStr(setStats))); if(adjState==null) str.append("<ASTATE/>"); else str.append(CMLib.xml().convertXMLtoTag("ASTATE",CMLib.coffeeMaker().getCharStateStr(adjState))); if(startAdjState==null) str.append("<STARTASTATE/>"); else str.append(CMLib.xml().convertXMLtoTag("STARTASTATE",CMLib.coffeeMaker().getCharStateStr(startAdjState))); str.append(CMLib.xml().convertXMLtoTag("DISFLAGS",""+disableFlags)); final Vector ables=getAbleSet(); if((ables==null)||(ables.size()==0)) str.append("<CABILITIES/>"); else { str.append("<CABILITIES>"); for(int r=0;r<ables.size();r++) { str.append("<CABILITY>"); str.append("<CACLASS>"+((AbilityMapper.AbilityMapping)ables.elementAt(r)).abilityID+"</CACLASS>"); str.append("<CALEVEL>"+((AbilityMapper.AbilityMapping)ables.elementAt(r)).qualLevel+"</CALEVEL>"); str.append("<CAPROFF>"+((AbilityMapper.AbilityMapping)ables.elementAt(r)).defaultProficiency+"</CAPROFF>"); str.append("<CAAGAIN>"+((AbilityMapper.AbilityMapping)ables.elementAt(r)).autoGain+"</CAAGAIN>"); str.append("<CASECR>"+((AbilityMapper.AbilityMapping)ables.elementAt(r)).isSecret+"</CASECR>"); str.append("<CAPARM>"+((AbilityMapper.AbilityMapping)ables.elementAt(r)).defaultParm+"</CAPARM>"); str.append("<CAPREQ>"+((AbilityMapper.AbilityMapping)ables.elementAt(r)).originalSkillPreReqList+"</CAPREQ>"); str.append("<CAMASK>"+((AbilityMapper.AbilityMapping)ables.elementAt(r)).extraMask+"</CAMASK>"); str.append("<CAMAXP>"+((AbilityMapper.AbilityMapping)ables.elementAt(r)).maxProficiency+"</CAMAXP>"); str.append("</CABILITY>"); } str.append("</CABILITIES>"); } if((disallowedWeaponSet==null)||(disallowedWeaponSet.size()==0)) str.append("<NOWEAPS/>"); else { str.append("<NOWEAPS>"); for(final Iterator i=disallowedWeaponSet.iterator();i.hasNext();) { final Integer I=(Integer)i.next(); str.append(CMLib.xml().convertXMLtoTag("WCLASS",""+I.intValue())); } str.append("</NOWEAPS>"); } if((requiredWeaponMaterials==null)||(requiredWeaponMaterials.size()==0)) str.append("<NOWMATS/>"); else { str.append("<NOWMATS>"); for(final Iterator i=requiredWeaponMaterials.iterator();i.hasNext();) { final Integer I=(Integer)i.next(); str.append(CMLib.xml().convertXMLtoTag("WMAT",""+I.intValue())); } str.append("</NOWMATS>"); } if((outfit(null)==null)||(outfit(null).size()==0)) str.append("<OUTFIT/>"); else { str.append("<OUTFIT>"); for(final Item I : outfit(null)) { str.append("<OFTITEM>"); str.append(CMLib.xml().convertXMLtoTag("OFCLASS",CMClass.classID(I))); str.append(CMLib.xml().convertXMLtoTag("OFDATA",CMLib.xml().parseOutAngleBrackets(I.text()))); str.append("</OFTITEM>"); } str.append("</OUTFIT>"); } for(int i=0;i<securityGroups.length;i++) if(i<securityGroupLevels.length) { str.append(CMLib.xml().convertXMLtoTag("SSET"+i,CMParms.combineQuoted(securityGroups[i],0))); str.append(CMLib.xml().convertXMLtoTag("SSETLEVEL"+i,securityGroupLevels[i].intValue())); } str.append(CMLib.xml().convertXMLtoTag("MONEY",startingMoney)); str.append(CMLib.xml().convertXMLtoTag("ARMORMINOR",""+requiredArmorSourceMinor)); str.append(CMLib.xml().convertXMLtoTag("STATCLASS",getCharClassLocatorID(statBuddy))); str.append(CMLib.xml().convertXMLtoTag("EVENTCLASS",getCharClassLocatorID(eventBuddy))); if(xtraValues==null) xtraValues=CMProps.getExtraStatCodesHolder(this); for(int i=this.getSaveStatIndex();i<getStatCodes().length;i++) str.append(CMLib.xml().convertXMLtoTag(getStatCodes()[i],getStat(getStatCodes()[i]))); str.append("</CCLASS>"); return str.toString(); } @Override public void setClassParms(String parms) { if(parms.trim().length()==0) return; final List<XMLLibrary.XMLpiece> xml=CMLib.xml().parseAllXML(parms); if(xml==null) { Log.errOut("GenCharClass","Unable to parse: "+parms); return; } final List<XMLLibrary.XMLpiece> classData=CMLib.xml().getContentsFromPieces(xml,"CCLASS"); if(classData==null){ Log.errOut("GenCharClass","Unable to get CCLASS data."); return;} final String classID=CMLib.xml().getValFromPieces(classData,"ID"); if(classID.length()==0) return; ID=classID; final String singleName=CMLib.xml().getValFromPieces(classData,"NAME"); if((singleName!=null)&&(singleName.length()>0)) { names=new String[1]; names[0]=singleName; nameLevels=new Integer[1]; nameLevels[0]=Integer.valueOf(0); } else { final Vector nameSet=new Vector(); final Vector levelSet=new Vector(); int index=0; int lastLevel=-1; while(true) { final String name=CMLib.xml().getValFromPieces(classData,"NAME"+index); final int level=CMLib.xml().getIntFromPieces(classData,"NAMELEVEL"+index); if((name.length()==0)||(level<=lastLevel)) break; nameSet.addElement(name); levelSet.addElement(Integer.valueOf(level)); lastLevel=level; index++; } names=new String[nameSet.size()]; nameLevels=new Integer[levelSet.size()]; for(int i=0;i<nameSet.size();i++) { names[i]=(String)nameSet.elementAt(i); nameLevels[i]=(Integer)levelSet.elementAt(i); } } final String base=CMLib.xml().getValFromPieces(classData,"BASE"); if((base==null)||(base.length()==0)) return; baseClass=base; hitPointsFormula=CMLib.xml().getValFromPieces(classData,"HPFRM"); if((hitPointsFormula==null)||(hitPointsFormula.length()==0)) { int hpDivisor=CMLib.xml().getIntFromPieces(classData,"HPDIV"); if(hpDivisor==0) hpDivisor=3; final int hpDice=CMLib.xml().getIntFromPieces(classData,"HPDICE"); final int hpDie=CMLib.xml().getIntFromPieces(classData,"HPDIE"); hitPointsFormula="((@x6<@x7)/"+hpDivisor+")+("+hpDice+"*(1?"+hpDie+"))"; } bonusPracLevel=CMLib.xml().getIntFromPieces(classData,"LVLPRAC"); manaFormula=CMLib.xml().getValFromPieces(classData,"MANAFRM"); if((manaFormula==null)||(manaFormula.length()==0)) { int manaDivisor=CMLib.xml().getIntFromPieces(classData,"MANADIV"); if(manaDivisor==0) manaDivisor=3; final int manaDice=CMLib.xml().getIntFromPieces(classData,"MANADICE"); final int manaDie=CMLib.xml().getIntFromPieces(classData,"MANADIE"); manaFormula="((@x4<@x5)/"+manaDivisor+")+("+manaDice+"*(1?"+manaDie+"))"; } levelCap=CMLib.xml().getIntFromPieces(classData,"LEVELCAP"); bonusAttackLevel=CMLib.xml().getIntFromPieces(classData,"LVLATT"); attackAttribute=CMLib.xml().getIntFromPieces(classData,"ATTATT"); trainsFirstLevel=CMLib.xml().getIntFromPieces(classData,"FSTTRAN"); pracsFirstLevel=CMLib.xml().getIntFromPieces(classData,"FSTPRAC"); levelsPerBonusDamage=CMLib.xml().getIntFromPieces(classData,"LVLDAM"); movementFormula=CMLib.xml().getValFromPieces(classData,"MVMTFRM"); if((movementFormula==null)||(movementFormula.length()==0)) { final int movementMultiplier=CMLib.xml().getIntFromPieces(classData,"LVLMOVE"); movementFormula=movementMultiplier+"*((@x2<@x3)/18)"; } allowedArmorLevel=CMLib.xml().getIntFromPieces(classData,"ARMOR"); //weaponLimitations=CMLib.xml().getValFromPieces(classData,"STRWEAP"); //armorLimitations=CMLib.xml().getValFromPieces(classData,"STRARM"); otherLimitations=CMLib.xml().getValFromPieces(classData,"STRLMT"); otherBonuses=CMLib.xml().getValFromPieces(classData,"STRBON"); qualifications=CMLib.xml().getValFromPieces(classData,"QUAL"); maxNonCraftingSkills=CMLib.xml().getIntFromPieces(classData,"MAXNCS"); maxCraftingSkills=CMLib.xml().getIntFromPieces(classData,"MAXCRS"); maxCommonSkills=CMLib.xml().getIntFromPieces(classData,"MAXCMS"); maxLanguages=CMLib.xml().getIntFromPieces(classData,"MAXLGS"); subClassRule=(SubClassRule)CMath.s_valueOf(SubClassRule.class,CMLib.xml().getValFromPieces(classData,"SUBRUL"),SubClassRule.BASEONLY); helpEntry=CMLib.xml().restoreAngleBrackets(CMLib.xml().getValFromPieces(classData,"HELP")); raceRequiredList=CMParms.parseCommas(CMLib.xml().getValFromPieces(classData,"RACQUAL"), true).toArray(new String[0]); final List<Pair<String,Integer>> statQuals=new ArrayList<Pair<String,Integer>>(); final List<XMLLibrary.XMLpiece> mV=CMLib.xml().getContentsFromPieces(classData,"MINSTATS"); if((mV!=null)&&(mV.size()>0)) for(final XMLLibrary.XMLpiece p : mV) if(p.tag.equalsIgnoreCase("STAT")) statQuals.add(new Pair<String,Integer>(p.parms.get("NAME"),Integer.valueOf(CMath.s_int(p.parms.get("MIN"))))); minimumStatRequirements=statQuals.toArray(new Pair[0]); final String s=CMLib.xml().getValFromPieces(classData,"PLAYER"); if(CMath.isNumber(s)) selectability=CMath.s_int(s); else selectability=CMath.s_bool(s)?Area.THEME_FANTASY:0; adjPStats=null; final String eStats=CMLib.xml().getValFromPieces(classData,"ESTATS"); if(eStats.length()>0){ adjPStats=(PhyStats)CMClass.getCommon("DefaultPhyStats"); CMLib.coffeeMaker().setPhyStats(adjPStats,eStats);} adjStats=null; final String aStats=CMLib.xml().getValFromPieces(classData,"ASTATS"); if(aStats.length()>0){ adjStats=(CharStats)CMClass.getCommon("DefaultCharStats"); CMLib.coffeeMaker().setCharStats(adjStats,aStats);} setStats=null; final String cStats=CMLib.xml().getValFromPieces(classData,"CSTATS"); if(cStats.length()>0){ setStats=(CharStats)CMClass.getCommon("DefaultCharStats"); CMLib.coffeeMaker().setCharStats(setStats,cStats);} adjState=null; final String aState=CMLib.xml().getValFromPieces(classData,"ASTATE"); if(aState.length()>0){ adjState=(CharState)CMClass.getCommon("DefaultCharState"); CMLib.coffeeMaker().setCharState(adjState,aState);} startAdjState=null; disableFlags=CMLib.xml().getIntFromPieces(classData,"DISFLAGS"); final String saState=CMLib.xml().getValFromPieces(classData,"STARTASTATE"); if(saState.length()>0){ startAdjState=(CharState)CMClass.getCommon("DefaultCharState"); startAdjState.setAllValues(0); CMLib.coffeeMaker().setCharState(startAdjState,saState);} List<XMLLibrary.XMLpiece> xV=CMLib.xml().getContentsFromPieces(classData,"CABILITIES"); CMLib.ableMapper().delCharMappings(ID()); if((xV!=null)&&(xV.size()>0)) for(int x=0;x<xV.size();x++) { final XMLLibrary.XMLpiece iblk=xV.get(x); if((!iblk.tag.equalsIgnoreCase("CABILITY"))||(iblk.contents==null)) continue; // I hate backwards compatibility. String maxProff=CMLib.xml().getValFromPieces(iblk.contents,"CAMAXP"); if((maxProff==null)||(maxProff.trim().length()==0)) maxProff="100"; CMLib.ableMapper().addCharAbilityMapping(ID(), CMLib.xml().getIntFromPieces(iblk.contents,"CALEVEL"), CMLib.xml().getValFromPieces(iblk.contents,"CACLASS"), CMLib.xml().getIntFromPieces(iblk.contents,"CAPROFF"), CMath.s_int(maxProff), CMLib.xml().getValFromPieces(iblk.contents,"CAPARM"), CMLib.xml().getBoolFromPieces(iblk.contents,"CAAGAIN"), CMLib.xml().getBoolFromPieces(iblk.contents,"CASECR"), CMParms.parseCommas(CMLib.xml().getValFromPieces(iblk.contents,"CAPREQ"),true), CMLib.xml().getValFromPieces(iblk.contents,"CAMASK"), null); } // now WEAPON RESTRICTIONS! xV=CMLib.xml().getContentsFromPieces(classData,"NOWEAPS"); disallowedWeaponSet=null; if((xV!=null)&&(xV.size()>0)) { disallowedWeaponSet=new HashSet(); for(int x=0;x<xV.size();x++) { final XMLLibrary.XMLpiece iblk=xV.get(x); if((!iblk.tag.equalsIgnoreCase("WCLASS"))||(iblk.contents==null)) continue; disallowedWeaponSet.add(Integer.valueOf(CMath.s_int(iblk.value))); } } // now WEAPON MATERIALS! xV=CMLib.xml().getContentsFromPieces(classData,"NOWMATS"); requiredWeaponMaterials=null; if((xV!=null)&&(xV.size()>0)) { requiredWeaponMaterials=new HashSet(); for(int x=0;x<xV.size();x++) { final XMLLibrary.XMLpiece iblk=xV.get(x); if((!iblk.tag.equalsIgnoreCase("WMAT"))||(iblk.contents==null)) continue; requiredWeaponMaterials.add(Integer.valueOf(CMath.s_int(iblk.value))); } } // now OUTFIT! final List<XMLLibrary.XMLpiece> oV=CMLib.xml().getContentsFromPieces(classData,"OUTFIT"); outfitChoices=null; if((oV!=null)&&(oV.size()>0)) { outfitChoices=new Vector(); for(int x=0;x<oV.size();x++) { final XMLLibrary.XMLpiece iblk=oV.get(x); if((!iblk.tag.equalsIgnoreCase("OFTITEM"))||(iblk.contents==null)) continue; final Item newOne=CMClass.getItem(CMLib.xml().getValFromPieces(iblk.contents,"OFCLASS")); final String idat=CMLib.xml().getValFromPieces(iblk.contents,"OFDATA"); newOne.setMiscText(CMLib.xml().restoreAngleBrackets(idat)); newOne.recoverPhyStats(); outfitChoices.add(newOne); } } // security groups final List<List<String>> groupSet=new Vector(); final List<Integer> groupLevelSet=new Vector(); int index=0; int lastLevel=-1; while(true) { final String groups=CMLib.xml().getValFromPieces(classData,"SSET"+index); final int groupLevel=CMLib.xml().getIntFromPieces(classData,"SSETLEVEL"+index); if((groups.length()==0)||(groupLevel<=lastLevel)) break; groupSet.add(CMParms.parse(groups.toUpperCase())); groupLevelSet.add(Integer.valueOf(groupLevel)); lastLevel=groupLevel; index++; } securityGroups=new Vector[groupSet.size()]; securityGroupLevels=new Integer[groupLevelSet.size()]; for(int i=0;i<groupSet.size();i++) { securityGroups[i]=groupSet.get(i); securityGroupLevels[i]=groupLevelSet.get(i); } securityGroupCache.clear(); requiredArmorSourceMinor=CMLib.xml().getIntFromPieces(classData,"ARMORMINOR"); startingMoney=CMLib.xml().getValFromPieces(classData,"MONEY"); if(startingMoney==null) startingMoney=""; setStat("STATCLASS",CMLib.xml().getValFromPieces(classData,"STATCLASS")); setStat("EVENTCLASS",CMLib.xml().getValFromPieces(classData,"EVENTCLASS")); xtraValues=CMProps.getExtraStatCodesHolder(this); for(int i=this.getSaveStatIndex();i<getStatCodes().length;i++) setStat(getStatCodes()[i],CMLib.xml().getValFromPieces(classData, getStatCodes()[i])); } protected Vector getAbleSet() { final Vector VA=new Vector(9); final List<AbilityMapper.AbilityMapping> V=CMLib.ableMapper().getUpToLevelListings(ID(),Integer.MAX_VALUE,true,false); for(final AbilityMapper.AbilityMapping able : V) { final String AID=able.abilityID; final AbilityMapper.AbilityMapping newMAP=new AbilityMapper.AbilityMapping(ID()); newMAP.abilityID = AID; newMAP.qualLevel = CMLib.ableMapper().getQualifyingLevel(ID(),false,AID); newMAP.defaultProficiency = CMLib.ableMapper().getDefaultProficiency(ID(),false,AID); newMAP.autoGain = CMLib.ableMapper().getDefaultGain(ID(),false,AID); newMAP.isSecret = CMLib.ableMapper().getSecretSkill(ID(),false,AID); newMAP.defaultParm = CMLib.ableMapper().getDefaultParm(ID(),false,AID); newMAP.originalSkillPreReqList = CMLib.ableMapper().getPreReqStrings(ID(),false,AID); newMAP.extraMask = CMLib.ableMapper().getExtraMask(ID(),false,AID); newMAP.maxProficiency = CMLib.ableMapper().getMaxProficiency(ID(),false,AID); VA.addElement(newMAP); } return VA; } protected static String[] CODES={"ID","NAME","BASE","HITPOINTSFORMULA","SUBRUL", "LVLPRAC","RACQUAL","LVLATT","ATTATT","FSTTRAN", "FSTPRAC","LVLDAM","MOVEMENTFORMULA","ARMOR","STRWEAP", "STRARM","STRLMT","STRBON","QUAL","PLAYER", "ESTATS","ASTATS","CSTATS","ASTATE","NUMCABLE", "GETCABLE","GETCABLELVL","GETCABLEPROF","GETCABLEGAIN","GETCABLESECR", "GETCABLEPARM","NUMWEP","GETWEP", "NUMOFT","GETOFTID", "GETOFTPARM","NUMMINSTATS","MANAFORMULA","GETMINSTAT","DISFLAGS", "STARTASTATE","NUMNAME","NAMELEVEL","NUMSSET","SSET", "SSETLEVEL","NUMWMAT","GETWMAT","ARMORMINOR","STATCLASS", "EVENTCLASS","GETCABLEPREQ","GETCABLEMASK","HELP","LEVELCAP", "GETCABLEMAXP","MAXNCS","MAXCRS","MAXCMS","MAXLGS","GETSTATMIN", "MONEY" }; @Override public String getStat(String code) { int num=0; int numDex=code.length(); while((numDex>0)&&(Character.isDigit(code.charAt(numDex-1)))) numDex--; if(numDex<code.length()) { num=CMath.s_int(code.substring(numDex)); code=code.substring(0,numDex); } switch(getCodeNum(code)) { case 0: return ID; case 1: if(num<names.length) return names[num]; break; case 2: return baseClass; case 3: return ""+hitPointsFormula; case 4: return subClassRule.toString(); case 5: return ""+bonusPracLevel; case 6: return CMParms.toStringList(getRequiredRaceList()); case 7: return ""+bonusAttackLevel; case 8: return ""+attackAttribute; case 9: return ""+trainsFirstLevel; case 10: return ""+pracsFirstLevel; case 11: return ""+levelsPerBonusDamage; case 12: return ""+movementFormula; case 13: return ""+allowedArmorLevel; case 14: return "";//weaponLimitations; case 15: return "";//armorLimitations; case 16: return otherLimitations; case 17: return otherBonuses; case 18: return qualifications; case 19: return ""+selectability; case 20: return (adjPStats==null)?"":CMLib.coffeeMaker().getPhyStatsStr(adjPStats); case 21: return (adjStats==null)?"":CMLib.coffeeMaker().getCharStatsStr(adjStats); case 22: return (setStats==null)?"":CMLib.coffeeMaker().getCharStatsStr(setStats); case 23: return (adjState==null)?"":CMLib.coffeeMaker().getCharStateStr(adjState); case 24: return Integer.toString(getAbleSet().size()); case 25: return ((AbilityMapper.AbilityMapping)getAbleSet().elementAt(num)).abilityID; case 26: return Integer.toString(((AbilityMapper.AbilityMapping)getAbleSet().elementAt(num)).qualLevel); case 27: return Integer.toString(((AbilityMapper.AbilityMapping)getAbleSet().elementAt(num)).defaultProficiency); case 28: return Boolean.toString(((AbilityMapper.AbilityMapping)getAbleSet().elementAt(num)).autoGain); case 29: return Boolean.toString(((AbilityMapper.AbilityMapping)getAbleSet().elementAt(num)).isSecret); case 30: return ((AbilityMapper.AbilityMapping)getAbleSet().elementAt(num)).defaultParm; case 31: return ""+((disallowedWeaponSet!=null)?disallowedWeaponSet.size():0); case 32: return CMParms.toStringList(disallowedWeaponSet); case 33: return ""+((outfit(null)!=null)?outfit(null).size():0); case 34: return ""+((outfit(null)!=null)?outfit(null).get(num).ID():""); case 35: return ""+((outfit(null)!=null)?outfit(null).get(num).text():""); case 36: return ""+getMinimumStatRequirements().length; case 37: return ""+manaFormula; case 38: return getMinimumStatRequirements()[num].first; case 39: return ""+disableFlags; case 40: return (startAdjState==null)?"":CMLib.coffeeMaker().getCharStateStr(startAdjState); case 41: return ""+names.length; case 42: if(num<nameLevels.length) return ""+nameLevels[num].intValue(); break; case 43: return ""+securityGroups.length; case 44: if(num<securityGroups.length) return CMParms.combineQuoted(securityGroups[num],0); break; case 45: if(num<securityGroupLevels.length) return ""+securityGroupLevels[num]; break; case 46: return ""+((requiredWeaponMaterials!=null)?requiredWeaponMaterials.size():0); case 47: return CMParms.toStringList(requiredWeaponMaterials); case 48: return ""+requiredArmorSourceMinor(); case 49: return this.getCharClassLocatorID(statBuddy); case 50: return this.getCharClassLocatorID(eventBuddy); case 51: return ((AbilityMapper.AbilityMapping)getAbleSet().elementAt(num)).originalSkillPreReqList; case 52: return ((AbilityMapper.AbilityMapping)getAbleSet().elementAt(num)).extraMask; case 53: return helpEntry; case 54: return ""+levelCap; case 55: return Integer.toString(((AbilityMapper.AbilityMapping)getAbleSet().elementAt(num)).maxProficiency); case 56: return ""+maxNonCraftingSkills; case 57: return ""+maxCraftingSkills; case 58: return ""+maxCommonSkills; case 59: return ""+maxLanguages; case 60: return getMinimumStatRequirements()[num].second.toString(); case 61: return startingMoney; default: return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code); } return ""; } protected String[] tempables=new String[9]; @Override public void setStat(String code, String val) { int num=0; int numDex=code.length(); while((numDex>0)&&(Character.isDigit(code.charAt(numDex-1)))) numDex--; if(numDex<code.length()) { num=CMath.s_int(code.substring(numDex)); code=code.substring(0,numDex); } switch(getCodeNum(code)) { case 0: ID=val; break; case 1: if(num<names.length) names[num]=val; break; case 2: baseClass=val; break; case 3: hitPointsFormula=val; super.hitPointsDesc=null; break; case 4: subClassRule=(SubClassRule)CMath.s_valueOf(SubClassRule.class,val.toUpperCase().trim(),SubClassRule.BASEONLY); break; case 5: bonusPracLevel=CMath.s_parseIntExpression(val); break; case 6: raceRequiredList=CMParms.parseCommas(val,true).toArray(new String[0]); break; case 7: bonusAttackLevel=CMath.s_parseIntExpression(val); break; case 8: attackAttribute=CMath.s_parseListIntExpression(CharStats.CODES.NAMES(),val); break; case 9: trainsFirstLevel=CMath.s_parseIntExpression(val); break; case 10: pracsFirstLevel=CMath.s_parseIntExpression(val); break; case 11: levelsPerBonusDamage=CMath.s_parseIntExpression(val); break; case 12: movementFormula=val; super.movementDesc=null; break; case 13: allowedArmorLevel=CMath.s_parseListIntExpression(CharClass.ARMOR_DESCS,val); break; case 14: break;//weaponLimitations=val;break; case 15: break;//armorLimitations=val;break; case 16: otherLimitations=val;break; case 17: otherBonuses=val;break; case 18: qualifications=val;break; case 19: selectability=CMath.s_parseBitIntExpression(Area.THEME_BIT_NAMES,val); break; case 20: adjPStats=null;if(val.length()>0){adjPStats=(PhyStats)CMClass.getCommon("DefaultPhyStats"); adjPStats.setAllValues(0); CMLib.coffeeMaker().setPhyStats(adjPStats,val);}break; case 21: adjStats=null;if(val.length()>0){adjStats=(CharStats)CMClass.getCommon("DefaultCharStats"); adjStats.setAllValues(0); CMLib.coffeeMaker().setCharStats(adjStats,val);}break; case 22: setStats=null;if(val.length()>0){setStats=(CharStats)CMClass.getCommon("DefaultCharStats"); setStats.setAllValues(0); CMLib.coffeeMaker().setCharStats(setStats,val);}break; case 23: adjState=null;if(val.length()>0){adjState=(CharState)CMClass.getCommon("DefaultCharState"); adjState.setAllValues(0); CMLib.coffeeMaker().setCharState(adjState,val);}break; case 24: CMLib.ableMapper().delCharMappings(ID()); break; case 25: CMLib.ableMapper().addCharAbilityMapping(ID(), CMath.s_int(tempables[1]), val, CMath.s_int(tempables[2]), CMath.s_int(tempables[8]), tempables[5], CMath.s_bool(tempables[3]), CMath.s_bool(tempables[4]), CMParms.parseCommas(tempables[6],true), tempables[7], null); break; case 26: tempables[1]=val; break; case 27: tempables[2]=val; break; case 28: tempables[3]=val; break; case 29: tempables[4]=val; break; case 30: tempables[5]=val; break; case 31: if(CMath.s_int(val)==0) disallowedWeaponSet=null; else disallowedWeaponSet=new HashSet(); break; case 32: { final List<String> V=CMParms.parseCommas(val,true); if(V.size()>0) { disallowedWeaponSet=new HashSet(); for(int v=0;v<V.size();v++) disallowedWeaponSet.add(Integer.valueOf(CMath.s_int(V.get(v)))); } else disallowedWeaponSet=null; break; } case 33: if(CMath.s_int(val)==0) outfitChoices=null; break; case 34: { if(outfitChoices==null) outfitChoices=new Vector(); if(num>=outfitChoices.size()) outfitChoices.add(CMClass.getItem(val)); else outfitChoices.setElementAt(CMClass.getItem(val),num); break; } case 35: { if((outfitChoices!=null)&&(num<outfitChoices.size())) { final Item I=(Item)outfitChoices.elementAt(num); I.setMiscText(val); I.recoverPhyStats(); } break; } case 36: { minimumStatRequirements=new Pair[CMath.s_int(val)]; for(int i=0;i<CMath.s_int(val);i++) minimumStatRequirements[i]=new Pair<String,Integer>("",Integer.valueOf(0)); break; } case 37: manaFormula=val; super.manaDesc=null; break; case 38: minimumStatRequirements[num].first=val; break; case 39: disableFlags=CMath.s_int(val); break; case 40: startAdjState=null;if(val.length()>0){startAdjState=(CharState)CMClass.getCommon("DefaultCharState"); startAdjState.setAllValues(0); CMLib.coffeeMaker().setCharState(startAdjState,val);}break; case 41: num=CMath.s_int(val); if(num>0) { final String[] newNames=new String[num]; final Integer[] newLevels=new Integer[num]; for(int i=0;i<names.length;i++) if(i<num) { newNames[i]=names[i]; newLevels[i]=nameLevels[i]; } if(newNames.length>names.length) for(int i=names.length;i<newNames.length;i++) { newNames[i]=names[names.length-1]; newLevels[i]=Integer.valueOf(newLevels[i-1].intValue()+1); } names=newNames; nameLevels=newLevels; } break; case 42: if(num<nameLevels.length) nameLevels[num]=Integer.valueOf(CMath.s_int(val)); break; case 43:{ num=CMath.s_int(val); if(num<0) num=0; final List<String>[] newGroups=new Vector[num]; final Integer[] newLevels=new Integer[num]; for(int i=0;i<securityGroups.length;i++) if(i<num) { newGroups[i]=securityGroups[i]; newLevels[i]=securityGroupLevels[i]; } if(newGroups.length>securityGroups.length) for(int i=securityGroups.length;i<newGroups.length;i++) { newGroups[i]=new Vector(); if(i==0) newLevels[0]=Integer.valueOf(0); else newLevels[i]=Integer.valueOf(newLevels[i-1].intValue()+1); } securityGroups=newGroups; securityGroupLevels=newLevels; securityGroupCache.clear(); break; } case 44: if(num<securityGroups.length) securityGroups[num]=CMParms.parse(val.toUpperCase()); securityGroupCache.clear(); break; case 45: if(num<securityGroupLevels.length) securityGroupLevels[num]=Integer.valueOf(CMath.s_int(val)); securityGroupCache.clear(); break; case 46: if(CMath.s_int(val)==0) requiredWeaponMaterials=null; else requiredWeaponMaterials=new HashSet(); break; case 47: { final List<String> V=CMParms.parseCommas(val,true); if(V.size()>0) { requiredWeaponMaterials=new HashSet(); for(int v=0;v<V.size();v++) requiredWeaponMaterials.add(Integer.valueOf(CMath.s_int(V.get(v)))); } else requiredWeaponMaterials=null; break; } case 48: requiredArmorSourceMinor=CMath.s_int(val); break; case 49: { statBuddy=CMClass.getCharClass(val); try { if(statBuddy==null) statBuddy=(CharClass)CMClass.getLoadNewClassInstance(CMObjectType.CHARCLASS,val,true); }catch(final Exception e){} break; } case 50: { eventBuddy=CMClass.getCharClass(val); try { if(eventBuddy==null) eventBuddy=(CharClass)CMClass.getLoadNewClassInstance(CMObjectType.CHARCLASS,val,true); }catch(final Exception e){} break; } case 51: tempables[6]=val; break; case 52: tempables[7]=val; break; case 53: helpEntry=val; break; case 54: levelCap=CMath.s_int(val); break; case 55: tempables[8]=val; break; case 56: maxNonCraftingSkills=CMath.s_int(val); break; case 57: maxCraftingSkills=CMath.s_int(val); break; case 58: maxCommonSkills=CMath.s_int(val); break; case 59: maxLanguages=CMath.s_int(val); break; case 60: minimumStatRequirements[num].second=Integer.valueOf(CMath.s_int(val)); break; case 61: startingMoney=val; break; default: CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val); break; } } @Override public void startCharacter(MOB mob, boolean isBorrowedClass, boolean verifyOnly) { super.startCharacter(mob,isBorrowedClass,verifyOnly); if((!verifyOnly)&&(startAdjState!=null)) { mob.baseState().setFatigue(mob.baseState().getFatigue()+startAdjState.getFatigue()); mob.baseState().setHitPoints(mob.baseState().getHitPoints()+startAdjState.getHitPoints()); mob.baseState().setHunger(mob.baseState().getHunger()+startAdjState.getHunger()); mob.baseState().setMana(mob.baseState().getMana()+startAdjState.getMana()); mob.baseState().setMovement(mob.baseState().getMovement()+startAdjState.getMovement()); mob.baseState().setThirst(mob.baseState().getThirst()+startAdjState.getThirst()); } } @Override public int getSaveStatIndex(){return (xtraValues==null)?getStatCodes().length:getStatCodes().length-xtraValues.length;} private static String[] codes=null; @Override public String[] getStatCodes() { if(codes!=null) return codes; codes=CMProps.getStatCodesList(CODES,this); return codes; } @Override protected int getCodeNum(String code) { while((code.length()>0)&&(Character.isDigit(code.charAt(code.length()-1)))) code=code.substring(0,code.length()-1); for(int i=0;i<CODES.length;i++) if(code.equalsIgnoreCase(CODES[i])) return i; return -1; } @Override public boolean sameAs(CharClass E) { if(!(E instanceof GenCharClass)) return false; if(E.classParms().equals(classParms())) return true; return false; } }
Java
public class Port { @JsonProperty("container_port") private int containerPort; @JsonProperty("host_port") private int hostPort; public int getContainerPort() { return containerPort; } public void setContainerPort(int containerPort) { this.containerPort = containerPort; } public int getHostPort() { return hostPort; } public void setHostPort(int hostPort) { this.hostPort = hostPort; } @Override public String toString() { return "Port{" + "containerPort=" + containerPort + ", hostPort=" + hostPort + '}'; } }
Java
public class ProtocolExceptionResolver implements HandlerExceptionResolver { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { logger.debug("ProtocolExceptionResolver.resolveException() called"); int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; String errMsg = exception.getMessage(); if (exception instanceof HTTPException) { HTTPException httpExc = (HTTPException) exception; statusCode = httpExc.getStatusCode(); if (exception instanceof ClientHTTPException) { logger.info("Client sent bad request ( " + statusCode + ")", exception); } else { logger.error("Error while handling request (" + statusCode + ")", exception); } } else { logger.error("Error while handling request", exception); } Map<String, Object> model = new HashMap<>(); model.put(SimpleResponseView.SC_KEY, statusCode); model.put(SimpleResponseView.CONTENT_KEY, errMsg); return new ModelAndView(SimpleResponseView.getInstance(), model); } }
Java
public class MainApplication extends Application { @Override public void onCreate() { super.onCreate(); } }
Java
public class ResourceContext { // =================================================================================== // Thread Local // ============ /** The thread-local for this. */ private static final ThreadLocal<ResourceContext> threadLocal = new ThreadLocal<ResourceContext>(); /** * Get the context of resource by the key. * @return The context of resource. (NullAllowed) */ public static ResourceContext getResourceContextOnThread() { return threadLocal.get(); } /** * Set the context of resource. * @param resourceContext The context of resource. (NotNull) */ public static void setResourceContextOnThread(ResourceContext resourceContext) { threadLocal.set(resourceContext); } /** * Is existing the context of resource on thread? * @return The determination, true or false. */ public static boolean isExistResourceContextOnThread() { return threadLocal.get() != null; } /** * Clear the context of resource on thread. */ public static void clearResourceContextOnThread() { threadLocal.set(null); } // =================================================================================== // Easy-to-Use // =========== /** * @return The behavior command. (NotNull) */ public static BehaviorCommand<?> behaviorCommand() { assertResourceContextExists(); final ResourceContext context = getResourceContextOnThread(); final BehaviorCommand<?> behaviorCommand = context.getBehaviorCommand(); if (behaviorCommand == null) { String msg = "The behavior command should exist: context=" + context; throw new IllegalStateException(msg); } return behaviorCommand; } /** * @return The current database definition. (NotNull) */ public static DBDef currentDBDef() { if (!isExistResourceContextOnThread()) { return DBDef.Unknown; } final DBDef currentDBDef = getResourceContextOnThread().getCurrentDBDef(); if (currentDBDef == null) { return DBDef.Unknown; } return currentDBDef; } public static boolean isCurrentDBDef(DBDef targetDBDef) { return currentDBDef().equals(targetDBDef); } /** * @return The provider of DB meta. (NotNull) */ public static DBMetaProvider dbmetaProvider() { assertResourceContextExists(); final ResourceContext context = getResourceContextOnThread(); final DBMetaProvider provider = context.getDBMetaProvider(); if (provider == null) { String msg = "The provider of DB meta should exist: context=" + context; throw new IllegalStateException(msg); } return provider; } /** * @param tableFlexibleName The flexible name of table. (NotNull) * @return The instance of DB meta. (NullAllowed: if null, means not found) */ public static DBMeta provideDBMeta(String tableFlexibleName) { if (!isExistResourceContextOnThread()) { return null; } final DBMetaProvider provider = getResourceContextOnThread().getDBMetaProvider(); return provider != null ? provider.provideDBMeta(tableFlexibleName) : null; } /** * @param entityType The entity type of table. (NotNull) * @return The instance of DB meta. (NullAllowed) */ public static DBMeta provideDBMeta(Class<?> entityType) { if (!isExistResourceContextOnThread()) { return null; } final DBMetaProvider provider = getResourceContextOnThread().getDBMetaProvider(); return provider != null ? provider.provideDBMeta(entityType) : null; } /** * @param tableFlexibleName The flexible name of table. (NotNull) * @return The instance of DB meta. (NotNull) */ public static DBMeta provideDBMetaChecked(String tableFlexibleName) { assertResourceContextExists(); final ResourceContext context = getResourceContextOnThread(); final DBMetaProvider provider = context.getDBMetaProvider(); if (provider == null) { String msg = "The provider of DB meta should exist:"; msg = msg + " tableFlexibleName=" + tableFlexibleName + " context=" + context; throw new IllegalStateException(msg); } return provider.provideDBMetaChecked(tableFlexibleName); } /** * @param entityType The entity type of table. (NotNull) * @return The instance of DB meta. (NotNull) */ public static DBMeta provideDBMetaChecked(Class<?> entityType) { assertResourceContextExists(); final ResourceContext context = getResourceContextOnThread(); final DBMetaProvider provider = context.getDBMetaProvider(); if (provider == null) { String msg = "The provider of DB meta should exist:"; msg = msg + " entityType=" + entityType + " context=" + context; throw new IllegalStateException(msg); } return provider.provideDBMetaChecked(entityType); } public static SqlAnalyzer createSqlAnalyzer(String sql, boolean blockNullParameter) { assertResourceContextExists(); final ResourceContext context = getResourceContextOnThread(); final SqlAnalyzerFactory factory = context.getSqlAnalyzerFactory(); if (factory == null) { String msg = "The factory of SQL analyzer should exist:"; msg = msg + " sql=" + sql + " blockNullParameter=" + blockNullParameter; throw new IllegalStateException(msg); } final SqlAnalyzer created = factory.create(sql, blockNullParameter); if (created != null) { return created; } String msg = "The factory should not return null:"; msg = msg + " sql=" + sql + " factory=" + factory; throw new IllegalStateException(msg); } public static SQLExceptionHandler createSQLExceptionHandler() { assertResourceContextExists(); final ResourceContext context = getResourceContextOnThread(); final SQLExceptionHandlerFactory factory = context.getSQLExceptionHandlerFactory(); if (factory == null) { String msg = "The factory of SQLException handler should exist."; throw new IllegalStateException(msg); } final SQLExceptionHandler created = factory.create(); if (created != null) { return created; } String msg = "The factory should not return null: factory=" + factory; throw new IllegalStateException(msg); } /** * Is the SQLException from unique constraint? {Use both SQLState and ErrorCode} * @param sqlState SQLState of the SQLException. (NullAllowed) * @param errorCode ErrorCode of the SQLException. (NullAllowed) * @return Is the SQLException from unique constraint? */ public static boolean isUniqueConstraintException(String sqlState, Integer errorCode) { if (!isExistResourceContextOnThread()) { return false; } final SqlClauseCreator sqlClauseCreator = getResourceContextOnThread().getSqlClauseCreator(); if (sqlClauseCreator == null) { return false; } return currentDBDef().dbway().isUniqueConstraintException(sqlState, errorCode); } public static ColumnFunctionCipher findColumnFunctionCipher(String tableDbName, String columnDbName) { assertResourceContextExists(); final ResourceContext context = getResourceContextOnThread(); final GearedCipherManager manager = context.getGearedCipherManager(); return manager != null ? manager.findColumnFunctionCipher(tableDbName, columnDbName) : null; } public static String getOutsideSqlPackage() { final ResourceParameter parameter = resourceParameter(); return parameter != null ? parameter.getOutsideSqlPackage() : null; } public static MappingDateTimeZoneProvider getMappingDateTimeZoneProvider() { final ResourceParameter parameter = resourceParameter(); return parameter != null ? parameter.getMappingDateTimeZoneProvider() : null; } public static TimeZone provideMappingDateTimeZone() { MappingDateTimeZoneProvider provider = getMappingDateTimeZoneProvider(); return provider != null ? provider.provide() : null; } public static String getLogDatePattern() { final ResourceParameter parameter = resourceParameter(); return parameter != null ? parameter.getLogDatePattern() : null; } public static String getLogTimestampPattern() { final ResourceParameter parameter = resourceParameter(); return parameter != null ? parameter.getLogTimestampPattern() : null; } public static String getLogTimePattern() { final ResourceParameter parameter = resourceParameter(); return parameter != null ? parameter.getLogTimePattern() : null; } public static BoundDateDisplayTimeZoneProvider getLogTimeZoneProvider() { final ResourceParameter parameter = resourceParameter(); return parameter != null ? parameter.getLogTimeZoneProvider() : null; } public static boolean isInternalDebug() { final ResourceParameter parameter = resourceParameter(); return parameter != null ? parameter.isInternalDebug() : false; } protected static ResourceParameter resourceParameter() { if (!isExistResourceContextOnThread()) { return null; } return getResourceContextOnThread().getResourceParameter(); } protected static void assertResourceContextExists() { if (!isExistResourceContextOnThread()) { String msg = "The resource context should exist!"; throw new IllegalStateException(msg); } } // ----------------------------------------------------- // Access Date // ----------- public static Date getAccessDate() { return AccessContext.getAccessDateOnThread(); } public static Timestamp getAccessTimestamp() { return AccessContext.getAccessTimestampOnThread(); } // ----------------------------------------------------- // Select Column // ------------- public static Map<String, String> createSelectColumnMap(ResultSet rs) throws SQLException { final ResultSetMetaData rsmd = rs.getMetaData(); final int count = rsmd.getColumnCount(); final Map<String, String> selectColumnKeyNameMap = getSelectColumnKeyNameMap(); // flexible for resolving non-compilable connectors and reservation words final Map<String, String> columnMap = StringKeyMap.createAsFlexible(); for (int i = 0; i < count; ++i) { String columnLabel = rsmd.getColumnLabel(i + 1); final int dotIndex = columnLabel.lastIndexOf('.'); if (dotIndex >= 0) { // basically for SQLite columnLabel = columnLabel.substring(dotIndex + 1); } final String realColumnName; if (selectColumnKeyNameMap != null) { // use select index final String mappedName = selectColumnKeyNameMap.get(columnLabel); if (mappedName != null) { // mainly true realColumnName = mappedName; // switch on-query-name to column DB names } else { // for derived columns and so on realColumnName = columnLabel; } } else { realColumnName = columnLabel; } columnMap.put(realColumnName, realColumnName); } return columnMap; } protected static Map<String, String> getSelectColumnKeyNameMap() { if (!ConditionBeanContext.isExistConditionBeanOnThread()) { return null; } final ConditionBean cb = ConditionBeanContext.getConditionBeanOnThread(); return cb.getSqlClause().getSelectColumnKeyNameMap(); } // ----------------------------------------------------- // Select Index // ------------ /** * Get the map of select index. map:{entityNo(e.g. loc00 or _0_3) = map:{selectColumnKeyName = selectIndex}} * @return The map of select index. (NullAllowed: null means select index is disabled) */ public static Map<String, Map<String, Integer>> getSelectIndexMap() { if (!ConditionBeanContext.isExistConditionBeanOnThread()) { return null; } // basically only used by getLocalValue() or getRelationValue() // but argument style for performance final ConditionBean cb = ConditionBeanContext.getConditionBeanOnThread(); return cb.getSqlClause().getSelectIndexMap(); } public static Object getLocalValue(ResultSet rs, String columnName, ValueType valueType, Map<String, Map<String, Integer>> selectIndexMap) throws SQLException { return doGetValue(rs, SqlClause.BASE_POINT_HANDLING_ENTITY_NO, columnName, valueType, selectIndexMap); } public static Object getRelationValue(ResultSet rs, String relationNoSuffix, String columnName, ValueType valueType, Map<String, Map<String, Integer>> selectIndexMap) throws SQLException { return doGetValue(rs, relationNoSuffix, columnName, valueType, selectIndexMap); } protected static Object doGetValue(ResultSet rs, String entityNo, String columnName, ValueType valueType, Map<String, Map<String, Integer>> selectIndexMap) throws SQLException { final Map<String, Integer> innerMap = selectIndexMap != null ? selectIndexMap.get(entityNo) : null; final Integer selectIndex = innerMap != null ? innerMap.get(columnName) : null; if (selectIndex != null) { return valueType.getValue(rs, selectIndex); } else { return valueType.getValue(rs, columnName); } } public static boolean isOutOfLocalSelectIndex(String columnDbName, Map<String, Map<String, Integer>> selectIndexMap) throws SQLException { // if use select index (basically ConditionBean) but no select index for the column, // the column is not set up in select clause (and selectColumnMap also does not contain it) // this determination is to avoid... // o exists duplicate key name, FOO_0 and FOO(_0) // o either is excepted column by SpecifyColumn // in this case, selectColumnMap returns true in both column // so it determines existence in select clause by this method return selectIndexMap != null && !hasLocalSelectIndex(columnDbName, selectIndexMap); } public static boolean isOutOfRelationSelectIndex(String relationNoSuffix, String columnDbName, Map<String, Map<String, Integer>> selectIndexMap) throws SQLException { // see comment on the method for local return selectIndexMap != null && !hasRelationSelectIndex(relationNoSuffix, columnDbName, selectIndexMap); } protected static boolean hasLocalSelectIndex(String columnName, Map<String, Map<String, Integer>> selectIndexMap) throws SQLException { return doHasSelectIndex(SqlClause.BASE_POINT_HANDLING_ENTITY_NO, columnName, selectIndexMap); } protected static boolean hasRelationSelectIndex(String relationNoSuffix, String columnName, Map<String, Map<String, Integer>> selectIndexMap) throws SQLException { return doHasSelectIndex(relationNoSuffix, columnName, selectIndexMap); } protected static boolean doHasSelectIndex(String entityNo, String columnName, Map<String, Map<String, Integer>> selectIndexMap) throws SQLException { final Map<String, Integer> innerMap = selectIndexMap != null ? selectIndexMap.get(entityNo) : null; return innerMap != null && innerMap.containsKey(columnName); } // =================================================================================== // Attribute // ========= protected ResourceContext _parentContext; // not null only when recursive invoking protected BehaviorCommand<?> _behaviorCommand; protected DBDef _currentDBDef; protected DBMetaProvider _dbmetaProvider; protected SqlClauseCreator _sqlClauseCreator; protected SqlAnalyzerFactory _sqlAnalyzerFactory; protected SQLExceptionHandlerFactory _sqlExceptionHandlerFactory; protected GearedCipherManager _gearedCipherManager; protected ResourceParameter _resourceParameter; // =================================================================================== // Basic Override // ============== @Override public String toString() { return "{" + _behaviorCommand + ", " + _currentDBDef // core resources + ", " + _dbmetaProvider + ", " + _sqlClauseCreator // basic resources + ", " + _sqlAnalyzerFactory + ", " + _sqlExceptionHandlerFactory // factories + ", " + _gearedCipherManager + ", " + _resourceParameter + "}"; // various } // =================================================================================== // Accessor // ======== public ResourceContext getParentContext() { return _parentContext; } public void setParentContext(ResourceContext parentContext) { _parentContext = parentContext; } public BehaviorCommand<?> getBehaviorCommand() { return _behaviorCommand; } public void setBehaviorCommand(BehaviorCommand<?> behaviorCommand) { _behaviorCommand = behaviorCommand; } public DBDef getCurrentDBDef() { return _currentDBDef; } public void setCurrentDBDef(DBDef currentDBDef) { _currentDBDef = currentDBDef; } public DBMetaProvider getDBMetaProvider() { return _dbmetaProvider; } public void setDBMetaProvider(DBMetaProvider dbmetaProvider) { _dbmetaProvider = dbmetaProvider; } public SqlClauseCreator getSqlClauseCreator() { return _sqlClauseCreator; } public void setSqlClauseCreator(SqlClauseCreator sqlClauseCreator) { _sqlClauseCreator = sqlClauseCreator; } public SqlAnalyzerFactory getSqlAnalyzerFactory() { return _sqlAnalyzerFactory; } public void setSqlAnalyzerFactory(SqlAnalyzerFactory sqlAnalyzerFactory) { _sqlAnalyzerFactory = sqlAnalyzerFactory; } public SQLExceptionHandlerFactory getSQLExceptionHandlerFactory() { return _sqlExceptionHandlerFactory; } public void setSQLExceptionHandlerFactory(SQLExceptionHandlerFactory sqlExceptionHandlerFactory) { _sqlExceptionHandlerFactory = sqlExceptionHandlerFactory; } public GearedCipherManager getGearedCipherManager() { return _gearedCipherManager; } public void setGearedCipherManager(GearedCipherManager gearedCipherManager) { _gearedCipherManager = gearedCipherManager; } public ResourceParameter getResourceParameter() { return _resourceParameter; } public void setResourceParameter(ResourceParameter resourceParameter) { _resourceParameter = resourceParameter; } }
Java
class TwitterStreamImpl extends TwitterBaseImpl implements TwitterStream { private static final long serialVersionUID = 5529611191443189901L; private final HttpClientWrapper http; private static final Logger logger = Logger.getLogger(TwitterStreamImpl.class); private StreamListener[] streamListeners = new StreamListener[0]; private List<ConnectionLifeCycleListener> lifeCycleListeners = new ArrayList<ConnectionLifeCycleListener>(0); private TwitterStreamConsumer handler = null; private String stallWarningsGetParam; private HttpParameter stallWarningsParam; /*package*/ TwitterStreamImpl(Configuration conf, Authorization auth) { super(conf, auth); http = new HttpClientWrapper(new StreamingReadTimeoutConfiguration(conf)); stallWarningsGetParam = "stall_warnings=" + (conf.isStallWarningsEnabled() ? "true" : "false"); stallWarningsParam = new HttpParameter("stall_warnings", conf.isStallWarningsEnabled()); } /* Streaming API */ /** * {@inheritDoc} */ @Override public void firehose(final int count) { ensureAuthorizationEnabled(); ensureListenerIsSet(); ensureStatusStreamListenerIsSet(); startHandler(new TwitterStreamConsumer() { @Override public StatusStream getStream() throws TwitterException { return getFirehoseStream(count); } }); } /** * {@inheritDoc} */ @Override public StatusStream getFirehoseStream(int count) throws TwitterException { ensureAuthorizationEnabled(); return getCountStream("statuses/firehose.json", count); } /** * {@inheritDoc} */ @Override public void links(final int count) { ensureAuthorizationEnabled(); ensureListenerIsSet(); ensureStatusStreamListenerIsSet(); startHandler(new TwitterStreamConsumer() { @Override public StatusStream getStream() throws TwitterException { return getLinksStream(count); } }); } /** * {@inheritDoc} */ @Override public StatusStream getLinksStream(int count) throws TwitterException { ensureAuthorizationEnabled(); return getCountStream("statuses/links.json", count); } private StatusStream getCountStream(String relativeUrl, int count) throws TwitterException { ensureAuthorizationEnabled(); try { return new StatusStreamImpl(getDispatcher(), http.post(conf.getStreamBaseURL() + relativeUrl , new HttpParameter[]{new HttpParameter("count", String.valueOf(count)) , stallWarningsParam}, auth), conf); } catch (IOException e) { throw new TwitterException(e); } } /** * {@inheritDoc} */ @Override public void retweet() { ensureAuthorizationEnabled(); ensureListenerIsSet(); ensureStatusStreamListenerIsSet(); startHandler(new TwitterStreamConsumer() { @Override public StatusStream getStream() throws TwitterException { return getRetweetStream(); } }); } /** * {@inheritDoc} */ @Override public StatusStream getRetweetStream() throws TwitterException { ensureAuthorizationEnabled(); try { return new StatusStreamImpl(getDispatcher(), http.post(conf.getStreamBaseURL() + "statuses/retweet.json" , new HttpParameter[]{stallWarningsParam}, auth), conf); } catch (IOException e) { throw new TwitterException(e); } } /** * {@inheritDoc} */ @Override public void sample() { ensureAuthorizationEnabled(); ensureListenerIsSet(); ensureStatusStreamListenerIsSet(); startHandler(new TwitterStreamConsumer() { @Override public StatusStream getStream() throws TwitterException { return getSampleStream(); } }); } /** * {@inheritDoc} */ @Override public StatusStream getSampleStream() throws TwitterException { ensureAuthorizationEnabled(); try { return new StatusStreamImpl(getDispatcher(), http.get(conf.getStreamBaseURL() + "statuses/sample.json?" + stallWarningsGetParam, auth), conf); } catch (IOException e) { throw new TwitterException(e); } } /** * {@inheritDoc} */ @Override public void user() { user(null); } /** * {@inheritDoc} */ @Override public void user(final String[] track) { ensureAuthorizationEnabled(); ensureListenerIsSet(); for (StreamListener listener : streamListeners) { if (!(listener instanceof UserStreamListener)) { throw new IllegalStateException("Only UserStreamListener is supported. found: " + listener.getClass()); } } startHandler(new TwitterStreamConsumer() { @Override public UserStream getStream() throws TwitterException { return getUserStream(track); } }); } /** * {@inheritDoc} */ @Override public UserStream getUserStream() throws TwitterException { return getUserStream(null); } /** * {@inheritDoc} */ @Override public UserStream getUserStream(String[] track) throws TwitterException { ensureAuthorizationEnabled(); try { List<HttpParameter> params = new ArrayList<HttpParameter>(); params.add(stallWarningsParam); if (conf.isUserStreamRepliesAllEnabled()) { params.add(new HttpParameter("replies", "all")); } if (track != null) { params.add(new HttpParameter("track", z_T4JInternalStringUtil.join(track))); } return new UserStreamImpl(getDispatcher(), http.post(conf.getUserStreamBaseURL() + "user.json" , params.toArray(new HttpParameter[params.size()]) , auth), conf); } catch (IOException e) { throw new TwitterException(e); } } /** * {@inheritDoc} */ @Override public StreamController site(final boolean withFollowings, final long[] follow) { ensureOAuthEnabled(); ensureListenerIsSet(); final StreamController cs = new StreamController(http, auth); for (StreamListener listener : streamListeners) { if (!(listener instanceof SiteStreamsListener)) { throw new IllegalStateException("Only SiteStreamListener is supported. found: " + listener.getClass()); } } startHandler(new TwitterStreamConsumer() { @Override public StreamImplementation getStream() throws TwitterException { try { return new SiteStreamsImpl(getDispatcher(), getSiteStream(withFollowings, follow), conf, cs); } catch (IOException e) { throw new TwitterException(e); } } }); return cs; } private Dispatcher getDispatcher() { if (null == TwitterStreamImpl.dispatcher) { synchronized (TwitterStreamImpl.class) { if (null == TwitterStreamImpl.dispatcher) { // dispatcher is held statically, but it'll be instantiated with // the configuration instance associated with this TwitterStream // instance which invokes getDispatcher() on the first time. TwitterStreamImpl.dispatcher = new DispatcherFactory(conf).getInstance(); } } } return TwitterStreamImpl.dispatcher; } private static transient Dispatcher dispatcher; InputStream getSiteStream(boolean withFollowings, long[] follow) throws TwitterException { ensureOAuthEnabled(); return http.post(conf.getSiteStreamBaseURL() + "/2b/site.json", new HttpParameter[]{ new HttpParameter("with", withFollowings ? "followings" : "user") , new HttpParameter("follow", z_T4JInternalStringUtil.join(follow)) , stallWarningsParam}, auth).asStream(); } /** * {@inheritDoc} */ @Override public void filter(final FilterQuery query) { ensureAuthorizationEnabled(); ensureListenerIsSet(); ensureStatusStreamListenerIsSet(); startHandler(new TwitterStreamConsumer() { @Override public StatusStream getStream() throws TwitterException { return getFilterStream(query); } }); } /** * {@inheritDoc} */ @Override public StatusStream getFilterStream(FilterQuery query) throws TwitterException { ensureAuthorizationEnabled(); try { return new StatusStreamImpl(getDispatcher(), http.post(conf.getStreamBaseURL() + "statuses/filter.json" , query.asHttpParameterArray(stallWarningsParam), auth), conf); } catch (IOException e) { throw new TwitterException(e); } } /** * check if any listener is set. Throws IllegalStateException if no listener is set. * * @throws IllegalStateException when no listener is set. */ private void ensureListenerIsSet() { if (streamListeners.length == 0) { throw new IllegalStateException("No listener is set."); } } private void ensureStatusStreamListenerIsSet() { for (StreamListener listener : streamListeners) { if (!(listener instanceof StatusListener)) { throw new IllegalStateException("Only StatusListener is supported. found: " + listener.getClass()); } } } private static int numberOfHandlers = 0; private synchronized void startHandler(TwitterStreamConsumer handler) { cleanUp(); if (streamListeners.length == 0) { throw new IllegalStateException("StatusListener is not set."); } this.handler = handler; this.handler.start(); numberOfHandlers++; } /** * {@inheritDoc} */ @Override public synchronized void cleanUp() { if (handler != null) { handler.close(); numberOfHandlers--; } } /** * {@inheritDoc} */ @Override public synchronized void shutdown() { super.shutdown(); cleanUp(); synchronized (TwitterStreamImpl.class) { if (0 == numberOfHandlers) { if (dispatcher != null) { dispatcher.shutdown(); dispatcher = null; } } } } /** * {@inheritDoc} */ @Override public void addConnectionLifeCycleListener(ConnectionLifeCycleListener listener) { this.lifeCycleListeners.add(listener); } /** * {@inheritDoc} */ @Override public void addListener(UserStreamListener listener) { addListener((StreamListener) listener); } /** * {@inheritDoc} */ @Override public void addListener(StatusListener listener) { addListener((StreamListener) listener); } /** * {@inheritDoc} */ @Override public void addListener(SiteStreamsListener listener) { addListener((StreamListener) listener); } private synchronized void addListener(StreamListener listener) { StreamListener[] newListeners = new StreamListener[this.streamListeners.length + 1]; System.arraycopy(this.streamListeners, 0, newListeners, 0, this.streamListeners.length); newListeners[newListeners.length - 1] = listener; this.streamListeners = newListeners; } /* https://dev.twitter.com/docs/streaming-api/concepts#connecting When a network error (TCP/IP level) is encountered, back off linearly. Perhaps start at 250 milliseconds, double, and cap at 16 seconds When a HTTP error (> 200) is returned, back off exponentially. Perhaps start with a 10 second wait, double on each subsequent failure, and finally cap the wait at 240 seconds. Consider sending an alert to a human operator after multiple HTTP errors, as there is probably a client configuration issue that is unlikely to be resolved without human intervention. There's not much point in polling any faster in the face of HTTP error codes and your client is may run afoul of a rate limit. */ private static final int TCP_ERROR_INITIAL_WAIT = 250; private static final int TCP_ERROR_WAIT_CAP = 16 * 1000; private static final int HTTP_ERROR_INITIAL_WAIT = 10 * 1000; private static final int HTTP_ERROR_WAIT_CAP = 240 * 1000; private static final int NO_WAIT = 0; static int count = 0; abstract class TwitterStreamConsumer extends Thread { private StreamImplementation stream = null; private final String NAME = "Twitter Stream consumer-" + (++count); private volatile boolean closed = false; TwitterStreamConsumer() { super(); setName(NAME + "[initializing]"); } @Override public void run() { int timeToSleep = NO_WAIT; boolean connected = false; while (!closed) { try { if (!closed && null == stream) { // try establishing connection logger.info("Establishing connection."); setStatus("[Establishing connection]"); stream = getStream(); connected = true; logger.info("Connection established."); for (ConnectionLifeCycleListener listener : lifeCycleListeners) { try { listener.onConnect(); } catch (Exception e) { logger.warn(e.getMessage()); } } // connection established successfully timeToSleep = NO_WAIT; logger.info("Receiving status stream."); setStatus("[Receiving stream]"); while (!closed) { try { stream.next(streamListeners); } catch (IllegalStateException ise) { logger.warn(ise.getMessage()); break; } catch (TwitterException e) { logger.info(e.getMessage()); stream.onException(e); throw e; } catch (Exception e) { logger.info(e.getMessage()); stream.onException(e); closed = true; break; } } } } catch (TwitterException te) { logger.info(te.getMessage()); if (!closed) { if (NO_WAIT == timeToSleep) { if (te.getStatusCode() == FORBIDDEN) { logger.warn("This account is not in required role. ", te.getMessage()); closed = true; break; } if (te.getStatusCode() == NOT_ACCEPTABLE) { logger.warn("Parameter not accepted with the role. ", te.getMessage()); closed = true; break; } connected = false; for (ConnectionLifeCycleListener listener : lifeCycleListeners) { try { listener.onDisconnect(); } catch (Exception e) { logger.warn(e.getMessage()); } } if (te.getStatusCode() > 200) { timeToSleep = HTTP_ERROR_INITIAL_WAIT; } else if (0 == timeToSleep) { timeToSleep = TCP_ERROR_INITIAL_WAIT; } } if (te.getStatusCode() > 200 && timeToSleep < HTTP_ERROR_INITIAL_WAIT) { timeToSleep = HTTP_ERROR_INITIAL_WAIT; } if (connected) { for (ConnectionLifeCycleListener listener : lifeCycleListeners) { try { listener.onDisconnect(); } catch (Exception e) { logger.warn(e.getMessage()); } } } // there was a problem establishing the connection, or the connection closed by peer if (!closed) { // wait for a moment not to overload Twitter API logger.info("Waiting for " + (timeToSleep) + " milliseconds"); setStatus("[Waiting for " + (timeToSleep) + " milliseconds]"); try { Thread.sleep(timeToSleep); } catch (InterruptedException ignore) { } timeToSleep = Math.min(timeToSleep * 2, (te.getStatusCode() > 200) ? HTTP_ERROR_WAIT_CAP : TCP_ERROR_WAIT_CAP); } stream = null; logger.debug(te.getMessage()); for (StreamListener statusListener : streamListeners) { statusListener.onException(te); } connected = false; } } } if (this.stream != null && connected) { try { this.stream.close(); } catch (IOException ignore) { } catch (Exception e) { e.printStackTrace(); logger.warn(e.getMessage()); } finally { for (ConnectionLifeCycleListener listener : lifeCycleListeners) { try { listener.onDisconnect(); } catch (Exception e) { logger.warn(e.getMessage()); } } } } for (ConnectionLifeCycleListener listener : lifeCycleListeners) { try { listener.onCleanUp(); } catch (Exception e) { logger.warn(e.getMessage()); } } } public synchronized void close() { setStatus("[Disposing thread]"); try { if (stream != null) { try { stream.close(); } catch (IOException ignore) { } catch (Exception e) { e.printStackTrace(); logger.warn(e.getMessage()); } } } finally { closed = true; } } private void setStatus(String message) { String actualMessage = NAME + message; setName(actualMessage); logger.debug(actualMessage); } abstract StreamImplementation getStream() throws TwitterException; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; TwitterStreamImpl that = (TwitterStreamImpl) o; if (handler != null ? !handler.equals(that.handler) : that.handler != null) return false; if (http != null ? !http.equals(that.http) : that.http != null) return false; if (lifeCycleListeners != null ? !lifeCycleListeners.equals(that.lifeCycleListeners) : that.lifeCycleListeners != null) return false; if (!Arrays.equals(streamListeners, that.streamListeners)) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (http != null ? http.hashCode() : 0); result = 31 * result + (streamListeners != null ? Arrays.hashCode(streamListeners) : 0); result = 31 * result + (lifeCycleListeners != null ? lifeCycleListeners.hashCode() : 0); result = 31 * result + (handler != null ? handler.hashCode() : 0); return result; } @Override public String toString() { return "TwitterStreamImpl{" + "http=" + http + ", streamListeners=" + (streamListeners == null ? null : Arrays.asList(streamListeners)) + ", lifeCycleListeners=" + lifeCycleListeners + ", handler=" + handler + '}'; } }
Java
public final class StorageMetricsOutput implements MetricsOutput { /** * Storage for metrics. */ private final Storage storage; /** * New storage metrics. * @param storage Storage */ public StorageMetricsOutput(final Storage storage) { this.storage = storage; } @Override public void counters(final Map<String, Long> data) { for (final Map.Entry<String, Long> metric : data.entrySet()) { final Key.From key = new Key.From(metric.getKey()); this.storage.exists(key).thenCompose( exists -> { final CompletionStage<Long> res; if (exists) { res = this.storage.value(key).thenCompose( content -> new PublisherAs(content) .string(StandardCharsets.UTF_8) .thenApply(Long::valueOf) ); } else { res = CompletableFuture.completedFuture(0L); } return res; } ).thenCompose(val -> this.storage.save(key, content(val + metric.getValue()))) .handle(StorageMetricsOutput::handle); } } @Override public void gauges(final Map<String, Long> data) { for (final Map.Entry<String, Long> metric : data.entrySet()) { this.storage.save(new Key.From(metric.getKey()), content(metric.getValue())) .handle(StorageMetricsOutput::handle); } } /** * Content for long. * @param val Long value * @return Content publisher */ private static Content content(final long val) { return new Content.From(Long.toString(val).getBytes(StandardCharsets.UTF_8)); } /** * Handle async result. * @param none Void result * @param err Error * @return Nothing */ private static Void handle(final Void none, final Throwable err) { if (err != null) { Logger.warn( StorageMetricsOutput.class, "Failed to update metric value: %[exception]s", err ); } return none; } }
Java
public class SubAccountServiceTest extends KFSTestCaseBase { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(SubAccountServiceTest.class); private final static SubAccount subAccount = SubAccountFixture.VALID_SUB_ACCOUNT.createSubAccount(); @Test public void testA21SubAccount() { SubAccount sa = SpringContext.getBean(SubAccountService.class).getByPrimaryId(subAccount.getChartOfAccountsCode(), subAccount.getAccountNumber(), subAccount.getSubAccountNumber()); assertTrue("expect to find this sub account: " + subAccount.getChartOfAccountsCode() + "/" + subAccount.getAccountNumber() + "/" + subAccount.getSubAccountNumber(), ObjectUtils.isNotNull(sa)); A21SubAccount a21 = sa.getA21SubAccount(); assertTrue("expect this to have a21subaccount", ObjectUtils.isNotNull(a21)); //remove reference to the obsolete account object - and there is not real test being done //a21.getIndirectCostRecoveryAcct(); } @Test public void testGetByPrimaryId() throws Exception { SubAccount sa = new SubAccount(); sa.setAccountNumber(subAccount.getAccountNumber()); sa.setChartOfAccountsCode(subAccount.getChartOfAccountsCode()); sa.setSubAccountNumber(subAccount.getSubAccountNumber()); SubAccount retrieved = SpringContext.getBean(SubAccountService.class).getByPrimaryId(subAccount.getChartOfAccountsCode(), subAccount.getAccountNumber(), subAccount.getSubAccountNumber()); assertTrue("Didn't retrieve sub account", ObjectUtils.isNotNull(retrieved)); assertEquals("Wrong chart", subAccount.getChartOfAccountsCode(), retrieved.getChartOfAccountsCode()); assertEquals("Wrong account", subAccount.getAccountNumber(), retrieved.getAccountNumber()); assertEquals("Wrong Sub account number", subAccount.getSubAccountNumber(), retrieved.getSubAccountNumber()); } @Test public void testGetByPrimaryIdWithCaching() throws Exception { SubAccount sa = new SubAccount(); sa.setAccountNumber(subAccount.getAccountNumber()); sa.setChartOfAccountsCode(subAccount.getChartOfAccountsCode()); sa.setSubAccountNumber(subAccount.getSubAccountNumber()); SubAccount retrieved = SpringContext.getBean(SubAccountService.class).getByPrimaryIdWithCaching(subAccount.getChartOfAccountsCode(), subAccount.getAccountNumber(), subAccount.getSubAccountNumber()); assertTrue("Didn't retrieve sub account", ObjectUtils.isNotNull(retrieved)); assertEquals("Wrong chart", subAccount.getChartOfAccountsCode(), retrieved.getChartOfAccountsCode()); assertEquals("Wrong account", subAccount.getAccountNumber(), retrieved.getAccountNumber()); assertEquals("Wrong Sub account number", subAccount.getSubAccountNumber(), retrieved.getSubAccountNumber()); } }
Java
public class HistogramGenerator implements SynsetLineProcessor.SynsetLineHandler { private SynsetSelector synsetSelector; private Histogram<String> nounHistogram; private Histogram<String> verbHistogram; private Histogram<String> adjHistogram; private Histogram<String> advHistogram; protected HistogramGenerator() { this.synsetSelector = new SynsetSelector(); this.nounHistogram = new Histogram<String>(); this.verbHistogram = new Histogram<String>(); this.adjHistogram = new Histogram<String>(); this.advHistogram = new Histogram<String>(); } @Override public void startLine(String line) { //no-op } @Override public void processSynsets(LexDictionary lexDictionary, Collection<String> synsetNames, AtnParse atnParse, Tree<String> tokenNode) { process("noun", nounHistogram, synsetNames); process("verb", verbHistogram, synsetNames); process("adj", adjHistogram, synsetNames); process("adv", advHistogram, synsetNames); } @Override public void endLine(String line, boolean fromParse) { //no-op } private final void process(String prefix, Histogram<String> histogram, Collection<String> synsetNames) { if (shouldInclude(prefix, synsetNames)) { for (String synsetName : synsetNames) { if (synsetName.startsWith(prefix)) { histogram.add(synsetName); } } } } public Histogram<String> getNounHistogram() { return nounHistogram; } public Histogram<String> getVerbHistogram() { return verbHistogram; } public Histogram<String> getAdjHistogram() { return adjHistogram; } public Histogram<String> getAdvHistogram() { return advHistogram; } protected boolean shouldInclude(String prefix, Collection<String> synsetNames) { boolean result = false; if (shouldInclude2(synsetNames)) { for (String synsetName : synsetNames) { if (synsetName.startsWith(prefix)) { result = true; break; } } } return result; } // include if possibly an open-set word protected boolean shouldInclude1(Collection<String> synsetNames) { boolean result = false; //todo: pare down or select from synsetNames by additional criteria for (String synsetName : synsetNames) { if (synsetSelector.hasQualifyingPartOfSpeech(synsetName)) { result = true; break; } } return result; } // exclude if possibly not an open-set word protected boolean shouldInclude2(Collection<String> synsetNames) { boolean result = true; //todo: pare down or select from synsetNames by additional criteria for (String synsetName : synsetNames) { if (!synsetSelector.hasQualifyingPartOfSpeech(synsetName)) { result = false; break; } } return result; } public static void main(String[] args) throws IOException { // Properties: // nounfile -- file for writing noun synset histogram // verbfile -- file for writing verb synset histogram // adjfile -- file for writing adj synset histogram // advfile -- file for writing adv synset histogram final ConfigUtil configUtil = new ConfigUtil(args); final DataProperties dataProperties = configUtil.getDataProperties(); args = dataProperties.getRemainingArgs(); final HistogramGenerator generator = new HistogramGenerator(); final SynsetLineProcessor processor = new SynsetLineProcessor(generator, dataProperties); processor.process(args); processor.close(); final Histogram<String> nounHistogram = generator.getNounHistogram(); final File nounFile = dataProperties.getFile("nounfile", "workingDir"); System.out.print("Noun Histogram:"); if (nounFile != null) System.out.print(" " + nounFile.getAbsolutePath()); System.out.println(); System.out.println(nounHistogram.toString(0)); if (nounFile != null) { HistogramUtil.writeHistogram(nounFile, nounHistogram); } final Histogram<String> verbHistogram = generator.getVerbHistogram(); final File verbFile = dataProperties.getFile("verbfile", "workingDir"); System.out.print("Verb Histogram:"); if (verbFile != null) System.out.print(" " + verbFile.getAbsolutePath()); System.out.println(); System.out.println(verbHistogram.toString(0)); if (verbFile != null) { HistogramUtil.writeHistogram(verbFile, verbHistogram); } final Histogram<String> adjHistogram = generator.getAdjHistogram(); final File adjFile = dataProperties.getFile("adjfile", "workingDir"); System.out.print("Adj Histogram:"); if (adjFile != null) System.out.print(" " + adjFile.getAbsolutePath()); System.out.println(); System.out.println(adjHistogram.toString(0)); if (adjFile != null) { HistogramUtil.writeHistogram(adjFile, adjHistogram); } final Histogram<String> advHistogram = generator.getAdvHistogram(); final File advFile = dataProperties.getFile("advfile", "workingDir"); System.out.print("Adv Histogram:"); if (advFile != null) System.out.print(" " + advFile.getAbsolutePath()); System.out.println(); System.out.println(advHistogram.toString(0)); if (advFile != null) { HistogramUtil.writeHistogram(advFile, advHistogram); } } }
Java
class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.ForecastAdapterViewHolder> { private static final int VIEW_TYPE_COUNT = 2; private static final String LOG_TAG = ForecastAdapter.class.getSimpleName(); private final int VIEW_TYPE_TODAY = 0; private final int VIEW_TYPE_FUTURE = 1; private boolean mIsTwoPane = false; final private ItemChoiceManager mICM; private Cursor mCursor; private Context mContext; private final ForecastAdapterOnClickHandler handler; private final View emptyView; public static interface ForecastAdapterOnClickHandler { void onClick(Long date, ForecastAdapterViewHolder vh); } ForecastAdapter(Context context, Cursor resultCursor, ForecastAdapterOnClickHandler clickHandler, View emptyView, int choiceMode) { mContext = context; mCursor = resultCursor; handler = clickHandler; this.emptyView = emptyView; mICM = new ItemChoiceManager(this); mICM.setChoiceMode(choiceMode); } Cursor getCursor(){ return mCursor; } void swapCursor(Cursor newCursor){ mCursor = newCursor; notifyDataSetChanged(); emptyView.setVisibility((getItemCount() == 0 ? View.VISIBLE : View.GONE)); } void setIsTwoPane(boolean IsTwoPane) { this.mIsTwoPane = IsTwoPane; } @Override public int getItemViewType(int position) { return (position == 0 && !mIsTwoPane)?(VIEW_TYPE_TODAY):(VIEW_TYPE_FUTURE); } @Override public int getItemCount() { if ( null == mCursor ) return 0; return mCursor.getCount(); } @Override public ForecastAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // int viewType = getItemViewType(mCursor.getPosition()); if ( parent instanceof RecyclerView ) { int layoutID = -1; switch (viewType) { case VIEW_TYPE_TODAY: { layoutID = R.layout.list_item_forecast_today; break; } case VIEW_TYPE_FUTURE: { layoutID = R.layout.list_item_forecast; break; } } View view = LayoutInflater.from(parent.getContext()).inflate(layoutID, parent, false); return new ForecastAdapterViewHolder(view); } else { throw new RuntimeException("Not bound to RecyclerView"); } } @Override public void onBindViewHolder(ForecastAdapterViewHolder forecastAdapterViewHolder, int position) { if (position >= mCursor.getCount()) return; // mCursor. mCursor.moveToPosition(position); ImageView iconView = forecastAdapterViewHolder.mIconView; int defaultImage; int weatherId = mCursor.getInt(ForecastFragment.COL_WEATHER_CONDITION_ID); boolean useLongToday; switch (getItemViewType(position)){ case VIEW_TYPE_TODAY:{ defaultImage = Utility.getArtResourceForWeatherCondition(weatherId); useLongToday = true; break; } default: { defaultImage = Utility.getIconResourceForWeatherCondition(weatherId); useLongToday = false; } } if (Utility.usingLocalGraphics(mContext)){ forecastAdapterViewHolder.mIconView.setImageResource(defaultImage); } else { Glide .with(mContext) .load(Utility.getArtUrlForWeatherCondition(mContext, weatherId)) .error(defaultImage) .crossFade() .into(iconView); } // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // iconView.setTransitionName(mContext.getString(R.string.transition_name_shared_main, position)); // } ViewCompat.setTransitionName(forecastAdapterViewHolder.mIconView, mContext.getString(R.string.transition_name_shared_main, position)); // "iconView" + position); Long dateText = mCursor.getLong(COL_WEATHER_DATE); TextView dateView = forecastAdapterViewHolder.mDateView; dateView.setText(Utility.getFriendlyDayString(mContext, dateText, useLongToday)); String forecastText = mCursor.getString(ForecastFragment.COL_WEATHER_DESC); TextView forecastView = forecastAdapterViewHolder.mDescriptionView; forecastView.setText(forecastText); forecastView.setContentDescription(mContext.getString(R.string.a11y_forecast, forecastText)); // Read high temperature from cursor double high = mCursor.getDouble(ForecastFragment.COL_WEATHER_MAX_TEMP); TextView highView = forecastAdapterViewHolder.mHighTempView; String highText = Utility.formatTemperature(mContext, high); highView.setText(highText); highView.setContentDescription(mContext.getString(R.string.a11y_high_temp, highText)); double low = mCursor.getDouble(ForecastFragment.COL_WEATHER_MIN_TEMP); TextView lowView = forecastAdapterViewHolder.mLowTempView; String lowText = Utility.formatTemperature(mContext, low); lowView.setText(lowText); lowView.setContentDescription(mContext.getString(R.string.a11y_low_temp, lowText)); mICM.onBindViewHolder(forecastAdapterViewHolder, position); } public void onRestoreInstanceState(Bundle savedInstanceState) { mICM.onRestoreInstanceState(savedInstanceState); } public void onSaveInstanceState(Bundle outState) { mICM.onSaveInstanceState(outState); } public int getSelectedItemPosition() { return mICM.getSelectedItemPosition(); } public void selectView(RecyclerView.ViewHolder viewHolder) { if ( viewHolder instanceof ForecastAdapterViewHolder) { ForecastAdapterViewHolder vfh = (ForecastAdapterViewHolder)viewHolder; vfh.onClick(vfh.itemView); } } /** * Cache of the children views for a forecast list item. */ public class ForecastAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ final ImageView mIconView; final TextView mDateView; final TextView mDescriptionView; final TextView mHighTempView; final TextView mLowTempView; @Override public void onClick(View v) { int adapterPosition = getAdapterPosition(); mCursor.moveToPosition(adapterPosition); handler.onClick(mCursor.getLong(mCursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DATE)), this); mICM.onClick(this); } ForecastAdapterViewHolder(View view) { super(view); view.setOnClickListener(this); mIconView = (ImageView) view.findViewById(R.id.list_item_icon); mDateView = (TextView) view.findViewById(R.id.list_item_date_textview); mDescriptionView = (TextView) view.findViewById(R.id.list_item_forecast_textview); mHighTempView = (TextView) view.findViewById(R.id.list_item_high_textview); mLowTempView = (TextView) view.findViewById(R.id.list_item_low_textview); } } }
Java
public class ForecastAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ final ImageView mIconView; final TextView mDateView; final TextView mDescriptionView; final TextView mHighTempView; final TextView mLowTempView; @Override public void onClick(View v) { int adapterPosition = getAdapterPosition(); mCursor.moveToPosition(adapterPosition); handler.onClick(mCursor.getLong(mCursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DATE)), this); mICM.onClick(this); } ForecastAdapterViewHolder(View view) { super(view); view.setOnClickListener(this); mIconView = (ImageView) view.findViewById(R.id.list_item_icon); mDateView = (TextView) view.findViewById(R.id.list_item_date_textview); mDescriptionView = (TextView) view.findViewById(R.id.list_item_forecast_textview); mHighTempView = (TextView) view.findViewById(R.id.list_item_high_textview); mLowTempView = (TextView) view.findViewById(R.id.list_item_low_textview); } }
Java
public class ConsoleQueryResultWriter extends AbstractQueryResultWriter { private final ConsoleIO consoleIO; private final int consoleWidth; private final Map<String, String> namespaces = new HashMap<>(); private List<String> bindingNames; private int columnWidth; private String separatorLine = ""; private String header = ""; private TupleQueryResultFormat queryResultFormat = new TupleQueryResultFormat("Console query result format", "application/x-dummy", "dummy", true); /** * Constructor * * @param consoleIO * @param consoleWidth console width */ public ConsoleQueryResultWriter(ConsoleIO consoleIO, int consoleWidth) { this.consoleIO = consoleIO; this.consoleWidth = consoleWidth; } @Override public QueryResultFormat getQueryResultFormat() { return queryResultFormat; } @Override public void handleNamespace(String prefix, String uri) throws QueryResultHandlerException { // use uri as the key, so the prefix can be retrieved and shown on the console namespaces.put(uri, prefix); } @Override public void startDocument() throws QueryResultHandlerException { // } @Override public void handleStylesheet(String stylesheetUrl) throws QueryResultHandlerException { // } @Override public void startHeader() throws QueryResultHandlerException { } @Override public void endHeader() throws QueryResultHandlerException { consoleIO.writeln(separatorLine); consoleIO.writeln(header); consoleIO.writeln(separatorLine); } @Override public void handleBoolean(boolean value) throws QueryResultHandlerException { consoleIO.writeln("Answer: " + value); } @Override public void handleLinks(List<String> linkUrls) throws QueryResultHandlerException { // } @Override public void startQueryResult(List<String> bindingNames) throws TupleQueryResultHandlerException { super.startQueryResult(bindingNames); this.bindingNames = bindingNames; int columns = bindingNames.size(); columnWidth = (consoleWidth - 1) / columns - 3; StringBuilder builder = new StringBuilder(consoleWidth); for (int i = columns; i > 0; i--) { builder.append('+'); StringUtil.appendN('-', columnWidth + 1, builder); } builder.append('+'); separatorLine = builder.toString(); // Build table header builder = new StringBuilder(consoleWidth); for (String bindingName : bindingNames) { builder.append("| ").append(bindingName); StringUtil.appendN(' ', columnWidth - bindingName.length(), builder); } builder.append("|"); header = builder.toString(); } @Override public void endQueryResult() throws TupleQueryResultHandlerException { if (!separatorLine.isEmpty()) { consoleIO.writeln(separatorLine); } } @Override protected void handleSolutionImpl(BindingSet bindingSet) throws TupleQueryResultHandlerException { StringBuilder builder = new StringBuilder(512); for (String bindingName : bindingNames) { Value value = bindingSet.getValue(bindingName); String valueStr = (value != null) ? Util.getPrefixedValue(value, namespaces) : ""; builder.append("| ").append(valueStr); StringUtil.appendN(' ', columnWidth - valueStr.length(), builder); } builder.append("|"); consoleIO.writeln(builder.toString()); } }
Java
public final class IPV4Address implements Comparable<IPV4Address> { /** * Class c 192. */ private static final String CLASS_C_192 = "192"; /** * IP V4 address. */ private final String address; /** * IP V4 address parts. */ private final String[] parts; /** * Constructor. * * @param address IP V4 address * @throws NullPointerException if address is null * @throws IllegalArgumentException if address is not an ip v4 address */ public IPV4Address(final String address) { super(); Objects.requireNonNull(address, "address"); //$NON-NLS-1$ if ((address.length() < 7) || (address.length() > 15)) { throw new IllegalArgumentException("To short or long for an IP V4 address"); //$NON-NLS-1$ } if (!address.matches("^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$")) //$NON-NLS-1$ { throw new IllegalArgumentException("Not an IP V4 address"); //$NON-NLS-1$ } this.address = address; this.parts = address.split("\\."); //$NON-NLS-1$ } /** * IPV4Address factory. * * @param address IP V4 address * @return IPV4Address object */ public static IPV4Address of(final String address) { return new IPV4Address(address); } /** * Is an IP V4 private address. * * 10.0.0.0–10.255.255.255 private, 1 8-Bit-Net 10.0.0.0/8 RFC 1918 * 172.16.0.0–172.31.255.255 private, 16 16-Bit-Nets 172.16.0.0/12 RFC 1918 * 192.168.0.0–192.168.255.255 private, 256 24-Bit-Nets 192.168.0.0/16 RFC 1918 * 169.254.0.0–169.254.255.255 link local, 1 16-Bit-Net 169.254.0.0/16 RFC 3927 * * @return true when private address, otherwise false */ public boolean isPrivate() { if ("10".equals(this.parts[0]) || (CLASS_C_192.equals(this.parts[0]) && "168".equals(this.parts[1])) || ("169".equals(this.parts[0]) && "254".equals(this.parts[1]))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ { return true; } if ("172".equals(this.parts[0])) //$NON-NLS-1$ { final int block2 = Integer.parseInt(this.parts[1]); if ((block2 >= 16) && (block2 <= 31)) { return true; } } return false; } /** * Is an IP V4 special address. * * 0.0.0.0/8 Das vorliegende Netzwerk RFC 1122 * 127.0.0.0/8 Loopback RFC 1122 * 100.64.0.0/10 Shared Transition Space RFC 6598 * 192.0.0.0/24 IETF Protocol Assignments RFC 6890 * 192.0.2.0/24 Test-Netzwerke RFC 6890 * 192.88.99.0/24 IPv6 zu IPv4 Relay (Veraltet) RFC 7526 * 198.18.0.0/15 Netzwerk-Benchmark-Tests RFC 2544 * 198.51.100.0/24 Test-Netzwerke RFC 6890 * 203.0.113.0/24 Test-Netzwerke RFC 6890 * 224.0.0.0/4 Multicasts RFC 5771 * 240.0.0.0/4 Reserviert RFC 1700 * 255.255.255.255/32 Limited Broadcast RFC 919, RFC 922 * * @return true when special address, otherwise false */ public boolean isSpecial() { if ("0".equals(this.parts[0]) || //$NON-NLS-1$ "127".equals(this.parts[0]) || //$NON-NLS-1$ (CLASS_C_192.equals(this.parts[0]) && "0".equals(this.parts[1]) && "0".equals(this.parts[2])) || //$NON-NLS-1$ //$NON-NLS-2$ (CLASS_C_192.equals(this.parts[0]) && "0".equals(this.parts[1]) && "2".equals(this.parts[2])) || //$NON-NLS-1$ //$NON-NLS-2$ (CLASS_C_192.equals(this.parts[0]) && "88".equals(this.parts[1]) && "99".equals(this.parts[2])) || //$NON-NLS-1$ //$NON-NLS-2$ ("198".equals(this.parts[0]) && "51".equals(this.parts[1]) && "100".equals(this.parts[2])) || //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ("203".equals(this.parts[0]) && "0".equals(this.parts[1]) && "113".equals(this.parts[2])) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ) { return true; } if ("100".equals(this.parts[0])) //$NON-NLS-1$ { final int block2 = Integer.parseInt(this.parts[1]); if ((block2 >= 64) && (block2 <= 127)) { return true; } } if ("198".equals(this.parts[0])) //$NON-NLS-1$ { final int block2 = Integer.parseInt(this.parts[1]); if ((block2 >= 18) && (block2 <= 19)) { return true; } } final int block1 = Integer.parseInt(this.parts[0]); return (((block1 >= 224) && (block1 <= 239)) || ((block1 >= 240) && (block1 <= 255))); } /** * Is an IP V4 public address. * * @return true when public address, otherwise false */ public boolean isPublic() { return !isPrivate() && !isSpecial(); } /** * Get ip V4 address string. * * @return IPV4Address string */ public String getAddress() { return this.address; } /** * Calculate hash code. * * @return Hash * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.address.hashCode(); } /** * Is equal with another object. * * @param obj Object * @return true when equal, false otherwise * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof IPV4Address)) { return false; } final IPV4Address other = (IPV4Address)obj; return this.address.equals(other.address); } /** * Returns the string representation of this IPV4Address. * * The exact details of this representation are unspecified and subject to change, but the following may be regarded as typical: * * "IPV4Address[address=192.168.0.0]" * * @return String representation of this IPV4Address * @see java.lang.Object#toString() */ @Override public String toString() { final StringBuilder builder = new StringBuilder(21); builder.append("IPV4Address[address=").append(this.address).append(']'); //$NON-NLS-1$ return builder.toString(); } /** * Compare with another object. * * @param obj Object to compare with * @return 0: equal; 1: greater; -1: smaller * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(final IPV4Address obj) { Objects.requireNonNull(obj, "obj"); //$NON-NLS-1$ return this.address.compareTo(obj.address); } }
Java
public class SOAPHeaderImpl extends SOAPHeaderBaseImpl implements SOAPHeader { /** Creates a new instance of SOAPHeaderImpl */ public SOAPHeaderImpl(WSDLModel model, Element e) { super(model, e); } public SOAPHeaderImpl(WSDLModel model){ this(model, createPrefixedElement(SOAPQName.HEADER.getQName(), model)); } public void accept(SOAPComponent.Visitor visitor) { visitor.visit(this); } public void removeSOAPHeaderFault(SOAPHeaderFault soapHeaderFault) { removeChild(HEADER_FAULT_PROPERTY, soapHeaderFault); } public void addSOAPHeaderFault(SOAPHeaderFault soapHeaderFault) { appendChild(HEADER_FAULT_PROPERTY, soapHeaderFault); } public Collection<SOAPHeaderFault> getSOAPHeaderFaults() { return getChildren(SOAPHeaderFault.class); } @Override public boolean canBeAddedTo(Component target) { if (target instanceof BindingInput || target instanceof BindingOutput) { return true; } return false; } }
Java
public class CompletedFragment extends Fragment { public static ListView tasklist; View view; SessionManager sessionManager; ProjectManager projectsession; ProgressDialog pd; public static ArrayList<CompletedFragment.AllTasks> allTasks = new ArrayList<CompletedFragment.AllTasks>(); public static CompletedFragment.AllTasks taskdetails; JSONArray results = null; String subActivityname, description,status, startdate; public static CompletedTaskAdapter taskAdapter; Context context; JSONArray alltaskarray=null; public CompletedFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view= inflater.inflate(R.layout.fragment_completed, container, false); tasklist=(ListView)view.findViewById(R.id.tasklistcompleted); context=getContext(); sessionManager=new SessionManager(getContext()); projectsession = new ProjectManager(context); if (!Util.verificaConexao(getActivity())){ Util.initToast(getActivity(),"You do not have an internet connection"); offlineAllTask(); }else{ getAllTasks(sessionManager.getUserId().toString()); } return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); MenuItem searchViewItem = menu.findItem(R.id.projects_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchViewItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchView.clearFocus(); if(allTasks.contains(query)){ taskAdapter.getFilter().filter(query); }else{ Toast.makeText(getActivity(), "No Match found",Toast.LENGTH_LONG).show(); } return false; } @Override public boolean onQueryTextChange(String newText) { if(newText.length()==0) { getAllTasks(sessionManager.getUserId().toString()); } else { taskAdapter.getFilter().filter(newText); } return false; } }); } private void getAllTasks(String s) { List<Header> headers = new ArrayList<Header>(); pd = new ProgressDialog(getActivity()); //pd.setTitle(getString(R.string.connecting)); pd.setMessage(getString(R.string.wait)); headers.add(new BasicHeader("Accept", "text/plain")); URLConnection.get(getActivity(), "/LoginAndroidService/GetAllTask?userId=" + s, headers.toArray(new Header[headers.size()]), null, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { pd.hide(); try { results = response.getJSONArray("result"); } catch (JSONException e) { e.printStackTrace(); } allTasks.clear(); if (results.length() > 0) { projectsession.setCOMPLETEDTASKRESULT(results.toString()); for (int i = 0; i < results.length(); i++) { try { JSONObject object = results.getJSONObject(i); subActivityname = object.getString("subActivityName"); description = object.getString("description"); status = object.getString("status"); startdate = object.getString("lastModificationTime"); String date1 = startdate; if(startdate.length()>4) { SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss"); Date newDate = null; try { newDate = spf.parse(date1); } catch (ParseException e) { e.printStackTrace(); } spf = new SimpleDateFormat("dd-MM-yyyy"); date1 = spf.format(newDate); } else { date1=""; } taskdetails = new AllTasks(subActivityname,description,status,date1); if(status.equals("3")||status.equals("4")) { allTasks.add(taskdetails); } } catch (JSONException e) { e.printStackTrace(); } } } else { Toast.makeText(getActivity(), "Project is not assinged yet", Toast.LENGTH_SHORT).show(); } if (allTasks.size() > 0) { taskAdapter= new CompletedTaskAdapter(getActivity(),allTasks); CompletedFragment.tasklist.setAdapter(taskAdapter); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.d("error", "onFailure : " + statusCode); offlineAllTask(); } @Override public void onStart() { pd.show(); } @Override public void onFinish() { if(pd.isShowing()) { pd.hide(); } } }); } public void offlineAllTask() { SharedPreferences pref = context.getSharedPreferences("myappprojects", Context.MODE_PRIVATE); String activitydata=pref.getString("completedtaskresult",""); try { alltaskarray = new JSONArray(activitydata); } catch (Throwable t) { } allTasks.clear(); if (alltaskarray.length() > 0) { for (int i = 0; i < alltaskarray.length(); i++) { try { JSONObject object = alltaskarray.getJSONObject(i); subActivityname = object.getString("subActivityName"); description = object.getString("description"); status = object.getString("status"); startdate = object.getString("lastModificationTime"); String date1 = startdate; if(startdate.length()>4) { SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss"); Date newDate = null; try { newDate = spf.parse(date1); } catch (ParseException e) { e.printStackTrace(); } spf = new SimpleDateFormat("dd-MM-yyyy"); date1 = spf.format(newDate); } else { date1=""; } taskdetails = new AllTasks(subActivityname,description,status,date1); if(status.equals("3")) { allTasks.add(taskdetails); } } catch (JSONException e) { e.printStackTrace(); } } } else { Toast.makeText(getActivity(), "Project is not assinged yet", Toast.LENGTH_SHORT).show(); } if (allTasks.size() > 0) { taskAdapter= new CompletedTaskAdapter(getActivity(),allTasks); CompletedFragment.tasklist.setAdapter(taskAdapter); } } public static class AllTasks { String subActivityname, description,status, startdate; public AllTasks() { } public AllTasks(String subActivityname, String description, String status, String startdate) { this.subActivityname = subActivityname; this.description = description; this.status = status; this.startdate = startdate; } public String getSubActivityname() { return subActivityname; } public void setSubActivityname(String subActivityname) { this.subActivityname = subActivityname; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getStartdate() { return startdate; } public void setStartdate(String startdate) { this.startdate = startdate; } } }
Java
public class DeleteMetadataStep implements Step { private final ResourceDao resourceDao; private final UUID workspaceId; private final UUID resourceId; private final Logger logger = LoggerFactory.getLogger(DeleteMetadataStep.class); public DeleteMetadataStep(ResourceDao resourceDao, UUID workspaceId, UUID resourceId) { this.resourceDao = resourceDao; this.workspaceId = workspaceId; this.resourceId = resourceId; } @Override public StepResult doStep(FlightContext flightContext) throws InterruptedException, RetryException { // deleteResource is idempotent, and here we don't care whether the resource was actually // deleted or just not found. resourceDao.deleteResource(workspaceId, resourceId); return StepResult.getStepResultSuccess(); } @Override public StepResult undoStep(FlightContext flightContext) throws InterruptedException { logger.error("Cannot undo delete of WSM resource {} in workspace {}.", resourceId, workspaceId); // Surface whatever error caused Stairway to begin undoing. return flightContext.getResult(); } }
Java
public abstract class AbstractTupleReceiveStrategy implements ITupleReceiveStrategy { protected static final String STRATEGYTYPE = "tupleReceiving"; private static final Logger LOGGER = Logger.getLogger(AbstractTupleReceiveStrategy.class); private ISwitchTupleSerializer serializer; private AbstractSignalConnection signalCon; private SwitchActionMap switchActionMap; private TupleReceiveServer server; /** * Constructor of the abstract strategy of tuple receiving. * @param serializer the tuple serializer * @param signalCon the signal connection used to send signals * @param switchActionMap the map containing the switch actions */ public AbstractTupleReceiveStrategy(ISwitchTupleSerializer serializer, AbstractSignalConnection signalCon, SwitchActionMap switchActionMap) { this.serializer = serializer; this.signalCon = signalCon; this.switchActionMap = switchActionMap; } @Override public String getStrategyType() { return STRATEGYTYPE; } /** * Return the tuple serializer. * @return the tuple serializer */ public ISwitchTupleSerializer getSerializer() { return serializer; } /** * Returns the signal connection. * @return the signal connection */ public AbstractSignalConnection getSignalCon() { return signalCon; } /** * Returns the switch action map. * @return the switch action map */ public SwitchActionMap getActionMap() { return switchActionMap; } @Override public void initTupleReceiveServer(int port) { LOGGER.info("Creating a socket server with the port:" + port); server = new TupleReceiveServer(this, port); server.start(); } @Override public void stopTupleReceiveServer() { LOGGER.info("Stopping the tuple receive server...."); try { server.stop(); } catch (IOException e) { e.printStackTrace(); } } }
Java
public class BasicNamedRecordPipeWriterReaderTest extends AbstractWriterReaderTest { // NOPMD NOCS (TestClassWithoutTestCases) private static final String PIPE_NAME = "pipe-IVvirGREEf"; private volatile ListCollectionFilter<IMonitoringRecord> sinkFilter = null; // NOPMD (init for findbugs) @Before public void setUp() throws Exception { final AnalysisController analysisController = new AnalysisController(); final Configuration pipeReaderConfig = new Configuration(); pipeReaderConfig.setProperty(PipeReader.CONFIG_PROPERTY_NAME_PIPENAME, BasicNamedRecordPipeWriterReaderTest.PIPE_NAME); final PipeReader pipeReader = new PipeReader(pipeReaderConfig, analysisController); this.sinkFilter = new ListCollectionFilter<IMonitoringRecord>(new Configuration(), analysisController); analysisController.connect(pipeReader, PipeReader.OUTPUT_PORT_NAME_RECORDS, this.sinkFilter, ListCollectionFilter.INPUT_PORT_NAME); final AnalysisControllerThread analysisThread = new AnalysisControllerThread(analysisController); analysisThread.start(); } @Override protected MonitoringController createController(final int numRecordsWritten) { final Configuration config = ConfigurationFactory.createDefaultConfiguration(); config.setProperty(ConfigurationFactory.WRITER_CLASSNAME, PipeWriter.class.getName()); config.setProperty(PipeWriter.CONFIG_PIPENAME, BasicNamedRecordPipeWriterReaderTest.PIPE_NAME); return MonitoringController.createInstance(config); } @Override protected void checkControllerStateBeforeRecordsPassedToController(final IMonitoringController monitoringController) throws Exception { Assert.assertTrue(monitoringController.isMonitoringEnabled()); } @Override protected void checkControllerStateAfterRecordsPassedToController(final IMonitoringController monitoringController) { Assert.assertTrue(monitoringController.isMonitoringEnabled()); } @Override protected void inspectRecords(final List<IMonitoringRecord> eventsPassedToController, final List<IMonitoringRecord> eventFromMonitoringLog) { Assert.assertEquals("Unexpected set of records", eventsPassedToController, eventFromMonitoringLog); } @Override protected boolean terminateBeforeLogInspection() { return false; } @Override protected List<IMonitoringRecord> readEvents() { return this.sinkFilter.getList(); } }
Java
public class EnvironmentDaoImpl implements EnvironmentDao { @Override public int add(Environment ev) { Connection connection= DBUtils.getConnection(); PreparedStatement pstmt=null; try{ String sql="insert into environment (temperature,rh,property) values (?,?,?)"; pstmt=connection.prepareStatement(sql); pstmt.setFloat(1,ev.getTemperature()); pstmt.setFloat(2,ev.getRh()); pstmt.setString(3,ev.getProperty()); int row=pstmt.executeUpdate(); return row; } catch (SQLException e) { e.printStackTrace(); } finally { DBUtils.closeAll(connection,pstmt,null); } return 0; } @Override public Environment findByStr(String str) { Connection connection= DBUtils.getConnection(); PreparedStatement pstmt=null; try { String sql="select * from environment where Property = ?"; pstmt=connection.prepareStatement(sql); pstmt.setString(1,str); ResultSet rs = pstmt.executeQuery(); Environment environment=null; if(rs.next()){ int eid = rs.getInt("eid"); float tmp=rs.getFloat("temperature"); float rh=rs.getFloat("rh"); String property = rs.getString("property"); environment = new Environment(eid, tmp,rh,property); } return environment; } catch (SQLException e) { e.printStackTrace(); } finally { DBUtils.closeAll(connection,pstmt,null); } return null; } }
Java
public abstract class AbstractShape implements Shape { @Override public boolean contains(Point2D p) { return contains(p.getX(), p.getY()); } @Override public boolean contains(Rectangle2D r) { return contains(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } public boolean contains(Point2D p, AffineTransform transform) { return contains(p.getX(), p.getY(), transform); } public boolean contains(Rectangle2D r, AffineTransform transform) { return contains(r.getX(), r.getY(), r.getWidth(), r.getHeight(), transform); } public abstract int getWindingRule(); @Override public boolean contains(double x, double y) { return contains(x, y, null); } public boolean contains(double x, double y, AffineTransform transform) { int windingRule = getWindingRule(); int crossings = countCrossings(x, y, transform); if (windingRule == PathIterator.WIND_EVEN_ODD) return ((crossings & 1) != 0); return crossings != 0; } /** * This counts the number of crossings from (-infinity,y) to (x,y). This * total is used in combination with the winding rule to determine when a * point is inside a shape. */ protected int countCrossings(double x, double y, AffineTransform transform) { // draw an imaginary line from (-infinity,y) to (x,y) // and count how many crossings we have int crossings = 0; double lastX = 0; double lastY = 0; double t2; double ay, ax, by, cy, bx, cx, dx, dy, det; double myX; int i; double curvature; PathIterator iter = getPathIterator(transform); double[] array = new double[4]; double[] results = new double[4]; /** The current segment data. */ double[] data = new double[6]; /** The last moveTo x-coordinate */ double moveX = 0; /** The last moveTo y-coordinate */ double moveY = 0; /** Are we inside the vertical bounds of the current segment? */ boolean inside; /** The segment type of the current segment. */ int type; while (iter.isDone() == false) { type = iter.currentSegment(data); inside = false; if (type == PathIterator.SEG_CLOSE) { // pretend there's a line back to the starting point: type = PathIterator.SEG_LINETO; data[0] = moveX; data[1] = moveY; } if (type == PathIterator.SEG_MOVETO) { moveX = data[0]; moveY = data[1]; lastX = data[0]; lastY = data[1]; } else { // constrain our search: if (type == PathIterator.SEG_LINETO) { inside = y >= Math.min(data[1], lastY) && y <= Math.max(data[1], lastY); if (inside) { if (lastY > data[1]) { t2 = (y - data[1]) / (lastY - data[1]); myX = data[0] + t2 * (lastX - data[0]); if (myX < x) { crossings--; } } else { t2 = (y - lastY) / (data[1] - lastY); myX = lastX + t2 * (data[0] - lastX); if (myX < x) { crossings++; } } } lastX = data[0]; lastY = data[1]; } else if (type == PathIterator.SEG_QUADTO) { ay = lastY - 2 * data[1] + data[3]; by = -2 * lastY + 2 * data[1]; cy = lastY - y; // this is a partial test to see if we're inside double minY = Math.min(data[3], lastY); double maxY = Math.max(data[3], lastY); inside = y >= minY && y <= maxY; if (!inside) { // not inside yet? Then let's do the slightly harder // test: double focusT = -by / (2 * ay); if (focusT >= 0 && focusT <= 1) { double focusY = ay * focusT * focusT + by * focusT + cy; minY = Math.min(minY, focusY); maxY = Math.max(maxY, focusY); inside = y >= minY && y <= maxY; } } if (inside) { det = by * by - 4 * ay * cy; if (det <= 0) { // do nothing; 1 1-solution parabola won't have // crossings i = 0; } else { det = Math.sqrt(det); i = 2; array[0] = (-by + det) / (2 * ay); array[1] = (-by - det) / (2 * ay); } ax = lastX - 2 * data[0] + data[2]; bx = -2 * lastX + 2 * data[0]; cx = lastX; for (int a = 0; a < i; a++) { if (array[a] >= 0 && array[a] <= 1) { myX = ((ax * array[a] + bx) * array[a] + cx); if (myX < x) { curvature = (2 * ay * array[a] + by); if (curvature > 0) { crossings++; } else if (curvature < 0) { crossings--; } } } } } lastX = data[2]; lastY = data[3]; } else if (type == PathIterator.SEG_CUBICTO) { ay = -lastY + 3 * data[1] - 3 * data[3] + data[5]; by = 3 * lastY - 6 * data[1] + 3 * data[3]; cy = -3 * lastY + 3 * data[1]; dy = lastY - y; double minY = Math.min(data[5], lastY); double maxY = Math.max(data[5], lastY); inside = y >= minY && y <= maxY; if (!inside) { // not inside yet? Then let's do the harder test: // take the derivative: 3*ay*t*t+2*by*t+cy // now the determinant of the derivative: det = (4 * by * by - 12 * ay * cy); if (det < 0) { // there are no solutions! nothing to do here } else if (det == 0) { // there is 1 solution double t = -2 * by / (6 * ay); if (t > 0 && t < 1) { double newY = ay * t * t * t + by * t * t + cy * t + dy; minY = Math.min(minY, newY); maxY = Math.max(maxY, newY); } } else { // there are 2 solutions: det = (float) Math.sqrt(det); double t = (-2 * by + det) / (6 * ay); if (t > 0 && t < 1) { double newY = ay * t * t * t + by * t * t + cy * t + dy; minY = Math.min(minY, newY); maxY = Math.max(maxY, newY); } t = (-2 * by - det) / (6 * ay); if (t > 0 && t < 1) { double newY = ay * t * t * t + by * t * t + cy * t + dy; minY = Math.min(minY, newY); maxY = Math.max(maxY, newY); } } inside = y >= minY && y <= maxY; } if (inside) { array[3] = ay; array[2] = by; array[1] = cy; array[0] = dy; i = CubicCurve2D.solveCubic(array, results); ax = -lastX + 3 * data[0] - 3 * data[2] + data[4]; bx = 3 * lastX - 6 * data[0] + 3 * data[2]; cx = -3 * lastX + 3 * data[0]; dx = lastX; for (int a = 0; a < i; a++) { if (results[a] >= 0 && results[a] <= 1) { myX = (((ax * results[a] + bx) * results[a] + cx) * results[a] + dx); if (myX < x) { curvature = ((3 * ay * results[a] + 2 * by) * results[a] + cy); if (curvature > 0) { crossings++; } else if (curvature < 0) { crossings--; } } } } } lastX = data[4]; lastY = data[5]; } } iter.next(); } return crossings; } /** * This checks to see if the rectangle argument ever crosses this shape. * This method returns immediately when/if it finds proof of an * intersection. * */ protected boolean identifyCrossings(double x, double y, double w, double h, AffineTransform transform) { /** * We're going to look at each segment and see if it intersects any of * the 4 sides of the argument rectangle. */ double x1; double x2; double y1; double y2; double lastX = 0; double lastY = 0; lastX = 0; lastY = 0; x1 = x; x2 = (x + w); y1 = y; y2 = (y + h); double y1e = y - .0001f; double y2e = (y + h) + .0001f; double t2; int i; double[] eqn = new double[4]; double[] data = new double[6]; double[] results = new double[3]; double[] array = new double[12]; PathIterator iter = getPathIterator(transform); int i2; double ay, ax, by, cy, dy, bx, cx, dx, det; double myX, myY; int state = -1; int myState; double moveX = 0; double moveY = 0; while (iter.isDone() == false) { int type = iter.currentSegment(data); if (type == PathIterator.SEG_CLOSE) { type = PathIterator.SEG_LINETO; data[0] = moveX; data[1] = moveY; } else if (type == PathIterator.SEG_MOVETO) { moveX = data[0]; moveY = data[1]; lastX = data[0]; lastY = data[1]; } if (type == PathIterator.SEG_LINETO) { ay = data[1] - lastY; ax = data[0] - lastX; // look at horizontal lines: if (ay != 0) { // top top line t2 = (y1 - lastY) / ay; if (t2 > 0 && t2 < 1) { x = ax * t2 + lastX; if (x1 < x && x < x2) { return true; } } // the bottom line: t2 = (y2 - lastY) / ay; if (t2 > 0 && t2 < 1) { x = ax * t2 + lastX; if (x1 < x && x < x2) { return true; } } } // look at vertical lines: if (ax != 0) { // left line: t2 = (x1 - lastX) / ax; if (t2 > 0 && t2 < 1) { y = ay * t2 + lastY; if (y1 < y && y < y2) { return true; } } // the right line: t2 = (x2 - lastX) / ax; if (t2 > 0 && t2 < 1) { y = ay * t2 + lastY; if (y1 < y && y < y2) { return true; } } } lastX = data[0]; lastY = data[1]; } else if (type == PathIterator.SEG_QUADTO) { ax = lastX - 2 * data[0] + data[2]; bx = -2 * lastX + 2 * data[0]; cx = lastX; ay = lastY - 2 * data[1] + data[3]; by = -2 * lastY + 2 * data[1]; cy = lastY; det = by * by - 4 * ay * (cy - y1); if (det > 0) { // if det < 0 we have no matched // if det == 0, the parabola just TOUCHES // on the boundary, and isn't grounds to return true det = Math.sqrt(det); // root #1: t2 = (-by + det) / (2 * ay); if (t2 > 0 && t2 < 1) { x = (ax * t2 + bx) * t2 + cx; if (x1 < x && x < x2) { return true; } } // root #2: t2 = (-by - det) / (2 * ay); if (t2 > 0 && t2 < 1) { x = (ax * t2 + bx) * t2 + cx; if (x1 < x && x < x2) { return true; } } } det = by * by - 4 * ay * (cy - y2); if (det > 0) { det = Math.sqrt(det); // root #1: t2 = (-by + det) / (2 * ay); if (t2 > 0 && t2 < 1) { x = (ax * t2 + bx) * t2 + cx; if (x1 < x && x < x2) { return true; } } // root #2: t2 = (-by - det) / (2 * ay); if (t2 > 0 && t2 < 1) { x = (ax * t2 + bx) * t2 + cx; if (x1 < x && x < x2) { return true; } } } // now the vertical lines: det = bx * bx - 4 * ax * (cx - x1); if (det > 0) { det = Math.sqrt(det); // root #1: t2 = (-bx + det) / (2 * ax); if (t2 > 0 && t2 < 1) { y = (ay * t2 + by) * t2 + cy; if (y1 < y && y < y2) { return true; } } // root #2: t2 = (-bx - det) / (2 * ax); if (t2 > 0 && t2 < 1) { y = (ay * t2 + by) * t2 + cy; if (y1 < y && y < y2) { return true; } } } det = bx * bx - 4 * ax * (cx - x2); if (det > 0) { det = Math.sqrt(det); // root #1: t2 = (-bx + det) / (2 * ax); if (t2 > 0 && t2 < 1) { y = (ay * t2 + by) * t2 + cy; if (y1 < y && y < y2) { return true; } } // root #2: t2 = (-bx - det) / (2 * ax); if (t2 > 0 && t2 < 1) { y = (ay * t2 + by) * t2 + cy; if (y1 < y && y < y2) { return true; } } } lastX = data[2]; lastY = data[3]; } else if (type == PathIterator.SEG_CUBICTO) { ay = -lastY + 3 * data[1] - 3 * data[3] + data[5]; by = 3 * lastY - 6 * data[1] + 3 * data[3]; cy = -3 * lastY + 3 * data[1]; dy = lastY; ax = -lastX + 3 * data[0] - 3 * data[2] + data[4]; bx = 3 * lastX - 6 * data[0] + 3 * data[2]; cx = -3 * lastX + 3 * data[0]; dx = lastX; array[0] = 0; i = 1; det = 4 * bx * bx - 12 * ax * cx; if (det == 0) { t2 = (-2 * bx) / (6 * ax); if (t2 > 0 && t2 < 1) array[i++] = t2; } else if (det > 0) { det = Math.sqrt(det); t2 = (-2 * bx - det) / (6 * ax); if (t2 > 0 && t2 < 1) array[i++] = t2; t2 = (-2 * bx + det) / (6 * ax); if (t2 > 0 && t2 < 1) array[i++] = t2; } det = 4 * by * by - 12 * ay * cy; if (det == 0) { t2 = (-2 * by) / (6 * ay); if (t2 > 0 && t2 < 1) array[i++] = t2; } else if (det > 0) { det = Math.sqrt(det); t2 = (-2 * by - det) / (6 * ay); if (t2 > 0 && t2 < 1) array[i++] = t2; t2 = (-2 * by + det) / (6 * ay); if (t2 > 0 && t2 < 1) array[i++] = t2; } eqn[0] = dy - y1; eqn[1] = cy; eqn[2] = by; eqn[3] = ay; i2 = CubicCurve2D.solveCubic(eqn, results); for (int a = 0; a < i2; a++) { if (results[a] > 0 && results[a] < 1) { array[i++] = results[a]; } } eqn[0] = dy - y2; eqn[1] = cy; eqn[2] = by; eqn[3] = ay; i2 = CubicCurve2D.solveCubic(array, results); for (int a = 0; a < i2; a++) { if (results[a] > 0 && results[a] < 1) { array[i++] = results[a]; } } array[i++] = 1; state = -1; // TODO: Arrays.sort() may allocate unnecessary memory? Arrays.sort(array, 0, i); for (int a = 0; a < i; a++) { myY = ((ay * array[a] + by) * array[a] + cy) * array[a] + dy; if (myY >= y1e && myY <= y2e) { myX = ((ax * array[a] + bx) * array[a] + cx) * array[a] + dx; if (myX < x1) { myState = 0; } else if (myX > x2) { myState = 2; } else { return true; } if (state == -1) { state = myState; } else if (state != myState) { return true; } } else { state = -1; } } lastX = data[4]; lastY = data[5]; } iter.next(); } return false; } @Override public boolean intersects(double x, double y, double w, double h) { return intersects(x, y, w, h, null); } public boolean intersects(double x, double y, double w, double h, AffineTransform transform) { if (identifyCrossings(x, y, w, h, transform)) { return true; } /** * It may not intersect, but if the rectangle lies entirely inside this * shape then we should also return true. */ if (contains(x + w / 2, y + h / 2) == false) { return true; } return false; } @Override public boolean contains(double x, double y, double w, double h) { return contains(x, y, w, h, null); } public boolean contains(double x, double y, double w, double h, AffineTransform transform) { if (identifyCrossings(x, y, w, h, transform)) { return false; } /** * We've established that this rectangle is either 100% inside or 100% * outside of this shape. (There are no segments of this shape crossing * this rectangle, or inside this rectangle.) * * Last test: are we inside or outside? */ if (contains(x + w / 2, y + h / 2) == false) { // the rectangle is 100% outside this shape return false; } return true; } @Override public Rectangle getBounds() { Rectangle r = new Rectangle(); getBounds(null, r); return r; } @Override public Rectangle2D getBounds2D() { Rectangle2D r = new Rectangle2D.Double(); getBounds(null, r); return r; } public Rectangle getBounds(AffineTransform transform) { Rectangle r = new Rectangle(); getBounds(transform, r); return r; } public Rectangle2D getBounds2D(AffineTransform transform) { Rectangle2D r = new Rectangle2D.Double(); getBounds(transform, r); return r; } public Rectangle2D getBounds(AffineTransform transform, Rectangle2D r) { PathIterator iterator = getPathIterator(transform); return ShapeBounds.getBounds(iterator, r); } @Override public PathIterator getPathIterator(AffineTransform at, double flatness) { return new FlatteningPathIterator(getPathIterator(at), flatness); } @Override public boolean intersects(Rectangle2D r) { return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } }
Java
public final class SkillHandler extends SkillStreamHandler { /** * Start the application context and retrieve the Skill from the context. * * @return the Skill instance. */ private static Skill getSkill() { try (var context = new AnnotationConfigApplicationContext(SkillConfig.class)) { return context.getBean(Skill.class); } } public SkillHandler() { super(getSkill()); } }
Java
public class OnExceptionRetryUntilWithDefaultErrorHandlerTest extends ContextTestSupport { private static int invoked; @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); jndi.bind("myRetryHandler", new MyRetryBean()); return jndi; } public void testRetryUntil() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { // as its based on a unit test we do not have any delays between and do not log the stack trace errorHandler(defaultErrorHandler().maximumRedeliveries(1).logStackTrace(false)); onException(MyFunctionalException.class) .retryWhile(method("myRetryHandler")) .redeliveryDelay(0) .handled(true) .transform().constant("Sorry").stop(); from("direct:start").process(new Processor() { public void process(Exchange exchange) throws Exception { throw new MyFunctionalException("Sorry you cannot do this"); } }); } }); Object out = template.requestBody("direct:start", "Hello World"); assertEquals("Sorry", out); assertEquals(3, invoked); } public class MyRetryBean { // using bean binding we can bind the information from the exchange to the types we have in our method signature public boolean retry(@Header(Exchange.REDELIVERY_COUNTER) Integer counter, @Body String body, @ExchangeException Exception causedBy) { // NOTE: counter is the redelivery attempt, will start from 1 invoked++; assertEquals("Hello World", body); assertTrue(causedBy instanceof MyFunctionalException); // we can of course do what ever we want to determine the result but this is a unit test so we end after 3 attempts return counter < 3; } } }
Java
class TabSelectionEditorMediator implements TabSelectionEditorCoordinator.TabSelectionEditorController { // TODO(977271): Unify similar interfaces in other components that used the TabListCoordinator. /** * Interface for resetting the selectable tab grid. */ interface ResetHandler { /** * Handles the reset event. * @param tabs List of {@link Tab}s to reset. * @param preSelectedCount First {@code preSelectedCount} {@code tabs} are pre-selected. */ void resetWithListOfTabs(@Nullable List<Tab> tabs, int preSelectedCount); } /** * An interface to provide the {@link Rect} used to position the selection editor on screen. */ public interface TabSelectionEditorPositionProvider { /** * This method fetches the {@link Rect} used to position the selection editor layout. * @return The {@link Rect} indicates where to show the selection editor layout. This Rect * should never be null. */ @NonNull Rect getSelectionEditorPositionRect(); } private final Context mContext; private final TabModelSelector mTabModelSelector; private final ResetHandler mResetHandler; private final PropertyModel mModel; private final SelectionDelegate<Integer> mSelectionDelegate; private final TabModelSelectorTabModelObserver mTabModelObserver; private final TabModelSelectorObserver mTabModelSelectorObserver; private final TabSelectionEditorPositionProvider mPositionProvider; private TabSelectionEditorActionProvider mActionProvider; private TabSelectionEditorCoordinator.TabSelectionEditorNavigationProvider mNavigationProvider; private final View.OnClickListener mNavigationClickListener = new View.OnClickListener() { @Override public void onClick(View v) { mNavigationProvider.goBack(); } }; private final View.OnClickListener mActionButtonOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { List<Tab> selectedTabs = new ArrayList<>(); for (int tabId : mSelectionDelegate.getSelectedItems()) { selectedTabs.add( TabModelUtils.getTabById(mTabModelSelector.getCurrentModel(), tabId)); } if (mActionProvider == null) return; mActionProvider.processSelectedTabs(selectedTabs, mTabModelSelector); } }; TabSelectionEditorMediator(Context context, TabModelSelector tabModelSelector, ResetHandler resetHandler, PropertyModel model, SelectionDelegate<Integer> selectionDelegate, @Nullable TabSelectionEditorMediator .TabSelectionEditorPositionProvider positionProvider) { mContext = context; mTabModelSelector = tabModelSelector; mResetHandler = resetHandler; mModel = model; mSelectionDelegate = selectionDelegate; mPositionProvider = positionProvider; mModel.set( TabSelectionEditorProperties.TOOLBAR_NAVIGATION_LISTENER, mNavigationClickListener); mModel.set(TabSelectionEditorProperties.TOOLBAR_ACTION_BUTTON_LISTENER, mActionButtonOnClickListener); mTabModelObserver = new TabModelSelectorTabModelObserver(mTabModelSelector) { @Override public void didAddTab(Tab tab, int type, @TabCreationState int creationState) { // When tab is added due to multi-window close or moving between multiple windows, // force hiding the selection editor. if (type == TabLaunchType.FROM_RESTORE || type == TabLaunchType.FROM_REPARENTING) { hide(); } } @Override public void willCloseTab(Tab tab, boolean animate) { if (isEditorVisible()) hide(); } }; mTabModelSelectorObserver = new EmptyTabModelSelectorObserver() { @Override public void onTabModelSelected(TabModel newModel, TabModel oldModel) { // Incognito in both light/dark theme is the same as non-incognito mode in dark // theme. Non-incognito mode and incognito in both light/dark themes in dark theme // all look dark. boolean isIncognito = newModel.isIncognito(); @ColorInt int primaryColor = ApiCompatibilityUtils.getColor(mContext.getResources(), isIncognito ? R.color.default_bg_color_dark : R.color.default_bg_color); // TODO(995876): Update color modern_blue_300 to active_color_dark when the // associated bug is landed. @ColorInt int toolbarBackgroundColor = ApiCompatibilityUtils.getColor(mContext.getResources(), isIncognito ? R.color.modern_blue_300 : R.color.default_control_color_active); ColorStateList toolbarTintColorList = AppCompatResources.getColorStateList(mContext, isIncognito ? R.color.dark_text_color_list : R.color.default_text_color_inverse_list); int textAppearance = isIncognito ? R.style.TextAppearance_Headline_Primary_Dark : R.style.TextAppearance_Headline_Primary_Inverse; mModel.set(TabSelectionEditorProperties.PRIMARY_COLOR, primaryColor); mModel.set(TabSelectionEditorProperties.TOOLBAR_BACKGROUND_COLOR, toolbarBackgroundColor); mModel.set(TabSelectionEditorProperties.TOOLBAR_GROUP_BUTTON_TINT, toolbarTintColorList); mModel.set(TabSelectionEditorProperties.TOOLBAR_TEXT_APPEARANCE, textAppearance); } }; mTabModelSelector.addObserver(mTabModelSelectorObserver); // Default action for action button is to group selected tabs. mActionProvider = new TabSelectionEditorActionProvider( this, TabSelectionEditorActionProvider.TabSelectionEditorAction.GROUP); mNavigationProvider = new TabSelectionEditorCoordinator.TabSelectionEditorNavigationProvider(this); if (mPositionProvider != null) { mModel.set(TabSelectionEditorProperties.SELECTION_EDITOR_GLOBAL_LAYOUT_LISTENER, () -> mModel.set( TabSelectionEditorProperties.SELECTION_EDITOR_POSITION_RECT, mPositionProvider.getSelectionEditorPositionRect())); } } private boolean isEditorVisible() { return mModel.get(TabSelectionEditorProperties.IS_VISIBLE); } /** * {@link TabSelectionEditorCoordinator.TabSelectionEditorController} implementation. */ @Override public void show(List<Tab> tabs) { show(tabs, 0); } @Override public void show(List<Tab> tabs, int preSelectedTabCount) { mSelectionDelegate.setSelectionModeEnabledForZeroItems(true); if (preSelectedTabCount > 0) { assert preSelectedTabCount <= tabs.size(); Set<Integer> preSelectedTabIds = new HashSet<>(); for (int i = 0; i < preSelectedTabCount; i++) { preSelectedTabIds.add(tabs.get(i).getId()); } mSelectionDelegate.setSelectedItems(preSelectedTabIds); } mResetHandler.resetWithListOfTabs(tabs, preSelectedTabCount); if (mPositionProvider != null) { mModel.set(TabSelectionEditorProperties.SELECTION_EDITOR_POSITION_RECT, mPositionProvider.getSelectionEditorPositionRect()); } mModel.set(TabSelectionEditorProperties.IS_VISIBLE, true); } @Override public void configureToolbar(@Nullable String actionButtonText, @Nullable TabSelectionEditorActionProvider actionProvider, int actionButtonEnablingThreshold, @Nullable TabSelectionEditorCoordinator .TabSelectionEditorNavigationProvider navigationProvider) { if (actionButtonText != null) { mModel.set(TabSelectionEditorProperties.TOOLBAR_ACTION_BUTTON_TEXT, actionButtonText); } if (actionProvider != null) { mActionProvider = actionProvider; } if (actionButtonEnablingThreshold != -1) { mModel.set(TabSelectionEditorProperties.TOOLBAR_ACTION_BUTTON_ENABLING_THRESHOLD, actionButtonEnablingThreshold); } if (navigationProvider != null) { mNavigationProvider = navigationProvider; } } @Override public boolean handleBackPressed() { if (!isEditorVisible()) return false; mNavigationProvider.goBack(); return true; } @Override public void hide() { mResetHandler.resetWithListOfTabs(null, 0); mModel.set(TabSelectionEditorProperties.IS_VISIBLE, false); } /** * Destroy any members that needs clean up. */ public void destroy() { mTabModelObserver.destroy(); if (mTabModelSelector != null) { mTabModelSelector.removeObserver(mTabModelSelectorObserver); } } }
Java
public class MyAdapter <T>extends BaseAdapter { private Context context; private List<T> list; private LayoutInflater inflater; private int resource; public MyAdapter(Context context, List<T> ele,int resource) { this.context = context; this.list = ele; this.inflater = LayoutInflater.from(this.context); this.resource=resource; } @Override public int getCount() { return list.size(); } @Override public T getItem(int position) { return this.list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view=null; ViewHolder holder; if (convertView==null){ view=inflater.inflate(this.resource, null); holder=new ViewHolder(); holder.textView=(TextView)view.findViewById(R.id.textView); holder.textView2=(TextView)view.findViewById(R.id.textView2); view.setTag(holder); }else { view=convertView; holder= (ViewHolder) view.getTag(); } User u=(User)getItem(position); holder.textView.setText(u.getName().toString()); holder.textView2.setText(u.getAge()+""); return view; } class ViewHolder{ TextView textView; TextView textView2; } }
Java
public class SymbolicShape { private Operand operand; private List<String> symbols = new ArrayList<>(); public SymbolicShape(Operand operand, String... symbols) { this.operand = operand; this.symbols.addAll(Arrays.asList(symbols)); } /** * @return the operand */ public Operand getOperand() { return operand; } /** * @param operand the operand to set */ public void setOperand(Operand operand) { this.operand = operand; } /** * @return the symbols */ public List<String> getSymbols() { return symbols; } /** * @param symbols the symbols to set */ public void setSymbols(List<String> symbols) { this.symbols = symbols; } public int rank() { return this.symbols.size(); } }
Java
public class HypercubeException extends RuntimeException { private static final long serialVersionUID = -1102120552379762035L; /** * Constructs a new {@link HypercubeException} with no message. */ public HypercubeException() { super(); } /** * Constructs a new {@link HypercubeException} with the specified detail * message. * * @param message * the detail message. */ public HypercubeException(String message) { super(message); } /** * Constructs a new {@link HypercubeException} with only cause. * * @param cause * the cause of this exception */ public HypercubeException(Throwable cause) { super("See below.", cause); } /** * Constructs a new {@link HypercubeException} with the specified detail * message and cause. * * @param message * the detail message. * @param cause * the cause of this exception */ public HypercubeException(String message, Throwable cause) { super(message, cause); } /** * Overrides the default {@link Throwable#printStackTrace()} and prints a * shorter backtrace constisting only of causes and their messages (if * exist) like the following. * * <pre> * hypercube: Message of this exception. * Caused by: java.lang.NullPointerException * Caused by: java.lang.IOException: File not found. * ... * </pre> */ @Override public void printStackTrace() { System.err.println("hypercube: " + getMessage()); Throwable cause = getCause(); while (cause != null) { System.err.println("Caused by: " + cause); cause = cause.getCause(); } } }
Java
private class RequestedListAdapter extends ArrayAdapter<Book>{ private int layout; public RequestedListAdapter(@NonNull Context context, int resource, @NonNull List<Book> objects) { super(context, resource, objects); layout = resource; } /** * Allows us to set the attributes of each list item independently * at different positions * @param position * @param convertView * @param parent * @return */ @NonNull @Override public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(getContext()); convertView = inflater.inflate(layout, parent, false); final RequestedViewHolder viewHolder = new RequestedViewHolder(); viewHolder.title = convertView.findViewById(R.id.requested_book_title); viewHolder.status = convertView.findViewById(R.id.requested_book_status); viewHolder.owner = convertView.findViewById(R.id.requested_book_owner); viewHolder.scan_button = convertView.findViewById(R.id.scan_received_button); viewHolder.book_pickup_button = convertView.findViewById(R.id.requested_book_pickup_button); viewHolder.book_pickup_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Shows the location the owner has picked for pickup final Intent pickup = new Intent(getContext(), PickupLocation.class); db = FirebaseFirestore.getInstance(); DocumentReference docRef = db.collection("Users") .document(MainActivity.current_user) .collection("Requested Books") .document(getItem(position).getIsbn()); docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { Log.d(TAG, "DocumentSnapshot data: " + document.getData()); if (document.get("book.pickupLat") == null || document.get("book.pickupLon") == null){ Toast.makeText(getActivity(), "Location Has Not Been Picked By Owner!", Toast.LENGTH_LONG).show(); }else { pickupLat = document.get("book.pickupLat").toString(); pickupLon = document.get("book.pickupLon").toString(); pickup.putExtra("pickupLat", pickupLat); pickup.putExtra("pickupLon", pickupLon); Log.d(TAG, "onComplete: " + pickupLat + "," + pickupLon); startActivity(pickup); } } else { Log.d(TAG, "No such document"); } } else { Log.d(TAG, "get failed with ", task.getException()); } } }); } }); viewHolder.scan_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Scan that confirms the user has received the book status = getItem(position).getStatus(); isbn = getItem(position).getIsbn(); owner = getItem(position).getOwner(); author = getItem(position).getAuthor(); title = getItem(position).getTitle(); requestStatus = getItem(position).getRequestStatus(); Intent intent = new Intent(getActivity(), ScanBarcodeActivity.class); startActivityForResult(intent, 103); } }); viewHolder.title.setText("Title: "+getItem(position).getTitle()); viewHolder.owner.setText("Owner: " + getItem(position).getOwner()); viewHolder.status.setText("Status: "+getItem(position).getRequestStatus()); if(getItem(position).getRequestStatus().equals("Accepted")){ viewHolder.book_pickup_button.setVisibility(View.VISIBLE); viewHolder.scan_button.setVisibility(View.VISIBLE); } convertView.setTag(viewHolder); return convertView; } }
Java
private class RequestedViewHolder{ TextView title; TextView status; TextView owner; Button scan_button; Button book_pickup_button; }
Java
@RestController @RequestMapping("/demo") public class DemoController { @GetMapping("/admin-list") @PreAuthorize("hasRole('ADMIN')") // 要求管理员 ROLE_ADMIN 角色 public String adminList(){ return "管理员列表"; } @GetMapping("user-list") @PreAuthorize("hasRole('USER')") // 要求普通用户 ROLE_USER 角色 public String userList(){ return "用户列表"; } }
Java
public class FashionFragment extends Fragment { public static final String TAG = "FF"; public FashionFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment RecyclerView rvRecyclerView = (RecyclerView) inflater.inflate(R.layout.recycler_view,container,false); ArrayList<Fashion> fashionArrayList = new ArrayList<>(); Fashion dummyData = new Fashion(); dummyData.setCount_of_item(5); dummyData.setName("Hello"); fashionArrayList.add(dummyData); fashionArrayList.add(dummyData); fashionArrayList.add(dummyData); fashionArrayList.add(dummyData); fashionArrayList.add(dummyData); FashionAdapter fashionAdapter = new FashionAdapter(getContext(),fashionArrayList); rvRecyclerView.setHasFixedSize(true); rvRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); rvRecyclerView.setAdapter(fashionAdapter); Log.d(TAG, "onCreateView: "+fashionArrayList.size()); return rvRecyclerView; } }
Java
public class CallLogListItemView extends LinearLayout { public CallLogListItemView(Context context) { super(context); } public CallLogListItemView(Context context, AttributeSet attrs) { super(context, attrs); } public CallLogListItemView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } }
Java
public class OfficeEntityContainerInvocationHandler extends EntityContainerInvocationHandler { /** * Currently used communication type. */ protected static ContainerType sContainerType = ContainerType.SEQUENTIAL; /** * Creates a new instance of {@link OfficeEntityContainerInvocationHandler} class. * * @param client Client to be used. * @param ref Container class. * @param factory Container factory. */ protected OfficeEntityContainerInvocationHandler(ODataClient client, Class<?> ref, EntityContainerFactory factory) { super(client, ref, factory); } /** * {@inheritDoc} */ @Override protected AbstractContainer getContainer() { switch (getContainerType()) { case BATCH: return new BatchContainer(client, factory); case SEQUENTIAL: return new SequentialContainer(client, factory); } throw new IllegalStateException("Unknown container type is set"); } /** * Gets currently used container type. * * @return Container type in use. */ public static ContainerType getContainerType() { return sContainerType; } /** * Sets container type to be used. * * @param containerType container type to be used for service communication. */ public static void setContainerType(ContainerType containerType) { sContainerType = containerType; } /** * Gets an instance of {@link OfficeEntityContainerInvocationHandler} class. * * @param client Client to be used. * @param ref Container class. * @param factory Container factory. * @return An instance of {@link OfficeEntityContainerInvocationHandler} class. */ public static OfficeEntityContainerInvocationHandler getInstance( final ODataClient client, final Class<?> ref, final OfficeEntityContainerFactory factory) { if (sContainers.containsKey(ref)) { return (OfficeEntityContainerInvocationHandler) sContainers.get(ref); } final OfficeEntityContainerInvocationHandler instance = new OfficeEntityContainerInvocationHandler(client, ref, factory); sContainers.put(ref, instance); instance.containerHandler = instance; return instance; } }
Java
public class DecayingHashSet extends DecayingBloomFilter { private ConcurrentHashSet<ArrayWrapper> _current; private ConcurrentHashSet<ArrayWrapper> _previous; /** * Create a double-buffered hash set that will decay its entries over time. * * @param durationMs entries last for at least this long, but no more than twice this long * @param entryBytes how large are the entries to be added? 1 to 32 bytes */ public DecayingHashSet(I2PAppContext context, int durationMs, int entryBytes) { this(context, durationMs, entryBytes, "DHS"); } /** @param name just for logging / debugging / stats */ public DecayingHashSet(I2PAppContext context, int durationMs, int entryBytes, String name) { super(durationMs, entryBytes, name, context); if (entryBytes <= 0 || entryBytes > 32) throw new IllegalArgumentException("Bad size"); _current = new ConcurrentHashSet<ArrayWrapper>(128); _previous = new ConcurrentHashSet<ArrayWrapper>(128); if (_log.shouldLog(Log.DEBUG)) _log.debug("New DHS " + name + " entryBytes = " + entryBytes + " cycle (s) = " + (durationMs / 1000)); // try to get a handle on memory usage vs. false positives context.statManager().createRateStat("router.decayingHashSet." + name + ".size", "Size", "Router", new long[] { 10 * Math.max(60*1000, durationMs) }); context.statManager().createRateStat("router.decayingHashSet." + name + ".dups", "1000000 * Duplicates/Size", "Router", new long[] { 10 * Math.max(60*1000, durationMs) }); } /** unsynchronized but only used for logging elsewhere */ @Override public int getInsertedCount() { return _current.size() + _previous.size(); } /** pointless, only used for logging elsewhere */ @Override public double getFalsePositiveRate() { if (_entryBytes <= 8) return 0d; return 1d / Math.pow(2d, 64d); // 5.4E-20 } /** * @return true if the entry added is a duplicate */ @Override public boolean add(byte entry[], int off, int len) { if (entry == null) throw new IllegalArgumentException("Null entry"); if (len != _entryBytes) throw new IllegalArgumentException("Bad entry [" + len + ", expected " + _entryBytes + "]"); ArrayWrapper w = new ArrayWrapper(entry, off, len); getReadLock(); try { return locked_add(w, true); } finally { releaseReadLock(); } } /** * @return true if the entry added is a duplicate. the number of low order * bits used is determined by the entryBytes parameter used on creation of the * filter. * */ @Override public boolean add(long entry) { return add(entry, true); } /** * @return true if the entry is already known. this does NOT add the * entry however. * */ @Override public boolean isKnown(long entry) { return add(entry, false); } private boolean add(long entry, boolean addIfNew) { ArrayWrapper w = new ArrayWrapper(entry); getReadLock(); try { return locked_add(w, addIfNew); } finally { releaseReadLock(); } } /** * @param addIfNew if true, add the element to current if it is not already there or in previous; * if false, only check * @return if the element is in either the current or previous set */ private boolean locked_add(ArrayWrapper w, boolean addIfNew) { boolean seen = _previous.contains(w); // only access _current once. if (!seen) { if (addIfNew) seen = !_current.add(w); else seen = _current.contains(w); } if (seen) { // why increment if addIfNew == false? Only used for stats... _currentDuplicates++; } return seen; } @Override public void clear() { _current.clear(); _previous.clear(); _currentDuplicates = 0; } /** super doesn't call clear, but neither do the users, so it seems like we should here */ @Override public void stopDecaying() { _keepDecaying = false; clear(); } @Override protected void decay() { int currentCount; long dups; if (!getWriteLock()) return; try { ConcurrentHashSet<ArrayWrapper> tmp = _previous; currentCount = _current.size(); _previous = _current; _current = tmp; _current.clear(); dups = _currentDuplicates; _currentDuplicates = 0; } finally { releaseWriteLock(); } if (_log.shouldLog(Log.DEBUG)) _log.debug("Decaying the filter " + _name + " after inserting " + currentCount + " elements and " + dups + " false positives"); _context.statManager().addRateData("router.decayingHashSet." + _name + ".size", currentCount); if (currentCount > 0) _context.statManager().addRateData("router.decayingHashSet." + _name + ".dups", 1000l*1000*dups/currentCount); } /** * This saves the data as-is if the length is <= 8 bytes, * otherwise it stores an 8-byte hash. * Hash function is from DataHelper, modded to get * the maximum entropy given the length of the data. */ private static class ArrayWrapper { private final long _longhashcode; public ArrayWrapper(byte[] b, int offset, int len) { int idx = offset; int shift = Math.min(8, 64 / len); long lhc = 0; for (int i = 0; i < len; i++) { // xor better than + in tests lhc ^= (((long) b[idx++]) << (i * shift)); } _longhashcode = lhc; } /** faster version for when storing <= 8 bytes */ public ArrayWrapper(long b) { _longhashcode = b; } public int hashCode() { return (int) _longhashcode; } public long longHashCode() { return _longhashcode; } public boolean equals(Object o) { if (o == null || !(o instanceof ArrayWrapper)) return false; return ((ArrayWrapper) o).longHashCode() == _longhashcode; } } /** * vs. DBF, this measures 1.93x faster for testByLong and 2.46x faster for testByBytes. */ /***** public static void main(String args[]) { // KBytes per sec, 1 message per KByte int kbps = 256; int iterations = 10; //testSize(); testByLong(kbps, iterations); testByBytes(kbps, iterations); } *****/ /** and the answer is: 49.9 bytes. The ArrayWrapper alone measured 16, so that's 34 for the HashSet entry. */ /***** private static void testSize() { int qty = 256*1024; byte b[] = new byte[8]; Random r = new Random(); long old = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); ConcurrentHashSet foo = new ConcurrentHashSet(qty); for (int i = 0; i < qty; i++) { r.nextBytes(b); foo.add(new ArrayWrapper(b, 0, 8)); } long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("Memory per ArrayWrapper: " + (((double) (used - old)) / qty)); } *****/ /** 8 bytes, simulate the router message validator */ /***** private static void testByLong(int kbps, int numRuns) { int messages = 60 * 10 * kbps; Random r = new Random(); DecayingBloomFilter filter = new DecayingHashSet(I2PAppContext.getGlobalContext(), 600*1000, 8); int falsePositives = 0; long totalTime = 0; for (int j = 0; j < numRuns; j++) { long start = System.currentTimeMillis(); for (int i = 0; i < messages; i++) { if (filter.add(r.nextLong())) { falsePositives++; System.out.println("False positive " + falsePositives + " (testByLong j=" + j + " i=" + i + ")"); } } totalTime += System.currentTimeMillis() - start; filter.clear(); } System.out.println("False postive rate should be " + filter.getFalsePositiveRate()); filter.stopDecaying(); System.out.println("After " + numRuns + " runs pushing " + messages + " entries in " + DataHelper.formatDuration(totalTime/numRuns) + " per run, there were " + falsePositives + " false positives"); } *****/ /** 16 bytes, simulate the tunnel IV validator */ /***** private static void testByBytes(int kbps, int numRuns) { byte iv[][] = new byte[60*10*kbps][16]; Random r = new Random(); for (int i = 0; i < iv.length; i++) r.nextBytes(iv[i]); DecayingBloomFilter filter = new DecayingHashSet(I2PAppContext.getGlobalContext(), 600*1000, 16); int falsePositives = 0; long totalTime = 0; for (int j = 0; j < numRuns; j++) { long start = System.currentTimeMillis(); for (int i = 0; i < iv.length; i++) { if (filter.add(iv[i])) { falsePositives++; System.out.println("False positive " + falsePositives + " (testByBytes j=" + j + " i=" + i + ")"); } } totalTime += System.currentTimeMillis() - start; filter.clear(); } System.out.println("False postive rate should be " + filter.getFalsePositiveRate()); filter.stopDecaying(); System.out.println("After " + numRuns + " runs pushing " + iv.length + " entries in " + DataHelper.formatDuration(totalTime/numRuns) + " per run, there were " + falsePositives + " false positives"); } *****/ }
Java
private static class ArrayWrapper { private final long _longhashcode; public ArrayWrapper(byte[] b, int offset, int len) { int idx = offset; int shift = Math.min(8, 64 / len); long lhc = 0; for (int i = 0; i < len; i++) { // xor better than + in tests lhc ^= (((long) b[idx++]) << (i * shift)); } _longhashcode = lhc; } /** faster version for when storing <= 8 bytes */ public ArrayWrapper(long b) { _longhashcode = b; } public int hashCode() { return (int) _longhashcode; } public long longHashCode() { return _longhashcode; } public boolean equals(Object o) { if (o == null || !(o instanceof ArrayWrapper)) return false; return ((ArrayWrapper) o).longHashCode() == _longhashcode; } }
Java
public class Iteration { /** * Gets the id of the iteration. */ @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) private UUID id; /** * Gets or sets the name of the iteration. */ @JsonProperty(value = "name", required = true) private String name; /** * Gets the current iteration status. */ @JsonProperty(value = "status", access = JsonProperty.Access.WRITE_ONLY) private String status; /** * Gets the time this iteration was completed. */ @JsonProperty(value = "created", access = JsonProperty.Access.WRITE_ONLY) private DateTime created; /** * Gets the time this iteration was last modified. */ @JsonProperty(value = "lastModified", access = JsonProperty.Access.WRITE_ONLY) private DateTime lastModified; /** * Gets the time this iteration was last modified. */ @JsonProperty(value = "trainedAt", access = JsonProperty.Access.WRITE_ONLY) private DateTime trainedAt; /** * Gets the project id of the iteration. */ @JsonProperty(value = "projectId", access = JsonProperty.Access.WRITE_ONLY) private UUID projectId; /** * Whether the iteration can be exported to another format for download. */ @JsonProperty(value = "exportable", access = JsonProperty.Access.WRITE_ONLY) private boolean exportable; /** * A set of platforms this iteration can export to. */ @JsonProperty(value = "exportableTo", access = JsonProperty.Access.WRITE_ONLY) private List<String> exportableTo; /** * Get or sets a guid of the domain the iteration has been trained on. */ @JsonProperty(value = "domainId", access = JsonProperty.Access.WRITE_ONLY) private UUID domainId; /** * Gets the classification type of the project. Possible values include: * 'Multiclass', 'Multilabel'. */ @JsonProperty(value = "classificationType", access = JsonProperty.Access.WRITE_ONLY) private Classifier classificationType; /** * Gets the training type of the iteration. Possible values include: * 'Regular', 'Advanced'. */ @JsonProperty(value = "trainingType", access = JsonProperty.Access.WRITE_ONLY) private TrainingType trainingType; /** * Gets the reserved advanced training budget for the iteration. */ @JsonProperty(value = "reservedBudgetInHours", access = JsonProperty.Access.WRITE_ONLY) private int reservedBudgetInHours; /** * Name of the published model. */ @JsonProperty(value = "publishName", access = JsonProperty.Access.WRITE_ONLY) private String publishName; /** * Resource Provider Id this iteration was originally published to. */ @JsonProperty(value = "originalPublishResourceId", access = JsonProperty.Access.WRITE_ONLY) private String originalPublishResourceId; /** * Get the id value. * * @return the id value */ public UUID id() { return this.id; } /** * Get the name value. * * @return the name value */ public String name() { return this.name; } /** * Set the name value. * * @param name the name value to set * @return the Iteration object itself. */ public Iteration withName(String name) { this.name = name; return this; } /** * Get the status value. * * @return the status value */ public String status() { return this.status; } /** * Get the created value. * * @return the created value */ public DateTime created() { return this.created; } /** * Get the lastModified value. * * @return the lastModified value */ public DateTime lastModified() { return this.lastModified; } /** * Get the trainedAt value. * * @return the trainedAt value */ public DateTime trainedAt() { return this.trainedAt; } /** * Get the projectId value. * * @return the projectId value */ public UUID projectId() { return this.projectId; } /** * Get the exportable value. * * @return the exportable value */ public boolean exportable() { return this.exportable; } /** * Get the exportableTo value. * * @return the exportableTo value */ public List<String> exportableTo() { return this.exportableTo; } /** * Get the domainId value. * * @return the domainId value */ public UUID domainId() { return this.domainId; } /** * Get the classificationType value. * * @return the classificationType value */ public Classifier classificationType() { return this.classificationType; } /** * Get the trainingType value. * * @return the trainingType value */ public TrainingType trainingType() { return this.trainingType; } /** * Get the reservedBudgetInHours value. * * @return the reservedBudgetInHours value */ public int reservedBudgetInHours() { return this.reservedBudgetInHours; } /** * Get the publishName value. * * @return the publishName value */ public String publishName() { return this.publishName; } /** * Get the originalPublishResourceId value. * * @return the originalPublishResourceId value */ public String originalPublishResourceId() { return this.originalPublishResourceId; } }
Java
public final class Cross { public static final String NORTH = "north"; public static final String EAST = "east"; public static final String SOUTH = "south"; public static final String WEST = "west"; public int id; int[] roadIds = new int[4]; Map<Integer, Map<Integer, Integer>> directionMap = new HashMap<>(); List<Integer> providerDirection; List<Integer> receiverDirection; List<Integer> validRoadDirection; List<Integer> receiver = new ArrayList<>(); List<Integer> provider = new ArrayList<>(); List<Integer> validRoad = new ArrayList<>(); int carportCarNum = ZERO; int finnishCarNum = ZERO; boolean done = false; boolean update = false; List<Integer> readyCars; List<Integer> left; // 剩余的车 Map<Integer, List<Integer>> carport; public Cross(int id) { this.id = id; for (int i = 0; i < roadIds.length; i++) { this.roadIds[i] = -1; // default } } public Cross(int id, int north, int east, int south, int west) { // static param this(id); this.roadIds[0] = north; this.roadIds[1] = east; this.roadIds[2] = south; this.roadIds[3] = west; // self.carport = {} // self.left = [] left = new ArrayList<>(); // 剩余的车 // this.x, self.y = 0, 0 carport = new HashMap<>(); // 构建 priorityMap this.directionMap = buildPriorityMap(north, east, south, west); this.providerDirection = new ArrayList<>(); this.receiverDirection = new ArrayList<>(); this.validRoadDirection = new ArrayList<>(); for (int i = 0; i < roadIds.length; i++) { int roadId = roadIds[i]; if (roadId != NONE) { Road road = ROAD_MAP.get(String.valueOf(roadId)); if (road.isDuplex || road.to == this.id) { this.providerDirection.add(i); } if (road.isDuplex || road.from == this.id) { this.receiverDirection.add(i); } this.validRoadDirection.add(i); } } for (int dir : this.receiverDirection) { this.receiver.add(roadIds[dir]); } for (int dir : this.validRoadDirection) { this.validRoad.add(roadIds[dir]); } List<List<Integer>> tempProvider = new ArrayList<>(); for (int dir : this.providerDirection) { List<Integer> pair = new ArrayList<>(); pair.add(dir); pair.add(roadIds[dir]); tempProvider.add(pair); } Collections.sort(tempProvider, new ArrayListCompare()); providerDirection.clear(); for (List<Integer> l : tempProvider) { this.providerDirection.add(l.get(0)); this.provider.add(l.get(1)); } // dynamic params // read cars ?? this.readyCars = new ArrayList<>(); this.carportCarNum = ZERO; this.finnishCarNum = ZERO; // flag this.done = false; this.update = false; } /** * 构建priority map * * @param north * @param east * @param south * @param west */ private Map<Integer, Map<Integer, Integer>> buildPriorityMap(int north, int east, int south, int west) { Map<Integer, Map<Integer, Integer>> directionMap = new HashMap<>(); Map<Integer, Integer> northMap = new HashMap<>(); northMap.put(east, 1); northMap.put(south, 2); northMap.put(west, -1); Map<Integer, Integer> eastMap = new HashMap<>(); eastMap.put(south, 1); eastMap.put(west, 2); eastMap.put(north, -1); Map<Integer, Integer> southMap = new HashMap<>(); southMap.put(west, 1); southMap.put(north, 2); southMap.put(east, -1); Map<Integer, Integer> westMap = new HashMap<>(); westMap.put(north, 1); westMap.put(east, 2); westMap.put(south, -1); directionMap.put(north, northMap); directionMap.put(east, eastMap); directionMap.put(south, southMap); directionMap.put(west, westMap); return directionMap; } public void step() { this.update = false; for (int roadId : this.validRoad) { ROAD_MAP.get(String.valueOf(roadId)).setBucket(this.id); } // data prepare // nextCarId, nextCar, nextRoad, nextDirection = [], [], [], [] List<Integer> nextCarId = new ArrayList<>(); List<CarRoute> nextCar = new ArrayList<>(); List<Integer> nextRoad = new ArrayList<>(); List<Integer> nextDirection = new ArrayList<>(); for (int i = 0; i < this.provider.size(); i++) { Road currentRoad = ROAD_MAP.get(String.valueOf(this.provider.get(i))); // 当前道路优先级的车 nextCarId.add(currentRoad.findPriorityCar()); // if first priority car exists if (nextCarId.get(i) != NONE) { nextCar.add(CAR_ROUTE_MAP.get(String.valueOf(nextCarId.get(i)))); // 下条路 nextRoad.add(nextCar.get(i).nextRoad()); if (nextRoad.get(i) == NONE) { // terminal,到达终点 nextDirection.add(2); } else { // 车的下一个方向:往东南西北走 nextDirection.add(this.direction(this.provider.get(i), nextRoad.get(i))); } } else { nextCar.add(null); nextRoad.add(NONE); nextDirection.add(NONE); } } for (int presenRoadIndex = 0; presenRoadIndex < this.provider.size(); presenRoadIndex++) { boolean conflict = false; while (nextCar.get(presenRoadIndex) != null) { Road provider = ROAD_MAP.get(String.valueOf(this.provider.get(presenRoadIndex))); for (int otherRoadIndex = 0; otherRoadIndex < this.provider.size(); otherRoadIndex++) { // if ((int) nextRoad.get(otherRoadIndex) != NONE && // // (isConflict(providerDirection.get(presenRoadIndex), // nextDirection.get(presenRoadIndex), // providerDirection.get(otherRoadIndex), // nextDirection.get(otherRoadIndex)))) { // conflict = true; // break; // } if ((int) nextRoad.get(presenRoadIndex) == (int) nextRoad.get(otherRoadIndex) && (int) nextDirection.get(presenRoadIndex) < (int) nextDirection.get(otherRoadIndex)) { conflict = true; break; } } // first priority car exists at road self.provider[otherRoadIndex] if (conflict) { break; } if (nextRoad.get(presenRoadIndex) == NONE) { // terminal 到达终点 // nextCar.get(presenRoadIndex).updateDynamic(3, MINUS_ONE, MINUS_ONE, MINUS_ONE, MINUS_ONE); provider.firstPriorityCarAct(0); CAR_DISTRIBUTION[1] -= 1; CAR_DISTRIBUTION[2] += 1; this.finnishCarNum += 1; this.update = true; } else { // 下一条路 Road nextRoad_ = ROAD_MAP.get(String.valueOf(nextRoad.get(presenRoadIndex))); // 下条路接收这个车 int tempY = nextCar.get(presenRoadIndex).getY(); int action = nextRoad_.receiveCar(nextCar.get(presenRoadIndex).carId); provider.moveInChannel(provider.provideBucket, tempY); if (action == 2) { // waiting conflict break; } this.update = true; provider.firstPriorityCarAct(action); } // 下辆车 nextCarId.set(presenRoadIndex, provider.findPriorityCar()); if (nextCarId.get(presenRoadIndex) != NONE) { nextCar.set(presenRoadIndex, CAR_ROUTE_MAP.get(String.valueOf(nextCarId.get(presenRoadIndex)))); nextRoad.set(presenRoadIndex, nextCar.get(presenRoadIndex).nextRoad()); // nextRoad == -1 => terminal if (nextRoad.get(presenRoadIndex) == NONE) { nextDirection.set(presenRoadIndex, 2); } else { nextDirection.set(presenRoadIndex, this.direction(this.provider.get(presenRoadIndex), nextRoad.get(presenRoadIndex))); } } else { nextCar.set(presenRoadIndex, null); // 没有 nextRoad.set(presenRoadIndex, NONE); // -1 nextDirection.set(presenRoadIndex, NONE); // -1 } } } boolean done = true; for (int fromA = 0; fromA < this.provider.size(); fromA++) { if (nextCar.get(fromA) != null) { done = false; } } this.done = done; } public void outOfCarport() { this.readyCars = this.left; this.left = new ArrayList<>(); if (this.carport.containsKey(TIME[0])) { Collections.sort(carport.get(TIME[0])); readyCars.addAll(carport.get(TIME[0])); } if (this.readyCars.size() == ZERO) { return; } Collections.sort(this.readyCars); for (int roadId : this.receiver) { ROAD_MAP.get(String.valueOf(roadId)).setBucket(this.id); } for (int i = 0; i < this.readyCars.size(); i++) { int carId = this.readyCars.get(i); int roadId = CAR_ROUTE_MAP.get(String.valueOf(carId)).nextRoad(); Road road = ROAD_MAP.get(String.valueOf(roadId)); if (!this.receiver.contains(roadId)) { System.out.printf("Car(%d).Road(%d) not in cross(%d).function:class.outOfCarport\n", carId, roadId, this.id); } int act = road.receiveCar(carId); if (act != 0) { // this.left = this.readyCars.subList(i, readyCars.size()); this.left.add(this.readyCars.get(i)); // break; } else { this.carportCarNum -= 1; CAR_DISTRIBUTION[0] -= 1; CAR_DISTRIBUTION[1] += 1; } } } public boolean isConflict(int fromA, int directionA, int fromB, int directionB) { if ((fromA + directionA) % 4 == (fromB + directionB) % 4 && directionA < directionB) { return true; } else { return false; } } public int direction(int providerId, int receiverId) { return this.directionMap.get(providerId).get(receiverId); } public void setDone(boolean done) { this.done = done; } public boolean done() { return this.done; } public boolean update() { return this.update; } public int roadDirection(int roadId) { if (this.roadIds[0] == roadId) { return 0; } else if (this.roadIds[1] == roadId) { return 1; } else if (this.roadIds[2] == roadId) { return 2; } else if (this.roadIds[3] == roadId) { return 3; } else { return -1; } } public void carportInitial(int timePlan, int carId) { if (!this.carport.containsKey(timePlan)) { List<Integer> list = new ArrayList<>(); list.add(carId); this.carport.put(timePlan, list); } else { this.carport.get(timePlan).add(carId); } this.carportCarNum += 1; } @Override public String toString() { return "Cross{" + "id=" + id + ", roadIds=" + Arrays.toString(roadIds) + '}'; } public static void main(String[] args) { Map<Integer, Map<Integer, Integer>> map = new HashMap<>(); Map<Integer, Integer> map1 = new HashMap<>(); map1.put(5000, 5000); map.put(5000000, map1); Map<Integer, Integer> map2 = new HashMap<>(); map2.put(5000, 5000); map.put(5000000, map2); System.out.println(map.size()); List<Integer> l1 = new ArrayList<>(); l1.add(1); List<Integer> l2 = new ArrayList<>(); l2.add(1); l2.add(3); l1.addAll(l2); System.out.println(l1); System.out.println(new Integer(500) <= new Integer(500)); } }
Java
public class JujubeServerExchangeHandler extends AbstractServerExchangeHandler<Message<HttpRequest, HttpEntity>> { private static final Logger LOG = Loggers.build(); private final JujubeConfig config; private final ExecutorService executor; private final Route route; private AtomicReference<Throwable> exceptionRef; public JujubeServerExchangeHandler(JujubeConfig config, Route route) { this.config = config; this.route = route; this.exceptionRef = new AtomicReference<>(); this.executor = config.getExecutorService(); } @Override protected AsyncRequestConsumer<Message<HttpRequest, HttpEntity>> supplyConsumer(HttpRequest request, EntityDetails entityDetails, HttpContext context) { LOG.debug("handling request: {}", request.toString()); // hydrating context: context.setAttribute("jujube.route", route); context.setAttribute("jujube.config", config); LOG.debug("dispatching pre consumption middleware"); Future<?> future = executor.submit(() -> { for (Middleware middleware : config.getMiddlewareRegistry()) { try { middleware.onBeforeContentConsumption(request, context); } catch (Exception e) { LOG.error("error while dispatching middleware {}", middleware); e.printStackTrace(); exceptionRef.set(e); } } }); try { future.get(); } catch (InterruptedException | ExecutionException ex) { throw new IllegalStateException(ex); } return new ContentAwareRequestConsumer(config, entityDetails, exceptionRef); } @Override protected void handle(Message<HttpRequest, HttpEntity> requestMessage, AsyncServerRequestHandler.ResponseTrigger responseTrigger, HttpContext context) throws HttpException { try { // wrapping around jujube objects: JujubeResponse response = null; JujubeRequest request = new JujubeRequest(requestMessage.getHead(), requestMessage.getBody()); // dispatching handler if we do not already have an exception/response if (exceptionRef.get() == null) { Future<JujubeResponse> responseFuture = this.executor.submit(() -> { // extracting parameters: var parentRequest = requestMessage.getHead(); var entity = requestMessage.getBody(); // constraints List<Parameter> parameters = new ArrayList<>(); // extracting parameters: config.getParameterExtractorRegistry().forEach(pe -> { parameters.addAll(pe.extract(parentRequest, entity, context)); }); request.setParameters(parameters); // dispatching return route.getHandler().handle(request, context); // blocking and awaiting response: }); try { response = responseFuture.get(); } catch (ExecutionException e) { exceptionRef.set(e); } } // if we errored before getting here, quickly exit: if (exceptionRef.get() != null) { response = handleException(exceptionRef.get()); } // handling response: if (response != null) { LOG.debug("dispatching post-execution middleware"); JujubeResponse finalResponse = response; Future<?> future = executor.submit(() -> { for (Middleware middleware : config.getMiddlewareRegistry()) { try { middleware.onAfterHandler(request, finalResponse, context); } catch (Exception e) { LOG.error("error while dispatching middleware {}", middleware); e.printStackTrace(); exceptionRef.set(e); } } }); try { future.get(); } catch (InterruptedException | ExecutionException ex) { throw new IllegalStateException(ex); } send(responseTrigger, response, context); } } catch (Exception e) { LOG.error("error handling request", e); throw new HttpException("error handling request", e); } } private JujubeResponse handleException(Throwable ex) { JujubeResponse response; if (ex instanceof ExecutionException) { ex = ex.getCause(); } if (ex instanceof RequestEntityLimitExceeded) { response = new ResponseRequestTooLarge(); } else if (ex instanceof JujubeHttpException) { response = ((JujubeHttpException) ex).toHttpResponse(); } else { ex.printStackTrace(); response = new ResponseServerError(); } return response; } private void send(AsyncServerRequestHandler.ResponseTrigger responseTrigger, JujubeResponse response, HttpContext context) throws IOException, HttpException { LOG.debug("beginning to send response {}", response); AsyncEntityProducer entityProducer; if (response.getContent() instanceof Path) { entityProducer = AsyncEntityProducers.create(((Path) response.getContent()).toFile(), response.getContentType()); } else if (response.getContent() instanceof String) { entityProducer = AsyncEntityProducers.create((String) response.getContent(), response.getContentType()); } else if (response.getContent() == null) { entityProducer = null; } else { throw new IllegalStateException("Unsupported content type: " + response.getContent()); } var responseProducer = AsyncResponseBuilder.create(response.getCode()) .setEntity(entityProducer) .setVersion(response.getVersion()) .setHeaders(response.getHeaders()) .build(); responseTrigger.submitResponse(responseProducer, context); } }
Java
class Loops { // EXPECT WARNING ABOUT NAME public static void main(String[] args) { int i = 0; while (i<10) { System.out.println(i); i++; } } }
Java
public final class SocketOwnedByCurrentProcessFilter implements TcpSocketStatisticsHandler { static final int MAX_NOT_OWNED_INODE_CACHE_SIZE = 4096; private static final int INITIAL_SOCKET_INODE_CACHE_SIZE = 256; private final TcpSocketStatisticsHandler delegate; private final Consumer<LongHashSet> socketInodeRetriever; private final LongHashSet socketInodesOwnedByThisProcess = new LongHashSet(INITIAL_SOCKET_INODE_CACHE_SIZE); private final LongHashSet socketInodesNotOwnedByThisProcess = new LongHashSet(INITIAL_SOCKET_INODE_CACHE_SIZE); public SocketOwnedByCurrentProcessFilter(final TcpSocketStatisticsHandler delegate, final Consumer<LongHashSet> socketInodeRetriever) { this.delegate = delegate; this.socketInodeRetriever = socketInodeRetriever; } /** * {@inheritDoc} */ @Override public void onStatisticsUpdated(final InetAddress inetAddress, final int port, final long socketIdentifier, final long inode, final long receiveQueueDepth, final long transmitQueueDepth) { if(socketInodesNotOwnedByThisProcess.contains(inode)) { return; } if(!socketInodesOwnedByThisProcess.contains(inode)) { socketInodeRetriever.accept(socketInodesOwnedByThisProcess); if(!socketInodesOwnedByThisProcess.contains(inode)) { clearNotOwnedInodeCacheIfTooLarge(); socketInodesNotOwnedByThisProcess.add(inode); } } if(socketInodesOwnedByThisProcess.contains(inode)) { delegate.onStatisticsUpdated(inetAddress, port, socketIdentifier, inode, receiveQueueDepth, transmitQueueDepth); } } private void clearNotOwnedInodeCacheIfTooLarge() { if(socketInodesNotOwnedByThisProcess.size() >= MAX_NOT_OWNED_INODE_CACHE_SIZE) { socketInodesNotOwnedByThisProcess.clear(); } } }
Java
public class ImgurUtil { private ImgurUtil() { } public static String userProfileLinkFromId(@NonNull String userId) { return "https://imgur.com/user/" + userId; } public static String userProfileHtmlLinkFromId(@NonNull String userId) { return "<a href=\"" + userProfileLinkFromId(userId) + "\">" + userId + "</a>"; } public static String imageLinkFromId(@NonNull String imageId) { return "http://i.imgur.com/" + imageId + ".jpg"; } public static String smallerImageLinkFromId(@NonNull String imageId) { return "http://i.imgur.com/" + imageId + "l.jpg"; } }
Java
class permFinder implements Comparable<permFinder> { public char letter; public int index; public permFinder(char l, int i) { letter = l; index = i; } public int compareTo(permFinder other) { // Check for double letters if (this.letter != other.letter) return this.letter - other.letter; return this.index - other.index; } }
Java
public class RelationshipHandler { private SubjectAreaRelationshipClients subjectAreaRelationship; /** * Constructor for the RelationshipHandler * * @param subjectAreaRelationship The SubjectAreaDefinition Open Metadata Access Service (OMAS) API for terms. This is the same as the * The SubjectAreaDefinition Open Metadata View Service (OMVS) API for terms. */ public RelationshipHandler(SubjectAreaRelationshipClients subjectAreaRelationship) { this.subjectAreaRelationship = subjectAreaRelationship; } /** * Create a Term HasA Relationship. A relationship between a spine object and a spine attribute. * Note that this method does not error if the relationship ends are not spine objects or spine attributes. * <p> * @param userId userId under which the request is performed * @param termHasARelationship the HasA relationship * @return the created term HasA relationship * * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public HasA createTermHasARelationship(String userId, HasA termHasARelationship) throws InvalidParameterException, PropertyServerException, UserNotAuthorizedException { return subjectAreaRelationship.hasA().create(userId, termHasARelationship); } /** * Get a Term HasA Relationship. A relationship between a spine object and a spine attribute. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Hasa relationship to get * @return Hasa * * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public HasA getTermHasARelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.hasA().getByGUID(userId, guid); } /** * Update a Term HasA Relationship. A relationship between a spine object and a spine attribute. * <p> * * @param userId userId under which the request is performed * @param guid guid of the Hasa relationship * @param termHasARelationship the HasA relationship * @return the updated term HasA relationship * * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property Server Exception */ public HasA updateTermHasARelationship(String userId, String guid, HasA termHasARelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.hasA().update(userId, guid, termHasARelationship); } /** * Replace a Term HasA Relationship. * <p> * * @param userId userId under which the request is performed * @param guid guid of the Hasa relationship * @param termHasARelationship the HasA relationship * @return the replaced term HasA relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public HasA replaceTermHasARelationship(String userId, String guid, HasA termHasARelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.hasA().replace(userId, guid, termHasARelationship); } /** * Delete a Term HasA Relationship. A relationship between a spine object and a spine attribute. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Hasa relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteTermHasARelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.hasA().delete(userId, guid); } /** * Purge a Term HasA Relationship. A relationship between a spine object and a spine attribute. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Hasa relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeTermHasARelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.hasA().purge(userId, guid); } /** * Restore a Term HasA Relationship. A relationship between a spine object and a spine attribute. * <p> * Restore allows the deleted has a relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the has a relationship to delete * @return the restored has a relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public HasA restoreTermHasARelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.hasA().restore(userId, guid); } /** * Create a RelatedTerm. A Related Term is a link between two similar Terms. * * <p> * * @param userId unique identifier for requesting user, under which the request is performed * @param relatedTermRelationship the RelatedTerm relationship * * @return the created RelatedTerm relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property Server Exception */ public RelatedTerm createRelatedTerm(String userId, RelatedTerm relatedTermRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.relatedTerm().create(userId, relatedTermRelationship); } /** * Get a RelatedTerm. A Related Term is a link between two similar Terms. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the RelatedTerm relationship to get * @return RelatedTerm * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public RelatedTerm getRelatedTerm(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.relatedTerm().getByGUID(userId, guid); } /** * Update a RelatedTerm Relationship. * <p> * * @param userId userId under which the request is performed * @param termRelatedTerm the RelatedTerm relationship * @param guid guid of the RelatedTerm relationship * @return the updated term RelatedTerm relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public RelatedTerm updateRelatedTerm(String userId, String guid, RelatedTerm termRelatedTerm) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.relatedTerm().update(userId, guid, termRelatedTerm); } /** * Replace an ReplacementTerm relationship, which is link to a glossary term that is replacing an obsolete glossary term. * <p> * * @param userId userId under which the request is performed * @param guid guid of the RelatedTerm relationship * @param termRelatedTerm the replacement related term relationship * @return ReplacementTerm replaced related Term relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public RelatedTerm replaceRelatedTerm(String userId, String guid, RelatedTerm termRelatedTerm) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.relatedTerm().replace(userId, guid, termRelatedTerm); } /** * Restore a Related Term relationship * <p> * Restore allows the deleted Synonym relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the related term relationship to restore * @return the restored related term relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public RelatedTerm restoreRelatedTerm(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.relatedTerm().restore(userId, guid); } /** * Delete a RelatedTerm. A Related Term is a link between two similar Terms. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the RelatedTerm relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteRelatedTerm(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.relatedTerm().delete(userId, guid); } /** * Purge a RelatedTerm. A Related Term is a link between two similar Terms. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the RelatedTerm relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeRelatedTerm(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.relatedTerm().purge(userId, guid); } /** * Restore a related term relationship * <p> * Restore allows the deleted related term relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the related term relationship to delete * @return the restored related term relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public RelatedTerm restoreRelatedTermRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.relatedTerm().restore(userId, guid); } /** * Create a synonym relationship. A link between glossary terms that have the same meaning. * <p> * * @param userId userId under which the request is performed * @param synonym the Synonym relationship * @return the created Synonym relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Synonym createSynonymRelationship(String userId, Synonym synonym) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.synonym().create(userId, synonym); } /** * Get a synonym relationship. A link between glossary terms that have the same meaning. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Synonym relationship to get * @return Synonym * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public Synonym getSynonymRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.synonym().getByGUID(userId, guid); } /** * Update a Synonym relationship which is a link between glossary terms that have the same meaning * <p> * * @param userId userId under which the request is performed * @param synonym the Synonym relationship * @param guid guid of the Synonym relationship * @return updated Synonym relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Synonym updateSynonymRelationship(String userId, String guid, Synonym synonym) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.synonym().update(userId, guid, synonym); } /** * Replace a Synonym relationship, which is a link between glossary terms that have the same meaning * <p> * * @param userId userId under which the request is performed * @param guid guid of the Synonym relationship * @param synonym the Synonym relationship * @return replaced synonym relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Synonym replaceSynonymRelationship(String userId, String guid, Synonym synonym) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.synonym().replace(userId, guid, synonym); } /** * Delete a synonym relationship. A link between glossary terms that have the same meaning. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the synonym relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteSynonymRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.synonym().delete(userId, guid); } /** * Purge a synonym relationship. A link between glossary terms that have the same meaning. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Synonym relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeSynonymRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.synonym().purge(userId, guid); } /** * Restore a Synonym relationship * <p> * Restore allows the deleted Synonym relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Synonym relationship to delete * @return the restored Synonym relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Synonym restoreSynonymRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.synonym().restore(userId, guid); } /** * Create a antonym relationship. A link between glossary terms that have the opposite meaning. * * <p> * * @param userId userId under which the request is performed * @param antonym the Antonym relationship * @return the created antonym relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Antonym createAntonymRelationship(String userId, Antonym antonym) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.antonym().create(userId, antonym); } /** * Get a antonym relationship. A link between glossary terms that have the opposite meaning. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Anonym relationship to get * @return Antonym relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public Antonym getAntonymRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.antonym().getByGUID(userId, guid); } /** * Update a Antonym relationship which is a link between glossary terms that have the opposite meaning * <p> * * @param userId userId under which the request is performed * @param guid guid of the Anonym relationship * @param antonym the Antonym relationship * @return Antonym updated antonym * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Antonym updateAntonymRelationship(String userId, String guid, Antonym antonym) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.antonym().update(userId, guid, antonym); } /** * Replace an Antonym relationship which is a link between glossary terms that have the opposite meaning * <p> * * @param userId userId under which the request is performed * @param guid guid of the Anonym relationship * @param antonym the antonym relationship * @return Antonym replaced antonym * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Antonym replaceAntonymRelationship(String userId, String guid, Antonym antonym) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.antonym().replace(userId, guid, antonym); } /** * Delete a antonym relationship. A link between glossary terms that have the opposite meaning. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Antonym relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteAntonymRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.antonym().delete(userId, guid); } /** * Purge a antonym relationship. A link between glossary terms that have the opposite meaning. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Antonym relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeAntonymRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.antonym().purge(userId, guid); } /** * Restore a Antonym relationship * <p> * Restore allows the deleted Antonym relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Antonym relationship to delete * @return the restored Antonym relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Antonym restoreAntonymRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.antonym().restore(userId, guid); } /** * Create a Translation relationship, which is link between glossary terms that provide different natural language translation of the same concept. * * <p> * * @param userId userId under which the request is performed * @param translation the Translation relationship * @return the created translation relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Translation createTranslationRelationship(String userId, Translation translation) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.translation().create(userId, translation); } /** * Get a translation relationship, which is link between glossary terms that provide different natural language translation of the same concept. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Translation relationship to get * @return Translation * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public Translation getTranslationRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.translation().getByGUID(userId, guid); } /** * Update a Translation relationship, which is link between glossary terms that provide different natural language translation of the same concept. * <p> * * @param userId userId under which the request is performed * @param guid guid of the Translation relationship * @param translation the Translation relationship * @return Translation updated translation * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Translation updateTranslationRelationship(String userId, String guid, Translation translation) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.translation().update(userId, guid, translation); } /** * Replace an Translation relationship, which is link between glossary terms that provide different natural language translation of the same concept. * <p> * * @param userId userId under which the request is performed * @param guid guid of the Translation relationship * @param translation the translation relationship * @return Translation replaced translation * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Translation replaceTranslationRelationship(String userId, String guid, Translation translation) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.translation().replace(userId, guid, translation); } /** * Delete a translation relationship, which is link between glossary terms that provide different natural language translation of the same concept. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Translation relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteTranslationRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.translation().delete(userId, guid); } /** * Purge a translation relationship, which is link between glossary terms that provide different natural language translation of the same concept. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Translation relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeTranslationRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.translation().purge(userId, guid); } /** * Restore a Translation relationship * <p> * Restore allows the deleted Translation relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Translation relationship to delete * @return the restored Translation relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Translation restoreTranslationRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.translation().restore(userId, guid); } /** * Create a UsedInContext relationship, which is link between glossary terms where on describes the context where the other one is valid to use. * * <p> * * @param userId userId under which the request is performed * @param usedInContext the UsedInContext relationship * @return the created usedInContext relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public UsedInContext createUsedInContextRelationship(String userId, UsedInContext usedInContext) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.usedInContext().create(userId, usedInContext); } /** * Get a usedInContext relationship, which is link between glossary terms where on describes the context where the other one is valid to use. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the UsedInContext relationship to get * @return UsedInContext * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public UsedInContext getUsedInContextRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.usedInContext().getByGUID(userId, guid); } /** * Update a UsedInContext relationship, which is link between glossary terms where on describes the context where the other one is valid to use. * <p> * * @param userId userId under which the request is performed * @param guid guid of the UsedInContext relationship * @param usedInContext the UsedInContext relationship * @return UsedInContext updated usedInContext * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public UsedInContext updateUsedInContextRelationship(String userId, String guid, UsedInContext usedInContext) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.usedInContext().update(userId, guid, usedInContext); } /** * Replace an UsedInContext relationship, which is link between glossary terms where on describes the context where the other one is valid to use. * <p> * * @param userId userId under which the request is performed * @param guid guid of the UsedInContext relationship * @param usedInContext the usedInContext relationship * @return UsedInContext replaced usedInContext * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public UsedInContext replaceUsedInContextRelationship(String userId, String guid, UsedInContext usedInContext) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.usedInContext().replace(userId, guid, usedInContext); } /** * Delete a usedInContext relationship, which is link between glossary terms where on describes the context where the other one is valid to use. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the UsedInContext relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteUsedInContextRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.usedInContext().delete(userId, guid); } /** * Purge a usedInContext relationship, which is link between glossary terms where on describes the context where the other one is valid to use. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the UsedInContext relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeUsedInContextRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.usedInContext().purge(userId, guid); } /** * Restore a Used in context relationship * <p> * Restore allows the deletedUsed in context relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Used in context relationship to delete * @return the restored Used in context relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public UsedInContext restoreUsedInContextRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.usedInContext().restore(userId, guid); } /** * Create a PreferredTerm relationship, which is link to an alternative term that the organization prefer is used. * * <p> * * @param userId userId under which the request is performed * @param preferredTerm the PreferredTerm relationship * @return the created preferredTerm relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public PreferredTerm createPreferredTermRelationship(String userId, PreferredTerm preferredTerm) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.preferredTerm().create(userId, preferredTerm); } /** * Get a preferredTerm relationship, which is link to an alternative term that the organization prefer is used. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the PreferredTerm relationship to get * @return PreferredTerm * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public PreferredTerm getPreferredTermRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.preferredTerm().getByGUID(userId, guid); } /** * Update a PreferredTerm relationship, which is link to an alternative term that the organization prefer is used. * <p> * * @param userId userId under which the request is performed * @param guid guid of the PreferredTerm relationship * @param preferredTerm the PreferredTerm relationship * @return PreferredTerm updated preferredTerm * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public PreferredTerm updatePreferredTermRelationship(String userId, String guid, PreferredTerm preferredTerm) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.preferredTerm().update(userId, guid, preferredTerm); } /** * Replace an PreferredTerm relationship, which is link to an alternative term that the organization prefer is used. * <p> * * @param userId userId under which the request is performed * @param guid guid of the PreferredTerm relationship * @param preferredTerm the preferredTerm relationship * @return PreferredTerm replaced preferredTerm * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public PreferredTerm replacePreferredTermRelationship(String userId, String guid, PreferredTerm preferredTerm) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.preferredTerm().replace(userId, guid, preferredTerm); } /** * Delete a preferredTerm relationship, which is link to an alternative term that the organization prefer is used. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the PreferredTerm relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deletePreferredTermRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.preferredTerm().delete(userId, guid); } /** * Purge a preferredTerm relationship, which is link to an alternative term that the organization prefer is used. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the PreferredTerm relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgePreferredTermRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.preferredTerm().purge(userId, guid); } /** * Restore a preferred term relationship * <p> * Restore allows the deletedpreferred term relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the preferred term relationship to delete * @return the restored preferred term relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public PreferredTerm restorePreferredTermRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.preferredTerm().restore(userId, guid); } /** * Create a ValidValue relationship, which is link between glossary terms where one defines one of the data values for the another. * * <p> * * @param userId userId under which the request is performed * @param validValue the ValidValue relationship * @return the created validValue relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ValidValue createValidValueRelationship(String userId, ValidValue validValue) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.validValue().create(userId, validValue); } /** * Get a validValue relationship, which is link between glossary terms where one defines one of the data values for the another. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ValidValue relationship to get * @return ValidValue * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public ValidValue getValidValueRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.validValue().getByGUID(userId, guid); } /** * Update a ValidValue relationship, which is link between glossary terms where one defines one of the data values for the another. * <p> * * @param userId userId under which the request is performed * @param guid guid of the ValidValue relationship * @param validValue the ValidValue relationship * @return ValidValue updated validValue * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ValidValue updateValidValueRelationship(String userId, String guid, ValidValue validValue) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.validValue().update(userId, guid, validValue); } /** * Replace an ValidValue relationship, which is link between glossary terms where one defines one of the data values for the another. * <p> * * @param userId userId under which the request is performed * @param guid guid of the ValidValue relationship * @param validValue the validValue relationship * @return ValidValue replaced validValue * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ValidValue replaceValidValueRelationship(String userId, String guid, ValidValue validValue) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.validValue().replace(userId, guid, validValue); } /** * Delete a validValue relationship, which is link between glossary terms where one defines one of the data values for the another. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ValidValue relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteValidValueRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.validValue().delete(userId, guid); } /** * Purge a validValue relationship, which is link between glossary terms where one defines one of the data values for the another. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ValidValue relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeValidValueRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.validValue().purge(userId, guid); } /** * Restore a valid value relationship * <p> * Restore allows the deletedvalid value relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the valid value relationship to delete * @return the restored valid value relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ValidValue restoreValidValueRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.validValue().restore(userId, guid); } /** * Create a ReplacementTerm relationship, which is link to a glossary term that is replacing an obsolete glossary term. * * <p> * * @param userId userId under which the request is performed * @param replacementTerm the ReplacementTerm relationship * @return the created replacementTerm relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ReplacementTerm createReplacementTermRelationship(String userId, ReplacementTerm replacementTerm) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.replacementTerm().create(userId, replacementTerm); } /** * Get a replacementTerm relationship, which is link to a glossary term that is replacing an obsolete glossary term. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ReplacementTerm relationship to get * @return ReplacementTerm * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public ReplacementTerm getReplacementTermRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.replacementTerm().getByGUID(userId, guid); } /** * Update a ReplacementTerm relationship, which is link to a glossary term that is replacing an obsolete glossary term. * <p> * * @param userId userId under which the request is performed * @param guid guid of the ReplacementTerm relationship * @param replacementTerm the ReplacementTerm relationship * @return ReplacementTerm updated replacementTerm * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ReplacementTerm updateReplacementTermRelationship(String userId, String guid, ReplacementTerm replacementTerm) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.replacementTerm().update(userId, guid, replacementTerm); } /** * Replace an ReplacementTerm relationship, which is link to a glossary term that is replacing an obsolete glossary term. * <p> * * @param userId userId under which the request is performed * @param guid guid of the ReplacementTerm relationship * @param replacementTerm the replacementTerm relationship * @return ReplacementTerm replaced replacementTerm * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ReplacementTerm replaceReplacementTermRelationship(String userId, String guid, ReplacementTerm replacementTerm) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.replacementTerm().replace(userId, guid, replacementTerm); } /** * Delete a replacementTerm relationship, which is link to a glossary term that is replacing an obsolete glossary term. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ReplacementTerm relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteReplacementTermRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.replacementTerm().delete(userId, guid); } /** * Purge a replacementTerm relationship, which is link to a glossary term that is replacing an obsolete glossary term. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ReplacementTerm relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeReplacementTermRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.replacementTerm().purge(userId, guid); } /** * Restore a replacement term relationship * <p> * Restore allows the deleted replacement term relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the replacement term relationship to delete * @return the restored replacement term relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ReplacementTerm restoreReplacementTermRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.replacementTerm().restore(userId, guid); } /** * Create a TypedBy relationship, which is defines the relationship between a spine attribute and its type. * * <p> * * @param userId userId under which the request is performed * @param termTYPEDBYRelationship the TypedBy relationship * @return the created termTYPEDBYRelationship relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public TypedBy createTermTYPEDBYRelationship(String userId, TypedBy termTYPEDBYRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.typedBy().create(userId, termTYPEDBYRelationship); } /** * Get a termTYPEDBYRelationship relationship, which is defines the relationship between a spine attribute and its type. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the termTYPEDBYRelationship relationship to get * @return TypedBy * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public TypedBy getTermTYPEDBYRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.typedBy().getByGUID(userId, guid); } /** * Update a TypedBy relationship, which is defines the relationship between a spine attribute and its type. * <p> * * @param userId userId under which the request is performed * @param guid guid of the TypedBy relationship * @param termTYPEDBYRelationship the TypedBy relationship * @return TypedBy updated termTYPEDBYRelationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public TypedBy updateTermTYPEDBYRelationship(String userId, String guid, TypedBy termTYPEDBYRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.typedBy().update(userId, guid, termTYPEDBYRelationship); } /** * Replace an TypedBy relationship, which is defines the relationship between a spine attribute and its type. * <p> * * @param userId userId under which the request is performed * @param guid guid of the TypedBy relationship * @param termTYPEDBYRelationship the termTYPEDBYRelationship relationship * @return TypedBy replaced termTYPEDBYRelationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public TypedBy replaceTermTYPEDBYRelationship(String userId, String guid, TypedBy termTYPEDBYRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.typedBy().replace(userId, guid, termTYPEDBYRelationship); } /** * Delete a termTYPEDBYRelationship relationship, which is defines the relationship between a spine attribute and its type. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the termTYPEDBYRelationship relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteTermTYPEDBYRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.typedBy().delete(userId, guid); } /** * Purge a termTYPEDBYRelationship relationship, which is defines the relationship between a spine attribute and its type. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the TypedBy relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeTermTYPEDBYRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.typedBy().purge(userId, guid); } /** * Restore a typed by relationship * <p> * Restore allows the deleted typed by relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the typed by relationship to delete * @return the restored typed by relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public TypedBy restoreTypedByRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.typedBy().restore(userId, guid); } /** * Create a Isa relationship, which is link between a more general glossary term and a more specific definition. * * <p> * * @param userId userId under which the request is performed * @param isa the Isa relationship * @return the created isa relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public IsA createIsaRelationship(String userId, IsA isa) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isA().create(userId, isa); } /** * Get a isa relationship, which is link between a more general glossary term and a more specific definition. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the isa relationship to get * @return Isa * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public IsA getIsaRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isA().getByGUID(userId, guid); } /** * Update a Isa relationship, which is link between a more general glossary term and a more specific definition. * <p> * * @param userId userId under which the request is performed * @param guid guid of the isa relationship * @param isa the Isa relationship * @return Isa updated isa * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public IsA updateIsaRelationship(String userId, String guid, IsA isa) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isA().update(userId, guid, isa); } /** * Replace an Isa relationship, which is link between a more general glossary term and a more specific definition. * <p> * * @param userId userId under which the request is performed * @param guid guid of the isa relationship * @param isa the isa relationship * @return Isa replaced isa * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public IsA replaceIsaRelationship(String userId, String guid, IsA isa) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isA().replace(userId, guid, isa); } /** * Delete a isa relationship, which is link between a more general glossary term and a more specific definition. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the isa relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteIsaRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.isA().delete(userId, guid); } /** * Purge a isa relationship, which is link between a more general glossary term and a more specific definition. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Isa relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeIsaRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.isA().purge(userId, guid); } /** * Restore an is a relationship * <p> * Restore allows the deleted is a relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the is a relationship to delete * @return the restored is a relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public IsA restoreIsaRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isA().restore(userId, guid); } /** * Create a IsaTypeOf relationship, which is defines an inheritance relationship between two spine objects. * * <p> * * @param userId userId under which the request is performed * @param isATypeOf the IsaTypeOf relationship * @return the created IsaTypeOf relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public IsATypeOf createTermIsATypeOfRelationship(String userId, IsATypeOf isATypeOf) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isaTypeOf().create(userId, isATypeOf); } /** * Get a IsaTypeOf relationship, which is defines an inheritance relationship between two spine objects. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the IsaTypeOf relationship to get * @return IsaTypeOf * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public IsATypeOf getTermIsATypeOfRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isaTypeOf().getByGUID(userId, guid); } /** * Update a IsaTypeOf relationship, which is defines an inheritance relationship between two spine objects. * <p> * * @param userId userId under which the request is performed * @param guid guid of the IsaTypeOf relationship * @param isATypeOf the IsaTypeOf relationship * @return IsaTypeOf updated IsaTypeOf * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public IsATypeOf updateTermIsATypeOfRelationship(String userId, String guid, IsATypeOf isATypeOf) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isaTypeOf().update(userId, guid, isATypeOf); } /** * Replace an IsaTypeOf relationship, which is defines an inheritance relationship between two spine objects. * <p> * * @param userId userId under which the request is performed * @param guid guid of the IsaTypeOf relationship * @param isATypeOf the IsaTypeOf relationship * @return IsaTypeOf replaced IsaTypeOf * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public IsATypeOf replaceTermIsATypeOfRelationship(String userId, String guid, IsATypeOf isATypeOf) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isaTypeOf().replace(userId, guid, isATypeOf); } /** * Delete a IsaTypeOf relationship, which is defines an inheritance relationship between two spine objects. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the IsaTypeOf relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteTermIsATypeOfRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.isaTypeOf().delete(userId, guid); } /** * Purge a IsaTypeOf relationship, which is defines an inheritance relationship between two spine objects. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the IsaTypeOf relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeTermIsATypeOfRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.isaTypeOf().purge(userId, guid); } /** * Restore an is a type of relationship * <p> * Restore allows the deleted is a type of relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the is a type of relationship to delete * @return the restored is a type of relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public IsATypeOf restoreIsaTypeOfRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.isaTypeOf().restore(userId, guid); } /** * Create a Term Categorization Relationship. A relationship between a Category and a Term. This relationship allows terms to be categorized. * Note that this method does not error if the relationship ends are not spine objects or spine attributes. * <p> * * @param userId userId under which the request is performed * @param termCategorizationRelationship the term categorization relationship * @return the created term categorization relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Categorization createTermCategorizationRelationship(String userId, Categorization termCategorizationRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termCategorization().create(userId, termCategorizationRelationship); } /** * Get a Term Categorization Relationship. A relationship between a Category and a Term. This relationship allows terms to be categorized. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the TermCategorizationRelationship relationship to get * @return TermCategorizationRelationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public Categorization getTermCategorizationRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termCategorization().getByGUID(userId, guid); } /** * Update a Term Categorization Relationship. A relationship between a Category and a Term. This relationship allows terms to be categorized. * <p> * @param userId userId under which the request is performed * @param guid guid of the TermCategorizationRelationship * @param termCategorizationRelationship the term categorization relationship * @return the updated term categorization relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Categorization updateTermCategorizationRelationship(String userId, String guid, Categorization termCategorizationRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termCategorization().update(userId, guid, termCategorizationRelationship); } /** * Replace a Term HasA Relationship. * <p> * * @param userId userId under which the request is performed * @param guid guid of the TermCategorizationRelationship * @param termCategorizationRelationship the term categorization relationship * @return the replaced term categorization relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Categorization replaceTermCategorizationRelationship(String userId, String guid, Categorization termCategorizationRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termCategorization().replace(userId, guid, termCategorizationRelationship); } /** * Delete a Term Categorization Relationship. A relationship between a Category and a Term. This relationship allows terms to be categorized. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the TermCategorizationRelationship relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteTermCategorizationRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.termCategorization().delete(userId, guid); } /** * Purge a Term Categorization Relationship. A relationship between a Category and a Term. This relationship allows terms to be categorized. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the TermCategorizationRelationship relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeTermCategorizationRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.termCategorization().purge(userId, guid); } /** * Restore a Term Categorization Relationship. A relationship between a Category and a Term. This relationship allows terms to be categorized. * <p> * Restore allows the deleted Term Categorization relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Term Categorization relationship to delete * @return the restored has a relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public Categorization restoreTermCategorizationRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termCategorization().restore(userId, guid); } /** * Create a Term Anchor Relationship. A relationship between a Glossary and a Term. This relationship allows terms to be owned by a glossary. * This method does not error if the relationship ends are not spine objects or spine attributes. * Terms created using the Glossary author OMVS cannot be created without a glossary and there can only be one glossary associated with a * Term. This method is to allow glossaries to be associated with Terms that have not been created via the Glossary Author OMVS or Subject Area OMAS or to recreate * the TermAnchor relationship if it has been purged. * <p> * * @param userId userId under which the request is performed * @param termAnchorRelationship the TermAnchor relationship * @return the created TermAnchor relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public TermAnchor createTermAnchorRelationship(String userId, TermAnchor termAnchorRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termAnchor().create(userId, termAnchorRelationship); } /** * Get a Term Anchor Relationship. A relationship between a Glossary and a Term. This relationship allows terms to be owned by a glossary. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the TermAnchorRelationship relationship to get * @return TermAnchorRelationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public TermAnchor getTermAnchorRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termAnchor().getByGUID(userId, guid); } /** * Update a Term Anchor Relationship. * <p> * * @param userId userId under which the request is performed * @param guid guid of the TermAnchorRelationship relationship * @param termAnchorRelationship the TermAnchor relationship * @return the updated TermAnchor relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public TermAnchor updateTermAnchorRelationship(String userId, String guid, TermAnchor termAnchorRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termAnchor().replace(userId, guid, termAnchorRelationship); } /** * Replace a Term Anchor Relationship. * <p> * * @param userId userId under which the request is performed * @param guid guid of the TermAnchorRelationship relationship * @param termAnchorRelationship the TermAnchor relationship * @return the updated TermAnchor relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public TermAnchor replaceTermAnchorRelationship(String userId, String guid, TermAnchor termAnchorRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termAnchor().replace(userId, guid, termAnchorRelationship); } /** * Delete a Term Anchor Relationship. A relationship between a Glossary and a Term. This relationship allows terms to be owned by a glossary. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the TermAnchorRelationship relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteTermAnchorRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.termAnchor().delete(userId, guid); } /** * Purge a Term Anchor Relationship. A relationship between a Glossary and a Term. This relationship allows terms to be owned by a glossary. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the TermAnchorRelationship relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeTermAnchorRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.termAnchor().purge(userId, guid); } /** * Restore a Term Anchor Relationship. A relationship between a Glossary and a Term. This relationship allows terms to be owned by a glossary. * <p> * Restore allows the deleted Term Categorization relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Term Anchor relationship to delete * @return the restored Term Anchor relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public TermAnchor restoreTermAnchorRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.termAnchor().restore(userId, guid); } /** * Create a Category Anchor Relationship. A relationship between a Glossary and a Category. This relationship allows categoriess to be owned by a glossary. * Categories created using the Subject Area OMAS cannot be created without a glossary and there can only be one glossary associated with a * Category. This method is to allow glossaries to be associated with Categories that have not been created via the Subject Area OMAS or to recreate * the CategoryAnchor relationship if it has been purged. * * @param userId userId under which the request is performed * @param categoryAnchorRelationship the category anchor relationship * @return the created term categorization relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public CategoryAnchor createCategoryAnchorRelationship(String userId, CategoryAnchor categoryAnchorRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.categoryAnchor().create(userId, categoryAnchorRelationship); } /** * Get a Category Anchor Relationship. A relationship between a Glossary and a Category. This relationship allows categoriess to be owned by a glossary. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the CategoryAnchorRelationship relationship to get * @return CategoryAnchorRelationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public CategoryAnchor getCategoryAnchorRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.categoryAnchor().getByGUID(userId, guid); } /** * Update a Category Anchor Relationship. * <p> * * @param userId userId under which the request is performed * @param guid guid of the CategoryAnchorRelationship * @param categoryAnchorRelationship the category anchor relationship * @return the updated category anchor relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public CategoryAnchor updateCategoryAnchorRelationship(String userId, String guid, CategoryAnchor categoryAnchorRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.categoryAnchor().update(userId, guid, categoryAnchorRelationship); } /** * Replace a Category Anchor Relationship. * <p> * * @param userId userId under which the request is performed * @param guid guid of the CategoryAnchorRelationship * @param categoryAnchorRelationship the category anchor relationship * @return the replaced category anchor relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public CategoryAnchor replaceCategoryAnchorRelationship(String userId, String guid, CategoryAnchor categoryAnchorRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.categoryAnchor().replace(userId, guid, categoryAnchorRelationship); } /** * Delete a Category Anchor Relationship. A relationship between a Glossary and a Category. This relationship allows categoriess to be owned by a glossary. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the CategoryAnchorRelationship relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteCategoryAnchorRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.categoryAnchor().delete(userId, guid); } /** * Purge a Category Anchor Relationship. A relationship between a Glossary and a Category. This relationship allows categoriess to be owned by a glossary. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the CategoryAnchorRelationship relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeCategoryAnchorRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.categoryAnchor().purge(userId, guid); } /** * Restore a Category Anchor Relationship. A relationship between a Glossary and a Category. This relationship allows categoriess to be owned by a glossary. * <p> * Restore allows the deleted Category Anchor relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the Category Anchor relationship to delete * @return the restored category anchor relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public CategoryAnchor restoreCategoryAnchorRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.categoryAnchor().restore(userId, guid); } /** * Create a ProjectScope relationship. A link between the project content and the project. * <p> * * @param userId userId under which the request is performed * @param projectScope the ProjectScope relationship * @return the created ProjectScope relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ProjectScope createProjectScopeRelationship(String userId, ProjectScope projectScope) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.projectScope().create(userId, projectScope); } /** * Get a ProjectScope relationship. A link between the project content and the project. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ProjectScope relationship to get * @return ProjectScope * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public ProjectScope getProjectScopeRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.projectScope().getByGUID(userId, guid); } /** * Update a ProjectScope relationship which is a link between the project content and the project. * <p> * * @param userId userId under which the request is performed * @param guid guid of the ProjectScope relationship * @param projectScopeRelationship the ProjectScope relationship * @return updated ProjectScope relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ProjectScope updateProjectScopeRelationship(String userId, String guid, ProjectScope projectScopeRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.projectScope().update(userId, guid, projectScopeRelationship); } /** * Replace a ProjectScope relationship which is a link between the project content and the project. * <p> * * @param userId userId under which the request is performed * @param guid guid of the ProjectScope relationship * @param projectScopeRelationship the ProjectScope relationship * @return replaced ProjectScope relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ProjectScope replaceProjectScopeRelationship(String userId, String guid, ProjectScope projectScopeRelationship) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.projectScope().replace(userId, guid, projectScopeRelationship); } /** * Delete a ProjectScope relationship. A link between the project content and the project. * A delete (also known as a soft delete) means that the relationship instance will exist in a deleted state in the repository after the delete operation. This means * that it is possible to undo the delete. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ProjectScope relationship to delete * <p> * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void deleteProjectScopeRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.projectScope().delete(userId, guid); } /** * Purge a ProjectScope relationship. A link between the project content and the project. * A purge means that the relationship will not exist after the operation. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ProjectScope relationship to delete * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid. * @throws PropertyServerException Property server exception */ public void purgeProjectScopeRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { subjectAreaRelationship.projectScope().purge(userId, guid); } /** * Restore a ProjectScope relationship which is a link between the project content and the project. * <p> * Restore allows the deleted ProjectScope relationship to be made active again. Restore allows deletes to be undone. Hard deletes are not stored in the repository so cannot be restored. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the ProjectScope relationship to restore * @return the restored ProjectScope relationship * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public ProjectScope restoreProjectScopeRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.projectScope().restore(userId, guid); } /** * Get a SemanticAssignment relationship, Links a glossary term to another element such as an asset or schema element to define its meaning. * * @param userId unique identifier for requesting user, under which the request is performed * @param guid guid of the SemanticAssignment relationship to get * @return the SemanticAssignment relationship with the requested guid * @throws UserNotAuthorizedException the requesting user is not authorized to issue this request. * @throws InvalidParameterException one of the parameters is null or invalid * @throws PropertyServerException Property server exception */ public SemanticAssignment getSemanticAssignmentRelationship(String userId, String guid) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { return subjectAreaRelationship.semanticAssignment().getByGUID(userId, guid); } }
Java
public class BuyCoinsActivity extends AppCompatActivity { @Bind(R.id.list) RecyclerView list; @Bind(R.id.btnBack) LinearLayout btnBack; /** * adapter */ private BuyCoinsAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_buy_coins_activity); initUi(); initAction(); //init app billing AppBillingManager.getInstance().initBillingBuyActivity(getApplicationContext(), this,adapter); } private void initAction(){ LogicInterfaceManager.getInstance().backAction(this, btnBack); } private void initUi(){ ButterKnife.bind(this); //set effect onclick and action LogicInterfaceManager.getInstance().setOnClickEffect(this, btnBack); //init ui list settings LinearLayoutManager mLayoutManager = new LinearLayoutManager(this); list.setLayoutManager(mLayoutManager); adapter = new BuyCoinsAdapter(BuyCoinsActivity.this); list.setAdapter(adapter); } @Override protected void onDestroy() { super.onDestroy(); AppBillingManager.getInstance().onDestroy(this); } }
Java
@WebServlet("/results") public class PollHandler extends HttpServlet { private static final long serialVersionUID = 1L; private static ConcurrentHashMap<Integer, String> outQueue; public PollHandler() { super(); } public void init(ServletConfig config) throws ServletException { outQueue = JobWorkerHandler.getOutQueue(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) * Get method receives Job number from SearchHandler after user enters input. */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String word = request.getParameter("word"); int jobNumber = Integer.parseInt(request.getParameter("jobNumber")); if(outQueue.containsKey(jobNumber)) { // Getting result value as well removing it from shared Hashmap, not just from Servlet copy String result = JobWorkerHandler.getResult(jobNumber); //Display results out.printf("<p align=\"center\"><b>%s</b>: <div style=\"white-space: pre-wrap;\">%s</div></p>",word, result); out.println(); //Home button out.printf("<p align=\"center\"><button onclick=\"window.location.href=' /Dictionary/'\">Home</button></p>"); } else { response.setIntHeader("Refresh", 10); out.printf("<p align=\"center\">Processing <b>%s</b>, please wait...</p>",word); out.println(); out.printf("<p align=\"center\">Job Number: <b>%d</b></p>",jobNumber); } } }
Java
public class SingletonApplicationContext { private static final Logger LOG = LoggerFactory.getLogger(SingletonApplicationContext.class); private static volatile SingletonApplicationContext singleton; private SingletonApplicationContext() { loadApplicationContext(); } public static final String SPRING_CONFIG = "hedwig.spring.config"; public static final String DEFAULT_SPRING_CONFIG = "classpath*:META-INF/spring/*.xml"; private ClassPathXmlApplicationContext applicationContext; public ClassPathXmlApplicationContext getApplicationContext() { return applicationContext; } private void loadApplicationContext() { String configPath = HedwigConfig.getInstance().getString(SPRING_CONFIG, ""); if (Strings.isNullOrEmpty(configPath)) { configPath = DEFAULT_SPRING_CONFIG; } LOG.info("Load spring configuration file from {}", configPath); applicationContext = new ClassPathXmlApplicationContext(configPath.split("[,\\s]+")); } public static SingletonApplicationContext getSingleton() { if (null == singleton) { synchronized (SingletonApplicationContext.class) { if (null == singleton) { singleton = new SingletonApplicationContext(); } } } return singleton; } }
Java
public final class UtilNetwork { public static final boolean EPOLL_AVAILABLE = Epoll.isAvailable() && System.getProperty("system.os").startsWith("Windows"); private UtilNetwork() {} /** * Creates the "best" event loop group available. * * <p>Epoll and KQueue are favoured and will be returned if available, followed by NIO. * * @return the "best" event loop group available */ public static EventLoopGroup createBestEventLoopGroup() { if (EPOLL_AVAILABLE) { return new EpollEventLoopGroup(); } return new NioEventLoopGroup(); } /** * Gets the "best" server socket channel available. * * <p>Epoll and KQueue are favoured and will be returned if available, followed by NIO. * * @return the "best" server socket channel available */ public static Class<? extends ServerSocketChannel> bestServerSocketChannel() { if (EPOLL_AVAILABLE) { return EpollServerSocketChannel.class; } return NioServerSocketChannel.class; } /** * Gets the "best" socket channel available. * * <p>Epoll and KQueue are favoured and will be returned if available, followed by NIO. * * @return the "best" socket channel available */ public static Class<? extends SocketChannel> bestSocketChannel() { if (EPOLL_AVAILABLE) { return EpollSocketChannel.class; } return NioSocketChannel.class; } /** * Gets the "best" datagram channel available. * * <p>Epoll and KQueue are favoured and will be returned if available, followed by NIO. * * @return the "best" datagram channel available */ public static Class<? extends DatagramChannel> bestDatagramChannel() { if (EPOLL_AVAILABLE) { return EpollDatagramChannel.class; } return NioDatagramChannel.class; } }
Java
public class FXMLFrontController implements Initializable { // Map size (x,y) @FXML private TextField txtMapSizeX; @FXML private TextField txtMapSizeY; // Predators @FXML private TextField txtPredInitNumber; @FXML private TextField txtPredDeathRate; // Preys @FXML private TextField txtPreyInitNumber; @FXML private TextField txtPreyDeathRate; // Steps @FXML private TextField txtPredNumber; @FXML private TextField txtPreyNumber; @FXML private TextField txtLabel; @FXML private TextField txtStepNumber; @FXML private Button btProcess; @FXML private TableColumn<StatusIter, SimpleIntegerProperty> colStep; @FXML private TableColumn<StatusIter, SimpleIntegerProperty> colPreys; @FXML private TableColumn<StatusIter, SimpleIntegerProperty> colPreds; @FXML private LineChart<Integer, Integer> chart; @FXML private Canvas canvas; @FXML private Canvas preyCanvas; @FXML private Canvas predCanvas; @FXML private TableView<StatusIter> table; private double offset = 1.0; private double mapSize = 600 + 2. * offset; private int pitch; private Simulation simulation; private List<Integer> nbPredators; private List<Integer> nbPreys; private int kStep = 0; private XYChart.Series preysSeries; private XYChart.Series predSeries; final ObservableList<StatusIter> data = FXCollections.observableArrayList(); /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { txtMapSizeX.setText("40"); txtMapSizeY.setText("40"); txtStepNumber.setText("20"); txtPredInitNumber.setText("2"); txtPredDeathRate.setText("80"); txtPreyInitNumber.setText("10"); txtPreyDeathRate.setText("130"); nbPredators = Collections.synchronizedList(new ArrayList<>()); nbPreys = Collections.synchronizedList(new ArrayList<>()); initTable(); calculateService.stateProperty() .addListener((ObservableValue<? extends Worker.State> observableValue, Worker.State oldValue, Worker.State newValue) -> { switch (newValue) { case FAILED: case CANCELLED: case SUCCEEDED: Platform.runLater(new Runnable() { @Override public void run() { } }); break; } } ); calculateService.valueProperty() .addListener(new ChangeListener<StatusIter>() { @Override public void changed(ObservableValue<? extends StatusIter> observable, StatusIter oldValue, StatusIter newValue) { Platform.runLater(new Runnable() { @Override public void run() { if (newValue != null) { nbPreys.add(newValue.getNbPreysValue()); nbPredators.add(newValue.getNbPredsValue()); drawOnChart(newValue); data.add(newValue); } } }); } }); } public void onProcessAction(ActionEvent ev) { init(); calculateService.restart(); } private void init() { data.clear(); nbPreys.clear(); nbPredators.clear(); int sizeX = Integer.parseInt(txtMapSizeX.getText().trim()); int sizeY = Integer.parseInt(txtMapSizeY.getText().trim()); int initPred = Integer.parseInt(txtPredInitNumber.getText()); int initPrey = Integer.parseInt(txtPreyInitNumber.getText()); int stepNumber = Integer.parseInt(txtStepNumber.getText()); double deathRate = Double.parseDouble(txtPredDeathRate.getText()) / 100.; double increaseRatio = Double.parseDouble(txtPreyDeathRate.getText()) / 100.; drawMesh(sizeX, sizeY); simulation = new Simulation(stepNumber, sizeX, sizeY, initPred, initPrey, deathRate, increaseRatio); List<Position> preys = simulation.getPreys(); drawPreys(preys); List<Position> predators = simulation.getPredators(); drawPredators(predators); nbPreys.add(preys.size()); nbPredators.add(predators.size()); StatusIter iter = new StatusIter(0, simulation.getNbPreys(), simulation.getNbPredators()); data.add(iter); preysSeries = new XYChart.Series(); predSeries = new XYChart.Series(); preysSeries.setName("Preys"); predSeries.setName("Predators"); chart.getData().addAll(predSeries); chart.getData().addAll(preysSeries); drawOnChart(iter); } public void drawOnChart(StatusIter iter) { preysSeries.getData().add(new XYChart.Data(iter.getNbIterValue(), iter.getNbPreysValue())); predSeries.getData().add(new XYChart.Data(iter.getNbIterValue(), iter.getNbPredsValue())); } public void drawMesh(int nbX, int nbY) { canvas.setHeight(mapSize); canvas.setWidth(mapSize); predCanvas.setHeight(mapSize); predCanvas.setWidth(mapSize); preyCanvas.setHeight(mapSize); preyCanvas.setWidth(mapSize); int nbMax = Math.max(nbX, nbY); pitch = ((int) canvas.getHeight()) / nbMax; double sizeX = nbX * pitch + 2. * offset; double sizeY = nbY * pitch + 2. * offset; GraphicsContext gc = canvas.getGraphicsContext2D(); gc.clearRect(0., 0., mapSize, mapSize); gc.setFill(new Color(0.2, 1.0, 0.2, 0.6)); gc.fillRect(0., 0., sizeX, sizeY); gc.setStroke(Color.BLACK); gc.setFill(Color.BLACK); gc.setLineWidth(1.); gc.strokeRect(0., 0., sizeX, sizeY); for (int i = 0; i < nbX; i++) { for (int j = 0; j < nbY; j++) { gc.strokeRect(offset + i * pitch, offset + j * pitch, pitch, pitch); } } } public void drawPreys(List<Position> positions) { GraphicsContext g2c = preyCanvas.getGraphicsContext2D(); g2c.clearRect(0., 0., mapSize, mapSize); g2c.setStroke(Color.GREEN); g2c.setLineWidth(2.); for (Position pos : positions) { int x = pos.getX() - 1; int y = pos.getY() - 1; RadialGradient radial = new RadialGradient(0, 0., offset + (x + 0.5) * pitch, offset + (y + 0.5) * pitch, pitch / 2, false, CycleMethod.NO_CYCLE, new Stop(0, Color.WHITE), new Stop(1, Color.BLACK)); g2c.setFill(radial); g2c.fillOval(offset + 2 + x * pitch, offset + 2 + y * pitch, pitch - 4, pitch - 4); } } public void drawPredators(List<Position> positions) { GraphicsContext g2c = predCanvas.getGraphicsContext2D(); g2c.clearRect(0., 0., mapSize, mapSize); g2c.setStroke(Color.RED); Color alphaRed = new Color(Color.RED.getRed(), 0., 0., 0.3f); g2c.setFill(alphaRed); g2c.setLineWidth(2.); for (Position pos : positions) { int x = pos.getX() - 1; int y = pos.getY() - 1; g2c.fillRect(offset + (x - 1) * pitch, offset + (y - 1) * pitch, 3 * pitch, 3 * pitch); g2c.strokeLine(offset + 2 + x * pitch, offset + 2 + y * pitch, offset + (x + 1) * pitch - 2, offset - 2 + (y + 1) * pitch); g2c.strokeLine(offset + 2 + x * pitch, offset - 2 + (y + 1) * pitch, offset + (x + 1) * pitch - 2, offset + 2 + y * pitch); } } public void initTable() { Callback<TableColumn<StatusIter, SimpleIntegerProperty>, TableCell<StatusIter, SimpleIntegerProperty>> renderer = new Callback<TableColumn<StatusIter, SimpleIntegerProperty>, TableCell<StatusIter, SimpleIntegerProperty>>() { @Override public TableCell<StatusIter, SimpleIntegerProperty> call(TableColumn<StatusIter, SimpleIntegerProperty> param) { return new TableCell<StatusIter, SimpleIntegerProperty>() { @Override protected void updateItem(SimpleIntegerProperty item, boolean empty) { super.updateItem(item, empty); //To change body of generated methods, choose Tools | Templates. if (!empty) { setText("" + item.get()); } else { setText(""); } } }; } }; colStep.setCellValueFactory(new PropertyValueFactory<>("nbIter")); colStep.setCellFactory(renderer); colPreys.setCellValueFactory(new PropertyValueFactory<>("nbPreys")); colPreys.setCellFactory(renderer); colPreds.setCellValueFactory(new PropertyValueFactory<>("nbPreds")); colPreds.setCellFactory(renderer); table.setItems(data); } final Service<StatusIter> calculateService = new Service<StatusIter>() { @Override protected Task<StatusIter> createTask() { return new Task<StatusIter>() { @Override protected StatusIter call() throws Exception { Integer nbLoop = simulation.getNbLoop(); StatusIter iter = null; for (int j = 0; j < nbLoop; j++) { simulation.next(); drawPreys(simulation.getPreys()); drawPredators(simulation.getPredators()); iter = new StatusIter(j + 1, simulation.getNbPreys(), simulation.getNbPredators()); updateValue(iter); try { Thread.sleep(250); } catch (InterruptedException ie) { } } return iter; } }; } }; }
Java
@Path("projects/{projectId}/generalizations") @Api(value = "Web Service for {" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "}") public class GeneralizationService { @Context private HttpServletRequest httpServletRequest; @Context private HttpServletResponse httpServletResponse; @Context private UriInfo uriInfo; private static final Logger log = LoggerFactory.getLogger(GeneralizationService.class); // Start of user code class_attributes // End of user code // Start of user code class_methods // End of user code public GeneralizationService() { super(); } private void addCORSHeaders (final HttpServletResponse httpServletResponse) { //UI preview can be blocked by CORS policy. //add select CORS headers to every response that is embedded in an iframe. httpServletResponse.addHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, OPTIONS, HEAD"); httpServletResponse.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true"); } @GET @Path("{id}") @Produces({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_JSON_LD, OslcMediaType.TEXT_TURTLE, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON}) @ApiOperation( value = "GET for resources of type {'" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "'}", notes = "GET for resources of type {'" + "<a href=\"" + SysmlDomainConstants.GENERALIZATION_TYPE + "\">" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "</a>" + "'}" + ", with respective resource shapes {'" + "<a href=\"" + "../services/" + OslcConstants.PATH_RESOURCE_SHAPES + "/" + SysmlDomainConstants.GENERALIZATION_PATH + "\">" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "</a>" + "'}", produces = OslcMediaType.APPLICATION_RDF_XML + ", " + OslcMediaType.APPLICATION_XML + ", " + OslcMediaType.APPLICATION_JSON + ", " + OslcMediaType.TEXT_TURTLE + ", " + MediaType.TEXT_HTML + ", " + OslcMediaType.APPLICATION_X_OSLC_COMPACT_XML ) public Generalization getGeneralization( @PathParam("projectId") final String projectId, @PathParam("id") final String id ) throws IOException, ServletException, URISyntaxException { // Start of user code getResource_init // End of user code final Generalization aGeneralization = SysmlServerManager.getGeneralization(httpServletRequest, projectId, id); if (aGeneralization != null) { // Start of user code getGeneralization // End of user code httpServletResponse.setHeader("ETag", SysmlServerManager.getETagFromGeneralization(aGeneralization)); httpServletResponse.addHeader(SysmlServerConstants.HDR_OSLC_VERSION, SysmlServerConstants.OSLC_VERSION_V2); return aGeneralization; } throw new WebApplicationException(Status.NOT_FOUND); } @GET @Path("{id}") @Produces({ MediaType.TEXT_HTML }) @ApiOperation( value = "GET for resources of type {'" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "'}", notes = "GET for resources of type {'" + "<a href=\"" + SysmlDomainConstants.GENERALIZATION_TYPE + "\">" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "</a>" + "'}" + ", with respective resource shapes {'" + "<a href=\"" + "../services/" + OslcConstants.PATH_RESOURCE_SHAPES + "/" + SysmlDomainConstants.GENERALIZATION_PATH + "\">" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "</a>" + "'}", produces = OslcMediaType.APPLICATION_RDF_XML + ", " + OslcMediaType.APPLICATION_XML + ", " + OslcMediaType.APPLICATION_JSON + ", " + OslcMediaType.TEXT_TURTLE + ", " + MediaType.TEXT_HTML + ", " + OslcMediaType.APPLICATION_X_OSLC_COMPACT_XML ) public void getGeneralizationAsHtml( @PathParam("projectId") final String projectId, @PathParam("id") final String id ) throws ServletException, IOException, URISyntaxException { // Start of user code getGeneralizationAsHtml_init // End of user code final Generalization aGeneralization = SysmlServerManager.getGeneralization(httpServletRequest, projectId, id); if (aGeneralization != null) { httpServletRequest.setAttribute("aGeneralization", aGeneralization); // Start of user code getGeneralizationAsHtml_setAttributes // End of user code RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/org/oasis/oslcop/sysml/generalization.jsp"); rd.forward(httpServletRequest,httpServletResponse); return; } throw new WebApplicationException(Status.NOT_FOUND); } @GET @Path("{id}") @Produces({OslcMediaType.APPLICATION_X_OSLC_COMPACT_XML}) @ApiOperation( value = "GET for resources of type {'" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "'}", notes = "GET for resources of type {'" + "<a href=\"" + SysmlDomainConstants.GENERALIZATION_TYPE + "\">" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "</a>" + "'}" + ", with respective resource shapes {'" + "<a href=\"" + "../services/" + OslcConstants.PATH_RESOURCE_SHAPES + "/" + SysmlDomainConstants.GENERALIZATION_PATH + "\">" + SysmlDomainConstants.GENERALIZATION_LOCALNAME + "</a>" + "'}", produces = OslcMediaType.APPLICATION_RDF_XML + ", " + OslcMediaType.APPLICATION_XML + ", " + OslcMediaType.APPLICATION_JSON + ", " + OslcMediaType.TEXT_TURTLE + ", " + MediaType.TEXT_HTML + ", " + OslcMediaType.APPLICATION_X_OSLC_COMPACT_XML ) public Compact getGeneralizationCompact( @PathParam("projectId") final String projectId, @PathParam("id") final String id ) throws ServletException, IOException, URISyntaxException { String iconUri = OSLC4JUtils.getPublicURI() + "/images/ui_preview_icon.gif"; String smallPreviewHintHeight = "10em"; String smallPreviewHintWidth = "45em"; String largePreviewHintHeight = "20em"; String largePreviewHintWidth = "45em"; // Start of user code getGeneralizationCompact_init //TODO: adjust the preview height & width values from the default values provided above. // End of user code final Generalization aGeneralization = SysmlServerManager.getGeneralization(httpServletRequest, projectId, id); if (aGeneralization != null) { final Compact compact = new Compact(); compact.setAbout(aGeneralization.getAbout()); compact.setTitle(aGeneralization.toString()); compact.setIcon(new URI(iconUri)); //Create and set attributes for OSLC preview resource final Preview smallPreview = new Preview(); smallPreview.setHintHeight(smallPreviewHintHeight); smallPreview.setHintWidth(smallPreviewHintWidth); smallPreview.setDocument(UriBuilder.fromUri(aGeneralization.getAbout()).path("smallPreview").build()); compact.setSmallPreview(smallPreview); final Preview largePreview = new Preview(); largePreview.setHintHeight(largePreviewHintHeight); largePreview.setHintWidth(largePreviewHintWidth); largePreview.setDocument(UriBuilder.fromUri(aGeneralization.getAbout()).path("largePreview").build()); compact.setLargePreview(largePreview); httpServletResponse.addHeader(SysmlServerConstants.HDR_OSLC_VERSION, SysmlServerConstants.OSLC_VERSION_V2); addCORSHeaders(httpServletResponse); return compact; } throw new WebApplicationException(Status.NOT_FOUND); } @GET @Path("{id}/smallPreview") @Produces({ MediaType.TEXT_HTML }) public void getGeneralizationAsHtmlSmallPreview( @PathParam("projectId") final String projectId, @PathParam("id") final String id ) throws ServletException, IOException, URISyntaxException { // Start of user code getGeneralizationAsHtmlSmallPreview_init // End of user code final Generalization aGeneralization = SysmlServerManager.getGeneralization(httpServletRequest, projectId, id); if (aGeneralization != null) { httpServletRequest.setAttribute("aGeneralization", aGeneralization); // Start of user code getGeneralizationAsHtmlSmallPreview_setAttributes // End of user code RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/org/oasis/oslcop/sysml/generalizationsmallpreview.jsp"); httpServletResponse.addHeader(SysmlServerConstants.HDR_OSLC_VERSION, SysmlServerConstants.OSLC_VERSION_V2); addCORSHeaders(httpServletResponse); rd.forward(httpServletRequest, httpServletResponse); return; } throw new WebApplicationException(Status.NOT_FOUND); } @GET @Path("{id}/largePreview") @Produces({ MediaType.TEXT_HTML }) public void getGeneralizationAsHtmlLargePreview( @PathParam("projectId") final String projectId, @PathParam("id") final String id ) throws ServletException, IOException, URISyntaxException { // Start of user code getGeneralizationAsHtmlLargePreview_init // End of user code final Generalization aGeneralization = SysmlServerManager.getGeneralization(httpServletRequest, projectId, id); if (aGeneralization != null) { httpServletRequest.setAttribute("aGeneralization", aGeneralization); // Start of user code getGeneralizationAsHtmlLargePreview_setAttributes // End of user code RequestDispatcher rd = httpServletRequest.getRequestDispatcher("/org/oasis/oslcop/sysml/generalizationlargepreview.jsp"); httpServletResponse.addHeader(SysmlServerConstants.HDR_OSLC_VERSION, SysmlServerConstants.OSLC_VERSION_V2); addCORSHeaders(httpServletResponse); rd.forward(httpServletRequest, httpServletResponse); return; } throw new WebApplicationException(Status.NOT_FOUND); } }
Java
public class SealedSecondPriceAuction extends Auction{ /** * @param secretBid secret bid (should not be lower than 1). * @param networkConfiguration network configuration (number of parties should not be lower than 2). */ public SealedSecondPriceAuction(int secretBid, NetworkConfiguration networkConfiguration) { super(secretBid, networkConfiguration); } @Override public DRes<AuctionResult> buildComputation(ProtocolBuilderNumeric builder) { return builder.seq(seq -> { Numeric numeric = seq.numeric(); List<Pair<DRes<SInt>, DRes<SInt>>> closedInputs = new ArrayList<>(networkConfiguration.noOfParties()); // close inputs and gather inputs of other parties for(int otherId = 1; otherId <= networkConfiguration.noOfParties(); otherId++){ if (otherId == networkConfiguration.getMyId()) { DRes<SInt> myPartyId = numeric.input(networkConfiguration.getMyId(), networkConfiguration.getMyId()); DRes<SInt> mySecretBid = numeric.input(secretBid, networkConfiguration.getMyId()); closedInputs.add(new Pair<>(myPartyId, mySecretBid)); } else { DRes<SInt> otherPartyId = numeric.input(null, otherId); DRes<SInt> otherSecretBid = numeric.input(null, otherId); closedInputs.add(new Pair<>(otherPartyId, otherSecretBid)); } } return () -> closedInputs; }).seq((seq, inputs) -> { AdvancedNumeric advancedNumeric = seq.advancedNumeric(); Comparison comparison = seq.comparison(); // party id of the highest bidder DRes<SInt> highBidderId = inputs.get(0).getFirst(); // highest bid DRes<SInt> highBid = inputs.get(0).getSecond(); // second highest bid DRes<SInt> secHighBid = seq.numeric().known(0); // find highest bid and the party id of the corresponding bidder for(int i = 1; i < inputs.size(); i++){ DRes<SInt> inputPartyId = inputs.get(i).getFirst(); DRes<SInt> inputBid = inputs.get(i).getSecond(); DRes<SInt> highBidIsLowerEquals = comparison.compareLEQ(highBid, inputBid); DRes<SInt> secHighBidIsLowerEquals = comparison.compareLEQ(secHighBid, inputBid); secHighBid = advancedNumeric.condSelect(highBidIsLowerEquals, highBid, advancedNumeric.condSelect(secHighBidIsLowerEquals, inputBid, secHighBid)); highBid = advancedNumeric.condSelect(highBidIsLowerEquals, inputBid, highBid); highBidderId = advancedNumeric.condSelect(highBidIsLowerEquals, inputPartyId, highBidderId); } Pair<DRes<SInt>, DRes<SInt>> resultPair = new Pair(highBidderId, secHighBid); return () -> resultPair; }).seq((seq, resultPair) -> { Numeric numeric = seq.numeric(); // open results for all parties DRes<BigInteger> openedHighBidderId = numeric.open(resultPair.getFirst()); DRes<BigInteger> openedSecHighBid = numeric.open(resultPair.getSecond()); Pair<DRes<BigInteger>, DRes<BigInteger>> openedResultPair = new Pair<>(openedHighBidderId, openedSecHighBid); return () -> openedResultPair; }).seq((seq, openedResultPair) -> { return () -> new AuctionResult(openedResultPair.getFirst().out().intValue(), openedResultPair.getSecond().out().intValue()); }); } }
Java
public class DescendantOf implements Matcher<ExpressionTree> { private final String fullClassName; private final String methodName; public DescendantOf(String fullClassName, String methodName) { this.fullClassName = fullClassName; this.methodName = methodName; } @Override public boolean matches(ExpressionTree expressionTree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(expressionTree); if (sym == null) { return false; } if (!(sym instanceof MethodSymbol)) { throw new IllegalArgumentException("DescendantOf matcher expects a method call but found " + sym.getClass() + ". Expression: " + expressionTree); } if (sym.isStatic()) { return false; } if (methodName.equals(sym.toString())) { Type accessedReferenceType = sym.owner.type; Type collectionType = state.getTypeFromString(fullClassName); if (collectionType != null) { return state.getTypes().isSubtype(accessedReferenceType, state.getTypes().erasure(collectionType)); } } return false; } }
Java
class CpuFilter implements FileFilter { @Override public boolean accept(File pathname) { //Check if filename is "cpu", followed by a single digit number if(Pattern.matches("cpu[0-9]+", pathname.getName())) { return true; } return false; } }
Java
public class MainActivity2 extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener { private Button button_1; private GridView mPhotoGradView; private SaveInspectionPreViewAdapter mAdapter; private int inspectionId = 0; @Override protected int getLayoutResourceId() { return R.layout.activity_2; } @Override protected void initial() { initView(); initClick(); } private void initView() { mPhotoGradView = (GridView) findViewById(R.id.gridview); } private void initClick() { mAdapter = new SaveInspectionPreViewAdapter(this); mPhotoGradView.setAdapter(mAdapter); mPhotoGradView.setOnItemClickListener(this); /* 网络图片 */ List<PhotoInfo> photoInfos = new ArrayList<>(); List<InspectionPicture> inspectionPictures = InspectionPicture.getInspectionPicture(inspectionId); for (InspectionPicture inspectionPicture : inspectionPictures) { PhotoInfo photoInfo = new PhotoInfo(inspectionPicture.filePath); photoInfo.lat = inspectionPicture.lat; photoInfo.lng = inspectionPicture.lng; photoInfos.add(photoInfo); } mAdapter.setItems(photoInfos); } @Override public void onClick(View v) { switch (v.getId()) { } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == mAdapter.getItems().size()) { PhotoUtils.pickPhoto(MainActivity2.this, Constants.MAX_VALUE_PHOTOS - mAdapter.getItems().size()); } else { return; } } }
Java
public class CarbonTable implements Serializable { /** * serialization id */ private static final long serialVersionUID = 8696507171227156445L; /** * Absolute table identifier */ private AbsoluteTableIdentifier absoluteTableIdentifier; /** * TableName, Dimensions list */ private Map<String, List<CarbonDimension>> tableDimensionsMap; /** * table measures list. */ private Map<String, List<CarbonMeasure>> tableMeasuresMap; /** * tableUniqueName */ private String tableUniqueName; /** * Aggregate tables name */ private List<String> aggregateTablesName; /** * metadata file path (check if it is really required ) */ private String metaDataFilepath; /** * last updated time */ private long tableLastUpdatedTime; public CarbonTable() { this.tableDimensionsMap = new HashMap<String, List<CarbonDimension>>(); this.tableMeasuresMap = new HashMap<String, List<CarbonMeasure>>(); this.aggregateTablesName = new ArrayList<String>(); } /** * @param tableInfo */ public void loadCarbonTable(TableInfo tableInfo) { this.tableLastUpdatedTime = tableInfo.getLastUpdatedTime(); this.tableUniqueName = tableInfo.getTableUniqueName(); this.metaDataFilepath = tableInfo.getMetaDataFilepath(); //setting unique table identifier CarbonTableIdentifier carbontableIdentifier = new CarbonTableIdentifier(tableInfo.getDatabaseName(), tableInfo.getFactTable().getTableName(), tableInfo.getFactTable().getTableId()); this.absoluteTableIdentifier = new AbsoluteTableIdentifier(tableInfo.getStorePath(), carbontableIdentifier); fillDimensionsAndMeasuresForTables(tableInfo.getFactTable()); List<TableSchema> aggregateTableList = tableInfo.getAggregateTableList(); for (TableSchema aggTable : aggregateTableList) { this.aggregateTablesName.add(aggTable.getTableName()); fillDimensionsAndMeasuresForTables(aggTable); } } /** * Fill dimensions and measures for carbon table * * @param tableSchema */ private void fillDimensionsAndMeasuresForTables(TableSchema tableSchema) { List<CarbonDimension> dimensions = new ArrayList<CarbonDimension>(); List<CarbonMeasure> measures = new ArrayList<CarbonMeasure>(); this.tableDimensionsMap.put(tableSchema.getTableName(), dimensions); this.tableMeasuresMap.put(tableSchema.getTableName(), measures); int dimensionOrdinal = 0; int measureOrdinal = 0; int keyOrdinal = 0; int columnGroupOrdinal = -1; int previousColumnGroupId = -1; List<ColumnSchema> listOfColumns = tableSchema.getListOfColumns(); for (int i = 0; i < listOfColumns.size(); i++) { ColumnSchema columnSchema = listOfColumns.get(i); if (columnSchema.isDimensionColumn()) { if (columnSchema.getNumberOfChild() > 0) { CarbonDimension complexDimension = new CarbonDimension(columnSchema, dimensionOrdinal++, -1, -1); complexDimension.initializeChildDimensionsList(columnSchema.getNumberOfChild()); dimensions.add(complexDimension); dimensionOrdinal = readAllComplexTypeChildrens(dimensionOrdinal, columnSchema.getNumberOfChild(), listOfColumns, complexDimension); i = dimensionOrdinal - 1; } else { if (!columnSchema.getEncodingList().contains(Encoding.DICTIONARY)) { dimensions.add(new CarbonDimension(columnSchema, dimensionOrdinal++, -1, -1)); } else if (columnSchema.getEncodingList().contains(Encoding.DICTIONARY) && columnSchema.getColumnGroupId() == -1) { dimensions.add(new CarbonDimension(columnSchema, dimensionOrdinal++, keyOrdinal++, -1)); } else { columnGroupOrdinal = previousColumnGroupId == columnSchema.getColumnGroupId() ? ++columnGroupOrdinal : 0; previousColumnGroupId = columnSchema.getColumnGroupId(); dimensions.add(new CarbonDimension(columnSchema, dimensionOrdinal++, keyOrdinal++, columnGroupOrdinal)); } } } else { measures.add(new CarbonMeasure(columnSchema, measureOrdinal++)); } } } /** * Read all primitive/complex children and set it as list of child carbon dimension to parent * dimension * * @param dimensionOrdinal * @param childCount * @param listOfColumns * @param parentDimension * @return */ private int readAllComplexTypeChildrens(int dimensionOrdinal, int childCount, List<ColumnSchema> listOfColumns, CarbonDimension parentDimension) { for (int i = 0; i < childCount; i++) { ColumnSchema columnSchema = listOfColumns.get(dimensionOrdinal); if (columnSchema.isDimensionColumn()) { if (columnSchema.getNumberOfChild() > 0) { CarbonDimension complexDimension = new CarbonDimension(columnSchema, dimensionOrdinal++, -1, -1); complexDimension.initializeChildDimensionsList(columnSchema.getNumberOfChild()); parentDimension.getListOfChildDimensions().add(complexDimension); dimensionOrdinal = readAllComplexTypeChildrens(dimensionOrdinal, columnSchema.getNumberOfChild(), listOfColumns, complexDimension); } else { parentDimension.getListOfChildDimensions() .add(new CarbonDimension(columnSchema, dimensionOrdinal++, -1, -1)); } } } return dimensionOrdinal; } /** * @return the databaseName */ public String getDatabaseName() { return absoluteTableIdentifier.getCarbonTableIdentifier().getDatabaseName(); } /** * @return the tabelName */ public String getFactTableName() { return absoluteTableIdentifier.getCarbonTableIdentifier().getTableName(); } /** * @return the tableUniqueName */ public String getTableUniqueName() { return tableUniqueName; } /** * @return the metaDataFilepath */ public String getMetaDataFilepath() { return metaDataFilepath; } /** * @return storepath */ public String getStorePath() { return absoluteTableIdentifier.getStorePath(); } /** * @return list of aggregate TablesName */ public List<String> getAggregateTablesName() { return aggregateTablesName; } /** * @return the tableLastUpdatedTime */ public long getTableLastUpdatedTime() { return tableLastUpdatedTime; } /** * to get the number of dimension present in the table * * @param tableName * @return number of dimension present the table */ public int getNumberOfDimensions(String tableName) { return tableDimensionsMap.get(tableName).size(); } /** * to get the number of measures present in the table * * @param tableName * @return number of measures present the table */ public int getNumberOfMeasures(String tableName) { return tableMeasuresMap.get(tableName).size(); } /** * to get the all dimension of a table * * @param tableName * @return all dimension of a table */ public List<CarbonDimension> getDimensionByTableName(String tableName) { return tableDimensionsMap.get(tableName); } /** * to get the all measure of a table * * @param tableName * @return all measure of a table */ public List<CarbonMeasure> getMeasureByTableName(String tableName) { return tableMeasuresMap.get(tableName); } /** * to get particular measure from a table * * @param tableName * @param columnName * @return */ public CarbonMeasure getMeasureByName(String tableName, String columnName) { List<CarbonMeasure> measureList = tableMeasuresMap.get(tableName); for (CarbonMeasure measure : measureList) { if (measure.getColName().equalsIgnoreCase(columnName)) { return measure; } } return null; } /** * to get particular dimension from a table * * @param tableName * @param columnName * @return */ public CarbonDimension getDimensionByName(String tableName, String columnName) { List<CarbonDimension> dimList = tableDimensionsMap.get(tableName); for (CarbonDimension dim : dimList) { if (dim.getColName().equalsIgnoreCase(columnName)) { return dim; } } return null; } /** * gets all children dimension for complex type * * @param dimName * @return list of child dimensions */ public List<CarbonDimension> getChildren(String dimName) { for (List<CarbonDimension> list : tableDimensionsMap.values()) { List<CarbonDimension> childDims = getChildren(dimName, list); if (childDims != null) { return childDims; } } return null; } /** * returns level 2 or more child dimensions * * @param dimName * @param dimensions * @return list of child dimensions */ public List<CarbonDimension> getChildren(String dimName, List<CarbonDimension> dimensions) { for (CarbonDimension carbonDimension : dimensions) { if (carbonDimension.getColName().equals(dimName)) { return carbonDimension.getListOfChildDimensions(); } else if (null != carbonDimension.getListOfChildDimensions() && carbonDimension.getListOfChildDimensions().size() > 0) { List<CarbonDimension> childDims = getChildren(dimName, carbonDimension.getListOfChildDimensions()); if (childDims != null) { return childDims; } } } return null; } /** * @return absolute table identifier */ public AbsoluteTableIdentifier getAbsoluteTableIdentifier() { return absoluteTableIdentifier; } /** * @return carbon table identifier */ public CarbonTableIdentifier getCarbonTableIdentifier() { return absoluteTableIdentifier.getCarbonTableIdentifier(); } /** * gets partition count for this table * TODO: to be implemented while supporting partitioning */ public int getPartitionCount() { return 1; } }
Java
public class ImmediateBankTransfer extends JavaProcess { /** DocAction */ private String p_docAction = IDocument.ACTION_Complete; /** Created # */ private int m_created = 0; private int m_C_Currency_ID; // Currency private String p_Name = ""; // Name private String p_Description= ""; // Description private int p_C_CashBook_ID = 0; // CashBook to be used as bridge private BigDecimal p_Amount = new BigDecimal(0); // Amount to be transfered between the accounts private int p_From_C_BP_BankAccount_ID = 0; // Bank Account From private int p_To_C_BP_BankAccount_ID= 0; // Bank Account To private Timestamp p_StatementDate = null; // Date Statement private Timestamp p_DateAcct = null; // Date Account /** * Prepare - e.g., get Parameters. */ @Override protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (name.equals("From_C_BP_BankAccount_ID")) { p_From_C_BP_BankAccount_ID = ((BigDecimal)para[i].getParameter()).intValue(); } else if (name.equals("To_C_BP_BankAccount_ID")) { p_To_C_BP_BankAccount_ID = ((BigDecimal)para[i].getParameter()).intValue(); } else if (name.equals("C_CashBook_ID")) p_C_CashBook_ID = ((BigDecimal)para[i].getParameter()).intValue(); else if (name.equals("Amount")) p_Amount = ((BigDecimal)para[i].getParameter()); else if (name.equals("Name")) p_Name = (String)para[i].getParameter(); else if (name.equals("Description")) p_Description = (String)para[i].getParameter(); else if (name.equals("StatementDate")) p_StatementDate = (Timestamp)para[i].getParameter(); else if (name.equals("DateAcct")) p_DateAcct = (Timestamp)para[i].getParameter(); else log.error("prepare - Unknown Parameter: " + name); } } // prepare /** * Perform process. * @return Message (translated text) * @throws Exception if not successful */ @Override protected String doIt() throws Exception { log.info("From Bank="+p_From_C_BP_BankAccount_ID+" - To Bank="+p_To_C_BP_BankAccount_ID + " - C_CashBook_ID="+p_C_CashBook_ID+" - Amount="+p_Amount+" - Name="+p_Name + " - Description="+p_Description+ " - Statement Date="+p_StatementDate+ " - Date Account="+p_DateAcct); if (p_To_C_BP_BankAccount_ID == 0 || p_From_C_BP_BankAccount_ID == 0) throw new IllegalArgumentException("Banks required"); if (p_Name == null || p_Name.length() == 0) throw new IllegalArgumentException("Name required"); // To_C_BP_BankAccount_ID MUST be different than From_C_BP_BankAccount_ID if (p_To_C_BP_BankAccount_ID == p_From_C_BP_BankAccount_ID) throw new AdempiereUserError ("Banks From and To must be different"); // Banks and CashBook must have same currency if (!isSameCurrency()) throw new AdempiereUserError ("Banks and CashBook must have same currency"); if (p_Amount.compareTo(new BigDecimal(0)) == 0) throw new AdempiereUserError ("Amount required"); // Login Date if (p_StatementDate == null) p_StatementDate = Env.getContextAsDate(getCtx(), "#Date"); if (p_StatementDate == null) p_StatementDate = new Timestamp(System.currentTimeMillis()); if (p_DateAcct == null) p_DateAcct = p_StatementDate; generateBankTransfer(); return "@Created@ = " + m_created; } // doIt /** * To check CashBook and Banks have the same currency * @return */ private boolean isSameCurrency() { MCashBook mcash = new MCashBook (getCtx(),p_C_CashBook_ID, get_TrxName()); I_C_BP_BankAccount mBankFrom = InterfaceWrapperHelper.create(getCtx(), p_From_C_BP_BankAccount_ID, I_C_BP_BankAccount.class, getTrxName()); I_C_BP_BankAccount mBankTo = InterfaceWrapperHelper.create(getCtx(), p_To_C_BP_BankAccount_ID, I_C_BP_BankAccount.class, getTrxName()); if ((mcash.getC_Currency_ID() != mBankFrom.getC_Currency_ID()) || (mcash.getC_Currency_ID() != mBankTo.getC_Currency_ID())) return false ; m_C_Currency_ID = mcash.getC_Currency_ID(); return true; } // isSameCurrency private MCash createCash() { MCash cash = new MCash (getCtx(), 0, get_TrxName()); cash.setName(p_Name); cash.setDescription(p_Description); cash.setDateAcct(p_DateAcct); cash.setStatementDate(p_StatementDate); cash.setC_CashBook_ID(p_C_CashBook_ID); if (!cash.save()) { throw new IllegalStateException("Could not create Cash"); } return cash; } // createCash private MCashLine[] createCashLines(MCash cash) { ArrayList<MCashLine> cashLineList = new ArrayList<MCashLine>(); // From Bank (From) to CashLine MCashLine cashLine = new MCashLine (cash); cashLine.setAmount(p_Amount); cashLine.setC_BP_BankAccount_ID(p_From_C_BP_BankAccount_ID); cashLine.setC_Currency_ID(m_C_Currency_ID); if (p_Description != null) cashLine.setDescription(p_Description); else cashLine.setDescription(p_Name); cashLine.setCashType("T"); // Transfer if (!cashLine.save()) { throw new IllegalStateException("Could not create Cash line (From Bank)"); } cashLineList.add(cashLine); // From CashLine to Bank (To) cashLine = new MCashLine (cash); cashLine.setAmount(p_Amount.negate()); cashLine.setC_BP_BankAccount_ID(p_To_C_BP_BankAccount_ID); cashLine.setC_Currency_ID(m_C_Currency_ID); if (p_Description != null) cashLine.setDescription(p_Description); else cashLine.setDescription(p_Name); cashLine.setCashType("T"); // Transfer if (!cashLine.save()) { throw new IllegalStateException("Could not create Cash line (To Bank)"); } cashLineList.add(cashLine); MCashLine cashLines[] = new MCashLine[cashLineList.size()]; cashLineList.toArray(cashLines); return cashLines; } // createCashLines /** * Generate CashJournal * */ private void generateBankTransfer() { // Create Cash & CashLines MCash cash = createCash(); MCashLine cashLines[]= createCashLines(cash); StringBuffer processMsg = new StringBuffer(cash.getDocumentNo()); cash.setDocAction(p_docAction); if (!cash.processIt(p_docAction)) { processMsg.append(" (NOT Processed)"); log.warn("Cash Processing failed: " + cash + " - " + cash.getProcessMsg()); addLog(cash.getC_Cash_ID(), cash.getStatementDate(), null, "Cash Processing failed: " + cash + " - " + cash.getProcessMsg() + " / please complete it manually"); } if (!cash.save()) { throw new IllegalStateException("Could not create Cash"); } // Add processing information to process log addLog(cash.getC_Cash_ID(), cash.getStatementDate(), null, processMsg.toString()); m_created++; } // generateBankTransfer }
Java
public abstract class AbstractComposedSyntaxTreeNode extends AbstractSyntaxTreeNode implements IComposedSyntaxTreeNode { private List<ISyntaxTreeNode> arguments = new ArrayList<ISyntaxTreeNode>(); @Override public ISyntaxTreeNode shiftArgument() { ISyntaxTreeNode result = this.arguments.get(0); this.arguments = this.arguments.subList( 1, this.arguments.size() ); return result; } @Override public void removeArgument( ISyntaxTreeNode node ) { this.arguments.remove(node); } @Override public void addArgument(ISyntaxTreeNode node) { this.arguments.add(node); } @Override public List<ISyntaxTreeNode> getArguments() { return this.arguments; } }
Java
public class MacInfo extends JSONObject implements Serializable{ //------------------------------------------------------------------------------------- private String address; private int vlan; int needVlan; public MacInfo(){} public MacInfo(String address, int vlan){ this.address = address; this.vlan = vlan; this.needVlan = 1; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getVlan() { return vlan; } public void setVlan(int vlan) { this.vlan = vlan; } public String toString() { if(needVlan!=0) return "{\"address\":\"" + address + '\"' + ", \"vlan\":\"" + vlan + '\"' + '}'; else return "{\"address\":\"" + address + '\"' + '}'; } }
Java
public class WanPublisherConfig implements IdentifiedDataSerializable { private static final int DEFAULT_QUEUE_CAPACITY = 10000; private static final WANQueueFullBehavior DEFAULT_QUEUE_FULL_BEHAVIOR = WANQueueFullBehavior.DISCARD_AFTER_MUTATION; private String groupName = "dev"; private int queueCapacity = DEFAULT_QUEUE_CAPACITY; private WANQueueFullBehavior queueFullBehavior = DEFAULT_QUEUE_FULL_BEHAVIOR; private Map<String, Comparable> properties = new HashMap<String, Comparable>(); private String className; private Object implementation; public String getGroupName() { return groupName; } public WanPublisherConfig setGroupName(String groupName) { this.groupName = groupName; return this; } /** * Get the capacity of the queue for WAN replication events. IMap, ICache, normal and backup events count against * the queue capacity separately. When the queue capacity is reached, backup events are dropped while normal * replication events behave as determined by the {@link #getQueueFullBehavior()}. * The default queue size for replication queues is {@value #DEFAULT_QUEUE_CAPACITY}. * * @return the queue capacity */ public int getQueueCapacity() { return queueCapacity; } /** * Set the capacity of the queue for WAN replication events. IMap, ICache, normal and backup events count against * the queue capacity separately. When the queue capacity is reached, backup events are dropped while normal * replication events behave as determined by the {@link #getQueueFullBehavior()}. * The default queue size for replication queues is {@value #DEFAULT_QUEUE_CAPACITY}. * * @param queueCapacity the queue capacity * @return this configuration */ public WanPublisherConfig setQueueCapacity(int queueCapacity) { this.queueCapacity = queueCapacity; return this; } public WANQueueFullBehavior getQueueFullBehavior() { return queueFullBehavior; } public WanPublisherConfig setQueueFullBehavior(WANQueueFullBehavior queueFullBehavior) { this.queueFullBehavior = queueFullBehavior; return this; } public Map<String, Comparable> getProperties() { return properties; } public WanPublisherConfig setProperties(Map<String, Comparable> properties) { this.properties = properties; return this; } public String getClassName() { return className; } /** * Set the name of the class implementing the WanReplicationEndpoint. * NOTE: OS and EE have different interfaces that this class should implement. * For OS see {@link com.hazelcast.wan.WanReplicationEndpoint}. * * @param className the name of the class implementation for the WAN replication * @return the wan publisher config */ public WanPublisherConfig setClassName(String className) { this.className = className; return this; } public Object getImplementation() { return implementation; } /** * Set the implementation of the WanReplicationEndpoint. * NOTE: OS and EE have different interfaces that this object should implement. * For OS see {@link com.hazelcast.wan.WanReplicationEndpoint}. * * @param implementation the implementation for the WAN replication * @return the wan publisher config */ public WanPublisherConfig setImplementation(Object implementation) { this.implementation = implementation; return this; } @Override public String toString() { return "WanPublisherConfig{" + "properties=" + properties + ", className='" + className + '\'' + ", implementation=" + implementation + ", groupName='" + groupName + '\'' + ", queueCapacity=" + queueCapacity + ", queueFullBehavior=" + queueFullBehavior + '}'; } @Override public int getFactoryId() { return ConfigDataSerializerHook.F_ID; } @Override public int getId() { return ConfigDataSerializerHook.WAN_PUBLISHER_CONFIG; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(groupName); out.writeInt(queueCapacity); out.writeInt(queueFullBehavior.getId()); int size = properties.size(); out.writeInt(size); for (Map.Entry<String, Comparable> entry : properties.entrySet()) { out.writeUTF(entry.getKey()); out.writeObject(entry.getValue()); } out.writeUTF(className); out.writeObject(implementation); } @Override public void readData(ObjectDataInput in) throws IOException { groupName = in.readUTF(); queueCapacity = in.readInt(); queueFullBehavior = WANQueueFullBehavior.getByType(in.readInt()); int size = in.readInt(); for (int i = 0; i < size; i++) { properties.put(in.readUTF(), (Comparable) in.readObject()); } className = in.readUTF(); implementation = in.readObject(); } }
Java
public class RemoveOverlappingObjects extends ReduceElementsGreedy { // START BEAN FIELDS /** Bounding boxes with scores above this threshold are removed */ @BeanField @Getter @Setter private double scoreThreshold = 0.3; // END BEAN FIELDS @Override protected boolean shouldObjectsBeProcessed(ObjectMask source, ObjectMask other) { // These objects are deemed sufficiently-overlapping to be removed return overlapScoreFor(source, other) >= scoreThreshold; } @Override protected boolean processObjects( LabelledWithConfidence<ObjectMask> source, LabelledWithConfidence<ObjectMask> overlapping, ReduceObjectsGraph graph) { // This removes the overlapping object from the current iteration try { graph.removeVertex(overlapping); } catch (OperationFailedException e) { throw new AnchorImpossibleSituationException(); } // No alteration to the source object return false; } private double overlapScoreFor(ObjectMask element1, ObjectMask element2) { ObjectMask merged = ObjectMaskMerger.merge(element1, element2); return OverlapCalculator.calculateOverlapRatio(element1, element2, merged); } }
Java
public class NetworkStatusParser { public NetworkStatusData parseConsensus(String consensusString) { NetworkStatusData result = new NetworkStatusData(); try { BufferedReader br = new BufferedReader(new StringReader( consensusString)); String line, rLine = null; SimpleDateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); while ((line = br.readLine()) != null) { if (line.startsWith("valid-after ")) { try { result.setValidAfterMillis(dateTimeFormat.parse( line.substring("valid-after ".length())).getTime()); } catch (ParseException e) { System.err.println("Could not parse valid-after timestamp in " + "line '" + line + "' of consensus. Skipping."); return null; } } else if (line.startsWith("r ")) { rLine = line; } else if (line.startsWith("s ") || line.equals("s")) { if (rLine == null) { System.err.println("s line without r line in consensus. " + "Skipping"); continue; } if (line.contains(" Running")) { String[] rLineParts = rLine.split(" "); String nickname = rLineParts[1]; String fingerprint = Hex.encodeHexString( Base64.decodeBase64(rLineParts[2] + "=")).toUpperCase(); String address = rLineParts[6]; int orPort = Integer.parseInt(rLineParts[7]); int dirPort = Integer.parseInt(rLineParts[8]); SortedSet<String> relayFlags = new TreeSet<String>( Arrays.asList(line.substring(2).split(" "))); result.addStatusEntry(nickname, fingerprint, address, orPort, dirPort, relayFlags); } } } } catch (IOException e) { System.err.println("Ran into an IOException while parsing a String " + "in memory. Something's really wrong. Exiting."); System.exit(1); } return result; } public ServerDescriptorData parseServerDescriptor( String descriptorString) { ServerDescriptorData result = new ServerDescriptorData(); try { BufferedReader br = new BufferedReader(new StringReader( descriptorString)); String line; SimpleDateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); List<String> exitPolicyLines = new ArrayList<String>(); while ((line = br.readLine()) != null) { if (line.startsWith("platform ")) { String platformLine = new String( line.substring("platform ".length()).getBytes(), "US-ASCII").replaceAll("[^\\p{ASCII}]",""). replaceAll("\\\"", "\\\\\""); result.setPlatformLine(platformLine); } else if (line.startsWith("published ")) { long publishedMillis = dateTimeFormat.parse(line.substring( "published ".length())).getTime(); result.setPublishedMillis(publishedMillis); } else if (line.startsWith("opt fingerprint") || line.startsWith("fingerprint")) { String fingerprint = line.substring(line.indexOf("fingerprint ") + "finerprint ".length()).replaceAll(" ", ""); result.setFingerprint(fingerprint); } else if (line.startsWith("contact ")) { String contactLine = new String( line.substring("contact ".length()).getBytes(), "US-ASCII"). replaceAll("[^\\p{ASCII}]","").replaceAll("\\\"", "\\\\\""); result.setContactLine(contactLine); } else if (line.startsWith("reject ") || line.startsWith("accept ")) { exitPolicyLines.add(line); } else if (line.startsWith("family ")) { List<String> family = Arrays.asList( line.substring("family ".length()).split(" ")); result.setFamily(family); } else if (line.equals("router-signature")) { break; } } result.setExitPolicyLines(exitPolicyLines); } catch (IOException e) { System.err.println("Ran into an IOException while parsing a String " + "in memory. Something's really wrong. Exiting."); e.printStackTrace(); System.exit(1); } catch (ParseException e) { System.err.println("Could not parse timestamp in server descriptor " + "string. Skipping."); e.printStackTrace(); result = null; } return result; } public BridgeNetworkStatusData parseBridgeNetworkStatus( String statusString, long publishedMillis) { BridgeNetworkStatusData result = new BridgeNetworkStatusData(); result.setPublishedMillis(publishedMillis); try { BufferedReader br = new BufferedReader(new StringReader( statusString)); String line, rLine = null; SimpleDateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); while ((line = br.readLine()) != null) { if (line.startsWith("r ")) { rLine = line; } else if (line.startsWith("s ") || line.equals("s")) { if (rLine == null) { System.err.println("s line without r line in consensus. " + "Skipping"); continue; } if (line.contains(" Running")) { String[] rLineParts = rLine.split(" "); String hashedFingerprint = Hex.encodeHexString( Base64.decodeBase64(rLineParts[2] + "=")).toUpperCase(); result.addStatusEntry(hashedFingerprint); } } } } catch (IOException e) { System.err.println("Ran into an IOException while parsing a String " + "in memory. Something's really wrong. Exiting."); System.exit(1); } return result; } }
Java
public class RelateComputer { private final GeometryGraph[] arg; // the arg(s) of the operation // this intersection matrix will hold the results compute for the relate private final ArrayList isolatedEdges = new ArrayList(); private final LineIntersector li = new RobustLineIntersector(); private final NodeMap nodes = new NodeMap(new RelateNodeFactory()); private final PointLocator ptLocator = new PointLocator(); public RelateComputer(final GeometryGraph[] arg) { this.arg = arg; } /** * If the Geometries are disjoint, we need to enter their dimension and * boundary dimension in the Ext rows in the IM */ private void computeDisjointIM(final IntersectionMatrix im) { final Geometry ga = this.arg[0].getGeometry(); if (!ga.isEmpty()) { im.set(Location.INTERIOR, Location.EXTERIOR, ga.getDimension()); im.set(Location.BOUNDARY, Location.EXTERIOR, ga.getBoundaryDimension()); } final Geometry gb = this.arg[1].getGeometry(); if (!gb.isEmpty()) { im.set(Location.EXTERIOR, Location.INTERIOR, gb.getDimension()); im.set(Location.EXTERIOR, Location.BOUNDARY, gb.getBoundaryDimension()); } } public IntersectionMatrix computeIM() { final Dimension dimension1 = this.arg[0].getGeometryDimension(); final Dimension dimension2 = this.arg[1].getGeometryDimension(); final IntersectionMatrix im = new IntersectionMatrix(dimension1, dimension2); // since Geometries are finite and embedded in a 2-D space, the EE element // must always be 2 im.set(Location.EXTERIOR, Location.EXTERIOR, Dimension.A); // if the Geometries don't overlap there is nothing to do if (!this.arg[0].getGeometry().bboxIntersects(this.arg[1].getGeometry())) { computeDisjointIM(im); return im; } this.arg[0].computeSelfNodes(this.li, false); this.arg[1].computeSelfNodes(this.li, false); // compute intersections between edges of the two input geometries final SegmentIntersector intersector = this.arg[0].computeEdgeIntersections(this.arg[1], this.li, false); // System.out.println("computeIM: # segment intersection tests: " + // intersector.numTests); computeIntersectionNodes(0); computeIntersectionNodes(1); /** * Copy the labelling for the nodes in the parent Geometries. These override * any labels determined by intersections between the geometries. */ copyNodesAndLabels(0); copyNodesAndLabels(1); // complete the labelling for any nodes which only have a label for a single // geometry // Debug.addWatch(nodes.find(new PointDouble((double)110, 200))); // Debug.printWatch(); labelIsolatedNodes(); // Debug.printWatch(); // If a proper intersection was found, we can set a lower bound on the IM. computeProperIntersectionIM(intersector, im); /** * Now process improper intersections * (eg where one or other of the geometries has a vertex at the intersection point) * We need to compute the edge graph at all nodes to determine the IM. */ // build EdgeEnds for all intersections final EdgeEndBuilder eeBuilder = new EdgeEndBuilder(); final List<EdgeEnd> ee0 = eeBuilder.computeEdgeEnds(this.arg[0].edges()); insertEdgeEnds(ee0); final List<EdgeEnd> ee1 = eeBuilder.computeEdgeEnds(this.arg[1].edges()); insertEdgeEnds(ee1); // Debug.println("==== NodeList ==="); // Debug.print(nodes); labelNodeEdges(); /** * Compute the labeling for isolated components * <br> * Isolated components are components that do not touch any other components in the graph. * They can be identified by the fact that they will * contain labels containing ONLY a single element, the one for their parent geometry. * We only need to check components contained in the input graphs, since * isolated components will not have been replaced by new components formed by intersections. */ // debugPrintln("Graph A isolated edges - "); labelIsolatedEdges(0, 1); // debugPrintln("Graph B isolated edges - "); labelIsolatedEdges(1, 0); // update the IM from all components updateIM(im); return im; } /** * Insert nodes for all intersections on the edges of a Geometry. * Label the created nodes the same as the edge label if they do not already have a label. * This allows nodes created by either self-intersections or * mutual intersections to be labelled. * Endpoint nodes will already be labelled from when they were inserted. */ private void computeIntersectionNodes(final int argIndex) { for (final Iterator i = this.arg[argIndex].getEdgeIterator(); i.hasNext();) { final Edge e = (Edge)i.next(); final Location eLoc = e.getLabel().getLocation(argIndex); for (final Object element : e.getEdgeIntersectionList()) { final EdgeIntersection ei = (EdgeIntersection)element; final RelateNode n = (RelateNode)this.nodes.addNode(ei.newPoint2D()); if (eLoc == Location.BOUNDARY) { n.setLabelBoundary(argIndex); } else { if (n.getLabel().isNull(argIndex)) { n.setLabel(argIndex, Location.INTERIOR); } } // Debug.println(n); } } } private void computeProperIntersectionIM(final SegmentIntersector intersector, final IntersectionMatrix im) { // If a proper intersection is found, we can set a lower bound on the IM. final Dimension dimA = this.arg[0].getGeometry().getDimension(); final Dimension dimB = this.arg[1].getGeometry().getDimension(); final boolean hasProper = intersector.hasProperIntersection(); final boolean hasProperInterior = intersector.hasProperInteriorIntersection(); // For Geometry's of dim 0 there can never be proper intersections. /** * If edge segments of Areas properly intersect, the areas must properly overlap. */ if (dimA.isArea() && dimB.isArea()) { if (hasProper) { im.setAtLeast("212101212"); } } /** * If an Line segment properly intersects an edge segment of an Area, * it follows that the Interior of the Line intersects the Boundary of the Area. * If the intersection is a proper <i>interior</i> intersection, then * there is an Interior-Interior intersection too. * Note that it does not follow that the Interior of the Line intersects the Exterior * of the Area, since there may be another Area component which contains the rest of the Line. */ else if (dimA.isArea() && dimB.isLine()) { if (hasProper) { im.setAtLeast("FFF0FFFF2"); } if (hasProperInterior) { im.setAtLeast("1FFFFF1FF"); } } else if (dimA.isLine() && dimB.isArea()) { if (hasProper) { im.setAtLeast("F0FFFFFF2"); } if (hasProperInterior) { im.setAtLeast("1F1FFFFFF"); } } /* * If edges of LineStrings properly intersect *in an interior point*, all we * can deduce is that the interiors intersect. (We can NOT deduce that the * exteriors intersect, since some other segments in the geometries might * cover the points in the neighbourhood of the intersection.) It is * important that the point be known to be an interior point of both * Geometries, since it is possible in a self-intersecting geometry to have * a proper intersection on one segment that is also a boundary point of * another segment. */ else if (dimA.isLine() && dimB.isLine()) { if (hasProperInterior) { im.setAtLeast("0FFFFFFFF"); } } } /** * Copy all nodes from an arg geometry into this graph. * The node label in the arg geometry overrides any previously computed * label for that argIndex. * (E.g. a node may be an intersection node with * a computed label of BOUNDARY, * but in the original arg Geometry it is actually * in the interior due to the Boundary Determination Rule) */ private void copyNodesAndLabels(final int argIndex) { for (final Iterator i = this.arg[argIndex].getNodeIterator(); i.hasNext();) { final Node graphNode = (Node)i.next(); final Node newNode = this.nodes.addNode(graphNode); newNode.setLabel(argIndex, graphNode.getLabel().getLocation(argIndex)); // node.print(System.out); } } private void insertEdgeEnds(final List ee) { for (final Object element : ee) { final EdgeEnd e = (EdgeEnd)element; this.nodes.add(e); } } /** * Label an isolated edge of a graph with its relationship to the target geometry. * If the target has dim 2 or 1, the edge can either be in the interior or the exterior. * If the target has dim 0, the edge must be in the exterior */ private void labelIsolatedEdge(final Edge edge, final int targetIndex, final Geometry target) { // this won't work for GeometryCollections with both dim 2 and 1 geoms if (target.getDimension().isGreaterThan(Dimension.P)) { // since edge is not in boundary, may not need the full generality of // PointLocator? // Possibly should use ptInArea locator instead? We probably know here // that the edge does not touch the bdy of the target Geometry final double x = edge.getX(0); final double y = edge.getY(0); final Location loc = this.ptLocator.locate(target, x, y); edge.getLabel().setAllLocations(targetIndex, loc); } else { edge.getLabel().setAllLocations(targetIndex, Location.EXTERIOR); } // System.out.println(e.getLabel()); } /** * Processes isolated edges by computing their labelling and adding them * to the isolated edges list. * Isolated edges are guaranteed not to touch the boundary of the target (since if they * did, they would have caused an intersection to be computed and hence would * not be isolated) */ private void labelIsolatedEdges(final int thisIndex, final int targetIndex) { for (final Iterator ei = this.arg[thisIndex].getEdgeIterator(); ei.hasNext();) { final Edge e = (Edge)ei.next(); if (e.isIsolated()) { labelIsolatedEdge(e, targetIndex, this.arg[targetIndex].getGeometry()); this.isolatedEdges.add(e); } } } /** * Label an isolated node with its relationship to the target geometry. */ private void labelIsolatedNode(final Node n, final int targetIndex) { final Geometry geometry = this.arg[targetIndex].getGeometry(); final double x = n.getX(); final double y = n.getY(); final Location loc = this.ptLocator.locate(geometry, x, y); n.getLabel().setAllLocations(targetIndex, loc); // debugPrintln(n.getLabel()); } /** * Isolated nodes are nodes whose labels are incomplete * (e.g. the location for one Geometry is null). * This is the case because nodes in one graph which don't intersect * nodes in the other are not completely labelled by the initial process * of adding nodes to the nodeList. * To complete the labelling we need to check for nodes that lie in the * interior of edges, and in the interior of areas. */ private void labelIsolatedNodes() { for (final Object element : this.nodes) { final Node n = (Node)element; final Label label = n.getLabel(); // isolated nodes should always have at least one geometry in their label Assert.isTrue(label.getGeometryCount() > 0, "node with empty label found"); if (n.isIsolated()) { if (label.isNull(0)) { labelIsolatedNode(n, 0); } else { labelIsolatedNode(n, 1); } } } } private void labelNodeEdges() { for (final Object element : this.nodes) { final RelateNode node = (RelateNode)element; node.getEdges().computeLabelling(this.arg); // Debug.print(node.getEdges()); // node.print(System.out); } } /** * update the IM with the sum of the IMs for each component */ private void updateIM(final IntersectionMatrix im) { // Debug.println(im); for (final Object element : this.isolatedEdges) { final Edge e = (Edge)element; e.updateIM(im); // Debug.println(im); } for (final Object element : this.nodes) { final RelateNode node = (RelateNode)element; node.updateIM(im); // Debug.println(im); node.updateIMFromEdges(im); // Debug.println(im); // node.print(System.out); } } }
Java
public class PhotonicMigrate { public static void migrateBlocks(MissingMappings<Block> event) { for (RegistryEvent.MissingMappings.Mapping<Block> missing: event.getMappings()) { if (missing.key.getResourceDomain().equals(ModPhotonicCraft.MODID)) { if (missing.key.getResourcePath().equals("bariumore")) { missing.remap(PhotonicBlocks.rheniumOre); } else if (missing.key.getResourcePath().equals("bariumblock")) { missing.remap(PhotonicBlocks.rheniumBlock); } } } } public static void migrateItems(MissingMappings<Item> event) { for (RegistryEvent.MissingMappings.Mapping<Item> missing: event.getMappings()) { if (missing.key.getResourceDomain().equals(ModPhotonicCraft.MODID)) { if (missing.key.getResourcePath().equals("bariumore")) { missing.remap(Item.getItemFromBlock(PhotonicBlocks.rheniumOre)); } else if (missing.key.getResourcePath().equals("bariumblock")) { missing.remap(Item.getItemFromBlock(PhotonicBlocks.rheniumBlock)); } else if (missing.key.getResourcePath().equals("bariumingot")) { missing.remap(PhotonicItems.photonicResources2[6]); } } } } private PhotonicMigrate() {} }
Java
class TransactionFactoryTenant extends TransactionFactory { private final DataSourceSupplier dataSourceSupplier; private final CurrentTenantProvider tenantProvider; TransactionFactoryTenant(TransactionManager manager, DataSourceSupplier dataSourceSupplier, CurrentTenantProvider tenantProvider) { super(manager); this.dataSourceSupplier = dataSourceSupplier; this.tenantProvider = tenantProvider; } @Override public SpiTransaction createQueryTransaction(Object tenantId) { return create(false, tenantId); } @Override public SpiTransaction createTransaction(boolean explicit, int isolationLevel) { SpiTransaction t = create(explicit, null); return setIsolationLevel(t, explicit, isolationLevel); } private SpiTransaction create(boolean explicit, Object tenantId) { Connection c = null; try { if (tenantId == null) { // tenantId not set (by lazy loading) so get current tenantId tenantId = tenantProvider.currentId(); } c = dataSourceSupplier.getConnection(tenantId); SpiTransaction transaction = manager.createTransaction(explicit, c, counter.incrementAndGet()); transaction.setTenantId(tenantId); return transaction; } catch (PersistenceException ex) { JdbcClose.close(c); throw ex; } catch (SQLException ex) { throw new PersistenceException(ex); } } }
Java
public final class BlobBatchStorageException extends HttpResponseException { private final Iterable<BlobStorageException> exceptions; BlobBatchStorageException(String message, HttpResponse response, Iterable<BlobStorageException> exceptions) { super(message, response); this.exceptions = exceptions; } /** * Gets all the exceptions thrown in a single batch request. * * @return All the exceptions thrown in a single batch request. */ public Iterable<BlobStorageException> getBatchExceptions() { return exceptions; } }
Java
public class DatasetChecker { private CheckerMessageHandler msgHandler; private KnownDataTypes knownUserDataTypes; /** * @param userDataTypes * all known user data types * @param checkerMessageHandler * handler for automated data checker messages * * @throws IllegalArgumentException * if either argument is null, or if there are no user data types given */ public DatasetChecker(KnownDataTypes userDataTypes, CheckerMessageHandler checkerMessageHandler) throws IllegalArgumentException { if ( (userDataTypes == null) || userDataTypes.isEmpty() ) throw new IllegalArgumentException("no known user data types"); if ( checkerMessageHandler == null ) throw new IllegalArgumentException("no message handler given to the dataset checker"); knownUserDataTypes = userDataTypes; msgHandler = checkerMessageHandler; } /** * Interprets the data string representations and standardizes, if required, these data values * for given dataset. Performs the automated data checks on these data values. Saves the messages * generated from these steps and assigns the automated data checker WOCE flags from these messages. * <p> * The given dataset object is updated with the set of checker QC flags, the set of user-provided * QC flags, the number of rows with errors (not marked by the PI), the number of rows with warnings * (not marked by the PI), and the current data check status. * <p> * The given metadata object, if not null, it is updated with values that can be derived from the data: * western-most longitude, eastern-most longitude, southern-most latitude, northern-most latitude, * start time, and end time. * * @param dataset * dataset data to check; various fields will be updated by this method * @param metadata * metadata to update; can be null * * @return standardized user data array of checked values * * @throws IllegalArgumentException * if there are no data values, * if a data column description is not a known user data type, * if a required unit conversion is not supported, * if a standardizer for a given data type is not known, * if .... */ public StdUserDataArray standardizeDataset(DashboardDatasetData dataset, DsgMetadata metadata) throws IllegalArgumentException { // Generate array of standardized data objects StdUserDataArray stdUserData = new StdUserDataArray(dataset, knownUserDataTypes); // Check for missing lon/lat/time Double[] sampleTimes = stdUserData.checkMissingLonLatTime(); // Check that the data is ordered in time; speeds and time gaps are not excessive. // Generate errors where this is not the case. if ( sampleTimes != null ) stdUserData.checkDataOrder(sampleTimes); // Bounds check the standardized data values stdUserData.checkBounds(); // Any metadata values given in data columns must be consistent (constant or missing) stdUserData.checkMetadataTypeValues(); // TODO: Perform any other data checks? // Save the messages accumulated in stdUserData. // Assigns the StdUserData WOCE_AUTOCHECK data column with the checker-generated data QC flags. // Assigns the DashboardDataset sets of checker-generated and user-provided data QC flags. msgHandler.processCheckerMessages(dataset, stdUserData); // Get the indices values the PI marked as bad or questionable. boolean hasCriticalError = false; HashSet<RowColumn> userErrs = new HashSet<RowColumn>(); HashSet<RowColumn> userWarns = new HashSet<RowColumn>(); for (DataQCFlag wtype : dataset.getUserFlags()) { if ( Severity.CRITICAL.equals(wtype.getSeverity()) ) { hasCriticalError = true; userErrs.add(new RowColumn(wtype.getRowIndex(), wtype.getColumnIndex())); } else if ( Severity.ERROR.equals(wtype.getSeverity()) ) { userErrs.add(new RowColumn(wtype.getRowIndex(), wtype.getColumnIndex())); } else if ( Severity.WARNING.equals(wtype.getSeverity()) ) { userWarns.add(new RowColumn(wtype.getRowIndex(), wtype.getColumnIndex())); } } // Get the indices of data rows the automated data checker // found having errors not not detected by the PI. HashSet<Integer> errRows = new HashSet<Integer>(); for (DataQCFlag wtype : dataset.getCheckerFlags()) { if ( Severity.CRITICAL.equals(wtype.getSeverity()) ) { hasCriticalError = true; RowColumn rowCol = new RowColumn(wtype.getRowIndex(), wtype.getColumnIndex()); if ( !userErrs.contains(rowCol) ) errRows.add(wtype.getRowIndex()); } if ( Severity.ERROR.equals(wtype.getSeverity()) ) { RowColumn rowCol = new RowColumn(wtype.getRowIndex(), wtype.getColumnIndex()); if ( !userErrs.contains(rowCol) ) errRows.add(wtype.getRowIndex()); } } // Get the indices of data rows the automated data checker // found having only warnings but not detected by the PI. HashSet<Integer> warnRows = new HashSet<Integer>(); for (DataQCFlag wtype : dataset.getCheckerFlags()) { if ( Severity.WARNING.equals(wtype.getSeverity()) ) { RowColumn rowCol = new RowColumn(wtype.getRowIndex(), wtype.getColumnIndex()); Integer rowIdx = wtype.getRowIndex(); if ( !(userErrs.contains(rowCol) || userWarns.contains(rowCol) || errRows.contains(rowIdx)) ) warnRows.add(rowIdx); } } int numErrorRows = errRows.size(); int numWarnRows = warnRows.size(); dataset.setNumErrorRows(numErrorRows); dataset.setNumWarnRows(numWarnRows); // Assign the data-check status message using the results of the sanity check if ( hasCriticalError ) { dataset.setDataCheckStatus(DashboardUtils.CHECK_STATUS_UNACCEPTABLE); } else if ( numErrorRows > 0 ) { dataset.setDataCheckStatus(DashboardUtils.CHECK_STATUS_ERRORS_PREFIX + Integer.toString(numErrorRows) + " errors"); } else if ( numWarnRows > 0 ) { dataset.setDataCheckStatus(DashboardUtils.CHECK_STATUS_WARNINGS_PREFIX + Integer.toString(numWarnRows) + " warnings"); } else { dataset.setDataCheckStatus(DashboardUtils.CHECK_STATUS_ACCEPTABLE); } if ( metadata != null ) { for (RowColumn rowCol : userErrs) { errRows.add(rowCol.getRow()); } Double[] sampleLongitudes = stdUserData.getSampleLongitudes(); Double[] sampleLatitudes = stdUserData.getSampleLatitudes(); metadata.assignLonLatTimeLimits(sampleLongitudes, sampleLatitudes, sampleTimes, errRows); } return stdUserData; } }
Java
public class Duration implements Comparable<Duration>, Serializable { /** * The duration, in milliseconds. */ private final long duration; /** * Constructs a Duration from a specified start date to an end date. * * @param start the starting instance * @param end the ending instance */ public Duration(@NotNull Date start, @NotNull Date end) { long difference = end.getTime() - start.getTime(); if (difference >= 0) { duration = difference; } else { throw new IllegalArgumentException("end is before start."); } } /** * Constructs a Duration from the specified duration, in milliseconds. * * @param duration the duration, in milliseconds */ Duration(long duration) { this.duration = duration; } public long getSeconds() { return duration / 1000; } @Override public int compareTo(@NotNull Duration duration) { return Long.compare(this.duration, duration.duration); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } Duration duration = (Duration) object; return this.duration == duration.duration; } @Override public int hashCode() { return (int) (duration ^ (duration >>> 32)); } @Override public String toString() { if (duration < DungeonTimeUnit.DAY.milliseconds) { return "Less than a day"; } TimeStringBuilder builder = new TimeStringBuilder(); int years = DungeonMath.safeCastLongToInteger(duration / DungeonTimeUnit.YEAR.milliseconds); long monthsLong = (duration % DungeonTimeUnit.YEAR.milliseconds) / DungeonTimeUnit.MONTH.milliseconds; int months = DungeonMath.safeCastLongToInteger(monthsLong); long daysLong = (duration % DungeonTimeUnit.MONTH.milliseconds) / DungeonTimeUnit.DAY.milliseconds; int days = DungeonMath.safeCastLongToInteger(daysLong); builder.set(DungeonTimeUnit.YEAR, years); builder.set(DungeonTimeUnit.MONTH, months); builder.set(DungeonTimeUnit.DAY, days); return builder.toString(); } }
Java
public class ConfigDetectDescribe implements Configuration { /** The feature descriptor is used. Not always used. */ public ConfigDescribeRegion.Type typeDescribe = ConfigDescribeRegion.Type.SURF_FAST; /** The feature detector is used. Not always used. */ public ConfigDetectInterestPoint.Type typeDetector = ConfigDetectInterestPoint.Type.FAST_HESSIAN; /** Describes the scale-space used by SIFT detector / descriptor. */ public ConfigSiftScaleSpace scaleSpaceSift = new ConfigSiftScaleSpace(); public ConfigSurfDescribe.Fast describeSurfFast = new ConfigSurfDescribe.Fast(); public ConfigSurfDescribe.Stability describeSurfStability = new ConfigSurfDescribe.Stability(); public ConfigSiftDescribe describeSift = new ConfigSiftDescribe(); public ConfigBrief describeBrief = new ConfigBrief(false); public ConfigTemplateDescribe describeTemplate = new ConfigTemplateDescribe(); /** Configuration for point based detectors (e.g. corners and blob) */ public ConfigPointDetector detectPoint = new ConfigPointDetector(); /** Fast Hessian scale invariant blob detector. This is what SURF uses */ public ConfigFastHessian detectFastHessian = new ConfigFastHessian(); /** SIFT scale invariant blob detector */ public ConfigSiftDetector detectSift = new ConfigSiftDetector(); /** Configuration for estimating the region's orientation */ public ConfigOrientation2 orientation = new ConfigOrientation2(); /** Convert the descriptor into a different format */ public ConfigConvertTupleDesc convertDescriptor = new ConfigConvertTupleDesc(); public void copyRefTo( ConfigDescribeRegion dst ) { dst.type = this.typeDescribe; dst.scaleSpaceSift = this.scaleSpaceSift; dst.template = this.describeTemplate; dst.surfFast = this.describeSurfFast; dst.surfStability = this.describeSurfStability; dst.brief = this.describeBrief; dst.sift = this.describeSift; } /** * Returns the non-max radius for the selected configuration */ public int findNonMaxRadius() { return switch (typeDetector) { case POINT -> detectPoint.general.radius; case FAST_HESSIAN -> detectFastHessian.extract.radius; case SIFT -> detectSift.extract.radius; }; } public void copyRefFrom( ConfigDescribeRegion src ) { this.typeDescribe = src.type; this.scaleSpaceSift = src.scaleSpaceSift; this.describeTemplate = src.template; this.describeSurfFast = src.surfFast; this.describeSurfStability = src.surfStability; this.describeBrief = src.brief; this.describeSift = src.sift; } @Override public void checkValidity() { scaleSpaceSift.checkValidity(); describeSurfFast.checkValidity(); describeSurfStability.checkValidity(); describeSift.checkValidity(); describeBrief.checkValidity(); describeTemplate.checkValidity(); detectPoint.checkValidity(); detectFastHessian.checkValidity(); detectSift.checkValidity(); convertDescriptor.checkValidity(); } public void setTo( ConfigDetectDescribe src ) { this.typeDescribe = src.typeDescribe; this.typeDetector = src.typeDetector; this.scaleSpaceSift.setTo(src.scaleSpaceSift); this.describeSurfFast.setTo(src.describeSurfFast); this.describeSurfStability.setTo(src.describeSurfStability); this.describeSift.setTo(src.describeSift); this.describeBrief.setTo(src.describeBrief); this.describeTemplate.setTo(src.describeTemplate); this.detectPoint.setTo(src.detectPoint); this.detectFastHessian.setTo(src.detectFastHessian); this.detectSift.setTo(src.detectSift); this.convertDescriptor.setTo(src.convertDescriptor); } public ConfigDetectDescribe copy() { var out = new ConfigDetectDescribe(); out.setTo(this); return out; } }
Java
public class PersonDetailsPanel extends UiPart<Region> { private static final String FXML = "person/PersonDetailsPanel.fxml"; private ReadOnlyPerson person; @FXML private Label name; @FXML private ImageView avatar; @FXML private ListView<Label> propertyListKeys; @FXML private ListView<Label> propertyListValues; public PersonDetailsPanel(ReadOnlyPerson person) { super(FXML); this.person = person; name.textProperty().bind(Bindings.convert(person.nameProperty())); person.avatarProperty().addListener((observable, oldValue, newValue) -> setAvatar()); setAvatar(); person.properties().addListener((observable, oldValue, newValue) -> bindProperties()); bindProperties(); } /** * Binds all properties of this person to a {@link ListView} of key-value pairs. */ private void bindProperties() { List<Label> keys = new ArrayList<>(); List<Label> values = new ArrayList<>(); person.getSortedProperties().forEach(property -> { Label newPropertyKey = new PropertyLabel(property.getFullName() + ":", "details-property-key"); Label newPropertyValue = new PropertyLabel(property.getValue(), "details-property-value"); keys.add(newPropertyKey); values.add(newPropertyValue); }); propertyListKeys.setItems(FXCollections.observableList(keys)); propertyListValues.setItems(FXCollections.observableList(values)); } /** * Displays the avatar of the person if the {@code avatar} has been set before. */ private void setAvatar() { if (person.getAvatar() != null) { Platform.runLater(() -> avatar.setImage(new Image(person.getAvatar().getUri(), 200, 200, false, true))); } } }
Java
public class PreferencesService { private final AdminEventPublisher adminEventPublisher; private final TransactionRunner transactionRunner; @Inject public PreferencesService(MessagingService messagingService, CConfiguration cConf, TransactionRunner transactionRunner) { MultiThreadMessagingContext messagingContext = new MultiThreadMessagingContext(messagingService); this.adminEventPublisher = new AdminEventPublisher(cConf, messagingContext); this.transactionRunner = transactionRunner; } private Map<String, String> getConfigProperties(EntityId entityId) { return TransactionRunners.run(transactionRunner, context -> { return new PreferencesTable(context).getPreferences(entityId); }); } private Map<String, String> getConfigResolvedProperties(EntityId entityId) { return TransactionRunners.run(transactionRunner, context -> { return new PreferencesTable(context).getResolvedPreferences(entityId); }); } /** * Validate the profile status is enabled and set the preferences in same transaction */ private void setConfig(EntityId entityId, Map<String, String> propertyMap) throws NotFoundException, ProfileConflictException, BadRequestException { TransactionRunners.run(transactionRunner, context -> { ProfileStore profileStore = ProfileStore.get(context); PreferencesTable preferencesTable = new PreferencesTable(context); setConfig(profileStore, preferencesTable, entityId, propertyMap); }, NotFoundException.class, ProfileConflictException.class, BadRequestException.class); } /** * Validate the profile status is enabled and set the preferences */ private void setConfig(ProfileStore profileStore, PreferencesTable preferencesTable, EntityId entityId, Map<String, String> propertyMap) throws NotFoundException, ProfileConflictException, BadRequestException, IOException { boolean isInstanceLevel = entityId.getEntityType().equals(EntityType.INSTANCE); NamespaceId namespaceId = isInstanceLevel ? NamespaceId.SYSTEM : ((NamespacedEntityId) entityId).getNamespaceId(); // validate the profile and publish the necessary metadata change if the profile exists in the property Optional<ProfileId> profile = SystemArguments.getProfileIdFromArgs(namespaceId, propertyMap); if (profile.isPresent()) { ProfileId profileId = profile.get(); // if it is instance level set, the profile has to be in SYSTEM scope, so throw BadRequestException when // setting a USER scoped profile if (isInstanceLevel && !propertyMap.get(SystemArguments.PROFILE_NAME).startsWith(EntityScope.SYSTEM.name())) { throw new BadRequestException(String.format("Cannot set profile %s at the instance level. " + "Only system profiles can be set at the instance level. " + "The profile property must look like SYSTEM:[profile-name]", propertyMap.get(SystemArguments.PROFILE_NAME))); } if (profileStore.getProfile(profileId).getStatus() == ProfileStatus.DISABLED) { throw new ProfileConflictException(String.format("Profile %s in namespace %s is disabled. It cannot be " + "assigned to any programs or schedules", profileId.getProfile(), profileId.getNamespace()), profileId); } } // need to get old property and check if it contains profile information Map<String, String> oldProperties = preferencesTable.getPreferences(entityId); // get the old profile information from the previous properties Optional<ProfileId> oldProfile = SystemArguments.getProfileIdFromArgs(namespaceId, oldProperties); long seqId = preferencesTable.setPreferences(entityId, propertyMap); // After everything is set, publish the update message and add the association if profile is present if (profile.isPresent()) { profileStore.addProfileAssignment(profile.get(), entityId); } // if old properties has the profile, remove the association if (oldProfile.isPresent()) { profileStore.removeProfileAssignment(oldProfile.get(), entityId); } // if new profiles do not have profile information but old profiles have, it is same as deletion of the profile if (profile.isPresent()) { adminEventPublisher.publishProfileAssignment(entityId, seqId); } else if (oldProfile.isPresent()) { adminEventPublisher.publishProfileUnAssignment(entityId, seqId); } } private void deleteConfig(EntityId entityId) { TransactionRunners.run(transactionRunner, context -> { PreferencesTable dataset = new PreferencesTable(context); Map<String, String> oldProp = dataset.getPreferences(entityId); NamespaceId namespaceId = entityId.getEntityType().equals(EntityType.INSTANCE) ? NamespaceId.SYSTEM : ((NamespacedEntityId) entityId).getNamespaceId(); Optional<ProfileId> oldProfile = SystemArguments.getProfileIdFromArgs(namespaceId, oldProp); long seqId = dataset.deleteProperties(entityId); // if there is profile properties, publish the message to update metadata and remove the assignment if (oldProfile.isPresent()) { ProfileStore.get(context).removeProfileAssignment(oldProfile.get(), entityId); adminEventPublisher.publishProfileUnAssignment(entityId, seqId); } }); } /** * Get instance level preferences */ public Map<String, String> getProperties() { return getConfigProperties(new InstanceId("")); } /** * Get namespace level preferences */ public Map<String, String> getProperties(NamespaceId namespaceId) { return getConfigProperties(namespaceId); } /** * Get app level preferences */ public Map<String, String> getProperties(ApplicationId applicationId) { return getConfigProperties(applicationId); } /** * Get program level preferences */ public Map<String, String> getProperties(ProgramId programId) { return getConfigProperties(programId); } /** * Get instance level resolved preferences */ public Map<String, String> getResolvedProperties() { return getConfigResolvedProperties(new InstanceId("")); } /** * Get namespace level resolved preferences */ public Map<String, String> getResolvedProperties(NamespaceId namespaceId) { return getConfigResolvedProperties(namespaceId); } /** * Get app level resolved preferences */ public Map<String, String> getResolvedProperties(ApplicationId appId) { return getConfigResolvedProperties(appId); } /** * Get program level resolved preferences */ public Map<String, String> getResolvedProperties(ProgramId programId) { return getConfigResolvedProperties(programId); } /** * Set instance level preferences */ public void setProperties(Map<String, String> propMap) throws NotFoundException, ProfileConflictException, BadRequestException { setConfig(new InstanceId(""), propMap); } /** * Set instance level preferences if they are not already set. Only adds the properties that don't already exist. * * @param properties the preferences to add * @return the preference keys that were added */ public Set<String> addProperties(Map<String, String> properties) throws NotFoundException, ProfileConflictException, BadRequestException { InstanceId instanceId = new InstanceId(""); Set<String> added = new HashSet<>(); TransactionRunners.run(transactionRunner, context -> { ProfileStore profileStore = ProfileStore.get(context); PreferencesTable preferencesTable = new PreferencesTable(context); Map<String, String> oldProperties = preferencesTable.getPreferences(instanceId); Map<String, String> newProperties = new HashMap<>(properties); added.addAll(Sets.difference(newProperties.keySet(), oldProperties.keySet())); newProperties.putAll(oldProperties); setConfig(profileStore, preferencesTable, instanceId, newProperties); }, NotFoundException.class, ProfileConflictException.class, BadRequestException.class); return added; } /** * Set namespace level preferences */ public void setProperties(NamespaceId namespaceId, Map<String, String> propMap) throws NotFoundException, ProfileConflictException, BadRequestException { setConfig(namespaceId, propMap); } /** * Set app level preferences */ public void setProperties(ApplicationId appId, Map<String, String> propMap) throws NotFoundException, ProfileConflictException, BadRequestException { setConfig(appId, propMap); } /** * Set program level preferences */ public void setProperties(ProgramId programId, Map<String, String> propMap) throws NotFoundException, ProfileConflictException, BadRequestException { setConfig(programId, propMap); } /** * Delete instance level preferences */ public void deleteProperties() { deleteConfig(new InstanceId("")); } /** * Delete namespace level preferences */ public void deleteProperties(NamespaceId namespaceId) { deleteConfig(namespaceId); } /** * Delete app level preferences */ public void deleteProperties(ApplicationId appId) { deleteConfig(appId); } /** * Delete program level preferences */ public void deleteProperties(ProgramId programId) { deleteConfig(programId); } }
Java
public class DvdLibraryException extends RuntimeException { private static final long serialVersionUID = 1L; public DvdLibraryException(String message) { super(message); } }
Java
public abstract class DelegatingDeserializer extends StdDeserializer<Object> implements ContextualDeserializer, ResolvableDeserializer { private static final long serialVersionUID = 1L; protected final JsonDeserializer<?> _delegatee; /* /********************************************************************** /* Construction /********************************************************************** */ public DelegatingDeserializer(JsonDeserializer<?> delegatee) { super(_figureType(delegatee)); _delegatee = delegatee; } protected abstract JsonDeserializer<?> newDelegatingInstance(JsonDeserializer<?> newDelegatee); private static Class<?> _figureType(JsonDeserializer<?> deser) { Class<?> cls = deser.handledType(); if (cls != null) { return cls; } return Object.class; } /* /********************************************************************** /* Overridden methods for contextualization, resolving /********************************************************************** */ @Override public void resolve(DeserializationContext ctxt) throws JsonMappingException { if (_delegatee instanceof ResolvableDeserializer) { ((ResolvableDeserializer) _delegatee).resolve(ctxt); } } @Override public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { JavaType vt = ctxt.constructType(_delegatee.handledType()); JsonDeserializer<?> del = ctxt.handleSecondaryContextualization(_delegatee, property, vt); if (del == _delegatee) { return this; } return newDelegatingInstance(del); } /** * @deprecated Since 2.3, use {@link #newDelegatingInstance} instead */ @Deprecated protected JsonDeserializer<?> _createContextual(DeserializationContext ctxt, BeanProperty property, JsonDeserializer<?> newDelegatee) { if (newDelegatee == _delegatee) { return this; } return newDelegatingInstance(newDelegatee); } @Override public SettableBeanProperty findBackReference(String logicalName) { // [Issue#253]: Hope this works.... return _delegatee.findBackReference(logicalName); } /* /********************************************************************** /* Overridden deserialization methods /********************************************************************** */ @Override public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { return _delegatee.deserialize(jp, ctxt); } @SuppressWarnings("unchecked") @Override public Object deserialize(JsonParser jp, DeserializationContext ctxt, Object intoValue) throws IOException, JsonProcessingException { return ((JsonDeserializer<Object>)_delegatee).deserialize(jp, ctxt, intoValue); } @Override public Object deserializeWithType(JsonParser jp, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException { return _delegatee.deserializeWithType(jp, ctxt, typeDeserializer); } /* /********************************************************************** /* Overridden other methods /********************************************************************** */ @Override public JsonDeserializer<?> replaceDelegatee(JsonDeserializer<?> delegatee) { if (delegatee == _delegatee) { return this; } return newDelegatingInstance(delegatee); } @Override public Object getNullValue() { return _delegatee.getNullValue(); } @Override public Object getEmptyValue() { return _delegatee.getEmptyValue(); } @Override public Collection<Object> getKnownPropertyNames() { return _delegatee.getKnownPropertyNames(); } @Override public boolean isCachable() { return _delegatee.isCachable(); } @Override public ObjectIdReader getObjectIdReader() { return _delegatee.getObjectIdReader(); } @Override public JsonDeserializer<?> getDelegatee() { return _delegatee; } }
Java
public class PropAbsolute extends Propagator<IntVar> { protected RemProc rem_proc; protected IIntDeltaMonitor[] idms; protected IntVar X, Y; protected boolean bothEnumerated; public PropAbsolute(IntVar X, IntVar Y) { super(ArrayUtils.toArray(X, Y), PropagatorPriority.BINARY, true); this.X = vars[0]; this.Y = vars[1]; bothEnumerated = X.hasEnumeratedDomain() && Y.hasEnumeratedDomain(); if (bothEnumerated) { rem_proc = new RemProc(); this.idms = new IIntDeltaMonitor[this.vars.length]; for (int i = 0; i < this.vars.length; i++) { idms[i] = vars[i].hasEnumeratedDomain() ? this.vars[i].monitorDelta(this) : IIntDeltaMonitor.Default.NONE; } } } @Override public int getPropagationConditions(int vIdx) { if (bothEnumerated) { return IntEventType.all(); } else { return IntEventType.boundAndInst(); } } @Override public ESat isEntailed() { if (vars[0].getUB() < 0) { return ESat.FALSE; } else if (vars[0].isInstantiated()) { if (vars[1].isInstantiated()) { return ESat.eval(vars[0].getValue() == Math.abs(vars[1].getValue())); } else if (vars[1].getDomainSize() == 2 && vars[1].contains(vars[0].getValue()) && vars[1].contains(-vars[0].getValue())) { return ESat.TRUE; } else if (!vars[1].contains(vars[0].getValue()) && !vars[1].contains(-vars[0].getValue())) { return ESat.FALSE; } else { return ESat.UNDEFINED; } } else { return ESat.UNDEFINED; } } @Override public String toString() { return String.format("%s = |%s|", vars[0].toString(), vars[1].toString()); } //*********************************************************************************** // FILTERING //*********************************************************************************** @Override public void propagate(int evtmask) throws ContradictionException { X.updateLowerBound(0, aCause); setBounds(); if (bothEnumerated) { enumeratedFiltering(); idms[0].unfreeze(); idms[1].unfreeze(); } } @Override public void propagate(int varIdx, int mask) throws ContradictionException { if (bothEnumerated) { idms[varIdx].freeze(); idms[varIdx].forEachRemVal(rem_proc.set(varIdx)); idms[varIdx].unfreeze(); } else { setBounds(); } } private void setBounds() throws ContradictionException { // X = |Y| int max = X.getUB(); int min = X.getLB(); Y.updateUpperBound(max, aCause); Y.updateLowerBound(-max, aCause); Y.removeInterval(1 - min, min - 1, aCause); ///////////////////////////////////////////////// int prevLB = X.getLB(); int prevUB = X.getUB(); min = Y.getLB(); max = Y.getUB(); if (max <= 0) { X.updateLowerBound(-max, aCause); X.updateUpperBound(-min, aCause); } else if (min >= 0) { X.updateLowerBound(min, aCause); X.updateUpperBound(max, aCause); } else { if (Y.hasEnumeratedDomain()) { int mP = Y.nextValue(-1); int mN = -Y.previousValue(1); X.updateLowerBound(Math.min(mP, mN), aCause); } X.updateUpperBound(Math.max(-min, max), aCause); } if (prevLB != X.getLB() || prevUB != X.getUB()) setBounds(); } private void enumeratedFiltering() throws ContradictionException { int min = X.getLB(); int max = X.getUB(); for (int v = min; v <= max; v = X.nextValue(v)) { if (!(Y.contains(v) || Y.contains(-v))) { X.removeValue(v, aCause); } } min = Y.getLB(); max = Y.getUB(); for (int v = min; v <= max; v = Y.nextValue(v)) { if (!(X.contains(Math.abs(v)))) { Y.removeValue(v, aCause); } } } private class RemProc implements UnaryIntProcedure<Integer> { private int var; @Override public UnaryIntProcedure set(Integer idxVar) { this.var = idxVar; return this; } @Override public void execute(int val) throws ContradictionException { if (var == 0) { vars[1].removeValue(val, aCause); vars[1].removeValue(-val, aCause); } else { if (!vars[1].contains(-val)) vars[0].removeValue(Math.abs(val), aCause); } } } //*********************************************************************************** // EXPLANATIONS //*********************************************************************************** @Override public void explain(ExplanationEngine xengine, Deduction d, Explanation e) { if (d.getVar() == vars[0]) { e.add(xengine.getPropagatorActivation(this)); if (d.getmType() == Deduction.Type.ValRem) { vars[1].explain(xengine, VariableState.REM, ((ValueRemoval) d).getVal(), e); vars[1].explain(xengine, VariableState.REM, -((ValueRemoval) d).getVal(), e); } else { throw new UnsupportedOperationException("PropAbsolute only knows how to explain ValueRemovals"); } } else if (d.getVar() == vars[1]) { e.add(xengine.getPropagatorActivation(this)); if (d.getmType() == Deduction.Type.ValRem) { vars[0].explain(xengine, VariableState.REM, Math.abs(((ValueRemoval) d).getVal()), e); } else { throw new UnsupportedOperationException("PropAbsolute only knows how to explain ValueRemovals"); } } else { super.explain(xengine, d, e); } } @Override public void duplicate(Solver solver, THashMap<Object, Object> identitymap) { if (!identitymap.containsKey(this)) { this.vars[0].duplicate(solver, identitymap); IntVar X = (IntVar) identitymap.get(this.vars[0]); this.vars[1].duplicate(solver, identitymap); IntVar Y = (IntVar) identitymap.get(this.vars[1]); identitymap.put(this, new PropAbsolute(X, Y)); } } }
Java
@OpMetadata( opType = PrelinearizeTuple.OP_NAME, inputsClass = PrelinearizeTuple.Inputs.class ) public final class PrelinearizeTuple extends RawOp implements Operand<TType> { /** * The name of this op, as known by TensorFlow core engine */ public static final String OP_NAME = "PrelinearizeTuple"; private Output<? extends TType> output; @SuppressWarnings("unchecked") public PrelinearizeTuple(Operation operation) { super(operation, OP_NAME); int outputIdx = 0; output = operation.output(outputIdx++); } /** * Factory method to create a class wrapping a new PrelinearizeTuple operation. * * @param scope current scope * @param inputs A list of tensors that will be provided using the infeed mechanism. * @param shapes The shapes of each tensor in {@code inputs}. * @param options carries optional attribute values * @return a new instance of PrelinearizeTuple */ @Endpoint( describeByClass = true ) public static PrelinearizeTuple create(Scope scope, Iterable<Operand<?>> inputs, List<Shape> shapes, Options... options) { OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "PrelinearizeTuple"); opBuilder.addInputList(Operands.asOutputs(inputs)); Shape[] shapesArray = new Shape[shapes.size()]; for (int i = 0 ; i < shapesArray.length ; i++) { shapesArray[i] = shapes.get(i); } opBuilder.setAttr("shapes", shapesArray); if (options != null) { for (Options opts : options) { if (opts.layouts != null) { long[] layoutsArray = new long[opts.layouts.size()]; for (int i = 0 ; i < layoutsArray.length ; i++) { layoutsArray[i] = opts.layouts.get(i); } opBuilder.setAttr("layouts", layoutsArray); } } } return new PrelinearizeTuple(opBuilder.build()); } /** * Sets the layouts option. * * @param layouts A vector holding the requested layout in minor-to-major sequence for all the * tuple shapes in the order the shapes appear in the &quot;shapes&quot; input. The layout * elements for a sub-shape can be set to -1 in which case the corresponding layout * will be computed by the infeed operation. * @return this Options instance. */ public static Options layouts(List<Long> layouts) { return new Options().layouts(layouts); } /** * Sets the layouts option. * * @param layouts A vector holding the requested layout in minor-to-major sequence for all the * tuple shapes in the order the shapes appear in the &quot;shapes&quot; input. The layout * elements for a sub-shape can be set to -1 in which case the corresponding layout * will be computed by the infeed operation. * @return this Options instance. */ public static Options layouts(Long... layouts) { return new Options().layouts(layouts); } /** * Gets output. * * @return output. */ public Output<? extends TType> output() { return output; } @Override @SuppressWarnings("unchecked") public Output<TType> asOutput() { return (Output<TType>) output; } /** * Optional attributes for {@link org.tensorflow.op.tpu.PrelinearizeTuple} */ public static class Options { private List<Long> layouts; private Options() { } /** * Sets the layouts option. * * @param layouts A vector holding the requested layout in minor-to-major sequence for all the * tuple shapes in the order the shapes appear in the &quot;shapes&quot; input. The layout * elements for a sub-shape can be set to -1 in which case the corresponding layout * will be computed by the infeed operation. * @return this Options instance. */ public Options layouts(List<Long> layouts) { this.layouts = layouts; return this; } /** * Sets the layouts option. * * @param layouts A vector holding the requested layout in minor-to-major sequence for all the * tuple shapes in the order the shapes appear in the &quot;shapes&quot; input. The layout * elements for a sub-shape can be set to -1 in which case the corresponding layout * will be computed by the infeed operation. * @return this Options instance. */ public Options layouts(Long... layouts) { this.layouts = Arrays.asList(layouts); return this; } } @OpInputsMetadata( outputsClass = PrelinearizeTuple.class ) public static class Inputs extends RawOpInputs<PrelinearizeTuple> { /** * A list of tensors that will be provided using the infeed mechanism. */ public final Iterable<Operand<?>> inputs; /** * The element types of each element in `inputs`. */ public final DataType[] dtypes; /** * The shapes of each tensor in `inputs`. */ public final Shape[] shapes; /** * A vector holding the requested layout in minor-to-major sequence for all the * tuple shapes in the order the shapes appear in the "shapes" input. The layout * elements for a sub-shape can be set to -1 in which case the corresponding layout * will be computed by the infeed operation. */ public final long[] layouts; public Inputs(GraphOperation op) { super(new PrelinearizeTuple(op), op, Arrays.asList("dtypes", "shapes", "layouts")); int inputIndex = 0; int inputsLength = op.inputListLength("inputs"); inputs = Arrays.asList((Operand<?>[]) op.inputList(inputIndex, inputsLength)); inputIndex += inputsLength; dtypes = op.attributes().getAttrTypeList("dtypes"); shapes = op.attributes().getAttrShapeList("shapes"); layouts = op.attributes().getAttrIntList("layouts"); } } }
Java
public class RequestHandler implements Runnable { /** * A request handler uses a page reader to randomely generate * webpage names to request from the web server. */ private final WebServer ws; private final WebPageReader wpr; /** * A request handler should know to which web server requests * should be made. * * @param ws the webserver to which the request is made */ public RequestHandler(WebServer ws) { this.ws = ws; ConfigReader cfg = new ConfigReader("/webserver.properties"); this.wpr = new WebPageReader(cfg.get("webpages.file")); } /** * As an implementation of run method for thread class, this method * requests a random webpage from the web server. */ public void run() { this.ws.request(this.wpr.getPage()); } }
Java
public class Countdown { private int startTime; private boolean timerRunning = false; private int currentTime; public Countdown(int startTime) { this.startTime = startTime; } // call this method to start the timer public void startCountdown(){ //sets the time which keeps track of the countdown to the current time. if(timerRunning){ return; } timerRunning = true; currentTime = startTime; Timer timer = new Timer(); TimerTask task = new TimerTask() { // run() method to carry out the action of the task public void run() { currentTime--; if(currentTime <=0) { timerRunning = false; // cancel method to cancel the execution timer.cancel(); } }; }; timer.schedule(task, 1000, 1000); } public int getCurrentTime(){ return this.currentTime; } public void setTime(int newTime) { this.currentTime = newTime; } }
Java
public class CommitUtils { /** * Length of used for abbreviations */ public static final int LENGTH = 10; private static final NumberFormat FORMAT = NumberFormat .getIntegerInstance(); /** * Abbreviate commit sha to default length if longer * * @param commit * @return abbreviated sha */ public static String abbreviate(final RepositoryCommit commit) { return commit != null ? abbreviate(commit.getSha()) : null; } /** * Abbreviate commit sha to default length if longer * * @param commit * @return abbreviated sha */ public static String abbreviate(final Commit commit) { return commit != null ? abbreviate(commit.getSha()) : null; } /** * Abbreviate sha to default length if longer * * @param sha * @return abbreviated sha */ public static String abbreviate(final String sha) { if (!TextUtils.isEmpty(sha) && sha.length() > LENGTH) return sha.substring(0, LENGTH); else return sha; } /** * Is the given commit SHA-1 valid? * * @param sha * @return true if valid, false otherwise */ public static boolean isValidCommit(final String sha) { return !TextUtils.isEmpty(sha) && sha.matches("[a-fA-F0-9]+"); } /** * Get author of commit * <p> * This checks both the {@link RepositoryCommit} and the underlying * {@link Commit} to retrieve a name * * @param commit * @return author name or null if missing */ public static String getAuthor(final RepositoryCommit commit) { User author = commit.getAuthor(); if (author != null) return author.getLogin(); Commit rawCommit = commit.getCommit(); if (rawCommit == null) return null; CommitUser commitAuthor = rawCommit.getAuthor(); return commitAuthor != null ? commitAuthor.getName() : null; } /** * Get committer of commit * <p> * This checks both the {@link RepositoryCommit} and the underlying * {@link Commit} to retrieve a name * * @param commit * @return committer name or null if missing */ public static String getCommitter(final RepositoryCommit commit) { User committer = commit.getCommitter(); if (committer != null) return committer.getLogin(); Commit rawCommit = commit.getCommit(); if (rawCommit == null) return null; CommitUser commitCommitter = rawCommit.getCommitter(); return commitCommitter != null ? commitCommitter.getName() : null; } /** * Get author date of commit * * @param commit * @return author name or null if missing */ public static Date getAuthorDate(final RepositoryCommit commit) { Commit rawCommit = commit.getCommit(); if (rawCommit == null) return null; CommitUser commitAuthor = rawCommit.getAuthor(); return commitAuthor != null ? commitAuthor.getDate() : null; } /** * Get committer date of commit * * @param commit * @return author name or null if missing */ public static Date getCommitterDate(final RepositoryCommit commit) { Commit rawCommit = commit.getCommit(); if (rawCommit == null) return null; CommitUser commitCommitter = rawCommit.getCommitter(); return commitCommitter != null ? commitCommitter.getDate() : null; } /** * Bind commit author avatar to image view * * @param commit * @param avatars * @param view * @return view */ public static ImageView bindAuthor(final RepositoryCommit commit, final AvatarLoader avatars, final ImageView view) { User author = commit.getAuthor(); if (author != null) avatars.bind(view, author); else { Commit rawCommit = commit.getCommit(); if (rawCommit != null) avatars.bind(view, rawCommit.getAuthor()); } return view; } /** * Bind commit committer avatar to image view * * @param commit * @param avatars * @param view * @return view */ public static ImageView bindCommitter(final RepositoryCommit commit, final AvatarLoader avatars, final ImageView view) { User committer = commit.getCommitter(); if (committer != null) avatars.bind(view, committer); else { Commit rawCommit = commit.getCommit(); if (rawCommit != null) avatars.bind(view, rawCommit.getCommitter()); } return view; } /** * Get comment count * * @param commit * @return count */ public static String getCommentCount(final RepositoryCommit commit) { final Commit rawCommit = commit.getCommit(); if (rawCommit != null) return FORMAT.format(rawCommit.getCommentCount()); else return "0"; } /** * Format stats into {@link StyledText} * * @param files * @return styled text */ public static StyledText formatStats(final Collection<CommitFile> files) { StyledText fileDetails = new StyledText(); int added = 0; int deleted = 0; int changed = 0; if (files != null) for (CommitFile file : files) { added += file.getAdditions(); deleted += file.getDeletions(); changed++; } if (changed != 1) fileDetails.append(FORMAT.format(changed)).append(" changed files"); else fileDetails.append("1 changed file"); fileDetails.append(" with "); if (added != 1) fileDetails.append(FORMAT.format(added)).append(" additions"); else fileDetails.append("1 addition "); fileDetails.append(" and "); if (deleted != 1) fileDetails.append(FORMAT.format(deleted)).append(" deletions"); else fileDetails.append("1 deletion"); return fileDetails; } /** * Get file name for commit file * * @param file * @return last segment of commit file path */ public static String getName(final CommitFile file) { return file != null ? getName(file.getFilename()) : null; } /** * Get file name for path * * @param path * @return last segment of path */ public static String getName(final String path) { if (TextUtils.isEmpty(path)) return path; int lastSlash = path.lastIndexOf('/'); if (lastSlash != -1 && lastSlash + 1 < path.length()) return path.substring(lastSlash + 1); else return path; } }
Java
public class CustomFileSystemEntry extends FileSystemEntry{ @Override public String toString(){ return getName(this); } /** * returns the name of the folder or file. * @param entry * The Filesystementry the name of should be computed. * @return * Returns the past after the last slash. * If the path ends with a slash like root the slash is returned */ public static String getName(FileSystemEntry entry){ var path = entry.getPath(); return path.substring( Math.min(path.lastIndexOf('/') + 1, path.length() - 1)); } }
Java
public class BINDelta implements Loggable { private final DatabaseId dbId; // owning db for this bin. private long lastFullLsn; // location of last full version private final List<DeltaInfo> deltas; // list of key/action changes /** * Read a BIN and create the deltas. */ public BINDelta(BIN bin) { lastFullLsn = bin.getLastFullVersion(); dbId = bin.getDatabaseId(); deltas = new ArrayList<DeltaInfo>(); /* * Save every entry that has been modified since the last full version. * Note that we must rely on the dirty bit, and we can't infer any * dirtiness by comparing the last full version LSN and the child * reference LSN. That's because the ChildReference LSN may be earlier * than the full version LSN because of aborts. */ for (int i = 0; i < bin.getNEntries(); i++) { if (bin.isDirty(i)) { deltas.add(new DeltaInfo(bin.getKey(i), bin.getLsn(i), bin.getState(i))); } } } /** * For instantiating from the log. */ public BINDelta() { dbId = new DatabaseId(); lastFullLsn = DbLsn.NULL_LSN; deltas = new ArrayList<DeltaInfo>(); } /** * @return a count of deltas for this BIN. */ int getNumDeltas() { return deltas.size(); } /** * @return the dbId for this BIN. */ public DatabaseId getDbId() { return dbId; } /** * @return the last full version of this BIN */ public long getLastFullLsn() { return lastFullLsn; } /** * Create a BIN by starting with the full version and applying the deltas. */ public BIN reconstituteBIN(EnvironmentImpl env) throws DatabaseException { /* Get the last full version of this BIN. */ BIN fullBIN = (BIN) env.getLogManager().getEntryHandleFileNotFound(lastFullLsn); DatabaseImpl db = env.getDbTree().getDb(dbId); try { /* * In effect, call fullBIN.postFetchInit(db) here. But we don't * want to do that since it will put fullBIN on the INList. Since * this is either recovery or during the Cleaner run, we don't want * it on the INList. */ fullBIN.setDatabase(db); fullBIN.setLastFullLsn(lastFullLsn); /* Process each delta. */ fullBIN.latch(); for (int i = 0; i < deltas.size(); i++) { DeltaInfo info = deltas.get(i); /* * The BINDelta holds the authoritative version of each entry. * In all cases, its entry should supersede the entry in the * full BIN. This is true even if the BIN Delta's entry is * knownDeleted or if the full BIN's version is knownDeleted. * Therefore we use the flavor of findEntry that will return a * knownDeleted entry if the entry key matches (i.e. true, * false) but still indicates exact matches with the return * index. findEntry only returns deleted entries if third arg * is false, but we still need to know if it's an exact match * or not so indicateExact is true. */ int foundIndex = fullBIN.findEntry(info.getKey(), true, false); if (foundIndex >= 0 && (foundIndex & IN.EXACT_MATCH) != 0) { foundIndex &= ~IN.EXACT_MATCH; /* * The entry exists in the full version, update it with the * delta info. */ if (info.isKnownDeleted()) { fullBIN.setKnownDeleted(foundIndex); } else { fullBIN.updateEntry (foundIndex, info.getLsn(), info.getState()); } } else { /* * The entry doesn't exist, add a new entry from the delta. */ if (!info.isKnownDeleted()) { ChildReference entry = new ChildReference(null, info.getKey(), info.getLsn(), info.getState()); boolean insertOk = fullBIN.insertEntry(entry); assert insertOk; } } } } finally { env.getDbTree().releaseDb(db); } /* * Reset the generation to 0, all this manipulation might have driven * it up. */ fullBIN.setGeneration(0); fullBIN.releaseLatch(); return fullBIN; } /* * Logging support */ /* * @see Loggable#getLogSize() */ public int getLogSize() { int numDeltas = deltas.size(); int size = dbId.getLogSize() + // database id LogUtils.getPackedLongLogSize(lastFullLsn) + LogUtils.getPackedIntLogSize(numDeltas); for (int i = 0; i < numDeltas; i++) { // deltas DeltaInfo info = deltas.get(i); size += info.getLogSize(); } return size; } /* * @see Loggable#writeToLog */ public void writeToLog(ByteBuffer logBuffer) { dbId.writeToLog(logBuffer); // database id LogUtils.writePackedLong(logBuffer, lastFullLsn); // last version LogUtils.writePackedInt(logBuffer, deltas.size()); // num deltas for (int i = 0; i < deltas.size(); i++) { // deltas DeltaInfo info = deltas.get(i); info.writeToLog(logBuffer); } } /* * @see Loggable#readFromLog() */ public void readFromLog(ByteBuffer itemBuffer, int entryVersion) { dbId.readFromLog(itemBuffer, entryVersion); // database id lastFullLsn = LogUtils.readLong(itemBuffer, (entryVersion < 6)); int numDeltas = LogUtils.readInt(itemBuffer, (entryVersion < 6)); for (int i=0; i < numDeltas; i++) { // deltas DeltaInfo info = new DeltaInfo(); info.readFromLog(itemBuffer, entryVersion); deltas.add(info); } } /* * @see Loggable#dumpLog */ public void dumpLog(StringBuilder sb, boolean verbose) { dbId.dumpLog(sb, verbose); sb.append("<lastFullLsn>"); sb.append(DbLsn.toString(lastFullLsn)); sb.append("</lastFullLsn>"); sb.append("<deltas size=\"").append(deltas.size()).append("\"/>"); for (int i = 0; i < deltas.size(); i++) { // deltas DeltaInfo info = deltas.get(i); info.dumpLog(sb, verbose); } } /** * @see Loggable#getTransactionId */ public long getTransactionId() { return 0; } /** * @see Loggable#logicalEquals * Always return false, this item should never be compared. */ public boolean logicalEquals(Loggable other) { return false; } }
Java
public class TextTest extends AbstractCharacterDataTest { protected Text text; @Override public void setUp() throws Exception { super.setUp(); text = textNode(); } protected Text textNode() { Node book = getChildNode(document.getDocumentElement(), "book"); Node title = getChildNode(book, "title"); return (Text) title.getFirstChild(); } protected String expectedText() { return "XML Developer's Guide"; } @Override protected Node node() { return text; } @Override protected CharacterData characterData() { return text; } /* * Node API. */ @Test public void testGetNodeName() { assertEquals("#text", text.getNodeName()); } @Test public void testGetNodeType() { assertEquals(Node.TEXT_NODE, text.getNodeType()); } @Test public void testGetNodeValue() { assertEquals(expectedText(), text.getNodeValue()); } @Test public void testSetNodeValue() { try { text.setNodeValue(expectedText()); fail(); } catch (DOMException e) { assertEquals(DOMException.NO_MODIFICATION_ALLOWED_ERR, e.code); } } @Test public void testGetParentNode() { assertEquals("title", text.getParentNode().getNodeName()); } @Test public void testGetChildNodes() { assertEquals(0, text.getChildNodes().getLength()); } @Test public void testGetFirstChild() { assertNull(text.getFirstChild()); } @Test public void testGetLastChild() { assertNull(text.getLastChild()); } @Test public void testHasChildNodes() { assertFalse(text.hasChildNodes()); } @Test public void testGetPreviousSibling() { assertNull(text.getPreviousSibling()); } @Test public void testGetNextSibling() { assertNull(text.getNextSibling()); } @Test public void testGetAttributes() { assertNull(text.getAttributes()); } @Test public void testHasAttributes() { assertFalse(text.hasAttributes()); } @Test public void testGetOwnerDocument() { assertEquals(document, text.getOwnerDocument()); } @Test public void testIsDefaultNamespace() { assertFalse(text.isDefaultNamespace(NS_CATALOG)); } @Test public void testGetNamespaceURI() { assertNull(text.getNamespaceURI()); } @Test public void testGetPrefix() { assertNull(text.getPrefix()); } @Test public void testGetLocalName() { assertNull(text.getLocalName()); } @Test public void testGetTextContent() { assertEquals(expectedText(), text.getTextContent()); } @Test public void testSetTextContent() { try { text.setTextContent(expectedText()); fail(); } catch (DOMException e) { assertEquals(DOMException.NO_MODIFICATION_ALLOWED_ERR, e.code); } } @Test public void testIsEqualNode() { assertTrue(text.isEqualNode(textNode())); assertFalse(text.isEqualNode(text.getParentNode())); assertFalse(text.isEqualNode(null)); } @Test public void testIsSameNode() { assertTrue(text.isSameNode(textNode())); assertFalse(text.isSameNode(text.getParentNode())); assertFalse(text.isSameNode(null)); } /* * CharacterData API. */ @Test public void testGetData() { assertEquals(expectedText(), text.getData()); } @Test public void testGetLength() { assertEquals(expectedText().length(), text.getLength()); } @Test public void testSubstringData() { assertEquals(expectedText(), text.substringData(0, expectedText().length())); assertEquals(expectedText(), text.substringData(0, expectedText().length() * 2)); assertEquals(expectedText().substring(0, expectedText().length() / 2), text.substringData(0, expectedText().length() / 2)); assertEquals("", text.substringData(0, 0)); } @Test public void testSubstringData_withInvalidCount() { try { text.substringData(0, -1); fail(); } catch (DOMException e) { assertEquals(DOMException.INDEX_SIZE_ERR, e.code); } } @Test public void testSubstringData_withInvalidOffset() { try { // Offset is greater than the data's length. text.substringData(expectedText().length(), 1); fail(); } catch (DOMException e) { assertEquals(DOMException.INDEX_SIZE_ERR, e.code); } } /* * Text API. */ @Test(expected = UnsupportedOperationException.class) public void testGetWholeText() { text.getWholeText(); } @Test(expected = UnsupportedOperationException.class) public void testIsElementContentWhitespace() { text.isElementContentWhitespace(); } @Test public void testReplaceWholeText() { try { text.replaceWholeText(expectedText()); fail(); } catch (DOMException e) { assertEquals(DOMException.NO_MODIFICATION_ALLOWED_ERR, e.code); } } @Test public void testSplitText() { try { text.splitText(expectedText().length() / 2); fail(); } catch (DOMException e) { assertEquals(DOMException.NO_MODIFICATION_ALLOWED_ERR, e.code); } } /* * Object API. */ @Test public void testEquals() { assertTrue(text.equals(textNode())); assertFalse(text.equals(text.getParentNode())); assertFalse(text.equals(new Object())); assertFalse(text.equals(null)); } }
Java
public abstract class AbstractEntityNotFoundExceptionMapper extends AbstractMapper { /** * Forward to a 404 status error. * * @param exception * the root exception. * @return the built response. */ protected Response toResponseNotFound(final Throwable exception) { return toResponse(Status.NOT_FOUND, "entity", exception); } }
Java
public class LogCrashManagerListener extends BaseCrashManagerListener { private static final String TAG = LogCrashManagerListener.class.getSimpleName(); private static final String START_MESSAGE = "//---- AppStart: "+System.currentTimeMillis()+" - language: "+ Locale.getDefault().toString() +" ----//"; private int logLevel; public LogCrashManagerListener(){ this(null); } public LogCrashManagerListener(Context context){ this(context, Log.VERBOSE); } /** * * @param loglevel should be any of * [{@link Log#VERBOSE}, * {@link Log#DEBUG}, * {@link Log#INFO}, * {@link Log#WARN}, * {@link Log#ERROR}}] */ public LogCrashManagerListener(Context context, int loglevel){ super(context); this.logLevel = loglevel; Log.i(TAG, START_MESSAGE); } @Override public String getDescription() { String description = ""; try { Process process = Runtime.getRuntime().exec(logcatParamsFromConfig()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder log = new StringBuilder(); String line; // skip all messages until messages starts form the current application process boolean startRecord = false; while ((line = bufferedReader.readLine()) != null) { //skip first lines when we are not starting to record if(!startRecord){ //check if we should start recording now if(line.contains(START_MESSAGE)){ startRecord = true; }else{ continue; } } log.append(line); log.append(System.getProperty("line.separator")); } bufferedReader.close(); description = log.toString(); } catch (IOException e) { e.printStackTrace(); } return description; } private String[] logcatParamsFromConfig(){ String logLevel = "*:V"; switch (this.logLevel){ case Log.VERBOSE: logLevel = "*:V"; break; case Log.DEBUG: logLevel = "*:D"; break; case Log.INFO: logLevel = "*:I"; break; case Log.WARN: logLevel = "*:W"; break; case Log.ERROR: logLevel = "*.E"; break; } String includeLogManagerListenerTagInLogcat = TAG+":I"; return new String[]{"logcat", "-d", includeLogManagerListenerTagInLogcat ,logLevel}; } }
Java
public class SoundFileElement extends DisplayElement { protected AudioInputStream audioInputStream = null; protected AudioFormat audioFormat; protected String fileName = null; protected File soundFile = null; protected Player player = null; public SoundFileElement() { type = DisplayElement.AUDIO_BEEP; setColorPar(ExPar.ScreenBackgroundColor); } public void setProperties(String dir, String fn, double volume, MediaEventListener mediaEventListener) { // System.out.println("SoundFileElement.setProperties(): fn = " + fn); URL url = FileBase.url(dir, fn); if (url != null) { try { Debug.show(Debug.FILES, "Open audio stream from " + url); audioInputStream = AudioSystem.getAudioInputStream(url); audioFormat = audioInputStream.getFormat(); if (player == null) { player = new Player(audioInputStream, audioFormat); player.setMediaEventListener(mediaEventListener); } else { player.addInputStream(audioInputStream, false); } } catch (UnsupportedAudioFileException uaf) { System.out .println("SoundFileElement.setProperties(): Unsupported audio format: " + fn); } catch (IOException iox) { System.out .println("SoundFileElement.setProperties(): I/O Error: " + fn); } } } public void show() { if (player != null) player.play(); } public AudioFormat getAudioFormat() { return audioFormat; } public ShortBuffer getAudioDataAsShort() { return (ShortBuffer) null; } public byte[] getAudioData() { return (byte[]) null; } }
Java
public static final class StoreEntry implements BaseColumns { public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_STORE); /** * The MIME type of the {@link #CONTENT_URI} for a list of pets. */ public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_STORE; /** * The MIME type of the {@link #CONTENT_URI} for a single pet. */ public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_STORE; public final static String TABLE_NAME = "inventory"; public static final String _ID = BaseColumns._ID; public final static String COLUMN_PRODUCT_NAME = "productName"; public final static String COLUMN_PRICE ="price"; public final static String COLUMN_QUANTITY = "quantity"; public final static String COLUMN_SUPPLIER_NAME = "supplierName"; public final static String COLUMN_SUPPLIER_PHONE_NUMBER = "supplierPhoneNumber"; public static final String DEFAULT_PHONE = "+90 000 000 00 00"; }
Java
public class RunLengthDecodeFilter implements Filter { private static final int RUN_LENGTH_EOD = 128; /** * Constructor. */ public RunLengthDecodeFilter() { //default constructor } /** * {@inheritDoc} */ public void decode( InputStream compressedData, OutputStream result, COSDictionary options, int filterIndex ) throws IOException { int dupAmount = -1; byte[] buffer = new byte[128]; while( (dupAmount = compressedData.read()) != -1 && dupAmount != RUN_LENGTH_EOD ) { if( dupAmount <= 127 ) { int amountToCopy = dupAmount+1; int compressedRead = 0; while( amountToCopy > 0 ) { compressedRead = compressedData.read( buffer, 0, amountToCopy ); result.write( buffer, 0, compressedRead ); amountToCopy -= compressedRead; } } else { int dupByte = compressedData.read(); for( int i=0; i<257-dupAmount; i++ ) { result.write( dupByte ); } } } } /** * {@inheritDoc} */ public void encode( InputStream rawData, OutputStream result, COSDictionary options, int filterIndex ) throws IOException { System.err.println( "Warning: RunLengthDecodeFilter.encode is not implemented yet, skipping this stream." ); } }
Java
@Entity @Table(name = "ven") public class Ven extends AbstractUser { /** * */ private static final long serialVersionUID = -4462874293418115268L; /** * Ven registered name */ private String oadrName; /** * 20a/20b profil */ private String oadrProfil; /** * http/xmpp transport */ private String transport; /** * push mode url */ private String pushUrl; /** * registrationId */ @Column(name = "registrationId", unique = true) private String registrationId; /** * is http pull model */ private Boolean httpPullModel = true; /** * report only */ private Boolean reportOnly = false; /** * support xml signature */ private Boolean xmlSignature = false; private Long pullFrequencySeconds; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "ven_vengroup", joinColumns = @JoinColumn(name = "ven_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "vengroup_id", referencedColumnName = "id")) private Set<VenGroup> venGroups; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "ven_venmarketcontext", joinColumns = @JoinColumn(name = "ven_id"), inverseJoinColumns = @JoinColumn(name = "venmarketcontext_id")) private Set<VenMarketContext> venMarketContexts; @OneToMany(mappedBy = "ven", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set<VenResource> venResources; @OneToMany(fetch = FetchType.LAZY, mappedBy = "ven") private List<VenDemandResponseEvent> venDemandResponseEvent; private Long lastUpdateDatetime; public String getOadrName() { return oadrName; } public void setOadrName(String name) { this.oadrName = name; } public String getOadrProfil() { return oadrProfil; } public void setOadrProfil(String oadrProfil) { this.oadrProfil = oadrProfil; } public String getTransport() { return transport; } public void setTransport(String transport) { this.transport = transport; } public Set<VenGroup> getVenGroups() { return venGroups; } public void setVenGroup(Set<VenGroup> venGroups) { this.venGroups = venGroups; } /** * @return the pushUrl */ public String getPushUrl() { return pushUrl; } /** * @param pushUrl the pushUrl to set */ public void setPushUrl(String pushUrl) { this.pushUrl = pushUrl; } public String getRegistrationId() { return registrationId; } public void setRegistrationId(String registrationId) { this.registrationId = registrationId; } public Boolean getHttpPullModel() { return httpPullModel; } public void setHttpPullModel(Boolean httpPullModel) { this.httpPullModel = httpPullModel; } public Boolean getReportOnly() { return reportOnly; } public void setReportOnly(Boolean reportOnly) { this.reportOnly = reportOnly; } public Boolean getXmlSignature() { return xmlSignature; } public void setXmlSignature(Boolean xmlSignature) { this.xmlSignature = xmlSignature; } public Set<VenMarketContext> getVenMarketContexts() { return venMarketContexts; } public void setVenMarketContexts(Set<VenMarketContext> venMarketContexts) { this.venMarketContexts = venMarketContexts; } public void removeGroup(VenGroup venGroup) { venGroups.remove(venGroup); } public void removeMarketContext(VenMarketContext venMarketContext) { venMarketContexts.remove(venMarketContext); } public Set<VenResource> getVenResources() { return venResources; } public void setVenResources(Set<VenResource> venResources) { this.venResources = venResources; } public void removeResource(VenResource venResource) { venResources.remove(venResource); } public Long getPullFrequencySeconds() { return pullFrequencySeconds; } public void setPullFrequencySeconds(Long pullFrequencySeconds) { this.pullFrequencySeconds = pullFrequencySeconds; } public Long getLastUpdateDatetime() { return lastUpdateDatetime; } public void setLastUpdateDatetime(Long lastUpdateDatetime) { this.lastUpdateDatetime = lastUpdateDatetime; } public List<VenDemandResponseEvent> getVenDemandResponseEvent() { return venDemandResponseEvent; } public void setVenDemandResponseEvent(List<VenDemandResponseEvent> venDemandResponseEvent) { this.venDemandResponseEvent = venDemandResponseEvent; } @Override public String toString() { return "Ven [oadrName=" + oadrName + ", oadrProfil=" + oadrProfil + ", transport=" + transport + ", pushUrl=" + pushUrl + ", registrationId=" + registrationId + ", httpPullModel=" + httpPullModel + ", reportOnly=" + reportOnly + ", xmlSignature=" + xmlSignature + ", pullFrequencySeconds=" + pullFrequencySeconds + ", lastUpdateDatetime=" + lastUpdateDatetime + "]"; } }
Java
public abstract class PredictionFormula { /** * Default constructor */ public PredictionFormula() { } /** * Computes the prediction for the metric value based on the refactoring * operation and the previous metrics * * @param ref the refactoring operation which will impact some metric * @param prevMetrics the previous metric values of the entire system * @return the predicted values of the classes involved in the refactoring * operation * @throws Exception if some error occurs */ public abstract HashMap<String, Double> predictMetrVal( RefactoringOperation ref, LinkedHashMap<String, LinkedHashMap<String, Double>> prevMetrics) throws Exception; /** * Get the code metric corresponding to this formula * * @return the code metric */ public abstract CodeMetric getMetric(); }
Java
@RegistryScopes(scopes = RegistryScope.GAME) public final class MapDecorationTypes { // SORTFIELDS:ON public static final DefaultedRegistryReference<MapDecorationType> BLUE_MARKER = MapDecorationTypes.key(ResourceKey.sponge("blue_marker")); public static final DefaultedRegistryReference<MapDecorationType> GREEN_MARKER = MapDecorationTypes.key(ResourceKey.sponge("frame")); public static final DefaultedRegistryReference<MapDecorationType> MANSION = MapDecorationTypes.key(ResourceKey.sponge("mansion")); public static final DefaultedRegistryReference<MapDecorationType> MONUMENT = MapDecorationTypes.key(ResourceKey.sponge("monument")); public static final DefaultedRegistryReference<MapDecorationType> PLAYER_MARKER = MapDecorationTypes.key(ResourceKey.sponge("player")); public static final DefaultedRegistryReference<MapDecorationType> PLAYER_OFF_LIMITS = MapDecorationTypes.key(ResourceKey.sponge("player_off_limits")); public static final DefaultedRegistryReference<MapDecorationType> PLAYER_OFF_MAP = MapDecorationTypes.key(ResourceKey.sponge("player_off_map")); public static final DefaultedRegistryReference<MapDecorationType> RED_MARKER = MapDecorationTypes.key(ResourceKey.sponge("red_marker")); public static final DefaultedRegistryReference<MapDecorationType> TARGET_POINT = MapDecorationTypes.key(ResourceKey.sponge("target_point")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_WHITE = MapDecorationTypes.key(ResourceKey.sponge("banner_white")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_ORANGE = MapDecorationTypes.key(ResourceKey.sponge("banner_orange")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_MAGENTA = MapDecorationTypes.key(ResourceKey.sponge("banner_magenta")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_LIGHT_BLUE = MapDecorationTypes.key(ResourceKey.sponge("banner_light_blue")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_YELLOW = MapDecorationTypes.key(ResourceKey.sponge("banner_yellow")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_LIME = MapDecorationTypes.key(ResourceKey.sponge("banner_lime")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_PINK = MapDecorationTypes.key(ResourceKey.sponge("banner_pink")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_GRAY = MapDecorationTypes.key(ResourceKey.sponge("banner_gray")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_LIGHT_GRAY = MapDecorationTypes.key(ResourceKey.sponge("banner_light_gray")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_CYAN = MapDecorationTypes.key(ResourceKey.sponge("banner_cyan")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_PURPLE = MapDecorationTypes.key(ResourceKey.sponge("banner_purple")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_BLUE = MapDecorationTypes.key(ResourceKey.sponge("banner_blue")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_BROWN = MapDecorationTypes.key(ResourceKey.sponge("banner_brown")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_GREEN = MapDecorationTypes.key(ResourceKey.sponge("banner_green")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_RED = MapDecorationTypes.key(ResourceKey.sponge("banner_red")); public static final DefaultedRegistryReference<MapDecorationType> BANNER_BLACK = MapDecorationTypes.key(ResourceKey.sponge("banner_black")); // SORTFIELDS:OFF private static DefaultedRegistryReference<MapDecorationType> key(final ResourceKey location) { return RegistryKey.of(RegistryTypes.MAP_DECORATION_TYPE, location).asDefaultedReference(Sponge::game); } }
Java
public class Util { private static Logger logger = LogManager.getLogger(); public static XPrv newXPrv(InputStream io) throws IOException { byte[] entropy = new byte[32]; if (io.read(entropy) != entropy.length) { throw new IOException("read eof of io, but entropy not full"); } return newXPrv(entropy); } // if entropy is null, random bytes is used public static XPrv newXPrv(byte[] entropy) { if (entropy == null) { entropy = new byte[32]; Random random = new Random(); random.setSeed(System.currentTimeMillis()); random.nextBytes(entropy); } if (entropy.length != 32) { throw new IllegalArgumentException("entropy length should be 32"); } Digest digest = new SHA512Digest(); byte[] flag = "Chain seed".getBytes(); digest.update(flag, 0, flag.length); digest.update(entropy, 0, entropy.length); byte[] out = new byte[digest.getDigestSize()]; digest.doFinal(out, 0); modifyScalar(out); return new XPrv(out); } public static PublicKey[] xPubKeys(XPub[] xpubs) { PublicKey[] res = new PublicKey[xpubs.length]; for (int i = 0; i < xpubs.length; i++) { res[i] = xpubs[i].publicKey(); } return res; } public static XPub[] deriveXPubs(XPub[] xpubs, byte[][] path) { XPub[] res = new XPub[xpubs.length]; for (int i = 0; i < xpubs.length; i++) { res[i] = xpubs[i].derive(path); } return res; } public static EdDSAPublicKey newEdDSAPublicKey(byte[] pubKey) { EdDSANamedCurveSpec edc = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.CURVE_ED25519_SHA512); return new EdDSAPublicKey(new EdDSAPublicKeySpec(pubKey, edc)); } public static boolean verify(byte[] pubKey, byte[] msg, byte[] sig) throws InvalidKeyException, SignatureException { EdDSAEngine engine = new EdDSAEngine(); engine.initVerify(newEdDSAPublicKey(pubKey)); engine.update(msg); return engine.verify(sig); } static byte[] hashKeySaltSelector(byte version, byte[] key, byte[] salt, byte[] sel) { Digest helper = hashKeySaltHelper(version, key, salt); byte[] l = new byte[10]; int n = VarInt.putUVarInt(l, sel.length); helper.update(l, 0, n); helper.update(sel, 0, sel.length); byte[] out = new byte[helper.getDigestSize()]; helper.doFinal(out, 0); modifyScalar(out); return out; } static byte[] hashKeySalt(byte version, byte[] key, byte[] salt) { Digest helper = hashKeySaltHelper(version, key, salt); byte[] out = new byte[helper.getDigestSize()]; helper.doFinal(out, 0); return out; } private static Digest hashKeySaltHelper(byte version, byte[] key, byte[] salt) { Digest digest = new SHA512Digest(); digest.update(version); digest.update(key, 0, key.length); digest.update(salt, 0, salt.length); return digest; } private static void modifyScalar(byte[] digest) { digest[0] &= 248; digest[31] &= 127; digest[31] |= 64; } }
Java
public class JavaToAS3Compiler { private final Logger logger = Logger.getLogger(getClass()); private Map<File,File> files = new HashMap<File,File>(); private boolean includeDefaultMutations = true; private Map<String,String> packageToPackage = new HashMap<String,String>(); private Map<String,String> classesToClasses = new HashMap<String,String>(); private Map<String,String> importsToImports = new HashMap<String,String>(); private List<String> importsToIgnore = new ArrayList<String>(); private List<String> forcedImports = new ArrayList<String>(); private List<String> classesToArrays = new ArrayList<String>(); private List<String> classesToDictionaries = new ArrayList<String>(); private List<String> classesToVectors = new ArrayList<String>(); private List<String> classesExtendArray = new ArrayList<String>(); private List<String> classesExtendDictionary = new ArrayList<String>(); private List<String> classesExtendVector = new ArrayList<String>(); private boolean forceSprite = false; private boolean forceMovieClip = false; private String arrayClass = null; private String vectorClass = null; private String dictionaryClass = null; /** * Constructor. */ public JavaToAS3Compiler() { } /** * Compile all specified files in the File map. * * @throws ParseException * @throws IOException */ public void compileAll() throws ParseException, IOException { if (files != null && files.size() > 0) { for (File input : files.keySet()) { File output = files.get(input); recursiveCompileFile(input, output); } } } /** * Compile a Java input file to an AS3 file. If the input file denotes a directory, all .java files * in the directory will be compiled recursively * * @param input Input file * @param output Output file * @throws ParseException * @throws IOException */ private void recursiveCompileFile(File input, File output) throws ParseException, IOException { if (input.isDirectory()) { for (File file : input.listFiles()) { // when recursing down the directory tree, only try to parse .java files if (file.isDirectory()) { File fileOutput = new File(output, file.getName()); recursiveCompileFile(file, fileOutput); } else if (file.getName().endsWith(".java")) { // create any intermediate dirs if (output != null) { output.mkdirs(); } compileFile(file, output); } } } else { compileFile(input, output); } } /** * Compile a Java input file to an AS3 file. * * @param inputFile * @param outputDir * @throws ParseException * @throws IOException */ public void compileFile(File inputFile, File outputDir) throws ParseException, IOException { logger.info("Parsing "+inputFile.getPath() + "..."); FileInputStream in = new FileInputStream(inputFile); CompilationUnit cu = null; cu = JavaParser.parse(in); in.close(); AS3MutationVisitor as3Mut = new AS3MutationVisitor(); if (includeDefaultMutations) { as3Mut.includeDefaults(); } mergeMutationOptions(as3Mut); as3Mut.visit(cu, null); AS3DumpVisitor as3 = new AS3DumpVisitor(); as3.visit(cu, null); String output = as3.toString(); //logger.debug("Compilation output:\n" + output); File outputFile = null; // outputDir/File is optional if (outputDir == null || outputDir.isDirectory()) { String name = inputFile.getName().replace(".java", ".as"); outputFile = new File(outputDir, name); } else { outputFile = outputDir; } outputFile.createNewFile(); FileOutputStream out = new FileOutputStream(outputFile); out.write(output.getBytes()); out.close(); } /** * Compile a Java String to an AS3 String. * * @param inputJava * @return * @throws ParseException */ public String compileString(String inputJava) throws ParseException { CompilationUnit cu = null; cu = JavaParser.parse(new ByteArrayInputStream(inputJava.getBytes())); AS3MutationVisitor as3Mut = new AS3MutationVisitor(); if (includeDefaultMutations) { as3Mut.includeDefaults(); } mergeMutationOptions(as3Mut); as3Mut.visit(cu, null); AS3DumpVisitor as3 = new AS3DumpVisitor(); as3.visit(cu, null); String output = as3.toString(); //logger.debug("Compilation output:\n" + output); return output; } private void mergeMutationOptions(AS3MutationVisitor as3Mut) { as3Mut.setForceSprite(forceSprite); as3Mut.setForceMovieClip(forceMovieClip); if (packageToPackage != null && packageToPackage.size() > 0) { as3Mut.getPackageToPackage().putAll(packageToPackage); } if (classesToClasses != null && classesToClasses.size() > 0) { as3Mut.getClassesToClasses().putAll(classesToClasses); } if (importsToImports != null && importsToImports.size() > 0) { as3Mut.getImportsToImports().putAll(importsToImports); } if (importsToIgnore != null && importsToIgnore.size() > 0) { as3Mut.getImportsToIgnore().addAll(importsToIgnore); } if (forcedImports != null && forcedImports.size() > 0) { as3Mut.getForcedImports().addAll(forcedImports); } if (classesToArrays != null && classesToArrays.size() > 0) { as3Mut.getClassesToArrays().addAll(classesToArrays); } if (classesToDictionaries != null && classesToDictionaries.size() > 0) { as3Mut.getClassesToDictionaries().addAll(classesToDictionaries); } if (classesToVectors != null && classesToVectors.size() > 0) { as3Mut.getClassesToVectors().addAll(classesToVectors); } if (classesExtendArray != null && classesExtendArray.size() > 0) { as3Mut.getClassesExtendArray().addAll(classesExtendArray); } if (classesExtendDictionary != null && classesExtendDictionary.size() > 0) { as3Mut.getClassesExtendDictionary().addAll(classesExtendDictionary); } if (classesExtendVector != null && classesExtendVector.size() > 0) { as3Mut.getClassesExtendVector().addAll(classesExtendVector); } if (arrayClass != null && !arrayClass.isEmpty()) { as3Mut.setArrayClass(arrayClass); } if (vectorClass != null && !vectorClass.isEmpty()) { as3Mut.setVectorClass(vectorClass); } if (dictionaryClass != null && !dictionaryClass.isEmpty()) { as3Mut.setDictionaryClass(dictionaryClass); } } public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Usage: java JavaToAS3Compiler <input file or directory> [<output file or directory>]"); return; } JavaToAS3Compiler me = new JavaToAS3Compiler(); File inFile = new File(args[0]); File outFile = null; if (args.length == 2) { outFile = new File(args[1]); } me.getFiles().put(inFile, outFile); me.compileAll(); } /** * @return the files */ public Map<File, File> getFiles() { return files; } /** * @param files the files to set */ public void setFiles(Map<File, File> files) { this.files = files; } /** * @return the includeDefaultMutations */ public boolean isIncludeDefaultMutations() { return includeDefaultMutations; } /** * @param includeDefaultMutations the includeDefaultMutations to set */ public void setIncludeDefaultMutations(boolean includeDefaultMutations) { this.includeDefaultMutations = includeDefaultMutations; } /** * @return the packageToPackage */ public Map<String, String> getPackageToPackage() { return packageToPackage; } /** * @param packageToPackage the packageToPackage to set */ public void setPackageToPackage(Map<String, String> packageToPackage) { this.packageToPackage = packageToPackage; } /** * @return the classesToClasses */ public Map<String, String> getClassesToClasses() { return classesToClasses; } /** * @param classesToClasses the classesToClasses to set */ public void setClassesToClasses(Map<String, String> classesToClasses) { this.classesToClasses = classesToClasses; } /** * @return the importsToImports */ public Map<String, String> getImportsToImports() { return importsToImports; } /** * @param importsToImports the importsToImports to set */ public void setImportsToImports(Map<String, String> importsToImports) { this.importsToImports = importsToImports; } /** * @return the importsToIgnore */ public List<String> getImportsToIgnore() { return importsToIgnore; } /** * @param importsToIgnore the importsToIgnore to set */ public void setImportsToIgnore(List<String> importsToIgnore) { this.importsToIgnore = importsToIgnore; } /** * @return the forcedImports */ public List<String> getForcedImports() { return forcedImports; } /** * @param forcedImports the forcedImports to set */ public void setForcedImports(List<String> forcedImports) { this.forcedImports = forcedImports; } /** * @return the classesToArrays */ public List<String> getClassesToArrays() { return classesToArrays; } /** * @param classesToArrays the classesToArrays to set */ public void setClassesToArrays(List<String> classesToArrays) { this.classesToArrays = classesToArrays; } /** * @return the classesToDictionaries */ public List<String> getClassesToDictionaries() { return classesToDictionaries; } /** * @param classesToDictionaries the classesToDictionaries to set */ public void setClassesToDictionaries(List<String> classesToDictionaries) { this.classesToDictionaries = classesToDictionaries; } /** * @return the classesToVectors */ public List<String> getClassesToVectors() { return classesToVectors; } /** * @param classesToVectors the classesToVectors to set */ public void setClassesToVectors(List<String> classesToVectors) { this.classesToVectors = classesToVectors; } /** * @return the classesExtendArray */ public List<String> getClassesExtendArray() { return classesExtendArray; } /** * @param classesExtendArray the classesExtendArray to set */ public void setClassesExtendArray(List<String> classesExtendArray) { this.classesExtendArray = classesExtendArray; } /** * @return the classesExtendDictionaries */ public List<String> getClassesExtendDictionary() { return classesExtendDictionary; } /** * @param classesExtendDictionaries the classesExtendDictionaries to set */ public void setClassesExtendDictionary(List<String> classesExtendDictionary) { this.classesExtendDictionary = classesExtendDictionary; } /** * @return the classesExtendVectors */ public List<String> getClassesExtendVector() { return classesExtendVector; } /** * @param classesExtendVectors the classesExtendVectors to set */ public void setClassesExtendVector(List<String> classesExtendVector) { this.classesExtendVector = classesExtendVector; } /** * @return the forceSprite */ public boolean isForceSprite() { return forceSprite; } /** * @param forceSprite the forceSprite to set */ public void setForceSprite(boolean forceSprite) { this.forceSprite = forceSprite; } /** * @return the forceMovieClip */ public boolean isForceMovieClip() { return forceMovieClip; } /** * @param forceMovieClip the forceMovieClip to set */ public void setForceMovieClip(boolean forceMovieClip) { this.forceMovieClip = forceMovieClip; } /** * @return the arrayClass */ public String getArrayClass() { return arrayClass; } /** * @param arrayClass the arrayClass to set */ public void setArrayClass(String arrayClass) { this.arrayClass = arrayClass; } /** * @return the vectorClass */ public String getVectorClass() { return vectorClass; } /** * @param vectorClass the vectorClass to set */ public void setVectorClass(String vectorClass) { this.vectorClass = vectorClass; } /** * @return the dictionaryClass */ public String getDictionaryClass() { return dictionaryClass; } /** * @param dictionaryClass the dictionaryClass to set */ public void setDictionaryClass(String dictionaryClass) { this.dictionaryClass = dictionaryClass; } }
Java
@com.gigaspaces.api.InternalApi public class QueryProcessorConfiguration { //logger final private static Logger _logger = LoggerFactory.getLogger(Constants.LOGGER_QUERY); private static final String TRACE_EXEC_TIME_PROPERTY = "TRACE_EXEC_TIME"; private static final String AUTO_COMMIT_PROPERTY = "AUTO_COMMIT"; private static final String PARSER_CASE_SENSETIVITY_PROPERTY = "PARSER_CASE_SENSETIVITY"; private static final String TRANSACTION_TIMEOUT_PROPERTY = "TRANSACTION_TIMEOUT"; private static final String SPACE_WRITE_LEASE_PROPERTY = "SPACE_WRITE_LEASE"; private static final String SPACE_READ_LEASE_TIME_PROPERTY = "SPACE_READ_LEASE_TIME"; private static final String SPACE_URL = "SPACE_URL"; private static final String PORT_PROPERTY = "PORT"; private static final int PORT_DEFAULT = 2872; private static final String SQL_DATE_FORMAT_PROPERTY = "SQL_DATE_FORMAT"; private static final String LOCAL_DATE_TIME_FORMAT_PROPERTY = "LOCAL_DATETIME_FORMAT"; private static final String SQL_TIME_FORMAT_PROPERTY = "SQL_TIME_FORMAT"; private static final String TIMESTAMP_FORMAT_PROPERTY = "TIMESTAMP_FORMAT"; private static final String UTIL_DATE_FORMAT_PROPERTY = "UTIL_DATE_FORMAT_FORMAT"; private static final String LOCAL_TIME_FORMAT_PROPERTY = "LOCAL_TIME_FORMAT"; private static final String LOCAL_DATE_FORMAT_PROPERTY = "LOCAL_DATE_FORMAT_PROPERTY"; private static final String INSTANT_FORMAT_PROPERTY = "INSTANT_FORMAT"; private int _readLease = Integer.parseInt(QueryProcessorInfo.QP_SPACE_READ_LEASE_TIME_DEFAULT); private long _writeLease = Long.parseLong(QueryProcessorInfo.QP_SPACE_WRITE_LEASE_DEFAULT); private long _transactionTimeout = Integer.parseInt(QueryProcessorInfo.QP_TRANSACTION_TIMEOUT_DEFAULT); private boolean _parserCaseSensitivity = Boolean.parseBoolean(QueryProcessorInfo.QP_PARSER_CASE_SENSETIVITY_DEFAULT); private String _utilDateFormat = QueryProcessorInfo.QP_UTILDATE_FORMAT_DEFAULT; private String _localDateTimeFormat = QueryProcessorInfo.QP_LOCALDATETIME_FORMAT_DEFAULT; private String _localTimeFormat = QueryProcessorInfo.QP_LOCALTIME_FORMAT_DEFAULT; private String _localDateFormat = QueryProcessorInfo.QP_LOCALDATE_FORMAT_DEFAULT; private String _sqlDateFormat = QueryProcessorInfo.QP_SQLDATE_FORMAT_DEFAULT; private String _sqlTimeFormat = QueryProcessorInfo.QP_SQLTIME_FORMAT_DEFAULT; private String _timestampFormat = QueryProcessorInfo.QP_TIMESTAMP_FORMAT_DEFAULT; private String _instantFormat = QueryProcessorInfo.QP_INSTANT_FORMAT_DEFAULT; private boolean _traceExecTime = Boolean.parseBoolean(QueryProcessorInfo.QP_TRACE_EXEC_TIME_DEFAULT); private boolean _autoCommit = Boolean.parseBoolean(QueryProcessorInfo.QP_AUTO_COMMIT_DEFAULT); private String _spaceURL; private int _listenPort = PORT_DEFAULT; private TransactionManagerConfiguration _transactionManagerConfiguration; public QueryProcessorConfiguration(JSpaceAttributes conf, Properties localProps) { // set properties from space if (conf != null) { _readLease = conf.getQpSpaceReadLeaseTime(); _writeLease = conf.getQpSpaceWriteLeaseTime(); _transactionTimeout = conf.getQpTransactionTimeout(); _parserCaseSensitivity = conf.isQPParserCaseSensetivity(); _autoCommit = conf.isQPAutoCommit(); _traceExecTime = conf.isQPTraceExecTime(); String oldTimeFormat = conf.getQpTimeFormat(); String oldDateFormat = conf.getQpDateFormat(); String oldDateTimeFormat = conf.getQpDateTimeFormat(); if (oldTimeFormat.equals("")) { _sqlTimeFormat = conf.getQpSqlTimeFormat(); _localTimeFormat = conf.getQpLocalTimeFormat(); } else{ _sqlTimeFormat = oldTimeFormat; _localTimeFormat = oldTimeFormat; } if (oldDateFormat.equals("")) { _utilDateFormat = conf.getQpUtilDateFormat(); _localDateFormat = conf.getQpLocalDateFormat(); _sqlDateFormat = conf.getQpSqlDateFormat(); } else{ _utilDateFormat = oldDateFormat; _localDateFormat = oldDateFormat; _sqlDateFormat = oldDateFormat; } if (oldDateTimeFormat.equals("")) { _localDateTimeFormat = conf.getQpLocalDateTimeFormat(); _timestampFormat = conf.getQpTimestampFormat(); } else{ _localDateTimeFormat = oldDateTimeFormat; _timestampFormat = oldDateTimeFormat; } _instantFormat = conf.getQpInstantFormat(); } // set properties from override properties file configure(localProps); if (_logger.isDebugEnabled()) { _logger.debug("\n QueryProcessor configuration:\n\t" + "parserCaseSensitivity=" + _parserCaseSensitivity + "\n\t" + "writeLease=" + _writeLease + "\n" + "\t" + "readLease=" + _readLease + "\n" + "\t" + "transactionTimeout=" + _transactionTimeout + "\n\t" + "autoCommit=" + _autoCommit + "\n\t" + "traceExecTime=" + _traceExecTime + "\n\t" + "dateFormat=" + _sqlDateFormat + "\n\t" + "dateTimeFormat=" + _localDateTimeFormat + "\n\t" + "timeFormat=" + _sqlTimeFormat ); } } private void configure(Properties localProps) { if (localProps == null) return; _readLease = getInteger(localProps.getProperty(SPACE_READ_LEASE_TIME_PROPERTY), _readLease); _writeLease = getLong(localProps.getProperty(SPACE_WRITE_LEASE_PROPERTY), _writeLease); _transactionTimeout = getLong(localProps.getProperty(TRANSACTION_TIMEOUT_PROPERTY), _transactionTimeout); _parserCaseSensitivity = getBoolean(localProps.getProperty(PARSER_CASE_SENSETIVITY_PROPERTY), _parserCaseSensitivity); _autoCommit = getBoolean(localProps.getProperty(AUTO_COMMIT_PROPERTY), _autoCommit); _traceExecTime = getBoolean(localProps.getProperty(TRACE_EXEC_TIME_PROPERTY), _traceExecTime); _sqlDateFormat = localProps.getProperty(SQL_DATE_FORMAT_PROPERTY, _sqlDateFormat); _localDateTimeFormat = localProps.getProperty(LOCAL_DATE_TIME_FORMAT_PROPERTY, _localDateTimeFormat); _utilDateFormat = localProps.getProperty(UTIL_DATE_FORMAT_PROPERTY, _utilDateFormat); _localTimeFormat = localProps.getProperty(LOCAL_TIME_FORMAT_PROPERTY, _localTimeFormat); _localDateFormat = localProps.getProperty(LOCAL_DATE_FORMAT_PROPERTY, _localDateFormat); _instantFormat = localProps.getProperty(INSTANT_FORMAT_PROPERTY, _instantFormat); _sqlTimeFormat = localProps.getProperty(SQL_TIME_FORMAT_PROPERTY, _sqlTimeFormat); _timestampFormat = localProps.getProperty(TIMESTAMP_FORMAT_PROPERTY, _timestampFormat); _spaceURL = localProps.getProperty(SPACE_URL); _listenPort = getInteger(localProps.getProperty(PORT_PROPERTY), PORT_DEFAULT); // Get JDBC transaction configuration String txnType = localProps.getProperty(QueryProcessorInfo.QP_TRANSACTION_TYPE, QueryProcessorInfo.QP_TRANSACTION_TYPE_DEFAULT); TransactionManagerType transactionManagerType = TransactionManagerType.getValue(txnType); if (transactionManagerType == null) transactionManagerType = TransactionManagerType.DISTRIBUTED; _transactionManagerConfiguration = TransactionManagerConfiguration.newConfiguration(transactionManagerType); if (transactionManagerType == TransactionManagerType.LOOKUP_DISTRIBUTED) { LookupTransactionManagerConfiguration lookupConfiguration = (LookupTransactionManagerConfiguration) _transactionManagerConfiguration; lookupConfiguration.setLookupTransactionName(localProps.getProperty(QueryProcessorInfo.QP_LOOKUP_TRANSACTION_NAME, QueryProcessorInfo.QP_LOOKUP_TRANSACTION_NAME_DEFAULT)); lookupConfiguration.setLookupTransactionGroups(localProps.getProperty(QueryProcessorInfo.QP_LOOKUP_TRANSACTION_GROUPS, SystemInfo.singleton().lookup().defaultGroups())); lookupConfiguration.setLookupTransactionLocators(localProps.getProperty(QueryProcessorInfo.QP_LOOKUP_TRANSACTION_LOCATORS, QueryProcessorInfo.QP_LOOKUP_TRANSACTION_LOCATORS_DEFAULT)); lookupConfiguration.setLookupTransactionTimeout(getLong(localProps.getProperty(QueryProcessorInfo.QP_LOOKUP_TRANSACTION_TIMEOUT), QueryProcessorInfo.QP_LOOKUP_TRANSACTION_TIMEOUT_DEFAULT)); } } private static boolean getBoolean(String val, boolean defaultVal) { return val != null ? Boolean.parseBoolean(val) : defaultVal; } private static int getInteger(String val, int defaultVal) { return val != null ? Integer.parseInt(val) : defaultVal; } private static long getLong(String val, long defaultVal) { return val != null ? Long.parseLong(val) : defaultVal; } public int getReadLease() { return _readLease; } public void setReadLease(int readLease) { _readLease = readLease; } public long getWriteLease() { return _writeLease; } public void setWriteLease(long writeLease) { _writeLease = writeLease; } public long getTransactionTimeout() { return _transactionTimeout; } public void setTransactionTimeout(long transactionTimeout) { _transactionTimeout = transactionTimeout; } public boolean isParserCaseSensitivity() { return _parserCaseSensitivity; } public void setParserCaseSensitivity(boolean parserCaseSensitivity) { _parserCaseSensitivity = parserCaseSensitivity; } public String getUtilDateFormat() { return _utilDateFormat; } public void setUtilDateFormat(String dateFormat) { _utilDateFormat = dateFormat; } public String getSqlDateFormat() { return _sqlDateFormat; } public void setSqlDateFormat(String dateFormat) { _sqlDateFormat = dateFormat; } public String getLocalDateTimeFormat() { return _localDateTimeFormat; } public void setLocalDateTimeFormat(String localDateTimeFormat) { _localDateTimeFormat = localDateTimeFormat; } public String getLocalTimeFormat() { return _localTimeFormat; } public void setLocalTimeFormat(String localTimeFormat) { _localTimeFormat = localTimeFormat; } public String getLocalDateFormat() { return _localDateFormat; } public void setLocalDateFormat(String localDateFormat) { _localTimeFormat = localDateFormat; } public String getSqlTimeFormat() { return _sqlTimeFormat; } public void setSqlTimeFormat(String timeFormat) { _sqlTimeFormat = timeFormat; } public void setTimestampFormat(String timestampFormat) { _timestampFormat = timestampFormat; } public String getTimestampFormat() { return _timestampFormat; } public String getInstantFormat() { return _instantFormat; } public void setInstantFormat(String _instantFormat) { this._instantFormat = _instantFormat; } public boolean isTraceExecTime() { return _traceExecTime; } public void setTraceExecTime(boolean traceExecTime) { _traceExecTime = traceExecTime; } public boolean isAutoCommit() { return _autoCommit; } public void setAutoCommit(boolean autoCommit) { _autoCommit = autoCommit; } public String getSpaceURL() { return _spaceURL; } public void setSpaceURL(String spaceURL) { _spaceURL = spaceURL; } public int getListenPort() { return _listenPort; } public void setListenPort(int listenPort) { _listenPort = listenPort; } public TransactionManagerConfiguration getTransactionManagerConfiguration() { return _transactionManagerConfiguration; } }
Java
public class AutoConnectListener extends BroadcastReceiver { private static final String TAG = "Gibberbot.AutoConnectListener"; static boolean firstCall = true; public final static String BOOTFLAG = "BOOTFLAG"; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "AppConnectivityListener"); if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { try { setBootFlag(context); } catch (Exception e) { Log.e(TAG, "Unable to set BOOTFLAG file",e); } } if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { boolean noConnectivity = intent.getBooleanExtra( ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean prefStartOnBoot = prefs.getBoolean("pref_start_on_boot", true); boolean hasBootFlag = hasBootFlag (context); Log.d(TAG, "autostart IM service firstCall=" + firstCall + " noconn=" + noConnectivity); if (firstCall && !noConnectivity) { if ((!hasBootFlag) || prefStartOnBoot) //either we have already booted, so let's restart, or we want to start on boot { ImApp.getApplication().startImServiceIfNeed(true); firstCall = false; } } } } private void setBootFlag (Context context) throws IOException { File file = new File(context.getFilesDir(),BOOTFLAG); file.createNewFile(); } private boolean hasBootFlag (Context context) { return new File(context.getFilesDir(),BOOTFLAG).exists(); } }
Java
public static class ConcatResourceFilter implements Predicate<Resource> { private final Collection<Predicate<Resource>> filters; public ConcatResourceFilter(Collection<Predicate<Resource>> filters) { Objects.requireNonNull(filters); this.filters = new ArrayList<>(filters); } @Override public boolean test(Resource resource) { for (Predicate<Resource> f: filters) { if (!f.test(resource)) return false; } return true; } }
Java
@Route(path = "/main/service1") public class TestServiceImpl implements TestService { @Override public void test() { Log.e("TestService","我是Main中的service 1"); } }
Java
public class FileCollectTask extends AbstractCollectTask { @Override public int getTimeSpan() { return PropertyUtils.getPropertyCache("bsf.health.file.timeSpan", 20); } @Override public boolean getEnabled() { return PropertyUtils.getPropertyCache("bsf.health.file.enabled", true); } @Override public String getDesc() { return "File服务性能采集"; } @Override public String getName() { return "file.info"; } @Override protected Object getData() { FileInfo data = new FileInfo(); if (ContextUtils.getBean(ReflectionUtils.tryClassForName("com.yh.csx.bsf.file.impl.HotFileProvider"), false) != null) { data.provider = "hotfile"; } else if (ContextUtils.getBean(ReflectionUtils.tryClassForName("com.yh.csx.bsf.file.impl.QiniuFileProvider"),false) != null) { data.provider = "qiniu"; } if (data.provider != null) { var hook = (Collector.Hook)ReflectionUtils.callMethod(ReflectionUtils.classForName("com.yh.csx.bsf.file.impl.FileProviderMonitor"), "hook", null); data.hookCurrent = hook.getCurrent(); data.hookError = hook.getLastErrorPerSecond(); data.hookSuccess = hook.getLastSuccessPerSecond(); data.hookList = hook.getMaxTimeSpanList().toText(); data.hookListPerMinute = hook.getMaxTimeSpanListPerMinute().toText(); } return data; } @Data private static class FileInfo { @FieldReport(name = "file.provider", desc = "File服务提供者") private String provider; @FieldReport(name = "file.hook.error", desc = "File服务拦截上一次每秒出错次数") private Long hookError; @FieldReport(name = "file.hook.success", desc = "File服务拦截上一次每秒成功次数") private Long hookSuccess; @FieldReport(name = "file.hook.current", desc = "File服务拦截当前执行任务数") private Long hookCurrent; @FieldReport(name = "file.hook.list.detail", desc = "File服务拦截历史最大耗时任务列表") private String hookList; @FieldReport(name = "file.hook.list.minute.detail", desc = "File服务拦截历史最大耗时任务列表(每分钟)") private String hookListPerMinute; } }
Java
public class Histogram { /////////////////////////////////////////////////// // static members /////////////////////////////////////////////////// static double CLUSTER_TOLERANCE = 0.01; static double MAX_RESIDUAL_MASS = 0.1; static double MIN_COVERAGE_FACTOR = 0.2; /////////////////////////////////////////////////// // static classes /////////////////////////////////////////////////// static class FrequencyPair implements Comparable { int perChunkFrequency; int overallChunkCount; public FrequencyPair(int perChunkFrequency, int overallChunkCount) { this.perChunkFrequency = perChunkFrequency; this.overallChunkCount = overallChunkCount; } public int compareTo(Object o) { FrequencyPair other = (FrequencyPair) o; int cmp = overallChunkCount - other.overallChunkCount; if (cmp != 0) { return -1 * cmp; } else { cmp = perChunkFrequency - other.perChunkFrequency; return cmp; } } public int getPerChunkFrequency() { return perChunkFrequency; } public int getCount() { return overallChunkCount; } } ////////////////////////////////////////////////////////////// // Static methods: for computing histograms from data, // and for clustering the resulting histograms. ////////////////////////////////////////////////////////////// /** * Compute a statistical summary of the data. This will return a histogram * for each token type, indicating the relative proportion and distribution of * the token type in the chunkset. * * Thus, the size of the output of this function is relatively small: no larger * than the number of potential token types. However, it can take awhile to compute * if the input data size is huge. * * REMIND mjc - This fn may be a good candidate for runtime-perf optimization */ public static List<Histogram> computeNormalizedHistograms(List<List<Token.AbstractToken>> chunks) { Map<String, Map<Integer, Integer>> allHistograms = new TreeMap<String, Map<Integer, Integer>>(); List<Histogram> normalizedHistograms = new ArrayList<Histogram>(); // // 1. Compute some per-chunk statistics // for (List<Token.AbstractToken> chunk: chunks) { // Compute frequencies of token-type within this chunk HashMap<String, Integer> localFreq = new HashMap<String, Integer>(); for (Token.AbstractToken tok: chunk) { Integer count = (Integer) localFreq.get(tok.getId()); if (count == null) { localFreq.put(tok.getId(), 1); } else { localFreq.put(tok.getId(), count.intValue() + 1); } } // Now adjust the "histogram of frequencies" associated with each token type for (String tokenId: localFreq.keySet()) { Map<Integer, Integer> perTokenTypeHistogram = allHistograms.get(tokenId); if (perTokenTypeHistogram == null) { perTokenTypeHistogram = new HashMap<Integer, Integer>(); allHistograms.put(tokenId, perTokenTypeHistogram); } Integer currentTokenTypeCount = localFreq.get(tokenId); Integer countSoFar = perTokenTypeHistogram.get(currentTokenTypeCount); if (countSoFar == null) { perTokenTypeHistogram.put(currentTokenTypeCount, 1); } else { perTokenTypeHistogram.put(currentTokenTypeCount, countSoFar.intValue() + 1); } } } // // 2. Now for each per-token-type histogram, compute how many times the // token was observed in *no chunk at all*. // for (String tokenId: allHistograms.keySet()) { Map<Integer, Integer> perTokenTypeHistogram = allHistograms.get(tokenId); int numberOfChunksForObservedTokenTypeCount = 0; for (Integer currentTokenTypeCount: perTokenTypeHistogram.keySet()) { numberOfChunksForObservedTokenTypeCount += perTokenTypeHistogram.get(currentTokenTypeCount); } perTokenTypeHistogram.put(0, chunks.size() - numberOfChunksForObservedTokenTypeCount); } // // 3. Normalize the per-token-type histograms // for (Map.Entry<String, Map<Integer, Integer>> e1: allHistograms.entrySet()) { String tokenId = e1.getKey(); Map<Integer, Integer> perTokenTypeHistogram = e1.getValue(); double coverage = 0; double totalMass = 0; // 3.1. Compute the histogram's normal form: all the counts in descending order of prevalence in the chunk set. // Also, compute some metainfo stats along the way SortedSet<FrequencyPair> sorter = new TreeSet<FrequencyPair>(); for (Map.Entry<Integer, Integer> e2: perTokenTypeHistogram.entrySet()) { Integer perChunkFrequency = e2.getKey(); Integer overallChunkCount = e2.getValue(); if (perChunkFrequency.intValue() != 0) { coverage += overallChunkCount.intValue(); sorter.add(new FrequencyPair(perChunkFrequency, overallChunkCount)); } totalMass += overallChunkCount.intValue(); } List<FrequencyPair> normalForm = new ArrayList<FrequencyPair>(); for (FrequencyPair p: sorter) { normalForm.add(p); } normalForm.add(0, new FrequencyPair(0, perTokenTypeHistogram.get(0))); // 3.2. Compute metainfo double width = perTokenTypeHistogram.size()-1; double residualMass = (totalMass - normalForm.get(1).getCount()) / totalMass; // 3.3 Done with the histogram! normalizedHistograms.add(new Histogram(tokenId, normalForm, width, residualMass, coverage)); } return normalizedHistograms; } /** * Cluster together histograms that appear to be related. * * We currently employ agglomerative single-link clustering. That means: * a) We can imagine that each data elt starts as its own cluster * b) We merge clusters whenever the distance between clusters is less than CLUSTER_TOLERANCE * c) The distance between two clusters is determined by the *minimum distance between any two members of the cluster*. * This is sometimes called "single link" clustering. The resulting cluster quality is not as good as computing * distance based on the average of the members of a cluster, but it is more efficient. */ public static List<List<Histogram>> clusterHistograms(List<Histogram> inputHistograms) { // 1. Handle degenerate case of size(input) == 1 if (inputHistograms.size() == 1) { List<List<Histogram>> clusters = new ArrayList<List<Histogram>>(); clusters.add(inputHistograms); return clusters; } // 2. Otherwise, compute pairwise symmetric relative entropy among histograms class Score implements Comparable { double s; int i; int j; public Score(double s, int i, int j) { this.s = s; this.i = i; this.j = j; } public int getIndex1() { return i; } public int getIndex2() { return j; } public int compareTo(Object o) { Score other = (Score) o; if (this.s < other.s) { return -1; } else if (this.s > other.s) { return 1; } else { int cmp = this.i - other.i; if (cmp == 0) { cmp = this.j - other.j; } return cmp; } } } SortedSet<Score> scores = new TreeSet<Score>(); for (int i = 0; i < inputHistograms.size(); i++) { for (int j = i+1; j < inputHistograms.size(); j++) { Histogram h1 = inputHistograms.get(i); Histogram h2 = inputHistograms.get(j); double sre = h1.computeSymmetricRelativeEntropy(h2); if (sre < CLUSTER_TOLERANCE) { scores.add(new Score(sre, i, j)); } } } // Initialize clusters Map<Integer, Integer> histogramToCluster = new TreeMap<Integer, Integer>(); Map<Integer, Set<Integer>> clusterToHistograms = new TreeMap<Integer, Set<Integer>>(); for (int i = 0; i < inputHistograms.size(); i++) { histogramToCluster.put(i, i); Set<Integer> containedHistograms = new HashSet<Integer>(); containedHistograms.add(i); clusterToHistograms.put(i, containedHistograms); } // Start merging clusters for (Score s: scores) { int idx1 = s.getIndex1(); int idx2 = s.getIndex2(); int cluster1 = histogramToCluster.get(idx1); int cluster2 = histogramToCluster.get(idx2); if (cluster1 == cluster2) { continue; } for (Integer histogramId: clusterToHistograms.get(cluster2)) { histogramToCluster.put(histogramId, cluster1); } clusterToHistograms.get(cluster1).addAll(clusterToHistograms.get(cluster2)); clusterToHistograms.remove(cluster2); } // Build the clustered histogram list. List<List<Histogram>> clusters = new ArrayList<List<Histogram>>(); for (Map.Entry<Integer, Set<Integer>> entry: clusterToHistograms.entrySet()) { Integer clusterId = entry.getKey(); Set<Integer> histograms = entry.getValue(); List<Histogram> curCluster = new ArrayList<Histogram>(); for (Integer histogramIndex: histograms) { curCluster.add(inputHistograms.get(histogramIndex)); } clusters.add(curCluster); } return clusters; } ////////////////////////////////////////////////////////////// // Members ////////////////////////////////////////////////////////////// String histogramType; List<FrequencyPair> normalForm; double width; double residualMass; double coverage; ////////////////////////////////////////////////////////////// // Methods ////////////////////////////////////////////////////////////// public Histogram(String histogramType, List<FrequencyPair> normalForm, double width, double residualMass, double coverage) { this.histogramType = histogramType; this.normalForm = normalForm; this.width = width; this.residualMass = residualMass; this.coverage = coverage; } public boolean passStructStatisticalTest(int numChunks) { return residualMass < MAX_RESIDUAL_MASS && coverage > MIN_COVERAGE_FACTOR * numChunks; } public boolean passArrayStatisticalTest(int numChunks) { return width > 3 && coverage > MIN_COVERAGE_FACTOR * numChunks; } public String getHistogramType() { return histogramType; } public double getWidth() { return width; } public double getResidualMass() { return residualMass; } public double getCoverage() { return coverage; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("Histogram: type=" + histogramType + ", width=" + width + ", residualMass=" + residualMass + ", coverage=" + coverage + ", normalForm=["); for (FrequencyPair fp: normalForm) { buf.append("(" + fp.getPerChunkFrequency() + ", " + fp.getCount() + ") "); } buf.append("]"); return buf.toString(); } /** * The relative entropy score is used for clustering. However, we can't compute * it directly, as histograms do not always contain the same components. Instead, * we preprocess the data with computeSymmetricRelativeEntropy(), then pass the resulting * averaged values into this pretty generic method. */ double computeRelativeEntropy(List<Double> avgCounts) { double total = 0; for (int i = 1; i < normalForm.size(); i++) { double selfOverallChunkCount = normalForm.get(i).getCount(); double otherOverallChunkCount = avgCounts.get(i); total += selfOverallChunkCount * Math.log(selfOverallChunkCount / otherOverallChunkCount); } return total; } /** * The point of this method is to preprocess the data from two input Histograms, * getting it ready for the relative entropy computation. Without this preprocessing, * the rel-entropy computation would be sensitive to varying numbers of components in each histogram. */ double computeSymmetricRelativeEntropy(Histogram other) { List<Double> avgCounts = new ArrayList<Double>(); for (int i = 0; i < Math.max(normalForm.size(), other.normalForm.size()); i++) { if ((i < normalForm.size()) && (i < other.normalForm.size())) { avgCounts.add((normalForm.get(i).getCount() + other.normalForm.get(i).getCount()) / 2.0); } else if (i < normalForm.size()) { avgCounts.add(normalForm.get(i).getCount() * 0.5); } else { avgCounts.add(other.normalForm.get(i).getCount() * 0.5); } } return 0.5 * this.computeRelativeEntropy(avgCounts) + 0.5 * other.computeRelativeEntropy(avgCounts); } }