code
stringlengths
73
34.1k
label
stringclasses
1 value
public static ByteBuffer newDirectByteBuffer(long addr, int size, Object att) { dbbCC.setAccessible(true); Object b = null; try { b = dbbCC.newInstance(new Long(addr), new Integer(size), att); return ByteBuffer.class.cast(b); } catch(Exception e) { throw new IllegalStateException(String.format("Failed to create DirectByteBuffer: %s", e.getMessage())); } }
java
public void releaseAll() { synchronized(this) { Object[] refSet = allocatedMemoryReferences.values().toArray(); if(refSet.length != 0) { logger.finer("Releasing allocated memory regions"); } for(Object ref : refSet) { release((MemoryReference) ref); } } }
java
public static String md5sum(InputStream input) throws IOException { InputStream in = new BufferedInputStream(input); try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); DigestInputStream digestInputStream = new DigestInputStream(in, digest); while(digestInputStream.read() >= 0) { } OutputStream md5out = new ByteArrayOutputStream(); md5out.write(digest.digest()); return md5out.toString(); } catch(NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 algorithm is not available: " + e.getMessage()); } finally { in.close(); } }
java
public void fill(long offset, long length, byte value) { unsafe.setMemory(address() + offset, length, value); }
java
public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) { int cursor = destOffset; for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) { int bbSize = bb.remaining(); if ((cursor + bbSize) > destArray.length) throw new ArrayIndexOutOfBoundsException(String.format("cursor + bbSize = %,d", cursor + bbSize)); bb.get(destArray, cursor, bbSize); cursor += bbSize; } }
java
public void copyTo(long srcOffset, LBufferAPI dest, long destOffset, long size) { unsafe.copyMemory(address() + srcOffset, dest.address() + destOffset, size); }
java
public LBuffer slice(long from, long to) { if(from > to) throw new IllegalArgumentException(String.format("invalid range %,d to %,d", from, to)); long size = to - from; LBuffer b = new LBuffer(size); copyTo(from, b, 0, size); return b; }
java
public byte[] toArray() { if (size() > Integer.MAX_VALUE) throw new IllegalStateException("Cannot create byte array of more than 2GB"); int len = (int) size(); ByteBuffer bb = toDirectByteBuffer(0L, len); byte[] b = new byte[len]; // Copy data to the array bb.get(b, 0, len); return b; }
java
public void writeTo(WritableByteChannel channel) throws IOException { for (ByteBuffer buffer : toDirectByteBuffers()) { channel.write(buffer); } }
java
public void writeTo(File file) throws IOException { FileChannel channel = new FileOutputStream(file).getChannel(); try { writeTo(channel); } finally { channel.close(); } }
java
public int readFrom(byte[] src, int srcOffset, long destOffset, int length) { int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length)); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src, srcOffset, readLen); return readLen; }
java
public int readFrom(ByteBuffer src, long destOffset) { if (src.remaining() + destOffset >= size()) throw new BufferOverflowException(); int readLen = src.remaining(); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src); return readLen; }
java
public static LBuffer loadFrom(File file) throws IOException { FileChannel fin = new FileInputStream(file).getChannel(); long fileSize = fin.size(); if (fileSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Cannot load from file more than 2GB: " + file); LBuffer b = new LBuffer((int) fileSize); long pos = 0L; WritableChannelWrap ch = new WritableChannelWrap(b); while (pos < fileSize) { pos += fin.transferTo(0, fileSize, ch); } return b; }
java
public ByteBuffer[] toDirectByteBuffers(long offset, long size) { long pos = offset; long blockSize = Integer.MAX_VALUE; long limit = offset + size; int numBuffers = (int) ((size + (blockSize - 1)) / blockSize); ByteBuffer[] result = new ByteBuffer[numBuffers]; int index = 0; while (pos < limit) { long blockLength = Math.min(limit - pos, blockSize); result[index++] = UnsafeUtil.newDirectByteBuffer(address() + pos, (int) blockLength, this) .order(ByteOrder.nativeOrder()); pos += blockLength; } return result; }
java
public String getWrappingHint(String fieldName) { if (isEmpty()) { return ""; } return String.format(" You can use this expression: %s(%s(%s))", formatMethod(wrappingMethodOwnerName, wrappingMethodName, ""), formatMethod(copyMethodOwnerName, copyMethodName, copyTypeParameterName), fieldName); }
java
public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable, final Collection<ControlFlowBlock> controlFlowBlocks) { return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks)); }
java
public Collection<FieldNode> removeAndGetCandidatesWithoutInitialisingMethod() { final List<FieldNode> result = new ArrayList<FieldNode>(); for (final Map.Entry<FieldNode, Initialisers> entry : candidatesAndInitialisers.entrySet()) { final Initialisers setters = entry.getValue(); final List<MethodNode> initialisingMethods = setters.getMethods(); if (initialisingMethods.isEmpty()) { result.add(entry.getKey()); } } for (final FieldNode unassociatedVariable : result) { candidatesAndInitialisers.remove(unassociatedVariable); } return result; }
java
protected final void verify() { collectInitialisers(); verifyCandidates(); verifyInitialisers(); collectPossibleInitialValues(); verifyPossibleInitialValues(); collectEffectiveAssignmentInstructions(); verifyEffectiveAssignmentInstructions(); collectAssignmentGuards(); verifyAssignmentGuards(); end(); }
java
protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) { Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream() .collect(Collectors.toMap(r -> r.className, r -> r)); resultsMap.putAll(otherConfiguration.hardcodedResults()); hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values()); }
java
protected void mergeImmutableContainerTypesFrom(Configuration otherConfiguration) { Set<Dotted> union = Sets.union(hardcodedImmutableContainerClasses.build(), otherConfiguration.immutableContainerClasses()); hardcodedImmutableContainerClasses = ImmutableSet.<Dotted>builder().addAll(union); }
java
protected final void hardcodeValidCopyMethod(Class<?> fieldType, String fullyQualifiedMethodName, Class<?> argType) { if (argType==null || fieldType==null || fullyQualifiedMethodName==null) { throw new IllegalArgumentException("All parameters must be supplied - no nulls"); } String className = fullyQualifiedMethodName.substring(0, fullyQualifiedMethodName.lastIndexOf(".")); String methodName = fullyQualifiedMethodName.substring(fullyQualifiedMethodName.lastIndexOf(".")+1); String desc = null; try { if (MethodIs.aConstructor(methodName)) { Constructor<?> ctor = Class.forName(className).getDeclaredConstructor(argType); desc = Type.getConstructorDescriptor(ctor); } else { Method method = Class.forName(className).getMethod(methodName, argType); desc = Type.getMethodDescriptor(method); } } catch (NoSuchMethodException e) { rethrow("No such method", e); } catch (SecurityException e) { rethrow("Security error", e); } catch (ClassNotFoundException e) { rethrow("Class not found", e); } CopyMethod copyMethod = new CopyMethod(dotted(className), methodName, desc); hardcodeValidCopyMethod(fieldType, copyMethod); }
java
public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) { checkArgument(!variableName.isEmpty()); return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine)); }
java
private void generateCopyingPart(WrappingHint.Builder builder) { ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder() .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS) .putAll(userDefinedCopyMethods) .build() .get(typeAssignedToField); if (copyMethods.isEmpty()) { throw new WrappingHintGenerationException(); } CopyMethod firstSuitable = copyMethods.iterator().next(); builder.setCopyMethodOwnerName(firstSuitable.owner.toString()) .setCopyMethodName(firstSuitable.name); if (firstSuitable.isGeneric && typeSignature != null) { CollectionField withRemovedWildcards = CollectionField.from(typeAssignedToField, typeSignature) .transformGenericTree(GenericType::withoutWildcard); builder.setCopyTypeParameterName(formatTypeParameter(withRemovedWildcards.asSimpleString())); } }
java
private void generateWrappingPart(WrappingHint.Builder builder) { builder.setWrappingMethodOwnerName(configuration.UNMODIFIABLE_METHOD_OWNER) .setWrappingMethodName(configuration.FIELD_TYPE_TO_UNMODIFIABLE_METHOD.get(typeAssignedToField)); }
java
public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; if(paintBorder != null) paintBorder.setStrokeWidth(borderWidth); requestLayout(); invalidate(); }
java
public void setShadow(float radius, float dx, float dy, int color) { shadowRadius = radius; shadowDx = dx; shadowDy = dy; shadowColor = color; updateShadow(); }
java
public Bitmap drawableToBitmap(Drawable drawable) { if (drawable == null) // Don't do anything without a proper drawable return null; else if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable Log.i(TAG, "Bitmap drawable!"); return ((BitmapDrawable) drawable).getBitmap(); } int intrinsicWidth = drawable.getIntrinsicWidth(); int intrinsicHeight = drawable.getIntrinsicHeight(); if (!(intrinsicWidth > 0 && intrinsicHeight > 0)) return null; try { // Create Bitmap object out of the drawable Bitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (OutOfMemoryError e) { // Simply return null of failed bitmap creations Log.e(TAG, "Encountered OutOfMemoryError while generating bitmap!"); return null; } }
java
public void updateBitmapShader() { if (image == null) return; shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); if(canvasSize != image.getWidth() || canvasSize != image.getHeight()) { Matrix matrix = new Matrix(); float scale = (float) canvasSize / (float) image.getWidth(); matrix.setScale(scale, scale); shader.setLocalMatrix(matrix); } }
java
public void refreshBitmapShader() { shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); }
java
private int calcItemWidth(RecyclerView rvCategories) { if (itemWidth == null || itemWidth == 0) { for (int i = 0; i < rvCategories.getChildCount(); i++) { itemWidth = rvCategories.getChildAt(i).getWidth(); if (itemWidth != 0) { break; } } } // in case of call before view was created if (itemWidth == null) { itemWidth = 0; } return itemWidth; }
java
public final void setOrientation(int orientation) { mOrientation = orientation; mOrientationState = getOrientationStateFromParam(mOrientation); invalidate(); if (mOuterAdapter != null) { mOuterAdapter.setOrientation(mOrientation); } }
java
@SuppressWarnings("unused") public void selectItem(int position, boolean invokeListeners) { IOperationItem item = mOuterAdapter.getItem(position); IOperationItem oldHidedItem = mOuterAdapter.getItem(mRealHidedPosition); int realPosition = mOuterAdapter.normalizePosition(position); //do nothing if position not changed if (realPosition == mCurrentItemPosition) { return; } int itemToShowAdapterPosition = position - realPosition + mRealHidedPosition; item.setVisible(false); startSelectedViewOutAnimation(position); mOuterAdapter.notifyRealItemChanged(position); mRealHidedPosition = realPosition; oldHidedItem.setVisible(true); mFlContainerSelected.requestLayout(); mOuterAdapter.notifyRealItemChanged(itemToShowAdapterPosition); mCurrentItemPosition = realPosition; if (invokeListeners) { notifyItemClickListeners(realPosition); } if (BuildConfig.DEBUG) { Log.i(TAG, "clicked on position =" + position); } }
java
public IOrientationState getOrientationStateFromParam(int orientation) { switch (orientation) { case Orientation.ORIENTATION_HORIZONTAL_BOTTOM: return new OrientationStateHorizontalBottom(); case Orientation.ORIENTATION_HORIZONTAL_TOP: return new OrientationStateHorizontalTop(); case Orientation.ORIENTATION_VERTICAL_LEFT: return new OrientationStateVerticalLeft(); case Orientation.ORIENTATION_VERTICAL_RIGHT: return new OrientationStateVerticalRight(); default: return new OrientationStateHorizontalBottom(); } }
java
@Override public <T extends ViewGroup.MarginLayoutParams> T setSelectionMargin(int marginPx, T layoutParams) { return mSelectionGravityState.setSelectionMargin(marginPx, layoutParams); }
java
public int consume(Map<String, String> initialVars) { int result = 0; for (int i = 0; i < repeatNumber; i++) { result += super.consume(initialVars); } return result; }
java
public static void main(String[] args) { String modelFile = ""; String outputFile = ""; int numberOfRows = 0; try { modelFile = args[0]; outputFile = args[1]; numberOfRows = Integer.valueOf(args[2]); } catch (IndexOutOfBoundsException | NumberFormatException e) { System.out.println("ERROR! Invalid command line arguments, expecting: <scxml model file> " + "<desired csv output file> <desired number of output rows>"); return; } FileInputStream model = null; try { model = new FileInputStream(modelFile); } catch (FileNotFoundException e) { System.out.println("ERROR! Model file not found"); return; } SCXMLEngine engine = new SCXMLEngine(); engine.setModelByInputFileStream(model); engine.setBootstrapMin(5); DataConsumer consumer = new DataConsumer(); CSVFileWriter writer; try { writer = new CSVFileWriter(outputFile); } catch (IOException e) { System.out.println("ERROR! Can not write to output csv file"); return; } consumer.addDataWriter(writer); DefaultDistributor dist = new DefaultDistributor(); dist.setThreadCount(5); dist.setMaxNumberOfLines(numberOfRows); dist.setDataConsumer(consumer); engine.process(dist); writer.closeCSVFile(); System.out.println("COMPLETE!"); }
java
public static Tuple2<Double, Double> getRandomGeographicalLocation() { return new Tuple2<>( (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100, (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100); }
java
public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { // sqrt( (x2-x1)^2 + (y2-y2)^2 ) Double xDiff = point1._1() - point2._1(); Double yDiff = point1._2() - point2._2(); return Math.sqrt(xDiff * xDiff + yDiff * yDiff); }
java
public static Double getDistanceWithinThresholdOfCoordinates( Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { throw new NotImplementedError(); }
java
public static Boolean areCoordinatesWithinThreshold(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { return getDistanceBetweenCoordinates(point1, point2) < COORDINATE_THRESHOLD; }
java
public static void main(String[] args) { //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal--> //MODEL USAGE EXAMPLE: <assign name="var_out_V1_2" expr="%ssn"/> <dg:transform name="EQ"/> Map<String, DataTransformer> transformers = new HashMap<String, DataTransformer>(); transformers.put("EQ", new EquivalenceClassTransformer()); Vector<CustomTagExtension> cte = new Vector<CustomTagExtension>(); cte.add(new InLineTransformerExtension(transformers)); Engine engine = new SCXMLEngine(cte); //will default to samplemachine, but you could specify a different file if you choose to InputStream is = CmdLine.class.getResourceAsStream("/" + (args.length == 0 ? "samplemachine" : args[0]) + ".xml"); engine.setModelByInputFileStream(is); // Usually, this should be more than the number of threads you intend to run engine.setBootstrapMin(1); //Prepare the consumer with the proper writer and transformer DataConsumer consumer = new DataConsumer(); consumer.addDataTransformer(new SampleMachineTransformer()); //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation. //MODEL USAGE EXAMPLE: <dg:assign name="var_out_V2" set="%regex([0-9]{3}[A-Z0-9]{5})"/> consumer.addDataTransformer(new EquivalenceClassTransformer()); consumer.addDataWriter(new DefaultWriter(System.out, new String[]{"var_1_1", "var_1_2", "var_1_3", "var_1_4", "var_1_5", "var_1_6", "var_1_7", "var_2_1", "var_2_2", "var_2_3", "var_2_4", "var_2_5", "var_2_6", "var_2_7", "var_2_8"})); //Prepare the distributor DefaultDistributor defaultDistributor = new DefaultDistributor(); defaultDistributor.setThreadCount(1); defaultDistributor.setDataConsumer(consumer); Logger.getLogger("org.apache").setLevel(Level.WARN); engine.process(defaultDistributor); }
java
public static UserStub getStubWithRandomParams(UserTypeVal userType) { // Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles! // Oh the joys of type erasure. Tuple2<Double, Double> tuple = SocialNetworkUtilities.getRandomGeographicalLocation(); return new UserStub(userType, new Tuple2<>((Double) tuple._1(), (Double) tuple._2()), SocialNetworkUtilities.getRandomIsSecret()); }
java
public void writeOutput(DataPipe cr) { String[] nextLine = new String[cr.getDataMap().entrySet().size()]; int count = 0; for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) { nextLine[count] = entry.getValue(); count++; } csvFile.writeNext(nextLine); }
java
public boolean isHoliday(String dateString) { boolean isHoliday = false; for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) { if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) { isHoliday = true; } } return isHoliday; }
java
public String getNextDay(String dateString, boolean onlyBusinessDays) { DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime date = parser.parseDateTime(dateString).plusDays(1); Calendar cal = Calendar.getInstance(); cal.setTime(date.toDate()); if (onlyBusinessDays) { if (cal.get(Calendar.DAY_OF_WEEK) == 1 || cal.get(Calendar.DAY_OF_WEEK) == 7 || isHoliday(date.toString().substring(0, 10))) { return getNextDay(date.toString().substring(0, 10), true); } else { return parser.print(date); } } else { return parser.print(date); } }
java
public Date toDate(String dateString) { Date date = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { date = df.parse(dateString); } catch (ParseException ex) { System.out.println(ex.fillInStackTrace()); } return date; }
java
public String getRandomHoliday(String earliest, String latest) { String dateString = ""; DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime earlyDate = parser.parseDateTime(earliest); DateTime lateDate = parser.parseDateTime(latest); List<Holiday> holidays = new LinkedList<>(); int min = Integer.parseInt(earlyDate.toString().substring(0, 4)); int max = Integer.parseInt(lateDate.toString().substring(0, 4)); int range = max - min + 1; int randomYear = (int) (Math.random() * range) + min; for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) { holidays.add(s); } Collections.shuffle(holidays); for (Holiday holiday : holidays) { dateString = convertToReadableDate(holiday.forYear(randomYear)); if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) { break; } } return dateString; }
java
public int numOccurrences(int year, int month, int day) { DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime date = parser.parseDateTime(year + "-" + month + "-" + "01"); Calendar cal = Calendar.getInstance(); cal.setTime(date.toDate()); GregorianChronology calendar = GregorianChronology.getInstance(); DateTimeField field = calendar.dayOfMonth(); int days = 0; int count = 0; int num = field.getMaximumValue(new LocalDate(year, month, day, calendar)); while (days < num) { if (cal.get(Calendar.DAY_OF_WEEK) == day) { count++; } date = date.plusDays(1); cal.setTime(date.toDate()); days++; } return count; }
java
public String convertToReadableDate(Holiday holiday) { DateTimeFormatter parser = ISODateTimeFormat.date(); if (holiday.isInDateForm()) { String month = Integer.toString(holiday.getMonth()).length() < 2 ? "0" + holiday.getMonth() : Integer.toString(holiday.getMonth()); String day = Integer.toString(holiday.getDayOfMonth()).length() < 2 ? "0" + holiday.getDayOfMonth() : Integer.toString(holiday.getDayOfMonth()); return holiday.getYear() + "-" + month + "-" + day; } else { /* * 5 denotes the final occurrence of the day in the month. Need to find actual * number of occurrences */ if (holiday.getOccurrence() == 5) { holiday.setOccurrence(numOccurrences(holiday.getYear(), holiday.getMonth(), holiday.getDayOfWeek())); } DateTime date = parser.parseDateTime(holiday.getYear() + "-" + holiday.getMonth() + "-" + "01"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date.toDate()); int count = 0; while (count < holiday.getOccurrence()) { if (calendar.get(Calendar.DAY_OF_WEEK) == holiday.getDayOfWeek()) { count++; if (count == holiday.getOccurrence()) { break; } } date = date.plusDays(1); calendar.setTime(date.toDate()); } return date.toString().substring(0, 10); } }
java
public synchronized String requestBlock(String name) { if (blocks.isEmpty()) { return "exit"; } remainingBlocks.decrementAndGet(); return blocks.poll().createResponse(); }
java
public String makeReport(String name, String report) { long increment = Long.valueOf(report); long currentLineCount = globalLineCounter.addAndGet(increment); if (currentLineCount >= maxScenarios) { return "exit"; } else { return "ok"; } }
java
public void prepareStatus() { globalLineCounter = new AtomicLong(0); time = new AtomicLong(System.currentTimeMillis()); startTime = System.currentTimeMillis(); lastCount = 0; // Status thread regularly reports on what is happening Thread statusThread = new Thread() { public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Status thread interrupted"); } long thisTime = System.currentTimeMillis(); long currentCount = globalLineCounter.get(); if (thisTime - time.get() > 1000) { long oldTime = time.get(); time.set(thisTime); double avgRate = 1000.0 * currentCount / (thisTime - startTime); double instRate = 1000.0 * (currentCount - lastCount) / (thisTime - oldTime); lastCount = currentCount; System.out.println(currentCount + " AvgRage:" + ((int) avgRate) + " lines/sec instRate:" + ((int) instRate) + " lines/sec Unassigned Work: " + remainingBlocks.get() + " blocks"); } } } }; statusThread.start(); }
java
public void prepareServer() { try { server = new Server(0); jettyHandler = new AbstractHandler() { public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); String[] operands = request.getRequestURI().split("/"); String name = ""; String command = ""; String value = ""; //operands[0] = "", request starts with a "/" if (operands.length >= 2) { name = operands[1]; } if (operands.length >= 3) { command = operands[2]; } if (operands.length >= 4) { value = operands[3]; } if (command.equals("report")) { //report a number of lines written response.getWriter().write(makeReport(name, value)); } else if (command.equals("request") && value.equals("block")) { //request a new block of work response.getWriter().write(requestBlock(name)); } else if (command.equals("request") && value.equals("name")) { //request a new name to report with response.getWriter().write(requestName()); } else { //non recognized response response.getWriter().write("exit"); } ((Request) request).setHandled(true); } }; server.setHandler(jettyHandler); // Select any available port server.start(); Connector[] connectors = server.getConnectors(); NetworkConnector nc = (NetworkConnector) connectors[0]; listeningPort = nc.getLocalPort(); hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { e.printStackTrace(); } }
java
public String getXmlFormatted(Map<String, String> dataMap) { StringBuilder sb = new StringBuilder(); for (String var : outTemplate) { sb.append(appendXmlStartTag(var)); sb.append(dataMap.get(var)); sb.append(appendXmlEndingTag(var)); } return sb.toString(); }
java
private String appendXmlStartTag(String value) { StringBuilder sb = new StringBuilder(); sb.append("<").append(value).append(">"); return sb.toString(); }
java
private String appendXmlEndingTag(String value) { StringBuilder sb = new StringBuilder(); sb.append("</").append(value).append(">"); return sb.toString(); }
java
private Map<String, String> fillInitialVariables() { Map<String, TransitionTarget> targets = model.getChildren(); Set<String> variables = new HashSet<>(); for (TransitionTarget target : targets.values()) { OnEntry entry = target.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { if (action instanceof Assign) { String variable = ((Assign) action).getName(); variables.add(variable); } else if (action instanceof SetAssignExtension.SetAssignTag) { String variable = ((SetAssignExtension.SetAssignTag) action).getName(); variables.add(variable); } } } Map<String, String> result = new HashMap<>(); for (String variable : variables) { result.put(variable, ""); } return result; }
java
public List<PossibleState> bfs(int min) throws ModelException { List<PossibleState> bootStrap = new LinkedList<>(); TransitionTarget initial = model.getInitialTarget(); PossibleState initialState = new PossibleState(initial, fillInitialVariables()); bootStrap.add(initialState); while (bootStrap.size() < min) { PossibleState state = bootStrap.remove(0); TransitionTarget nextState = state.nextState; if (nextState.getId().equalsIgnoreCase("end")) { throw new ModelException("Could not achieve required bootstrap without reaching end state"); } //run every action in series List<Map<String, String>> product = new LinkedList<>(); product.add(new HashMap<>(state.variables)); OnEntry entry = nextState.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { for (CustomTagExtension tagExtension : tagExtensionList) { if (tagExtension.getTagActionClass().isInstance(action)) { product = tagExtension.pipelinePossibleStates(action, product); } } } //go through every transition and see which of the products are valid, adding them to the list List<Transition> transitions = nextState.getTransitionsList(); for (Transition transition : transitions) { String condition = transition.getCond(); TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0); for (Map<String, String> p : product) { Boolean pass; if (condition == null) { pass = true; } else { //scrub the context clean so we may use it to evaluate transition conditional Context context = this.getRootContext(); context.reset(); //set up new context for (Map.Entry<String, String> e : p.entrySet()) { context.set(e.getKey(), e.getValue()); } //evaluate condition try { pass = (Boolean) this.getEvaluator().eval(context, condition); } catch (SCXMLExpressionException ex) { pass = false; } } //transition condition satisfied, add to bootstrap list if (pass) { PossibleState result = new PossibleState(target, p); bootStrap.add(result); } } } } return bootStrap; }
java
public void process(SearchDistributor distributor) { List<PossibleState> bootStrap; try { bootStrap = bfs(bootStrapMin); } catch (ModelException e) { bootStrap = new LinkedList<>(); } List<Frontier> frontiers = new LinkedList<>(); for (PossibleState p : bootStrap) { SCXMLFrontier dge = new SCXMLFrontier(p, model, tagExtensionList); frontiers.add(dge); } distributor.distribute(frontiers); }
java
public void setModelByInputFileStream(InputStream inputFileStream) { try { this.model = SCXMLParser.parse(new InputSource(inputFileStream), null, customActionsFromTagExtensions()); this.setStateMachine(this.model); } catch (IOException | SAXException | ModelException e) { e.printStackTrace(); } }
java
public void setModelByText(String model) { try { InputStream is = new ByteArrayInputStream(model.getBytes()); this.model = SCXMLParser.parse(new InputSource(is), null, customActionsFromTagExtensions()); this.setStateMachine(this.model); } catch (IOException | SAXException | ModelException e) { e.printStackTrace(); } }
java
public List<Set<String>> makeNWiseTuples(String[] variables, int nWise) { List<Set<String>> completeTuples = new ArrayList<>(); makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet<String>(), nWise); return completeTuples; }
java
public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) { List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise); List<Map<String, String>> testCases = new ArrayList<>(); for (Set<String> tuple : tuples) { testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains)); } return testCases; }
java
public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) { String[] coVariables = action.getCoVariables().split(","); int n = Integer.valueOf(action.getN()); List<Map<String, String>> newPossibleStateList = new ArrayList<>(); for (Map<String, String> possibleState : possibleStateList) { Map<String, String[]> variableDomains = new HashMap<>(); Map<String, String> defaultVariableValues = new HashMap<>(); for (String variable : coVariables) { String variableMetaInfo = possibleState.get(variable); String[] variableDomain = variableMetaInfo.split(","); variableDomains.put(variable, variableDomain); defaultVariableValues.put(variable, variableDomain[0]); } List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains); for (Map<String, String> nWiseCombination : nWiseCombinations) { Map<String, String> newPossibleState = new HashMap<>(possibleState); newPossibleState.putAll(defaultVariableValues); newPossibleState.putAll(nWiseCombination); newPossibleStateList.add(newPossibleState); } } return newPossibleStateList; }
java
public void transform(DataPipe cr) { Map<String, String> map = cr.getDataMap(); for (String key : map.keySet()) { String value = map.get(key); if (value.equals("#{customplaceholder}")) { // Generate a random number int ran = rand.nextInt(); map.put(key, String.valueOf(ran)); } else if (value.equals("#{divideBy2}")) { String i = map.get("var_out_V3"); String result = String.valueOf(Integer.valueOf(i) / 2); map.put(key, result); } } }
java
@Override public void processOutput(Map<String, String> resultsMap) { queue.add(resultsMap); if (queue.size() > 10000) { log.info("Queue size " + queue.size() + ", waiting"); try { Thread.sleep(500); } catch (InterruptedException ex) { log.info("Interrupted ", ex); } } }
java
public void writeOutput(DataPipe cr) { try { context.write(NullWritable.get(), new Text(cr.getPipeDelimited(outTemplate))); } catch (Exception e) { throw new RuntimeException("Exception occurred while writing to Context", e); } }
java
public Map<String, String> decompose(Frontier frontier, String modelText) { if (!(frontier instanceof SCXMLFrontier)) { return null; } TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState; Map<String, String> variables = ((SCXMLFrontier) frontier).getRoot().variables; Map<String, String> decomposition = new HashMap<String, String>(); decomposition.put("target", target.getId()); StringBuilder packedVariables = new StringBuilder(); for (Map.Entry<String, String> variable : variables.entrySet()) { packedVariables.append(variable.getKey()); packedVariables.append("::"); packedVariables.append(variable.getValue()); packedVariables.append(";"); } decomposition.put("variables", packedVariables.toString()); decomposition.put("model", modelText); return decomposition; }
java
public static void printHelp(final Options options) { Collection<Option> c = options.getOptions(); System.out.println("Command line options are:"); int longestLongOption = 0; for (Option op : c) { if (op.getLongOpt().length() > longestLongOption) { longestLongOption = op.getLongOpt().length(); } } longestLongOption += 2; String spaces = StringUtils.repeat(" ", longestLongOption); for (Option op : c) { System.out.print("\t-" + op.getOpt() + " --" + op.getLongOpt()); if (op.getLongOpt().length() < spaces.length()) { System.out.print(spaces.substring(op.getLongOpt().length())); } else { System.out.print(" "); } System.out.println(op.getDescription()); } }
java
public static void main(String[] args) { CmdLine cmd = new CmdLine(); Configuration conf = new Configuration(); int res = 0; try { res = ToolRunner.run(conf, cmd, args); } catch (Exception e) { System.err.println("Error while running MR job"); e.printStackTrace(); } System.exit(res); }
java
public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) { return JavaConverters.asScalaIterableConverter(linkedList).asScala(); }
java
public static <T> T flattenOption(scala.Option<T> option) { if (option.isEmpty()) { return null; } else { return option.get(); } }
java
public List<Map<String, String>> pipelinePossibleStates(Assign action, List<Map<String, String>> possibleStateList) { for (Map<String, String> possibleState : possibleStateList) { possibleState.put(action.getName(), action.getExpr()); } return possibleStateList; }
java
public JSONObject getJsonFormatted(Map<String, String> dataMap) { JSONObject oneRowJson = new JSONObject(); for (int i = 0; i < outTemplate.length; i++) { oneRowJson.put(outTemplate[i], dataMap.get(outTemplate[i])); } return oneRowJson; }
java
public Vector<Graph<UserStub>> generateAllNodeDataTypeGraphCombinationsOfMaxLength(int length) { Vector<Graph<UserStub>> graphs = super.generateAllNodeDataTypeGraphCombinationsOfMaxLength(length); if (WRITE_STRUCTURES_IN_PARALLEL) { // Left as an exercise to the student. throw new NotImplementedError(); } else { int i = 0; for (Iterator<Graph<UserStub>> iter = graphs.toIterator(); iter.hasNext();) { Graph<UserStub> graph = iter.next(); graph.setGraphId("S_" + ++i + "_" + graph.allNodes().size()); graph.writeDotFile(outDir + graph.graphId() + ".gv", false, ALSO_WRITE_AS_PNG); } System.out.println("Wrote " + i + " graph files in DOT format to " + outDir + ""); } return graphs; }
java
public int consume(Map<String, String> initialVars) { this.dataPipe = new DataPipe(this); // Set initial variables for (Map.Entry<String, String> ent : initialVars.entrySet()) { dataPipe.getDataMap().put(ent.getKey(), ent.getValue()); } // Call transformers for (DataTransformer dc : dataTransformers) { dc.transform(dataPipe); } // Call writers for (DataWriter oneOw : dataWriters) { try { oneOw.writeOutput(dataPipe); } catch (Exception e) { //NOPMD log.error("Exception in DataWriter", e); } } return 1; }
java
public Future<String> sendRequest(final String path, final ReportingHandler reportingHandler) { return threadPool.submit(new Callable<String>() { @Override public String call() { String response = getResponse(path); if (reportingHandler != null) { reportingHandler.handleResponse(response); } return response; } }); }
java
public void transform(DataPipe cr) { for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) { String value = entry.getValue(); if (value.equals("#{customplaceholder}")) { // Generate a random number int ran = rand.nextInt(); entry.setValue(String.valueOf(ran)); } } }
java
public boolean isExit() { if (currentRow > finalRow) { //request new block of work String newBlock = this.sendRequestSync("this/request/block"); LineCountManager.LineCountBlock block = new LineCountManager.LineCountBlock(0, 0); if (newBlock.contains("exit")) { getExitFlag().set(true); makeReport(true); return true; } else { block.buildFromResponse(newBlock); } currentRow = block.getStart(); finalRow = block.getStop(); } else { //report the number of lines written makeReport(false); if (exit.get()) { getExitFlag().set(true); return true; } } return false; }
java
@Override public View getDropDownView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder; if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false); viewHolder = new ViewHolder(); viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.intl_phone_edit__country__item_image); viewHolder.mNameView = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_name); viewHolder.mDialCode = (TextView) convertView.findViewById(R.id.intl_phone_edit__country__item_dialcode); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } Country country = getItem(position); viewHolder.mImageView.setImageResource(getFlagResource(country)); viewHolder.mNameView.setText(country.getName()); viewHolder.mDialCode.setText(String.format("+%s", country.getDialCode())); return convertView; }
java
@Override public View getView(int position, View convertView, ViewGroup parent) { Country country = getItem(position); if (convertView == null) { convertView = new ImageView(getContext()); } ((ImageView) convertView).setImageResource(getFlagResource(country)); return convertView; }
java
private int getFlagResource(Country country) { return getContext().getResources().getIdentifier("country_" + country.getIso().toLowerCase(), "drawable", getContext().getPackageName()); }
java
private static String getJsonFromRaw(Context context, int resource) { String json; try { InputStream inputStream = context.getResources().openRawResource(resource); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); inputStream.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; }
java
public static CountryList getCountries(Context context) { if (mCountries != null) { return mCountries; } mCountries = new CountryList(); try { JSONArray countries = new JSONArray(getJsonFromRaw(context, R.raw.countries)); for (int i = 0; i < countries.length(); i++) { try { JSONObject country = (JSONObject) countries.get(i); mCountries.add(new Country(country.getString("name"), country.getString("iso2"), country.getInt("dialCode"))); } catch (JSONException e) { e.printStackTrace(); } } } catch (JSONException e) { e.printStackTrace(); } return mCountries; }
java
private void init(AttributeSet attrs) { inflate(getContext(), R.layout.intl_phone_input, this); /**+ * Country spinner */ mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country); mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext()); mCountrySpinner.setAdapter(mCountrySpinnerAdapter); mCountries = CountriesFetcher.getCountries(getContext()); mCountrySpinnerAdapter.addAll(mCountries); mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener); setFlagDefaults(attrs); /** * Phone text field */ mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone); mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher); setDefault(); setEditTextDefaults(attrs); }
java
public void hideKeyboard() { InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0); }
java
public void setDefault() { try { TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); String phone = telephonyManager.getLine1Number(); if (phone != null && !phone.isEmpty()) { this.setNumber(phone); } else { String iso = telephonyManager.getNetworkCountryIso(); setEmptyDefault(iso); } } catch (SecurityException e) { setEmptyDefault(); } }
java
public void setEmptyDefault(String iso) { if (iso == null || iso.isEmpty()) { iso = DEFAULT_COUNTRY; } int defaultIdx = mCountries.indexOfIso(iso); mSelectedCountry = mCountries.get(defaultIdx); mCountrySpinner.setSelection(defaultIdx); }
java
private void setHint() { if (mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry.getIso() != null) { Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.getExampleNumberForType(mSelectedCountry.getIso(), PhoneNumberUtil.PhoneNumberType.MOBILE); if (phoneNumber != null) { mPhoneEdit.setHint(mPhoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL)); } } }
java
@SuppressWarnings("unused") public Phonenumber.PhoneNumber getPhoneNumber() { try { String iso = null; if (mSelectedCountry != null) { iso = mSelectedCountry.getIso(); } return mPhoneUtil.parse(mPhoneEdit.getText().toString(), iso); } catch (NumberParseException ignored) { return null; } }
java
@SuppressWarnings("unused") public boolean isValid() { Phonenumber.PhoneNumber phoneNumber = getPhoneNumber(); return phoneNumber != null && mPhoneUtil.isValidNumber(phoneNumber); }
java
@SuppressWarnings("unused") public void setError(CharSequence error, Drawable icon) { mPhoneEdit.setError(error, icon); }
java
public void setOnKeyboardDone(final IntlPhoneInputListener listener) { mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { listener.done(IntlPhoneInput.this, isValid()); } return false; } }); }
java
private synchronized Client allocateClient(int targetPlayer, String description) throws IOException { Client result = openClients.get(targetPlayer); if (result == null) { // We need to open a new connection. final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getInstance().getLatestAnnouncementFrom(targetPlayer); if (deviceAnnouncement == null) { throw new IllegalStateException("Player " + targetPlayer + " could not be found " + description); } final int dbServerPort = getPlayerDBServerPort(targetPlayer); if (dbServerPort < 0) { throw new IllegalStateException("Player " + targetPlayer + " does not have a db server " + description); } final byte posingAsPlayerNumber = (byte) chooseAskingPlayerNumber(targetPlayer); Socket socket = null; try { InetSocketAddress address = new InetSocketAddress(deviceAnnouncement.getAddress(), dbServerPort); socket = new Socket(); socket.connect(address, socketTimeout.get()); socket.setSoTimeout(socketTimeout.get()); result = new Client(socket, targetPlayer, posingAsPlayerNumber); } catch (IOException e) { try { socket.close(); } catch (IOException e2) { logger.error("Problem closing socket for failed client creation attempt " + description); } throw e; } openClients.put(targetPlayer, result); useCounts.put(result, 0); } useCounts.put(result, useCounts.get(result) + 1); return result; }
java
private void closeClient(Client client) { logger.debug("Closing client {}", client); client.close(); openClients.remove(client.targetPlayer); useCounts.remove(client); timestamps.remove(client); }
java
private synchronized void freeClient(Client client) { int current = useCounts.get(client); if (current > 0) { timestamps.put(client, System.currentTimeMillis()); // Mark that it was used until now. useCounts.put(client, current - 1); if ((current == 1) && (idleLimit.get() == 0)) { closeClient(client); // This was the last use, and we are supposed to immediately close idle clients. } } else { logger.error("Ignoring attempt to free a client that is not allocated: {}", client); } }
java
public <T> T invokeWithClientSession(int targetPlayer, ClientTask<T> task, String description) throws Exception { if (!isRunning()) { throw new IllegalStateException("ConnectionManager is not running, aborting " + description); } final Client client = allocateClient(targetPlayer, description); try { return task.useClient(client); } finally { freeClient(client); } }
java
@SuppressWarnings("WeakerAccess") public int getPlayerDBServerPort(int player) { ensureRunning(); Integer result = dbServerPorts.get(player); if (result == null) { return -1; } return result; }
java
private void requestPlayerDBServerPort(DeviceAnnouncement announcement) { Socket socket = null; try { InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT); socket = new Socket(); socket.connect(address, socketTimeout.get()); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); socket.setSoTimeout(socketTimeout.get()); os.write(DB_SERVER_QUERY_PACKET); byte[] response = readResponseWithExpectedSize(is, 2, "database server port query packet"); if (response.length == 2) { setPlayerDBServerPort(announcement.getNumber(), (int)Util.bytesToNumber(response, 0, 2)); } } catch (java.net.ConnectException ce) { logger.info("Player " + announcement.getNumber() + " doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata."); } catch (Exception e) { logger.warn("Problem requesting database server port number", e); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { logger.warn("Problem closing database server port request socket", e); } } } }
java
private byte[] receiveBytes(InputStream is) throws IOException { byte[] buffer = new byte[8192]; int len = (is.read(buffer)); if (len < 1) { throw new IOException("receiveBytes read " + len + " bytes."); } return Arrays.copyOf(buffer, len); }
java