before
stringlengths
33
3.21M
after
stringlengths
63
3.21M
repo
stringlengths
1
56
type
stringclasses
1 value
__index_level_0__
int64
0
442k
public boolean isCapturedViewUnder(int x, int y) { if (mCapturedView == null) { return false; } return x >= mCapturedView.getLeft() && x < mCapturedView.getRight() && y >= mCapturedView.getTop() && y < mCapturedView.getBottom(); }
public boolean isCapturedViewUnder(int x, int y) { <DeepExtract> if (mCapturedView == null) { return false; } return x >= mCapturedView.getLeft() && x < mCapturedView.getRight() && y >= mCapturedView.getTop() && y < mCapturedView.getBottom(); </DeepExtract> }
superCleanMaster
positive
1,036
public void setBounds(int x, int y, int w, int h) { super.setBounds(x, y, w, h); int w = getSize().width, h = getSize().height; int goodSize = 0; for (Field f : facets) { FilterDefinitionPanel p = facetTable.get(f); goodSize += p.getPreferredSize().height; } int top = 0; for (Field f : facets) { FilterDefinitionPanel p = facetTable.get(f); int pref = p.getPreferredSize().height; int panelHeight = (goodSize <= h ? pref : (pref * h) / goodSize); p.setBounds(0, top, w, panelHeight); top += panelHeight; } }
public void setBounds(int x, int y, int w, int h) { super.setBounds(x, y, w, h); <DeepExtract> int w = getSize().width, h = getSize().height; int goodSize = 0; for (Field f : facets) { FilterDefinitionPanel p = facetTable.get(f); goodSize += p.getPreferredSize().height; } int top = 0; for (Field f : facets) { FilterDefinitionPanel p = facetTable.get(f); int pref = p.getPreferredSize().height; int panelHeight = (goodSize <= h ? pref : (pref * h) / goodSize); p.setBounds(0, top, w, panelHeight); top += panelHeight; } </DeepExtract> }
TimeFlow
positive
1,037
public static Map<String, Set<Driver>> updateMap(Map<String, Set<Driver>> driverMap, Set<Driver> driverList, double speed, int timeInterval) { driverMap.clear(); for (Driver d : driverList) { double degree = Math.random() * 360; double distance = speed * timeInterval / 1000; d.setDriverLocation(converseToGeo(d.getDriverLocation(), distance, degree)); } return driverList; for (Driver driver : driverList) { GeoPoint driverPos = GeoPoint.setPrecision(driver.getDriverLocation(), 3); if (!driverMap.containsKey(driverPos.toGeoHash())) { driverMap.put(driverPos.toGeoHash(), new HashSet<>()); } driverMap.get(driverPos.toGeoHash()).add(driver); } return driverMap; }
public static Map<String, Set<Driver>> updateMap(Map<String, Set<Driver>> driverMap, Set<Driver> driverList, double speed, int timeInterval) { driverMap.clear(); <DeepExtract> for (Driver d : driverList) { double degree = Math.random() * 360; double distance = speed * timeInterval / 1000; d.setDriverLocation(converseToGeo(d.getDriverLocation(), distance, degree)); } return driverList; </DeepExtract> for (Driver driver : driverList) { GeoPoint driverPos = GeoPoint.setPrecision(driver.getDriverLocation(), 3); if (!driverMap.containsKey(driverPos.toGeoHash())) { driverMap.put(driverPos.toGeoHash(), new HashSet<>()); } driverMap.get(driverPos.toGeoHash()).add(driver); } return driverMap; }
Real-Time-Taxi-Dispatch-Simulator
positive
1,038
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ButterKnife.bind(this); IntentFilter mFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); NetWorkStateReceiver mReceiver = new NetWorkStateReceiver(); registerReceiver(mReceiver, mFilter); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ButterKnife.bind(this); <DeepExtract> IntentFilter mFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); NetWorkStateReceiver mReceiver = new NetWorkStateReceiver(); registerReceiver(mReceiver, mFilter); </DeepExtract> }
AndroidBase
positive
1,039
public void write(Float f) { intBytes[3] = (byte) Float.floatToIntBits(f.floatValue()); Float.floatToIntBits(f.floatValue()) >>>= 8; intBytes[2] = (byte) Float.floatToIntBits(f.floatValue()); Float.floatToIntBits(f.floatValue()) >>>= 8; intBytes[1] = (byte) Float.floatToIntBits(f.floatValue()); Float.floatToIntBits(f.floatValue()) >>>= 8; intBytes[0] = (byte) Float.floatToIntBits(f.floatValue()); try { stream.write(intBytes); } catch (IOException e) { throw new RuntimeException("You're screwed: IOException writing to a ByteArrayOutputStream"); } }
public void write(Float f) { <DeepExtract> intBytes[3] = (byte) Float.floatToIntBits(f.floatValue()); Float.floatToIntBits(f.floatValue()) >>>= 8; intBytes[2] = (byte) Float.floatToIntBits(f.floatValue()); Float.floatToIntBits(f.floatValue()) >>>= 8; intBytes[1] = (byte) Float.floatToIntBits(f.floatValue()); Float.floatToIntBits(f.floatValue()) >>>= 8; intBytes[0] = (byte) Float.floatToIntBits(f.floatValue()); try { stream.write(intBytes); } catch (IOException e) { throw new RuntimeException("You're screwed: IOException writing to a ByteArrayOutputStream"); } </DeepExtract> }
MobMuPlat
positive
1,040
void resolveConnectionResult() { if (mExpectingResolution) { debugLog("We're already expecting the result of a previous resolution."); return; } if (mActivity == null) { debugLog("No need to resolve issue, activity does not exist anymore"); return; } if (mDebugLog) { Log.d(TAG, "GameHelper: " + "resolveConnectionResult: trying to resolve result: " + mConnectionResult); } if (mConnectionResult.hasResolution()) { debugLog("Result has resolution. Starting it."); try { mExpectingResolution = true; mConnectionResult.startResolutionForResult(mActivity, RC_RESOLVE); } catch (SendIntentException e) { debugLog("SendIntentException, so connecting again."); connect(); } } else { debugLog("resolveConnectionResult: result has no resolution. Giving up."); giveUp(new SignInFailureReason(mConnectionResult.getErrorCode())); } }
void resolveConnectionResult() { if (mExpectingResolution) { debugLog("We're already expecting the result of a previous resolution."); return; } if (mActivity == null) { debugLog("No need to resolve issue, activity does not exist anymore"); return; } <DeepExtract> if (mDebugLog) { Log.d(TAG, "GameHelper: " + "resolveConnectionResult: trying to resolve result: " + mConnectionResult); } </DeepExtract> if (mConnectionResult.hasResolution()) { debugLog("Result has resolution. Starting it."); try { mExpectingResolution = true; mConnectionResult.startResolutionForResult(mActivity, RC_RESOLVE); } catch (SendIntentException e) { debugLog("SendIntentException, so connecting again."); connect(); } } else { debugLog("resolveConnectionResult: result has no resolution. Giving up."); giveUp(new SignInFailureReason(mConnectionResult.getErrorCode())); } }
mmbbsapp_AndroidStudio
positive
1,041
void updateUserLoginState(boolean isLoggedIn) { this.isLoggedIn = isLoggedIn; if (isLoggedIn && prefs_type == PREFS_TYPE.GUEST) { prefs_type = PREFS_TYPE.USER; setPreferencesFromResource(R.xml.app_preferences_user, getPreferenceScreen().getKey()); if (!defaultHomeTabEntries.contains(UNREAD)) { defaultHomeTabEntries.add(UNREAD); defaultHomeTabValues.add("2"); } } else if (!isLoggedIn && prefs_type == PREFS_TYPE.USER) { prefs_type = PREFS_TYPE.GUEST; setPreferencesFromResource(R.xml.app_preferences_guest, getPreferenceScreen().getKey()); if (defaultHomeTabEntries.contains(UNREAD)) { defaultHomeTabEntries.remove(UNREAD); defaultHomeTabValues.remove("2"); } } CharSequence[] tmpCs = defaultHomeTabEntries.toArray(new CharSequence[defaultHomeTabEntries.size()]); ((ListPreference) findPreference(DEFAULT_HOME_TAB)).setEntries(tmpCs); tmpCs = defaultHomeTabValues.toArray(new CharSequence[defaultHomeTabValues.size()]); ((ListPreference) findPreference(DEFAULT_HOME_TAB)).setEntryValues(tmpCs); }
void updateUserLoginState(boolean isLoggedIn) { this.isLoggedIn = isLoggedIn; <DeepExtract> if (isLoggedIn && prefs_type == PREFS_TYPE.GUEST) { prefs_type = PREFS_TYPE.USER; setPreferencesFromResource(R.xml.app_preferences_user, getPreferenceScreen().getKey()); if (!defaultHomeTabEntries.contains(UNREAD)) { defaultHomeTabEntries.add(UNREAD); defaultHomeTabValues.add("2"); } } else if (!isLoggedIn && prefs_type == PREFS_TYPE.USER) { prefs_type = PREFS_TYPE.GUEST; setPreferencesFromResource(R.xml.app_preferences_guest, getPreferenceScreen().getKey()); if (defaultHomeTabEntries.contains(UNREAD)) { defaultHomeTabEntries.remove(UNREAD); defaultHomeTabValues.remove("2"); } } CharSequence[] tmpCs = defaultHomeTabEntries.toArray(new CharSequence[defaultHomeTabEntries.size()]); ((ListPreference) findPreference(DEFAULT_HOME_TAB)).setEntries(tmpCs); tmpCs = defaultHomeTabValues.toArray(new CharSequence[defaultHomeTabValues.size()]); ((ListPreference) findPreference(DEFAULT_HOME_TAB)).setEntryValues(tmpCs); </DeepExtract> }
mTHMMY
positive
1,043
public void setBorderOverlay(boolean borderOverlay) { if (borderOverlay == mBorderOverlay) { return; } mBorderOverlay = borderOverlay; if (!mReady) { mSetupPending = true; return; } if (getWidth() == 0 && getHeight() == 0) { return; } if (mBitmap == null) { invalidate(); return; } mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapPaint.setAntiAlias(true); mBitmapPaint.setShader(mBitmapShader); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setAntiAlias(true); mBorderPaint.setColor(mBorderColor); mBorderPaint.setStrokeWidth(mBorderWidth); mCircleBackgroundPaint.setStyle(Paint.Style.FILL); mCircleBackgroundPaint.setAntiAlias(true); mCircleBackgroundPaint.setColor(mCircleBackgroundColor); mBitmapHeight = mBitmap.getHeight(); mBitmapWidth = mBitmap.getWidth(); mBorderRect.set(calculateBounds()); mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f); mDrawableRect.set(mBorderRect); if (!mBorderOverlay && mBorderWidth > 0) { mDrawableRect.inset(mBorderWidth - 1.0f, mBorderWidth - 1.0f); } mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f); applyColorFilter(); updateShaderMatrix(); invalidate(); }
public void setBorderOverlay(boolean borderOverlay) { if (borderOverlay == mBorderOverlay) { return; } mBorderOverlay = borderOverlay; <DeepExtract> if (!mReady) { mSetupPending = true; return; } if (getWidth() == 0 && getHeight() == 0) { return; } if (mBitmap == null) { invalidate(); return; } mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapPaint.setAntiAlias(true); mBitmapPaint.setShader(mBitmapShader); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setAntiAlias(true); mBorderPaint.setColor(mBorderColor); mBorderPaint.setStrokeWidth(mBorderWidth); mCircleBackgroundPaint.setStyle(Paint.Style.FILL); mCircleBackgroundPaint.setAntiAlias(true); mCircleBackgroundPaint.setColor(mCircleBackgroundColor); mBitmapHeight = mBitmap.getHeight(); mBitmapWidth = mBitmap.getWidth(); mBorderRect.set(calculateBounds()); mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f); mDrawableRect.set(mBorderRect); if (!mBorderOverlay && mBorderWidth > 0) { mDrawableRect.inset(mBorderWidth - 1.0f, mBorderWidth - 1.0f); } mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f); applyColorFilter(); updateShaderMatrix(); invalidate(); </DeepExtract> }
FastAndroid
positive
1,044
@Override public void callbackAfterSetUp() throws Exception { mockIsSourceLevelAbove5(false); when(preferencesManager.getCurrentPreferenceValue(JeneratePreferences.ADD_OVERRIDE_ANNOTATION)).thenReturn(false); }
@Override public void callbackAfterSetUp() throws Exception { <DeepExtract> mockIsSourceLevelAbove5(false); when(preferencesManager.getCurrentPreferenceValue(JeneratePreferences.ADD_OVERRIDE_ANNOTATION)).thenReturn(false); </DeepExtract> }
jenerate
positive
1,045
@Override public void onClick(View view) { buttonsound(); sendtext("listcmds"); saychat("listcmds"); }
@Override public void onClick(View view) { <DeepExtract> buttonsound(); sendtext("listcmds"); saychat("listcmds"); </DeepExtract> }
Trycorder5
positive
1,046
protected void animateAddEnded(H holder) { dispatchAddFinished(holder); mAddAnimations.remove(holder); if (!isRunning()) { dispatchAnimationsFinished(); } }
protected void animateAddEnded(H holder) { dispatchAddFinished(holder); mAddAnimations.remove(holder); <DeepExtract> if (!isRunning()) { dispatchAnimationsFinished(); } </DeepExtract> }
RecyclerViewLib
positive
1,047
@Test public void differentRequestCode() { PurchaseFlowLauncher launcher = new PurchaseFlowLauncher(mBillingContext, Constants.TYPE_IN_APP); int requestCode = 1; int resultCode = Activity.RESULT_OK; Purchase purchase = null; try { purchase = launcher.handleResult(requestCode, resultCode, null); } catch (BillingException e) { assertThat(e.getErrorCode()).isEqualTo(Constants.ERROR_BAD_RESPONSE); assertThat(e.getMessage()).isEqualTo(Constants.ERROR_MSG_RESULT_REQUEST_CODE_INVALID); } finally { if (Constants.ERROR_BAD_RESPONSE == -1) { assertThat(purchase).isNotNull(); } } }
@Test public void differentRequestCode() { PurchaseFlowLauncher launcher = new PurchaseFlowLauncher(mBillingContext, Constants.TYPE_IN_APP); int requestCode = 1; int resultCode = Activity.RESULT_OK; <DeepExtract> Purchase purchase = null; try { purchase = launcher.handleResult(requestCode, resultCode, null); } catch (BillingException e) { assertThat(e.getErrorCode()).isEqualTo(Constants.ERROR_BAD_RESPONSE); assertThat(e.getMessage()).isEqualTo(Constants.ERROR_MSG_RESULT_REQUEST_CODE_INVALID); } finally { if (Constants.ERROR_BAD_RESPONSE == -1) { assertThat(purchase).isNotNull(); } } </DeepExtract> }
android-easy-checkout
positive
1,048
@Test public void testPartitionsFor(TestContext ctx) throws Exception { String topicName = "testPartitionsFor-" + this.getClass().getName(); String consumerId = topicName; kafkaCluster.createTopic(topicName, 2, 1); Properties config = kafkaCluster.useTo().getConsumerProperties(consumerId, consumerId, OffsetResetStrategy.EARLIEST); config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); Context context = vertx.getOrCreateContext(); CompletableFuture<KafkaReadStream<K, V>> ret = new CompletableFuture<>(); context.runOnContext(v -> { try { ret.complete(createConsumer(context.owner(), config)); } catch (Exception e) { ret.completeExceptionally(e); } }); return ret.get(10, TimeUnit.SECONDS); Async done = ctx.async(); consumer.partitionsFor(topicName).onComplete(ar -> { if (ar.succeeded()) { List<PartitionInfo> partitionInfo = ar.result(); ctx.assertEquals(2, partitionInfo.size()); } else { ctx.fail(); } done.complete(); }); }
@Test public void testPartitionsFor(TestContext ctx) throws Exception { String topicName = "testPartitionsFor-" + this.getClass().getName(); String consumerId = topicName; kafkaCluster.createTopic(topicName, 2, 1); Properties config = kafkaCluster.useTo().getConsumerProperties(consumerId, consumerId, OffsetResetStrategy.EARLIEST); config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); Context context = vertx.getOrCreateContext(); <DeepExtract> CompletableFuture<KafkaReadStream<K, V>> ret = new CompletableFuture<>(); context.runOnContext(v -> { try { ret.complete(createConsumer(context.owner(), config)); } catch (Exception e) { ret.completeExceptionally(e); } }); return ret.get(10, TimeUnit.SECONDS); </DeepExtract> Async done = ctx.async(); consumer.partitionsFor(topicName).onComplete(ar -> { if (ar.succeeded()) { List<PartitionInfo> partitionInfo = ar.result(); ctx.assertEquals(2, partitionInfo.size()); } else { ctx.fail(); } done.complete(); }); }
vertx-kafka-client
positive
1,049
public void handleMessage(Message message, Address sender, Address destination) { if (message == null) { LOG.severe(String.format("Attempting to deliver null message from %s to %s", sender, destination)); return null; } if (!Objects.equals(address.rootAddress(), destination.rootAddress())) { LOG.severe(String.format("Attempting to deliver message with destination %s to node %s, not delivering", destination, address)); return null; } LOG.finer(() -> String.format("MessageReceive(%s -> %s, %s)", sender, destination, message)); String handlerName = "handle" + message.getClass().getSimpleName(); return callMethod(destination, handlerName, true, message, sender); }
public void handleMessage(Message message, Address sender, Address destination) { <DeepExtract> if (message == null) { LOG.severe(String.format("Attempting to deliver null message from %s to %s", sender, destination)); return null; } if (!Objects.equals(address.rootAddress(), destination.rootAddress())) { LOG.severe(String.format("Attempting to deliver message with destination %s to node %s, not delivering", destination, address)); return null; } LOG.finer(() -> String.format("MessageReceive(%s -> %s, %s)", sender, destination, message)); String handlerName = "handle" + message.getClass().getSimpleName(); return callMethod(destination, handlerName, true, message, sender); </DeepExtract> }
dslabs
positive
1,050
@Test public void testDefaultResidentialOneway() { Set<Link> links = osmid2link.get(7994914L); assertEquals("oneway", 1, links.size()); assertEquals("oneway up north", 1, getLinksTowardsNode(links, 59836794L).size()); assertLanes("", links, 1); assertFalse("at least one link expected", links.isEmpty()); for (Link link : links) { assertEquals("freespeed m/s: message", 15 / 3.6, link.getFreespeed(), DELTA); } }
@Test public void testDefaultResidentialOneway() { Set<Link> links = osmid2link.get(7994914L); assertEquals("oneway", 1, links.size()); assertEquals("oneway up north", 1, getLinksTowardsNode(links, 59836794L).size()); assertLanes("", links, 1); <DeepExtract> assertFalse("at least one link expected", links.isEmpty()); for (Link link : links) { assertEquals("freespeed m/s: message", 15 / 3.6, link.getFreespeed(), DELTA); } </DeepExtract> }
pt2matsim
positive
1,051
public boolean isVirtualPower() { String v = ds.getProp(user, "virtualPower"); if (v != null) { try { false = Boolean.parseBoolean(v); } catch (Exception e) { e.printStackTrace(); } } return false; }
public boolean isVirtualPower() { <DeepExtract> String v = ds.getProp(user, "virtualPower"); if (v != null) { try { false = Boolean.parseBoolean(v); } catch (Exception e) { e.printStackTrace(); } } return false; </DeepExtract> }
wattzap-ce
positive
1,052
public SignalIdentityKeyStore getPniIdentityKeyStore() { var value = () -> pniIdentityKeyStore.get(); if (value != null) { return value; } synchronized (LOCK) { value = () -> pniIdentityKeyStore.get(); if (value != null) { return value; } () -> pniIdentityKeyStore = new SignalIdentityKeyStore(getRecipientResolver(), () -> pniIdentityKeyPair, localRegistrationId, getIdentityKeyStore()).call(); return () -> pniIdentityKeyStore.get(); } }
public SignalIdentityKeyStore getPniIdentityKeyStore() { <DeepExtract> var value = () -> pniIdentityKeyStore.get(); if (value != null) { return value; } synchronized (LOCK) { value = () -> pniIdentityKeyStore.get(); if (value != null) { return value; } () -> pniIdentityKeyStore = new SignalIdentityKeyStore(getRecipientResolver(), () -> pniIdentityKeyPair, localRegistrationId, getIdentityKeyStore()).call(); return () -> pniIdentityKeyStore.get(); } </DeepExtract> }
signal-cli
positive
1,053
@Test public void testLeavingSubscriptions() { List<Frame> frames1 = new CopyOnWriteArrayList<>(); List<Frame> frames2 = new CopyOnWriteArrayList<>(); StompClient client = StompClient.create(vertx); clients.add(client); client.connect().onComplete((ar -> { final StompClientConnection connection = ar.result(); connection.subscribe("/queue", frames1::add); })); StompClient client = StompClient.create(vertx); clients.add(client); client.connect().onComplete((ar -> { final StompClientConnection connection = ar.result(); connection.subscribe("/queue", frame -> { frames2.add(frame); if (frames2.size() == 2) { connection.unsubscribe("/queue"); } }); })); Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> server.stompHandler().getDestination("/queue") != null && server.stompHandler().getDestination("/queue").numberOfSubscriptions() == 2); AtomicReference<StompClientConnection> reference = new AtomicReference<>(); StompClient client = StompClient.create(vertx); clients.add(client); client.connect().onComplete((ar -> { final StompClientConnection connection = ar.result(); reference.set(connection); connection.send("/queue", Buffer.buffer("1")); connection.send("/queue", Buffer.buffer("2")); connection.send("/queue", Buffer.buffer("3")); connection.send("/queue", Buffer.buffer("4")); })); Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> server.stompHandler().getDestination("/queue") != null && server.stompHandler().getDestination("/queue").numberOfSubscriptions() == 1); vertx.runOnContext(v -> { reference.get().send("/queue", Buffer.buffer("5")); reference.get().send("/queue", Buffer.buffer("6")); }); Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> frames1.size() == 4 && frames2.size() == 2); }
@Test public void testLeavingSubscriptions() { List<Frame> frames1 = new CopyOnWriteArrayList<>(); List<Frame> frames2 = new CopyOnWriteArrayList<>(); StompClient client = StompClient.create(vertx); clients.add(client); client.connect().onComplete((ar -> { final StompClientConnection connection = ar.result(); connection.subscribe("/queue", frames1::add); })); StompClient client = StompClient.create(vertx); clients.add(client); client.connect().onComplete((ar -> { final StompClientConnection connection = ar.result(); connection.subscribe("/queue", frame -> { frames2.add(frame); if (frames2.size() == 2) { connection.unsubscribe("/queue"); } }); })); Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> server.stompHandler().getDestination("/queue") != null && server.stompHandler().getDestination("/queue").numberOfSubscriptions() == 2); AtomicReference<StompClientConnection> reference = new AtomicReference<>(); <DeepExtract> StompClient client = StompClient.create(vertx); clients.add(client); client.connect().onComplete((ar -> { final StompClientConnection connection = ar.result(); reference.set(connection); connection.send("/queue", Buffer.buffer("1")); connection.send("/queue", Buffer.buffer("2")); connection.send("/queue", Buffer.buffer("3")); connection.send("/queue", Buffer.buffer("4")); })); </DeepExtract> Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> server.stompHandler().getDestination("/queue") != null && server.stompHandler().getDestination("/queue").numberOfSubscriptions() == 1); vertx.runOnContext(v -> { reference.get().send("/queue", Buffer.buffer("5")); reference.get().send("/queue", Buffer.buffer("6")); }); Awaitility.waitAtMost(10, TimeUnit.SECONDS).until(() -> frames1.size() == 4 && frames2.size() == 2); }
vertx-stomp
positive
1,054
private static List<Length> parseLengthList(String val) throws SVGParseException { if (val.length() == 0) throw new SVGParseException("Invalid length list (empty string)"); List<Length> coords = new ArrayList<>(1); TextScanner scan = new TextScanner(val); while (position < inputLength) { if (!isWhitespace(input.charAt(position))) break; position++; } while (!scan.empty()) { float scalar = scan.nextFloat(); if (Float.isNaN(scalar)) throw new SVGParseException("Invalid length list value: " + scan.ahead()); Unit unit = scan.nextUnit(); if (unit == null) unit = Unit.px; coords.add(new Length(scalar, unit)); scan.skipCommaWhitespace(); } return coords; }
private static List<Length> parseLengthList(String val) throws SVGParseException { if (val.length() == 0) throw new SVGParseException("Invalid length list (empty string)"); List<Length> coords = new ArrayList<>(1); TextScanner scan = new TextScanner(val); <DeepExtract> while (position < inputLength) { if (!isWhitespace(input.charAt(position))) break; position++; } </DeepExtract> while (!scan.empty()) { float scalar = scan.nextFloat(); if (Float.isNaN(scalar)) throw new SVGParseException("Invalid length list value: " + scan.ahead()); Unit unit = scan.nextUnit(); if (unit == null) unit = Unit.px; coords.add(new Length(scalar, unit)); scan.skipCommaWhitespace(); } return coords; }
android-svg-code-render
positive
1,055
public static Intent getUninstallAppIntent(final String packageName, final boolean isNewTask) { Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + packageName)); return isNewTask ? intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) : intent; }
public static Intent getUninstallAppIntent(final String packageName, final boolean isNewTask) { Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + packageName)); <DeepExtract> return isNewTask ? intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) : intent; </DeepExtract> }
Engine
positive
1,056
public static void WhiffsRecover(Entity user) { if (CheckCancelFireWhiffs(user)) return; if (!user.getEntityData().getBoolean(IS_WHIFFS_STR)) return; user.getEntityData().setBoolean(IS_WHIFFS_STR, false); if (user == null) return; NBTTagCompound tag = getTag(user); int value = 0; if (AttackTypes.types.containsKey(whiffsPointChangeAmount())) value = (int) (RankRange * AttackTypes.types.get(whiffsPointChangeAmount()) * RankRate); if (value == 0) return; else if (value < 0) { value = Math.abs(value); } else { String timerKey = "SBAttackTime" + whiffsPointChangeAmount(); long last = tag.getLong(timerKey); long now = user.world.getGameTime(); if (last < now) { tag.setLong(timerKey, now + initCooltime); } else if ((last - now) < initCooltime) { value /= 2; tag.setLong(timerKey, Math.min(now + maxCooltime, last + addCooltime)); } else { value = 1; tag.setLong(timerKey, now + maxCooltime); } } int currentRank = getStylishRank(user); if (2 < currentRank) { currentRank = Math.min(rankText.length - 2, currentRank); currentRank -= 2; do { value *= 0.8f; } while (0 < --currentRank); value = Math.max(1, value); } addRankPoint(user, value); }
public static void WhiffsRecover(Entity user) { if (CheckCancelFireWhiffs(user)) return; if (!user.getEntityData().getBoolean(IS_WHIFFS_STR)) return; user.getEntityData().setBoolean(IS_WHIFFS_STR, false); <DeepExtract> if (user == null) return; NBTTagCompound tag = getTag(user); int value = 0; if (AttackTypes.types.containsKey(whiffsPointChangeAmount())) value = (int) (RankRange * AttackTypes.types.get(whiffsPointChangeAmount()) * RankRate); if (value == 0) return; else if (value < 0) { value = Math.abs(value); } else { String timerKey = "SBAttackTime" + whiffsPointChangeAmount(); long last = tag.getLong(timerKey); long now = user.world.getGameTime(); if (last < now) { tag.setLong(timerKey, now + initCooltime); } else if ((last - now) < initCooltime) { value /= 2; tag.setLong(timerKey, Math.min(now + maxCooltime, last + addCooltime)); } else { value = 1; tag.setLong(timerKey, now + maxCooltime); } } int currentRank = getStylishRank(user); if (2 < currentRank) { currentRank = Math.min(rankText.length - 2, currentRank); currentRank -= 2; do { value *= 0.8f; } while (0 < --currentRank); value = Math.max(1, value); } addRankPoint(user, value); </DeepExtract> }
SlashBlade
positive
1,057
public void logoff() throws RemoteException { if (this.sessionId == null) { throw new CollabNetApp.CollabNetAppException("Not currently in " + "a valid session."); } this.icns.logoff(this.username, this.sessionId); this.sessionId = null; }
public void logoff() throws RemoteException { <DeepExtract> if (this.sessionId == null) { throw new CollabNetApp.CollabNetAppException("Not currently in " + "a valid session."); } </DeepExtract> this.icns.logoff(this.username, this.sessionId); this.sessionId = null; }
collabnet-plugin
positive
1,058
public static void main(String[] args) { String subject = "sss"; User user = new User(); user.setUsername("ssadfasdf"); Map claims = new HashMap<>(); claims.put(Const.CURRENT_USER, "ssss"); System.out.println(new Date().getTime() + Const.ExpiredType.ONE_MONTH); String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMiIsImN1cnJlbnRVc2VyIjp7ImlkIjoyMiwidXNlcm5hbWUiOiJxcXFxIiwicGFzc3dvcmQiOiIzQkFENkFGMEZBNEI4QjMzMEQxNjJFMTk5MzhFRTk4MSIsImVtYWlsIjpudWxsLCJwaG9uZSI6IjEzNjUyNzM5MjExIiwicXVlc3Rpb24iOiLpl67popgiLCJhbnN3ZXIiOiLnrZTmoYgiLCJyb2xlIjowLCJ3ZWNoYXRPcGVuaWQiOm51bGwsImNyZWF0ZVRpbWUiOjE1MjY2MDcxNzcwMDAsInVwZGF0ZVRpbWUiOjE1MjY2MDcxNzcwMDB9LCJleHAiOjI1OTIwMDAsImlhdCI6MTUzMDU5NzM5MCwianRpIjoiYWEyYjg4YTMxMTNiNDZmNDk2Y2QyYTIwY2E4MTdiYmYifQ.kb7rnEKLLW6rP0zzs8hWTRkxjjQMliWfVZyzXJvgQNM"; System.out.println(token); try { Claims claims = parseToken(token); System.out.println(claims.get(Const.CURRENT_USER)); } catch (ExpiredJwtException e) { System.out.println("token expired"); } catch (InvalidClaimException e) { System.out.println("token invalid"); } catch (Exception e) { System.out.println("token error"); } }
public static void main(String[] args) { String subject = "sss"; User user = new User(); user.setUsername("ssadfasdf"); Map claims = new HashMap<>(); claims.put(Const.CURRENT_USER, "ssss"); System.out.println(new Date().getTime() + Const.ExpiredType.ONE_MONTH); String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMiIsImN1cnJlbnRVc2VyIjp7ImlkIjoyMiwidXNlcm5hbWUiOiJxcXFxIiwicGFzc3dvcmQiOiIzQkFENkFGMEZBNEI4QjMzMEQxNjJFMTk5MzhFRTk4MSIsImVtYWlsIjpudWxsLCJwaG9uZSI6IjEzNjUyNzM5MjExIiwicXVlc3Rpb24iOiLpl67popgiLCJhbnN3ZXIiOiLnrZTmoYgiLCJyb2xlIjowLCJ3ZWNoYXRPcGVuaWQiOm51bGwsImNyZWF0ZVRpbWUiOjE1MjY2MDcxNzcwMDAsInVwZGF0ZVRpbWUiOjE1MjY2MDcxNzcwMDB9LCJleHAiOjI1OTIwMDAsImlhdCI6MTUzMDU5NzM5MCwianRpIjoiYWEyYjg4YTMxMTNiNDZmNDk2Y2QyYTIwY2E4MTdiYmYifQ.kb7rnEKLLW6rP0zzs8hWTRkxjjQMliWfVZyzXJvgQNM"; System.out.println(token); <DeepExtract> try { Claims claims = parseToken(token); System.out.println(claims.get(Const.CURRENT_USER)); } catch (ExpiredJwtException e) { System.out.println("token expired"); } catch (InvalidClaimException e) { System.out.println("token invalid"); } catch (Exception e) { System.out.println("token error"); } </DeepExtract> }
ppmall-server
positive
1,059
@Override public PageResource display() { g.drawImage(this.unwrap(Draw.class).image, 0, 0, null); return this; return this; }
@Override public PageResource display() { <DeepExtract> g.drawImage(this.unwrap(Draw.class).image, 0, 0, null); return this; </DeepExtract> return this; }
bbvm
positive
1,060
public static OtapInitRequest deserialize_OtapInitRequest(byte[] buffer, ByteArrayOutputStream reader) { is = new ByteArrayInputStream(buffer); long result = 0; for (int i1 = 0; i1 < 1; ++i1) { result |= ((is.read() & 0xFF) << (8 * i1)); } return result; long result = 0; for (int i1 = 0; i1 < 1; ++i1) { result |= ((is.read() & 0xFF) << (8 * i1)); } return result; OtapInitRequest dtype = new OtapInitRequest(); dtype.chunk_count = (short) readInteger(1); dtype.timeout_multiplier_ms = (short) readInteger(1); dtype.max_re_requests = (short) readInteger(1); dtype.participating_devices.count = (int) readInteger(1); for (int i1 = 0; i1 < dtype.participating_devices.count; ++i1) { dtype.participating_devices.value[i1] = (int) readInteger(2); } return dtype; }
public static OtapInitRequest deserialize_OtapInitRequest(byte[] buffer, ByteArrayOutputStream reader) { is = new ByteArrayInputStream(buffer); <DeepExtract> long result = 0; for (int i1 = 0; i1 < 1; ++i1) { result |= ((is.read() & 0xFF) << (8 * i1)); } return result; </DeepExtract> long result = 0; for (int i1 = 0; i1 < 1; ++i1) { result |= ((is.read() & 0xFF) << (8 * i1)); } return result; OtapInitRequest dtype = new OtapInitRequest(); dtype.chunk_count = (short) readInteger(1); dtype.timeout_multiplier_ms = (short) readInteger(1); dtype.max_re_requests = (short) readInteger(1); dtype.participating_devices.count = (int) readInteger(1); for (int i1 = 0; i1 < dtype.participating_devices.count; ++i1) { dtype.participating_devices.value[i1] = (int) readInteger(2); } return dtype; }
netty-protocols
positive
1,062
@Test public void testTransitEncrypt() throws Exception { final JsonObject expectedRequest = new JsonObject().add("plaintext", PLAIN_DATA[0]); final JsonObject expectedResponse = new JsonObject().add("data", new JsonObject().add("ciphertext", CIPHER_DATA[0])); vaultServer = new MockVault(200, expectedResponse.toString()); server = VaultTestUtils.initHttpMockVault(vaultServer); server.start(); final VaultConfig vaultConfig = new VaultConfig().address("http://127.0.0.1:8999").build(); final Vault vault = new Vault(vaultConfig, 1); LogicalResponse response = vault.logical().write("transit/encrypt/test", Collections.singletonMap("plaintext", PLAIN_DATA[0])); assertEquals("http://127.0.0.1:8999/v1/transit/encrypt/test", vaultServer.getRequestUrl()); assertEquals(Optional.of(expectedRequest), vaultServer.getRequestBody()); assertEquals(200, response.getRestResponse().getStatus()); }
@Test public void testTransitEncrypt() throws Exception { final JsonObject expectedRequest = new JsonObject().add("plaintext", PLAIN_DATA[0]); final JsonObject expectedResponse = new JsonObject().add("data", new JsonObject().add("ciphertext", CIPHER_DATA[0])); <DeepExtract> vaultServer = new MockVault(200, expectedResponse.toString()); server = VaultTestUtils.initHttpMockVault(vaultServer); server.start(); </DeepExtract> final VaultConfig vaultConfig = new VaultConfig().address("http://127.0.0.1:8999").build(); final Vault vault = new Vault(vaultConfig, 1); LogicalResponse response = vault.logical().write("transit/encrypt/test", Collections.singletonMap("plaintext", PLAIN_DATA[0])); assertEquals("http://127.0.0.1:8999/v1/transit/encrypt/test", vaultServer.getRequestUrl()); assertEquals(Optional.of(expectedRequest), vaultServer.getRequestBody()); assertEquals(200, response.getRestResponse().getStatus()); }
vault-java-driver
positive
1,063
public static void writeChipSign(Sign sign, String type, String[] args) { sign.setLine(0, type); String line = ""; int curLine = 1; for (String a : args) { String added = line + " " + a; if (added.length() > 13 && curLine != 3) { sign.setLine(curLine, line); line = a; curLine++; } else line = added; } sign.setLine(curLine, line); if (curLine < 3) for (int i = curLine + 1; i < 4; i++) sign.setLine(i, ""); sign.update(); }
public static void writeChipSign(Sign sign, String type, String[] args) { sign.setLine(0, type); <DeepExtract> String line = ""; int curLine = 1; for (String a : args) { String added = line + " " + a; if (added.length() > 13 && curLine != 3) { sign.setLine(curLine, line); line = a; curLine++; } else line = added; } sign.setLine(curLine, line); if (curLine < 3) for (int i = curLine + 1; i < 4; i++) sign.setLine(i, ""); </DeepExtract> sign.update(); }
RedstoneChips
positive
1,064
public Criteria andAsyncDelayLessThan(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "asyncDelay" + " cannot be null"); } criteria.add(new Criterion("async_delay <", value)); return (Criteria) this; }
public Criteria andAsyncDelayLessThan(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "asyncDelay" + " cannot be null"); } criteria.add(new Criterion("async_delay <", value)); </DeepExtract> return (Criteria) this; }
AnyMock
positive
1,065
public static byte[] encryptHmacSHA224(byte[] data, byte[] key) { if (data == null || data.length == 0 || key == null || key.length == 0) return null; try { SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA224"); Mac mac = Mac.getInstance("HmacSHA224"); mac.init(secretKey); return mac.doFinal(data); } catch (InvalidKeyException | NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
public static byte[] encryptHmacSHA224(byte[] data, byte[] key) { <DeepExtract> if (data == null || data.length == 0 || key == null || key.length == 0) return null; try { SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA224"); Mac mac = Mac.getInstance("HmacSHA224"); mac.init(secretKey); return mac.doFinal(data); } catch (InvalidKeyException | NoSuchAlgorithmException e) { e.printStackTrace(); return null; } </DeepExtract> }
AndroidBase
positive
1,066
@Override public ActionResult simulate(Context context) { ActionResult actionResult = context.createActionResult(); try { Authorizable authorizable = context.getCurrentAuthorizable(); actionResult.setAuthorizable(authorizable.getID()); if (context.isCompositeNodeStore() && PathUtils.isAppsOrLibsPath(path)) { actionResult.changeStatus(Status.SKIPPED, "Skipped purging privileges for " + authorizable.getID() + " on " + path); } else { LOGGER.info(String.format("Purging privileges for authorizable with id = %s under path = %s", authorizable.getID(), path)); if (false) { purge(context, actionResult); } actionResult.logMessage("Purged privileges for " + authorizable.getID() + " on " + path); } } catch (RepositoryException | ActionExecutionException e) { actionResult.logError(MessagingUtils.createMessage(e)); } return actionResult; }
@Override public ActionResult simulate(Context context) { <DeepExtract> ActionResult actionResult = context.createActionResult(); try { Authorizable authorizable = context.getCurrentAuthorizable(); actionResult.setAuthorizable(authorizable.getID()); if (context.isCompositeNodeStore() && PathUtils.isAppsOrLibsPath(path)) { actionResult.changeStatus(Status.SKIPPED, "Skipped purging privileges for " + authorizable.getID() + " on " + path); } else { LOGGER.info(String.format("Purging privileges for authorizable with id = %s under path = %s", authorizable.getID(), path)); if (false) { purge(context, actionResult); } actionResult.logMessage("Purged privileges for " + authorizable.getID() + " on " + path); } } catch (RepositoryException | ActionExecutionException e) { actionResult.logError(MessagingUtils.createMessage(e)); } return actionResult; </DeepExtract> }
APM
positive
1,067
public static String delZeroPre(String num) { if (!NumberUtil.isNumber(num)) { return num; } if (NumberUtil.parseNumber(num) == null) { return StrUtil.EMPTY; } return NumberUtil.toStr(NumberUtil.parseNumber(num)); }
public static String delZeroPre(String num) { if (!NumberUtil.isNumber(num)) { return num; } <DeepExtract> if (NumberUtil.parseNumber(num) == null) { return StrUtil.EMPTY; } return NumberUtil.toStr(NumberUtil.parseNumber(num)); </DeepExtract> }
chao-cloud
positive
1,068
@Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { if (toTransform == null) return null; Bitmap result = pool.get(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); RectF rectF = new RectF(0f, 0f, toTransform.getWidth(), toTransform.getHeight()); canvas.drawRoundRect(rectF, radius, radius, paint); return result; }
@Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { <DeepExtract> if (toTransform == null) return null; Bitmap result = pool.get(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(toTransform.getWidth(), toTransform.getHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); RectF rectF = new RectF(0f, 0f, toTransform.getWidth(), toTransform.getHeight()); canvas.drawRoundRect(rectF, radius, radius, paint); return result; </DeepExtract> }
Headline_News_Kotlin_App
positive
1,069
protected void startLoading() { if (isPullLoading()) { return; } mPullUpState = State.REFRESHING; if (null != mFooterLayout) { mFooterLayout.setState(State.REFRESHING); } if (null != mRefreshListener) { postDelayed(new Runnable() { @Override public void run() { mRefreshListener.onPullUpToRefresh(PullToRefreshBase.this); } }, getSmoothScrollDuration()); } }
protected void startLoading() { <DeepExtract> </DeepExtract> if (isPullLoading()) { <DeepExtract> </DeepExtract> return; <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> mPullUpState = State.REFRESHING; <DeepExtract> </DeepExtract> if (null != mFooterLayout) { <DeepExtract> </DeepExtract> mFooterLayout.setState(State.REFRESHING); <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> if (null != mRefreshListener) { <DeepExtract> </DeepExtract> postDelayed(new Runnable() { <DeepExtract> </DeepExtract> @Override <DeepExtract> </DeepExtract> public void run() { <DeepExtract> </DeepExtract> mRefreshListener.onPullUpToRefresh(PullToRefreshBase.this); <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> }, getSmoothScrollDuration()); <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> }
eduOnline_android
positive
1,070
public void loadNextPage() { page++; if (NetWorkUtil.isNetWorkConnected(mActivity)) { loadData(); } else { loadCache(); } }
public void loadNextPage() { page++; <DeepExtract> if (NetWorkUtil.isNetWorkConnected(mActivity)) { loadData(); } else { loadCache(); } </DeepExtract> }
JianDan_OkHttp
positive
1,071
public boolean skipRecord() throws IOException { if (closed) { throw new IOException("This instance of the CsvReader class has already been closed."); } boolean recordRead = false; if (hasMoreData) { recordRead = readRecord(); if (recordRead) { currentRecord--; } } return recordRead; }
public boolean skipRecord() throws IOException { <DeepExtract> if (closed) { throw new IOException("This instance of the CsvReader class has already been closed."); } </DeepExtract> boolean recordRead = false; if (hasMoreData) { recordRead = readRecord(); if (recordRead) { currentRecord--; } } return recordRead; }
dataSync
positive
1,072
@Override public ArrayList<DateHolder> previous() { cPeriod = cPeriod.minusYears(1); ArrayList<DateHolder> dates = new ArrayList<DateHolder>(); checkDate = new LocalDate(cPeriod); int counter = 0; int quantity = checkDate.dayOfYear().getMaximumValue(); while ((openFuturePeriods > 0 || currentDate.isAfter(checkDate)) && counter < quantity) { String date = checkDate.toString(DATE_FORMAT); String dName = checkDate.dayOfMonth().getAsString(); String mName = checkDate.monthOfYear().getAsText(); String yName = checkDate.year().getAsString(); String label = String.format(DATE_LABEL_FORMAT, dName, mName, yName); if (checkDate.isBefore(maxDate) && isInInputPeriods(date)) { DateHolder dateHolder = new DateHolder(date, checkDate.toString(), label); dates.add(dateHolder); } counter++; checkDate = checkDate.plusDays(1); } Collections.reverse(dates); return dates; }
@Override public ArrayList<DateHolder> previous() { cPeriod = cPeriod.minusYears(1); <DeepExtract> ArrayList<DateHolder> dates = new ArrayList<DateHolder>(); checkDate = new LocalDate(cPeriod); int counter = 0; int quantity = checkDate.dayOfYear().getMaximumValue(); while ((openFuturePeriods > 0 || currentDate.isAfter(checkDate)) && counter < quantity) { String date = checkDate.toString(DATE_FORMAT); String dName = checkDate.dayOfMonth().getAsString(); String mName = checkDate.monthOfYear().getAsText(); String yName = checkDate.year().getAsString(); String label = String.format(DATE_LABEL_FORMAT, dName, mName, yName); if (checkDate.isBefore(maxDate) && isInInputPeriods(date)) { DateHolder dateHolder = new DateHolder(date, checkDate.toString(), label); dates.add(dateHolder); } counter++; checkDate = checkDate.plusDays(1); } Collections.reverse(dates); return dates; </DeepExtract> }
dhis2-android-datacapture
positive
1,074
public static DaoSession newDevSession(Context context, String name) { Database db = new DevOpenHelper(context, name).getWritableDb(); DaoMaster daoMaster = new DaoMaster(db); return new DaoSession(db, IdentityScopeType.Session, daoConfigMap); }
public static DaoSession newDevSession(Context context, String name) { Database db = new DevOpenHelper(context, name).getWritableDb(); DaoMaster daoMaster = new DaoMaster(db); <DeepExtract> return new DaoSession(db, IdentityScopeType.Session, daoConfigMap); </DeepExtract> }
MovieNews
positive
1,075
public static DataSource fromEnvironment(String name, String group, String key, String contentType) { Validate.notEmpty(System.getenv(key), "Environment variable not found: " + key); final StringDataSource dataSource = new StringDataSource(name, System.getenv(key), contentType, UTF_8); final URI uri = UriUtils.toUri(Location.ENVIRONMENT, key); return DataSource.builder().name(name).group(group).uri(uri).dataSource(dataSource).contentType(contentType).charset(UTF_8).properties(noProperties()).build(); }
public static DataSource fromEnvironment(String name, String group, String key, String contentType) { Validate.notEmpty(System.getenv(key), "Environment variable not found: " + key); final StringDataSource dataSource = new StringDataSource(name, System.getenv(key), contentType, UTF_8); final URI uri = UriUtils.toUri(Location.ENVIRONMENT, key); <DeepExtract> return DataSource.builder().name(name).group(group).uri(uri).dataSource(dataSource).contentType(contentType).charset(UTF_8).properties(noProperties()).build(); </DeepExtract> }
freemarker-generator
positive
1,076
public void setScopeTestExcluded(boolean value) throws CoreException { getConfigurationWorkingCopy().setAttribute(ATTR_EXCLUDE_SCOPE_TEST, value); if (!false) { return; } JettyPlugin.getDefaultScope().getNode(JettyPlugin.PLUGIN_ID).putBoolean(ATTR_EXCLUDE_SCOPE_TEST, value); try { JettyPlugin.getDefaultScope().getNode(JettyPlugin.PLUGIN_ID).flush(); } catch (BackingStoreException e) { } }
public void setScopeTestExcluded(boolean value) throws CoreException { <DeepExtract> getConfigurationWorkingCopy().setAttribute(ATTR_EXCLUDE_SCOPE_TEST, value); if (!false) { return; } JettyPlugin.getDefaultScope().getNode(JettyPlugin.PLUGIN_ID).putBoolean(ATTR_EXCLUDE_SCOPE_TEST, value); try { JettyPlugin.getDefaultScope().getNode(JettyPlugin.PLUGIN_ID).flush(); } catch (BackingStoreException e) { } </DeepExtract> }
eclipse-jetty-plugin
positive
1,077
public Criteria andMarkIsNotNull() { if ("mark is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("mark is not null")); return (Criteria) this; }
public Criteria andMarkIsNotNull() { <DeepExtract> if ("mark is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("mark is not null")); </DeepExtract> return (Criteria) this; }
JavaWeb-WeChatMini
positive
1,078
@Override public void onButtonStartEmailClick() { IntentUtility.startEmailActivity(getContext(), "[email protected]", "Alfonz", "Hello world!"); }
@Override public void onButtonStartEmailClick() { <DeepExtract> IntentUtility.startEmailActivity(getContext(), "[email protected]", "Alfonz", "Hello world!"); </DeepExtract> }
Alfonz
positive
1,079
public Criteria andWorkPlaceNotLike(String value) { if (value == null) { throw new RuntimeException("Value for " + "workPlace" + " cannot be null"); } criteria.add(new Criterion("work_place not like", value)); return (Criteria) this; }
public Criteria andWorkPlaceNotLike(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "workPlace" + " cannot be null"); } criteria.add(new Criterion("work_place not like", value)); </DeepExtract> return (Criteria) this; }
BookLibrarySystem
positive
1,080
private void init() { connector = new NioSocketConnector(); this.connectTimeoutMillis = connectTimeoutMillis; connector.getFilterChain().addLast("logger", new LoggingFilter()); this.readBufferSize = new Double(MathUtil.evaluate(readBufferSize)).intValue(); if (protocolCodecFactory != null) { connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(protocolCodecFactory)); } LongClientHandler clientHandler = new LongClientHandler(); connector.setHandler(clientHandler); for (int i = 0; i < poolSize; i++) { ConnectFuture connection = connector.connect(new InetSocketAddress(host, port)); connection.awaitUninterruptibly(); try { idlePool.put(connection); } catch (InterruptedException e) { e.printStackTrace(); } } }
private void init() { connector = new NioSocketConnector(); this.connectTimeoutMillis = connectTimeoutMillis; connector.getFilterChain().addLast("logger", new LoggingFilter()); this.readBufferSize = new Double(MathUtil.evaluate(readBufferSize)).intValue(); if (protocolCodecFactory != null) { connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(protocolCodecFactory)); } LongClientHandler clientHandler = new LongClientHandler(); connector.setHandler(clientHandler); <DeepExtract> for (int i = 0; i < poolSize; i++) { ConnectFuture connection = connector.connect(new InetSocketAddress(host, port)); connection.awaitUninterruptibly(); try { idlePool.put(connection); } catch (InterruptedException e) { e.printStackTrace(); } } </DeepExtract> }
springmore
positive
1,081
private void evalConcatExprs(final ArrayList<BaseExpr> exprs) { final AbraSiteKnot site = new AbraSiteKnot(); for (final BaseExpr expr : exprs) { expr.eval(this); site.size += expr.size; if (lastSite instanceof AbraSiteKnot) { final AbraSiteKnot knot = (AbraSiteKnot) lastSite; if (knot.block.index == AbraBlockSpecial.TYPE_CONCAT) { site.inputs.addAll(knot.inputs); continue; } } site.inputs.add(lastSite); } site.block = new AbraBlockSpecial(AbraBlockSpecial.TYPE_CONCAT, site.size); if (stmt != null) { site.stmt = stmt; stmt = null; } site.index = branch.totalSites(); branch.sites.add(site); lastSite = site; }
private void evalConcatExprs(final ArrayList<BaseExpr> exprs) { final AbraSiteKnot site = new AbraSiteKnot(); for (final BaseExpr expr : exprs) { expr.eval(this); site.size += expr.size; if (lastSite instanceof AbraSiteKnot) { final AbraSiteKnot knot = (AbraSiteKnot) lastSite; if (knot.block.index == AbraBlockSpecial.TYPE_CONCAT) { site.inputs.addAll(knot.inputs); continue; } } site.inputs.add(lastSite); } site.block = new AbraBlockSpecial(AbraBlockSpecial.TYPE_CONCAT, site.size); <DeepExtract> if (stmt != null) { site.stmt = stmt; stmt = null; } site.index = branch.totalSites(); branch.sites.add(site); lastSite = site; </DeepExtract> }
qupla
positive
1,082
public void setCard(Card godCard, VirtualClient client, TurnController controller) { this.card = godCard; WorkerCreator creator = new WorkerCreator(); workers.add(creator.getWorker(card, color, controller)); workers.add(creator.getWorker(card, color, controller)); workers.forEach(n -> n.createListeners(client)); }
public void setCard(Card godCard, VirtualClient client, TurnController controller) { this.card = godCard; <DeepExtract> WorkerCreator creator = new WorkerCreator(); workers.add(creator.getWorker(card, color, controller)); workers.add(creator.getWorker(card, color, controller)); workers.forEach(n -> n.createListeners(client)); </DeepExtract> }
ing-sw-2020-piemonti-pirovano-sonnino
positive
1,083
@Override public void sendPushMessage(final Variant variant, final Collection<String> tokens, final UnifiedPushMessage pushMessage, final String pushMessageInformationId, final NotificationSenderCallback senderCallback) { if (tokens.isEmpty()) { return; } final iOSVariant apnsVariant = (iOSVariant) variant; if (!ApnsUtil.checkValidity(apnsVariant.getCertificate(), apnsVariant.getPassphrase().toCharArray())) { senderCallback.onError("The provided certificate is invalid or expired for variant " + apnsVariant.getId()); return; } final String payload; { try { payload = createPushPayload(pushMessage.getMessage(), pushMessageInformationId); } catch (IllegalArgumentException iae) { logger.info(iae.getMessage(), iae); senderCallback.onError("Nothing sent to APNs since the payload is too large"); return; } } final ApnsClient apnsClient; { try { apnsClient = receiveApnsConnection(apnsVariant); } catch (IllegalArgumentException iae) { logger.error(iae.getMessage(), iae); senderCallback.onError(String.format("Unable to connect to APNs (%s))", iae.getMessage())); return; } } if (apnsClient != null) { PrometheusExporter.instance().increaseTotalPushIosRequests(); senderCallback.onSuccess(); final String defaultApnsTopic = ApnsUtil.readDefaultTopic(apnsVariant.getCertificate(), apnsVariant.getPassphrase().toCharArray()); Date expireDate = createFutureDateBasedOnTTL(pushMessage.getConfig().getTimeToLive()); logger.debug("sending payload for all tokens for {} to APNs ({})", apnsVariant.getVariantID(), defaultApnsTopic); tokens.forEach(token -> { final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token, defaultApnsTopic, payload, expireDate.toInstant(), DeliveryPriority.IMMEDIATE, determinePushType(pushMessage.getMessage()), null, null); PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> notificationSendFuture = apnsClient.sendNotification(pushNotification); notificationSendFuture.whenComplete((pushNotificationResponse, cause) -> { if (pushNotificationResponse != null) { handlePushNotificationResponsePerToken(pushNotificationResponse); } else { logger.error("Unable to send notifications", cause); senderCallback.onError("Unable to send notifications: " + cause.getMessage()); variantUpdateEventEvent.fire(new APNSVariantUpdateEvent(apnsVariant)); } }); }); } else { logger.error("Unable to send notifications, client is not connected. Removing from cache pool"); senderCallback.onError("Unable to send notifications, client is not connected"); variantUpdateEventEvent.fire(new APNSVariantUpdateEvent(apnsVariant)); } }
@Override public void sendPushMessage(final Variant variant, final Collection<String> tokens, final UnifiedPushMessage pushMessage, final String pushMessageInformationId, final NotificationSenderCallback senderCallback) { if (tokens.isEmpty()) { return; } final iOSVariant apnsVariant = (iOSVariant) variant; <DeepExtract> if (!ApnsUtil.checkValidity(apnsVariant.getCertificate(), apnsVariant.getPassphrase().toCharArray())) { senderCallback.onError("The provided certificate is invalid or expired for variant " + apnsVariant.getId()); return; } final String payload; { try { payload = createPushPayload(pushMessage.getMessage(), pushMessageInformationId); } catch (IllegalArgumentException iae) { logger.info(iae.getMessage(), iae); senderCallback.onError("Nothing sent to APNs since the payload is too large"); return; } } final ApnsClient apnsClient; { try { apnsClient = receiveApnsConnection(apnsVariant); } catch (IllegalArgumentException iae) { logger.error(iae.getMessage(), iae); senderCallback.onError(String.format("Unable to connect to APNs (%s))", iae.getMessage())); return; } } if (apnsClient != null) { PrometheusExporter.instance().increaseTotalPushIosRequests(); senderCallback.onSuccess(); final String defaultApnsTopic = ApnsUtil.readDefaultTopic(apnsVariant.getCertificate(), apnsVariant.getPassphrase().toCharArray()); Date expireDate = createFutureDateBasedOnTTL(pushMessage.getConfig().getTimeToLive()); logger.debug("sending payload for all tokens for {} to APNs ({})", apnsVariant.getVariantID(), defaultApnsTopic); tokens.forEach(token -> { final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token, defaultApnsTopic, payload, expireDate.toInstant(), DeliveryPriority.IMMEDIATE, determinePushType(pushMessage.getMessage()), null, null); PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> notificationSendFuture = apnsClient.sendNotification(pushNotification); notificationSendFuture.whenComplete((pushNotificationResponse, cause) -> { if (pushNotificationResponse != null) { handlePushNotificationResponsePerToken(pushNotificationResponse); } else { logger.error("Unable to send notifications", cause); senderCallback.onError("Unable to send notifications: " + cause.getMessage()); variantUpdateEventEvent.fire(new APNSVariantUpdateEvent(apnsVariant)); } }); }); } else { logger.error("Unable to send notifications, client is not connected. Removing from cache pool"); senderCallback.onError("Unable to send notifications, client is not connected"); variantUpdateEventEvent.fire(new APNSVariantUpdateEvent(apnsVariant)); } </DeepExtract> }
aerogear-unifiedpush-server
positive
1,084
@Override public void refreshNew(@NonNull List items) { mPullToRefreshRecyclerView.onRefreshComplete(); baseProgressbar.loadingHide(); if (items.isEmpty() || adapter.getItems().containsAll(items)) { return; } adapter.getItems().clear(); adapter.getItems().addAll(items); adapter.notifyDataSetChanged(); }
@Override public void refreshNew(@NonNull List items) { <DeepExtract> mPullToRefreshRecyclerView.onRefreshComplete(); baseProgressbar.loadingHide(); </DeepExtract> if (items.isEmpty() || adapter.getItems().containsAll(items)) { return; } adapter.getItems().clear(); adapter.getItems().addAll(items); adapter.notifyDataSetChanged(); }
banciyuan-unofficial
positive
1,085
private void processSeedList(int[] seeds) { for (int j = 0; j < seeds.length; j += 4) { processSeed(seeds[j], seeds[j + 1], seeds[j + 2], seeds[j + 3]); } if (hbdBaos.size() >= BAOS_THRESHOLD) { try { hbdOut.close(); hbdOS.write(hbdBaos.toByteArray()); hbdBaos.reset(); hbdOut = printWriter(hbdBaos); } catch (IOException ex) { Utilities.exit("ERROR: ", ex); } } if (ibdBaos.size() >= BAOS_THRESHOLD) { try { ibdOut.close(); ibdOS.write(ibdBaos.toByteArray()); ibdBaos.reset(); ibdOut = printWriter(ibdBaos); } catch (IOException ex) { Utilities.exit("ERROR: ", ex); } } }
private void processSeedList(int[] seeds) { for (int j = 0; j < seeds.length; j += 4) { processSeed(seeds[j], seeds[j + 1], seeds[j + 2], seeds[j + 3]); } if (hbdBaos.size() >= BAOS_THRESHOLD) { try { hbdOut.close(); hbdOS.write(hbdBaos.toByteArray()); hbdBaos.reset(); hbdOut = printWriter(hbdBaos); } catch (IOException ex) { Utilities.exit("ERROR: ", ex); } } <DeepExtract> if (ibdBaos.size() >= BAOS_THRESHOLD) { try { ibdOut.close(); ibdOS.write(ibdBaos.toByteArray()); ibdBaos.reset(); ibdOut = printWriter(ibdBaos); } catch (IOException ex) { Utilities.exit("ERROR: ", ex); } } </DeepExtract> }
hap-ibd
positive
1,087
public void createCursor(int[] cursorPixels, int hotX, int hotY, int width, int height) { createNewCursorImage(cursorPixels, hotX, hotY, width, height); this.hotX = hotX; this.hotY = hotY; oldWidth = this.width; oldHeight = this.height; oldRX = rX; oldRY = rY; rX = x - hotX; rY = y - hotY; this.width = width; this.height = height; }
public void createCursor(int[] cursorPixels, int hotX, int hotY, int width, int height) { createNewCursorImage(cursorPixels, hotX, hotY, width, height); <DeepExtract> this.hotX = hotX; this.hotY = hotY; oldWidth = this.width; oldHeight = this.height; oldRX = rX; oldRY = rY; rX = x - hotX; rY = y - hotY; this.width = width; this.height = height; </DeepExtract> }
tvnjviewer
positive
1,088
@Override protected void onScrollChanged(int x, int y, int oldx, int oldy) { super.onScrollChanged(x, y, oldx, oldy); if (contentView != null && contentView.getMeasuredHeight() <= getScrollY() + getHeight()) { if (onBorderListener != null) { onBorderListener.onBottom(); } } else if (getScrollY() == 0) { if (onBorderListener != null) { onBorderListener.onTop(); } } }
@Override protected void onScrollChanged(int x, int y, int oldx, int oldy) { super.onScrollChanged(x, y, oldx, oldy); <DeepExtract> if (contentView != null && contentView.getMeasuredHeight() <= getScrollY() + getHeight()) { if (onBorderListener != null) { onBorderListener.onBottom(); } } else if (getScrollY() == 0) { if (onBorderListener != null) { onBorderListener.onTop(); } } </DeepExtract> }
android-common
positive
1,089
public PageNavigation previous() { getPagination().previousPage(); items = null; return PageNavigation.LIST; }
public PageNavigation previous() { getPagination().previousPage(); <DeepExtract> items = null; </DeepExtract> return PageNavigation.LIST; }
modular-dukes-forest
positive
1,090
public void setUniform(int index, long val) { if (slots[index].dataType().compareTo(UniformUsage.UNIFORM_USAGE_INT_64) != 0) { throw new Error("Uniform usage mismatch! Expected: " + slots[index].toString() + " Recived: " + UniformUsage.UNIFORM_USAGE_INT_64.name()); } upToDate = false; data.putLong(prefTab[index], val); }
public void setUniform(int index, long val) { <DeepExtract> if (slots[index].dataType().compareTo(UniformUsage.UNIFORM_USAGE_INT_64) != 0) { throw new Error("Uniform usage mismatch! Expected: " + slots[index].toString() + " Recived: " + UniformUsage.UNIFORM_USAGE_INT_64.name()); } upToDate = false; </DeepExtract> data.putLong(prefTab[index], val); }
SFE-Engine
positive
1,091
public void setRenderer(GLTextureView.Renderer renderer) { if (mGLThread != null) { throw new IllegalStateException("setRenderer has already been called for this instance."); } if (mEGLConfigChooser == null) { mEGLConfigChooser = new SimpleEGLConfigChooser(true); } if (mEGLContextFactory == null) { mEGLContextFactory = new DefaultContextFactory(); } if (mEGLWindowSurfaceFactory == null) { mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory(); } mRenderer = renderer; mGLThread = new GLThread(mThisWeakRef); if (LOG_EGL) { Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId()); } mEgl = (EGL10) EGLContext.getEGL(); mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); if (mEglDisplay == EGL10.EGL_NO_DISPLAY) { throw new RuntimeException("eglGetDisplay failed"); } int[] version = new int[2]; if (!mEgl.eglInitialize(mEglDisplay, version)) { throw new RuntimeException("eglInitialize failed"); } GLTextureView view = mGLSurfaceViewWeakRef.get(); if (view == null) { mEglConfig = null; mEglContext = null; } else { mEglConfig = view.mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay); mEglContext = view.mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig); } if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) { mEglContext = null; throwEglException("createContext"); } if (LOG_EGL) { Log.w("EglHelper", "createContext " + mEglContext + " tid=" + Thread.currentThread().getId()); } mEglSurface = null; }
public void setRenderer(GLTextureView.Renderer renderer) { if (mGLThread != null) { throw new IllegalStateException("setRenderer has already been called for this instance."); } if (mEGLConfigChooser == null) { mEGLConfigChooser = new SimpleEGLConfigChooser(true); } if (mEGLContextFactory == null) { mEGLContextFactory = new DefaultContextFactory(); } if (mEGLWindowSurfaceFactory == null) { mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory(); } mRenderer = renderer; mGLThread = new GLThread(mThisWeakRef); <DeepExtract> if (LOG_EGL) { Log.w("EglHelper", "start() tid=" + Thread.currentThread().getId()); } mEgl = (EGL10) EGLContext.getEGL(); mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); if (mEglDisplay == EGL10.EGL_NO_DISPLAY) { throw new RuntimeException("eglGetDisplay failed"); } int[] version = new int[2]; if (!mEgl.eglInitialize(mEglDisplay, version)) { throw new RuntimeException("eglInitialize failed"); } GLTextureView view = mGLSurfaceViewWeakRef.get(); if (view == null) { mEglConfig = null; mEglContext = null; } else { mEglConfig = view.mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay); mEglContext = view.mEGLContextFactory.createContext(mEgl, mEglDisplay, mEglConfig); } if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) { mEglContext = null; throwEglException("createContext"); } if (LOG_EGL) { Log.w("EglHelper", "createContext " + mEglContext + " tid=" + Thread.currentThread().getId()); } mEglSurface = null; </DeepExtract> }
PhotoMovie
positive
1,092
public Criteria andBz119NotBetween(String value1, String value2) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "bz119" + " cannot be null"); } criteria.add(new Criterion("`bz119` not between", value1, value2)); return (Criteria) this; }
public Criteria andBz119NotBetween(String value1, String value2) { <DeepExtract> if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "bz119" + " cannot be null"); } criteria.add(new Criterion("`bz119` not between", value1, value2)); </DeepExtract> return (Criteria) this; }
blockhealth
positive
1,093
public static void index(byte[] source, UUID picture_id, IndexWriterConfig conf) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(source); BufferedImage image = ImageIO.read(in); log.debug("Is Lucene configured? " + (conf == null)); if (conf == null) { conf = new IndexWriterConfig(LuceneUtils.LUCENE_VERSION, new WhitespaceAnalyzer(LuceneUtils.LUCENE_VERSION)); conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); } File path = getPath(FeatureEnumerate.AutoColorCorrelogram.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getAutoColorCorrelogramDocumentBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); File path = getPath(FeatureEnumerate.CEDD.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getCEDDDocumentBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); File path = getPath(FeatureEnumerate.ColorLayout.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getColorLayoutBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); File path = getPath(FeatureEnumerate.EdgeHistogram.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getEdgeHistogramBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); File path = getPath(FeatureEnumerate.ColorHistogram.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getColorHistogramDocumentBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); File path = getPath(FeatureEnumerate.PHOG.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getPHOGDocumentBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); }
public static void index(byte[] source, UUID picture_id, IndexWriterConfig conf) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(source); BufferedImage image = ImageIO.read(in); log.debug("Is Lucene configured? " + (conf == null)); if (conf == null) { conf = new IndexWriterConfig(LuceneUtils.LUCENE_VERSION, new WhitespaceAnalyzer(LuceneUtils.LUCENE_VERSION)); conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); } File path = getPath(FeatureEnumerate.AutoColorCorrelogram.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getAutoColorCorrelogramDocumentBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); File path = getPath(FeatureEnumerate.CEDD.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getCEDDDocumentBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); File path = getPath(FeatureEnumerate.ColorLayout.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getColorLayoutBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); File path = getPath(FeatureEnumerate.EdgeHistogram.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getEdgeHistogramBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); File path = getPath(FeatureEnumerate.ColorHistogram.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getColorHistogramDocumentBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); <DeepExtract> File path = getPath(FeatureEnumerate.PHOG.getText()); log.debug("creating indexed path " + path.getAbsolutePath()); IndexWriter iw = new IndexWriter(FSDirectory.open(path), conf); try { Document document = DocumentBuilderFactory.getPHOGDocumentBuilder().createDocument(image, picture_id.toString()); iw.addDocument(document); } catch (Exception e) { System.err.println("Error reading image or indexing it."); e.printStackTrace(); } iw.close(); </DeepExtract> }
flipper-reverse-image-search
positive
1,094
public boolean equalString(String str, int len) { String other = str.length() == len ? str : str.substring(0, len); return (other instanceof AbstractSymbol) && ((AbstractSymbol) other).index == this.index; }
public boolean equalString(String str, int len) { String other = str.length() == len ? str : str.substring(0, len); <DeepExtract> return (other instanceof AbstractSymbol) && ((AbstractSymbol) other).index == this.index; </DeepExtract> }
Compiler
positive
1,095
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { mEditText.setError(""); }
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { <DeepExtract> mEditText.setError(""); </DeepExtract> }
igniter
positive
1,096
public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) { if (useFieldNames && fieldName != null) { buffer.append(fieldName); buffer.append(fieldNameValueSeparator); } if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldSeparator(buffer); }
public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) { if (useFieldNames && fieldName != null) { buffer.append(fieldName); buffer.append(fieldNameValueSeparator); } if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } <DeepExtract> appendFieldSeparator(buffer); </DeepExtract> }
xposed-art
positive
1,097
@PostConstruct public void init() { connectionManagerFactory = new DefaultApacheHttpClientConnectionManagerFactory(); return connectionManagerFactory.newConnectionManager(false, 200, 20, -1, TimeUnit.MILLISECONDS, null); httpClientFactory = new DefaultApacheHttpClientFactory(HttpClientBuilder.create()); final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(-1).setSocketTimeout(10000).setConnectTimeout(2000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); return httpClientFactory.createBuilder().setDefaultRequestConfig(requestConfig).setConnectionManager(this.connectionManager).disableRedirectHandling().build(); }
@PostConstruct public void init() { connectionManagerFactory = new DefaultApacheHttpClientConnectionManagerFactory(); return connectionManagerFactory.newConnectionManager(false, 200, 20, -1, TimeUnit.MILLISECONDS, null); httpClientFactory = new DefaultApacheHttpClientFactory(HttpClientBuilder.create()); <DeepExtract> final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(-1).setSocketTimeout(10000).setConnectTimeout(2000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); return httpClientFactory.createBuilder().setDefaultRequestConfig(requestConfig).setConnectionManager(this.connectionManager).disableRedirectHandling().build(); </DeepExtract> }
springcloud-vip-2
positive
1,098
@Override public LineStringBuilder pointLatLon(double latitude, double longitude) { shapes.add(ShapeFactoryImpl.this.pointLatLon(latitude, longitude)); return this; return this; }
@Override public LineStringBuilder pointLatLon(double latitude, double longitude) { <DeepExtract> shapes.add(ShapeFactoryImpl.this.pointLatLon(latitude, longitude)); return this; </DeepExtract> return this; }
spatial4j
positive
1,099
@Override protected void handleDefaultAction(Intent intent, int flags, int startId) { if (mPrefs.getLong(StopwatchFragment.KEY_START_TIME, 0) == 0) { mCurrentLap = new Lap(); mUpdateHandler.asyncInsert(mCurrentLap); } clearActions(getNoteId()); addAction(ACTION_ADD_LAP, R.drawable.ic_add_lap_24dp, getString(R.string.lap), getNoteId()); addStartPauseAction(true, getNoteId()); addStopAction(getNoteId()); quitCurrentThread(getNoteId()); if (true) { long startTime = mPrefs.getLong(StopwatchFragment.KEY_START_TIME, SystemClock.elapsedRealtime()); startNewThread(getNoteId(), startTime); } }
@Override protected void handleDefaultAction(Intent intent, int flags, int startId) { if (mPrefs.getLong(StopwatchFragment.KEY_START_TIME, 0) == 0) { mCurrentLap = new Lap(); mUpdateHandler.asyncInsert(mCurrentLap); } <DeepExtract> clearActions(getNoteId()); addAction(ACTION_ADD_LAP, R.drawable.ic_add_lap_24dp, getString(R.string.lap), getNoteId()); addStartPauseAction(true, getNoteId()); addStopAction(getNoteId()); quitCurrentThread(getNoteId()); if (true) { long startTime = mPrefs.getLong(StopwatchFragment.KEY_START_TIME, SystemClock.elapsedRealtime()); startNewThread(getNoteId(), startTime); } </DeepExtract> }
ClockPlus
positive
1,101
private int choosePivot(int[][] points, int l, int r) { int pivot = (int) (Math.random() * (r - l + 1)) + l; int[] temp = points[r]; points[r] = points[pivot]; points[pivot] = temp; int i = l; for (int j = l; j < r; j++) { if (compare(points[j], points[r]) < 0) { swap(points, i, j); i++; } } int[] temp = points[i]; points[i] = points[r]; points[r] = temp; return i; }
private int choosePivot(int[][] points, int l, int r) { int pivot = (int) (Math.random() * (r - l + 1)) + l; int[] temp = points[r]; points[r] = points[pivot]; points[pivot] = temp; int i = l; for (int j = l; j < r; j++) { if (compare(points[j], points[r]) < 0) { swap(points, i, j); i++; } } <DeepExtract> int[] temp = points[i]; points[i] = points[r]; points[r] = temp; </DeepExtract> return i; }
computer-science
positive
1,102
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!placedBall) { placeBall(); } Paint paint = new Paint(); if (value == min) { if (bitmap == null) { bitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888); } Canvas temp = new Canvas(bitmap); paint.setColor(Color.parseColor("#B0B0B0")); paint.setStrokeWidth(Utils.dpToPx(2, getResources())); temp.drawLine(getHeight() / 2, getHeight() / 2, getWidth() - getHeight() / 2, getHeight() / 2, paint); Paint transparentPaint = new Paint(); transparentPaint.setColor(getResources().getColor(android.R.color.transparent)); transparentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); temp.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2, ViewHelper.getY(ball) + ball.getHeight() / 2, ball.getWidth() / 2, transparentPaint); } else { paint.setColor(Color.parseColor("#B0B0B0")); paint.setStrokeWidth(Utils.dpToPx(2, getResources())); canvas.drawLine(getHeight() / 2, getHeight() / 2, getWidth() - getHeight() / 2, getHeight() / 2, paint); paint.setColor(backgroundColor); float division = (ball.xFin - ball.xIni) / (max - min); int value = this.value - min; canvas.drawLine(getHeight() / 2, getHeight() / 2, value * division + getHeight() / 2, getHeight() / 2, paint); } if (press && !showNumberIndicator) { paint.setColor(backgroundColor); paint.setAntiAlias(true); canvas.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2, getHeight() / 2, getHeight() / 3, paint); } ball.invalidate(); super.invalidate(); }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!placedBall) { placeBall(); } Paint paint = new Paint(); if (value == min) { if (bitmap == null) { bitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888); } Canvas temp = new Canvas(bitmap); paint.setColor(Color.parseColor("#B0B0B0")); paint.setStrokeWidth(Utils.dpToPx(2, getResources())); temp.drawLine(getHeight() / 2, getHeight() / 2, getWidth() - getHeight() / 2, getHeight() / 2, paint); Paint transparentPaint = new Paint(); transparentPaint.setColor(getResources().getColor(android.R.color.transparent)); transparentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); temp.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2, ViewHelper.getY(ball) + ball.getHeight() / 2, ball.getWidth() / 2, transparentPaint); } else { paint.setColor(Color.parseColor("#B0B0B0")); paint.setStrokeWidth(Utils.dpToPx(2, getResources())); canvas.drawLine(getHeight() / 2, getHeight() / 2, getWidth() - getHeight() / 2, getHeight() / 2, paint); paint.setColor(backgroundColor); float division = (ball.xFin - ball.xIni) / (max - min); int value = this.value - min; canvas.drawLine(getHeight() / 2, getHeight() / 2, value * division + getHeight() / 2, getHeight() / 2, paint); } if (press && !showNumberIndicator) { paint.setColor(backgroundColor); paint.setAntiAlias(true); canvas.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2, getHeight() / 2, getHeight() / 3, paint); } <DeepExtract> ball.invalidate(); super.invalidate(); </DeepExtract> }
meiShi
positive
1,103
@Override public void handleFailure(String message) { iconLoading.setVisibility(View.GONE); iconEmpty.setVisibility(View.VISIBLE); tvLoadFailed.setText(message); }
@Override public void handleFailure(String message) { <DeepExtract> iconLoading.setVisibility(View.GONE); iconEmpty.setVisibility(View.VISIBLE); tvLoadFailed.setText(message); </DeepExtract> }
LNTUOnline-Android
positive
1,104
@Deprecated public void setClientSecret(String clientSecret) { properties.setProperty("clientSecret", clientSecret); }
@Deprecated public void setClientSecret(String clientSecret) { <DeepExtract> properties.setProperty("clientSecret", clientSecret); </DeepExtract> }
FuelSDK-Java
positive
1,105
public void onResume() { activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); cancel(); inactivityTask = new InactivityAsyncTask(); taskExec.execute(inactivityTask); }
public void onResume() { activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); <DeepExtract> cancel(); inactivityTask = new InactivityAsyncTask(); taskExec.execute(inactivityTask); </DeepExtract> }
PeerDeviceNet_Src
positive
1,106
public void btnMapClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("geo:24.915982,67.092849")); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } }
public void btnMapClick(View v) { <DeepExtract> Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("geo:24.915982,67.092849")); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } </DeepExtract> }
ssuet-android-adv-mar17
positive
1,107
@Override public T top() { if (size == 0) { throw new EmptyStackException(); } return (T) elements[size - 1]; }
@Override public T top() { <DeepExtract> if (size == 0) { throw new EmptyStackException(); } return (T) elements[size - 1]; </DeepExtract> }
spork
positive
1,108
@Override public void showLoading() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.cancel(); } mProgressDialog = CommonUtils.showLoadingDialog(this.getContext()); }
@Override public void showLoading() { <DeepExtract> if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.cancel(); } </DeepExtract> mProgressDialog = CommonUtils.showLoadingDialog(this.getContext()); }
android-mvp-interactor-architecture
positive
1,109
public void alignToByte() throws IOException { bitBuffer = (bitBuffer << (64 - bitBufferLen) % 8) | (0 & ((1L << (64 - bitBufferLen) % 8) - 1)); bitBufferLen += (64 - bitBufferLen) % 8; while (bitBufferLen >= 8) { bitBufferLen -= 8; int b = (int) (bitBuffer >>> bitBufferLen) & 0xFF; out.write(b); crc8 ^= b; crc16 ^= b << 8; for (int i = 0; i < 8; i++) { crc8 = (crc8 << 1) ^ ((crc8 >>> 7) * 0x107); crc16 = (crc16 << 1) ^ ((crc16 >>> 15) * 0x18005); } } }
public void alignToByte() throws IOException { <DeepExtract> bitBuffer = (bitBuffer << (64 - bitBufferLen) % 8) | (0 & ((1L << (64 - bitBufferLen) % 8) - 1)); bitBufferLen += (64 - bitBufferLen) % 8; while (bitBufferLen >= 8) { bitBufferLen -= 8; int b = (int) (bitBuffer >>> bitBufferLen) & 0xFF; out.write(b); crc8 ^= b; crc16 ^= b << 8; for (int i = 0; i < 8; i++) { crc8 = (crc8 << 1) ^ ((crc8 >>> 7) * 0x107); crc16 = (crc16 << 1) ^ ((crc16 >>> 15) * 0x18005); } } </DeepExtract> }
Nayuki-web-published-code
positive
1,110
@Override public void onChanged() { super.onChanged(); int w = this.getWidth(); int h = this.getHeight(); if (this.mBitmapRes > -1) { Drawable drawable = this.getResources().getDrawable(this.mBitmapRes); if (drawable instanceof BitmapDrawable) { this.mBitmap = ((BitmapDrawable) drawable).getBitmap(); } else { this.mBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888); Canvas canvas = new Canvas(this.mBitmap); drawable.setBounds(this.getLeft(), this.getTop(), this.getRight(), this.getBottom()); drawable.draw(canvas); } } if (this.mBitmap != null && w != 0 && h != 0) { float count = 1.0F; if (this.getAdapter() != null && this.getAdapter().getCount() > 0) { count = (float) this.getAdapter().getCount(); } int imgWidth = this.mBitmap.getWidth(); int imgHeight = this.mBitmap.getHeight(); float ratio = (float) imgWidth / (float) imgHeight; float width = (float) h * ratio; float height = (float) h; this.mBackgroundOriginalRect = new Rect(0, 0, imgWidth, imgHeight); this.mBackgroundNewRect = new RectF(0.0F, 0.0F, width, height); Rect sizeRect = new Rect(0, 0, w * (int) ratio, h); this.fraction = (float) sizeRect.width() / ((float) w * count); } ZBackgroundViewPager.this.invalidate(); ZBackgroundViewPager.this.requestLayout(); }
@Override public void onChanged() { super.onChanged(); <DeepExtract> int w = this.getWidth(); int h = this.getHeight(); if (this.mBitmapRes > -1) { Drawable drawable = this.getResources().getDrawable(this.mBitmapRes); if (drawable instanceof BitmapDrawable) { this.mBitmap = ((BitmapDrawable) drawable).getBitmap(); } else { this.mBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888); Canvas canvas = new Canvas(this.mBitmap); drawable.setBounds(this.getLeft(), this.getTop(), this.getRight(), this.getBottom()); drawable.draw(canvas); } } if (this.mBitmap != null && w != 0 && h != 0) { float count = 1.0F; if (this.getAdapter() != null && this.getAdapter().getCount() > 0) { count = (float) this.getAdapter().getCount(); } int imgWidth = this.mBitmap.getWidth(); int imgHeight = this.mBitmap.getHeight(); float ratio = (float) imgWidth / (float) imgHeight; float width = (float) h * ratio; float height = (float) h; this.mBackgroundOriginalRect = new Rect(0, 0, imgWidth, imgHeight); this.mBackgroundNewRect = new RectF(0.0F, 0.0F, width, height); Rect sizeRect = new Rect(0, 0, w * (int) ratio, h); this.fraction = (float) sizeRect.width() / ((float) w * count); } </DeepExtract> ZBackgroundViewPager.this.invalidate(); ZBackgroundViewPager.this.requestLayout(); }
ZUILib
positive
1,112
public HttpRequest acceptCharset(final String acceptCharset) { getConnection().setRequestProperty(HEADER_ACCEPT_CHARSET, acceptCharset); return this; }
public HttpRequest acceptCharset(final String acceptCharset) { <DeepExtract> getConnection().setRequestProperty(HEADER_ACCEPT_CHARSET, acceptCharset); return this; </DeepExtract> }
nanoleaf-aurora
positive
1,113
public void add(E value) { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (next == 0) { LinkedList2.this.add(value); expectedModCount++; return; } lock.writeLock().lock(); try { Entry<E> e = new Entry<E>(prev, next, value); long recid = db.insert(e, entrySerializer, false); if (prev != 0) { Entry<E> p = db.fetch(prev, entrySerializer); if (p.next != next) throw new Error(); p.next = recid; db.update(prev, p, entrySerializer); } Entry<E> n = fetch(next); if (n.prev != prev) throw new Error(); n.prev = recid; db.update(next, n, entrySerializer); Root r = getRoot(); r.size++; db.update(rootRecid, r, ROOT_SERIALIZER); expectedModCount++; modCount++; prev = recid; } catch (IOException e) { throw new IOError(e); } finally { lock.writeLock().unlock(); } }
public void add(E value) { <DeepExtract> if (modCount != expectedModCount) throw new ConcurrentModificationException(); </DeepExtract> if (next == 0) { LinkedList2.this.add(value); expectedModCount++; return; } lock.writeLock().lock(); try { Entry<E> e = new Entry<E>(prev, next, value); long recid = db.insert(e, entrySerializer, false); if (prev != 0) { Entry<E> p = db.fetch(prev, entrySerializer); if (p.next != next) throw new Error(); p.next = recid; db.update(prev, p, entrySerializer); } Entry<E> n = fetch(next); if (n.prev != prev) throw new Error(); n.prev = recid; db.update(next, n, entrySerializer); Root r = getRoot(); r.size++; db.update(rootRecid, r, ROOT_SERIALIZER); expectedModCount++; modCount++; prev = recid; } catch (IOException e) { throw new IOError(e); } finally { lock.writeLock().unlock(); } }
JDBM3
positive
1,115
@Test public void hget() throws Exception { String key = keyPrefix + "_HGET"; conn.createStatement().execute("HSET " + key + " field1 \"foo\""); assertEquals("foo", executeSingleStringResult("HGET " + key + " field1")); assertNull(executeSingleStringResult("HGET " + key + " field2")); execute("DEL " + key); }
@Test public void hget() throws Exception { String key = keyPrefix + "_HGET"; conn.createStatement().execute("HSET " + key + " field1 \"foo\""); assertEquals("foo", executeSingleStringResult("HGET " + key + " field1")); assertNull(executeSingleStringResult("HGET " + key + " field2")); <DeepExtract> execute("DEL " + key); </DeepExtract> }
jdbc-redis
positive
1,116
private void run(String[] args) throws DatabaseException { for (int i = 0; i < args.length; ++i) { if (args[i].startsWith("-")) { switch(args[i].charAt(1)) { case 'h': myDbEnvPath = new File(args[++i]); break; case 's': locateItem = args[++i]; break; default: usage(); } } } myDbEnv.setup(myDbEnvPath, true); da = new DataAccessor(myDbEnv.getEntityStore()); if (locateItem != null) { showItem(); } else { showAllInventory(); } }
private void run(String[] args) throws DatabaseException { <DeepExtract> for (int i = 0; i < args.length; ++i) { if (args[i].startsWith("-")) { switch(args[i].charAt(1)) { case 'h': myDbEnvPath = new File(args[++i]); break; case 's': locateItem = args[++i]; break; default: usage(); } } } </DeepExtract> myDbEnv.setup(myDbEnvPath, true); da = new DataAccessor(myDbEnv.getEntityStore()); if (locateItem != null) { showItem(); } else { showAllInventory(); } }
berkeley-db
positive
1,117
private int getParity() { int x, counter = 0; return Integer.parseInt(dataValue, 16); String s = Integer.toBinaryString(x); char[] c = s.toCharArray(); for (int i = 0; i < s.length(); i++) { if (c[i] == '1') { counter++; } } if (counter % 2 == 0) { return 1; } else { return 0; } }
private int getParity() { int x, counter = 0; <DeepExtract> return Integer.parseInt(dataValue, 16); </DeepExtract> String s = Integer.toBinaryString(x); char[] c = s.toCharArray(); for (int i = 0; i < s.length(); i++) { if (c[i] == '1') { counter++; } } if (counter % 2 == 0) { return 1; } else { return 0; } }
8085
positive
1,118
public static String md5(String string) { byte[] hash = null; try { hash = string.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Huh,UTF-8 should be supported?", e); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(hash, 0, hash.length); byte[] md5bytes = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < md5bytes.length; i++) { String hex = Integer.toHexString(0xff & md5bytes[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
public static String md5(String string) { byte[] hash = null; try { hash = string.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Huh,UTF-8 should be supported?", e); } <DeepExtract> try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(hash, 0, hash.length); byte[] md5bytes = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < md5bytes.length; i++) { String hex = Integer.toHexString(0xff & md5bytes[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } </DeepExtract> }
LoveTalkClient
positive
1,119
public void addNumber(int num) { if (this.maxHeap.isEmpty()) { this.maxHeap.add(num); return; } if (this.maxHeap.peek() >= num) { this.maxHeap.add(num); } else { if (this.minHeap.isEmpty()) { this.minHeap.add(num); return; } if (this.minHeap.peek() > num) { this.maxHeap.add(num); } else { this.minHeap.add(num); } } if (this.maxHeap.size() == this.minHeap.size() + 2) { this.minHeap.add(this.maxHeap.poll()); } if (this.minHeap.size() == this.maxHeap.size() + 2) { this.maxHeap.add(this.minHeap.poll()); } }
public void addNumber(int num) { if (this.maxHeap.isEmpty()) { this.maxHeap.add(num); return; } if (this.maxHeap.peek() >= num) { this.maxHeap.add(num); } else { if (this.minHeap.isEmpty()) { this.minHeap.add(num); return; } if (this.minHeap.peek() > num) { this.maxHeap.add(num); } else { this.minHeap.add(num); } } <DeepExtract> if (this.maxHeap.size() == this.minHeap.size() + 2) { this.minHeap.add(this.maxHeap.poll()); } if (this.minHeap.size() == this.maxHeap.size() + 2) { this.maxHeap.add(this.minHeap.poll()); } </DeepExtract> }
nowcoder-zuo
positive
1,120
public HPacket appendUShort(int ushort) { isEdited = true; packetInBytes = Arrays.copyOf(packetInBytes, packetInBytes.length + 2); ByteBuffer byteBuffer = ByteBuffer.allocate(4).putInt(ushort); for (int j = 2; j < 4; j++) { packetInBytes[packetInBytes.length - 4 + j] = byteBuffer.array()[j]; } boolean remember = isEdited; replaceInt(0, packetInBytes.length - 4); isEdited = remember; return this; }
public HPacket appendUShort(int ushort) { isEdited = true; packetInBytes = Arrays.copyOf(packetInBytes, packetInBytes.length + 2); ByteBuffer byteBuffer = ByteBuffer.allocate(4).putInt(ushort); for (int j = 2; j < 4; j++) { packetInBytes[packetInBytes.length - 4 + j] = byteBuffer.array()[j]; } <DeepExtract> boolean remember = isEdited; replaceInt(0, packetInBytes.length - 4); isEdited = remember; </DeepExtract> return this; }
G-Earth
positive
1,122
@BeforeTest public void configuring() { String translationDir = AbstractVectorSpaceTest.class.getClassLoader().getResource("translations/pt").getPath(); return new LuceneTranslator(translationDir); String vsmDir = AbstractVectorSpaceTest.class.getClassLoader().getResource("models/annoy/dense/en/simple").getPath(); return new AnnoyVectorSpace(vsmDir); analyzer = vectorSpace.getAnalyzer(); }
@BeforeTest public void configuring() { String translationDir = AbstractVectorSpaceTest.class.getClassLoader().getResource("translations/pt").getPath(); return new LuceneTranslator(translationDir); <DeepExtract> String vsmDir = AbstractVectorSpaceTest.class.getClassLoader().getResource("models/annoy/dense/en/simple").getPath(); return new AnnoyVectorSpace(vsmDir); </DeepExtract> analyzer = vectorSpace.getAnalyzer(); }
Indra
positive
1,125
public BackendConnection getConnection(String schema, boolean autoCommit, Object attachment) throws Exception { BackendConnection con = null; if (schema != null && !schema.equals(this.database)) { throw new RuntimeException("invalid param ,connection request db is :" + schema + " and datanode db is " + this.database); } if (!dbPool.isInitSuccess()) { dbPool.init(dbPool.activedIndex); } if (dbPool.isInitSuccess()) { con = dbPool.getSource().getConnection(schema, autoCommit, attachment); } else { throw new IllegalArgumentException("Invalid DataSource:" + dbPool.getActivedIndex()); } return con; }
public BackendConnection getConnection(String schema, boolean autoCommit, Object attachment) throws Exception { BackendConnection con = null; <DeepExtract> if (schema != null && !schema.equals(this.database)) { throw new RuntimeException("invalid param ,connection request db is :" + schema + " and datanode db is " + this.database); } if (!dbPool.isInitSuccess()) { dbPool.init(dbPool.activedIndex); } </DeepExtract> if (dbPool.isInitSuccess()) { con = dbPool.getSource().getConnection(schema, autoCommit, attachment); } else { throw new IllegalArgumentException("Invalid DataSource:" + dbPool.getActivedIndex()); } return con; }
Mycat-NIO
positive
1,127
@java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.Long> getLongValues() { return internalGetLongValues().getMap(); }
@java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.Long> getLongValues() { <DeepExtract> return internalGetLongValues().getMap(); </DeepExtract> }
game-server
positive
1,128
@Override public WaterMarkSegment clone() { WaterMarkSegment waterMarkSegment = new WaterMarkSegment(); mBitmap = mBitmap; mDstRect = new RectF(mDstRect); mAlpha = mAlpha; synchronized (this) { mBitmapInfo = null; } return waterMarkSegment; }
@Override public WaterMarkSegment clone() { WaterMarkSegment waterMarkSegment = new WaterMarkSegment(); <DeepExtract> mBitmap = mBitmap; mDstRect = new RectF(mDstRect); mAlpha = mAlpha; synchronized (this) { mBitmapInfo = null; } </DeepExtract> return waterMarkSegment; }
PhotoMovie
positive
1,129
@Override public void onBlockExploded(World world, int x, int y, int z, Explosion explosion) { TileEntity tileEntity = world.getTileEntity(x, y, z); if (tileEntity instanceof IBlockNotifier) { ((IBlockNotifier) tileEntity).onBlockRemoval(world, x, y, z); } super.onBlockExploded(world, x, y, z, explosion); }
@Override public void onBlockExploded(World world, int x, int y, int z, Explosion explosion) { <DeepExtract> TileEntity tileEntity = world.getTileEntity(x, y, z); if (tileEntity instanceof IBlockNotifier) { ((IBlockNotifier) tileEntity).onBlockRemoval(world, x, y, z); } </DeepExtract> super.onBlockExploded(world, x, y, z, explosion); }
Dimensional-Pockets
positive
1,130
@Override protected String doInBackground(Context... params) { parent = params[0]; _dev = new USBSerial(); try { List<String> res = RootTools.sendShell("dmesg | grep ttyUSB | tail -n 1 | awk '{print $NF}'", 0); ttyUSB_name = res.get(0); } catch (Exception e) { return ""; } if (!_dev.openPort("/dev/" + ttyUSB_name)) return "FAIL"; if (VERBOSE) Log.d("ZigBeeInit", "opened device, now waiting for sequence"); byte[] readSeq = new byte[initialized_sequence.length]; MainInterface.sendThreadMessage(_parent, MainInterface.ThreadMessages.CANCEL_PROGRESS_DIALOG); MainInterface.sendProgressDialogRequest(_parent, "Press the ZigBee reset button..."); while (!checkInitSeq(readSeq)) { for (int i = 0; i < initialized_sequence.length - 1; i++) readSeq[i] = readSeq[i + 1]; readSeq[initialized_sequence.length - 1] = _dev.getByte(); } if (VERBOSE) Log.d("ZigBeeInit", "received the initialization sequence!"); if (!_dev.closePort()) MainInterface.sendToastRequest(_parent, "Failed to initialize ZigBee device"); return "OK"; }
@Override protected String doInBackground(Context... params) { parent = params[0]; _dev = new USBSerial(); try { List<String> res = RootTools.sendShell("dmesg | grep ttyUSB | tail -n 1 | awk '{print $NF}'", 0); ttyUSB_name = res.get(0); } catch (Exception e) { return ""; } if (!_dev.openPort("/dev/" + ttyUSB_name)) return "FAIL"; if (VERBOSE) Log.d("ZigBeeInit", "opened device, now waiting for sequence"); byte[] readSeq = new byte[initialized_sequence.length]; MainInterface.sendThreadMessage(_parent, MainInterface.ThreadMessages.CANCEL_PROGRESS_DIALOG); MainInterface.sendProgressDialogRequest(_parent, "Press the ZigBee reset button..."); while (!checkInitSeq(readSeq)) { for (int i = 0; i < initialized_sequence.length - 1; i++) readSeq[i] = readSeq[i + 1]; readSeq[initialized_sequence.length - 1] = _dev.getByte(); } <DeepExtract> if (VERBOSE) Log.d("ZigBeeInit", "received the initialization sequence!"); </DeepExtract> if (!_dev.closePort()) MainInterface.sendToastRequest(_parent, "Failed to initialize ZigBee device"); return "OK"; }
android-wmon
positive
1,131
protected void setVersionName(String versionName) { if (isDebug) { Log.d(TAG, "setVersionName invoked!"); } final String curVer = versionName; PluginWrapper.runOnMainThread(new Runnable() { @Override public void run() { try { FlurryAgent.setVersionName(curVer); } catch (Exception e) { LogE("Exception in setVersionName", e); } } }); }
protected void setVersionName(String versionName) { <DeepExtract> if (isDebug) { Log.d(TAG, "setVersionName invoked!"); } </DeepExtract> final String curVer = versionName; PluginWrapper.runOnMainThread(new Runnable() { @Override public void run() { try { FlurryAgent.setVersionName(curVer); } catch (Exception e) { LogE("Exception in setVersionName", e); } } }); }
cocos2dx-3.2-qt
positive
1,132
@Test public void getLists_byScreenName() { mockServer.expect(requestTo("https://api.twitter.com/1.1/lists/list.json?screen_name=habuma")).andExpect(method(GET)).andRespond(withSuccess(jsonResource("multiple-list"), APPLICATION_JSON)); assertEquals(2, twitter.listOperations().getLists("habuma").size()); UserList list1 = twitter.listOperations().getLists("habuma").get(0); assertEquals(40842137, list1.getId()); assertEquals("forFun2", list1.getName()); assertEquals("@habuma/forfun2", list1.getFullName()); assertEquals("forfun2", list1.getSlug()); assertEquals("Just for fun, too", list1.getDescription()); assertEquals(3, list1.getMemberCount()); assertEquals(0, list1.getSubscriberCount()); assertEquals("/habuma/forfun2", list1.getUriPath()); assertTrue(list1.isPublic()); UserList list2 = twitter.listOperations().getLists("habuma").get(1); assertEquals(40841803, list2.getId()); assertEquals("forFun", list2.getName()); assertEquals("@habuma/forfun", list2.getFullName()); assertEquals("forfun", list2.getSlug()); assertEquals("Just for fun", list2.getDescription()); assertEquals(22, list2.getMemberCount()); assertEquals(100, list2.getSubscriberCount()); assertEquals("/habuma/forfun", list2.getUriPath()); assertFalse(list2.isPublic()); }
@Test public void getLists_byScreenName() { mockServer.expect(requestTo("https://api.twitter.com/1.1/lists/list.json?screen_name=habuma")).andExpect(method(GET)).andRespond(withSuccess(jsonResource("multiple-list"), APPLICATION_JSON)); <DeepExtract> assertEquals(2, twitter.listOperations().getLists("habuma").size()); UserList list1 = twitter.listOperations().getLists("habuma").get(0); assertEquals(40842137, list1.getId()); assertEquals("forFun2", list1.getName()); assertEquals("@habuma/forfun2", list1.getFullName()); assertEquals("forfun2", list1.getSlug()); assertEquals("Just for fun, too", list1.getDescription()); assertEquals(3, list1.getMemberCount()); assertEquals(0, list1.getSubscriberCount()); assertEquals("/habuma/forfun2", list1.getUriPath()); assertTrue(list1.isPublic()); UserList list2 = twitter.listOperations().getLists("habuma").get(1); assertEquals(40841803, list2.getId()); assertEquals("forFun", list2.getName()); assertEquals("@habuma/forfun", list2.getFullName()); assertEquals("forfun", list2.getSlug()); assertEquals("Just for fun", list2.getDescription()); assertEquals(22, list2.getMemberCount()); assertEquals(100, list2.getSubscriberCount()); assertEquals("/habuma/forfun", list2.getUriPath()); assertFalse(list2.isPublic()); </DeepExtract> }
spring-social-twitter
positive
1,133
@Override public void openFileChooser(ValueCallback valueCallback, String acceptType) { Log.i(TAG, "openFileChooser>3.0"); if (valueCallback == null) { return; } Activity mActivity = this.mActivityWeakReference.get(); if (mActivity == null || mActivity.isFinishing()) { valueCallback.onReceiveValue(new Object()); return; } AgentWebUtils.showFileChooserCompat(mActivity, mWebView, null, null, this.mPermissionInterceptor, valueCallback, acceptType, null); }
@Override public void openFileChooser(ValueCallback valueCallback, String acceptType) { Log.i(TAG, "openFileChooser>3.0"); <DeepExtract> if (valueCallback == null) { return; } Activity mActivity = this.mActivityWeakReference.get(); if (mActivity == null || mActivity.isFinishing()) { valueCallback.onReceiveValue(new Object()); return; } AgentWebUtils.showFileChooserCompat(mActivity, mWebView, null, null, this.mPermissionInterceptor, valueCallback, acceptType, null); </DeepExtract> }
AgentWeb
positive
1,134
public void judgeCard(User judge, int cardId) throws BaseCahHandler.CahException { synchronized (judgeLock) { Player judgePlayer = getPlayerForUser(judge); if (getJudge() != judgePlayer) throw new BaseCahHandler.CahException(Consts.ErrorCode.NOT_JUDGE); else if (state != Consts.GameState.JUDGING) throw new BaseCahHandler.CahException(Consts.ErrorCode.NOT_YOUR_TURN); if (judgePlayer != null) judgePlayer.resetSkipCount(); winner = playedCards.getPlayerForId(cardId); if (winner == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.INVALID_CARD); winner.increaseScore(); } state = Consts.GameState.ROUND_OVER; boolean won; if (winner.getScore() >= options.scoreGoal) { if (options.winBy == 0) won = true; int highestScore = -1; synchronized (roundPlayers) { for (Player p : roundPlayers) { if (winner.equals(p)) continue; if (p.getScore() > highestScore) highestScore = p.getScore(); } } won = highestScore == -1 || winner.getScore() >= highestScore + options.winBy; } else { won = false; } EventWrapper ev = new EventWrapper(this, Consts.Event.GAME_STATE_CHANGE); ev.add(Consts.GeneralGameData.STATE, Consts.GameState.ROUND_OVER.toString()); ev.add(Consts.OngoingGameData.ROUND_WINNER, winner.getUser().getNickname()); ev.add(Consts.OngoingGameData.WILL_STOP, won); ev.add(Consts.OngoingGameData.WINNING_CARD, Utils.joinCardIds(playedCards.getCards(winner), ",")); ev.add(Consts.OngoingGameData.INTERMISSION, ROUND_INTERMISSION); connectedUsers.broadcastToList(playersToUsers(), QueuedMessage.MessageType.GAME_EVENT, ev); if (winner == null) return; EventWrapper ev = new EventWrapper(this, Consts.Event.GAME_PLAYER_INFO_CHANGE); ev.add(Consts.GamePlayerInfo.INFO, getPlayerInfoJson(winner)); broadcastToPlayers(QueuedMessage.MessageType.GAME_PLAYER_EVENT, ev); synchronized (roundTimerLock) { if (won) { rescheduleTimer(new SafeTimerTask() { @Override public void process() { resetState(false); } }, ROUND_INTERMISSION); } else { rescheduleTimer(new SafeTimerTask() { @Override public void process() { startNextRound(); } }, ROUND_INTERMISSION); } } Map<String, List<WhiteCard>> cardsBySessionId = new HashMap<>(); playedCards.cardsByUser().forEach((key, value) -> cardsBySessionId.put(key.getSessionId(), value)); }
public void judgeCard(User judge, int cardId) throws BaseCahHandler.CahException { synchronized (judgeLock) { Player judgePlayer = getPlayerForUser(judge); if (getJudge() != judgePlayer) throw new BaseCahHandler.CahException(Consts.ErrorCode.NOT_JUDGE); else if (state != Consts.GameState.JUDGING) throw new BaseCahHandler.CahException(Consts.ErrorCode.NOT_YOUR_TURN); if (judgePlayer != null) judgePlayer.resetSkipCount(); winner = playedCards.getPlayerForId(cardId); if (winner == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.INVALID_CARD); winner.increaseScore(); } state = Consts.GameState.ROUND_OVER; boolean won; if (winner.getScore() >= options.scoreGoal) { if (options.winBy == 0) won = true; int highestScore = -1; synchronized (roundPlayers) { for (Player p : roundPlayers) { if (winner.equals(p)) continue; if (p.getScore() > highestScore) highestScore = p.getScore(); } } won = highestScore == -1 || winner.getScore() >= highestScore + options.winBy; } else { won = false; } EventWrapper ev = new EventWrapper(this, Consts.Event.GAME_STATE_CHANGE); ev.add(Consts.GeneralGameData.STATE, Consts.GameState.ROUND_OVER.toString()); ev.add(Consts.OngoingGameData.ROUND_WINNER, winner.getUser().getNickname()); ev.add(Consts.OngoingGameData.WILL_STOP, won); ev.add(Consts.OngoingGameData.WINNING_CARD, Utils.joinCardIds(playedCards.getCards(winner), ",")); ev.add(Consts.OngoingGameData.INTERMISSION, ROUND_INTERMISSION); connectedUsers.broadcastToList(playersToUsers(), QueuedMessage.MessageType.GAME_EVENT, ev); <DeepExtract> if (winner == null) return; EventWrapper ev = new EventWrapper(this, Consts.Event.GAME_PLAYER_INFO_CHANGE); ev.add(Consts.GamePlayerInfo.INFO, getPlayerInfoJson(winner)); broadcastToPlayers(QueuedMessage.MessageType.GAME_PLAYER_EVENT, ev); </DeepExtract> synchronized (roundTimerLock) { if (won) { rescheduleTimer(new SafeTimerTask() { @Override public void process() { resetState(false); } }, ROUND_INTERMISSION); } else { rescheduleTimer(new SafeTimerTask() { @Override public void process() { startNextRound(); } }, ROUND_INTERMISSION); } } Map<String, List<WhiteCard>> cardsBySessionId = new HashMap<>(); playedCards.cardsByUser().forEach((key, value) -> cardsBySessionId.put(key.getSessionId(), value)); }
PYX-Reloaded
positive
1,135
@Test public void hasImeAction_withInteger_addsCorrectMatcher() { notCompletable.hasImeAction(1); assertThat(cortado.matchers).hasSize(1); Utils.assertThat(cortado.matchers.get(0)).isEqualTo(ViewMatchers.hasImeAction(1)); }
@Test public void hasImeAction_withInteger_addsCorrectMatcher() { notCompletable.hasImeAction(1); <DeepExtract> assertThat(cortado.matchers).hasSize(1); Utils.assertThat(cortado.matchers.get(0)).isEqualTo(ViewMatchers.hasImeAction(1)); </DeepExtract> }
cortado
positive
1,136
public String rightToString() { String sRegle = null; int iIndiceItem = 0; Item item = null; boolean bItemsQualitatifsPresents = false; boolean bPremierItemInscrit = false; int iIndiceDisjonction = 0; int iNombreDisjonctions = 0; int iNombreItemsQuantitatifs = 0; int iNombreItems = 0; Item[] tItemsRegle = null; sRegle = new String(""); iNombreItems = m_iNombreItemsDroite; tItemsRegle = m_tItemsDroite; int iPosition = 0; int iCompteur = 0; iCompteur = 0; for (iPosition = 0; iPosition < m_iNombreItemsDroite; iPosition++) if (m_tItemsDroite[iPosition].m_iTypeItem == Item.ITEM_TYPE_QUANTITATIF) iCompteur++; return iCompteur; iNombreDisjonctions = m_iNombreDisjonctionsDroiteValides; bPremierItemInscrit = false; for (iIndiceItem = 0; iIndiceItem < iNombreItems; iIndiceItem++) { item = tItemsRegle[iIndiceItem]; if (item.m_iTypeItem == Item.ITEM_TYPE_QUALITATIF) { if (bPremierItemInscrit) sRegle += " AND "; sRegle += ((ItemQualitative) item).toString(); bPremierItemInscrit = true; } } bItemsQualitatifsPresents = bPremierItemInscrit; if (iNombreItemsQuantitatifs > 0) { if (bItemsQualitatifsPresents) { sRegle += " AND "; if (iNombreDisjonctions > 1) sRegle += "( "; } for (iIndiceDisjonction = 0; iIndiceDisjonction < iNombreDisjonctions; iIndiceDisjonction++) { if (iIndiceDisjonction > 0) sRegle += " OR "; if ((iNombreItemsQuantitatifs > 1) && (iNombreDisjonctions > 1)) sRegle += "( "; bPremierItemInscrit = false; for (iIndiceItem = 0; iIndiceItem < iNombreItems; iIndiceItem++) { item = tItemsRegle[iIndiceItem]; if (item.m_iTypeItem == Item.ITEM_TYPE_QUANTITATIF) { if (bPremierItemInscrit) sRegle += " AND "; sRegle += ((ItemQuantitative) item).toString(iIndiceDisjonction); bPremierItemInscrit = true; } } if ((iNombreItemsQuantitatifs > 1) && (iNombreDisjonctions > 1)) sRegle += " )"; } if ((bItemsQualitatifsPresents) && (iNombreDisjonctions > 1)) sRegle += " ) "; } return sRegle; }
public String rightToString() { String sRegle = null; int iIndiceItem = 0; Item item = null; boolean bItemsQualitatifsPresents = false; boolean bPremierItemInscrit = false; int iIndiceDisjonction = 0; int iNombreDisjonctions = 0; int iNombreItemsQuantitatifs = 0; int iNombreItems = 0; Item[] tItemsRegle = null; sRegle = new String(""); iNombreItems = m_iNombreItemsDroite; tItemsRegle = m_tItemsDroite; <DeepExtract> int iPosition = 0; int iCompteur = 0; iCompteur = 0; for (iPosition = 0; iPosition < m_iNombreItemsDroite; iPosition++) if (m_tItemsDroite[iPosition].m_iTypeItem == Item.ITEM_TYPE_QUANTITATIF) iCompteur++; return iCompteur; </DeepExtract> iNombreDisjonctions = m_iNombreDisjonctionsDroiteValides; bPremierItemInscrit = false; for (iIndiceItem = 0; iIndiceItem < iNombreItems; iIndiceItem++) { item = tItemsRegle[iIndiceItem]; if (item.m_iTypeItem == Item.ITEM_TYPE_QUALITATIF) { if (bPremierItemInscrit) sRegle += " AND "; sRegle += ((ItemQualitative) item).toString(); bPremierItemInscrit = true; } } bItemsQualitatifsPresents = bPremierItemInscrit; if (iNombreItemsQuantitatifs > 0) { if (bItemsQualitatifsPresents) { sRegle += " AND "; if (iNombreDisjonctions > 1) sRegle += "( "; } for (iIndiceDisjonction = 0; iIndiceDisjonction < iNombreDisjonctions; iIndiceDisjonction++) { if (iIndiceDisjonction > 0) sRegle += " OR "; if ((iNombreItemsQuantitatifs > 1) && (iNombreDisjonctions > 1)) sRegle += "( "; bPremierItemInscrit = false; for (iIndiceItem = 0; iIndiceItem < iNombreItems; iIndiceItem++) { item = tItemsRegle[iIndiceItem]; if (item.m_iTypeItem == Item.ITEM_TYPE_QUANTITATIF) { if (bPremierItemInscrit) sRegle += " AND "; sRegle += ((ItemQuantitative) item).toString(iIndiceDisjonction); bPremierItemInscrit = true; } } if ((iNombreItemsQuantitatifs > 1) && (iNombreDisjonctions > 1)) sRegle += " )"; } if ((bItemsQualitatifsPresents) && (iNombreDisjonctions > 1)) sRegle += " ) "; } return sRegle; }
QuantMiner
positive
1,137
public static synchronized void createSparseDoubleTable(int tableId, int staleness) { Preconditions.checkState(isInitialized, "PsTableGroup has not been initialized!"); RowFactory rowFactory = new SparseDoubleRowFactory(); RowUpdateFactory rowUpdateFactory = new SparseDoubleRowUpdateFactory(); doubleTables.add(tableId); Preconditions.checkState(isInitialized, "PsTableGroup has not been initialized!"); Preconditions.checkState(numWorkerThreadsRegistered.get() == 0, "Cannot create table after a worker thread is registered!"); Preconditions.checkArgument(!tables.containsKey(tableId), "Already created table with ID=" + tableId + "!"); Preconditions.checkArgument(staleness >= 0, "Cannot create table with negative staleness value!"); if (staleness > maxTableStaleness) { maxTableStaleness = staleness; } ServerThreadGroup.createTable(tableId, rowFactory, rowUpdateFactory); tables.put(tableId, new ClientTable(tableId, staleness, rowFactory, rowUpdateFactory)); }
public static synchronized void createSparseDoubleTable(int tableId, int staleness) { Preconditions.checkState(isInitialized, "PsTableGroup has not been initialized!"); RowFactory rowFactory = new SparseDoubleRowFactory(); RowUpdateFactory rowUpdateFactory = new SparseDoubleRowUpdateFactory(); doubleTables.add(tableId); <DeepExtract> Preconditions.checkState(isInitialized, "PsTableGroup has not been initialized!"); Preconditions.checkState(numWorkerThreadsRegistered.get() == 0, "Cannot create table after a worker thread is registered!"); Preconditions.checkArgument(!tables.containsKey(tableId), "Already created table with ID=" + tableId + "!"); Preconditions.checkArgument(staleness >= 0, "Cannot create table with negative staleness value!"); if (staleness > maxTableStaleness) { maxTableStaleness = staleness; } ServerThreadGroup.createTable(tableId, rowFactory, rowUpdateFactory); tables.put(tableId, new ClientTable(tableId, staleness, rowFactory, rowUpdateFactory)); </DeepExtract> }
jbosen
positive
1,138
@Test public void noTenacityConfigurationSetShouldUseDefault() { clientConfiguration.setTimeout(Duration.milliseconds(1)); final Client tenacityClient = tenacityClientBuilder.build(buildClient()); doSleep(null); }
@Test public void noTenacityConfigurationSetShouldUseDefault() { clientConfiguration.setTimeout(Duration.milliseconds(1)); final Client tenacityClient = tenacityClientBuilder.build(buildClient()); <DeepExtract> doSleep(null); </DeepExtract> }
tenacity
positive
1,139
@Override public void onFinishInflate() { mOnButton = (RadioButton) findViewById(TkR.id.compat_mode_on_radio); mOffButton = (RadioButton) findViewById(TkR.id.compat_mode_off_radio); mOnButton.setOnClickListener(this); mOffButton.setOnClickListener(this); int COMPAT_MODE_ENABLED = XposedHelpers.getStaticIntField(ActivityManager.class, "COMPAT_MODE_ENABLED"); int COMPAT_MODE_ALWAYS = XposedHelpers.getStaticIntField(ActivityManager.class, "COMPAT_MODE_ALWAYS"); int COMPAT_MODE_NEVER = XposedHelpers.getStaticIntField(ActivityManager.class, "COMPAT_MODE_NEVER"); int mode = (Integer) XposedHelpers.callMethod(mAM, "getFrontActivityScreenCompatMode"); if (mode == COMPAT_MODE_ALWAYS || mode == COMPAT_MODE_NEVER) { closePanel(); return; } final boolean on = (mode == COMPAT_MODE_ENABLED); mOnButton.setChecked(on); mOffButton.setChecked(!on); }
@Override public void onFinishInflate() { mOnButton = (RadioButton) findViewById(TkR.id.compat_mode_on_radio); mOffButton = (RadioButton) findViewById(TkR.id.compat_mode_off_radio); mOnButton.setOnClickListener(this); mOffButton.setOnClickListener(this); <DeepExtract> int COMPAT_MODE_ENABLED = XposedHelpers.getStaticIntField(ActivityManager.class, "COMPAT_MODE_ENABLED"); int COMPAT_MODE_ALWAYS = XposedHelpers.getStaticIntField(ActivityManager.class, "COMPAT_MODE_ALWAYS"); int COMPAT_MODE_NEVER = XposedHelpers.getStaticIntField(ActivityManager.class, "COMPAT_MODE_NEVER"); int mode = (Integer) XposedHelpers.callMethod(mAM, "getFrontActivityScreenCompatMode"); if (mode == COMPAT_MODE_ALWAYS || mode == COMPAT_MODE_NEVER) { closePanel(); return; } final boolean on = (mode == COMPAT_MODE_ENABLED); mOnButton.setChecked(on); mOffButton.setChecked(!on); </DeepExtract> }
tabletkat
positive
1,140
public Criteria andCallbackRequestMethodGreaterThan(String value) { if (value == null) { throw new RuntimeException("Value for " + "callbackRequestMethod" + " cannot be null"); } criteria.add(new Criterion("callback_request_method >", value)); return (Criteria) this; }
public Criteria andCallbackRequestMethodGreaterThan(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "callbackRequestMethod" + " cannot be null"); } criteria.add(new Criterion("callback_request_method >", value)); </DeepExtract> return (Criteria) this; }
AnyMock
positive
1,142
public void storeIntVariable(int vindex) { if (vindex < 0) throw new IllegalArgumentException("vindex must be positive"); if (vindex >= numLocals) { numLocals = vindex + 1; if (numLocals > 65535) throw new ClassFileLimitExceededException("Too many locals."); } if (stackSize == -1) { return; } stackSize -= 1; if (stackSize < 0) throw new IllegalStateException("Stack underflow."); stackSize += 0; if (stackSize > maxStackSize) { maxStackSize = stackSize; if (stackSize >= 65534) throw new ClassFileLimitExceededException("Stack overflow."); } if (vindex < 4) { emit(59 + vindex); } else if (vindex <= 255) { emit(54); emit(vindex); } else { emit(196); emit(54); emitUInt16(vindex); } }
public void storeIntVariable(int vindex) { if (vindex < 0) throw new IllegalArgumentException("vindex must be positive"); if (vindex >= numLocals) { numLocals = vindex + 1; if (numLocals > 65535) throw new ClassFileLimitExceededException("Too many locals."); } <DeepExtract> if (stackSize == -1) { return; } stackSize -= 1; if (stackSize < 0) throw new IllegalStateException("Stack underflow."); stackSize += 0; if (stackSize > maxStackSize) { maxStackSize = stackSize; if (stackSize >= 65534) throw new ClassFileLimitExceededException("Stack overflow."); } </DeepExtract> if (vindex < 4) { emit(59 + vindex); } else if (vindex <= 255) { emit(54); emit(vindex); } else { emit(196); emit(54); emitUInt16(vindex); } }
arden2bytecode
positive
1,143
private void initData() { progressBar.post(() -> progressBar.setVisibility(View.VISIBLE)); new Thread(() -> { data.clear(); picked.clear(); notInstalled.clear(); SharedPreferenceUtil sharedPreferenceUtil = SharedPreferenceUtil.getInstance(); String raw = ""; switch(pickerType) { case PICKER_WHITE_LIST: raw = (String) sharedPreferenceUtil.get(AppPickActivity.this, Constants.PREF_FLOAT_WINDOW_FILTER, Constants.DEFAULT_VALUE_PREF_FLOAT_WINDOW_FILTER); break; case PICKER_TYPE_STICKY_APPS: raw = (String) sharedPreferenceUtil.get(AppPickActivity.this, Constants.PREF_FLOAT_STICKY_APPS, Constants.DEFAULT_VALUE_PREF_FLOAT_STICKY_APPS); break; } if (raw != null && !raw.equals("")) { String[] filter_cooking = raw.split(","); Collections.addAll(picked, filter_cooking); Collections.addAll(notInstalled, filter_cooking); } PickerPack system_server = new PickerPack("system_server", "system_server", null, picked.contains("system_server")); data.add(system_server); List<PackageInfo> packageInfo = getPackageManager().getInstalledPackages(0); for (PackageInfo i : packageInfo) { String label = PackageCtlUtils.getLabel(AppPickActivity.this, i.applicationInfo); Drawable icon = PackageCtlUtils.getIcon(AppPickActivity.this, i.applicationInfo); boolean currentPicked = picked.contains(i.packageName); PickerPack current = new PickerPack(i.packageName, label, icon, currentPicked); notInstalled.remove(i.packageName); if (currentPicked) { data.add(0, current); } else { data.add(current); } } addNotInstalledButSelectedPacks(); runOnUiThread(() -> { adapter.notifyDataSetChanged(); recyclerView.scheduleLayoutAnimation(); hideProcessing(); }); }).start(); }
private void initData() { <DeepExtract> progressBar.post(() -> progressBar.setVisibility(View.VISIBLE)); </DeepExtract> new Thread(() -> { data.clear(); picked.clear(); notInstalled.clear(); SharedPreferenceUtil sharedPreferenceUtil = SharedPreferenceUtil.getInstance(); String raw = ""; switch(pickerType) { case PICKER_WHITE_LIST: raw = (String) sharedPreferenceUtil.get(AppPickActivity.this, Constants.PREF_FLOAT_WINDOW_FILTER, Constants.DEFAULT_VALUE_PREF_FLOAT_WINDOW_FILTER); break; case PICKER_TYPE_STICKY_APPS: raw = (String) sharedPreferenceUtil.get(AppPickActivity.this, Constants.PREF_FLOAT_STICKY_APPS, Constants.DEFAULT_VALUE_PREF_FLOAT_STICKY_APPS); break; } if (raw != null && !raw.equals("")) { String[] filter_cooking = raw.split(","); Collections.addAll(picked, filter_cooking); Collections.addAll(notInstalled, filter_cooking); } PickerPack system_server = new PickerPack("system_server", "system_server", null, picked.contains("system_server")); data.add(system_server); List<PackageInfo> packageInfo = getPackageManager().getInstalledPackages(0); for (PackageInfo i : packageInfo) { String label = PackageCtlUtils.getLabel(AppPickActivity.this, i.applicationInfo); Drawable icon = PackageCtlUtils.getIcon(AppPickActivity.this, i.applicationInfo); boolean currentPicked = picked.contains(i.packageName); PickerPack current = new PickerPack(i.packageName, label, icon, currentPicked); notInstalled.remove(i.packageName); if (currentPicked) { data.add(0, current); } else { data.add(current); } } addNotInstalledButSelectedPacks(); runOnUiThread(() -> { adapter.notifyDataSetChanged(); recyclerView.scheduleLayoutAnimation(); hideProcessing(); }); }).start(); }
audiohq_md2
positive
1,144
public static boolean assignment(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "assignment")) return false; Marker m = enter_section_(b, l, _NONE_, "<assignment>"); if (!recursion_guard_(b, l + 1, "infix")) r = false; boolean r; Marker m = enter_section_(b, l + 1, _NONE_, "<infix>"); r = term(b, l + 1 + 1); r = r && infix_1(b, l + 1 + 1); exit_section_(b, l + 1, m, INFIX, r, false, null); return r; r = r && assignment_1(b, l + 1); exit_section_(b, l, m, ASSIGNMENT, r, false, null); return r; }
public static boolean assignment(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "assignment")) return false; Marker m = enter_section_(b, l, _NONE_, "<assignment>"); <DeepExtract> if (!recursion_guard_(b, l + 1, "infix")) r = false; boolean r; Marker m = enter_section_(b, l + 1, _NONE_, "<infix>"); r = term(b, l + 1 + 1); r = r && infix_1(b, l + 1 + 1); exit_section_(b, l + 1, m, INFIX, r, false, null); return r; </DeepExtract> r = r && assignment_1(b, l + 1); exit_section_(b, l, m, ASSIGNMENT, r, false, null); return r; }
intellij-pony
positive
1,145
public String getDescriptor() { StringBuilder buf = new StringBuilder(); getDescriptor(buf); return getDescriptor(); }
public String getDescriptor() { StringBuilder buf = new StringBuilder(); getDescriptor(buf); <DeepExtract> return getDescriptor(); </DeepExtract> }
ekstazi
positive
1,146
public Object getAttribute(String name) { attributes.put(CommonConstant.SESSION_CHANGED, Boolean.TRUE); return attributes.get(name); }
public Object getAttribute(String name) { <DeepExtract> attributes.put(CommonConstant.SESSION_CHANGED, Boolean.TRUE); </DeepExtract> return attributes.get(name); }
rop
positive
1,147