public static VertexData CreateRand(float radius) { VertexData retval = new VertexData(); retval.setRGB(0.2f, 0.9f, 0.7f); retval.setST(0, 0); retval.setXYZ(Helpers.rnd(radius), Helpers.rnd(radius), Helpers.rnd(radius)); return retval; }
private boolean haveLowAcceleration(float err) { if (cachedHaveLowAcceleration == -1) { final float len1 = curLeafCtrlPolyLengths[0]; final float len2 = curLeafCtrlPolyLengths[1]; // the test below is equivalent to !within(len1/len2, 1, err). // It is using a multiplication instead of a division, so it // should be a bit faster. if (!Helpers.within(len1, len2, err * len2)) { cachedHaveLowAcceleration = 0; return false; } if (curveType == 8) { final float len3 = curLeafCtrlPolyLengths[2]; // if len1 is close to 2 and 2 is close to 3, that probably // means 1 is close to 3 so the second part of this test might // not be needed, but it doesn't hurt to include it. if (!(Helpers.within(len2, len3, err * len3) && Helpers.within(len1, len3, err * len3))) { cachedHaveLowAcceleration = 0; return false; } } cachedHaveLowAcceleration = 1; return true; } return (cachedHaveLowAcceleration == 1); }
@Test public void testNext() { Function<String, String> next = null; Helpers.assertThrows(NullPointerException.class, () -> new Range<>("").next(next)); BiFunction<String, Integer, String> biNext = null; Helpers.assertThrows(NullPointerException.class, () -> new Range<>("").next(biNext)); }
public static JSONArray storeInDB(SQLiteManager dbHelper, JSONObject jsonobj) { // Gets the data repository in write mode SQLiteDatabase db = dbHelper.getWritableDatabase(); dbHelper.onCreate(db); try { JSONArray jsonarray = jsonobj.getJSONArray("features"); Log.d("EarthquakeMonitor", "MainActivity.storeInDB() deleted old records"); dbHelper.deleteRecords(db); Log.d("EarthquakeMonitor", "MainActivity.storeInDB() length is => " + jsonarray.length()); for (int i = 0; i < jsonarray.length(); i++) { JSONObject row = jsonarray.getJSONObject(i); // Log.d("EarthquakeMonitor", "** "+row.getString("id")+", // "+row.getJSONObject("properties").getDouble("mag")+", // "+Helpers.getDate(row.getJSONObject("properties").getInt("time"))+", // "+row.getJSONObject("properties").getString("place")); // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); values.put(FeedEntry.COLUMN_NAME_ID, row.getString("id")); values.put(FeedEntry.COLUMN_NAME_MAG, row.getJSONObject("properties").getDouble("mag")); values.put(FeedEntry.COLUMN_NAME_PLACE, row.getJSONObject("properties").getString("place")); values.put(FeedEntry.COLUMN_NAME_TIME, row.getJSONObject("properties").getLong("time")); values.put( FeedEntry.COLUMN_NAME_LAT, Helpers.stringtoArray(row.getJSONObject("geometry").getString("coordinates"))[1]); values.put( FeedEntry.COLUMN_NAME_LNG, Helpers.stringtoArray(row.getJSONObject("geometry").getString("coordinates"))[0]); values.put( FeedEntry.COLUMN_NAME_DPT, Helpers.stringtoArray(row.getJSONObject("geometry").getString("coordinates"))[2]); // Insert the new row, returning the primary key value of the new row long newRowId; newRowId = db.insert(FeedEntry.TABLE_NAME, FeedEntry.COLUMN_NAME_PLACE, values); } Log.d( "EarthquakeMonitor", "MainActivity.storeInDB() jsonarray length stored = > " + jsonarray.length()); return jsonarray; } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return null; } }
/** Run before each test * */ @Before public void setUp() throws Exception { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("appium-version", "1.1.0"); capabilities.setCapability("platformVersion", "7.1"); capabilities.setCapability("platformName", "ios"); capabilities.setCapability("deviceName", "iPhone Simulator"); // Set job name on Sauce Labs capabilities.setCapability("name", "Java iOS tutorial " + date); String userDir = System.getProperty("user.dir"); String localApp = "UICatalog6.1.app.zip"; if (runOnSauce) { String user = auth.getUsername(); String key = auth.getAccessKey(); // Upload app to Sauce Labs SauceREST rest = new SauceREST(user, key); rest.uploadFile(new File(userDir, localApp), localApp); capabilities.setCapability("app", "sauce-storage:" + localApp); URL sauceURL = new URL("http://" + user + ":" + key + "@ondemand.saucelabs.com:80/wd/hub"); driver = new AppiumDriver(sauceURL, capabilities); } else { String appPath = Paths.get(userDir, localApp).toAbsolutePath().toString(); capabilities.setCapability("app", appPath); driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); } sessionId = driver.getSessionId().toString(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); Helpers.init(driver); }
@Override public void translate( final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) throws InternalTranslationException { TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "bnel"); final List<? extends IOperandTree> operands = instruction.getOperands(); final String rs = operands.get(0).getRootNode().getChildren().get(0).getValue(); final String rt = operands.get(1).getRootNode().getChildren().get(0).getValue(); final IOperandTreeNode target = operands.get(2).getRootNode().getChildren().get(0); final long baseOffset = ReilHelpers.toReilAddress(instruction.getAddress()).toLong(); long offset = baseOffset; final OperandSize dw = OperandSize.DWORD; final OperandSize qw = OperandSize.QWORD; final String subtractedValue = environment.getNextVariableString(); instructions.add(ReilHelpers.createSub(offset++, dw, rs, dw, rt, qw, subtractedValue)); Helpers.generateDelayBranchLikely(instructions, offset, qw, subtractedValue, dw, target); }
@Override public IRubyObject yield( ThreadContext context, IRubyObject[] args, IRubyObject self, RubyModule klass, Binding binding, Block.Type type, Block block) { if (klass == null) { self = prepareSelf(binding); } Visibility oldVis = binding.getFrame().getVisibility(); Frame lastFrame = pre(context, klass, binding); Ruby runtime = context.runtime; try { if (!noargblock) { IRubyObject[] preppedArgs = RubyProc.prepareArgs(context, type, arity, args); RubyArray argArray = context.runtime.newArrayNoCopyLight(preppedArgs); IRubyObject value = assigner.convertIfAlreadyArray(runtime, argArray); assigner.assignArray(runtime, context, self, value, block); } // This while loop is for restarting the block call in case a 'redo' fires. return evalBlockBody(context, binding, self); } catch (JumpException.FlowControlException jump) { return Helpers.handleBlockJump(context, jump, type); } finally { post(context, binding, oldVis, lastFrame); } }
public void init() { assetManager.load(ATLAS_UI, TextureAtlas.class); assetManager.load(SKIN_UI, Skin.class); assetManager.load(ATLAS_UI_BUTTONS, TextureAtlas.class); // assetManager.load(SKIN_UI_BUTTONS, Skin.class); // TODO: load game graphics atlas here assetManager.finishLoading(); skinUI = assetManager.get(SKIN_UI); textureAtlasUI = assetManager.get(ATLAS_UI); textureAtlasButtons = assetManager.get(ATLAS_UI_BUTTONS, TextureAtlas.class); // Stopped loading the skinButton skin in the Assetmanager to generate font size on the fly skinButton = new Skin(); skinButton.add( "default-font", this.fonts.getLemonMilk(Helpers.getFontSize(20, 720.0f, Gdx.graphics.getHeight()))); skinButton.addRegions(new TextureAtlas(Gdx.files.internal("ui/9patch_buttons.atlas"))); skinButton.load(Gdx.files.internal("ui/9patch_buttons.json")); // this.assetManager = assetManager; // assetManager.load(Constants.ATLAS_GAME, TextureAtlas.class); // assetManager.finishLoading(); // TextureAtlas atlas = assetManager.get(Constants.ATLAS_GAME); // initAssets(atlas); }
/** Deletes a row in the database */ @Override public int delete(final Uri uri, final String where, final String[] whereArgs) { Helpers.validateSelection(where, sAppReadableColumnsSet); SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count; int match = sURIMatcher.match(uri); switch (match) { case MY_DOWNLOADS: case MY_DOWNLOADS_ID: case ALL_DOWNLOADS: case ALL_DOWNLOADS_ID: SqlSelection selection = getWhereClause(uri, where, whereArgs, match); deleteRequestHeaders(db, selection.getSelection(), selection.getParameters()); count = db.delete(DB_TABLE, selection.getSelection(), selection.getParameters()); break; default: Log.d(Constants.TAG, "deleting unknown/invalid URI: " + uri); throw new UnsupportedOperationException("Cannot delete URI: " + uri); } notifyContentChanged(uri, match); return count; }
@Override public IRubyObject yieldSpecific( ThreadContext context, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Binding binding, Block.Type type) { Visibility oldVis = binding.getFrame().getVisibility(); Frame lastFrame = pre(context, null, binding); IRubyObject self = prepareSelf(binding); try { if (!noargblock) { assigner.assign(context.runtime, context, self, arg0, arg1, arg2, Block.NULL_BLOCK); } // This while loop is for restarting the block call in case a 'redo' fires. return evalBlockBody(context, binding, self); } catch (JumpException.FlowControlException jump) { return Helpers.handleBlockJump(context, jump, type); } finally { post(context, binding, oldVis, lastFrame); } }
@Override public void translate( final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) throws InternalTranslationException { TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "bltl"); final IOperandTreeNode addressOperand1 = instruction.getOperands().get(1).getRootNode().getChildren().get(0); final IOperandTreeNode BIOperand = instruction.getOperands().get(0).getRootNode().getChildren().get(0); BranchGenerator.generate( instruction.getAddress().toLong() * 0x100, environment, instruction, instructions, "bltl", String.valueOf(Helpers.getCRRegisterIndex(BIOperand.getValue()) * 4), addressOperand1.getValue(), true, false, false, false, true, false); }
@Test public void testUntil() { Range<Character> range = new Range<>('a').until('z'); assertThat(range.getTo(), is('z')); assertThat(range.isToIncluded(), is(false)); Helpers.assertThrows(NullPointerException.class, () -> new Range<>("").until(null)); }
@Test public void testIterator() { Iterator<Integer> itr = new Range<>(1).to(1).next(i -> i + 1).iterator(); assertThat(itr.next(), is(1)); assertThat(itr.hasNext(), is(false)); final Iterator<Integer> it = itr; Helpers.assertThrows(NoSuchElementException.class, () -> it.next()); itr = new Range<>(1).to(2).next(i -> i + 1).iterator(); assertThat(itr.next(), is(1)); assertThat(itr.next(), is(2)); assertThat(itr.hasNext(), is(false)); itr = new Range<>(1).next(i -> i + 1).iterator(); assertThat(itr.hasNext(), is(true)); for (int i = 0; i < 100; i++) { itr.next(); } assertThat(itr.next(), is(101)); assertThat(itr.hasNext(), is(true)); List<Integer> list = new ArrayList<>(); for (int d : new Range<>(1).next(i -> i + 1).until(5)) { list.add(d); } assertThat(list, equalTo(Arrays.asList(1, 2, 3, 4))); }
/** * Yield to this block, usually passed to the current call. * * @param context represents the current thread-specific data * @param args The args for yield * @param self The current self * @return */ @Override public IRubyObject yield( ThreadContext context, IRubyObject[] args, IRubyObject self, Binding binding, Block.Type type, Block block) { // SSS FIXME: This is now being done unconditionally compared to if (klass == null) earlier self = prepareSelf(binding); Frame lastFrame = pre(context, binding); try { // This while loop is for restarting the block call in case a 'redo' fires. while (true) { try { IRubyObject[] preppedArgs = RubyProc.prepareArgs(context, type, arity, args); return callback(context.runtime.newArrayNoCopyLight(preppedArgs), method, self, block); } catch (JumpException.RedoJump rj) { context.pollThreadEvents(); // do nothing, allow loop to redo } catch (JumpException.BreakJump bj) { // if (bj.getTarget() == 0) { // bj.setTarget(this); // } throw bj; } } } catch (JumpException.FlowControlException jump) { return Helpers.handleBlockJump(context, jump, type); } finally { post(context, binding, null, lastFrame); } }
public String mediaGetStreamUrl( String url, String id, String asset_name, int seclevel, String asnum, String ip, String useragent, String[] countries, String[] referers, int expires, String extension, Boolean download) throws DCException { if (extension.equals("")) { String[] parts = asset_name.split("\\_"); extension = (!parts[0].equals(asset_name)) ? parts[0] : extension; } if (asset_name.length() >= 15 && asset_name.substring(0, 15).equals("jpeg_thumbnail_")) { return CloudKey.STATIC_URL + this.user_id + "/" + id + "/" + asset_name + "." + extension; } else { String _url = this.cdn_url + "/route/" + this.user_id + "/" + id + "/" + asset_name + ((!extension.equals("")) ? "." + extension : ""); return Helpers.sign_url( _url, this.api_key, seclevel, asnum, ip, useragent, countries, referers, expires) + (download ? "&throttle=0&helper=0&cache=0" : ""); } }
@Override public void translate( final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) throws InternalTranslationException { TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "beqlr"); final IOperandTreeNode BIOperand = instruction.getOperands().get(0).getRootNode().getChildren().get(0); String suffix = ""; if (instruction.getMnemonic().endsWith("+")) { suffix = "+"; } if (instruction.getMnemonic().endsWith("-")) { suffix = "-"; } BranchGenerator.generate( instruction.getAddress().toLong() * 0x100, environment, instruction, instructions, "beqlr" + suffix, String.valueOf((Helpers.getCRRegisterIndex(BIOperand.getValue()) * 4) + 2), Helpers.LINK_REGISTER, false, false, false, false, true, false); }
@Test public void testTake() { assertThat(new Range<>(1).next(i -> i + 1).take(0), equalTo(Seqs.newMutableSeq())); assertThat(new Range<>(1).next(i -> i + 1).take(5), equalTo(Seqs.newMutableSeq(1, 2, 3, 4, 5))); assertThat(new Range<>(1).next(i -> i + 1).to(3).take(5), equalTo(Seqs.newMutableSeq(1, 2, 3))); Helpers.assertThrows(UnsupportedOperationException.class, () -> new Range<>(1).spliterator()); }
public RecommendationDataManager(List<Set<Integer>> userVisits) { trainingSet = new ArrayList<>(); validationSet = new ArrayList<>(); testSet = new ArrayList<>(); virtualSet = new HashSet<>(); for (int i = 0; i < Constants.ITEM_COUNT; i++) virtualSet.add(i); for (Set<Integer> visitedIds : userVisits) { currentSet = visitedIds; // %80 nini al trainingSet.add(getRandomlySet(80)); // kalan?n %50 si validationSet.add(getRandomlySet(50)); // kalan? al testSet.add(currentSet); } Helpers.dumpSetForGraph("Training Set", trainingSet); Helpers.dumpSetForGraph("Validation Set", validationSet); Helpers.dumpSetForGraph("Test Set", testSet); notVisitedTrainingSet = new ArrayList<>(); for (Set<Integer> visitedIds : trainingSet) { Set<Integer> newSet = new HashSet<>(); newSet.addAll(virtualSet); newSet.removeAll(visitedIds); notVisitedTrainingSet.add(newSet); } // bir item hangi userlar taraf?ndan clicklenmi? itemVisitorsMap = new HashMap<>(); for (int userId = 0; userId < Constants.ITEM_COUNT; userId++) { List<Integer> userList = new ArrayList<>(); for (int rowId = 0; rowId < trainingSet.size(); rowId++) for (Integer subSet : trainingSet.get(rowId)) if (subSet.equals(userId)) userList.add(rowId); itemVisitorsMap.put(userId, userList); } }
@Test public void test01CheckChildIsLinearLayout() { FrameLayout frame = (FrameLayout) Helpers.findViewByIdString(activity, "activity_pace_calculator"); assertThat(frame, notNullValue()); assertThat(frame.getChildCount(), equalTo(1)); assertThat(frame.getChildAt(0), instanceOf(LinearLayout.class)); }
@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { Helpers.publishMessage( TwitterJobProperty.CONFIG.getConsumerKey(), TwitterJobProperty.CONFIG.getConsumerSecret(), TwitterJobProperty.CONFIG.getAccessToken(), TwitterJobProperty.CONFIG.getAccessTokenSecret(), "I'm done build " + build.getDisplayName() + "."); return true; }
// this is a bit of a hack. It returns -1 if we're not on a leaf, and // the length of the leaf if we are on a leaf. private float onLeaf() { float[] curve = recCurveStack[recLevel]; float polyLen = 0; float x0 = curve[0], y0 = curve[1]; for (int i = 2; i < curveType; i += 2) { final float x1 = curve[i], y1 = curve[i + 1]; final float len = Helpers.linelen(x0, y0, x1, y1); polyLen += len; curLeafCtrlPolyLengths[i / 2 - 1] = len; x0 = x1; y0 = y1; } final float lineLen = Helpers.linelen(curve[0], curve[1], curve[curveType - 2], curve[curveType - 1]); if (polyLen - lineLen < ERR || recLevel == limit) { return (polyLen + lineLen) / 2; } return -1; }
@Test public void test04CheckPaceCalculation() { EditText inputDistance = (EditText) Helpers.findViewByIdString(activity, "input_distance"); EditText inputTimeMin = (EditText) Helpers.findViewByIdString(activity, "input_time_min"); EditText inputTimeSec = (EditText) Helpers.findViewByIdString(activity, "input_time_sec"); EditText inputPaceMin = (EditText) Helpers.findViewByIdString(activity, "input_pace_min"); EditText inputPaceSec = (EditText) Helpers.findViewByIdString(activity, "input_pace_sec"); Button buttonCalculate = (Button) Helpers.findViewByIdString(activity, "button_calculate"); assertThat(inputDistance, notNullValue()); assertThat(inputTimeMin, notNullValue()); assertThat(inputTimeSec, notNullValue()); assertThat(inputPaceMin, notNullValue()); assertThat(inputPaceSec, notNullValue()); assertThat(buttonCalculate, notNullValue()); inputDistance.setText("3.1"); inputTimeMin.setText("23"); inputTimeSec.setText("22"); buttonCalculate.callOnClick(); Assertions.assertThat(inputPaceMin).containsText("7"); Assertions.assertThat(inputPaceSec).containsText("32"); }
public String retrieveUserId(HttpServletRequest req) { HttpSession session = req.getSession(); String userKey = "userId"; String userId = (String) session.getAttribute(userKey); if (userId == null) { String a = this.requestUserId(); userId = Helpers.jsonFromString(a).getString("id"); session.setAttribute(userKey, userId); } return userId; }
@Override public void translate( final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) throws InternalTranslationException { TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "blel"); Long baseOffset = instruction.getAddress().toLong() * 0x100; final String jumpOperand = environment.getNextVariableString(); final IOperandTreeNode addressOperand1 = instruction.getOperands().get(1).getRootNode().getChildren().get(0); final IOperandTreeNode BIOperand = instruction.getOperands().get(0).getRootNode().getChildren().get(0); instructions.add( ReilHelpers.createOr( baseOffset++, OperandSize.BYTE, String.valueOf((Helpers.getCRRegisterIndex(BIOperand.getValue()) * 4) + 2), OperandSize.BYTE, String.valueOf((Helpers.getCRRegisterIndex(BIOperand.getValue()) * 4) + 0), OperandSize.BYTE, jumpOperand)); BranchGenerator.generate( baseOffset, environment, instruction, instructions, "blel", jumpOperand, addressOperand1.getValue(), true, false, false, false, false, false); }
/** * Translates a PUSHFW instruction to REIL code. * * @param environment A valid translation environment. * @param instruction The PUSHFW instruction to translate. * @param instructions The generated REIL code will be added to this list * @throws InternalTranslationException if any of the arguments are null the passed instruction is * not an PUSHFW instruction */ @Override public void translate( final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) throws InternalTranslationException { TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "pushfw"); if (instruction.getOperands().size() != 0) { throw new InternalTranslationException( "Error: Argument instruction is not a pushfw instruction (invalid number of operands)"); } final long baseOffset = instruction.getAddress().toLong() * 0x100; long offset = baseOffset; final String result = Helpers.shiftFlagsIntoValue(environment, offset, OperandSize.WORD, instructions); offset = baseOffset + instructions.size(); Helpers.generatePush(environment, offset, result, OperandSize.WORD, instructions); }
public String mediaGetEmbedUrl( String url, String id, int seclevel, String asnum, String ip, String useragent, String[] countries, String[] referers, int expires) throws DCException { String _url = url + "/embed/" + this.user_id + "/" + id; return Helpers.sign_url( _url, this.api_key, seclevel, asnum, ip, useragent, countries, referers, expires); }
/** Remotely opens a file */ @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { if (Constants.LOGVV) { logVerboseOpenFileInfo(uri, mode); } Cursor cursor = query(uri, new String[] {"_data"}, null, null, null); String path; try { int count = (cursor != null) ? cursor.getCount() : 0; if (count != 1) { // If there is not exactly one result, throw an appropriate // exception. if (count == 0) { throw new FileNotFoundException("No entry for " + uri); } throw new FileNotFoundException("Multiple items at " + uri); } cursor.moveToFirst(); path = cursor.getString(0); } finally { if (cursor != null) { cursor.close(); } } if (path == null) { throw new FileNotFoundException("No filename found."); } if (!Helpers.isFilenameValid(path)) { throw new FileNotFoundException("Invalid filename."); } if (!"r".equals(mode)) { throw new FileNotFoundException("Bad mode for " + uri + ": " + mode); } ParcelFileDescriptor ret = ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY); if (ret == null) { if (Constants.LOGV) { Log.v(Constants.TAG, "couldn't open file"); } throw new FileNotFoundException("couldn't open file"); } return ret; }
@Test public void testForEach() { List<Integer> list = new ArrayList<>(); new Range<>(1).to(64).next(i -> i + i).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1, 2, 4, 8, 16, 32, 64))); list.clear(); new Range<>(1).until(64).next(i -> i + i).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1, 2, 4, 8, 16, 32))); list.clear(); new Range<>(64).to(1).next(i -> i / 2).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(64, 32, 16, 8, 4, 2, 1))); list.clear(); new Range<>(1).to(1).next(i -> i + i).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1))); list.clear(); new Range<>(1).until(1).next(i -> i + i).forEach(e -> list.add(e)); assertThat(list, equalTo(Collections.emptyList())); list.clear(); List<Integer> indices = new ArrayList<>(); new Range<>(1) .until(64) .next(i -> i + i) .forEach( (e, i) -> { list.add(e); indices.add(i); }); assertThat(list, equalTo(Arrays.asList(1, 2, 4, 8, 16, 32))); assertThat(indices, equalTo(Arrays.asList(0, 1, 2, 3, 4, 5))); list.clear(); new Range<>(1).to(720).next((c, i) -> c * (i + 2)).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1, 2, 6, 24, 120, 720))); list.clear(); new Range<>(1).to(5).next(i -> i + 1).next((c, i) -> c * (i + 2)).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1, 2, 3, 4, 5))); list.clear(); Helpers.assertThrows( NullPointerException.class, () -> new Range<>(1).to(10).forEach(e -> list.add(e))); }
public IRubyObject yield(ThreadContext context, Binding binding, Block.Type type) { IRubyObject self = prepareSelf(binding); Visibility oldVis = binding.getFrame().getVisibility(); Frame lastFrame = pre(context, null, binding); try { if (!noargblock) { assigner.assign(context.runtime, context, self, Block.NULL_BLOCK); } return evalBlockBody(context, binding, self); } catch (JumpException.FlowControlException jump) { return Helpers.handleBlockJump(context, jump, type); } finally { post(context, binding, oldVis, lastFrame); } }
// preconditions: curCurvepts must be an array of length at least 2 * type, // that contains the curve we want to dash in the first type elements private void somethingTo(int type) { if (pointCurve(curCurvepts, type)) { return; } if (li == null) { li = new LengthIterator(4, 0.01f); } li.initializeIterationOnCurve(curCurvepts, type); int curCurveoff = 0; // initially the current curve is at curCurvepts[0...type] float lastSplitT = 0; float t = 0; float leftInThisDashSegment = dash[idx] - phase; while ((t = li.next(leftInThisDashSegment)) < 1) { if (t != 0) { Helpers.subdivideAt( (t - lastSplitT) / (1 - lastSplitT), curCurvepts, curCurveoff, curCurvepts, 0, curCurvepts, type, type); lastSplitT = t; goTo(curCurvepts, 2, type); curCurveoff = type; } // Advance to next dash segment idx = (idx + 1) % dash.length; dashOn = !dashOn; phase = 0; leftInThisDashSegment = dash[idx]; } goTo(curCurvepts, curCurveoff + 2, type); phase += li.lastSegLen(); if (phase >= dash[idx]) { phase = 0f; idx = (idx + 1) % dash.length; dashOn = !dashOn; } }