/** * Executes the timed check. * * @param requestParameters Query or Form parameters submitted to the HTTP servlet. * @return MessagePayload representing the timed check. * @throws Throwable Thrown if an error occurred during the execution of the health check. */ @Override public MessagePayload performCheck(ImmutableMultimap<String, String> requestParameters) throws Throwable { long start = System.nanoTime(); Optional<Collection<PerfDatum>> extraPerfData = doTimedCheck(requestParameters); long total = System.nanoTime() - start; double timeInSeconds = Conversion.nsToS(total); ArrayList<PerfDatum> perfData = Lists.newArrayList(); perfData.add( PerfDatum.builder("tte", timeInSeconds) .criteria( Conversion.nsToS(getWarningThresholdInNs()), Conversion.nsToS(getCriticalThresholdNs())) .build()); if (extraPerfData.isPresent()) { perfData.addAll(extraPerfData.get()); } return new MessagePayloadBuilder() .withLevel(Level.evaluate(total, getWarningThresholdInNs(), getCriticalThresholdNs())) .withMessage(String.format("%s took %ss;", this.getName(), Conversion.nsToS(total))) .withPerfData(perfData) .build(); }
public void insert(String s) { Conversion c = new Conversion(s); s = c.inToPost(); Stack1 stk = new Stack1(s.length()); s = s + "#"; int i = 0; char symbol = s.charAt(i); Node newNode; while (symbol != '#') { if (symbol >= '0' && symbol <= '9' || symbol >= 'A' && symbol <= 'Z' || symbol >= 'a' && symbol <= 'z') { newNode = new Node(symbol); stk.push(newNode); } else if (symbol == '+' || symbol == '-' || symbol == '/' || symbol == '*') { Node ptr1 = stk.pop(); Node ptr2 = stk.pop(); newNode = new Node(symbol); newNode.leftChild = ptr2; newNode.rightChild = ptr1; stk.push(newNode); } symbol = s.charAt(++i); } root = stk.pop(); }
private boolean canMake(Conversion conv) { if (conv == null) return false; if (power < conv.minPower) return false; if (torque < conv.minTorque) return false; return input.getLevel() >= conv.getRequiredAmount() && output.canTakeIn(conv.outputFluid, conv.getProductionAmount()); }
/** * 类型检测 * * @param clazz * @return */ public static boolean isSupport(Class<?> clazz) { Converter converter = getConverter(); for (Conversion conversion : converter.conversions) { if (conversion.isSupport(clazz)) { return true; } } return false; }
private Conversion getConversion() { if (input.isEmpty()) return null; for (int i = 0; i < Conversion.list.length; i++) { Conversion c = Conversion.list[i]; if (c.validate()) { if (c.inputFluid.equals(input.getActualFluid())) return c; } } return null; }
@Override public boolean isValidFluid(Fluid f) { for (int i = 0; i < Conversion.list.length; i++) { Conversion c = Conversion.list[i]; if (c.validate()) { if (c.inputFluid.equals(f)) return true; } } return false; }
public static String getValidConversions() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < Conversion.list.length; i++) { Conversion c = Conversion.list[i]; if (c.validate()) { sb.append(c.toString()); if (i < Conversion.list.length - 1) sb.append("\n"); } } return sb.toString(); }
public void add(Conversion conversion) { if (conversion == null) { throw new IllegalArgumentException("conversion is null."); } List<Conversion> conversions = getConversions(conversion.getFromType()); if (conversions.contains(conversion)) { throw new IllegalArgumentException( String.format( "Conversion from %s to %s is already defined.", conversion.getFromType().toString(), conversion.getToType().toString())); } conversions.add(conversion); }
static void runAttacker(RobotController rc, int squad) throws GameActionException { Team team = rc.getTeam(); Team enemy = team.opponent(); int squadInfo = rc.readBroadcast(squad); MapLocation target = Conversion.intToMapLocation(squadInfo); MapLocation curr = rc.getLocation(); Robot[] allies = rc.senseNearbyGameObjects(Robot.class, rc.getType().attackRadiusMaxSquared * 2, team); // First steps away from home HQ if (curr.distanceSquaredTo(rc.senseHQLocation()) < 25) Move.tryToMove(rc); // attack! Robot[] enemyRobots = rc.senseNearbyGameObjects(Robot.class, rc.getType().sensorRadiusSquared * 2, enemy); MapLocation eloc = Attack.nearestEnemyLoc(rc, enemyRobots, rc.getLocation()); if (eloc != null) { if (rc.isActive()) Move.moveToward(rc, eloc); if (rc.isActive() && rc.canAttackSquare(eloc)) rc.attackSquare(eloc); } // Go to right place if (curr.distanceSquaredTo(target) > 7) { // System.out.println(target + " target " + allies.length + "ally length"); Move.moveTo(rc, target); } }
/** * Returns true if the conversion objects are equal in this object and given object, and if the * {@link Mutation#equals} superclass method returns true. */ @Override public boolean equals(Object other) { if (other instanceof Converter) { Converter o = (Converter) other; return conversion.equals(o.conversion) && super.equals(other); } else { return false; } }
@Override public Result convert(Source source) { for (Map.Entry<Predicate<Source>, Conversion<Source, Result>> conversionCase : cases) { if (conversionCase.getKey().test(source)) { return conversionCase.getValue().convert(source); } } return defaultConversion.convert(source); }
public Conversion findConversion(DataType fromType, DataType toType, boolean isImplicit) { Conversion result = findCompatibleConversion(fromType, toType); if (result == null) { int score = Integer.MAX_VALUE; for (Conversion conversion : getConversions(fromType)) { if ((!isImplicit || conversion.isImplicit()) && (conversion.getToType().isSuperTypeOf(toType) || conversion.getToType().isGeneric())) { // Lower score is better. If the conversion matches the target type exactly, the score is // 0. // If the conversion is generic, the score is 1 (because that will be instantiated to an // exact match) // If the conversion is a super type, it should only be used if an exact match cannot be // found. // If the score is equal to an existing, it indicates a duplicate conversion int newScore = conversion.getToType().equals(toType) ? 0 : (conversion.getToType().isGeneric() ? 1 : 2); if (newScore < score) { result = conversion; score = newScore; } else if (newScore == score) { throw new IllegalArgumentException( String.format( "Ambiguous implicit conversion from %s to %s or %s.", fromType.toString(), result.getToType().toString(), conversion.getToType().toString())); } } } } if (result == null) { // If both types are lists, attempt to find a conversion between the element types if (fromType instanceof ListType && toType instanceof ListType) { result = findListConversion((ListType) fromType, (ListType) toType); } // If both types are intervals, attempt to find a conversion between the point types if (fromType instanceof IntervalType && toType instanceof IntervalType) { result = findIntervalConversion((IntervalType) fromType, (IntervalType) toType); } } return result; }
public void showClosestClubDialogMeters(ShotResult shot, Integer yDist, Integer zDist) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle("HillCaddy Says..."); Integer dist = ShotCalculator.calculateDistance(yDist, zDist); // convert distance to meters dist = Conversion.yardToMeterRnd(dist); String shotDist = "The shot will play " + dist.toString() + " meters.\n"; if (shot.getDistance() < 0) { Integer shotAbs = Math.abs(Conversion.yardToMeterRnd(shot.getDistance())); builder.setMessage( shotDist + "The closest club is your " + shot.getClubName() + ". It will land " + shotAbs.toString() + " m short of the target"); } else if (shot.getDistance() < 1000) { builder.setMessage( shotDist + "The closest club is your " + shot.getClubName() + ". It will land " + shot.getDistance().toString() + " m past the target"); } else { builder.setMessage( shotDist + "No clubs available, go to range mode and check your clubs and distances for a club recommendation."); } builder.setPositiveButton( "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) {} }); builder.show(); }
static void runDefender(RobotController rc, int squad) throws GameActionException { Team team = rc.getTeam(); Team enemy = team.opponent(); int squadInfo = rc.readBroadcast(squad); MapLocation target = Conversion.intToMapLocation(squadInfo); MapLocation curr = rc.getLocation(); int status = rc.readBroadcast(squad + 1); int PASTRstatus = Channels.NTPASTRDecoding(status)[1]; int NTstatus = Channels.NTPASTRDecoding(status)[0]; Robot[] allies = rc.senseNearbyGameObjects(Robot.class, rc.getType().attackRadiusMaxSquared * 2, team); // Create a PASTR/NT if not already there // System.out.println(allies.length + " " + rc.readBroadcast(Channels.numAlliesNeededChannel)); if (allies.length >= rc.readBroadcast(Channels.numAlliesNeededChannel) && curr.distanceSquaredTo(target) < distanceThreshold && rc.isActive()) { if (PASTRstatus == 0) { rc.construct(RobotType.PASTR); rc.broadcast(squad + 1, Channels.NTPASTREncoding(NTstatus, 1)); System.out.println("Constructing a PASTR..."); } else if (NTstatus == 0) { rc.construct(RobotType.NOISETOWER); rc.broadcast(squad + 1, Channels.NTPASTREncoding(1, PASTRstatus)); System.out.println("Constructing a NT..."); } } // Then go to right place if (curr.distanceSquaredTo(target) > 8) Move.moveTo(rc, target); // Then attack! Robot[] enemyRobots = rc.senseNearbyGameObjects(Robot.class, rc.getType().sensorRadiusSquared * 2, enemy); MapLocation eloc = Attack.nearestEnemyLoc(rc, enemyRobots, rc.getLocation()); if (eloc != null) { if (rc.isActive()) Move.moveToward(rc, eloc); if (rc.isActive() && rc.canAttackSquare(eloc)) rc.attackSquare(eloc); } // If there is a pastr and noisetower, don't block them! if (PASTRstatus == 1 && NTstatus == 1) { if (enemyRobots.length == 0 && rc.senseCowsAtLocation(rc.getLocation()) > 30) { Move.tryToSneak(rc); } } }
static void runScout(RobotController rc, int squad) throws GameActionException { int squadInfo = rc.readBroadcast(squad); MapLocation target = Conversion.intToMapLocation(Channels.scoutDecoding(squadInfo)[1]); MapLocation curr = rc.getLocation(); if (curr.distanceSquaredTo(target) > 50) Move.moveTo(rc, target); else { int start = Channels.scoutDecoding(squadInfo)[0]; rc.broadcast( Channels.scoutChannel, Channels.scoutEncoding((Clock.getRoundNum() - start), target, 1)); } }
/** * 转换 * * @param clazz * @param value * @return */ @SuppressWarnings("unchecked") public static Object convert(Class<?> clazz, Object value) { Converter converter = getConverter(); for (Conversion conversion : converter.conversions) { if (conversion.isSupport(clazz)) { try { return conversion.convert(clazz, value); } catch (Exception e) { } } } if (value == null) { return defaultValue(clazz); } Class<?> srcType = value.getClass(); if (srcType == null || clazz.isAssignableFrom(srcType)) { return value; } else if (clazz.isArray() && srcType.isArray()) { } else if (srcType.isArray()) { if (Array.getLength(value) == 0) { return defaultValue(clazz); } return convert(clazz, Array.get(value, 0)); } else if (clazz.isArray()) { if (clazz.getComponentType().isAssignableFrom(srcType)) { Object array = Array.newInstance(clazz.getComponentType(), 1); Array.set(array, 0, value); return array; } } else if (value instanceof String) { return Reflects.newInstance((String) value); } else if (value instanceof Map) { return Reflects.newInstance(clazz, (Map<String, Object>) value); } throw new IllegalStateException( "Unsupported convert to " + clazz.getName() + " from " + srcType.getName()); }
/** * Returns a {@link ConversionCategory} for every conversion found in the format string. * * <p>Throws an exception if the format is not syntactically valid. */ public static ConversionCategory[] formatParameterCategories(String format) throws IllegalFormatException { tryFormatSatisfiability(format); int last = -1; // index of last argument referenced int lasto = -1; // last ordinary index int maxindex = -1; Conversion[] cs = parse(format); Map<Integer, ConversionCategory> conv = new HashMap<Integer, ConversionCategory>(); for (Conversion c : cs) { int index = c.index(); switch (index) { case -1: // relative index break; case 0: // ordinary index lasto++; last = lasto; break; default: // explicit index last = index - 1; break; } maxindex = Math.max(maxindex, last); conv.put( last, ConversionCategory.intersect( conv.containsKey(last) ? conv.get(last) : ConversionCategory.UNUSED, c.category())); } ConversionCategory[] res = new ConversionCategory[maxindex + 1]; for (int i = 0; i <= maxindex; ++i) { res[i] = conv.containsKey(i) ? conv.get(i) : ConversionCategory.UNUSED; } return res; }
/** * Creates a mutation for converting all values of the given field in the given class version to a * type compatible with the current declared type of the field. */ public Converter( String declaringClassName, int declaringClassVersion, String fieldName, Conversion conversion) { super(declaringClassName, declaringClassVersion, fieldName); this.conversion = conversion; /* Require explicit implementation of the equals method. */ Class cls = conversion.getClass(); try { Method m = cls.getMethod("equals", Object.class); if (m.getDeclaringClass() == Object.class) { throw new IllegalArgumentException( "Conversion class does not implement the equals method " + "explicitly (Object.equals is not sufficient): " + cls.getName()); } } catch (NoSuchMethodException e) { throw DbCompat.unexpectedException(e); } }
@Override public void init() throws IOException { super.init(); camera = new Camera(true); camera.setPosition(-17f, 20f, 17f, 0, 0, 0, 0, 1, 0); float df = 100.0f; // Precalculate the Sine and Cosine Lookup Tables. // Basically, loop through 360 Degrees and assign the Radian // value to each array index (which represents the Degree). for (int i = 0; i < 360; i++) { g_fSinTable[i] = (float) Math.sin(AR_DegToRad(i)); g_fCosTable[i] = (float) Math.cos(AR_DegToRad(i)); } pObj = new Sphere(); pObj.setOrientation(GLU_OUTSIDE); Octree.debug = new BoundingBox(); // Turn lighting on initially Octree.turnLighting = true; // The current amount of end nodes in our tree (The nodes with vertices stored in them) Octree.totalNodesCount = 0; // This stores the amount of nodes that are in the frustum Octree.totalNodesDrawn = 0; // The maximum amount of triangles per node. If a node has equal or less // than this, stop subdividing and store the face indices in that node Octree.maxTriangles = 800; // The maximum amount of subdivisions allowed (Levels of subdivision) Octree.maxSubdivisions = 5; // The number of Nodes we've checked for collision. Octree.numNodesCollided = 0; // Wheter the Object is Colliding with anything in the World or not. octree.setObjectColliding(false); // Wheter we test the whole world for collision or just the nodes we are in. Octree.octreeCollisionDetection = true; LoadWorld(); // for(int i=0; i < g_World.getNumOfMaterials(); i++) // { // System.out.println(g_World.getMaterials(i).getName() + " indice " + i); // } // for(int i=0; i < g_World.getNumOfObjects(); i++) // { // System.out.println(g_World.getObject(i).getName()); // System.out.println(g_World.getObject(i).getMaterialID()); // System.out.println(g_World.getPObject(i).getMaterialID()); // } // System.out.println(g_World.getPMaterials(12).getColor()[0] + " " + // g_World.getPMaterials(12).getColor()[1] // + " " + g_World.getPMaterials(12).getColor()[2]); // System.out.println(g_World.getPMaterials(g_World.getPObject(6).getMaterialID())); inputManager = new InputManager(); createGameActions(); posLuz1F = Conversion.allocFloats(posLuz1); // Define a cor de fundo da janela de visualização como preto glClearColor(0, 0, 0, 1); // Ajusta iluminação glLight(GL_LIGHT0, GL_AMBIENT, Conversion.allocFloats(luzAmb1)); glLight(GL_LIGHT0, GL_DIFFUSE, Conversion.allocFloats(luzDif1)); glLight(GL_LIGHT0, GL_SPECULAR, Conversion.allocFloats(luzEsp1)); // Habilita todas as fontes de luz glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); // Agora posiciona demais fontes de luz glLight(GL_LIGHT0, GL_POSITION, posLuz1F); // Habilita Z-Buffer glEnable(GL_DEPTH_TEST); // Seleciona o modo de GL_COLOR_MATERIAL // glColorMaterial(GL_FRONT, GL_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glMaterial(GL_FRONT, GL_SPECULAR, Conversion.allocFloats(spec)); glMaterialf(GL_FRONT, GL_SHININESS, df); }
private void showShotResults(Integer ydist, Integer zdist) { Profile profile = globals.getCurrentProfile(); List<ShotResult> distanceList = profile.getAllDistancesFromTarget(ydist, zdist); TableLayout distanceTable = (TableLayout) findViewById(R.id.resultCard_table); // make sure the table is clear before making changes distanceTable.removeAllViews(); TableRow header = new TableRow(this); TextView tv0 = new TextView(this); tv0.setText("Club "); tv0.setTextColor(Color.BLACK); tv0.setTypeface(null, Typeface.BOLD); tv0.setGravity(Gravity.LEFT); tv0.setTextSize(20); header.addView(tv0); TextView tv1 = new TextView(this); // determine whether to use metrics or yards for text if (!globals.getDisplayUnits()) tv1.setText(R.string.distance_yds_table_result_text); else tv1.setText(R.string.distance_m_table_result_text); tv1.setTextColor(Color.BLACK); tv1.setTypeface(null, Typeface.BOLD); tv1.setGravity(Gravity.LEFT); tv1.setTextSize(20); header.addView(tv1); distanceTable.addView(header); Iterator<ShotResult> iterator = distanceList.iterator(); while (iterator.hasNext()) { ShotResult shot = iterator.next(); TableRow tbrow = new TableRow(this); TextView t1v = new TextView(this); t1v.setText(shot.getClubName()); t1v.setTextColor(Color.BLACK); t1v.setGravity(Gravity.LEFT); t1v.setTextSize(18); tbrow.addView(t1v); TextView t2v = new TextView(this); // check to see whether distance should be in yards or meters if (!globals.getDisplayUnits()) t2v.setText(shot.getDistance().toString()); else { t2v.setText(Conversion.yardToMeterRnd(shot.getDistance()).toString()); } t2v.setTextColor(Color.BLACK); t2v.setGravity(Gravity.LEFT); t2v.setTextSize(18); tbrow.addView(t2v); distanceTable.addView(tbrow); } ShotResult closestShot = findClosestShot(distanceList); // decide whether the closest club dialog should show yards or meters for results if (!globals.getDisplayUnits()) showClosestClubDialogYards(closestShot, ydist, zdist); else showClosestClubDialogMeters(closestShot, ydist, zdist); }
public void add(Conversion conversion) { if (LOG.isDebugEnabled()) { LOG.info("Binding conversion {}", conversion.getClass().getName()); } conversions.add(conversion); }
public static Value evaluate( DOMObjects nativeObject, FunctionCalls.CallInfo call, State s, Solver.SolverInterface c) { switch (nativeObject) { case MOUSE_EVENT_INIT_MOUSE_EVENT: { NativeFunctions.expectParameters(nativeObject, call, c, 15, 15); /* Value typeArg =*/ Conversion.toString(NativeFunctions.readParameter(call, s, 0), c); /* Value canBubbleArg =*/ Conversion.toBoolean(NativeFunctions.readParameter(call, s, 1)); /* Value cancelableArg =*/ Conversion.toBoolean( NativeFunctions.readParameter(call, s, 2)); // View arg not checked /* Value detailArg =*/ Conversion.toNumber(NativeFunctions.readParameter(call, s, 4), c); /* Value screenXArg =*/ Conversion.toNumber(NativeFunctions.readParameter(call, s, 5), c); /* Value screenYArg =*/ Conversion.toNumber(NativeFunctions.readParameter(call, s, 6), c); /* Value clientXArg =*/ Conversion.toNumber(NativeFunctions.readParameter(call, s, 7), c); /* Value clientYArg =*/ Conversion.toNumber(NativeFunctions.readParameter(call, s, 8), c); /* Value ctrlKeyArg =*/ Conversion.toBoolean(NativeFunctions.readParameter(call, s, 9)); /* Value altKeyArg =*/ Conversion.toBoolean(NativeFunctions.readParameter(call, s, 10)); /* Value shiftKeyArg =*/ Conversion.toBoolean(NativeFunctions.readParameter(call, s, 11)); /* Value metaKeyArg =*/ Conversion.toBoolean(NativeFunctions.readParameter(call, s, 12)); /* Value buttonArg =*/ Conversion.toNumber(NativeFunctions.readParameter(call, s, 13), c); /* Value relatedTargetArg =*/ DOMConversion.toEventTarget( NativeFunctions.readParameter(call, s, 14), c); return Value.makeUndef(); } default: throw new UnsupportedOperationException("Unsupported Native Object: " + nativeObject); } }
@SuppressWarnings({"rawtypes", "unchecked"}) private <T> T convert( MetaData md, String[] data, Class<T> type, T defaultValue, Annotation annotation) { Object out = data[md.index]; if (out == null) { out = defaultValue == null ? md.defaultValue : defaultValue; } if (annotation == null) { initializeMetadataConversions(data, md); out = md.convert(out); if (out == null) { out = defaultValue == null ? md.defaultValue : defaultValue; } } if (type != null) { if (out != null && type.isAssignableFrom(out.getClass())) { return (T) out; } Conversion conversion; if (type != String.class) { if (annotation == null) { conversion = conversionByType.get(type); if (conversion == null) { conversion = AnnotationHelper.getDefaultConversion(type, null); conversionByType.put(type, conversion); } } else { Map<Annotation, Conversion> m = conversionsByAnnotation.get(type); if (m == null) { m = new HashMap<Annotation, Conversion>(); conversionsByAnnotation.put(type, m); } conversion = m.get(annotation); if (conversion == null) { conversion = AnnotationHelper.getConversion(type, annotation); m.put(annotation, conversion); } } if (conversion == null) { String message = ""; if (type == Date.class || type == Calendar.class) { message = ". Need to specify format for date"; } DataProcessingException exception = new DataProcessingException( "Cannot convert '{value}' to " + type.getName() + message); exception.setValue(out); exception.setErrorContentLength(context.errorContentLength()); throw exception; } out = conversion.execute(out); } } if (type == null) { return (T) out; } try { return type.cast(out); } catch (ClassCastException e) { DataProcessingException exception = new DataProcessingException( "Cannot cast value '{value}' of type " + out.getClass().toString() + " to " + type.getName()); exception.setValue(out); exception.setErrorContentLength(context.errorContentLength()); throw exception; } }
public void accept(Conversion conversion) { conversion.convert(this); }
private void make(Conversion conv) { input.removeLiquid(conv.getRequiredAmount()); output.addLiquid(conv.getProductionAmount(), conv.outputFluid); }
@Override public int hashCode() { return conversion.hashCode() + super.hashCode(); }