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 Builder addValuesBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
if (!((bitField0_ & 0x00000001) != 0)) {
values_ = new com.google.protobuf.LazyStringArrayList(values_);
bitField0_ |= 0x00000001;
}
values_.add(value);
onChanged();
return this;
} | public Builder addValuesBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
<DeepExtract>
if (!((bitField0_ & 0x00000001) != 0)) {
values_ = new com.google.protobuf.LazyStringArrayList(values_);
bitField0_ |= 0x00000001;
}
</DeepExtract>
values_.add(value);
onChanged();
return this;
} | url-frontier | positive | 439,972 |
public void setTrueRange(double low, double high) {
double span = max - min;
if (span <= 0)
return;
this.relLow = Math.max(0, (low - min) / span);
this.relHigh = Math.min(1, (high - min) / span);
repaint();
} | public void setTrueRange(double low, double high) {
double span = max - min;
if (span <= 0)
return;
<DeepExtract>
this.relLow = Math.max(0, (low - min) / span);
this.relHigh = Math.min(1, (high - min) / span);
repaint();
</DeepExtract>
} | TimeFlow | positive | 439,973 |
@Override
public void onClick(View v) {
ivMall.setSelected(false);
tvMall.setSelected(false);
ivDapp.setSelected(false);
tvDapp.setSelected(false);
ivMine.setSelected(false);
tvMine.setSelected(false);
switch(v.getId()) {
case R.id.lly_mall:
ivMall.setSelected(true);
tvMall.setSelected(true);
vpHome.setCurrentItem(0, false);
break;
case R.id.lly_dapp:
ivDapp.setSelected(true);
tvDapp.setSelected(true);
vpHome.setCurrentItem(1, false);
setupToolbarForDapp();
break;
case R.id.lly_mine:
ivMine.setSelected(true);
tvMine.setSelected(true);
vpHome.setCurrentItem(2, false);
break;
}
} | @Override
public void onClick(View v) {
<DeepExtract>
ivMall.setSelected(false);
tvMall.setSelected(false);
ivDapp.setSelected(false);
tvDapp.setSelected(false);
ivMine.setSelected(false);
tvMine.setSelected(false);
</DeepExtract>
switch(v.getId()) {
case R.id.lly_mall:
ivMall.setSelected(true);
tvMall.setSelected(true);
vpHome.setCurrentItem(0, false);
break;
case R.id.lly_dapp:
ivDapp.setSelected(true);
tvDapp.setSelected(true);
vpHome.setCurrentItem(1, false);
setupToolbarForDapp();
break;
case R.id.lly_mine:
ivMine.setSelected(true);
tvMine.setSelected(true);
vpHome.setCurrentItem(2, false);
break;
}
} | Upchain-wallet | positive | 439,974 |
@RepeatedTest(10)
public void test_execute_until_none_left_happy() {
DEBUG_LOG.info("Starting test_execute_until_none_left_happy");
Instant now = Instant.now();
OneTimeTask<Void> task = TestTasks.oneTime("onetime-a", Void.class, TestTasks.DO_NOTHING);
TestableRegistry.Condition condition = TestableRegistry.Conditions.completed(20);
TestableRegistry registry = TestableRegistry.create().waitConditions(condition).build();
Scheduler scheduler = Scheduler.create(postgres.getDataSource(), task).threads(2).pollingInterval(Duration.ofMinutes(1)).schedulerName(new SchedulerName.Fixed("test")).statsRegistry(registry).build();
stopScheduler.register(scheduler);
IntStream.range(0, 20).forEach(i -> scheduler.schedule(task.instance(String.valueOf(i)), clock.now()));
Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
scheduler.start();
condition.waitFor();
List<ExecutionComplete> completed = registry.getCompleted();
assertThat(completed, hasSize(20));
completed.forEach(e -> {
assertThat(e.getResult(), is(ExecutionComplete.Result.OK));
Duration durationUntilExecuted = Duration.between(now, e.getTimeDone());
assertThat(durationUntilExecuted, TimeMatchers.shorterThan(Duration.ofMillis(1100)));
});
registry.assertNoFailures();
}, waitingForConditionTimedOut(scheduler));
} | @RepeatedTest(10)
public void test_execute_until_none_left_happy() {
DEBUG_LOG.info("Starting test_execute_until_none_left_happy");
<DeepExtract>
Instant now = Instant.now();
OneTimeTask<Void> task = TestTasks.oneTime("onetime-a", Void.class, TestTasks.DO_NOTHING);
TestableRegistry.Condition condition = TestableRegistry.Conditions.completed(20);
TestableRegistry registry = TestableRegistry.create().waitConditions(condition).build();
Scheduler scheduler = Scheduler.create(postgres.getDataSource(), task).threads(2).pollingInterval(Duration.ofMinutes(1)).schedulerName(new SchedulerName.Fixed("test")).statsRegistry(registry).build();
stopScheduler.register(scheduler);
IntStream.range(0, 20).forEach(i -> scheduler.schedule(task.instance(String.valueOf(i)), clock.now()));
Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
scheduler.start();
condition.waitFor();
List<ExecutionComplete> completed = registry.getCompleted();
assertThat(completed, hasSize(20));
completed.forEach(e -> {
assertThat(e.getResult(), is(ExecutionComplete.Result.OK));
Duration durationUntilExecuted = Duration.between(now, e.getTimeDone());
assertThat(durationUntilExecuted, TimeMatchers.shorterThan(Duration.ofMillis(1100)));
});
registry.assertNoFailures();
}, waitingForConditionTimedOut(scheduler));
</DeepExtract>
} | db-scheduler | positive | 439,975 |
public void sort() {
Collections.sort(mItems);
notifyDataSetChanged();
if (mDirtyState != false) {
mDirtyState = false;
if (mListener != null) {
mListener.onDirtyStateChanged(false);
}
}
} | public void sort() {
Collections.sort(mItems);
notifyDataSetChanged();
<DeepExtract>
if (mDirtyState != false) {
mDirtyState = false;
if (mListener != null) {
mListener.onDirtyStateChanged(false);
}
}
</DeepExtract>
} | AppLocker | positive | 439,976 |
private void stopRecord() {
try {
if (mMediaRecorder != null) {
mMediaRecorder.stop();
mMediaRecorder.release();
}
mMediaRecorder = null;
} catch (Exception e) {
e.printStackTrace();
}
if (camera == null)
return;
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
rlDecide.setVisibility(View.VISIBLE);
rlStart.setVisibility(View.GONE);
findViewById(R.id.iv_switch).setVisibility(View.GONE);
viewSave.setVisibility(View.VISIBLE);
if (videoPath == null)
return;
try {
mediaplayer = new MediaPlayer();
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaplayer.setDataSource(this, Uri.fromFile(new File(videoPath)));
mediaplayer.setDisplay(surfaceView.getHolder());
mediaplayer.setLooping(true);
mediaplayer.prepare();
mediaplayer.start();
} catch (Exception e) {
e.printStackTrace();
}
} | private void stopRecord() {
try {
if (mMediaRecorder != null) {
mMediaRecorder.stop();
mMediaRecorder.release();
}
mMediaRecorder = null;
} catch (Exception e) {
e.printStackTrace();
}
if (camera == null)
return;
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
rlDecide.setVisibility(View.VISIBLE);
rlStart.setVisibility(View.GONE);
findViewById(R.id.iv_switch).setVisibility(View.GONE);
viewSave.setVisibility(View.VISIBLE);
<DeepExtract>
if (videoPath == null)
return;
try {
mediaplayer = new MediaPlayer();
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaplayer.setDataSource(this, Uri.fromFile(new File(videoPath)));
mediaplayer.setDisplay(surfaceView.getHolder());
mediaplayer.setLooping(true);
mediaplayer.prepare();
mediaplayer.start();
} catch (Exception e) {
e.printStackTrace();
}
</DeepExtract>
} | MediaPicker | positive | 439,977 |
@Override
public void readFromJSon(JsonObject object) {
name = object.get("name").getAsString();
JsonArray paletteArray = object.get("palette").getAsJsonArray();
for (JsonElement element : paletteArray) {
JsonObject o = element.getAsJsonObject();
Object value = null;
Character c = o.get("char").getAsCharacter();
IBlockState dmg = null;
if (o.has("damaged")) {
dmg = Tools.stringToState(o.get("damaged").getAsString());
}
if (o.has("mob")) {
mobIds.put(c, o.get("mob").getAsString());
}
if (o.has("loot")) {
lootTables.put(c, o.get("loot").getAsString());
}
if (o.has("block")) {
String block = o.get("block").getAsString();
IBlockState state = Tools.stringToState(block);
palette.put(c, state);
if (dmg != null) {
damaged.put(state, dmg);
}
} else if (o.has("frompalette")) {
value = o.get("frompalette").getAsString();
palette.put(c, value);
} else if (o.has("blocks")) {
JsonArray array = o.get("blocks").getAsJsonArray();
List<Pair<Integer, IBlockState>> blocks = new ArrayList<>();
for (JsonElement el : array) {
JsonObject ob = el.getAsJsonObject();
Integer f = ob.get("random").getAsInt();
String block = ob.get("block").getAsString();
IBlockState state = Tools.stringToState(block);
blocks.add(Pair.of(f, state));
if (dmg != null) {
damaged.put(state, dmg);
}
}
addMappingViaState(c, blocks.toArray(new Pair[blocks.size()]));
} else {
throw new RuntimeException("Illegal palette!");
}
}
} | @Override
public void readFromJSon(JsonObject object) {
name = object.get("name").getAsString();
JsonArray paletteArray = object.get("palette").getAsJsonArray();
<DeepExtract>
for (JsonElement element : paletteArray) {
JsonObject o = element.getAsJsonObject();
Object value = null;
Character c = o.get("char").getAsCharacter();
IBlockState dmg = null;
if (o.has("damaged")) {
dmg = Tools.stringToState(o.get("damaged").getAsString());
}
if (o.has("mob")) {
mobIds.put(c, o.get("mob").getAsString());
}
if (o.has("loot")) {
lootTables.put(c, o.get("loot").getAsString());
}
if (o.has("block")) {
String block = o.get("block").getAsString();
IBlockState state = Tools.stringToState(block);
palette.put(c, state);
if (dmg != null) {
damaged.put(state, dmg);
}
} else if (o.has("frompalette")) {
value = o.get("frompalette").getAsString();
palette.put(c, value);
} else if (o.has("blocks")) {
JsonArray array = o.get("blocks").getAsJsonArray();
List<Pair<Integer, IBlockState>> blocks = new ArrayList<>();
for (JsonElement el : array) {
JsonObject ob = el.getAsJsonObject();
Integer f = ob.get("random").getAsInt();
String block = ob.get("block").getAsString();
IBlockState state = Tools.stringToState(block);
blocks.add(Pair.of(f, state));
if (dmg != null) {
damaged.put(state, dmg);
}
}
addMappingViaState(c, blocks.toArray(new Pair[blocks.size()]));
} else {
throw new RuntimeException("Illegal palette!");
}
}
</DeepExtract>
} | LostCities | positive | 439,978 |
public void readFromTo() throws IOException {
pointmap = new HashMap<>();
waypoints = new ArrayList<>();
nogopoints = new ArrayList<>();
_readPointmap(internalDir + "/favourites.gpx");
_readNogoLines(basedir + tracksdir);
boolean fromToMissing = false;
for (String name : posnames) {
OsmNodeNamed n = pointmap.get(name);
if (n != null) {
waypoints.add(n);
} else {
if ("from".equals(name))
fromToMissing = true;
if ("to".equals(name))
fromToMissing = true;
}
}
if (fromToMissing)
waypoints.clear();
} | public void readFromTo() throws IOException {
pointmap = new HashMap<>();
waypoints = new ArrayList<>();
nogopoints = new ArrayList<>();
<DeepExtract>
_readPointmap(internalDir + "/favourites.gpx");
_readNogoLines(basedir + tracksdir);
</DeepExtract>
boolean fromToMissing = false;
for (String name : posnames) {
OsmNodeNamed n = pointmap.get(name);
if (n != null) {
waypoints.add(n);
} else {
if ("from".equals(name))
fromToMissing = true;
if ("to".equals(name))
fromToMissing = true;
}
}
if (fromToMissing)
waypoints.clear();
} | brouter | positive | 439,979 |
public StringBuilder visitConstructor(Constructor o, StringBuilder collector) {
collector.append(" NEW ");
collector.append(o.getName()).append("(");
collectNodesFor(o.getProjections(), collector, "", ", ");
collector.append(")");
return collector;
} | public StringBuilder visitConstructor(Constructor o, StringBuilder collector) {
collector.append(" NEW ");
collector.append(o.getName()).append("(");
<DeepExtract>
collectNodesFor(o.getProjections(), collector, "", ", ");
</DeepExtract>
collector.append(")");
return collector;
} | active-persistence | positive | 439,981 |
@Test
public void test100() throws IOException, ClassNotFoundException {
l = new int[100];
a = new short[100][];
for (int i = 0; i < 100; i++) l[i] = (int) (Math.abs(r.nextGaussian()) * 32);
for (int i = 0; i < 100; i++) a[i] = new short[l[i]];
for (int i = 0; i < 100; i++) for (int j = 0; j < l[i]; j++) a[i][j] = genKey();
ShortArrayFrontCodedList m = new ShortArrayFrontCodedList(it.unimi.dsi.fastutil.objects.ObjectIterators.wrap(a), r.nextInt(4) + 1);
final it.unimi.dsi.fastutil.objects.ObjectArrayList t = new it.unimi.dsi.fastutil.objects.ObjectArrayList(a);
assertTrue("Error: m does not equal t at creation", contentEquals(m, t));
assertTrue("Error: m does not equal m.clone()", contentEquals(m, m.clone()));
{
ObjectListIterator i;
java.util.ListIterator j;
i = m.listIterator();
j = t.listIterator();
for (int k = 0; k < 2 * 100; k++) {
assertTrue("Error: divergence in hasNext()", i.hasNext() == j.hasNext());
assertTrue("Error: divergence in hasPrevious()", i.hasPrevious() == j.hasPrevious());
if (r.nextFloat() < .8 && i.hasNext()) {
assertTrue("Error: divergence in next()", java.util.Arrays.equals((short[]) i.next(), (short[]) j.next()));
} else if (r.nextFloat() < .2 && i.hasPrevious()) {
assertTrue("Error: divergence in previous()", java.util.Arrays.equals((short[]) i.previous(), (short[]) j.previous()));
}
assertTrue("Error: divergence in nextIndex()", i.nextIndex() == j.nextIndex());
assertTrue("Error: divergence in previousIndex()", i.previousIndex() == j.previousIndex());
}
}
{
final int from = r.nextInt(m.size() + 1);
ObjectListIterator i;
java.util.ListIterator j;
i = m.listIterator(from);
j = t.listIterator(from);
for (int k = 0; k < 2 * 100; k++) {
assertTrue("Error: divergence in hasNext() (iterator with starting point " + from + ")", i.hasNext() == j.hasNext());
assertTrue("Error: divergence in hasPrevious() (iterator with starting point " + from + ")", i.hasPrevious() == j.hasPrevious());
if (r.nextFloat() < .8 && i.hasNext()) {
assertTrue("Error: divergence in next() (iterator with starting point " + from + ")", java.util.Arrays.equals((short[]) i.next(), (short[]) j.next()));
} else if (r.nextFloat() < .2 && i.hasPrevious()) {
assertTrue("Error: divergence in previous() (iterator with starting point " + from + ")", java.util.Arrays.equals((short[]) i.previous(), (short[]) j.previous()));
}
}
}
final java.io.File ff = new java.io.File("it.unimi.dsi.fastutil.test.junit." + m.getClass().getSimpleName() + "." + 100);
final java.io.OutputStream os = new java.io.FileOutputStream(ff);
final java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(os);
oos.writeObject(m);
oos.close();
final java.io.InputStream is = new java.io.FileInputStream(ff);
final java.io.ObjectInputStream ois = new java.io.ObjectInputStream(is);
m = (ShortArrayFrontCodedList) ois.readObject();
ois.close();
ff.delete();
assertTrue("Error: m does not equal t after save/read", contentEquals(m, t));
return;
} | @Test
public void test100() throws IOException, ClassNotFoundException {
<DeepExtract>
l = new int[100];
a = new short[100][];
for (int i = 0; i < 100; i++) l[i] = (int) (Math.abs(r.nextGaussian()) * 32);
for (int i = 0; i < 100; i++) a[i] = new short[l[i]];
for (int i = 0; i < 100; i++) for (int j = 0; j < l[i]; j++) a[i][j] = genKey();
ShortArrayFrontCodedList m = new ShortArrayFrontCodedList(it.unimi.dsi.fastutil.objects.ObjectIterators.wrap(a), r.nextInt(4) + 1);
final it.unimi.dsi.fastutil.objects.ObjectArrayList t = new it.unimi.dsi.fastutil.objects.ObjectArrayList(a);
assertTrue("Error: m does not equal t at creation", contentEquals(m, t));
assertTrue("Error: m does not equal m.clone()", contentEquals(m, m.clone()));
{
ObjectListIterator i;
java.util.ListIterator j;
i = m.listIterator();
j = t.listIterator();
for (int k = 0; k < 2 * 100; k++) {
assertTrue("Error: divergence in hasNext()", i.hasNext() == j.hasNext());
assertTrue("Error: divergence in hasPrevious()", i.hasPrevious() == j.hasPrevious());
if (r.nextFloat() < .8 && i.hasNext()) {
assertTrue("Error: divergence in next()", java.util.Arrays.equals((short[]) i.next(), (short[]) j.next()));
} else if (r.nextFloat() < .2 && i.hasPrevious()) {
assertTrue("Error: divergence in previous()", java.util.Arrays.equals((short[]) i.previous(), (short[]) j.previous()));
}
assertTrue("Error: divergence in nextIndex()", i.nextIndex() == j.nextIndex());
assertTrue("Error: divergence in previousIndex()", i.previousIndex() == j.previousIndex());
}
}
{
final int from = r.nextInt(m.size() + 1);
ObjectListIterator i;
java.util.ListIterator j;
i = m.listIterator(from);
j = t.listIterator(from);
for (int k = 0; k < 2 * 100; k++) {
assertTrue("Error: divergence in hasNext() (iterator with starting point " + from + ")", i.hasNext() == j.hasNext());
assertTrue("Error: divergence in hasPrevious() (iterator with starting point " + from + ")", i.hasPrevious() == j.hasPrevious());
if (r.nextFloat() < .8 && i.hasNext()) {
assertTrue("Error: divergence in next() (iterator with starting point " + from + ")", java.util.Arrays.equals((short[]) i.next(), (short[]) j.next()));
} else if (r.nextFloat() < .2 && i.hasPrevious()) {
assertTrue("Error: divergence in previous() (iterator with starting point " + from + ")", java.util.Arrays.equals((short[]) i.previous(), (short[]) j.previous()));
}
}
}
final java.io.File ff = new java.io.File("it.unimi.dsi.fastutil.test.junit." + m.getClass().getSimpleName() + "." + 100);
final java.io.OutputStream os = new java.io.FileOutputStream(ff);
final java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(os);
oos.writeObject(m);
oos.close();
final java.io.InputStream is = new java.io.FileInputStream(ff);
final java.io.ObjectInputStream ois = new java.io.ObjectInputStream(is);
m = (ShortArrayFrontCodedList) ois.readObject();
ois.close();
ff.delete();
assertTrue("Error: m does not equal t after save/read", contentEquals(m, t));
return;
</DeepExtract>
} | fastutil | positive | 439,983 |
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject errorResponse) {
Timber.e("Error signing in with euc.world; connection failed: %s", errorResponse.toString());
String url = String.format(Locale.getDefault(), "%s/app.v2?appid=%s&appversion=%s&apikey=%s&locale=%s&tid=%d", Constants.getEucWorldUrl(), Constants.appId(this), BuildConfig.VERSION_NAME, LivemapService.getApiKey(), Locale.getDefault().toString(), System.currentTimeMillis());
eucWorldWebView.loadUrl(url);
} | @Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject errorResponse) {
Timber.e("Error signing in with euc.world; connection failed: %s", errorResponse.toString());
<DeepExtract>
String url = String.format(Locale.getDefault(), "%s/app.v2?appid=%s&appversion=%s&apikey=%s&locale=%s&tid=%d", Constants.getEucWorldUrl(), Constants.appId(this), BuildConfig.VERSION_NAME, LivemapService.getApiKey(), Locale.getDefault().toString(), System.currentTimeMillis());
eucWorldWebView.loadUrl(url);
</DeepExtract>
} | EucWorldAndroid | positive | 439,985 |
@Override
public void onPause() {
super.onPause();
mAdapter.batchSetCardsToRead(previousVisibleHeadCardIndex, currentCardIndexAtBottomOfScreen);
} | @Override
public void onPause() {
super.onPause();
<DeepExtract>
mAdapter.batchSetCardsToRead(previousVisibleHeadCardIndex, currentCardIndexAtBottomOfScreen);
</DeepExtract>
} | appboy-android-sdk | positive | 439,989 |
public static void sleepSecondsLog(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
log.error("Sleep of {} interrupted", e, seconds * 1000);
}
} | public static void sleepSecondsLog(int seconds) {
<DeepExtract>
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
log.error("Sleep of {} interrupted", e, seconds * 1000);
}
</DeepExtract>
} | parallel-consumer | positive | 439,990 |
@Override
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
byte[] bytes = ExchangeHelper.convertToType(exchange, byte[].class, stream);
byte[] result = new byte[bytes.length];
final int lim = bytes.length - 1;
for (int i = 0; i <= lim; i++) {
result[i] = bytes[lim - i];
}
return result;
} | @Override
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
byte[] bytes = ExchangeHelper.convertToType(exchange, byte[].class, stream);
<DeepExtract>
byte[] result = new byte[bytes.length];
final int lim = bytes.length - 1;
for (int i = 0; i <= lim; i++) {
result[i] = bytes[lim - i];
}
return result;
</DeepExtract>
} | camel-cookbook-examples | positive | 439,991 |
public Criteria andTagImgLessThan(Short value) {
if (value == null) {
throw new RuntimeException("Value for " + "tagImg" + " cannot be null");
}
criteria.add(new Criterion("TAG_IMG <", value));
return (Criteria) this;
} | public Criteria andTagImgLessThan(Short value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "tagImg" + " cannot be null");
}
criteria.add(new Criterion("TAG_IMG <", value));
</DeepExtract>
return (Criteria) this;
} | ECPS | positive | 439,992 |
@Test
public void testGetBothDirectionsEdgesDefaultUntypedSet() {
Iterator<EdgeFrame> actualEdges = abstractList.getBothDirectionsExtendEdgeFramesSet().iterator();
Iterator<ExtendsEdge> framedExtendsEdges = new ReframingEdgeIterator<>(actualEdges, ExtendsEdge.class);
int actualEdgesCount = 0;
while (framedExtendsEdges.hasNext()) {
ExtendsEdge extEdge = framedExtendsEdges.next();
String superclassFqn = extEdge.getSuperClass().getFullyQualifiedName();
String subclassFqn = extEdge.getSubClass().getFullyQualifiedName();
Assert.assertEquals(getAbstrListBothDirectionsExtEdges().get(subclassFqn), superclassFqn);
actualEdgesCount += 1;
}
Assert.assertEquals(getAbstrListBothDirectionsExtEdges().size(), actualEdgesCount);
} | @Test
public void testGetBothDirectionsEdgesDefaultUntypedSet() {
Iterator<EdgeFrame> actualEdges = abstractList.getBothDirectionsExtendEdgeFramesSet().iterator();
Iterator<ExtendsEdge> framedExtendsEdges = new ReframingEdgeIterator<>(actualEdges, ExtendsEdge.class);
<DeepExtract>
int actualEdgesCount = 0;
while (framedExtendsEdges.hasNext()) {
ExtendsEdge extEdge = framedExtendsEdges.next();
String superclassFqn = extEdge.getSuperClass().getFullyQualifiedName();
String subclassFqn = extEdge.getSubClass().getFullyQualifiedName();
Assert.assertEquals(getAbstrListBothDirectionsExtEdges().get(subclassFqn), superclassFqn);
actualEdgesCount += 1;
}
Assert.assertEquals(getAbstrListBothDirectionsExtEdges().size(), actualEdgesCount);
</DeepExtract>
} | Ferma | positive | 439,993 |
@Test
public void failure() throws IOException, SparkAPIClientException {
SparkAPIClientException ex = new SparkAPIClientException("Something blew up");
Response rs = new Response(ex);
rs.setSuccess(false);
HttpClient hc = mock(HttpClient.class);
HttpHost h = new HttpHost("MY.TEST.SERVER.FBSDATA.COM");
c.setClient(hc);
c.setHost(h);
when(hc.execute(eq(h), any(HttpPut.class), any(JsonResponseHandler.class))).thenReturn(rs);
try {
c.get("TEST");
fail("exception expected");
} catch (SparkAPIClientException e) {
assertEquals(ex, e);
}
} | @Test
public void failure() throws IOException, SparkAPIClientException {
SparkAPIClientException ex = new SparkAPIClientException("Something blew up");
Response rs = new Response(ex);
rs.setSuccess(false);
<DeepExtract>
HttpClient hc = mock(HttpClient.class);
HttpHost h = new HttpHost("MY.TEST.SERVER.FBSDATA.COM");
c.setClient(hc);
c.setHost(h);
when(hc.execute(eq(h), any(HttpPut.class), any(JsonResponseHandler.class))).thenReturn(rs);
</DeepExtract>
try {
c.get("TEST");
fail("exception expected");
} catch (SparkAPIClientException e) {
assertEquals(ex, e);
}
} | SparkJava | positive | 439,994 |
@Override
public Object terminatePartial(AggregationBuffer agg) throws HiveException {
try {
HLLBuffer myagg = (HLLBuffer) agg;
return myagg.getPartial();
} catch (Exception e) {
LOG.error("Error", e);
throw new HiveException(e);
}
} | @Override
public Object terminatePartial(AggregationBuffer agg) throws HiveException {
<DeepExtract>
try {
HLLBuffer myagg = (HLLBuffer) agg;
return myagg.getPartial();
} catch (Exception e) {
LOG.error("Error", e);
throw new HiveException(e);
}
</DeepExtract>
} | brickhouse | positive | 439,995 |
@Override
protected void injectFilterInvoke() {
visitor.get().incrementInvokeFilterCount();
} | @Override
protected void injectFilterInvoke() {
<DeepExtract>
visitor.get().incrementInvokeFilterCount();
</DeepExtract>
} | NettyRPC | positive | 439,997 |
@Override
protected void onRestoreInstanceState(Parcelable state) {
Bundle bundle = (Bundle) state;
Parcelable superData = bundle.getParcelable("super");
mDelegate.mSelectedCalendar = (Calendar) bundle.getSerializable("selected_calendar");
mDelegate.mIndexCalendar = (Calendar) bundle.getSerializable("index_calendar");
if (mDelegate.mCalendarSelectListener != null) {
mDelegate.mCalendarSelectListener.onCalendarSelect(mDelegate.mSelectedCalendar, false);
}
if (mDelegate.mIndexCalendar != null) {
scrollToCalendar(mDelegate.mIndexCalendar.getYear(), mDelegate.mIndexCalendar.getMonth(), mDelegate.mIndexCalendar.getDay());
}
mWeekBar.onWeekStartChange(mDelegate.getWeekStart());
mYearViewPager.update();
mMonthPager.updateScheme();
mWeekPager.updateScheme();
super.onRestoreInstanceState(superData);
} | @Override
protected void onRestoreInstanceState(Parcelable state) {
Bundle bundle = (Bundle) state;
Parcelable superData = bundle.getParcelable("super");
mDelegate.mSelectedCalendar = (Calendar) bundle.getSerializable("selected_calendar");
mDelegate.mIndexCalendar = (Calendar) bundle.getSerializable("index_calendar");
if (mDelegate.mCalendarSelectListener != null) {
mDelegate.mCalendarSelectListener.onCalendarSelect(mDelegate.mSelectedCalendar, false);
}
if (mDelegate.mIndexCalendar != null) {
scrollToCalendar(mDelegate.mIndexCalendar.getYear(), mDelegate.mIndexCalendar.getMonth(), mDelegate.mIndexCalendar.getDay());
}
<DeepExtract>
mWeekBar.onWeekStartChange(mDelegate.getWeekStart());
mYearViewPager.update();
mMonthPager.updateScheme();
mWeekPager.updateScheme();
</DeepExtract>
super.onRestoreInstanceState(superData);
} | CalendarView | positive | 439,998 |
public Criteria andBz110Between(String value1, String value2) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "bz110" + " cannot be null");
}
criteria.add(new Criterion("`bz110` between", value1, value2));
return (Criteria) this;
} | public Criteria andBz110Between(String value1, String value2) {
<DeepExtract>
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "bz110" + " cannot be null");
}
criteria.add(new Criterion("`bz110` between", value1, value2));
</DeepExtract>
return (Criteria) this;
} | blockhealth | positive | 439,999 |
@Override
public Runnable poll() {
if (this.size() <= 0) {
return null;
}
return this.remove(this.size() - 1);
} | @Override
public Runnable poll() {
<DeepExtract>
if (this.size() <= 0) {
return null;
}
return this.remove(this.size() - 1);
</DeepExtract>
} | JSNose | positive | 440,000 |
public static CityItem build(Context context) {
CityItem_ instance = new CityItem_(context);
if (!alreadyInflated_) {
alreadyInflated_ = true;
inflate(getContext(), layout.item_city, this);
onViewChangedNotifier_.notifyViewChanged(this);
}
super.onFinishInflate();
return instance;
} | public static CityItem build(Context context) {
CityItem_ instance = new CityItem_(context);
<DeepExtract>
if (!alreadyInflated_) {
alreadyInflated_ = true;
inflate(getContext(), layout.item_city, this);
onViewChangedNotifier_.notifyViewChanged(this);
}
super.onFinishInflate();
</DeepExtract>
return instance;
} | FineDay | positive | 440,002 |
public void acknowledgeAlarm(long alarmId) {
if (AppSettings.isDebugMode(context)) {
Toast.makeText(context, "ACKNOWLEDGE ALARM " + alarmId, Toast.LENGTH_SHORT).show();
}
service.acknowledgeAlarm(alarmId);
} | public void acknowledgeAlarm(long alarmId) {
<DeepExtract>
if (AppSettings.isDebugMode(context)) {
Toast.makeText(context, "ACKNOWLEDGE ALARM " + alarmId, Toast.LENGTH_SHORT).show();
}
</DeepExtract>
service.acknowledgeAlarm(alarmId);
} | AlarmOn | positive | 440,003 |
@Override
protected void onDestroy() {
super.onDestroy();
String inputText = edit.getText().toString();
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} | @Override
protected void onDestroy() {
super.onDestroy();
String inputText = edit.getText().toString();
<DeepExtract>
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
</DeepExtract>
} | QCAndroidResource | positive | 440,004 |
@Override
public Observable<Boolean> checkBomNameExist(String name) {
return localDataSource.checkBomNameExist(name);
} | @Override
public Observable<Boolean> checkBomNameExist(String name) {
<DeepExtract>
return localDataSource.checkBomNameExist(name);
</DeepExtract>
} | Consumer | positive | 440,007 |
public Criteria andPicNormalNotLike(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "picNormal" + " cannot be null");
}
criteria.add(new Criterion("pic_normal not like", value));
return (Criteria) this;
} | public Criteria andPicNormalNotLike(String value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "picNormal" + " cannot be null");
}
criteria.add(new Criterion("pic_normal not like", value));
</DeepExtract>
return (Criteria) this;
} | chat-software | positive | 440,010 |
@Test
void installsFromRepoWithSubDirs() throws IOException, InterruptedException {
new TestRpm.Aspell().put(new SubStorage(new Key.From("spelling"), this.asto));
new TestRpm.Time().put(this.asto);
new Rpm(this.asto, RpmSliceDownloadITCase.CONFIG).batchUpdate(Key.ROOT).blockingAwait();
this.server = new VertxSliceServer(RpmSliceDownloadITCase.VERTX, new LoggingSlice(new RpmSlice(this.asto, Policy.FREE, Authentication.ANONYMOUS, RpmSliceDownloadITCase.CONFIG)));
this.port = this.server.start();
Testcontainers.exposeHostPorts(this.port);
this.cntn = new GenericContainer<>("fedora:36").withCommand("tail", "-f", "/dev/null").withWorkingDirectory("/home/").withFileSystemBind(this.tmp.toString(), "/home");
this.cntn.start();
final Path setting = this.tmp.resolve("example.repo");
this.tmp.resolve("example.repo").toFile().createNewFile();
Files.write(setting, new ListOf<>("[example]", "name=Example Repository", String.format("baseurl=http://host.testcontainers.internal:%d/", this.port), "enabled=1", "gpgcheck=0"));
this.cntn.execInContainer("mv", "/home/example.repo", "/etc/yum.repos.d/");
MatcherAssert.assertThat(this.cntn.execInContainer("dnf", "-y", "repository-packages", "example", "install").toString(), new StringContainsInOrder(new ListOf<>("Installed", "aspell-12:0.60.6.1-9.el7.x86_64", "time-1.7-45.el7.x86_64", "Complete!")));
} | @Test
void installsFromRepoWithSubDirs() throws IOException, InterruptedException {
new TestRpm.Aspell().put(new SubStorage(new Key.From("spelling"), this.asto));
new TestRpm.Time().put(this.asto);
new Rpm(this.asto, RpmSliceDownloadITCase.CONFIG).batchUpdate(Key.ROOT).blockingAwait();
<DeepExtract>
this.server = new VertxSliceServer(RpmSliceDownloadITCase.VERTX, new LoggingSlice(new RpmSlice(this.asto, Policy.FREE, Authentication.ANONYMOUS, RpmSliceDownloadITCase.CONFIG)));
this.port = this.server.start();
Testcontainers.exposeHostPorts(this.port);
this.cntn = new GenericContainer<>("fedora:36").withCommand("tail", "-f", "/dev/null").withWorkingDirectory("/home/").withFileSystemBind(this.tmp.toString(), "/home");
this.cntn.start();
</DeepExtract>
final Path setting = this.tmp.resolve("example.repo");
this.tmp.resolve("example.repo").toFile().createNewFile();
Files.write(setting, new ListOf<>("[example]", "name=Example Repository", String.format("baseurl=http://host.testcontainers.internal:%d/", this.port), "enabled=1", "gpgcheck=0"));
this.cntn.execInContainer("mv", "/home/example.repo", "/etc/yum.repos.d/");
MatcherAssert.assertThat(this.cntn.execInContainer("dnf", "-y", "repository-packages", "example", "install").toString(), new StringContainsInOrder(new ListOf<>("Installed", "aspell-12:0.60.6.1-9.el7.x86_64", "time-1.7-45.el7.x86_64", "Complete!")));
} | rpm-adapter | positive | 440,011 |
public void addAttribute(byte attrId, ItemStack itemStack) {
if (hasAttribute(attrId) || itemStack == null) {
return;
}
ItemStack reducedStack = ItemStack.copyItemStack(itemStack);
reducedStack.stackSize = 1;
cbAttrMap.put(attrId, new Attribute(reducedStack));
World world = getWorldObj();
Block block = BlockProperties.toBlock(itemStack);
if (attrId < 7) {
if (attrId == ATTR_COVER[6]) {
int metadata = itemStack.getItemDamage();
world.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, metadata, 0);
}
world.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, block);
} else if (attrId == ATTR_PLANT | attrId == ATTR_SOIL) {
world.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, block);
}
if (attrId == ATTR_FERTILIZER) {
getWorldObj().playAuxSFX(2005, xCoord, yCoord, zCoord, 0);
}
World world = getWorldObj();
if (world != null) {
updateCachedLighting();
world.markBlockForUpdate(xCoord, yCoord, zCoord);
}
markDirty();
} | public void addAttribute(byte attrId, ItemStack itemStack) {
if (hasAttribute(attrId) || itemStack == null) {
return;
}
ItemStack reducedStack = ItemStack.copyItemStack(itemStack);
reducedStack.stackSize = 1;
cbAttrMap.put(attrId, new Attribute(reducedStack));
World world = getWorldObj();
Block block = BlockProperties.toBlock(itemStack);
if (attrId < 7) {
if (attrId == ATTR_COVER[6]) {
int metadata = itemStack.getItemDamage();
world.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, metadata, 0);
}
world.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, block);
} else if (attrId == ATTR_PLANT | attrId == ATTR_SOIL) {
world.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, block);
}
if (attrId == ATTR_FERTILIZER) {
getWorldObj().playAuxSFX(2005, xCoord, yCoord, zCoord, 0);
}
<DeepExtract>
World world = getWorldObj();
if (world != null) {
updateCachedLighting();
world.markBlockForUpdate(xCoord, yCoord, zCoord);
}
</DeepExtract>
markDirty();
} | carpentersblocks | positive | 440,012 |
@Override
public void printJsonRequest(Request request, String bodyString) {
final String requestBody = LINE_SEPARATOR + BODY_TAG + LINE_SEPARATOR + bodyString;
String tag;
if (true) {
tag = TAG + "-Request";
} else {
tag = TAG + "-Response";
}
Timber.tag(tag).i(REQUEST_UP_LINE);
for (String line : new String[] { URL_TAG + request.url() }) {
int lineLength = line.length();
int MAX_LONG_SIZE = false ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
Timber.tag(resolveTag(tag)).i(DEFAULT_LINE + line.substring(start, end));
}
}
for (String line : getRequest(request)) {
int lineLength = line.length();
int MAX_LONG_SIZE = true ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
Timber.tag(resolveTag(tag)).i(DEFAULT_LINE + line.substring(start, end));
}
}
for (String line : requestBody.split(LINE_SEPARATOR)) {
int lineLength = line.length();
int MAX_LONG_SIZE = true ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
Timber.tag(resolveTag(tag)).i(DEFAULT_LINE + line.substring(start, end));
}
}
Timber.tag(tag).i(END_LINE);
} | @Override
public void printJsonRequest(Request request, String bodyString) {
final String requestBody = LINE_SEPARATOR + BODY_TAG + LINE_SEPARATOR + bodyString;
String tag;
if (true) {
tag = TAG + "-Request";
} else {
tag = TAG + "-Response";
}
Timber.tag(tag).i(REQUEST_UP_LINE);
for (String line : new String[] { URL_TAG + request.url() }) {
int lineLength = line.length();
int MAX_LONG_SIZE = false ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
Timber.tag(resolveTag(tag)).i(DEFAULT_LINE + line.substring(start, end));
}
}
for (String line : getRequest(request)) {
int lineLength = line.length();
int MAX_LONG_SIZE = true ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
Timber.tag(resolveTag(tag)).i(DEFAULT_LINE + line.substring(start, end));
}
}
<DeepExtract>
for (String line : requestBody.split(LINE_SEPARATOR)) {
int lineLength = line.length();
int MAX_LONG_SIZE = true ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
Timber.tag(resolveTag(tag)).i(DEFAULT_LINE + line.substring(start, end));
}
}
</DeepExtract>
Timber.tag(tag).i(END_LINE);
} | MVPSamples | positive | 440,013 |
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
stop();
MediaPlayer player = this.player;
if (player != null && !player.isReleased()) {
player.release();
}
this.player = null;
state = STATE_IDLE;
} | @Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
<DeepExtract>
stop();
MediaPlayer player = this.player;
if (player != null && !player.isReleased()) {
player.release();
}
this.player = null;
state = STATE_IDLE;
</DeepExtract>
} | ONVIF-Camera | positive | 440,014 |
@TruffleBoundary
private static void doPrint(PrintWriter out, long value) {
doPrint(getContext().getOutput(), value);
return value;
} | @TruffleBoundary
private static void doPrint(PrintWriter out, long value) {
<DeepExtract>
doPrint(getContext().getOutput(), value);
return value;
</DeepExtract>
} | cover | positive | 440,015 |
@Override
public void run() {
mClickedMenuItem = mClickedMenuItem;
switch(mClickedMenuItem.getItemId()) {
case R.id.menu_scroll_top:
scrollTop();
break;
case R.id.menu_scroll_down:
scrollDown();
break;
case R.id.menu_refresh:
reloadErrorLog();
return true;
case R.id.menu_send:
try {
send();
} catch (NullPointerException ignored) {
}
return true;
case R.id.menu_save:
save();
return true;
case R.id.menu_clear:
clear();
return true;
}
return super.onOptionsItemSelected(mClickedMenuItem);
} | @Override
public void run() {
<DeepExtract>
mClickedMenuItem = mClickedMenuItem;
switch(mClickedMenuItem.getItemId()) {
case R.id.menu_scroll_top:
scrollTop();
break;
case R.id.menu_scroll_down:
scrollDown();
break;
case R.id.menu_refresh:
reloadErrorLog();
return true;
case R.id.menu_send:
try {
send();
} catch (NullPointerException ignored) {
}
return true;
case R.id.menu_save:
save();
return true;
case R.id.menu_clear:
clear();
return true;
}
return super.onOptionsItemSelected(mClickedMenuItem);
</DeepExtract>
} | XposedInstaller | positive | 440,016 |
@Test
public void testDeserializationAsInt03MillisecondsWithoutTimeZone() throws Exception {
ZonedDateTime date = ZonedDateTime.now(Z3);
date = date.minus(date.getNano() - (date.get(ChronoField.MILLI_OF_SECOND) * 1_000_000L), ChronoUnit.NANOS);
ObjectMapper mapper = newMapper();
ZonedDateTime value = mapper.readerFor(ZonedDateTime.class).without(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS).readValue(Long.toString(date.toInstant().toEpochMilli()));
assertTrue("The value is not correct. Expected timezone-adjusted <" + date + ">, actual <" + value + ">.", date.isEqual(value));
assertEquals("The time zone is not correct.", DEFAULT_TZ, value.getZone());
} | @Test
public void testDeserializationAsInt03MillisecondsWithoutTimeZone() throws Exception {
ZonedDateTime date = ZonedDateTime.now(Z3);
date = date.minus(date.getNano() - (date.get(ChronoField.MILLI_OF_SECOND) * 1_000_000L), ChronoUnit.NANOS);
ObjectMapper mapper = newMapper();
ZonedDateTime value = mapper.readerFor(ZonedDateTime.class).without(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS).readValue(Long.toString(date.toInstant().toEpochMilli()));
<DeepExtract>
assertTrue("The value is not correct. Expected timezone-adjusted <" + date + ">, actual <" + value + ">.", date.isEqual(value));
</DeepExtract>
assertEquals("The time zone is not correct.", DEFAULT_TZ, value.getZone());
} | jackson-modules-java8 | positive | 440,017 |
private static MessageFunction fromJava(String className, String returnType, String methodName, String methodParams) {
String namespace = className.replace('.', '/');
int messageIndex = -1;
int contextIndex = -1;
int pluralIndex = -1;
boolean isConstructor = "<init>".equals(methodName);
String[] params = methodParams.split("\\s*,\\s*");
StringBuilder desc = new StringBuilder();
desc.append("(");
int length = params.length;
for (int i = 0; i < length; i++) {
String[] typeAndName = params[i].split("\\s+");
if (typeAndName.length > 1) {
String name = typeAndName[1];
if ("context".equals(name)) {
contextIndex = isConstructor ? i + 1 : i;
} else if ("message".equals(name)) {
messageIndex = isConstructor ? i + 1 : i;
} else if ("plural".equals(name)) {
pluralIndex = isConstructor ? i + 1 : i;
}
}
if (typeAndName[0].length() > 0) {
appendInternalName(desc, typeAndName[0]);
}
}
desc.append(")");
if (returnType.endsWith("...")) {
desc.append("[");
returnType = returnType.substring(0, returnType.length() - 3);
}
while (returnType.endsWith("[]")) {
desc.append("[");
returnType = returnType.substring(0, returnType.length() - 2);
}
if ("void".equals(returnType)) {
desc.append("V");
} else if ("boolean".equals(returnType)) {
desc.append("Z");
} else if ("byte".equals(returnType)) {
desc.append("B");
} else if ("char".equals(returnType)) {
desc.append("C");
} else if ("short".equals(returnType)) {
desc.append("S");
} else if ("int".equals(returnType)) {
desc.append("I");
} else if ("long".equals(returnType)) {
desc.append("J");
} else if ("float".equals(returnType)) {
desc.append("F");
} else if ("double".equals(returnType)) {
desc.append("D");
} else if ("Object".equals(returnType)) {
desc.append("Ljava/lang/Object;");
} else if ("String".equals(returnType)) {
desc.append("Ljava/lang/String;");
} else if ("Locale".equals(returnType)) {
desc.append("Ljava/util/Locale;");
} else if ("ResourceBundle".equals(returnType)) {
desc.append("Ljava/util/ResourceBundle;");
} else {
desc.append("L");
desc.append(returnType.replace('.', '/'));
desc.append(";");
}
return new MessageFunction(namespace, methodName, desc.toString(), messageIndex, contextIndex, pluralIndex, length);
} | private static MessageFunction fromJava(String className, String returnType, String methodName, String methodParams) {
String namespace = className.replace('.', '/');
int messageIndex = -1;
int contextIndex = -1;
int pluralIndex = -1;
boolean isConstructor = "<init>".equals(methodName);
String[] params = methodParams.split("\\s*,\\s*");
StringBuilder desc = new StringBuilder();
desc.append("(");
int length = params.length;
for (int i = 0; i < length; i++) {
String[] typeAndName = params[i].split("\\s+");
if (typeAndName.length > 1) {
String name = typeAndName[1];
if ("context".equals(name)) {
contextIndex = isConstructor ? i + 1 : i;
} else if ("message".equals(name)) {
messageIndex = isConstructor ? i + 1 : i;
} else if ("plural".equals(name)) {
pluralIndex = isConstructor ? i + 1 : i;
}
}
if (typeAndName[0].length() > 0) {
appendInternalName(desc, typeAndName[0]);
}
}
desc.append(")");
<DeepExtract>
if (returnType.endsWith("...")) {
desc.append("[");
returnType = returnType.substring(0, returnType.length() - 3);
}
while (returnType.endsWith("[]")) {
desc.append("[");
returnType = returnType.substring(0, returnType.length() - 2);
}
if ("void".equals(returnType)) {
desc.append("V");
} else if ("boolean".equals(returnType)) {
desc.append("Z");
} else if ("byte".equals(returnType)) {
desc.append("B");
} else if ("char".equals(returnType)) {
desc.append("C");
} else if ("short".equals(returnType)) {
desc.append("S");
} else if ("int".equals(returnType)) {
desc.append("I");
} else if ("long".equals(returnType)) {
desc.append("J");
} else if ("float".equals(returnType)) {
desc.append("F");
} else if ("double".equals(returnType)) {
desc.append("D");
} else if ("Object".equals(returnType)) {
desc.append("Ljava/lang/Object;");
} else if ("String".equals(returnType)) {
desc.append("Ljava/lang/String;");
} else if ("Locale".equals(returnType)) {
desc.append("Ljava/util/Locale;");
} else if ("ResourceBundle".equals(returnType)) {
desc.append("Ljava/util/ResourceBundle;");
} else {
desc.append("L");
desc.append(returnType.replace('.', '/'));
desc.append(";");
}
</DeepExtract>
return new MessageFunction(namespace, methodName, desc.toString(), messageIndex, contextIndex, pluralIndex, length);
} | i18n | positive | 440,018 |
@SuppressWarnings("javadoc")
private static void multipleUnchangedAssertions(CallInfo callInfo, DataSource[] dataSources) {
HashSet<DataSource> set = new HashSet<>();
for (T object : dataSources) {
if (!set.add(Function.identity().apply(object))) {
throw new InvalidOperationException("Repeated data source in call!");
}
}
if (dataSources == null || dataSources.length == 0) {
throw new InvalidOperationException("Empty or null array!");
}
for (T argument : dataSources) {
(ci, dataSource) -> {
DataSet emptyDataSet = empty(dataSource);
DBAssert.deltaAssertion(ci, emptyDataSet, emptyDataSet);
}.action(callInfo, argument);
}
} | @SuppressWarnings("javadoc")
private static void multipleUnchangedAssertions(CallInfo callInfo, DataSource[] dataSources) {
HashSet<DataSource> set = new HashSet<>();
for (T object : dataSources) {
if (!set.add(Function.identity().apply(object))) {
throw new InvalidOperationException("Repeated data source in call!");
}
}
<DeepExtract>
if (dataSources == null || dataSources.length == 0) {
throw new InvalidOperationException("Empty or null array!");
}
for (T argument : dataSources) {
(ci, dataSource) -> {
DataSet emptyDataSet = empty(dataSource);
DBAssert.deltaAssertion(ci, emptyDataSet, emptyDataSet);
}.action(callInfo, argument);
}
</DeepExtract>
} | jdbdt | positive | 440,019 |
public boolean onPreferenceChange(final Preference preference, final Object newValue) {
result.setValue((String) newValue);
final Intent i = new Intent();
i.setAction(PREFERENCES_CHANGED_INTENT);
context.sendBroadcast(i);
return false;
} | public boolean onPreferenceChange(final Preference preference, final Object newValue) {
result.setValue((String) newValue);
<DeepExtract>
final Intent i = new Intent();
i.setAction(PREFERENCES_CHANGED_INTENT);
context.sendBroadcast(i);
</DeepExtract>
return false;
} | Humansense-Android-App | positive | 440,022 |
public void testValidDate() throws ValidatorException {
final ValueBean info = new ValueBean();
info.setValue("12/01/2005");
final Validator validator = new Validator(resources, FORM_KEY);
validator.setParameter(Validator.BEAN_PARAM, info);
validator.setParameter(Validator.LOCALE_PARAM, Locale.US);
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult result = results.getValidatorResult("value");
assertNotNull(ACTION + " value ValidatorResult should not be null.", result);
assertTrue(ACTION + " value ValidatorResult should contain the '" + ACTION + "' action.", result.containsAction(ACTION));
assertTrue(ACTION + " value ValidatorResult for the '" + ACTION + "' action should have " + (true ? "passed" : "failed") + ".", (true ? result.isValid(ACTION) : !result.isValid(ACTION)));
} | public void testValidDate() throws ValidatorException {
final ValueBean info = new ValueBean();
info.setValue("12/01/2005");
<DeepExtract>
final Validator validator = new Validator(resources, FORM_KEY);
validator.setParameter(Validator.BEAN_PARAM, info);
validator.setParameter(Validator.LOCALE_PARAM, Locale.US);
final ValidatorResults results = validator.validate();
assertNotNull("Results are null.", results);
final ValidatorResult result = results.getValidatorResult("value");
assertNotNull(ACTION + " value ValidatorResult should not be null.", result);
assertTrue(ACTION + " value ValidatorResult should contain the '" + ACTION + "' action.", result.containsAction(ACTION));
assertTrue(ACTION + " value ValidatorResult for the '" + ACTION + "' action should have " + (true ? "passed" : "failed") + ".", (true ? result.isValid(ACTION) : !result.isValid(ACTION)));
</DeepExtract>
} | commons-validator | positive | 440,023 |
public Post withCategories(List<Long> categories) {
this.categories = categories;
return this;
} | public Post withCategories(List<Long> categories) {
<DeepExtract>
this.categories = categories;
</DeepExtract>
return this;
} | wp-api-v2-client-android | positive | 440,024 |
@Override
public void spawnGlitterParticles(World worldObj, double x, double y, double z, double velocityX, double velocityY, double velocityZ, int count, int color, float scale) {
Minecraft.getMinecraft().effectRenderer.addEffect(new ParticleFluidXP(worldObj, x, y, z, velocityX, velocityY, velocityZ, count, color, scale));
} | @Override
public void spawnGlitterParticles(World worldObj, double x, double y, double z, double velocityX, double velocityY, double velocityZ, int count, int color, float scale) {
<DeepExtract>
Minecraft.getMinecraft().effectRenderer.addEffect(new ParticleFluidXP(worldObj, x, y, z, velocityX, velocityY, velocityZ, count, color, scale));
</DeepExtract>
} | Mob-Grinding-Utils | positive | 440,025 |
private void shutdown() {
for (JarFile jarFile : _lstJarFile) {
try {
jarFile.close();
} catch (IOException e) {
}
}
String sPersistentFile = System.getProperty("user.home") + File.separator + ".JarClassLoader";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(sPersistentFile));
String sLine;
while ((sLine = reader.readLine()) != null) {
File file = new File(sLine);
if (!file.exists()) {
continue;
}
if (!file.delete()) {
hsNativeFile.add(file);
}
}
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(sPersistentFile));
for (File fileNative : hsNativeFile) {
writer.write(fileNative.getCanonicalPath());
writer.newLine();
fileNative.delete();
}
} catch (IOException e) {
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
} | private void shutdown() {
for (JarFile jarFile : _lstJarFile) {
try {
jarFile.close();
} catch (IOException e) {
}
}
String sPersistentFile = System.getProperty("user.home") + File.separator + ".JarClassLoader";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(sPersistentFile));
String sLine;
while ((sLine = reader.readLine()) != null) {
File file = new File(sLine);
if (!file.exists()) {
continue;
}
if (!file.delete()) {
hsNativeFile.add(file);
}
}
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
<DeepExtract>
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(sPersistentFile));
for (File fileNative : hsNativeFile) {
writer.write(fileNative.getCanonicalPath());
writer.newLine();
fileNative.delete();
}
} catch (IOException e) {
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
</DeepExtract>
} | DiffKit | positive | 440,026 |
private void valueItalicActionPerformed(java.awt.event.ActionEvent evt) {
String fType = (String) fontTypes.getSelectedItem();
int fSize = (Integer) fontSize.getValue();
Font font = new Font(fType, Font.PLAIN, fSize);
if (valueBold.isSelected() && !valueItalic.isSelected()) {
font = font.deriveFont(Font.BOLD);
} else if (!valueBold.isSelected() && valueItalic.isSelected()) {
font = font.deriveFont(Font.ITALIC);
} else if (valueBold.isSelected() && valueItalic.isSelected()) {
font = font.deriveFont(Font.ITALIC + Font.BOLD);
}
valuePreview.setFont(font);
valuePreview.setForeground(valueColor.getBackground());
} | private void valueItalicActionPerformed(java.awt.event.ActionEvent evt) {
<DeepExtract>
String fType = (String) fontTypes.getSelectedItem();
int fSize = (Integer) fontSize.getValue();
Font font = new Font(fType, Font.PLAIN, fSize);
if (valueBold.isSelected() && !valueItalic.isSelected()) {
font = font.deriveFont(Font.BOLD);
} else if (!valueBold.isSelected() && valueItalic.isSelected()) {
font = font.deriveFont(Font.ITALIC);
} else if (valueBold.isSelected() && valueItalic.isSelected()) {
font = font.deriveFont(Font.ITALIC + Font.BOLD);
}
valuePreview.setFont(font);
valuePreview.setForeground(valueColor.getBackground());
</DeepExtract>
} | portugol | positive | 440,027 |
public DbModel findDbModelFirst(DbModelSelector selector) throws DbException {
if (!tableIsExist(selector.getEntityType()))
return null;
Cursor cursor;
debugSql(selector.limit(1).toString().getSql());
try {
cursor = database.rawQuery(selector.limit(1).toString().getSql(), selector.limit(1).toString().getBindArgsAsStrArray());
} catch (Throwable e) {
throw new DbException(e);
}
if (cursor != null) {
try {
if (cursor.moveToNext()) {
return CursorUtils.getDbModel(cursor);
}
} catch (Throwable e) {
throw new DbException(e);
} finally {
Utils.closeQuietly(cursor);
}
}
return null;
} | public DbModel findDbModelFirst(DbModelSelector selector) throws DbException {
if (!tableIsExist(selector.getEntityType()))
return null;
<DeepExtract>
Cursor cursor;
debugSql(selector.limit(1).toString().getSql());
try {
cursor = database.rawQuery(selector.limit(1).toString().getSql(), selector.limit(1).toString().getBindArgsAsStrArray());
} catch (Throwable e) {
throw new DbException(e);
}
</DeepExtract>
if (cursor != null) {
try {
if (cursor.moveToNext()) {
return CursorUtils.getDbModel(cursor);
}
} catch (Throwable e) {
throw new DbException(e);
} finally {
Utils.closeQuietly(cursor);
}
}
return null;
} | volley | positive | 440,028 |
@Deprecated
public SeriesDefaults createSeriesDefaults() {
if (seriesDefaults == null) {
seriesDefaults = new SeriesDefaults();
}
return seriesDefaults;
} | @Deprecated
public SeriesDefaults createSeriesDefaults() {
<DeepExtract>
if (seriesDefaults == null) {
seriesDefaults = new SeriesDefaults();
}
return seriesDefaults;
</DeepExtract>
} | jqplot4java | positive | 440,030 |
@Override
public Event apply(@Nullable GenericRecord rec) {
this.i += 1;
boolean useURI = (i % 2) == 0;
Map<String, String> headers = Maps.newHashMap();
if (useURI) {
headers.put(DatasetSinkConstants.AVRO_SCHEMA_URL_HEADER, SCHEMA_FILE.getAbsoluteFile().toURI().toString());
} else {
headers.put(DatasetSinkConstants.AVRO_SCHEMA_LITERAL_HEADER, RECORD_SCHEMA.toString());
}
Event e = new SimpleEvent();
e.setBody(serialize(rec, RECORD_SCHEMA));
e.setHeaders(headers);
return e;
} | @Override
public Event apply(@Nullable GenericRecord rec) {
this.i += 1;
boolean useURI = (i % 2) == 0;
<DeepExtract>
Map<String, String> headers = Maps.newHashMap();
if (useURI) {
headers.put(DatasetSinkConstants.AVRO_SCHEMA_URL_HEADER, SCHEMA_FILE.getAbsoluteFile().toURI().toString());
} else {
headers.put(DatasetSinkConstants.AVRO_SCHEMA_LITERAL_HEADER, RECORD_SCHEMA.toString());
}
Event e = new SimpleEvent();
e.setBody(serialize(rec, RECORD_SCHEMA));
e.setHeaders(headers);
return e;
</DeepExtract>
} | JavaBigData | positive | 440,031 |
private void buildHist(int nid) throws Mp4jException {
smallLeafGradSum = histBuilder.buildHist(position.getNodeSampleInterval().get(nid), position.getPosAndSampleIndex(), trainData, feaIndex, groupId, smallLeafGradSum, timeStats.buildDetail);
return histPool.setHist(nid, smallLeafGradSum);
} | private void buildHist(int nid) throws Mp4jException {
<DeepExtract>
smallLeafGradSum = histBuilder.buildHist(position.getNodeSampleInterval().get(nid), position.getPosAndSampleIndex(), trainData, feaIndex, groupId, smallLeafGradSum, timeStats.buildDetail);
return histPool.setHist(nid, smallLeafGradSum);
</DeepExtract>
} | ytk-learn | positive | 440,033 |
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "That didn't work! error=" + error);
Log.i(TAG, "parseProvisioningData()");
try {
JSONObject dataForRegion;
JSONObject jsonObject = new JSONObject(getLocalProvisioningData());
Log.d(TAG, "jsonObject=" + jsonObject);
JSONObject regions = jsonObject.getJSONObject("regions");
Log.d(TAG, "regions=" + regions);
Log.d(TAG, "mDmeHostname=" + meHelper.mDmeHostname);
if (regions.has(meHelper.mDmeHostname)) {
Log.d(TAG, "getting region data for " + meHelper.mDmeHostname);
dataForRegion = regions.getJSONObject(meHelper.mDmeHostname);
} else {
Log.d(TAG, "getting region data for default");
dataForRegion = regions.getJSONObject("default");
}
JSONObject defaultHostNames = dataForRegion.getJSONObject("defaultHostNames");
mDefaultHostCloud = defaultHostNames.getString("cloud");
mDefaultHostEdge = defaultHostNames.getString("edge");
Log.i(TAG, "mDefaultHostCloud = " + mDefaultHostCloud);
Log.i(TAG, "mDefaultHostEdge = " + mDefaultHostEdge);
startImageSenders();
} catch (JSONException e) {
Log.e(TAG, "Error parsing JSON", e);
if (true) {
new androidx.appcompat.app.AlertDialog.Builder(getContext()).setTitle("Error in provisioning data").setMessage("Unable to parse JSON string. Please alert MobiledgeX support.").setPositiveButton("OK", null).show();
} else {
Log.w(TAG, "Online version of provisioning data failed to parse. Using local copy.");
parseProvisioningData(getLocalProvisioningData(), true);
}
}
} | @Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "That didn't work! error=" + error);
<DeepExtract>
Log.i(TAG, "parseProvisioningData()");
try {
JSONObject dataForRegion;
JSONObject jsonObject = new JSONObject(getLocalProvisioningData());
Log.d(TAG, "jsonObject=" + jsonObject);
JSONObject regions = jsonObject.getJSONObject("regions");
Log.d(TAG, "regions=" + regions);
Log.d(TAG, "mDmeHostname=" + meHelper.mDmeHostname);
if (regions.has(meHelper.mDmeHostname)) {
Log.d(TAG, "getting region data for " + meHelper.mDmeHostname);
dataForRegion = regions.getJSONObject(meHelper.mDmeHostname);
} else {
Log.d(TAG, "getting region data for default");
dataForRegion = regions.getJSONObject("default");
}
JSONObject defaultHostNames = dataForRegion.getJSONObject("defaultHostNames");
mDefaultHostCloud = defaultHostNames.getString("cloud");
mDefaultHostEdge = defaultHostNames.getString("edge");
Log.i(TAG, "mDefaultHostCloud = " + mDefaultHostCloud);
Log.i(TAG, "mDefaultHostEdge = " + mDefaultHostEdge);
startImageSenders();
} catch (JSONException e) {
Log.e(TAG, "Error parsing JSON", e);
if (true) {
new androidx.appcompat.app.AlertDialog.Builder(getContext()).setTitle("Error in provisioning data").setMessage("Unable to parse JSON string. Please alert MobiledgeX support.").setPositiveButton("OK", null).show();
} else {
Log.w(TAG, "Online version of provisioning data failed to parse. Using local copy.");
parseProvisioningData(getLocalProvisioningData(), true);
}
}
</DeepExtract>
} | edge-cloud-sampleapps | positive | 440,034 |
public void deleteAllRecords() {
mContext.getContentResolver().delete(FilmContract.MoviesEntry.CONTENT_URI, null, null);
mContext.getContentResolver().delete(FilmContract.CastEntry.CONTENT_URI, null, null);
Cursor cursor = mContext.getContentResolver().query(FilmContract.MoviesEntry.CONTENT_URI, null, null, null, null);
assertEquals("Error: Records not deleted from Weather table during delete", 0, cursor.getCount());
cursor.close();
cursor = mContext.getContentResolver().query(FilmContract.CastEntry.CONTENT_URI, null, null, null, null);
assertEquals("Error: Records not deleted from Location table during delete", 0, cursor.getCount());
cursor.close();
} | public void deleteAllRecords() {
<DeepExtract>
mContext.getContentResolver().delete(FilmContract.MoviesEntry.CONTENT_URI, null, null);
mContext.getContentResolver().delete(FilmContract.CastEntry.CONTENT_URI, null, null);
Cursor cursor = mContext.getContentResolver().query(FilmContract.MoviesEntry.CONTENT_URI, null, null, null, null);
assertEquals("Error: Records not deleted from Weather table during delete", 0, cursor.getCount());
cursor.close();
cursor = mContext.getContentResolver().query(FilmContract.CastEntry.CONTENT_URI, null, null, null, null);
assertEquals("Error: Records not deleted from Location table during delete", 0, cursor.getCount());
cursor.close();
</DeepExtract>
} | Filmy | positive | 440,036 |
@Test
public void genotypeTest2() throws IOException {
File wd = tmpFolder.newFolder("tmp");
String truthVcf = new File("src/test/resources/validationTest/genotypeTest2", "truth.vcf").toString();
String vcfForCompare = new File("src/test/resources/validationTest/genotypeTest2", "compare.vcf").toString();
String expectedFalseNegative = new File("src/test/resources/validationTest/genotypeTest2", "test_FN.vcf").toString();
String expectedFalsePositive = new File("src/test/resources/validationTest/genotypeTest2", "test_FP.vcf").toString();
String expectedTruePositive = new File("src/test/resources/validationTest/genotypeTest2", "test_TP.vcf").toString();
String expectedUnknownFalsePositive = new File("src/test/resources/validationTest/genotypeTest2", "test_unknown_FP.vcf").toString();
String expectedUnknownTruePositive = new File("src/test/resources/validationTest/genotypeTest2", "test_unknown_TP.vcf").toString();
Path outputFalseNegative = Paths.get(wd.getCanonicalPath(), "test_FN.vcf");
Path outputFalsePositive = Paths.get(wd.getCanonicalPath(), "test_FP.vcf");
Path outputTruePositive = Paths.get(wd.getCanonicalPath(), "test_TP.vcf");
Path outputUnknownFalsePositive = Paths.get(wd.getCanonicalPath(), "test_unknown_FP.vcf");
Path outputUnknownTruePositive = Paths.get(wd.getCanonicalPath(), "test_unknown_TP.vcf");
Path outputJson = Paths.get(wd.getCanonicalPath(), "test_report.json");
String[] args = new String[] { "-true_vcf", truthVcf, "-prefix", Paths.get(wd.getCanonicalPath(), "test").toString(), vcfForCompare };
VCFcompare.main(ArrayUtils.addAll(args, new String[] { "-match_geno" }));
if (updateVCF) {
Files.copy(outputFalseNegative, Paths.get(expectedFalseNegative), StandardCopyOption.REPLACE_EXISTING);
Files.copy(outputFalsePositive, Paths.get(expectedFalsePositive), StandardCopyOption.REPLACE_EXISTING);
Files.copy(outputTruePositive, Paths.get(expectedTruePositive), StandardCopyOption.REPLACE_EXISTING);
Files.copy(outputUnknownTruePositive, Paths.get(expectedUnknownTruePositive), StandardCopyOption.REPLACE_EXISTING);
Files.copy(outputUnknownFalsePositive, Paths.get(expectedUnknownFalsePositive), StandardCopyOption.REPLACE_EXISTING);
}
assertTrue(FileUtils.contentEquals(outputFalseNegative.toFile(), new File(expectedFalseNegative)));
assertTrue(FileUtils.contentEquals(outputFalsePositive.toFile(), new File(expectedFalsePositive)));
assertTrue(FileUtils.contentEquals(outputTruePositive.toFile(), new File(expectedTruePositive)));
assertTrue(FileUtils.contentEquals(outputUnknownFalsePositive.toFile(), new File(expectedUnknownFalsePositive)));
assertTrue(FileUtils.contentEquals(outputUnknownTruePositive.toFile(), new File(expectedUnknownTruePositive)));
} | @Test
public void genotypeTest2() throws IOException {
<DeepExtract>
File wd = tmpFolder.newFolder("tmp");
String truthVcf = new File("src/test/resources/validationTest/genotypeTest2", "truth.vcf").toString();
String vcfForCompare = new File("src/test/resources/validationTest/genotypeTest2", "compare.vcf").toString();
String expectedFalseNegative = new File("src/test/resources/validationTest/genotypeTest2", "test_FN.vcf").toString();
String expectedFalsePositive = new File("src/test/resources/validationTest/genotypeTest2", "test_FP.vcf").toString();
String expectedTruePositive = new File("src/test/resources/validationTest/genotypeTest2", "test_TP.vcf").toString();
String expectedUnknownFalsePositive = new File("src/test/resources/validationTest/genotypeTest2", "test_unknown_FP.vcf").toString();
String expectedUnknownTruePositive = new File("src/test/resources/validationTest/genotypeTest2", "test_unknown_TP.vcf").toString();
Path outputFalseNegative = Paths.get(wd.getCanonicalPath(), "test_FN.vcf");
Path outputFalsePositive = Paths.get(wd.getCanonicalPath(), "test_FP.vcf");
Path outputTruePositive = Paths.get(wd.getCanonicalPath(), "test_TP.vcf");
Path outputUnknownFalsePositive = Paths.get(wd.getCanonicalPath(), "test_unknown_FP.vcf");
Path outputUnknownTruePositive = Paths.get(wd.getCanonicalPath(), "test_unknown_TP.vcf");
Path outputJson = Paths.get(wd.getCanonicalPath(), "test_report.json");
String[] args = new String[] { "-true_vcf", truthVcf, "-prefix", Paths.get(wd.getCanonicalPath(), "test").toString(), vcfForCompare };
VCFcompare.main(ArrayUtils.addAll(args, new String[] { "-match_geno" }));
if (updateVCF) {
Files.copy(outputFalseNegative, Paths.get(expectedFalseNegative), StandardCopyOption.REPLACE_EXISTING);
Files.copy(outputFalsePositive, Paths.get(expectedFalsePositive), StandardCopyOption.REPLACE_EXISTING);
Files.copy(outputTruePositive, Paths.get(expectedTruePositive), StandardCopyOption.REPLACE_EXISTING);
Files.copy(outputUnknownTruePositive, Paths.get(expectedUnknownTruePositive), StandardCopyOption.REPLACE_EXISTING);
Files.copy(outputUnknownFalsePositive, Paths.get(expectedUnknownFalsePositive), StandardCopyOption.REPLACE_EXISTING);
}
assertTrue(FileUtils.contentEquals(outputFalseNegative.toFile(), new File(expectedFalseNegative)));
assertTrue(FileUtils.contentEquals(outputFalsePositive.toFile(), new File(expectedFalsePositive)));
assertTrue(FileUtils.contentEquals(outputTruePositive.toFile(), new File(expectedTruePositive)));
assertTrue(FileUtils.contentEquals(outputUnknownFalsePositive.toFile(), new File(expectedUnknownFalsePositive)));
assertTrue(FileUtils.contentEquals(outputUnknownTruePositive.toFile(), new File(expectedUnknownTruePositive)));
</DeepExtract>
} | varsim | positive | 440,039 |
public void clearFilter() {
if (null == null || null.length() == 0 || null.matches(" +")) {
setFilter((LogFilter) null);
} else {
try {
LogFilter filter = new LogFilter(LoggerPlusPlus.instance.getLibraryController(), null);
setFilter(filter);
} catch (ParseException e) {
logTable.setFilter(null);
JLabel header = new JLabel("Could not parse filter:");
JTextArea errorArea = new JTextArea(e.getMessage());
errorArea.setEditable(false);
JScrollPane errorScroller = new JScrollPane(errorArea);
errorScroller.setBorder(BorderFactory.createEmptyBorder());
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.add(errorScroller, BorderLayout.CENTER);
wrapper.setPreferredSize(new Dimension(600, 300));
JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(logTable), new Component[] { header, wrapper }, "Parse Error", JOptionPane.ERROR_MESSAGE);
formatFilter(null);
}
}
SwingUtilities.invokeLater(() -> {
if (!"".equalsIgnoreCase("")) {
((HistoryField.HistoryComboModel) filterField.getModel()).addToHistory("");
filterField.setSelectedItem("");
} else {
filterField.setSelectedItem(null);
}
});
} | public void clearFilter() {
if (null == null || null.length() == 0 || null.matches(" +")) {
setFilter((LogFilter) null);
} else {
try {
LogFilter filter = new LogFilter(LoggerPlusPlus.instance.getLibraryController(), null);
setFilter(filter);
} catch (ParseException e) {
logTable.setFilter(null);
JLabel header = new JLabel("Could not parse filter:");
JTextArea errorArea = new JTextArea(e.getMessage());
errorArea.setEditable(false);
JScrollPane errorScroller = new JScrollPane(errorArea);
errorScroller.setBorder(BorderFactory.createEmptyBorder());
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.add(errorScroller, BorderLayout.CENTER);
wrapper.setPreferredSize(new Dimension(600, 300));
JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(logTable), new Component[] { header, wrapper }, "Parse Error", JOptionPane.ERROR_MESSAGE);
formatFilter(null);
}
}
<DeepExtract>
SwingUtilities.invokeLater(() -> {
if (!"".equalsIgnoreCase("")) {
((HistoryField.HistoryComboModel) filterField.getModel()).addToHistory("");
filterField.setSelectedItem("");
} else {
filterField.setSelectedItem(null);
}
});
</DeepExtract>
} | LoggerPlusPlus | positive | 440,042 |
public boolean insert(TeamUser teamUser) {
Integer result = teamUserMapper.insert(teamUser);
return result > 0;
} | public boolean insert(TeamUser teamUser) {
Integer result = teamUserMapper.insert(teamUser);
<DeepExtract>
return result > 0;
</DeepExtract>
} | KafkaCenter | positive | 440,043 |
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mIndexItems.length == 0) {
return super.onTouchEvent(event);
}
float eventY = event.getY();
float eventX = event.getX();
mCurrentY = eventY - (getHeight() / 2 - mBarHeight / 2);
if (mCurrentY <= 0) {
mCurrentIndex = 0;
}
int index = (int) (mCurrentY / this.mIndexItemHeight);
if (index >= this.mIndexItems.length) {
index = this.mIndexItems.length - 1;
}
return index;
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mStartTouchingArea.contains(eventX, eventY)) {
mStartTouching = true;
if (!mLazyRespond && onSelectIndexItemListener != null) {
onSelectIndexItemListener.onSelectIndexItem(mIndexItems[mCurrentIndex]);
}
invalidate();
return true;
} else {
mCurrentIndex = -1;
return false;
}
case MotionEvent.ACTION_MOVE:
if (mStartTouching && !mLazyRespond && onSelectIndexItemListener != null) {
onSelectIndexItemListener.onSelectIndexItem(mIndexItems[mCurrentIndex]);
}
invalidate();
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (mLazyRespond && onSelectIndexItemListener != null) {
onSelectIndexItemListener.onSelectIndexItem(mIndexItems[mCurrentIndex]);
}
mCurrentIndex = -1;
mStartTouching = false;
invalidate();
return true;
}
return super.onTouchEvent(event);
} | @Override
public boolean onTouchEvent(MotionEvent event) {
if (mIndexItems.length == 0) {
return super.onTouchEvent(event);
}
float eventY = event.getY();
float eventX = event.getX();
<DeepExtract>
mCurrentY = eventY - (getHeight() / 2 - mBarHeight / 2);
if (mCurrentY <= 0) {
mCurrentIndex = 0;
}
int index = (int) (mCurrentY / this.mIndexItemHeight);
if (index >= this.mIndexItems.length) {
index = this.mIndexItems.length - 1;
}
return index;
</DeepExtract>
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mStartTouchingArea.contains(eventX, eventY)) {
mStartTouching = true;
if (!mLazyRespond && onSelectIndexItemListener != null) {
onSelectIndexItemListener.onSelectIndexItem(mIndexItems[mCurrentIndex]);
}
invalidate();
return true;
} else {
mCurrentIndex = -1;
return false;
}
case MotionEvent.ACTION_MOVE:
if (mStartTouching && !mLazyRespond && onSelectIndexItemListener != null) {
onSelectIndexItemListener.onSelectIndexItem(mIndexItems[mCurrentIndex]);
}
invalidate();
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (mLazyRespond && onSelectIndexItemListener != null) {
onSelectIndexItemListener.onSelectIndexItem(mIndexItems[mCurrentIndex]);
}
mCurrentIndex = -1;
mStartTouching = false;
invalidate();
return true;
}
return super.onTouchEvent(event);
} | RemoteControler | positive | 440,044 |
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
satisfyDependencies();
getPresenter().attachView(this);
if (savedInstanceState != null) {
getPresenter().onRestore(savedInstanceState);
}
new Handler().post(() -> getPresenter().onLoad());
} | @Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
satisfyDependencies();
<DeepExtract>
getPresenter().attachView(this);
</DeepExtract>
if (savedInstanceState != null) {
getPresenter().onRestore(savedInstanceState);
}
new Handler().post(() -> getPresenter().onLoad());
} | clean_app | positive | 440,045 |
private void tokenizeIn(String text, StringBuilder tokenBuilder, List<String> tokens, boolean isRecursiveCall) {
char[] characters = text.toCharArray();
for (int i = 0; i < characters.length; i++) {
char charAt = characters[i];
if (charAt == ' ') {
appendTokenIfValid(tokenBuilder, tokens);
continue;
}
if (charAt != '"' && charAt != '\'') {
tokenBuilder.append(charAt);
continue;
}
String previous = tokenBuilder.toString();
tokenBuilder.setLength(0);
boolean closed = false;
while (++i < characters.length) {
char current = characters[i];
if (current == charAt) {
closed = true;
break;
}
tokenBuilder.append(current);
}
String tokenString = tokenBuilder.toString();
tokenBuilder.setLength(0);
if (closed) {
if (!previous.isEmpty()) {
tokens.add(previous);
}
tokens.add(tokenString);
} else {
tokenBuilder.append(previous);
tokenBuilder.append(charAt);
tokenizeIn(tokenString, tokenBuilder, tokens, true);
if (!isRecursiveCall) {
appendTokenIfValid(tokenBuilder, tokens);
}
}
}
String tokenString = tokenBuilder.toString();
if (!tokenString.isEmpty()) {
tokens.add(tokenString);
tokenBuilder.setLength(0);
}
} | private void tokenizeIn(String text, StringBuilder tokenBuilder, List<String> tokens, boolean isRecursiveCall) {
char[] characters = text.toCharArray();
for (int i = 0; i < characters.length; i++) {
char charAt = characters[i];
if (charAt == ' ') {
appendTokenIfValid(tokenBuilder, tokens);
continue;
}
if (charAt != '"' && charAt != '\'') {
tokenBuilder.append(charAt);
continue;
}
String previous = tokenBuilder.toString();
tokenBuilder.setLength(0);
boolean closed = false;
while (++i < characters.length) {
char current = characters[i];
if (current == charAt) {
closed = true;
break;
}
tokenBuilder.append(current);
}
String tokenString = tokenBuilder.toString();
tokenBuilder.setLength(0);
if (closed) {
if (!previous.isEmpty()) {
tokens.add(previous);
}
tokens.add(tokenString);
} else {
tokenBuilder.append(previous);
tokenBuilder.append(charAt);
tokenizeIn(tokenString, tokenBuilder, tokens, true);
if (!isRecursiveCall) {
appendTokenIfValid(tokenBuilder, tokens);
}
}
}
<DeepExtract>
String tokenString = tokenBuilder.toString();
if (!tokenString.isEmpty()) {
tokens.add(tokenString);
tokenBuilder.setLength(0);
}
</DeepExtract>
} | CommandFlow | positive | 440,046 |
public void insertUpdate(DocumentEvent e) {
String text = getText_();
if (isTextValid(text)) {
hidePopup();
} else {
showPopup(maximumLength > 0 && text.length() > maximumLength);
}
} | public void insertUpdate(DocumentEvent e) {
<DeepExtract>
String text = getText_();
if (isTextValid(text)) {
hidePopup();
} else {
showPopup(maximumLength > 0 && text.length() > maximumLength);
}
</DeepExtract>
} | DJ-Swing-Suite | positive | 440,047 |
@Test
@Ignore("Operation not yet implemented.")
public void queryTest2() throws Exception {
final DatabaseStatistics statistics = new DatabaseStatistics("queryTestConcat2_db");
spark().sql("DROP DATABASE IF EXISTS queryTestConcat2_db CASCADE");
spark().sql("CREATE DATABASE IF NOT EXISTS queryTestConcat2_db");
spark().sql("USE queryTestConcat2_db");
final TripleBean t1 = new TripleBean();
t1.setS("<http://example.org/alice>");
t1.setP("<http://example.org/givenName>");
t1.setO("Alice");
final TripleBean t2 = new TripleBean();
t2.setS("<http://example.org/alice>");
t2.setP("<http://example.org/surname>");
t2.setO("Abc");
final ArrayList<TripleBean> triplesList = new ArrayList<>();
triplesList.add(t1);
triplesList.add(t2);
final Dataset<Row> ttDataset = spark().createDataset(triplesList, triplesEncoder).select("s", "p", "o").orderBy("s", "p", "o");
ttDataset.write().saveAsTable("tripletable");
final loader.Settings loaderSettings = new loader.Settings.Builder("queryTestConcat2_db").withInputPath((System.getProperty("user.dir") + "\\target\\test_output\\ConcatTest").replace('\\', '/')).generateVp().generateWpt().generateIwpt().generateJwptOuter().generateJwptLeftOuter().generateJwptInner().build();
final VerticalPartitioningLoader vpLoader = new VerticalPartitioningLoader(loaderSettings, spark(), statistics);
vpLoader.load();
statistics.computePropertyStatistics(spark());
final WidePropertyTableLoader wptLoader = new WidePropertyTableLoader(loaderSettings, spark(), statistics);
wptLoader.load();
final InverseWidePropertyTableLoader iwptLoader = new InverseWidePropertyTableLoader(loaderSettings, spark(), statistics);
iwptLoader.load();
final JoinedWidePropertyTableLoader jwptOuterLoader = new JoinedWidePropertyTableLoader(loaderSettings, spark(), JoinedWidePropertyTableLoader.JoinType.outer, statistics);
jwptOuterLoader.load();
final JoinedWidePropertyTableLoader jwptLeftOuterLoader = new JoinedWidePropertyTableLoader(loaderSettings, spark(), JoinedWidePropertyTableLoader.JoinType.leftouter, statistics);
jwptLeftOuterLoader.load();
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingTTNodes().usingCharacteristicSets().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
System.out.print("ConcatTest: queryTest2");
expectedResult.printSchema();
expectedResult.show();
nullableActualResult.printSchema();
nullableActualResult.show();
assertDataFrameEquals(expectedResult, nullableActualResult);
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingVPNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingWPTNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingIWPTNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingJWPTOuterNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingJWPTLeftouterNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
} | @Test
@Ignore("Operation not yet implemented.")
public void queryTest2() throws Exception {
final DatabaseStatistics statistics = new DatabaseStatistics("queryTestConcat2_db");
spark().sql("DROP DATABASE IF EXISTS queryTestConcat2_db CASCADE");
spark().sql("CREATE DATABASE IF NOT EXISTS queryTestConcat2_db");
spark().sql("USE queryTestConcat2_db");
final TripleBean t1 = new TripleBean();
t1.setS("<http://example.org/alice>");
t1.setP("<http://example.org/givenName>");
t1.setO("Alice");
final TripleBean t2 = new TripleBean();
t2.setS("<http://example.org/alice>");
t2.setP("<http://example.org/surname>");
t2.setO("Abc");
final ArrayList<TripleBean> triplesList = new ArrayList<>();
triplesList.add(t1);
triplesList.add(t2);
final Dataset<Row> ttDataset = spark().createDataset(triplesList, triplesEncoder).select("s", "p", "o").orderBy("s", "p", "o");
ttDataset.write().saveAsTable("tripletable");
final loader.Settings loaderSettings = new loader.Settings.Builder("queryTestConcat2_db").withInputPath((System.getProperty("user.dir") + "\\target\\test_output\\ConcatTest").replace('\\', '/')).generateVp().generateWpt().generateIwpt().generateJwptOuter().generateJwptLeftOuter().generateJwptInner().build();
final VerticalPartitioningLoader vpLoader = new VerticalPartitioningLoader(loaderSettings, spark(), statistics);
vpLoader.load();
statistics.computePropertyStatistics(spark());
final WidePropertyTableLoader wptLoader = new WidePropertyTableLoader(loaderSettings, spark(), statistics);
wptLoader.load();
final InverseWidePropertyTableLoader iwptLoader = new InverseWidePropertyTableLoader(loaderSettings, spark(), statistics);
iwptLoader.load();
final JoinedWidePropertyTableLoader jwptOuterLoader = new JoinedWidePropertyTableLoader(loaderSettings, spark(), JoinedWidePropertyTableLoader.JoinType.outer, statistics);
jwptOuterLoader.load();
final JoinedWidePropertyTableLoader jwptLeftOuterLoader = new JoinedWidePropertyTableLoader(loaderSettings, spark(), JoinedWidePropertyTableLoader.JoinType.leftouter, statistics);
jwptLeftOuterLoader.load();
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingTTNodes().usingCharacteristicSets().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
System.out.print("ConcatTest: queryTest2");
expectedResult.printSchema();
expectedResult.show();
nullableActualResult.printSchema();
nullableActualResult.show();
assertDataFrameEquals(expectedResult, nullableActualResult);
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingVPNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingWPTNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingIWPTNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingJWPTOuterNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
<DeepExtract>
final Settings settings = new Settings.Builder("queryTestConcat2_db").usingJWPTLeftouterNodes().build();
final ClassLoader classLoader = getClass().getClassLoader();
final Query query = new Query(classLoader.getResource("queryTestConcat2.q").getPath(), statistics, settings);
final StructType schema = DataTypes.createStructType(new StructField[] { DataTypes.createStructField("name", DataTypes.StringType, true) });
final Row row1 = RowFactory.create("Alice", "Abc");
final List<Row> rowList = ImmutableList.of(row1);
final Dataset<Row> expectedResult = spark().createDataFrame(rowList, schema);
final Dataset<Row> actualResult = query.compute(spark().sqlContext()).orderBy("name");
final Dataset<Row> nullableActualResult = sqlContext().createDataFrame(actualResult.collectAsList(), actualResult.schema().asNullable());
assertDataFrameEquals(expectedResult, nullableActualResult);
</DeepExtract>
} | PRoST | positive | 440,050 |
public void setFrontModifier(NLGElement newFrontModifier) {
this.setFeature(InternalFeature.FRONT_MODIFIERS, null);
List<NLGElement> frontModifiers = getFeatureAsElementList(InternalFeature.FRONT_MODIFIERS);
if (frontModifiers == null) {
frontModifiers = new ArrayList<NLGElement>();
}
frontModifiers.add(newFrontModifier);
setFeature(InternalFeature.FRONT_MODIFIERS, frontModifiers);
} | public void setFrontModifier(NLGElement newFrontModifier) {
this.setFeature(InternalFeature.FRONT_MODIFIERS, null);
<DeepExtract>
List<NLGElement> frontModifiers = getFeatureAsElementList(InternalFeature.FRONT_MODIFIERS);
if (frontModifiers == null) {
frontModifiers = new ArrayList<NLGElement>();
}
frontModifiers.add(newFrontModifier);
setFeature(InternalFeature.FRONT_MODIFIERS, frontModifiers);
</DeepExtract>
} | simplenlg | positive | 440,052 |
public static void main(String[] args) throws Exception {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
Credential credential = CredentialsProvider.authorize(httpTransport, jsonFactory);
Storage storage = new Storage.Builder(httpTransport, jsonFactory, credential).setApplicationName("Google-BucketsGetExample/1.0").build();
Storage.Buckets.Get getBucket = storage.buckets().get(BUCKET_NAME);
getBucket.setProjection("full");
return getBucket.execute();
} | public static void main(String[] args) throws Exception {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
Credential credential = CredentialsProvider.authorize(httpTransport, jsonFactory);
Storage storage = new Storage.Builder(httpTransport, jsonFactory, credential).setApplicationName("Google-BucketsGetExample/1.0").build();
<DeepExtract>
Storage.Buckets.Get getBucket = storage.buckets().get(BUCKET_NAME);
getBucket.setProjection("full");
return getBucket.execute();
</DeepExtract>
} | google-api-java-client-samples | positive | 440,053 |
@Override
public void onDataConnectionStateChanged(int state, int networkType) {
handlePhoneStateChange();
} | @Override
public void onDataConnectionStateChanged(int state, int networkType) {
<DeepExtract>
handlePhoneStateChange();
</DeepExtract>
} | AIMSICDL | positive | 440,054 |
public Subscription cancel() throws PagarMeException {
validateId();
final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/cancel", getClassName(), getId()));
final Subscription other = JSONUtils.getAsObject((JsonObject) request.execute(), Subscription.class);
super.copy(other);
this.plan = other.getPlan();
this.currentTransaction = other.getCurrentTransaction();
this.postbackUrl = other.getPostbackUrl();
this.currentPeriodStart = other.getCurrentPeriodStart();
this.currentPeriodEnd = other.getCurrentPeriodEnd();
this.charges = other.getCharges();
this.status = other.getStatus();
this.metadata = other.getMetadata();
this.customer = other.getCustomer();
this.paymentMethod = other.getPaymentMethod();
this.splitRules = other.getSplitRules();
this.softDescriptor = other.getSoftDescriptor();
this.phone = other.getPhone();
this.address = other.getAddress();
this.card = other.getCard();
this.settledCharges = other.getSettledCharges();
flush();
return other;
} | public Subscription cancel() throws PagarMeException {
validateId();
final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/cancel", getClassName(), getId()));
final Subscription other = JSONUtils.getAsObject((JsonObject) request.execute(), Subscription.class);
<DeepExtract>
super.copy(other);
this.plan = other.getPlan();
this.currentTransaction = other.getCurrentTransaction();
this.postbackUrl = other.getPostbackUrl();
this.currentPeriodStart = other.getCurrentPeriodStart();
this.currentPeriodEnd = other.getCurrentPeriodEnd();
this.charges = other.getCharges();
this.status = other.getStatus();
this.metadata = other.getMetadata();
this.customer = other.getCustomer();
this.paymentMethod = other.getPaymentMethod();
this.splitRules = other.getSplitRules();
this.softDescriptor = other.getSoftDescriptor();
this.phone = other.getPhone();
this.address = other.getAddress();
this.card = other.getCard();
this.settledCharges = other.getSettledCharges();
</DeepExtract>
flush();
return other;
} | pagarme-java | positive | 440,056 |
public DissectorTester expectAbsentDouble(String fieldname) {
if (pathPrefix.isEmpty()) {
fieldname = fieldname;
}
return PREFIX_INSERTER.matcher(fieldname).replaceAll(pathPrefix);
expectedAbsentDoubles.add(fieldname);
try {
parser.addParseTarget(TestRecord.class.getMethod("setDoubleValue", String.class, Double.class), fieldname);
} catch (NoSuchMethodException e) {
e.printStackTrace();
fail(e.getMessage());
}
return this;
} | public DissectorTester expectAbsentDouble(String fieldname) {
if (pathPrefix.isEmpty()) {
fieldname = fieldname;
}
return PREFIX_INSERTER.matcher(fieldname).replaceAll(pathPrefix);
expectedAbsentDoubles.add(fieldname);
<DeepExtract>
try {
parser.addParseTarget(TestRecord.class.getMethod("setDoubleValue", String.class, Double.class), fieldname);
} catch (NoSuchMethodException e) {
e.printStackTrace();
fail(e.getMessage());
}
</DeepExtract>
return this;
} | logparser | positive | 440,058 |
protected void insertRefinedPayload() throws Exception {
final TestRunner runner = TestRunners.newTestRunner(new StoreInMongo());
HashMap<String, String> props = new HashMap<>();
runner.addControllerService(MONGO_CONTROLLER_SERVICE, mongo, props);
runner.setProperty(MongoProps.MONGO_SERVICE, MONGO_CONTROLLER_SERVICE);
runner.enableControllerService(mongo);
runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
runner.setProperty(MongoProps.COLLECTION, "insert_test");
String contents = FileUtils.readFileToString(Paths.get("src/test/resources/mongo/query_payload.json").toFile());
runner.enqueue(contents.getBytes());
runner.run();
} | protected void insertRefinedPayload() throws Exception {
final TestRunner runner = TestRunners.newTestRunner(new StoreInMongo());
<DeepExtract>
HashMap<String, String> props = new HashMap<>();
runner.addControllerService(MONGO_CONTROLLER_SERVICE, mongo, props);
runner.setProperty(MongoProps.MONGO_SERVICE, MONGO_CONTROLLER_SERVICE);
runner.enableControllerService(mongo);
</DeepExtract>
runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
runner.setProperty(MongoProps.COLLECTION, "insert_test");
String contents = FileUtils.readFileToString(Paths.get("src/test/resources/mongo/query_payload.json").toFile());
runner.enqueue(contents.getBytes());
runner.run();
} | nifi-nar-bundles | positive | 440,059 |
public void powerOn() {
screen.powerOn();
speaker.powerOn();
awtControls.powerOn();
if (currentConsole.cartridgeSocket().inserted() != null)
return;
loadCartridgeProvided();
if (cartridgeProvided != null)
currentConsole.cartridgeSocket().insert(cartridgeProvided, true);
if (currentConsole.cartridgeSocket().inserted() != null && !currentConsole.powerOn)
currentConsole.powerOn();
} | public void powerOn() {
screen.powerOn();
speaker.powerOn();
awtControls.powerOn();
<DeepExtract>
if (currentConsole.cartridgeSocket().inserted() != null)
return;
loadCartridgeProvided();
if (cartridgeProvided != null)
currentConsole.cartridgeSocket().insert(cartridgeProvided, true);
</DeepExtract>
if (currentConsole.cartridgeSocket().inserted() != null && !currentConsole.powerOn)
currentConsole.powerOn();
} | javatari | positive | 440,060 |
@Override
public JsonNode createNull() {
if (null == null) {
return JsonNodeFactory.instance.nullNode();
} else {
return null;
}
} | @Override
public JsonNode createNull() {
<DeepExtract>
if (null == null) {
return JsonNodeFactory.instance.nullNode();
} else {
return null;
}
</DeepExtract>
} | jmespath-java | positive | 440,061 |
private void addNotFilter(@Nonnull FilterBy filter) {
if (this.filter == null) {
this.filter = new NOTFilter(filter);
return;
}
if (this.filter instanceof ANDFilter) {
((ANDFilter) this.filter).addFilter(new NOTFilter(filter));
}
ANDFilter newFilter = new ANDFilter(new ArrayList<>(Arrays.asList(this.filter, new NOTFilter(filter))));
this.filter = newFilter;
} | private void addNotFilter(@Nonnull FilterBy filter) {
<DeepExtract>
if (this.filter == null) {
this.filter = new NOTFilter(filter);
return;
}
if (this.filter instanceof ANDFilter) {
((ANDFilter) this.filter).addFilter(new NOTFilter(filter));
}
ANDFilter newFilter = new ANDFilter(new ArrayList<>(Arrays.asList(this.filter, new NOTFilter(filter))));
this.filter = newFilter;
</DeepExtract>
} | aem-easy-content-upgrade | positive | 440,062 |
public static List<PKLocationBuilder> toLocationBuilderList(List<PKLocation> locations) {
if (isEmpty(locations)) {
return Collections.emptyList();
}
return locations.stream().map(PKLocation::builder).collect(Collectors.toCollection(CopyOnWriteArrayList::new));
} | public static List<PKLocationBuilder> toLocationBuilderList(List<PKLocation> locations) {
<DeepExtract>
if (isEmpty(locations)) {
return Collections.emptyList();
}
return locations.stream().map(PKLocation::builder).collect(Collectors.toCollection(CopyOnWriteArrayList::new));
</DeepExtract>
} | jpasskit | positive | 440,064 |
private static JmxMonitorMBean start(ScalecubeServiceDiscovery instance) throws Exception {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance);
discovery.listen().subscribe(this::onDiscoveryEvent);
ObjectName objectName = new ObjectName(String.format(OBJECT_NAME_FORMAT, instance.cluster.member().id(), System.nanoTime()));
StandardMBean standardMBean = new StandardMBean(jmxMBean, MonitorMBean.class);
mbeanServer.registerMBean(standardMBean, objectName);
return jmxMBean;
} | private static JmxMonitorMBean start(ScalecubeServiceDiscovery instance) throws Exception {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance);
<DeepExtract>
discovery.listen().subscribe(this::onDiscoveryEvent);
</DeepExtract>
ObjectName objectName = new ObjectName(String.format(OBJECT_NAME_FORMAT, instance.cluster.member().id(), System.nanoTime()));
StandardMBean standardMBean = new StandardMBean(jmxMBean, MonitorMBean.class);
mbeanServer.registerMBean(standardMBean, objectName);
return jmxMBean;
} | scalecube-services | positive | 440,065 |
@SuppressWarnings("unchecked")
public static <T> T[] remove(final T[] array, final int index) {
int length;
if (array == null) {
length = 0;
} else {
length = Array.getLength(array);
}
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
}
Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);
System.arraycopy(array, 0, result, 0, index);
if (index < length - 1) {
System.arraycopy(array, index + 1, result, index, length - index - 1);
}
return (T[]) result;
} | @SuppressWarnings("unchecked")
public static <T> T[] remove(final T[] array, final int index) {
<DeepExtract>
int length;
if (array == null) {
length = 0;
} else {
length = Array.getLength(array);
}
</DeepExtract>
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
}
Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);
System.arraycopy(array, 0, result, 0, index);
if (index < length - 1) {
System.arraycopy(array, index + 1, result, index, length - index - 1);
}
return (T[]) result;
} | btree4j | positive | 440,067 |
public void onRestoreInstanceState(Bundle savedInstanceState) {
final Bundle dialogHierarchyState = savedInstanceState.getBundle(DIALOG_HIERARCHY_TAG);
if (dialogHierarchyState == null) {
return;
}
if (!mCreated) {
onCreate(savedInstanceState);
mCreated = true;
}
mWindow.restoreHierarchyState(dialogHierarchyState);
if (savedInstanceState.getBoolean(DIALOG_SHOWING_TAG)) {
show();
}
} | public void onRestoreInstanceState(Bundle savedInstanceState) {
final Bundle dialogHierarchyState = savedInstanceState.getBundle(DIALOG_HIERARCHY_TAG);
if (dialogHierarchyState == null) {
return;
}
<DeepExtract>
if (!mCreated) {
onCreate(savedInstanceState);
mCreated = true;
}
</DeepExtract>
mWindow.restoreHierarchyState(dialogHierarchyState);
if (savedInstanceState.getBoolean(DIALOG_SHOWING_TAG)) {
show();
}
} | PreferenceFragment | positive | 440,068 |
@Override
public void onCameraError(@NonNull CameraException exception) {
try {
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M || notificationManager.isNotificationPolicyAccessGranted()) {
AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mgr.setStreamMute(AudioManager.STREAM_SYSTEM, !true);
}
} catch (SecurityException e) {
Crashlytics.logException(e);
}
} | @Override
public void onCameraError(@NonNull CameraException exception) {
<DeepExtract>
try {
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M || notificationManager.isNotificationPolicyAccessGranted()) {
AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mgr.setStreamMute(AudioManager.STREAM_SYSTEM, !true);
}
} catch (SecurityException e) {
Crashlytics.logException(e);
}
</DeepExtract>
} | Rando-android | positive | 440,070 |
@Override
public void withParameter(String name, float value) {
if (name == null || name.trim().isEmpty()) {
throw new DescriptorBuilderException("a valid parameter name is required");
}
if (value == null) {
throw new DescriptorBuilderException("parameter values cannot be null");
}
if (parameters.containsKey(name)) {
throw new DescriptorBuilderException("duplicate annotation parameter name found: " + name);
}
parameters.put(name, value);
} | @Override
public void withParameter(String name, float value) {
<DeepExtract>
if (name == null || name.trim().isEmpty()) {
throw new DescriptorBuilderException("a valid parameter name is required");
}
if (value == null) {
throw new DescriptorBuilderException("parameter values cannot be null");
}
if (parameters.containsKey(name)) {
throw new DescriptorBuilderException("duplicate annotation parameter name found: " + name);
}
parameters.put(name, value);
</DeepExtract>
} | Flapi | positive | 440,071 |
public static DateOnlyCalendar today() {
if (System.currentTimeMillis() < 0) {
return null;
}
DateOnlyCalendar dateOnlyCalendar = DateOnlyCalendar.obtain();
dateOnlyCalendar.setTimeInMillis(System.currentTimeMillis());
dateOnlyCalendar.stripTime();
dateOnlyCalendar.setFirstDayOfWeek(sWeekStart);
return dateOnlyCalendar;
} | public static DateOnlyCalendar today() {
<DeepExtract>
if (System.currentTimeMillis() < 0) {
return null;
}
DateOnlyCalendar dateOnlyCalendar = DateOnlyCalendar.obtain();
dateOnlyCalendar.setTimeInMillis(System.currentTimeMillis());
dateOnlyCalendar.stripTime();
dateOnlyCalendar.setFirstDayOfWeek(sWeekStart);
return dateOnlyCalendar;
</DeepExtract>
} | ToDay | positive | 440,074 |
public static WebSocketFrame createTextFrame(String payload) {
if (payload != null && payload.length == 0) {
payload = null;
}
mPayload = payload;
return this;
} | public static WebSocketFrame createTextFrame(String payload) {
<DeepExtract>
if (payload != null && payload.length == 0) {
payload = null;
}
mPayload = payload;
return this;
</DeepExtract>
} | nv-websocket-client | positive | 440,075 |
@Override
public void onChanged(@Nullable List<CityInfoData> cityInfoData) {
if (Check.isEmpty(cityInfoData)) {
mEmptyView.setVisibility(View.VISIBLE);
} else {
mEmptyView.setVisibility(View.GONE);
mSearchResultAdapter.setData(cityInfoData);
}
} | @Override
public void onChanged(@Nullable List<CityInfoData> cityInfoData) {
<DeepExtract>
if (Check.isEmpty(cityInfoData)) {
mEmptyView.setVisibility(View.VISIBLE);
} else {
mEmptyView.setVisibility(View.GONE);
mSearchResultAdapter.setData(cityInfoData);
}
</DeepExtract>
} | KnowWeather | positive | 440,077 |
public void handleActionMethod(ActionEvent event) throws AbortProcessingException {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Method expression listener called"));
} | public void handleActionMethod(ActionEvent event) throws AbortProcessingException {
<DeepExtract>
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Method expression listener called"));
</DeepExtract>
} | showcase | positive | 440,079 |
public SymmetricZrElement mul(int z) {
this.value = this.value.mod(order);
return mod();
if (this.value.compareTo(halfOrder) > 0)
this.value = this.value.subtract(order);
return this;
} | public SymmetricZrElement mul(int z) {
this.value = this.value.mod(order);
return mod();
<DeepExtract>
if (this.value.compareTo(halfOrder) > 0)
this.value = this.value.subtract(order);
return this;
</DeepExtract>
} | jlbc | positive | 440,080 |
private void handleUploadError(VolleyError error) {
Log.d(TAG, "Network error: " + error.getMessage(), error.getCause());
JSONObject responseData = null;
if (error.networkResponse != null && error.networkResponse.data != null) {
try {
responseData = new JSONObject(new String(error.networkResponse.data, "UTF-8"));
} catch (UnsupportedEncodingException | JSONException e) {
Log.w(TAG, "handleUploadError: couldn't convert response data to JSON\n", e);
}
}
setState(State.READY_TO_UPLOAD);
uploadStatus.setText(getErrorMessageFromResponseData(responseData));
updateRemainingUploads();
} | private void handleUploadError(VolleyError error) {
Log.d(TAG, "Network error: " + error.getMessage(), error.getCause());
JSONObject responseData = null;
if (error.networkResponse != null && error.networkResponse.data != null) {
try {
responseData = new JSONObject(new String(error.networkResponse.data, "UTF-8"));
} catch (UnsupportedEncodingException | JSONException e) {
Log.w(TAG, "handleUploadError: couldn't convert response data to JSON\n", e);
}
}
<DeepExtract>
setState(State.READY_TO_UPLOAD);
uploadStatus.setText(getErrorMessageFromResponseData(responseData));
updateRemainingUploads();
</DeepExtract>
} | Awful.apk | positive | 440,082 |
public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
Map<List<Integer>, Integer> dp = new HashMap<>();
List<Integer> allZero = new ArrayList<>();
for (int i = 0; i < needs.size(); i++) {
allZero.add(0);
}
dp.put(allZero, 0);
if (dp.containsKey(needs))
return dp.get(needs);
int res = Integer.MAX_VALUE;
for (List<Integer> s : special) {
List<Integer> needsCopy = new ArrayList<>(needs);
boolean valid = true;
for (int i = 0; i < needs.size(); i++) {
needsCopy.set(i, needsCopy.get(i) - s.get(i));
if (needsCopy.get(i) < 0) {
valid = false;
break;
}
}
if (valid) {
res = Math.min(res, s.get(needs.size()) + dfs(needsCopy, price, special, dp));
}
}
int noSpecial = 0;
for (int i = 0; i < needs.size(); i++) {
noSpecial += needs.get(i) * price.get(i);
}
res = Math.min(res, noSpecial);
dp.put(needs, res);
return res;
} | public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
Map<List<Integer>, Integer> dp = new HashMap<>();
List<Integer> allZero = new ArrayList<>();
for (int i = 0; i < needs.size(); i++) {
allZero.add(0);
}
dp.put(allZero, 0);
<DeepExtract>
if (dp.containsKey(needs))
return dp.get(needs);
int res = Integer.MAX_VALUE;
for (List<Integer> s : special) {
List<Integer> needsCopy = new ArrayList<>(needs);
boolean valid = true;
for (int i = 0; i < needs.size(); i++) {
needsCopy.set(i, needsCopy.get(i) - s.get(i));
if (needsCopy.get(i) < 0) {
valid = false;
break;
}
}
if (valid) {
res = Math.min(res, s.get(needs.size()) + dfs(needsCopy, price, special, dp));
}
}
int noSpecial = 0;
for (int i = 0; i < needs.size(); i++) {
noSpecial += needs.get(i) * price.get(i);
}
res = Math.min(res, noSpecial);
dp.put(needs, res);
return res;
</DeepExtract>
} | Leetcode-for-Fun | positive | 440,083 |
private void layout(final long timeNow) {
double displayedRank = scrolledRank;
for (RankAnimation anim : scrollAnimation) {
displayedRank += slerp((anim.toRank() - anim.fromRank()) * -1.0, 0.0, anim.progress(timeNow));
}
if (displayedRank < minScrolledRank)
displayedRank = minScrolledRank;
if (displayedRank > maxScrolledRank)
displayedRank = maxScrolledRank;
return displayedRank;
screen.y = (float) ((displayedRank + visibleRowsBelow) * (rowHeight + cellMargin) + cellMargin);
List<RankAnimation> moveAnims = new ArrayList<>(moveAnimation);
Collections.reverse(moveAnims);
for (int rowIndex = ranklist.getRows().size(); rowIndex-- > 0; ) {
final ScoreboardRow row = ranklist.getRow(rowIndex);
double effectiveRank = row.getRank();
long rankForAnim = row.getRank();
for (RankAnimation anim : moveAnims) {
double factor = 0.0;
if (rankForAnim == anim.toRank()) {
effectiveRank += slerp(anim.fromRank() - anim.toRank(), 0.0, anim.progress(timeNow));
rankForAnim += anim.fromRank() - anim.toRank();
} else if (anim.fromRank() >= rankForAnim && rankForAnim >= anim.toRank()) {
effectiveRank += 1.0 * slerp(-1.0, 0.0, anim.progress(timeNow));
rankForAnim -= 1;
}
}
final Layout rowLayout = rowLayouts.get(row.getTeamId());
rowLayout.relX = 0.0f;
rowLayout.relY = (float) (screen.y - effectiveRank * (rowHeight + cellMargin) - cellMargin) - cellMargin / 2.0f;
rowLayout.width = (float) screen.width;
rowLayout.height = (float) rowHeight + cellMargin;
final Layout scoreLayout = rowLayout.children().get(0);
scoreLayout.relX = (float) (teamLabelWidth + (screen.width - teamLabelWidth - rowWidth) / 1.0f);
scoreLayout.relY = (float) cellMargin;
scoreLayout.width = (float) rowWidth;
scoreLayout.height = (float) rowHeight;
}
rootLayout.layout();
if (particles != null) {
particles.setOffset(0.0, screen.y);
particles.update(timeNow);
}
} | private void layout(final long timeNow) {
double displayedRank = scrolledRank;
for (RankAnimation anim : scrollAnimation) {
displayedRank += slerp((anim.toRank() - anim.fromRank()) * -1.0, 0.0, anim.progress(timeNow));
}
<DeepExtract>
if (displayedRank < minScrolledRank)
displayedRank = minScrolledRank;
if (displayedRank > maxScrolledRank)
displayedRank = maxScrolledRank;
return displayedRank;
</DeepExtract>
screen.y = (float) ((displayedRank + visibleRowsBelow) * (rowHeight + cellMargin) + cellMargin);
List<RankAnimation> moveAnims = new ArrayList<>(moveAnimation);
Collections.reverse(moveAnims);
for (int rowIndex = ranklist.getRows().size(); rowIndex-- > 0; ) {
final ScoreboardRow row = ranklist.getRow(rowIndex);
double effectiveRank = row.getRank();
long rankForAnim = row.getRank();
for (RankAnimation anim : moveAnims) {
double factor = 0.0;
if (rankForAnim == anim.toRank()) {
effectiveRank += slerp(anim.fromRank() - anim.toRank(), 0.0, anim.progress(timeNow));
rankForAnim += anim.fromRank() - anim.toRank();
} else if (anim.fromRank() >= rankForAnim && rankForAnim >= anim.toRank()) {
effectiveRank += 1.0 * slerp(-1.0, 0.0, anim.progress(timeNow));
rankForAnim -= 1;
}
}
final Layout rowLayout = rowLayouts.get(row.getTeamId());
rowLayout.relX = 0.0f;
rowLayout.relY = (float) (screen.y - effectiveRank * (rowHeight + cellMargin) - cellMargin) - cellMargin / 2.0f;
rowLayout.width = (float) screen.width;
rowLayout.height = (float) rowHeight + cellMargin;
final Layout scoreLayout = rowLayout.children().get(0);
scoreLayout.relX = (float) (teamLabelWidth + (screen.width - teamLabelWidth - rowWidth) / 1.0f);
scoreLayout.relY = (float) cellMargin;
scoreLayout.width = (float) rowWidth;
scoreLayout.height = (float) rowHeight;
}
rootLayout.layout();
if (particles != null) {
particles.setOffset(0.0, screen.y);
particles.update(timeNow);
}
} | scoreboard | positive | 440,085 |
public CriteriaQuery<T> orderBy(Order... orders) {
jpqlString = null;
compilation = null;
params = null;
if (orders == null || orders.length == 0) {
ordering = null;
return this;
}
ordering = new ArrayList<>();
for (int i = 0; i < orders.length; i++) {
ordering.add(orders[i]);
}
return this;
} | public CriteriaQuery<T> orderBy(Order... orders) {
<DeepExtract>
jpqlString = null;
compilation = null;
params = null;
</DeepExtract>
if (orders == null || orders.length == 0) {
ordering = null;
return this;
}
ordering = new ArrayList<>();
for (int i = 0; i < orders.length; i++) {
ordering.add(orders[i]);
}
return this;
} | datanucleus-api-jpa | positive | 440,086 |
@Override
public void create() {
log.debug("Calling create method on clone");
TaskEventService eventService = environment.fetchEventService();
for (TaskEventListener listener : listeners) {
eventService.addEventListener(listener);
}
try {
this.vm = cloneVM();
for (NetworkRefTask networkRef : networkRefs) {
networkRef.setVirtualSwitch(environment.restoreNetworkForName(networkRef.getNetworkName()).fetchSwitch());
networkRef.setVirtualMachine(this.vm);
networkRef.setVirtualHost(environment.fetchVirtualHost());
networkRef.create();
}
for (SecurityGroupRefTask sgr : securityGroupRefs) {
sgr.setSecurityGroup(environment.restoreSecurityGroupForName(sgr.getName()));
}
} catch (RemoteException e) {
log.warn("remote exception when creating clone task", e);
} catch (InterruptedException e) {
log.warn("interrupted exception when creating clone task", e);
} catch (Exception e) {
log.warn("unknown exception when creating clone task", e);
}
CloneVmCreatedEvent actionEvent = new CloneVmCreatedEvent(this);
environment.fetchEventService().sendEvent(actionEvent);
for (PostCreateTask task : postCreateTaskList) {
task.setUser(user);
task.setPassword(password);
task.create();
}
try {
powerOnVm();
} catch (Exception e) {
log.warn("exception when powering on vm", e);
}
} | @Override
public void create() {
log.debug("Calling create method on clone");
TaskEventService eventService = environment.fetchEventService();
for (TaskEventListener listener : listeners) {
eventService.addEventListener(listener);
}
try {
this.vm = cloneVM();
for (NetworkRefTask networkRef : networkRefs) {
networkRef.setVirtualSwitch(environment.restoreNetworkForName(networkRef.getNetworkName()).fetchSwitch());
networkRef.setVirtualMachine(this.vm);
networkRef.setVirtualHost(environment.fetchVirtualHost());
networkRef.create();
}
for (SecurityGroupRefTask sgr : securityGroupRefs) {
sgr.setSecurityGroup(environment.restoreSecurityGroupForName(sgr.getName()));
}
} catch (RemoteException e) {
log.warn("remote exception when creating clone task", e);
} catch (InterruptedException e) {
log.warn("interrupted exception when creating clone task", e);
} catch (Exception e) {
log.warn("unknown exception when creating clone task", e);
}
CloneVmCreatedEvent actionEvent = new CloneVmCreatedEvent(this);
environment.fetchEventService().sendEvent(actionEvent);
<DeepExtract>
for (PostCreateTask task : postCreateTaskList) {
task.setUser(user);
task.setPassword(password);
task.create();
}
</DeepExtract>
try {
powerOnVm();
} catch (Exception e) {
log.warn("exception when powering on vm", e);
}
} | terraform | positive | 440,087 |
private void changeState(int state) {
if (this.state == state) {
return;
}
tempBitmap.recycle();
tempBitmap = Bitmap.createBitmap(getWidth(), getWidth(), Bitmap.Config.ARGB_8888);
tempCanvas = new Canvas(tempBitmap);
this.state = state;
if (state == STATE_PROGRESS_STARTED) {
setCurrentProgress(0);
simulateProgressAnimator.start();
} else if (state == STATE_DONE_STARTED) {
setCurrentDoneBgOffset(MAX_DONE_BG_OFFSET);
setCurrentCheckmarkOffset(MAX_DONE_IMG_OFFSET);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playSequentially(doneBgAnimator, checkmarkAnimator);
animatorSet.start();
} else if (state == STATE_FINISHED) {
if (onLoadingFinishedListener != null) {
onLoadingFinishedListener.onLoadingFinished();
}
}
} | private void changeState(int state) {
if (this.state == state) {
return;
}
tempBitmap.recycle();
<DeepExtract>
tempBitmap = Bitmap.createBitmap(getWidth(), getWidth(), Bitmap.Config.ARGB_8888);
tempCanvas = new Canvas(tempBitmap);
</DeepExtract>
this.state = state;
if (state == STATE_PROGRESS_STARTED) {
setCurrentProgress(0);
simulateProgressAnimator.start();
} else if (state == STATE_DONE_STARTED) {
setCurrentDoneBgOffset(MAX_DONE_BG_OFFSET);
setCurrentCheckmarkOffset(MAX_DONE_IMG_OFFSET);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playSequentially(doneBgAnimator, checkmarkAnimator);
animatorSet.start();
} else if (state == STATE_FINISHED) {
if (onLoadingFinishedListener != null) {
onLoadingFinishedListener.onLoadingFinished();
}
}
} | UPES-SPE-Fest | positive | 440,088 |
public static void main(String[] args) throws IOException {
List<Person> people = CommonsCsvExample.csvExample();
DataFrame<Object> df;
try {
df = doConvert(people, Person.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println(df);
} | public static void main(String[] args) throws IOException {
List<Person> people = CommonsCsvExample.csvExample();
<DeepExtract>
DataFrame<Object> df;
try {
df = doConvert(people, Person.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
</DeepExtract>
System.out.println(df);
} | mastering-java-data-science | positive | 440,090 |
private void internalRelease() {
mIsEOS = true;
if (mIsCapturing) {
mIsCapturing = false;
try {
mListener.onStopEncode(this);
} catch (final Exception e) {
Log.e(TAG, "failed onStopped", e);
}
}
if (mRecorderStarted) {
mRecorderStarted = false;
if (mRecorder != null) {
try {
mRecorder.stop(this);
} catch (final Exception e) {
Log.e(TAG, "failed stopping muxer", e);
}
}
}
try {
mListener.onDestroy(this);
} catch (final Exception e) {
Log.e(TAG, "destroy:", e);
}
mRecorder = null;
synchronized (mPool) {
mPool.clear();
}
mFrameQueue.clear();
cnt = 0;
} | private void internalRelease() {
mIsEOS = true;
if (mIsCapturing) {
mIsCapturing = false;
try {
mListener.onStopEncode(this);
} catch (final Exception e) {
Log.e(TAG, "failed onStopped", e);
}
}
if (mRecorderStarted) {
mRecorderStarted = false;
if (mRecorder != null) {
try {
mRecorder.stop(this);
} catch (final Exception e) {
Log.e(TAG, "failed stopping muxer", e);
}
}
}
try {
mListener.onDestroy(this);
} catch (final Exception e) {
Log.e(TAG, "destroy:", e);
}
mRecorder = null;
<DeepExtract>
synchronized (mPool) {
mPool.clear();
}
mFrameQueue.clear();
cnt = 0;
</DeepExtract>
} | AndroidUSBCamera | positive | 440,091 |
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Payout payout = new Payout();
PayoutSenderBatchHeader senderBatchHeader = new PayoutSenderBatchHeader();
Random random = new Random();
senderBatchHeader.setSenderBatchId(new Double(random.nextDouble()).toString()).setEmailSubject("You have a Payout!");
Currency amount = new Currency();
amount.setValue("1.00").setCurrency("USD");
PayoutItem senderItem = new PayoutItem();
senderItem.setRecipientType("Email").setNote("Thanks for your patronage").setReceiver("shirt-supplier-one@gmail.com").setSenderItemId("201404324234").setAmount(amount);
List<PayoutItem> items = new ArrayList<PayoutItem>();
items.add(senderItem);
payout.setSenderBatchHeader(senderBatchHeader).setItems(items);
PayoutBatch batch = null;
try {
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
batch = payout.createSynchronous(apiContext);
LOGGER.info("Payout Batch With ID: " + batch.getBatchHeader().getPayoutBatchId());
ResultPrinter.addResult(req, resp, "Created Single Synchronous Payout", Payout.getLastRequest(), Payout.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Created Single Synchronous Payout", Payout.getLastRequest(), null, e.getMessage());
}
return batch;
req.getRequestDispatcher("response.jsp").forward(req, resp);
} | @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
<DeepExtract>
Payout payout = new Payout();
PayoutSenderBatchHeader senderBatchHeader = new PayoutSenderBatchHeader();
Random random = new Random();
senderBatchHeader.setSenderBatchId(new Double(random.nextDouble()).toString()).setEmailSubject("You have a Payout!");
Currency amount = new Currency();
amount.setValue("1.00").setCurrency("USD");
PayoutItem senderItem = new PayoutItem();
senderItem.setRecipientType("Email").setNote("Thanks for your patronage").setReceiver("shirt-supplier-one@gmail.com").setSenderItemId("201404324234").setAmount(amount);
List<PayoutItem> items = new ArrayList<PayoutItem>();
items.add(senderItem);
payout.setSenderBatchHeader(senderBatchHeader).setItems(items);
PayoutBatch batch = null;
try {
APIContext apiContext = new APIContext(clientID, clientSecret, mode);
batch = payout.createSynchronous(apiContext);
LOGGER.info("Payout Batch With ID: " + batch.getBatchHeader().getPayoutBatchId());
ResultPrinter.addResult(req, resp, "Created Single Synchronous Payout", Payout.getLastRequest(), Payout.getLastResponse(), null);
} catch (PayPalRESTException e) {
ResultPrinter.addResult(req, resp, "Created Single Synchronous Payout", Payout.getLastRequest(), null, e.getMessage());
}
return batch;
</DeepExtract>
req.getRequestDispatcher("response.jsp").forward(req, resp);
} | PayPal-Java-SDK | positive | 440,093 |
private void addRandomCard() {
emptyPoints.clear();
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
if (cardMaps[x][y].getNum() == 0) {
emptyPoints.add(new Point(x, y));
}
}
}
Point point = emptyPoints.remove((int) (Math.random() * emptyPoints.size()));
AlphaAnimation animation = new AlphaAnimation(0, 1f);
animation.setDuration(500);
cardMaps[point.x][point.y].startAnimation(animation);
this.num = Math.random() > 0.1 ? 2 : 4;
if (Math.random() > 0.1 ? 2 : 4 <= 0) {
mTextView.setText("");
} else {
mTextView.setText(String.valueOf(Math.random() > 0.1 ? 2 : 4));
}
mTextView.setTextColor(0xCCffffff);
switch(Math.random() > 0.1 ? 2 : 4) {
case 0:
mTextView.setBackground(UEImage.createBackground(0xFFFFFF, 80, 8));
break;
case 2:
mTextView.setTextColor(0xFF888888);
mTextView.setBackground(UEImage.createBackground(0xe5dcd2, 8));
break;
case 4:
mTextView.setTextColor(0xFF888888);
mTextView.setBackground(UEImage.createBackground(0xede0c8, 8));
break;
case 8:
mTextView.setBackground(UEImage.createBackground(0xf2b179, 8));
break;
case 16:
mTextView.setBackground(UEImage.createBackground(0xf59563, 8));
break;
case 32:
mTextView.setBackground(UEImage.createBackground(0xf67c5f, 8));
break;
case 64:
mTextView.setBackground(UEImage.createBackground(0xf65e3b, 8));
break;
case 128:
mTextView.setBackground(UEImage.createBackground(0xedcf72, 8));
break;
case 256:
mTextView.setBackground(UEImage.createBackground(0xedcc61, 8));
break;
case 512:
mTextView.setBackground(UEImage.createBackground(0xedc850, 8));
break;
case 1024:
mTextView.setBackground(UEImage.createBackground(0xedc53f, 8));
break;
case 2048:
mTextView.setBackground(UEImage.createBackground(0xedc22e, 8));
break;
case 4096:
mTextView.setBackground(UEImage.createBackground(0x3c3a32, 8));
break;
case 8192:
mTextView.setBackground(UEImage.createBackground(0xff0000, 8));
break;
case 16384:
mTextView.setBackground(UEImage.createBackground(0x009efc, 8));
break;
case 32768:
mTextView.setBackground(UEImage.createBackground(0x000000, 8));
break;
default:
mTextView.setTextColor(0x000000);
mTextView.setBackground(UEImage.createBackground(0xFFFFFF, 8));
break;
}
} | private void addRandomCard() {
emptyPoints.clear();
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
if (cardMaps[x][y].getNum() == 0) {
emptyPoints.add(new Point(x, y));
}
}
}
Point point = emptyPoints.remove((int) (Math.random() * emptyPoints.size()));
AlphaAnimation animation = new AlphaAnimation(0, 1f);
animation.setDuration(500);
cardMaps[point.x][point.y].startAnimation(animation);
<DeepExtract>
this.num = Math.random() > 0.1 ? 2 : 4;
if (Math.random() > 0.1 ? 2 : 4 <= 0) {
mTextView.setText("");
} else {
mTextView.setText(String.valueOf(Math.random() > 0.1 ? 2 : 4));
}
mTextView.setTextColor(0xCCffffff);
switch(Math.random() > 0.1 ? 2 : 4) {
case 0:
mTextView.setBackground(UEImage.createBackground(0xFFFFFF, 80, 8));
break;
case 2:
mTextView.setTextColor(0xFF888888);
mTextView.setBackground(UEImage.createBackground(0xe5dcd2, 8));
break;
case 4:
mTextView.setTextColor(0xFF888888);
mTextView.setBackground(UEImage.createBackground(0xede0c8, 8));
break;
case 8:
mTextView.setBackground(UEImage.createBackground(0xf2b179, 8));
break;
case 16:
mTextView.setBackground(UEImage.createBackground(0xf59563, 8));
break;
case 32:
mTextView.setBackground(UEImage.createBackground(0xf67c5f, 8));
break;
case 64:
mTextView.setBackground(UEImage.createBackground(0xf65e3b, 8));
break;
case 128:
mTextView.setBackground(UEImage.createBackground(0xedcf72, 8));
break;
case 256:
mTextView.setBackground(UEImage.createBackground(0xedcc61, 8));
break;
case 512:
mTextView.setBackground(UEImage.createBackground(0xedc850, 8));
break;
case 1024:
mTextView.setBackground(UEImage.createBackground(0xedc53f, 8));
break;
case 2048:
mTextView.setBackground(UEImage.createBackground(0xedc22e, 8));
break;
case 4096:
mTextView.setBackground(UEImage.createBackground(0x3c3a32, 8));
break;
case 8192:
mTextView.setBackground(UEImage.createBackground(0xff0000, 8));
break;
case 16384:
mTextView.setBackground(UEImage.createBackground(0x009efc, 8));
break;
case 32768:
mTextView.setBackground(UEImage.createBackground(0x000000, 8));
break;
default:
mTextView.setTextColor(0x000000);
mTextView.setBackground(UEImage.createBackground(0xFFFFFF, 8));
break;
}
</DeepExtract>
} | Auie | positive | 440,094 |
public void onClick(DialogInterface dialog, int id) {
ext = "ext2";
u.log("chose ext2 format");
Intent service = new Intent(this, NandRestoreService.class);
service.putExtra("ext", ext);
service.putExtra("nandroid", nandroid);
service.putExtra("slot", slot);
startService(service);
Intent i = new Intent(NandPicker.this, Install.class);
startActivity(i);
} | public void onClick(DialogInterface dialog, int id) {
ext = "ext2";
u.log("chose ext2 format");
<DeepExtract>
Intent service = new Intent(this, NandRestoreService.class);
service.putExtra("ext", ext);
service.putExtra("nandroid", nandroid);
service.putExtra("slot", slot);
startService(service);
</DeepExtract>
Intent i = new Intent(NandPicker.this, Install.class);
startActivity(i);
} | BootManager | positive | 440,095 |
@Override
public boolean hasTries(@NonNull final String providerName, @NonNull final Operation operation) {
OPFLog.logMethod(providerName, operation);
if (operation != UNREGISTER) {
throw new IllegalStateException("Wrong operation for UnregisterBackoffAdapter : " + operation);
}
if (backoffMap.containsKey(providerName)) {
OPFLog.d("Backoff map contains key for provider " + providerName);
return backoffMap.get(providerName).hasTries();
}
Backoff newUnregisterBackoff;
try {
newUnregisterBackoff = backoffClass.newInstance();
} catch (Exception e) {
OPFLog.w("Exception while instantiating class " + backoffClass + " : " + e);
OPFLog.w("Use " + InfinityExponentialBackoff.class.getSimpleName());
newUnregisterBackoff = new InfinityExponentialBackoff();
}
backoffMap.put(providerName, newUnregisterBackoff);
return newUnregisterBackoff.hasTries();
} | @Override
public boolean hasTries(@NonNull final String providerName, @NonNull final Operation operation) {
OPFLog.logMethod(providerName, operation);
if (operation != UNREGISTER) {
throw new IllegalStateException("Wrong operation for UnregisterBackoffAdapter : " + operation);
}
if (backoffMap.containsKey(providerName)) {
OPFLog.d("Backoff map contains key for provider " + providerName);
return backoffMap.get(providerName).hasTries();
}
<DeepExtract>
Backoff newUnregisterBackoff;
try {
newUnregisterBackoff = backoffClass.newInstance();
} catch (Exception e) {
OPFLog.w("Exception while instantiating class " + backoffClass + " : " + e);
OPFLog.w("Use " + InfinityExponentialBackoff.class.getSimpleName());
newUnregisterBackoff = new InfinityExponentialBackoff();
}
</DeepExtract>
backoffMap.put(providerName, newUnregisterBackoff);
return newUnregisterBackoff.hasTries();
} | OPFPush | positive | 440,096 |
public void delete() {
GL30.glDeleteVertexArrays(this.handle());
this.invalidateHandle();
} | public void delete() {
<DeepExtract>
GL30.glDeleteVertexArrays(this.handle());
</DeepExtract>
this.invalidateHandle();
} | sodium-fabric | positive | 440,099 |
private void associate(PodcastItemView row, PodcastVisual pv) {
PodcastVisual former = (PodcastVisual) row.getTag();
if (former != null) {
former.disassociate();
}
row.setTag(pv);
pv.associateWith(row);
} | private void associate(PodcastItemView row, PodcastVisual pv) {
PodcastVisual former = (PodcastVisual) row.getTag();
if (former != null) {
former.disassociate();
}
<DeepExtract>
row.setTag(pv);
pv.associateWith(row);
</DeepExtract>
} | android-radio-t | positive | 440,100 |
@Override
public void onCreate() {
super.onCreate();
context = this;
mSelfData = new SelfData();
mChatMessageClient = new ChatMessageClient(context);
mNetReceiver = new NetWorkReceiver();
IntentFilter netFilter = new IntentFilter();
netFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetReceiver, netFilter);
isPad = ScreenUtils.isPad(this);
JPushInterface.setDebugMode(true);
JPushInterface.init(this);
PgyCrashManager.register(this);
} | @Override
public void onCreate() {
super.onCreate();
context = this;
mSelfData = new SelfData();
mChatMessageClient = new ChatMessageClient(context);
<DeepExtract>
mNetReceiver = new NetWorkReceiver();
IntentFilter netFilter = new IntentFilter();
netFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetReceiver, netFilter);
</DeepExtract>
isPad = ScreenUtils.isPad(this);
JPushInterface.setDebugMode(true);
JPushInterface.init(this);
PgyCrashManager.register(this);
} | Teameeting-Android | positive | 440,101 |
public void process(DbSettings dbSettings, String outputFileName) {
startTimeStamp = LocalDateTime.now();
sourceType = dbSettings.sourceType;
dbType = dbSettings.dbType;
database = dbSettings.database;
tableToFieldInfos = new HashMap<>();
StringUtilities.outputWithTime("Started new scan of " + dbSettings.tables.size() + " tables...");
if (sourceType == DbSettings.SourceType.CSV_FILES) {
if (!scanValues)
this.minCellCount = Math.max(minCellCount, MIN_CELL_COUNT_FOR_CSV);
processCsvFiles(dbSettings);
} else if (sourceType == DbSettings.SourceType.SAS_FILES) {
processSasFiles(dbSettings);
} else {
processDatabase(dbSettings);
}
StringUtilities.outputWithTime("Generating scan report");
removeEmptyTables();
workbook = new SXSSFWorkbook(100);
int i = 0;
indexedTableNameLookup = new HashMap<>();
for (Table table : tableToFieldInfos.keySet()) {
String tableNameIndexed = Table.indexTableNameForSheet(table.getName(), i);
indexedTableNameLookup.put(table.getName(), tableNameIndexed);
i++;
}
createFieldOverviewSheet();
createTableOverviewSheet();
if (scanValues) {
createValueSheet();
}
createMetaSheet();
try (FileOutputStream out = new FileOutputStream(new File(outputFileName))) {
workbook.write(out);
out.close();
StringUtilities.outputWithTime("Scan report generated: " + outputFileName);
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage());
}
} | public void process(DbSettings dbSettings, String outputFileName) {
startTimeStamp = LocalDateTime.now();
sourceType = dbSettings.sourceType;
dbType = dbSettings.dbType;
database = dbSettings.database;
tableToFieldInfos = new HashMap<>();
StringUtilities.outputWithTime("Started new scan of " + dbSettings.tables.size() + " tables...");
if (sourceType == DbSettings.SourceType.CSV_FILES) {
if (!scanValues)
this.minCellCount = Math.max(minCellCount, MIN_CELL_COUNT_FOR_CSV);
processCsvFiles(dbSettings);
} else if (sourceType == DbSettings.SourceType.SAS_FILES) {
processSasFiles(dbSettings);
} else {
processDatabase(dbSettings);
}
<DeepExtract>
StringUtilities.outputWithTime("Generating scan report");
removeEmptyTables();
workbook = new SXSSFWorkbook(100);
int i = 0;
indexedTableNameLookup = new HashMap<>();
for (Table table : tableToFieldInfos.keySet()) {
String tableNameIndexed = Table.indexTableNameForSheet(table.getName(), i);
indexedTableNameLookup.put(table.getName(), tableNameIndexed);
i++;
}
createFieldOverviewSheet();
createTableOverviewSheet();
if (scanValues) {
createValueSheet();
}
createMetaSheet();
try (FileOutputStream out = new FileOutputStream(new File(outputFileName))) {
workbook.write(out);
out.close();
StringUtilities.outputWithTime("Scan report generated: " + outputFileName);
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage());
}
</DeepExtract>
} | WhiteRabbit | positive | 440,102 |
public void diff_cleanupSemantic(LinkedList<Diff> diffs) {
if (diffs.isEmpty()) {
return;
}
boolean changes = false;
Stack<Diff> equalities = new Stack<Diff>();
String lastequality = null;
ListIterator<Diff> pointer = diffs.listIterator();
int length_changes1 = 0;
int length_changes2 = 0;
Diff thisDiff = pointer.next();
while (thisDiff != null) {
if (thisDiff.operation == Operation.EQUAL) {
equalities.push(thisDiff);
length_changes1 = length_changes2;
length_changes2 = 0;
lastequality = thisDiff.text;
} else {
length_changes2 += thisDiff.text.length();
if (lastequality != null && (lastequality.length() <= length_changes1) && (lastequality.length() <= length_changes2)) {
while (thisDiff != equalities.lastElement()) {
thisDiff = pointer.previous();
}
pointer.next();
pointer.set(new Diff(Operation.DELETE, lastequality));
pointer.add(new Diff(Operation.INSERT, lastequality));
equalities.pop();
if (!equalities.empty()) {
equalities.pop();
}
if (equalities.empty()) {
while (pointer.hasPrevious()) {
pointer.previous();
}
} else {
thisDiff = equalities.lastElement();
while (thisDiff != pointer.previous()) {
}
}
length_changes1 = 0;
length_changes2 = 0;
lastequality = null;
changes = true;
}
}
thisDiff = pointer.hasNext() ? pointer.next() : null;
}
if (changes) {
diff_cleanupMerge(diffs);
}
String equality1, edit, equality2;
String commonString;
int commonOffset;
int score, bestScore;
String bestEquality1, bestEdit, bestEquality2;
ListIterator<Diff> pointer = diffs.listIterator();
Diff prevDiff = pointer.hasNext() ? pointer.next() : null;
Diff thisDiff = pointer.hasNext() ? pointer.next() : null;
Diff nextDiff = pointer.hasNext() ? pointer.next() : null;
while (nextDiff != null) {
if (prevDiff.operation == Operation.EQUAL && nextDiff.operation == Operation.EQUAL) {
equality1 = prevDiff.text;
edit = thisDiff.text;
equality2 = nextDiff.text;
commonOffset = diff_commonSuffix(equality1, edit);
if (commonOffset != 0) {
commonString = edit.substring(edit.length() - commonOffset);
equality1 = equality1.substring(0, equality1.length() - commonOffset);
edit = commonString + edit.substring(0, edit.length() - commonOffset);
equality2 = commonString + equality2;
}
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
bestScore = diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2);
while (edit.length() != 0 && equality2.length() != 0 && edit.charAt(0) == equality2.charAt(0)) {
equality1 += edit.charAt(0);
edit = edit.substring(1) + equality2.charAt(0);
equality2 = equality2.substring(1);
score = diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2);
if (score >= bestScore) {
bestScore = score;
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
}
}
if (!prevDiff.text.equals(bestEquality1)) {
if (bestEquality1.length() != 0) {
prevDiff.text = bestEquality1;
} else {
pointer.previous();
pointer.previous();
pointer.previous();
pointer.remove();
pointer.next();
pointer.next();
}
thisDiff.text = bestEdit;
if (bestEquality2.length() != 0) {
nextDiff.text = bestEquality2;
} else {
pointer.remove();
nextDiff = thisDiff;
thisDiff = prevDiff;
}
}
}
prevDiff = thisDiff;
thisDiff = nextDiff;
nextDiff = pointer.hasNext() ? pointer.next() : null;
}
} | public void diff_cleanupSemantic(LinkedList<Diff> diffs) {
if (diffs.isEmpty()) {
return;
}
boolean changes = false;
Stack<Diff> equalities = new Stack<Diff>();
String lastequality = null;
ListIterator<Diff> pointer = diffs.listIterator();
int length_changes1 = 0;
int length_changes2 = 0;
Diff thisDiff = pointer.next();
while (thisDiff != null) {
if (thisDiff.operation == Operation.EQUAL) {
equalities.push(thisDiff);
length_changes1 = length_changes2;
length_changes2 = 0;
lastequality = thisDiff.text;
} else {
length_changes2 += thisDiff.text.length();
if (lastequality != null && (lastequality.length() <= length_changes1) && (lastequality.length() <= length_changes2)) {
while (thisDiff != equalities.lastElement()) {
thisDiff = pointer.previous();
}
pointer.next();
pointer.set(new Diff(Operation.DELETE, lastequality));
pointer.add(new Diff(Operation.INSERT, lastequality));
equalities.pop();
if (!equalities.empty()) {
equalities.pop();
}
if (equalities.empty()) {
while (pointer.hasPrevious()) {
pointer.previous();
}
} else {
thisDiff = equalities.lastElement();
while (thisDiff != pointer.previous()) {
}
}
length_changes1 = 0;
length_changes2 = 0;
lastequality = null;
changes = true;
}
}
thisDiff = pointer.hasNext() ? pointer.next() : null;
}
if (changes) {
diff_cleanupMerge(diffs);
}
<DeepExtract>
String equality1, edit, equality2;
String commonString;
int commonOffset;
int score, bestScore;
String bestEquality1, bestEdit, bestEquality2;
ListIterator<Diff> pointer = diffs.listIterator();
Diff prevDiff = pointer.hasNext() ? pointer.next() : null;
Diff thisDiff = pointer.hasNext() ? pointer.next() : null;
Diff nextDiff = pointer.hasNext() ? pointer.next() : null;
while (nextDiff != null) {
if (prevDiff.operation == Operation.EQUAL && nextDiff.operation == Operation.EQUAL) {
equality1 = prevDiff.text;
edit = thisDiff.text;
equality2 = nextDiff.text;
commonOffset = diff_commonSuffix(equality1, edit);
if (commonOffset != 0) {
commonString = edit.substring(edit.length() - commonOffset);
equality1 = equality1.substring(0, equality1.length() - commonOffset);
edit = commonString + edit.substring(0, edit.length() - commonOffset);
equality2 = commonString + equality2;
}
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
bestScore = diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2);
while (edit.length() != 0 && equality2.length() != 0 && edit.charAt(0) == equality2.charAt(0)) {
equality1 += edit.charAt(0);
edit = edit.substring(1) + equality2.charAt(0);
equality2 = equality2.substring(1);
score = diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2);
if (score >= bestScore) {
bestScore = score;
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
}
}
if (!prevDiff.text.equals(bestEquality1)) {
if (bestEquality1.length() != 0) {
prevDiff.text = bestEquality1;
} else {
pointer.previous();
pointer.previous();
pointer.previous();
pointer.remove();
pointer.next();
pointer.next();
}
thisDiff.text = bestEdit;
if (bestEquality2.length() != 0) {
nextDiff.text = bestEquality2;
} else {
pointer.remove();
nextDiff = thisDiff;
thisDiff = prevDiff;
}
}
}
prevDiff = thisDiff;
thisDiff = nextDiff;
nextDiff = pointer.hasNext() ? pointer.next() : null;
}
</DeepExtract>
} | Aooms | positive | 440,104 |
private void onStructureFound(MachineStructureRecipe structure, int index) {
ArrayList<BlockPos> portPoses = structure.getPorts(pos, world, index);
List<PortStorage> inputPorts = new ArrayList<>();
List<PortStorage> outputPorts = new ArrayList<>();
for (BlockPos pos : portPoses) {
TileEntity blockEntity = world.getTileEntity(pos);
if (blockEntity instanceof IMachinePortTile) {
IMachinePortTile port = (IMachinePortTile) blockEntity;
if (port.isInput()) {
inputPorts.add(port.getStorage());
} else {
outputPorts.add(port.getStorage());
}
}
}
processData.getStructureDefinition().setInputPorts(inputPorts);
processData.getStructureDefinition().setOutputPorts(outputPorts);
List<MachineProcessRecipe> processRecipes = world.getRecipeManager().getRecipesForType(RecipeTypes.MACHINE_PROCESS);
boolean processed = false;
if (processData.getRecipe() != null && processData.getRecipe().matches(inputPorts, structure.getStructureId(), processData)) {
processData.getRecipe().process(inputPorts, outputPorts, processData);
return;
}
for (MachineProcessRecipe recipe : processRecipes) {
if (recipe.matches(inputPorts, structure.getStructureId(), processData)) {
if (!recipe.equals(processData.getRecipe())) {
if (processData.getRecipe() != null) {
processData.getRecipe().onInterrupted(inputPorts, outputPorts);
}
}
processData.setRecipe(recipe);
recipe.process(inputPorts, outputPorts, processData);
processed = true;
break;
}
}
if (!processed) {
invalidateRecipe();
}
} | private void onStructureFound(MachineStructureRecipe structure, int index) {
ArrayList<BlockPos> portPoses = structure.getPorts(pos, world, index);
List<PortStorage> inputPorts = new ArrayList<>();
List<PortStorage> outputPorts = new ArrayList<>();
for (BlockPos pos : portPoses) {
TileEntity blockEntity = world.getTileEntity(pos);
if (blockEntity instanceof IMachinePortTile) {
IMachinePortTile port = (IMachinePortTile) blockEntity;
if (port.isInput()) {
inputPorts.add(port.getStorage());
} else {
outputPorts.add(port.getStorage());
}
}
}
processData.getStructureDefinition().setInputPorts(inputPorts);
processData.getStructureDefinition().setOutputPorts(outputPorts);
<DeepExtract>
List<MachineProcessRecipe> processRecipes = world.getRecipeManager().getRecipesForType(RecipeTypes.MACHINE_PROCESS);
boolean processed = false;
if (processData.getRecipe() != null && processData.getRecipe().matches(inputPorts, structure.getStructureId(), processData)) {
processData.getRecipe().process(inputPorts, outputPorts, processData);
return;
}
for (MachineProcessRecipe recipe : processRecipes) {
if (recipe.matches(inputPorts, structure.getStructureId(), processData)) {
if (!recipe.equals(processData.getRecipe())) {
if (processData.getRecipe() != null) {
processData.getRecipe().onInterrupted(inputPorts, outputPorts);
}
}
processData.setRecipe(recipe);
recipe.process(inputPorts, outputPorts, processData);
processed = true;
break;
}
}
if (!processed) {
invalidateRecipe();
}
</DeepExtract>
} | MasterfulMachinery | positive | 440,109 |
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_frame_container);
mDataProgressFragment = new DataProgressFragment();
mMultiItemListViewFragment = new MultiItemListViewFragment();
mCustomProgressBarFrag = new CustomProgressBarFrag();
findViewById(R.id.show_progress_data_btn).setOnClickListener(this);
findViewById(R.id.multi_item_lv_btn).setOnClickListener(this);
Intent ii = getIntent();
if (null != ii) {
int pageType = ii.getIntExtra(K_PAGE_TYPE, 0);
switch(pageType) {
case PAGE_CUSTOM_PB:
getSupportFragmentManager().beginTransaction().replace(R.id.container, mCustomProgressBarFrag).commit();
break;
default:
break;
}
}
} | @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_frame_container);
<DeepExtract>
mDataProgressFragment = new DataProgressFragment();
mMultiItemListViewFragment = new MultiItemListViewFragment();
mCustomProgressBarFrag = new CustomProgressBarFrag();
findViewById(R.id.show_progress_data_btn).setOnClickListener(this);
findViewById(R.id.multi_item_lv_btn).setOnClickListener(this);
</DeepExtract>
Intent ii = getIntent();
if (null != ii) {
int pageType = ii.getIntExtra(K_PAGE_TYPE, 0);
switch(pageType) {
case PAGE_CUSTOM_PB:
getSupportFragmentManager().beginTransaction().replace(R.id.container, mCustomProgressBarFrag).commit();
break;
default:
break;
}
}
} | aboutView | positive | 440,111 |
@Override
public void onRefresh() {
getLoadStatusView().hideLoadStatus();
if (getCatid() != null) {
newsList.clear();
newsList.addAll(getCatid().getData());
cacheManager.putCache(getContext(), getCatid(), newsList);
tabAdapter.notifyDataSetChanged();
return;
}
} | @Override
public void onRefresh() {
<DeepExtract>
getLoadStatusView().hideLoadStatus();
if (getCatid() != null) {
newsList.clear();
newsList.addAll(getCatid().getData());
cacheManager.putCache(getContext(), getCatid(), newsList);
tabAdapter.notifyDataSetChanged();
return;
}
</DeepExtract>
} | WeMedia | positive | 440,112 |
@Override
public boolean buildInterrupted(@NotNull SBuild build, @NotNull BuildRevision revision) throws PublisherException {
String url = getViewUrl(build);
String commitMessage = null;
Long commitDate = null;
if (revision instanceof BuildRevisionEx) {
Long modId = ((BuildRevisionEx) revision).getModificationId();
if (modId != null) {
SVcsModification m = myVcsHistory.findChangeById(modId);
if (m != null) {
commitMessage = m.getDescription();
commitDate = m.getVcsDate().getTime();
}
}
}
String buildName = build.getFullName() + " #" + build.getBuildNumber();
String payload = createPayload(myParams.get(Constants.UPSOURCE_PROJECT_ID), build.getBuildTypeExternalId(), UpsourceStatus.FAILED, buildName, url, build.getStatusDescriptor().getText(), getRevision(revision), commitMessage, commitDate);
try {
publish(payload, LogUtil.describe(build));
} catch (Exception e) {
throw new PublisherException("Cannot publish status to Upsource for VCS root " + revision.getRoot().getName() + ": " + e.toString(), e);
}
return true;
} | @Override
public boolean buildInterrupted(@NotNull SBuild build, @NotNull BuildRevision revision) throws PublisherException {
<DeepExtract>
String url = getViewUrl(build);
String commitMessage = null;
Long commitDate = null;
if (revision instanceof BuildRevisionEx) {
Long modId = ((BuildRevisionEx) revision).getModificationId();
if (modId != null) {
SVcsModification m = myVcsHistory.findChangeById(modId);
if (m != null) {
commitMessage = m.getDescription();
commitDate = m.getVcsDate().getTime();
}
}
}
String buildName = build.getFullName() + " #" + build.getBuildNumber();
String payload = createPayload(myParams.get(Constants.UPSOURCE_PROJECT_ID), build.getBuildTypeExternalId(), UpsourceStatus.FAILED, buildName, url, build.getStatusDescriptor().getText(), getRevision(revision), commitMessage, commitDate);
try {
publish(payload, LogUtil.describe(build));
} catch (Exception e) {
throw new PublisherException("Cannot publish status to Upsource for VCS root " + revision.getRoot().getName() + ": " + e.toString(), e);
}
</DeepExtract>
return true;
} | commit-status-publisher | positive | 440,114 |
public void putShort(short value) {
for (byte aValue : toBytes(value)) {
putByte(aValue);
}
} | public void putShort(short value) {
<DeepExtract>
for (byte aValue : toBytes(value)) {
putByte(aValue);
}
</DeepExtract>
} | JPRE | positive | 440,115 |
public void test() {
Random random = new Random();
int N = 20;
int[] arr = new int[N];
for (int i = 0; i < N; i++) arr[i] = random.nextInt(100);
int[] arr2 = Arrays.copyOf(arr, arr.length);
System.out.println(Arrays.toString(arr));
if (arr == null || arr.length == 0)
return;
for (int i = 0; i < arr.length; i++) {
for (int j = arr.length - 1; j > i; j--) {
if (arr[j] < arr[j - 1]) {
int tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
}
}
}
System.out.println(Arrays.toString(arr));
if (arr2 == null || arr2.length == 0)
return;
for (int i = 0; i < arr2.length; i++) {
for (int j = 1; j < arr2.length - i; j++) {
if (arr2[j] < arr2[j - 1]) {
int tmp = arr2[j];
arr2[j] = arr2[j - 1];
arr2[j - 1] = tmp;
}
}
}
System.out.println(Arrays.toString(arr2));
} | public void test() {
Random random = new Random();
int N = 20;
int[] arr = new int[N];
for (int i = 0; i < N; i++) arr[i] = random.nextInt(100);
int[] arr2 = Arrays.copyOf(arr, arr.length);
System.out.println(Arrays.toString(arr));
if (arr == null || arr.length == 0)
return;
for (int i = 0; i < arr.length; i++) {
for (int j = arr.length - 1; j > i; j--) {
if (arr[j] < arr[j - 1]) {
int tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
}
}
}
System.out.println(Arrays.toString(arr));
<DeepExtract>
if (arr2 == null || arr2.length == 0)
return;
for (int i = 0; i < arr2.length; i++) {
for (int j = 1; j < arr2.length - i; j++) {
if (arr2[j] < arr2[j - 1]) {
int tmp = arr2[j];
arr2[j] = arr2[j - 1];
arr2[j - 1] = tmp;
}
}
}
</DeepExtract>
System.out.println(Arrays.toString(arr2));
} | algorithm-primer | positive | 440,117 |
public WebElement upUntilPredicate(Path expectedElement, int scrollStep, int maxNumberOfScrolls, Predicate<WebElement> predicate) {
JavascriptExecutor js = (JavascriptExecutor) driver;
InBrowser browser = new InBrowser(driver);
WebElement wrapperEl = browser.find(wrapper);
try {
return doWithRetries(() -> {
long left = 1;
final int MAX_FAILURES = 5;
int failures = 0;
for (int i = 0; i < maxNumberOfScrolls; i++) {
List<WebElement> els = browser.findAll(expectedElement);
Optional<WebElement> foundOne = els.stream().filter(predicate).findFirst();
if (foundOne.isPresent())
return foundOne.get();
if (left <= 0)
break;
try {
Object ret = js.executeScript("elem = arguments[0];elem.scrollTop = elem.scrollTop-arguments[1];return elem.scrollTop;", wrapperEl, scrollStep);
left = (ret.getClass() == Double.class) ? ((Double) ret).longValue() : (long) ret;
} catch (Exception e) {
e.printStackTrace();
failures++;
if (failures >= MAX_FAILURES) {
throw new RuntimeException(e);
}
}
}
throw new NoSuchElementException(expectedElement.toString());
}, 3, 200);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | public WebElement upUntilPredicate(Path expectedElement, int scrollStep, int maxNumberOfScrolls, Predicate<WebElement> predicate) {
<DeepExtract>
JavascriptExecutor js = (JavascriptExecutor) driver;
InBrowser browser = new InBrowser(driver);
WebElement wrapperEl = browser.find(wrapper);
try {
return doWithRetries(() -> {
long left = 1;
final int MAX_FAILURES = 5;
int failures = 0;
for (int i = 0; i < maxNumberOfScrolls; i++) {
List<WebElement> els = browser.findAll(expectedElement);
Optional<WebElement> foundOne = els.stream().filter(predicate).findFirst();
if (foundOne.isPresent())
return foundOne.get();
if (left <= 0)
break;
try {
Object ret = js.executeScript("elem = arguments[0];elem.scrollTop = elem.scrollTop-arguments[1];return elem.scrollTop;", wrapperEl, scrollStep);
left = (ret.getClass() == Double.class) ? ((Double) ret).longValue() : (long) ret;
} catch (Exception e) {
e.printStackTrace();
failures++;
if (failures >= MAX_FAILURES) {
throw new RuntimeException(e);
}
}
}
throw new NoSuchElementException(expectedElement.toString());
}, 3, 200);
} catch (Exception e) {
throw new RuntimeException(e);
}
</DeepExtract>
} | dollarx | positive | 440,118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.