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 Criteria andTagNotIn(List<String> values) {
if (values == null) {
throw new RuntimeException("Value for " + "tag" + " cannot be null");
}
criteria.add(new Criterion("tag not in", values));
return (Criteria) this;
} | public Criteria andTagNotIn(List<String> values) {
<DeepExtract>
if (values == null) {
throw new RuntimeException("Value for " + "tag" + " cannot be null");
}
criteria.add(new Criterion("tag not in", values));
</DeepExtract>
return (Criteria) this;
} | music | positive | 2,777 |
public void loadFront(SolutionSet solutionSet, int notLoadingIndex) {
if (notLoadingIndex >= 0 && notLoadingIndex < solutionSet.size()) {
numberOfPoints_ = solutionSet.size() - 1;
} else {
numberOfPoints_ = solutionSet.size();
}
nPoints_ = numberOfPoints_;
return dimension_;
points_ = new Point[numberOfPoints_];
int index = 0;
for (int i = 0; i < solutionSet.size(); i++) {
if (i != notLoadingIndex) {
double[] vector = new double[dimension_];
for (int j = 0; j < dimension_; j++) {
vector[j] = solutionSet.get(i).getObjective(j);
}
points_[index++] = new Point(vector);
}
}
} | public void loadFront(SolutionSet solutionSet, int notLoadingIndex) {
if (notLoadingIndex >= 0 && notLoadingIndex < solutionSet.size()) {
numberOfPoints_ = solutionSet.size() - 1;
} else {
numberOfPoints_ = solutionSet.size();
}
nPoints_ = numberOfPoints_;
<DeepExtract>
return dimension_;
</DeepExtract>
points_ = new Point[numberOfPoints_];
int index = 0;
for (int i = 0; i < solutionSet.size(); i++) {
if (i != notLoadingIndex) {
double[] vector = new double[dimension_];
for (int j = 0; j < dimension_; j++) {
vector[j] = solutionSet.get(i).getObjective(j);
}
points_[index++] = new Point(vector);
}
}
} | reproblems | positive | 2,778 |
@Override
public HttpResponse post(String url, Map<String, String> parameters, HttpRequestOptions requestOptions) throws IOException {
final FetchOptions options = getFetchOptions(requestOptions);
String currentUrl = url;
for (int i = 0; i <= requestOptions.getMaxRedirects(); i++) {
HTTPRequest httpRequest = new HTTPRequest(new URL(currentUrl), HTTPMethod.POST, options);
addHeaders(httpRequest, requestOptions);
if (HTTPMethod.POST == HTTPMethod.POST && encodeParameters(parameters) != null) {
httpRequest.setPayload(encodeParameters(parameters).getBytes());
}
HTTPResponse httpResponse;
try {
httpResponse = fetchService.fetch(httpRequest);
} catch (ResponseTooLargeException e) {
return new TooLargeResponse(currentUrl);
}
if (!isRedirect(httpResponse.getResponseCode())) {
boolean isResponseTooLarge = (getContentLength(httpResponse) > requestOptions.getMaxBodySize());
return new AppEngineFetchResponse(httpResponse, isResponseTooLarge, currentUrl);
} else {
currentUrl = getResponseHeader(httpResponse, "Location").getValue();
}
}
throw new IOException("exceeded maximum number of redirects");
} | @Override
public HttpResponse post(String url, Map<String, String> parameters, HttpRequestOptions requestOptions) throws IOException {
<DeepExtract>
final FetchOptions options = getFetchOptions(requestOptions);
String currentUrl = url;
for (int i = 0; i <= requestOptions.getMaxRedirects(); i++) {
HTTPRequest httpRequest = new HTTPRequest(new URL(currentUrl), HTTPMethod.POST, options);
addHeaders(httpRequest, requestOptions);
if (HTTPMethod.POST == HTTPMethod.POST && encodeParameters(parameters) != null) {
httpRequest.setPayload(encodeParameters(parameters).getBytes());
}
HTTPResponse httpResponse;
try {
httpResponse = fetchService.fetch(httpRequest);
} catch (ResponseTooLargeException e) {
return new TooLargeResponse(currentUrl);
}
if (!isRedirect(httpResponse.getResponseCode())) {
boolean isResponseTooLarge = (getContentLength(httpResponse) > requestOptions.getMaxBodySize());
return new AppEngineFetchResponse(httpResponse, isResponseTooLarge, currentUrl);
} else {
currentUrl = getResponseHeader(httpResponse, "Location").getValue();
}
}
throw new IOException("exceeded maximum number of redirects");
</DeepExtract>
} | openid4java | positive | 2,779 |
public _Fields fieldForId(int fieldId) {
switch(fieldId) {
case 1:
return CMD;
case 2:
return TASK_ID;
case 3:
return UNDO_REPORT_HTTP;
case 4:
return UNDO_REPORT_HTTP_URL;
case 5:
return EXEC_TYPE;
case 6:
return DEL_TEMP_FILE;
case 7:
return EXTRA;
default:
return null;
}
} | public _Fields fieldForId(int fieldId) {
<DeepExtract>
switch(fieldId) {
case 1:
return CMD;
case 2:
return TASK_ID;
case 3:
return UNDO_REPORT_HTTP;
case 4:
return UNDO_REPORT_HTTP_URL;
case 5:
return EXEC_TYPE;
case 6:
return DEL_TEMP_FILE;
case 7:
return EXTRA;
default:
return null;
}
</DeepExtract>
} | CronHub | positive | 2,781 |
public Document set(FieldPath fieldPath, ODate value) {
FieldSegment field = fieldPath.next();
if (field == null)
return;
String key = field.getNameSegment().getName();
if (Strings.isNullOrEmpty(key))
return;
if (key.equals(ID)) {
if (!field.isLastPath())
throw new IllegalArgumentException("_id must be last on path");
setId(new HValue(value));
return;
}
HValue oldValue = (HValue) entries.get(key);
if (field.isLastPath()) {
if (compareValueTimestamps && new HValue(value).hasNewerTs(oldValue))
return;
entries.put(key, new HValue(value));
} else if (field.isMap()) {
if (oldValue != null && oldValue.getType() == Type.MAP) {
HDocument doc = (HDocument) oldValue;
doc.setCompareValueTimestamps(compareValueTimestamps);
doc.setHValue(fieldPath, new HValue(value));
doc.setTs(new HValue(value).getTs());
} else {
if (compareValueTimestamps && new HValue(value).hasNewerTs(oldValue))
return;
HDocument doc = new HDocument();
doc.setCompareValueTimestamps(compareValueTimestamps);
doc.setHValue(fieldPath, new HValue(value));
doc.setTs(new HValue(value).getTs());
entries.put(key, doc);
}
} else if (field.isArray()) {
if (oldValue != null && oldValue.getType() == Type.ARRAY) {
HList list = (HList) oldValue;
list.setCompareValueTimestamps(compareValueTimestamps);
list.setHValue(fieldPath, new HValue(value));
list.setTs(new HValue(value).getTs());
} else {
if (compareValueTimestamps && new HValue(value).hasNewerTs(oldValue))
return;
HList list = new HList();
list.setCompareValueTimestamps(compareValueTimestamps);
list.setHValue(fieldPath, new HValue(value));
list.setTs(new HValue(value).getTs());
entries.put(key, list);
}
}
return this;
} | public Document set(FieldPath fieldPath, ODate value) {
<DeepExtract>
FieldSegment field = fieldPath.next();
if (field == null)
return;
String key = field.getNameSegment().getName();
if (Strings.isNullOrEmpty(key))
return;
if (key.equals(ID)) {
if (!field.isLastPath())
throw new IllegalArgumentException("_id must be last on path");
setId(new HValue(value));
return;
}
HValue oldValue = (HValue) entries.get(key);
if (field.isLastPath()) {
if (compareValueTimestamps && new HValue(value).hasNewerTs(oldValue))
return;
entries.put(key, new HValue(value));
} else if (field.isMap()) {
if (oldValue != null && oldValue.getType() == Type.MAP) {
HDocument doc = (HDocument) oldValue;
doc.setCompareValueTimestamps(compareValueTimestamps);
doc.setHValue(fieldPath, new HValue(value));
doc.setTs(new HValue(value).getTs());
} else {
if (compareValueTimestamps && new HValue(value).hasNewerTs(oldValue))
return;
HDocument doc = new HDocument();
doc.setCompareValueTimestamps(compareValueTimestamps);
doc.setHValue(fieldPath, new HValue(value));
doc.setTs(new HValue(value).getTs());
entries.put(key, doc);
}
} else if (field.isArray()) {
if (oldValue != null && oldValue.getType() == Type.ARRAY) {
HList list = (HList) oldValue;
list.setCompareValueTimestamps(compareValueTimestamps);
list.setHValue(fieldPath, new HValue(value));
list.setTs(new HValue(value).getTs());
} else {
if (compareValueTimestamps && new HValue(value).hasNewerTs(oldValue))
return;
HList list = new HList();
list.setCompareValueTimestamps(compareValueTimestamps);
list.setHValue(fieldPath, new HValue(value));
list.setTs(new HValue(value).getTs());
entries.put(key, list);
}
}
</DeepExtract>
return this;
} | hdocdb | positive | 2,782 |
IOutputBuffer getEncodedDictionary() {
IEncoder encoder = Types.getPrimitiveEncoder(primitiveColumn.type, Types.PLAIN);
for (Object o : statsCollector.getFrequencies().keySet()) {
encoder.encode(o);
}
throw new UnsupportedOperationException();
return encoder;
} | IOutputBuffer getEncodedDictionary() {
IEncoder encoder = Types.getPrimitiveEncoder(primitiveColumn.type, Types.PLAIN);
for (Object o : statsCollector.getFrequencies().keySet()) {
encoder.encode(o);
}
<DeepExtract>
throw new UnsupportedOperationException();
</DeepExtract>
return encoder;
} | dendrite | positive | 2,783 |
@EventHandler(ignoreCancelled = true)
public void effect(MTEntityDamageByEntityEvent event) {
Player player = event.getPlayer();
Entity entity = event.getEvent().getEntity();
if (!player.isSneaking()) {
return;
}
if (!event.getEvent().getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)) {
return;
}
if (player.equals(event.getEvent().getEntity())) {
return;
}
if (!player.hasPermission("minetinker.modifiers.ender.use")) {
return;
}
ItemStack tool = event.getTool();
if (!modManager.hasMod(tool, this)) {
return;
}
if (modManager.getModLevel(tool, this) < 2) {
return;
}
if (entity instanceof Player) {
if (entity.hasPermission("minetinker.modifiers.ender.prohibittp")) {
ChatWriter.sendActionBar(player, LanguageManager.getString("Modifier.Ender.TeleportationProhibited", player));
ChatWriter.logModifier(player, event, this, tool, "Teleport denied");
return;
}
}
Location loc = entity.getLocation().clone();
Location oldLoc = player.getLocation();
entity.teleport(oldLoc);
if (this.hasParticles) {
AreaEffectCloud cloud = (AreaEffectCloud) player.getWorld().spawnEntity(player.getLocation(), EntityType.AREA_EFFECT_CLOUD);
cloud.setVelocity(new Vector(0, 1, 0));
cloud.setRadius(0.5f);
cloud.setDuration(5);
cloud.setColor(Color.GREEN);
cloud.getLocation().setYaw(90);
AreaEffectCloud cloud2 = (AreaEffectCloud) player.getWorld().spawnEntity(loc, EntityType.AREA_EFFECT_CLOUD);
cloud2.setVelocity(new Vector(0, 1, 0));
cloud2.setRadius(0.5f);
cloud2.setDuration(5);
cloud2.setColor(Color.GREEN);
cloud2.getLocation().setPitch(90);
}
player.teleport(loc);
int stat = (DataHandler.hasTag(tool, getKey() + "_stat_used", PersistentDataType.INTEGER, false)) ? DataHandler.getTag(tool, getKey() + "_stat_used", PersistentDataType.INTEGER, false) : 0;
DataHandler.setTag(tool, getKey() + "_stat_used", stat + 1, PersistentDataType.INTEGER, false);
double distance = (DataHandler.hasTag(tool, getKey() + "_stat_distance", PersistentDataType.DOUBLE, false)) ? DataHandler.getTag(tool, getKey() + "_stat_distance", PersistentDataType.DOUBLE, false) : 0;
distance += oldLoc.distance(loc);
DataHandler.setTag(tool, getKey() + "_stat_distance", distance, PersistentDataType.DOUBLE, false);
int swapped = (DataHandler.hasTag(tool, getKey() + "_stat_swapped", PersistentDataType.INTEGER, false)) ? DataHandler.getTag(tool, getKey() + "_stat_swapped", PersistentDataType.INTEGER, false) : 0;
DataHandler.setTag(tool, getKey() + "_stat_swapped", swapped + 1, PersistentDataType.INTEGER, false);
if (this.hasSound) {
player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ENDERMAN_TELEPORT, 1.0F, 0.3F);
player.getWorld().playSound(event.getEvent().getEntity().getLocation(), Sound.ENTITY_ENDERMAN_TELEPORT, 1.0F, 0.3F);
}
if (this.giveNauseaOnUse) {
player.removePotionEffect(PotionEffectType.CONFUSION);
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, this.nauseaDuration, 0, false, false));
if (entity instanceof LivingEntity) {
((LivingEntity) entity).removePotionEffect(PotionEffectType.CONFUSION);
((LivingEntity) entity).addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, this.nauseaDuration, 0, false, false));
}
}
if (this.giveBlindnessOnUse) {
player.removePotionEffect(PotionEffectType.BLINDNESS);
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, this.blindnessDuration, 0, false, false));
if (entity instanceof LivingEntity) {
((LivingEntity) entity).removePotionEffect(PotionEffectType.BLINDNESS);
((LivingEntity) entity).addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, this.blindnessDuration, 0, false, false));
}
}
ChatWriter.logModifier(player, event, this, tool, "Entity(" + entity.getType() + ")", String.format("Location: (%s: %d/%d/%d <-> %d/%d/%d)", loc.getWorld().getName(), oldLoc.getBlockX(), oldLoc.getBlockY(), oldLoc.getBlockZ(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
} | @EventHandler(ignoreCancelled = true)
public void effect(MTEntityDamageByEntityEvent event) {
Player player = event.getPlayer();
Entity entity = event.getEvent().getEntity();
if (!player.isSneaking()) {
return;
}
if (!event.getEvent().getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)) {
return;
}
if (player.equals(event.getEvent().getEntity())) {
return;
}
if (!player.hasPermission("minetinker.modifiers.ender.use")) {
return;
}
ItemStack tool = event.getTool();
if (!modManager.hasMod(tool, this)) {
return;
}
if (modManager.getModLevel(tool, this) < 2) {
return;
}
if (entity instanceof Player) {
if (entity.hasPermission("minetinker.modifiers.ender.prohibittp")) {
ChatWriter.sendActionBar(player, LanguageManager.getString("Modifier.Ender.TeleportationProhibited", player));
ChatWriter.logModifier(player, event, this, tool, "Teleport denied");
return;
}
}
Location loc = entity.getLocation().clone();
Location oldLoc = player.getLocation();
entity.teleport(oldLoc);
<DeepExtract>
if (this.hasParticles) {
AreaEffectCloud cloud = (AreaEffectCloud) player.getWorld().spawnEntity(player.getLocation(), EntityType.AREA_EFFECT_CLOUD);
cloud.setVelocity(new Vector(0, 1, 0));
cloud.setRadius(0.5f);
cloud.setDuration(5);
cloud.setColor(Color.GREEN);
cloud.getLocation().setYaw(90);
AreaEffectCloud cloud2 = (AreaEffectCloud) player.getWorld().spawnEntity(loc, EntityType.AREA_EFFECT_CLOUD);
cloud2.setVelocity(new Vector(0, 1, 0));
cloud2.setRadius(0.5f);
cloud2.setDuration(5);
cloud2.setColor(Color.GREEN);
cloud2.getLocation().setPitch(90);
}
</DeepExtract>
player.teleport(loc);
int stat = (DataHandler.hasTag(tool, getKey() + "_stat_used", PersistentDataType.INTEGER, false)) ? DataHandler.getTag(tool, getKey() + "_stat_used", PersistentDataType.INTEGER, false) : 0;
DataHandler.setTag(tool, getKey() + "_stat_used", stat + 1, PersistentDataType.INTEGER, false);
double distance = (DataHandler.hasTag(tool, getKey() + "_stat_distance", PersistentDataType.DOUBLE, false)) ? DataHandler.getTag(tool, getKey() + "_stat_distance", PersistentDataType.DOUBLE, false) : 0;
distance += oldLoc.distance(loc);
DataHandler.setTag(tool, getKey() + "_stat_distance", distance, PersistentDataType.DOUBLE, false);
int swapped = (DataHandler.hasTag(tool, getKey() + "_stat_swapped", PersistentDataType.INTEGER, false)) ? DataHandler.getTag(tool, getKey() + "_stat_swapped", PersistentDataType.INTEGER, false) : 0;
DataHandler.setTag(tool, getKey() + "_stat_swapped", swapped + 1, PersistentDataType.INTEGER, false);
if (this.hasSound) {
player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ENDERMAN_TELEPORT, 1.0F, 0.3F);
player.getWorld().playSound(event.getEvent().getEntity().getLocation(), Sound.ENTITY_ENDERMAN_TELEPORT, 1.0F, 0.3F);
}
if (this.giveNauseaOnUse) {
player.removePotionEffect(PotionEffectType.CONFUSION);
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, this.nauseaDuration, 0, false, false));
if (entity instanceof LivingEntity) {
((LivingEntity) entity).removePotionEffect(PotionEffectType.CONFUSION);
((LivingEntity) entity).addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, this.nauseaDuration, 0, false, false));
}
}
if (this.giveBlindnessOnUse) {
player.removePotionEffect(PotionEffectType.BLINDNESS);
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, this.blindnessDuration, 0, false, false));
if (entity instanceof LivingEntity) {
((LivingEntity) entity).removePotionEffect(PotionEffectType.BLINDNESS);
((LivingEntity) entity).addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, this.blindnessDuration, 0, false, false));
}
}
ChatWriter.logModifier(player, event, this, tool, "Entity(" + entity.getType() + ")", String.format("Location: (%s: %d/%d/%d <-> %d/%d/%d)", loc.getWorld().getName(), oldLoc.getBlockX(), oldLoc.getBlockY(), oldLoc.getBlockZ(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
} | MineTinker | positive | 2,786 |
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
System.out.println("className:" + className);
if (!className.equalsIgnoreCase("demo/Dog")) {
return null;
}
File file = new File("../Instrument/target/classes/demo/Dog.class");
try (InputStream is = new FileInputStream(file)) {
long length = file.length();
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file" + file.getName());
}
is.close();
return bytes;
} catch (Exception e) {
System.out.println("error occurs in _ClassTransformer!" + e.getClass().getName());
return null;
}
} | @Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
System.out.println("className:" + className);
if (!className.equalsIgnoreCase("demo/Dog")) {
return null;
}
<DeepExtract>
File file = new File("../Instrument/target/classes/demo/Dog.class");
try (InputStream is = new FileInputStream(file)) {
long length = file.length();
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file" + file.getName());
}
is.close();
return bytes;
} catch (Exception e) {
System.out.println("error occurs in _ClassTransformer!" + e.getClass().getName());
return null;
}
</DeepExtract>
} | wheel | positive | 2,787 |
@Test
public void doListsOverlap3() {
list1 = LinkedListUtil.createLinkedList(1, 2, 3);
list2 = LinkedListUtil.createLinkedList(4, 5, 6);
overlap = null;
assertEquals(overlap, TestForOverlappingLists.doListsOverlap(list1, list2));
} | @Test
public void doListsOverlap3() {
list1 = LinkedListUtil.createLinkedList(1, 2, 3);
list2 = LinkedListUtil.createLinkedList(4, 5, 6);
overlap = null;
<DeepExtract>
assertEquals(overlap, TestForOverlappingLists.doListsOverlap(list1, list2));
</DeepExtract>
} | Elements-of-programming-interviews | positive | 2,788 |
public static IterablePropertyValueMapper createForIterableType(ValueTransformer valueTransformer, Class<?> iterableType) {
requireNonNull(iterableType);
Supplier<ImmutableCollection.Builder<Object>> createCollectionBuilder;
if (iterableType.equals(Set.class)) {
createCollectionBuilder = ImmutableSet::builder;
} else if (iterableType.equals(List.class)) {
createCollectionBuilder = ImmutableList::builder;
}
throw new RuntimeException("don't know how to create a factory for collection type [" + iterableType.getCanonicalName() + "]");
return new IterablePropertyValueMapper(valueTransformer, createCollectionBuilder);
} | public static IterablePropertyValueMapper createForIterableType(ValueTransformer valueTransformer, Class<?> iterableType) {
requireNonNull(iterableType);
<DeepExtract>
Supplier<ImmutableCollection.Builder<Object>> createCollectionBuilder;
if (iterableType.equals(Set.class)) {
createCollectionBuilder = ImmutableSet::builder;
} else if (iterableType.equals(List.class)) {
createCollectionBuilder = ImmutableList::builder;
}
throw new RuntimeException("don't know how to create a factory for collection type [" + iterableType.getCanonicalName() + "]");
</DeepExtract>
return new IterablePropertyValueMapper(valueTransformer, createCollectionBuilder);
} | carml | positive | 2,789 |
public void actionPerformed(ActionEvent evt) {
UINewDoc ui = new UINewDoc(this, Collections.emptyMap(), true);
PIGuiHelper.centerWindowOnMC(ui);
ui.setVisible(true);
if (!ui.isCanceled()) {
try {
DocumentationManager.addLocalDoc(ui.getDocID(), ui.getDocName());
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, e.getMessage(), "An Error Occurred!", JOptionPane.ERROR_MESSAGE);
}
}
} | public void actionPerformed(ActionEvent evt) {
<DeepExtract>
UINewDoc ui = new UINewDoc(this, Collections.emptyMap(), true);
PIGuiHelper.centerWindowOnMC(ui);
ui.setVisible(true);
if (!ui.isCanceled()) {
try {
DocumentationManager.addLocalDoc(ui.getDocID(), ui.getDocName());
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, e.getMessage(), "An Error Occurred!", JOptionPane.ERROR_MESSAGE);
}
}
</DeepExtract>
} | ProjectIntelligence | positive | 2,790 |
@Override
public void windowClosing(WindowEvent e) {
Parameters.savePreferences();
room.awtControls().initPreferences();
room.joystickControls().initPreferences();
setVisible(false);
} | @Override
public void windowClosing(WindowEvent e) {
<DeepExtract>
Parameters.savePreferences();
room.awtControls().initPreferences();
room.joystickControls().initPreferences();
setVisible(false);
</DeepExtract>
} | javatari | positive | 2,791 |
private void initView() {
gvDateSelect = (GridView) findViewById(R.id.gvDateSelect);
tvTiming = (TextView) findViewById(R.id.tvTiming);
tvDelay = (TextView) findViewById(R.id.tvDelay);
tvTimingTime = (TextView) findViewById(R.id.tvTimingTime);
tvDelayTime = (TextView) findViewById(R.id.tvDelayTime);
tbTiming = (ToggleButton) findViewById(R.id.tbTimingFlag);
tbDelay = (ToggleButton) findViewById(R.id.tbDelayFlag);
ivBack = (ImageView) findViewById(R.id.ivBack);
llAppointmentMenu = (LinearLayout) findViewById(R.id.llAppointmentMenu);
llSetAppointment = (LinearLayout) findViewById(R.id.llSetAppointment);
rlStartTimeSetting = (RelativeLayout) findViewById(R.id.rlStartTimeSetting);
rlEndTimeSetting = (RelativeLayout) findViewById(R.id.rlEndTimeSetting);
tvTimingStart = (TextView) findViewById(R.id.tvTimingStart);
tvTimingEnd = (TextView) findViewById(R.id.tvTimingEnd);
tvTitle = (TextView) findViewById(R.id.tvTitle);
mSelectList = new ArrayList<Boolean>();
for (int i = 0; i < 8; i++) {
mSelectList.add(false);
}
mWeekRepeatAdapter = new WeekRepeatAdapter(this, mSelectList);
gvDateSelect.setAdapter(mWeekRepeatAdapter);
gvDateSelect.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
isLock = true;
handler.removeMessages(handler_key.UNLOCK.ordinal());
boolean isSelected = mSelectList.get(position);
mSelectList.set(position, !isSelected);
mWeekRepeatAdapter.notifyDataSetInvalidated();
mCenter.cWeekRepeat(mXpgWifiDevice, bytes2Integer(mSelectList));
handler.sendEmptyMessageDelayed(handler_key.UNLOCK.ordinal(), Lock_Time);
}
});
uiNow = UI_STATE.MENU;
switch(UI_STATE.MENU) {
case MENU:
tvTitle.setText(R.string.appoinment);
llAppointmentMenu.setVisibility(View.VISIBLE);
llSetAppointment.setVisibility(View.GONE);
break;
case SET_APPOINTMENT:
tvTitle.setText(R.string.timing_appointment);
llAppointmentMenu.setVisibility(View.GONE);
llSetAppointment.setVisibility(View.VISIBLE);
break;
}
} | private void initView() {
gvDateSelect = (GridView) findViewById(R.id.gvDateSelect);
tvTiming = (TextView) findViewById(R.id.tvTiming);
tvDelay = (TextView) findViewById(R.id.tvDelay);
tvTimingTime = (TextView) findViewById(R.id.tvTimingTime);
tvDelayTime = (TextView) findViewById(R.id.tvDelayTime);
tbTiming = (ToggleButton) findViewById(R.id.tbTimingFlag);
tbDelay = (ToggleButton) findViewById(R.id.tbDelayFlag);
ivBack = (ImageView) findViewById(R.id.ivBack);
llAppointmentMenu = (LinearLayout) findViewById(R.id.llAppointmentMenu);
llSetAppointment = (LinearLayout) findViewById(R.id.llSetAppointment);
rlStartTimeSetting = (RelativeLayout) findViewById(R.id.rlStartTimeSetting);
rlEndTimeSetting = (RelativeLayout) findViewById(R.id.rlEndTimeSetting);
tvTimingStart = (TextView) findViewById(R.id.tvTimingStart);
tvTimingEnd = (TextView) findViewById(R.id.tvTimingEnd);
tvTitle = (TextView) findViewById(R.id.tvTitle);
mSelectList = new ArrayList<Boolean>();
for (int i = 0; i < 8; i++) {
mSelectList.add(false);
}
mWeekRepeatAdapter = new WeekRepeatAdapter(this, mSelectList);
gvDateSelect.setAdapter(mWeekRepeatAdapter);
gvDateSelect.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
isLock = true;
handler.removeMessages(handler_key.UNLOCK.ordinal());
boolean isSelected = mSelectList.get(position);
mSelectList.set(position, !isSelected);
mWeekRepeatAdapter.notifyDataSetInvalidated();
mCenter.cWeekRepeat(mXpgWifiDevice, bytes2Integer(mSelectList));
handler.sendEmptyMessageDelayed(handler_key.UNLOCK.ordinal(), Lock_Time);
}
});
<DeepExtract>
uiNow = UI_STATE.MENU;
switch(UI_STATE.MENU) {
case MENU:
tvTitle.setText(R.string.appoinment);
llAppointmentMenu.setVisibility(View.VISIBLE);
llSetAppointment.setVisibility(View.GONE);
break;
case SET_APPOINTMENT:
tvTitle.setText(R.string.timing_appointment);
llAppointmentMenu.setVisibility(View.GONE);
llSetAppointment.setVisibility(View.VISIBLE);
break;
}
</DeepExtract>
} | Gizwits-SmartSocket_Android | positive | 2,793 |
public static ZonedDateTime now(Clock clock) {
Jdk7Methods.Objects_requireNonNull(clock, "clock");
final Instant now = clock.instant();
Jdk7Methods.Objects_requireNonNull(now, "instant");
Jdk7Methods.Objects_requireNonNull(clock.getZone(), "zone");
return create(now.getEpochSecond(), now.getNano(), clock.getZone());
} | public static ZonedDateTime now(Clock clock) {
Jdk7Methods.Objects_requireNonNull(clock, "clock");
final Instant now = clock.instant();
<DeepExtract>
Jdk7Methods.Objects_requireNonNull(now, "instant");
Jdk7Methods.Objects_requireNonNull(clock.getZone(), "zone");
return create(now.getEpochSecond(), now.getNano(), clock.getZone());
</DeepExtract>
} | gwt-time | positive | 2,796 |
public void changeFragmentShader(String fragmentShader) {
if (fragmentShader == null) {
fragmentShader = FRAGMENT_SHADER;
}
GLES20.glDeleteProgram(mProgram);
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, VERTEX_SHADER);
if (vertexShader == 0) {
mProgram = 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShader);
if (pixelShader == 0) {
mProgram = 0;
}
int program = GLES20.glCreateProgram();
checkGlError("glCreateProgram");
if (program == 0) {
Log.e(TAG, "Could not create program");
}
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e(TAG, "Could not link program: ");
Log.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
return program;
if (mProgram == 0) {
throw new RuntimeException("failed creating program");
}
} | public void changeFragmentShader(String fragmentShader) {
if (fragmentShader == null) {
fragmentShader = FRAGMENT_SHADER;
}
GLES20.glDeleteProgram(mProgram);
<DeepExtract>
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, VERTEX_SHADER);
if (vertexShader == 0) {
mProgram = 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShader);
if (pixelShader == 0) {
mProgram = 0;
}
int program = GLES20.glCreateProgram();
checkGlError("glCreateProgram");
if (program == 0) {
Log.e(TAG, "Could not create program");
}
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e(TAG, "Could not link program: ");
Log.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
return program;
</DeepExtract>
if (mProgram == 0) {
throw new RuntimeException("failed creating program");
}
} | Endoscope | positive | 2,797 |
public Builder addMaxEnergies(int value) {
if (!((bitField0_ & 0x00000002) != 0)) {
maxEnergies_ = mutableCopy(maxEnergies_);
bitField0_ |= 0x00000002;
}
maxEnergies_.addInt(value);
onChanged();
return this;
} | public Builder addMaxEnergies(int value) {
<DeepExtract>
if (!((bitField0_ & 0x00000002) != 0)) {
maxEnergies_ = mutableCopy(maxEnergies_);
bitField0_ |= 0x00000002;
}
</DeepExtract>
maxEnergies_.addInt(value);
onChanged();
return this;
} | FightingICE | positive | 2,798 |
public Object generateEmptyChunk(Object world, int xPos, int zPos) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
Object primer = rChunkPrimer.createChunkPrimer();
short[] data = new short[65536];
rChunkPrimer.setData(primer, data);
Object chunk = c_chunk.newInstance(world, primer, xPos, zPos);
m_genHeightMap.invoke(chunk);
onChunkLoad(chunk);
return chunk;
} | public Object generateEmptyChunk(Object world, int xPos, int zPos) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
Object primer = rChunkPrimer.createChunkPrimer();
short[] data = new short[65536];
rChunkPrimer.setData(primer, data);
<DeepExtract>
Object chunk = c_chunk.newInstance(world, primer, xPos, zPos);
m_genHeightMap.invoke(chunk);
onChunkLoad(chunk);
return chunk;
</DeepExtract>
} | MC-ticker | positive | 2,799 |
public static void show(Context context, String text, int duration) {
if (sToast == null) {
sToast = Toast.makeText(context, text, duration);
}
sToast.setText(text);
sToast.setDuration(duration);
sToast.show();
} | public static void show(Context context, String text, int duration) {
<DeepExtract>
if (sToast == null) {
sToast = Toast.makeText(context, text, duration);
}
sToast.setText(text);
sToast.setDuration(duration);
sToast.show();
</DeepExtract>
} | Meizi | positive | 2,800 |
public void testDiffPrettyHtml() {
LinkedList<Diff> diffs = diffList(new Diff(EQUAL, "a\n"), new Diff(DELETE, "<B>b</B>"), new Diff(INSERT, "c&d"));
Assert.assertEquals("diff_prettyHtml:", "<span>a¶<br></span><del style=\"background:#ffe6e6;\"><B>b</B></del><ins style=\"background:#e6ffe6;\">c&d</ins>", dmp.diff_prettyHtml(diffs));
} | public void testDiffPrettyHtml() {
LinkedList<Diff> diffs = diffList(new Diff(EQUAL, "a\n"), new Diff(DELETE, "<B>b</B>"), new Diff(INSERT, "c&d"));
<DeepExtract>
Assert.assertEquals("diff_prettyHtml:", "<span>a¶<br></span><del style=\"background:#ffe6e6;\"><B>b</B></del><ins style=\"background:#e6ffe6;\">c&d</ins>", dmp.diff_prettyHtml(diffs));
</DeepExtract>
} | frpMgr | positive | 2,801 |
public static void blurShape(float g, float f, float h, float height, float intensity, float blurWidth, float blurHeight) {
ScaledResolution scale = new ScaledResolution(mc);
int factor = scale.getScaleFactor();
int factor2 = scale.getScaledWidth();
int factor3 = scale.getScaledHeight();
if (lastScale != factor || lastScaleWidth != factor2 || lastScaleHeight != factor3 || buffer == null || blurShader == null) {
initFboAndShader();
}
lastScale = factor;
lastScaleWidth = factor2;
lastScaleHeight = factor3;
GL11.glScissor((int) (g * factor), (int) ((mc.displayHeight - (f * factor) - height * factor)) + 1, (int) (h * factor), (int) (height * factor));
GL11.glEnable(GL11.GL_SCISSOR_TEST);
blurShader.listShaders.get(0).getShaderManager().getShaderUniform("BlurDir").set(blurWidth, blurHeight);
blurShader.listShaders.get(1).getShaderManager().getShaderUniform("BlurDir").set(blurHeight, blurWidth);
buffer.bindFramebuffer(true);
blurShader.loadShaderGroup(mc.timer.renderPartialTicks);
mc.getFramebuffer().bindFramebuffer(true);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
} | public static void blurShape(float g, float f, float h, float height, float intensity, float blurWidth, float blurHeight) {
ScaledResolution scale = new ScaledResolution(mc);
int factor = scale.getScaleFactor();
int factor2 = scale.getScaledWidth();
int factor3 = scale.getScaledHeight();
if (lastScale != factor || lastScaleWidth != factor2 || lastScaleHeight != factor3 || buffer == null || blurShader == null) {
initFboAndShader();
}
lastScale = factor;
lastScaleWidth = factor2;
lastScaleHeight = factor3;
GL11.glScissor((int) (g * factor), (int) ((mc.displayHeight - (f * factor) - height * factor)) + 1, (int) (h * factor), (int) (height * factor));
GL11.glEnable(GL11.GL_SCISSOR_TEST);
<DeepExtract>
blurShader.listShaders.get(0).getShaderManager().getShaderUniform("BlurDir").set(blurWidth, blurHeight);
blurShader.listShaders.get(1).getShaderManager().getShaderUniform("BlurDir").set(blurHeight, blurWidth);
</DeepExtract>
buffer.bindFramebuffer(true);
blurShader.loadShaderGroup(mc.timer.renderPartialTicks);
mc.getFramebuffer().bindFramebuffer(true);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
} | Hydrogen | positive | 2,802 |
public void updateWeekView(int scroll, Date today, int firstDayOfWeek, Collection<CalendarItem> events, List<CalendarDay> days) {
while (outer.getWidgetCount() > 0) {
outer.remove(0);
}
monthGrid = null;
String[] realDayNames = new String[getDayNames().length];
int j = 0;
for (int i = 1; i < getDayNames().length; i++) {
realDayNames[j++] = getDayNames()[i];
}
realDayNames[j] = getDayNames()[0];
weeklyLongEvents = new WeeklyLongItems(this);
if (weekGrid == null) {
weekGrid = new WeekGrid(this, is24HFormat());
}
weekGrid.setFirstHour(getFirstHourOfTheDay());
weekGrid.setLastHour(getLastHourOfTheDay());
weekGrid.getTimeBar().updateTimeBar(is24HFormat());
dayToolbar.clear();
dayToolbar.addBackButton();
dayToolbar.setVerticalSized(isHeightUndefined);
dayToolbar.setHorizontalSized(isWidthUndefined);
weekGrid.clearDates();
weekGrid.setDisabled(isDisabled());
for (CalendarDay day : days) {
Date date = day.getDate();
int dayOfWeek = day.getDayOfWeek();
if (dayOfWeek < getFirstDayNumber() || dayOfWeek > getLastDayNumber()) {
continue;
}
boolean isToday = false;
int dayOfMonth = date.getDate();
if (today.getDate() == dayOfMonth && today.getYear() == date.getYear() && today.getMonth() == date.getMonth()) {
isToday = true;
}
dayToolbar.add(realDayNames[dayOfWeek - 1], date, day.getLocalizedDateFormat(), isToday ? "today" : null);
weeklyLongEvents.addDate(date);
weekGrid.addDate(date, day.getStyledSlots());
if (isToday) {
weekGrid.setToday(date, today);
}
}
dayToolbar.addNextButton();
List<CalendarItem> allDayLong = new ArrayList<>();
List<CalendarItem> belowDayLong = new ArrayList<>();
for (CalendarItem item : sortItems(events)) {
if (item.isAllDay()) {
allDayLong.add(item);
} else {
belowDayLong.add(item);
}
}
weeklyLongEvents.addItems(allDayLong);
for (CalendarItem item : belowDayLong) {
weekGrid.addItem(item);
}
outer.add(dayToolbar, DockPanel.NORTH);
outer.add(weeklyLongEvents, DockPanel.NORTH);
outer.add(weekGrid, DockPanel.SOUTH);
weekGrid.setVerticalScrollPosition(scroll);
} | public void updateWeekView(int scroll, Date today, int firstDayOfWeek, Collection<CalendarItem> events, List<CalendarDay> days) {
while (outer.getWidgetCount() > 0) {
outer.remove(0);
}
monthGrid = null;
String[] realDayNames = new String[getDayNames().length];
int j = 0;
for (int i = 1; i < getDayNames().length; i++) {
realDayNames[j++] = getDayNames()[i];
}
realDayNames[j] = getDayNames()[0];
weeklyLongEvents = new WeeklyLongItems(this);
if (weekGrid == null) {
weekGrid = new WeekGrid(this, is24HFormat());
}
weekGrid.setFirstHour(getFirstHourOfTheDay());
weekGrid.setLastHour(getLastHourOfTheDay());
weekGrid.getTimeBar().updateTimeBar(is24HFormat());
dayToolbar.clear();
dayToolbar.addBackButton();
dayToolbar.setVerticalSized(isHeightUndefined);
dayToolbar.setHorizontalSized(isWidthUndefined);
weekGrid.clearDates();
weekGrid.setDisabled(isDisabled());
for (CalendarDay day : days) {
Date date = day.getDate();
int dayOfWeek = day.getDayOfWeek();
if (dayOfWeek < getFirstDayNumber() || dayOfWeek > getLastDayNumber()) {
continue;
}
boolean isToday = false;
int dayOfMonth = date.getDate();
if (today.getDate() == dayOfMonth && today.getYear() == date.getYear() && today.getMonth() == date.getMonth()) {
isToday = true;
}
dayToolbar.add(realDayNames[dayOfWeek - 1], date, day.getLocalizedDateFormat(), isToday ? "today" : null);
weeklyLongEvents.addDate(date);
weekGrid.addDate(date, day.getStyledSlots());
if (isToday) {
weekGrid.setToday(date, today);
}
}
dayToolbar.addNextButton();
<DeepExtract>
List<CalendarItem> allDayLong = new ArrayList<>();
List<CalendarItem> belowDayLong = new ArrayList<>();
for (CalendarItem item : sortItems(events)) {
if (item.isAllDay()) {
allDayLong.add(item);
} else {
belowDayLong.add(item);
}
}
weeklyLongEvents.addItems(allDayLong);
for (CalendarItem item : belowDayLong) {
weekGrid.addItem(item);
}
</DeepExtract>
outer.add(dayToolbar, DockPanel.NORTH);
outer.add(weeklyLongEvents, DockPanel.NORTH);
outer.add(weekGrid, DockPanel.SOUTH);
weekGrid.setVerticalScrollPosition(scroll);
} | calendar-component | positive | 2,803 |
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (mTask != null) {
mTask.cancel();
mTask = null;
}
mTask = new MyTimerTask(updateHandler);
timer.schedule(mTask, 0, 10);
} | @Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
<DeepExtract>
if (mTask != null) {
mTask.cancel();
mTask = null;
}
mTask = new MyTimerTask(updateHandler);
timer.schedule(mTask, 0, 10);
</DeepExtract>
} | PracticeDemo | positive | 2,804 |
public int[] getIntArray(String key) {
String[] array;
String v = p.getProperty(key);
if (v == null) {
array = new String[0];
} else {
array = StringTokenizerUtils.split(v, ",");
}
int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = Integer.parseInt(array[i]);
}
return result;
} | public int[] getIntArray(String key) {
<DeepExtract>
String[] array;
String v = p.getProperty(key);
if (v == null) {
array = new String[0];
} else {
array = StringTokenizerUtils.split(v, ",");
}
</DeepExtract>
int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = Integer.parseInt(array[i]);
}
return result;
} | framework | positive | 2,805 |
public static void setPublisher(Model metadata, IRI uri, Agent publisher) {
if (publisher == null) {
metadata.filter(uri, DCTERMS.PUBLISHER, null).stream().findFirst().ifPresent(statement -> {
final IRI publisherUri = i(statement.getObject().stringValue());
metadata.remove(uri, DCTERMS.PUBLISHER, publisherUri);
metadata.remove(publisherUri, RDF.TYPE, null);
metadata.remove(publisherUri, FOAF.NAME, null);
});
} else {
update(metadata, uri, DCTERMS.PUBLISHER, publisher.getUri());
update(metadata, publisher.getUri(), RDF.TYPE, publisher.getType());
update(metadata, publisher.getUri(), FOAF.NAME, publisher.getName());
}
} | public static void setPublisher(Model metadata, IRI uri, Agent publisher) {
<DeepExtract>
if (publisher == null) {
metadata.filter(uri, DCTERMS.PUBLISHER, null).stream().findFirst().ifPresent(statement -> {
final IRI publisherUri = i(statement.getObject().stringValue());
metadata.remove(uri, DCTERMS.PUBLISHER, publisherUri);
metadata.remove(publisherUri, RDF.TYPE, null);
metadata.remove(publisherUri, FOAF.NAME, null);
});
} else {
update(metadata, uri, DCTERMS.PUBLISHER, publisher.getUri());
update(metadata, publisher.getUri(), RDF.TYPE, publisher.getType());
update(metadata, publisher.getUri(), FOAF.NAME, publisher.getName());
}
</DeepExtract>
} | FAIRDataPoint | positive | 2,806 |
@Override
public void visit(final IntersectionType n, final Void arg) {
if (configuration.isIgnoreComments())
return;
if (n instanceof Comment)
return;
Node parent = n.getParentNode().orElse(null);
if (parent == null)
return;
List<Node> everything = new ArrayList<>(parent.getChildNodes());
sortByBeginPosition(everything);
int positionOfTheChild = -1;
for (int i = 0; i < everything.size(); ++i) {
if (everything.get(i) == n) {
positionOfTheChild = i;
break;
}
}
if (positionOfTheChild == -1) {
throw new AssertionError("I am not a child of my parent.");
}
int positionOfPreviousChild = -1;
for (int i = positionOfTheChild - 1; i >= 0 && positionOfPreviousChild == -1; i--) {
if (!(everything.get(i) instanceof Comment))
positionOfPreviousChild = i;
}
for (int i = positionOfPreviousChild + 1; i < positionOfTheChild; i++) {
Node nodeToPrint = everything.get(i);
if (!(nodeToPrint instanceof Comment)) {
throw new RuntimeException("Expected comment, instead " + nodeToPrint.getClass() + ". Position of previous child: " + positionOfPreviousChild + ", position of child " + positionOfTheChild);
}
nodeToPrint.accept(this, null);
}
n.getComment().ifPresent(c -> c.accept(this, arg));
if (n.getAnnotations().isEmpty()) {
return;
}
if (false) {
printer.print(" ");
}
for (AnnotationExpr annotation : n.getAnnotations()) {
annotation.accept(this, arg);
printer.print(" ");
}
boolean isFirst = true;
for (ReferenceType element : n.getElements()) {
if (isFirst) {
isFirst = false;
} else {
printer.print(" & ");
}
element.accept(this, arg);
}
} | @Override
public void visit(final IntersectionType n, final Void arg) {
if (configuration.isIgnoreComments())
return;
if (n instanceof Comment)
return;
Node parent = n.getParentNode().orElse(null);
if (parent == null)
return;
List<Node> everything = new ArrayList<>(parent.getChildNodes());
sortByBeginPosition(everything);
int positionOfTheChild = -1;
for (int i = 0; i < everything.size(); ++i) {
if (everything.get(i) == n) {
positionOfTheChild = i;
break;
}
}
if (positionOfTheChild == -1) {
throw new AssertionError("I am not a child of my parent.");
}
int positionOfPreviousChild = -1;
for (int i = positionOfTheChild - 1; i >= 0 && positionOfPreviousChild == -1; i--) {
if (!(everything.get(i) instanceof Comment))
positionOfPreviousChild = i;
}
for (int i = positionOfPreviousChild + 1; i < positionOfTheChild; i++) {
Node nodeToPrint = everything.get(i);
if (!(nodeToPrint instanceof Comment)) {
throw new RuntimeException("Expected comment, instead " + nodeToPrint.getClass() + ". Position of previous child: " + positionOfPreviousChild + ", position of child " + positionOfTheChild);
}
nodeToPrint.accept(this, null);
}
n.getComment().ifPresent(c -> c.accept(this, arg));
<DeepExtract>
if (n.getAnnotations().isEmpty()) {
return;
}
if (false) {
printer.print(" ");
}
for (AnnotationExpr annotation : n.getAnnotations()) {
annotation.accept(this, arg);
printer.print(" ");
}
</DeepExtract>
boolean isFirst = true;
for (ReferenceType element : n.getElements()) {
if (isFirst) {
isFirst = false;
} else {
printer.print(" & ");
}
element.accept(this, arg);
}
} | Matcher | positive | 2,807 |
@Override
public SelectionCoreImpl mean(final Object column) {
if (currentSelection != null) {
moveToColumns(currentSelection);
}
currentSelection = FunctionFactory.mean(column);
return this;
} | @Override
public SelectionCoreImpl mean(final Object column) {
<DeepExtract>
if (currentSelection != null) {
moveToColumns(currentSelection);
}
currentSelection = FunctionFactory.mean(column);
return this;
</DeepExtract>
} | influxdb-java | positive | 2,809 |
public void onDestroy() {
if (mFileLoadTask != null) {
mFileLoadTask.destroy();
}
if (mStrLoadTask != null) {
mStrLoadTask.destroy();
}
} | public void onDestroy() {
if (mFileLoadTask != null) {
mFileLoadTask.destroy();
}
<DeepExtract>
if (mStrLoadTask != null) {
mStrLoadTask.destroy();
}
</DeepExtract>
} | HwTxtReader | positive | 2,810 |
private void applyCloseAndRefresh(ActionEvent actionEvent) {
Settings.getInstance().additionalFolders = additionalXmlFilesBox.getText();
Settings.getInstance().cbAlsoImportTxtFiles = cbAlsoImportTxtFiles.isSelected();
Settings.getInstance().toolbarDeselectEverything = cbDeselectAll.isSelected();
Settings.getInstance().disableOutputParsing = cbDisableOutputParsing.isSelected();
Settings.getInstance().disableOutputParsingWarning = cbDisableOutputParsingWarning.isSelected();
Settings.getInstance().cbShowNonexistentOptionFirst = cbFirstCompletionOption.isSelected();
Settings.getInstance().toolbarReloadAll = cbReloadAll.isSelected();
Settings.getInstance().cbAutoExpandSelectedTests = cbAutoExpandSelectedTests.isSelected();
Settings.getInstance().cbRunGarbageCollection = cbGarbageCollect.isSelected();
Settings.getInstance().cbHighlightSameCells = cbHighlightSameCells.isSelected();
Settings.getInstance().cbUseStructureChanged = cbUseStructureChanged.isSelected();
Settings.getInstance().cbUseSystemColorWindow = cbUseSystemColorWindow.isSelected();
Settings.getInstance().cbAutocompleteVariables = cbAutocompleteVariables.isSelected();
Settings.getInstance().reloadOnChangeStrategy = cbReloadStrategy.getValue();
try {
Settings.getInstance().numberOfSuccessesBeforeEnd = Integer.parseInt(tbNumber.getText());
mainForm.runTab.numberOfSuccessesToStop.setValue(Settings.getInstance().numberOfSuccessesBeforeEnd);
} catch (NumberFormatException e) {
e.printStackTrace();
}
Settings.getInstance().saveAllSettings();
mainForm.updateAdditionalToolbarButtonsVisibility();
mainForm.reloadExternalLibraries();
this.close();
mainForm.reloadAll();
} | private void applyCloseAndRefresh(ActionEvent actionEvent) {
<DeepExtract>
Settings.getInstance().additionalFolders = additionalXmlFilesBox.getText();
Settings.getInstance().cbAlsoImportTxtFiles = cbAlsoImportTxtFiles.isSelected();
Settings.getInstance().toolbarDeselectEverything = cbDeselectAll.isSelected();
Settings.getInstance().disableOutputParsing = cbDisableOutputParsing.isSelected();
Settings.getInstance().disableOutputParsingWarning = cbDisableOutputParsingWarning.isSelected();
Settings.getInstance().cbShowNonexistentOptionFirst = cbFirstCompletionOption.isSelected();
Settings.getInstance().toolbarReloadAll = cbReloadAll.isSelected();
Settings.getInstance().cbAutoExpandSelectedTests = cbAutoExpandSelectedTests.isSelected();
Settings.getInstance().cbRunGarbageCollection = cbGarbageCollect.isSelected();
Settings.getInstance().cbHighlightSameCells = cbHighlightSameCells.isSelected();
Settings.getInstance().cbUseStructureChanged = cbUseStructureChanged.isSelected();
Settings.getInstance().cbUseSystemColorWindow = cbUseSystemColorWindow.isSelected();
Settings.getInstance().cbAutocompleteVariables = cbAutocompleteVariables.isSelected();
Settings.getInstance().reloadOnChangeStrategy = cbReloadStrategy.getValue();
try {
Settings.getInstance().numberOfSuccessesBeforeEnd = Integer.parseInt(tbNumber.getText());
mainForm.runTab.numberOfSuccessesToStop.setValue(Settings.getInstance().numberOfSuccessesBeforeEnd);
} catch (NumberFormatException e) {
e.printStackTrace();
}
Settings.getInstance().saveAllSettings();
mainForm.updateAdditionalToolbarButtonsVisibility();
mainForm.reloadExternalLibraries();
this.close();
</DeepExtract>
mainForm.reloadAll();
} | snowride | positive | 2,811 |
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
setSelected(true);
} else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
setSelected(false);
}
boolean ret = l.onTouch(v, event);
if (!ret && mOnTouchStateListener != null) {
return mOnTouchStateListener.onTouch(v, event);
} else {
return ret;
}
} | @Override
public boolean onTouch(View v, MotionEvent event) {
<DeepExtract>
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
setSelected(true);
} else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
setSelected(false);
}
</DeepExtract>
boolean ret = l.onTouch(v, event);
if (!ret && mOnTouchStateListener != null) {
return mOnTouchStateListener.onTouch(v, event);
} else {
return ret;
}
} | FuAgoraDemoDroid | positive | 2,812 |
@Override
public void actionPerformed(ActionEvent e) {
if (DownloadPanel.this.jTextField.getText() == null || DownloadPanel.this.jTextField.getText().trim().isEmpty()) {
} else if (DownloadPanel.this.jTextField.getText().startsWith("http://") || DownloadPanel.this.jTextField.getText().startsWith("https://")) {
addHttpDownloadTask(DownloadPanel.this.jTextField.getText().trim());
} else {
List<String> barcodes = newTaskInterpreter.getBarcodes(DownloadPanel.this.jTextField.getText().trim(), extractor);
for (String barcode : barcodes) {
addTask(barcode);
}
saveAllJobs(getTableModel().getModelData());
}
jTextField.setText("");
} | @Override
public void actionPerformed(ActionEvent e) {
<DeepExtract>
if (DownloadPanel.this.jTextField.getText() == null || DownloadPanel.this.jTextField.getText().trim().isEmpty()) {
} else if (DownloadPanel.this.jTextField.getText().startsWith("http://") || DownloadPanel.this.jTextField.getText().startsWith("https://")) {
addHttpDownloadTask(DownloadPanel.this.jTextField.getText().trim());
} else {
List<String> barcodes = newTaskInterpreter.getBarcodes(DownloadPanel.this.jTextField.getText().trim(), extractor);
for (String barcode : barcodes) {
addTask(barcode);
}
saveAllJobs(getTableModel().getModelData());
}
</DeepExtract>
jTextField.setText("");
} | dli-downloader | positive | 2,814 |
boolean moveToFist() {
P.bug(isUiThread());
P.bug(isUiThread());
if (0 < 0 || 0 >= mVs.length)
return false;
mVi = 0;
return true;
} | boolean moveToFist() {
P.bug(isUiThread());
<DeepExtract>
P.bug(isUiThread());
if (0 < 0 || 0 >= mVs.length)
return false;
mVi = 0;
return true;
</DeepExtract>
} | netmbuddy | positive | 2,815 |
public Criteria andFhLike(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "fh" + " cannot be null");
}
criteria.add(new Criterion("fh like", value));
return (Criteria) this;
} | public Criteria andFhLike(String value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "fh" + " cannot be null");
}
criteria.add(new Criterion("fh like", value));
</DeepExtract>
return (Criteria) this;
} | einvoice | positive | 2,816 |
public static MessageDigest getMd2Digest() {
try {
return MessageDigest.getInstance(MessageDigestAlgorithms.MD2);
} catch (final NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
} | public static MessageDigest getMd2Digest() {
<DeepExtract>
try {
return MessageDigest.getInstance(MessageDigestAlgorithms.MD2);
} catch (final NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
</DeepExtract>
} | pivaa | positive | 2,817 |
public void onDeath(PlayerDeathInArenaInfo info) {
SkyConfiguration config = plugin.getConfiguration();
SkyPlayer skyPlayer = plugin.getPlayers().getPlayer(info.getKilled().getUniqueId());
if (skyPlayer != null) {
skyPlayer.addScore(config.getDeathScoreDiff());
} else {
backend.addScore(info.getKilled().getUniqueId(), config.getDeathScoreDiff());
}
dataChanged();
} | public void onDeath(PlayerDeathInArenaInfo info) {
SkyConfiguration config = plugin.getConfiguration();
<DeepExtract>
SkyPlayer skyPlayer = plugin.getPlayers().getPlayer(info.getKilled().getUniqueId());
if (skyPlayer != null) {
skyPlayer.addScore(config.getDeathScoreDiff());
} else {
backend.addScore(info.getKilled().getUniqueId(), config.getDeathScoreDiff());
}
dataChanged();
</DeepExtract>
} | SkyWars | positive | 2,818 |
public DynamicResource getColorStrip(long platformId) {
final Minecraft minecraftClient = Minecraft.getInstance();
if (font == null || fontCjk == null) {
final ResourceManager resourceManager = minecraftClient.getResourceManager();
try {
font = Font.createFont(Font.TRUETYPE_FONT, Utilities.getInputStream(resourceManager.getResource(new ResourceLocation(MTR.MOD_ID, "font/noto-sans-semibold.ttf"))));
fontCjk = Font.createFont(Font.TRUETYPE_FONT, Utilities.getInputStream(resourceManager.getResource(new ResourceLocation(MTR.MOD_ID, "font/noto-serif-cjk-tc-semibold.ttf"))));
} catch (Exception e) {
e.printStackTrace();
}
}
if (!resourceRegistryQueue.isEmpty()) {
final Runnable runnable = resourceRegistryQueue.remove(0);
if (runnable != null) {
runnable.run();
}
}
final boolean needsRefresh = resourcesToRefresh.contains(String.format("color_%s", platformId));
final DynamicResource dynamicResource = dynamicResources.get(String.format("color_%s", platformId));
if (dynamicResource != null && !needsRefresh) {
return dynamicResource;
}
RouteMapGenerator.setConstants();
CompletableFuture.supplyAsync(() -> RouteMapGenerator.generateColorStrip(platformId)).thenAccept(nativeImage -> resourceRegistryQueue.add(() -> {
final DynamicResource staticTextureProviderOld = dynamicResources.get(String.format("color_%s", platformId));
if (staticTextureProviderOld != null) {
staticTextureProviderOld.remove();
}
final DynamicResource dynamicResourceNew;
if (nativeImage == null) {
dynamicResourceNew = DefaultRenderingColor.TRANSPARENT.dynamicResource;
} else {
final DynamicTexture dynamicTexture = new DynamicTexture(nativeImage);
String newKey = String.format("color_%s", platformId);
try {
newKey = URLEncoder.encode(String.format("color_%s", platformId), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
final ResourceLocation resourceLocation = new ResourceLocation(MTR.MOD_ID, "dynamic_texture_" + newKey.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9a-z_]", "_"));
minecraftClient.getTextureManager().register(resourceLocation, dynamicTexture);
dynamicResourceNew = new DynamicResource(resourceLocation, dynamicTexture);
}
dynamicResources.put(String.format("color_%s", platformId), dynamicResourceNew);
}));
if (needsRefresh) {
resourcesToRefresh.remove(String.format("color_%s", platformId));
}
if (dynamicResource == null) {
dynamicResources.put(String.format("color_%s", platformId), DefaultRenderingColor.TRANSPARENT.dynamicResource);
return DefaultRenderingColor.TRANSPARENT.dynamicResource;
} else {
return dynamicResource;
}
} | public DynamicResource getColorStrip(long platformId) {
<DeepExtract>
final Minecraft minecraftClient = Minecraft.getInstance();
if (font == null || fontCjk == null) {
final ResourceManager resourceManager = minecraftClient.getResourceManager();
try {
font = Font.createFont(Font.TRUETYPE_FONT, Utilities.getInputStream(resourceManager.getResource(new ResourceLocation(MTR.MOD_ID, "font/noto-sans-semibold.ttf"))));
fontCjk = Font.createFont(Font.TRUETYPE_FONT, Utilities.getInputStream(resourceManager.getResource(new ResourceLocation(MTR.MOD_ID, "font/noto-serif-cjk-tc-semibold.ttf"))));
} catch (Exception e) {
e.printStackTrace();
}
}
if (!resourceRegistryQueue.isEmpty()) {
final Runnable runnable = resourceRegistryQueue.remove(0);
if (runnable != null) {
runnable.run();
}
}
final boolean needsRefresh = resourcesToRefresh.contains(String.format("color_%s", platformId));
final DynamicResource dynamicResource = dynamicResources.get(String.format("color_%s", platformId));
if (dynamicResource != null && !needsRefresh) {
return dynamicResource;
}
RouteMapGenerator.setConstants();
CompletableFuture.supplyAsync(() -> RouteMapGenerator.generateColorStrip(platformId)).thenAccept(nativeImage -> resourceRegistryQueue.add(() -> {
final DynamicResource staticTextureProviderOld = dynamicResources.get(String.format("color_%s", platformId));
if (staticTextureProviderOld != null) {
staticTextureProviderOld.remove();
}
final DynamicResource dynamicResourceNew;
if (nativeImage == null) {
dynamicResourceNew = DefaultRenderingColor.TRANSPARENT.dynamicResource;
} else {
final DynamicTexture dynamicTexture = new DynamicTexture(nativeImage);
String newKey = String.format("color_%s", platformId);
try {
newKey = URLEncoder.encode(String.format("color_%s", platformId), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
final ResourceLocation resourceLocation = new ResourceLocation(MTR.MOD_ID, "dynamic_texture_" + newKey.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9a-z_]", "_"));
minecraftClient.getTextureManager().register(resourceLocation, dynamicTexture);
dynamicResourceNew = new DynamicResource(resourceLocation, dynamicTexture);
}
dynamicResources.put(String.format("color_%s", platformId), dynamicResourceNew);
}));
if (needsRefresh) {
resourcesToRefresh.remove(String.format("color_%s", platformId));
}
if (dynamicResource == null) {
dynamicResources.put(String.format("color_%s", platformId), DefaultRenderingColor.TRANSPARENT.dynamicResource);
return DefaultRenderingColor.TRANSPARENT.dynamicResource;
} else {
return dynamicResource;
}
</DeepExtract>
} | Minecraft-Transit-Railway | positive | 2,819 |
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + TABLE_PRODUCTS);
String query = "CREATE_TABLE" + TABLE_PRODUCTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT" + COLUMN_PRODUCTNAME + "TEXT" + ")";
db.execSQL(query);
} | @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + TABLE_PRODUCTS);
<DeepExtract>
String query = "CREATE_TABLE" + TABLE_PRODUCTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT" + COLUMN_PRODUCTNAME + "TEXT" + ")";
db.execSQL(query);
</DeepExtract>
} | programming | positive | 2,820 |
public JsonObject buyItem(Item item, SRR req, Skins skins) throws NoConnectionException {
JsonObject ret = new JsonObject();
switch(item.section) {
case SRC.Store.dungeon:
cur = keys;
break;
case SRC.Store.event:
cur = eventcurrency;
break;
case SRC.Store.bones:
cur = bones;
break;
default:
cur = gold;
break;
}
int price = item.price;
if (price > getCurrency(cur)) {
ret.addProperty(SRC.errorMessage, "not enough " + cur.get());
return ret;
}
switch(item.name) {
case "chest":
ret.addProperty("buyType", BuyType.CHEST.toString());
Json.override(ret, Json.parseObj(req.purchaseChestItem(item.uid)));
if (ret.get(SRC.errorMessage).isJsonPrimitive())
return ret;
break;
case "skin":
ret.addProperty("buyType", BuyType.SKIN.toString());
Json.override(ret, Json.parseObj(req.purchaseStoreSkin(item.uid)));
if (ret.get(SRC.errorMessage).isJsonPrimitive())
return ret;
skins.addSkin(item.uid);
break;
default:
if (item.uid.equals("dailydrop")) {
ret.addProperty("buyType", BuyType.DAILY.toString());
Json.override(ret, Json.parseObj(req.grantDailyDrop()));
} else {
ret.addProperty("buyType", BuyType.ITEM.toString());
Json.override(ret, Json.parseObj(req.purchaseStoreItem(item.uid)));
}
if (ret.get(SRC.errorMessage).isJsonPrimitive())
return ret;
for (int i = 0; i < shopItems.size(); i++) {
JsonObject item_ = shopItems.get(i).getAsJsonObject();
if (item_.get("itemId").getAsString().equals(item.uid))
item_.addProperty("purchased", 1);
}
break;
}
decreaseCurrency(cur.get(), price);
return ret;
} | public JsonObject buyItem(Item item, SRR req, Skins skins) throws NoConnectionException {
JsonObject ret = new JsonObject();
switch(item.section) {
case SRC.Store.dungeon:
cur = keys;
break;
case SRC.Store.event:
cur = eventcurrency;
break;
case SRC.Store.bones:
cur = bones;
break;
default:
cur = gold;
break;
}
int price = item.price;
if (price > getCurrency(cur)) {
ret.addProperty(SRC.errorMessage, "not enough " + cur.get());
return ret;
}
switch(item.name) {
case "chest":
ret.addProperty("buyType", BuyType.CHEST.toString());
Json.override(ret, Json.parseObj(req.purchaseChestItem(item.uid)));
if (ret.get(SRC.errorMessage).isJsonPrimitive())
return ret;
break;
case "skin":
ret.addProperty("buyType", BuyType.SKIN.toString());
Json.override(ret, Json.parseObj(req.purchaseStoreSkin(item.uid)));
if (ret.get(SRC.errorMessage).isJsonPrimitive())
return ret;
skins.addSkin(item.uid);
break;
default:
if (item.uid.equals("dailydrop")) {
ret.addProperty("buyType", BuyType.DAILY.toString());
Json.override(ret, Json.parseObj(req.grantDailyDrop()));
} else {
ret.addProperty("buyType", BuyType.ITEM.toString());
Json.override(ret, Json.parseObj(req.purchaseStoreItem(item.uid)));
}
if (ret.get(SRC.errorMessage).isJsonPrimitive())
return ret;
for (int i = 0; i < shopItems.size(); i++) {
JsonObject item_ = shopItems.get(i).getAsJsonObject();
if (item_.get("itemId").getAsString().equals(item.uid))
item_.addProperty("purchased", 1);
}
break;
}
<DeepExtract>
decreaseCurrency(cur.get(), price);
</DeepExtract>
return ret;
} | StreamRaidersBot | positive | 2,823 |
public static void openGui(String searchText) {
try {
Class.forName("codechicken.nei.TextField").getDeclaredMethod("setText", String.class).invoke(Class.forName("codechicken.nei.LayoutManager").getDeclaredField("searchField").get(null), searchText);
} catch (Exception e) {
}
Minecraft.getMinecraft().displayGuiScreen(new GuiInventory(Minecraft.getMinecraft().thePlayer));
} | public static void openGui(String searchText) {
<DeepExtract>
try {
Class.forName("codechicken.nei.TextField").getDeclaredMethod("setText", String.class).invoke(Class.forName("codechicken.nei.LayoutManager").getDeclaredField("searchField").get(null), searchText);
} catch (Exception e) {
}
</DeepExtract>
Minecraft.getMinecraft().displayGuiScreen(new GuiInventory(Minecraft.getMinecraft().thePlayer));
} | Xenobyte | positive | 2,824 |
@Test
public void acquireReadWriteLocksOnTwoPages() throws Exception {
bp.getPage(tid1, p0, Permissions.READ_ONLY);
grabLock(tid2, p1, Permissions.READ_WRITE, true);
} | @Test
public void acquireReadWriteLocksOnTwoPages() throws Exception {
<DeepExtract>
bp.getPage(tid1, p0, Permissions.READ_ONLY);
grabLock(tid2, p1, Permissions.READ_WRITE, true);
</DeepExtract>
} | simple-db-hw | positive | 2,825 |
@Override
protected void onPostExecute(PassClickResult result) {
if (result.changed) {
changeReporter.run();
}
} | @Override
<DeepExtract>
</DeepExtract>
protected void onPostExecute(PassClickResult result) {
<DeepExtract>
</DeepExtract>
if (result.changed) {
<DeepExtract>
</DeepExtract>
changeReporter.run();
<DeepExtract>
</DeepExtract>
}
<DeepExtract>
</DeepExtract>
} | zReader-mupdf | positive | 2,826 |
@Override
public void onRefresh() {
refreshSpinners();
new LoadStatData().execute(true);
} | @Override
public void onRefresh() {
<DeepExtract>
refreshSpinners();
new LoadStatData().execute(true);
</DeepExtract>
} | BetterBatteryStats | positive | 2,827 |
public static void smoothScrollToTargetView(RecyclerView recyclerView, View targetView) {
final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (!(layoutManager instanceof ViewPagerLayoutManager))
return;
final int targetPosition = ((ViewPagerLayoutManager) layoutManager).getLayoutPositionOfView(targetView);
final int delta = (ViewPagerLayoutManager) layoutManager.getOffsetToPosition(targetPosition);
if ((ViewPagerLayoutManager) layoutManager.getOrientation() == ViewPagerLayoutManager.VERTICAL) {
recyclerView.smoothScrollBy(0, delta);
} else {
recyclerView.smoothScrollBy(delta, 0);
}
} | public static void smoothScrollToTargetView(RecyclerView recyclerView, View targetView) {
final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (!(layoutManager instanceof ViewPagerLayoutManager))
return;
final int targetPosition = ((ViewPagerLayoutManager) layoutManager).getLayoutPositionOfView(targetView);
<DeepExtract>
final int delta = (ViewPagerLayoutManager) layoutManager.getOffsetToPosition(targetPosition);
if ((ViewPagerLayoutManager) layoutManager.getOrientation() == ViewPagerLayoutManager.VERTICAL) {
recyclerView.smoothScrollBy(0, delta);
} else {
recyclerView.smoothScrollBy(delta, 0);
}
</DeepExtract>
} | RxBanner | positive | 2,828 |
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_dispatch");
expr.dump_with_types(out, n + 2);
dump_AbstractSymbol(out, n + 2, name);
out.println(Utilities.pad(n + 2) + "(");
for (Enumeration e = actual.getElements(); e.hasMoreElements(); ) {
((Expression) e.nextElement()).dump_with_types(out, n + 2);
}
out.println(Utilities.pad(n + 2) + ")");
if (type != null) {
out.println(Utilities.pad(n) + ": " + type.getString());
} else {
out.println(Utilities.pad(n) + ": _no_type");
}
} | public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_dispatch");
expr.dump_with_types(out, n + 2);
dump_AbstractSymbol(out, n + 2, name);
out.println(Utilities.pad(n + 2) + "(");
for (Enumeration e = actual.getElements(); e.hasMoreElements(); ) {
((Expression) e.nextElement()).dump_with_types(out, n + 2);
}
out.println(Utilities.pad(n + 2) + ")");
<DeepExtract>
if (type != null) {
out.println(Utilities.pad(n) + ": " + type.getString());
} else {
out.println(Utilities.pad(n) + ": _no_type");
}
</DeepExtract>
} | Cool-Compiler | positive | 2,830 |
@Override
public void onInitialApplication() {
ThMod.logger.info("SatelIllusPower : onInitialApplication : checkDrawPile");
int temp = AbstractDungeon.player.drawPile.size();
ThMod.logger.info("SatelIllusPower : checkDrawPile :" + " counter : " + counter + " ; drawPile size " + temp + " ; grant energy :" + (temp > counter));
if (temp > counter) {
this.flash();
AbstractDungeon.actionManager.addToBottom(new GainEnergyAction(this.amount));
}
if (temp != counter) {
counter = temp;
}
} | @Override
public void onInitialApplication() {
ThMod.logger.info("SatelIllusPower : onInitialApplication : checkDrawPile");
<DeepExtract>
int temp = AbstractDungeon.player.drawPile.size();
ThMod.logger.info("SatelIllusPower : checkDrawPile :" + " counter : " + counter + " ; drawPile size " + temp + " ; grant energy :" + (temp > counter));
if (temp > counter) {
this.flash();
AbstractDungeon.actionManager.addToBottom(new GainEnergyAction(this.amount));
}
if (temp != counter) {
counter = temp;
}
</DeepExtract>
} | STS_ThMod_MRS | positive | 2,831 |
public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) {
if (mDisposed)
throw new IllegalStateException("IabHelper was disposed of, so it cannot be used.");
if (!mSetupDone) {
logError("Illegal state for operation (" + "launchPurchaseFlow" + "): IAB helper is not set up.");
throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + "launchPurchaseFlow");
}
if (mAsyncInProgress)
throw new IllegalStateException("Can't start async operation (" + "launchPurchaseFlow" + ") because another async operation(" + mAsyncOperation + ") is in progress.");
mAsyncOperation = "launchPurchaseFlow";
mAsyncInProgress = true;
logDebug("Starting async operation: " + "launchPurchaseFlow");
if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) {
IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available.");
flagEndAsync();
if (listener != null)
listener.onIabPurchaseFinished(r, null);
return;
}
try {
logDebug("Constructing buy intent for " + sku + ", item type: " + itemType);
Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData);
int response = getResponseCodeFromBundle(buyIntentBundle);
if (response != BILLING_RESPONSE_RESULT_OK) {
logError("Unable to buy item, Error response: " + getResponseDesc(response));
flagEndAsync();
result = new IabResult(response, "Unable to buy item");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
return;
}
PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode);
mRequestCode = requestCode;
mPurchaseListener = listener;
mPurchasingItemType = itemType;
act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (SendIntentException e) {
logError("SendIntentException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
} catch (RemoteException e) {
logError("RemoteException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
}
} | public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) {
if (mDisposed)
throw new IllegalStateException("IabHelper was disposed of, so it cannot be used.");
if (!mSetupDone) {
logError("Illegal state for operation (" + "launchPurchaseFlow" + "): IAB helper is not set up.");
throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + "launchPurchaseFlow");
}
<DeepExtract>
if (mAsyncInProgress)
throw new IllegalStateException("Can't start async operation (" + "launchPurchaseFlow" + ") because another async operation(" + mAsyncOperation + ") is in progress.");
mAsyncOperation = "launchPurchaseFlow";
mAsyncInProgress = true;
logDebug("Starting async operation: " + "launchPurchaseFlow");
</DeepExtract>
if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) {
IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available.");
flagEndAsync();
if (listener != null)
listener.onIabPurchaseFinished(r, null);
return;
}
try {
logDebug("Constructing buy intent for " + sku + ", item type: " + itemType);
Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData);
int response = getResponseCodeFromBundle(buyIntentBundle);
if (response != BILLING_RESPONSE_RESULT_OK) {
logError("Unable to buy item, Error response: " + getResponseDesc(response));
flagEndAsync();
result = new IabResult(response, "Unable to buy item");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
return;
}
PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode);
mRequestCode = requestCode;
mPurchaseListener = listener;
mPurchasingItemType = itemType;
act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (SendIntentException e) {
logError("SendIntentException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
} catch (RemoteException e) {
logError("RemoteException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
if (listener != null)
listener.onIabPurchaseFinished(result, null);
}
} | scdl | positive | 2,832 |
public void setFrom(Vector3 normal) {
if (released)
throw new IllegalStateException("plane released do not use it.");
zAxis.setFrom(normal);
xAxis.setFrom(normal);
xAxis.orthogonal();
yAxis.setFrom(normal);
yAxis.cross(xAxis);
xAxis.normalize();
yAxis.normalize();
zAxis.normalize();
} | public void setFrom(Vector3 normal) {
<DeepExtract>
if (released)
throw new IllegalStateException("plane released do not use it.");
</DeepExtract>
zAxis.setFrom(normal);
xAxis.setFrom(normal);
xAxis.orthogonal();
yAxis.setFrom(normal);
yAxis.cross(xAxis);
xAxis.normalize();
yAxis.normalize();
zAxis.normalize();
} | Tanks | positive | 2,833 |
@Override
public void onDestroy() {
if (mFrameBufferTextures != null) {
GLES20.glDeleteTextures(mFrameBufferTextures.length, mFrameBufferTextures, 0);
mFrameBufferTextures = null;
}
if (mFrameBuffers != null) {
GLES20.glDeleteFramebuffers(mFrameBuffers.length, mFrameBuffers, 0);
mFrameBuffers = null;
}
for (GPUImageFilter filter : mFilters) {
filter.destroy();
}
super.onDestroy();
} | @Override
public void onDestroy() {
<DeepExtract>
if (mFrameBufferTextures != null) {
GLES20.glDeleteTextures(mFrameBufferTextures.length, mFrameBufferTextures, 0);
mFrameBufferTextures = null;
}
if (mFrameBuffers != null) {
GLES20.glDeleteFramebuffers(mFrameBuffers.length, mFrameBuffers, 0);
mFrameBuffers = null;
}
</DeepExtract>
for (GPUImageFilter filter : mFilters) {
filter.destroy();
}
super.onDestroy();
} | KSYStreamer_Android | positive | 2,834 |
public WaybackStatistics getWayBackStatistics(int statusCode, String url, String url_norm, String crawlDate) throws Exception {
final long startNS = System.nanoTime();
WaybackStatistics stats = new WaybackStatistics();
stats.setStatusCode(statusCode);
stats.setUrl(url);
stats.setUrl_norm(url_norm);
stats.setLastHarvestDate(crawlDate);
stats.setFirstHarvestDate(crawlDate);
String domain = null;
stats.setHarvestDate(crawlDate);
final String statsField = "crawl_date";
long results = 0;
String query = "url_norm:\"" + url_norm + "\" AND crawl_date:{\"" + crawlDate + "\" TO *]";
SolrQuery solrQuery = new SolrQuery(query);
solrQuery.setRows(1);
solrQuery.setGetFieldStatistics(true);
solrQuery.setGetFieldStatistics(statsField);
long call1ns = -System.nanoTime();
SolrUtils.setSolrParams(solrQuery);
QueryResponse rsp;
SolrUtils.setSolrParams(solrQuery);
try {
rsp = METHOD.POST ? solrServer.query(solrQuery, METHOD.POST) : noCacheSolrServer.query(solrQuery, METHOD.POST);
} catch (SolrServerException e) {
throw new RuntimeException("SolrServerException issuing query", e);
} catch (IOException e) {
throw new RuntimeException("IOException issuing query", e);
}
call1ns += System.nanoTime();
final long call1nsSolr = rsp.getQTime();
results += rsp.getResults().getNumFound();
if (rsp.getResults().getNumFound() != 0) {
domain = (String) rsp.getResults().get(0).getFieldValue("domain");
final FieldStatsInfo fieldStats = rsp.getFieldStatsInfo().get(statsField);
if (fieldStats != null) {
stats.setLastHarvestDate(DateUtils.getSolrDate((Date) fieldStats.getMax()));
String next = DateUtils.getSolrDate((Date) fieldStats.getMin());
if (!crawlDate.equals(next)) {
stats.setNextHarvestDate(next);
}
}
}
solrQuery = new SolrQuery("(url_norm:\"" + url_norm + "\") AND crawl_date:[* TO \"" + crawlDate + "\"}");
solrQuery.setRows(1);
solrQuery.add("fl", "domain");
solrQuery.setGetFieldStatistics(true);
solrQuery.setGetFieldStatistics(statsField);
long call2ns = -System.nanoTime();
SolrUtils.setSolrParams(solrQuery);
SolrUtils.setSolrParams(solrQuery);
try {
rsp = METHOD.POST ? solrServer.query(solrQuery, METHOD.POST) : noCacheSolrServer.query(solrQuery, METHOD.POST);
} catch (SolrServerException e) {
throw new RuntimeException("SolrServerException issuing query", e);
} catch (IOException e) {
throw new RuntimeException("IOException issuing query", e);
}
call2ns += System.nanoTime();
final long call2nsSolr = rsp.getQTime();
results += rsp.getResults().getNumFound();
if (rsp.getResults().getNumFound() != 0) {
domain = (String) rsp.getResults().get(0).getFieldValue("domain");
final FieldStatsInfo fieldStats = rsp.getFieldStatsInfo().get(statsField);
if (fieldStats != null) {
stats.setFirstHarvestDate(DateUtils.getSolrDate((Date) fieldStats.getMin()));
String previous = DateUtils.getSolrDate((Date) fieldStats.getMax());
if (!crawlDate.equals(previous)) {
stats.setPreviousHarvestDate(previous);
}
}
}
stats.setNumberOfHarvest(results + 1);
long callDomain = -1;
long callDomainSolr = -1;
if (domain == null) {
solrQuery = new SolrQuery("url_norm:\"" + url_norm + "\"");
solrQuery.setRows(1);
solrQuery.setGetFieldStatistics(true);
solrQuery.setGetFieldStatistics(statsField);
callDomain = -System.nanoTime();
SolrUtils.setSolrParams(solrQuery);
rsp = solrServer.query(solrQuery, METHOD.POST);
callDomain += System.nanoTime();
callDomainSolr = rsp.getQTime();
if (rsp.getResults().size() == 0) {
return stats;
}
domain = (String) rsp.getResults().get(0).getFieldValue("domain");
}
stats.setDomain(domain);
solrQuery = new SolrQuery("domain:\"" + domain + "\"");
solrQuery.setRows(0);
solrQuery.setGetFieldStatistics(true);
solrQuery.setGetFieldStatistics("content_length");
long call3ns = -System.nanoTime();
SolrUtils.setSolrParams(solrQuery);
SolrUtils.setSolrParams(solrQuery);
try {
rsp = METHOD.POST ? solrServer.query(solrQuery, METHOD.POST) : noCacheSolrServer.query(solrQuery, METHOD.POST);
} catch (SolrServerException e) {
throw new RuntimeException("SolrServerException issuing query", e);
} catch (IOException e) {
throw new RuntimeException("IOException issuing query", e);
}
call3ns += System.nanoTime();
final long call3nsSolr = rsp.getQTime();
long numberHarvestDomain = rsp.getResults().getNumFound();
stats.setNumberHarvestDomain(numberHarvestDomain);
if (numberHarvestDomain != 0) {
final FieldStatsInfo fieldStats = rsp.getFieldStatsInfo().get("content_length");
if (fieldStats != null) {
double totalContentLength = (Double) fieldStats.getSum();
stats.setDomainHarvestTotalContentLength((long) totalContentLength);
}
}
log.info(String.format("Wayback statistics for url='%s', solrdate=%s extracted in %d ms " + "(call_1=%d ms (qtime=%d ms), call_2=%d ms (qtime=%d ms), call_3=%d ms (qtime=%d ms), " + "domain_call=%d ms (qtime=%d ms))", url_norm.length() > 50 ? url_norm.substring(0, 50) + "..." : url_norm, crawlDate, (System.nanoTime() - startNS) / M, call1ns / M, call1nsSolr, call2ns / M, call2nsSolr, call3ns / M, call3nsSolr, callDomain / M, callDomainSolr));
return stats;
} | public WaybackStatistics getWayBackStatistics(int statusCode, String url, String url_norm, String crawlDate) throws Exception {
final long startNS = System.nanoTime();
WaybackStatistics stats = new WaybackStatistics();
stats.setStatusCode(statusCode);
stats.setUrl(url);
stats.setUrl_norm(url_norm);
stats.setLastHarvestDate(crawlDate);
stats.setFirstHarvestDate(crawlDate);
String domain = null;
stats.setHarvestDate(crawlDate);
final String statsField = "crawl_date";
long results = 0;
String query = "url_norm:\"" + url_norm + "\" AND crawl_date:{\"" + crawlDate + "\" TO *]";
SolrQuery solrQuery = new SolrQuery(query);
solrQuery.setRows(1);
solrQuery.setGetFieldStatistics(true);
solrQuery.setGetFieldStatistics(statsField);
long call1ns = -System.nanoTime();
SolrUtils.setSolrParams(solrQuery);
QueryResponse rsp;
<DeepExtract>
SolrUtils.setSolrParams(solrQuery);
try {
rsp = METHOD.POST ? solrServer.query(solrQuery, METHOD.POST) : noCacheSolrServer.query(solrQuery, METHOD.POST);
} catch (SolrServerException e) {
throw new RuntimeException("SolrServerException issuing query", e);
} catch (IOException e) {
throw new RuntimeException("IOException issuing query", e);
}
</DeepExtract>
call1ns += System.nanoTime();
final long call1nsSolr = rsp.getQTime();
results += rsp.getResults().getNumFound();
if (rsp.getResults().getNumFound() != 0) {
domain = (String) rsp.getResults().get(0).getFieldValue("domain");
final FieldStatsInfo fieldStats = rsp.getFieldStatsInfo().get(statsField);
if (fieldStats != null) {
stats.setLastHarvestDate(DateUtils.getSolrDate((Date) fieldStats.getMax()));
String next = DateUtils.getSolrDate((Date) fieldStats.getMin());
if (!crawlDate.equals(next)) {
stats.setNextHarvestDate(next);
}
}
}
solrQuery = new SolrQuery("(url_norm:\"" + url_norm + "\") AND crawl_date:[* TO \"" + crawlDate + "\"}");
solrQuery.setRows(1);
solrQuery.add("fl", "domain");
solrQuery.setGetFieldStatistics(true);
solrQuery.setGetFieldStatistics(statsField);
long call2ns = -System.nanoTime();
SolrUtils.setSolrParams(solrQuery);
<DeepExtract>
SolrUtils.setSolrParams(solrQuery);
try {
rsp = METHOD.POST ? solrServer.query(solrQuery, METHOD.POST) : noCacheSolrServer.query(solrQuery, METHOD.POST);
} catch (SolrServerException e) {
throw new RuntimeException("SolrServerException issuing query", e);
} catch (IOException e) {
throw new RuntimeException("IOException issuing query", e);
}
</DeepExtract>
call2ns += System.nanoTime();
final long call2nsSolr = rsp.getQTime();
results += rsp.getResults().getNumFound();
if (rsp.getResults().getNumFound() != 0) {
domain = (String) rsp.getResults().get(0).getFieldValue("domain");
final FieldStatsInfo fieldStats = rsp.getFieldStatsInfo().get(statsField);
if (fieldStats != null) {
stats.setFirstHarvestDate(DateUtils.getSolrDate((Date) fieldStats.getMin()));
String previous = DateUtils.getSolrDate((Date) fieldStats.getMax());
if (!crawlDate.equals(previous)) {
stats.setPreviousHarvestDate(previous);
}
}
}
stats.setNumberOfHarvest(results + 1);
long callDomain = -1;
long callDomainSolr = -1;
if (domain == null) {
solrQuery = new SolrQuery("url_norm:\"" + url_norm + "\"");
solrQuery.setRows(1);
solrQuery.setGetFieldStatistics(true);
solrQuery.setGetFieldStatistics(statsField);
callDomain = -System.nanoTime();
SolrUtils.setSolrParams(solrQuery);
rsp = solrServer.query(solrQuery, METHOD.POST);
callDomain += System.nanoTime();
callDomainSolr = rsp.getQTime();
if (rsp.getResults().size() == 0) {
return stats;
}
domain = (String) rsp.getResults().get(0).getFieldValue("domain");
}
stats.setDomain(domain);
solrQuery = new SolrQuery("domain:\"" + domain + "\"");
solrQuery.setRows(0);
solrQuery.setGetFieldStatistics(true);
solrQuery.setGetFieldStatistics("content_length");
long call3ns = -System.nanoTime();
SolrUtils.setSolrParams(solrQuery);
<DeepExtract>
SolrUtils.setSolrParams(solrQuery);
try {
rsp = METHOD.POST ? solrServer.query(solrQuery, METHOD.POST) : noCacheSolrServer.query(solrQuery, METHOD.POST);
} catch (SolrServerException e) {
throw new RuntimeException("SolrServerException issuing query", e);
} catch (IOException e) {
throw new RuntimeException("IOException issuing query", e);
}
</DeepExtract>
call3ns += System.nanoTime();
final long call3nsSolr = rsp.getQTime();
long numberHarvestDomain = rsp.getResults().getNumFound();
stats.setNumberHarvestDomain(numberHarvestDomain);
if (numberHarvestDomain != 0) {
final FieldStatsInfo fieldStats = rsp.getFieldStatsInfo().get("content_length");
if (fieldStats != null) {
double totalContentLength = (Double) fieldStats.getSum();
stats.setDomainHarvestTotalContentLength((long) totalContentLength);
}
}
log.info(String.format("Wayback statistics for url='%s', solrdate=%s extracted in %d ms " + "(call_1=%d ms (qtime=%d ms), call_2=%d ms (qtime=%d ms), call_3=%d ms (qtime=%d ms), " + "domain_call=%d ms (qtime=%d ms))", url_norm.length() > 50 ? url_norm.substring(0, 50) + "..." : url_norm, crawlDate, (System.nanoTime() - startNS) / M, call1ns / M, call1nsSolr, call2ns / M, call2nsSolr, call3ns / M, call3nsSolr, callDomain / M, callDomainSolr));
return stats;
} | solrwayback | positive | 2,835 |
public static <T> Response<T> createSuccessResponse() {
Response<T> response = new Response<>();
response.setCode(SUCCESS);
if (null != null) {
response.setDescription(null);
}
return response;
} | public static <T> Response<T> createSuccessResponse() {
<DeepExtract>
Response<T> response = new Response<>();
response.setCode(SUCCESS);
if (null != null) {
response.setDescription(null);
}
return response;
</DeepExtract>
} | hkr-si | positive | 2,836 |
@Test
public void shouldRemoveCustomTagForFileConstructor() throws Exception {
File filename = new File(MP3_WITH_ID3V1_AND_ID3V23_AND_CUSTOM_TAGS);
String saveFilename = new Mp3File(filename).getFilename() + ".copy";
try {
new Mp3File(filename).removeCustomTag();
new Mp3File(filename).save(saveFilename);
Mp3File newMp3File = new Mp3File(saveFilename);
assertTrue(newMp3File.hasId3v1Tag());
assertTrue(newMp3File.hasId3v2Tag());
assertFalse(newMp3File.hasCustomTag());
} finally {
TestHelper.deleteFile(saveFilename);
}
} | @Test
public void shouldRemoveCustomTagForFileConstructor() throws Exception {
File filename = new File(MP3_WITH_ID3V1_AND_ID3V23_AND_CUSTOM_TAGS);
<DeepExtract>
String saveFilename = new Mp3File(filename).getFilename() + ".copy";
try {
new Mp3File(filename).removeCustomTag();
new Mp3File(filename).save(saveFilename);
Mp3File newMp3File = new Mp3File(saveFilename);
assertTrue(newMp3File.hasId3v1Tag());
assertTrue(newMp3File.hasId3v2Tag());
assertFalse(newMp3File.hasCustomTag());
} finally {
TestHelper.deleteFile(saveFilename);
}
</DeepExtract>
} | mp3agic | positive | 2,837 |
public void actionPerformed(ActionEvent evt) {
String action = evt.getActionCommand();
Consumer<ContentInfo> applyContentTag = contentInfo -> {
if (contentInfo != null) {
String tag = contentInfo.toMDTag();
markdownWindow.insert(tag + " ", markdownWindow.getCaretPosition());
markdownWindow.moveCaretPosition(markdownWindow.getCaretPosition() + tag.length());
mdTextChange(null);
}
toFront();
};
switch(action) {
case "stack":
toBack();
PIGuiHelper.openContentChooser(null, MD_CONTENT, applyContentTag, ITEM_STACK);
break;
case "recipe":
{
toBack();
PIGuiHelper.openContentChooser(null, GuiContentSelect.SelectMode.PICK_STACK, contentInfo -> SwingUtilities.invokeLater(() -> {
toFront();
if (contentInfo == null)
return;
MDTagDialog tagD = new MDTagDialog(this, MDTagDialog.TagType.RECIPE);
tagD.setStack(StringyStacks.toStringNoCaps(contentInfo.stack));
tagD.setVisible(true);
markdownWindow.insert(tagD.getTag(), markdownWindow.getCaretPosition());
mdTextChange(null);
}), ContentInfo.ContentType.ITEM_STACK);
break;
}
case "image":
toBack();
PIGuiHelper.openContentChooser(null, MD_CONTENT, applyContentTag, IMAGE);
break;
case "link":
{
MDTagDialog tagD = new MDTagDialog(this, MDTagDialog.TagType.LINK);
tagD.setVisible(true);
markdownWindow.insert(tagD.getTag(), markdownWindow.getCaretPosition());
break;
}
case "entity":
toBack();
PIGuiHelper.openContentChooser(null, MD_CONTENT, applyContentTag, ENTITY);
break;
case "rule":
{
MDTagDialog tagD = new MDTagDialog(this, MDTagDialog.TagType.RULE);
tagD.setVisible(true);
markdownWindow.insert(tagD.getTag(), markdownWindow.getCaretPosition());
break;
}
case "table":
{
MDTagDialog tagD = new MDTagDialog(this, MDTagDialog.TagType.TABLE);
tagD.setVisible(true);
markdownWindow.insert(tagD.getTag(), markdownWindow.getCaretPosition());
break;
}
}
mdTextChange(null);
} | public void actionPerformed(ActionEvent evt) {
<DeepExtract>
String action = evt.getActionCommand();
Consumer<ContentInfo> applyContentTag = contentInfo -> {
if (contentInfo != null) {
String tag = contentInfo.toMDTag();
markdownWindow.insert(tag + " ", markdownWindow.getCaretPosition());
markdownWindow.moveCaretPosition(markdownWindow.getCaretPosition() + tag.length());
mdTextChange(null);
}
toFront();
};
switch(action) {
case "stack":
toBack();
PIGuiHelper.openContentChooser(null, MD_CONTENT, applyContentTag, ITEM_STACK);
break;
case "recipe":
{
toBack();
PIGuiHelper.openContentChooser(null, GuiContentSelect.SelectMode.PICK_STACK, contentInfo -> SwingUtilities.invokeLater(() -> {
toFront();
if (contentInfo == null)
return;
MDTagDialog tagD = new MDTagDialog(this, MDTagDialog.TagType.RECIPE);
tagD.setStack(StringyStacks.toStringNoCaps(contentInfo.stack));
tagD.setVisible(true);
markdownWindow.insert(tagD.getTag(), markdownWindow.getCaretPosition());
mdTextChange(null);
}), ContentInfo.ContentType.ITEM_STACK);
break;
}
case "image":
toBack();
PIGuiHelper.openContentChooser(null, MD_CONTENT, applyContentTag, IMAGE);
break;
case "link":
{
MDTagDialog tagD = new MDTagDialog(this, MDTagDialog.TagType.LINK);
tagD.setVisible(true);
markdownWindow.insert(tagD.getTag(), markdownWindow.getCaretPosition());
break;
}
case "entity":
toBack();
PIGuiHelper.openContentChooser(null, MD_CONTENT, applyContentTag, ENTITY);
break;
case "rule":
{
MDTagDialog tagD = new MDTagDialog(this, MDTagDialog.TagType.RULE);
tagD.setVisible(true);
markdownWindow.insert(tagD.getTag(), markdownWindow.getCaretPosition());
break;
}
case "table":
{
MDTagDialog tagD = new MDTagDialog(this, MDTagDialog.TagType.TABLE);
tagD.setVisible(true);
markdownWindow.insert(tagD.getTag(), markdownWindow.getCaretPosition());
break;
}
}
mdTextChange(null);
</DeepExtract>
} | ProjectIntelligence | positive | 2,839 |
@Override
protected Void doInBackground() throws Exception {
boolean externalLogger = true;
long tstart = System.nanoTime();
solutions = algorithmWorker.execute();
long tend = System.nanoTime();
double totalTime = tend - tstart;
totalTime /= 1000000000.0;
ArrayList<Double> extFitnesses = new ArrayList<Double>();
String extPhenotype = null;
for (Solution<Variable<Integer>> solution : solutions) {
extFitnesses = solution.getObjectives();
extPhenotype = problem.generatePhenotype(solution).toString();
logger.info(System.lineSeparator());
logger.info("Fitness for selected objetive(s) = " + solution.getObjectives());
phenotypeString = problem.generatePhenotype(solution).toString();
logger.info("Phenotype = (" + phenotypeString + ")");
}
if (externalLogger) {
ArrayList<FitnessEvaluatorInterface> fitnessFuncs = ctrl.getFitnessFuncs();
String csvName = "Registro.csv";
String fitns = "[";
for (int i = 0; i < fitnessFuncs.size(); i++) {
fitns += fitnessFuncs.get(i).getName();
if (i != fitnessFuncs.size() - 1)
fitns += ", ";
}
fitns += "]";
int aborted = (ctrl.getCurrentGeneration() == ctrl.getGenerations()) ? 0 : 1;
ExtLog extLog = new ExtLog(ctrl.getSelectedSelectionOperator(), ctrl.getSelectedMutationOperator(), ctrl.getMutationProb(), ctrl.getSelectedCrossoverOperator(), ctrl.getCrossProb(), ctrl.getElitismPercentage(), ctrl.getPopulationSize(), ctrl.getGenerations(), ctrl.getItersPerIndividual(), fitns, extFitnesses, extPhenotype, totalTime, aborted);
ExtLogger extlogger = new ExtLogger();
extlogger.generateCSV(extLog, csvName);
}
return null;
} | @Override
protected Void doInBackground() throws Exception {
<DeepExtract>
boolean externalLogger = true;
long tstart = System.nanoTime();
solutions = algorithmWorker.execute();
long tend = System.nanoTime();
double totalTime = tend - tstart;
totalTime /= 1000000000.0;
ArrayList<Double> extFitnesses = new ArrayList<Double>();
String extPhenotype = null;
for (Solution<Variable<Integer>> solution : solutions) {
extFitnesses = solution.getObjectives();
extPhenotype = problem.generatePhenotype(solution).toString();
logger.info(System.lineSeparator());
logger.info("Fitness for selected objetive(s) = " + solution.getObjectives());
phenotypeString = problem.generatePhenotype(solution).toString();
logger.info("Phenotype = (" + phenotypeString + ")");
}
if (externalLogger) {
ArrayList<FitnessEvaluatorInterface> fitnessFuncs = ctrl.getFitnessFuncs();
String csvName = "Registro.csv";
String fitns = "[";
for (int i = 0; i < fitnessFuncs.size(); i++) {
fitns += fitnessFuncs.get(i).getName();
if (i != fitnessFuncs.size() - 1)
fitns += ", ";
}
fitns += "]";
int aborted = (ctrl.getCurrentGeneration() == ctrl.getGenerations()) ? 0 : 1;
ExtLog extLog = new ExtLog(ctrl.getSelectedSelectionOperator(), ctrl.getSelectedMutationOperator(), ctrl.getMutationProb(), ctrl.getSelectedCrossoverOperator(), ctrl.getCrossProb(), ctrl.getElitismPercentage(), ctrl.getPopulationSize(), ctrl.getGenerations(), ctrl.getItersPerIndividual(), fitns, extFitnesses, extPhenotype, totalTime, aborted);
ExtLogger extlogger = new ExtLogger();
extlogger.generateCSV(extLog, csvName);
}
</DeepExtract>
return null;
} | Pac-Man | positive | 2,841 |
public Criteria andCountryNotIn(List<String> values) {
if (values == null) {
throw new RuntimeException("Value for " + "country" + " cannot be null");
}
criteria.add(new Criterion("country not in", values));
return (Criteria) this;
} | public Criteria andCountryNotIn(List<String> values) {
<DeepExtract>
if (values == null) {
throw new RuntimeException("Value for " + "country" + " cannot be null");
}
criteria.add(new Criterion("country not in", values));
</DeepExtract>
return (Criteria) this;
} | answerWeb | positive | 2,842 |
private void presentFragmentInternalRemoveOld(boolean removeLast, final BaseFragment fragment) {
if (fragment == null) {
return;
}
if (!fragmentsStack.isEmpty()) {
BaseFragment lastFragment = fragmentsStack.get(fragmentsStack.size() - 1);
lastFragment.onPause();
}
if (removeLast) {
fragment.onFragmentDestroy();
fragment.setParentLayout(null);
fragmentsStack.remove(fragment);
} else {
if (fragment.fragmentView != null) {
ViewGroup parent = (ViewGroup) fragment.fragmentView.getParent();
if (parent != null) {
parent.removeView(fragment.fragmentView);
}
}
if (fragment.actionBar != null && fragment.actionBar.getAddToContainer()) {
ViewGroup parent = (ViewGroup) fragment.actionBar.getParent();
if (parent != null) {
parent.removeView(fragment.actionBar);
}
}
}
containerViewBack.setVisibility(View.GONE);
} | private void presentFragmentInternalRemoveOld(boolean removeLast, final BaseFragment fragment) {
if (fragment == null) {
return;
}
<DeepExtract>
if (!fragmentsStack.isEmpty()) {
BaseFragment lastFragment = fragmentsStack.get(fragmentsStack.size() - 1);
lastFragment.onPause();
}
</DeepExtract>
if (removeLast) {
fragment.onFragmentDestroy();
fragment.setParentLayout(null);
fragmentsStack.remove(fragment);
} else {
if (fragment.fragmentView != null) {
ViewGroup parent = (ViewGroup) fragment.fragmentView.getParent();
if (parent != null) {
parent.removeView(fragment.fragmentView);
}
}
if (fragment.actionBar != null && fragment.actionBar.getAddToContainer()) {
ViewGroup parent = (ViewGroup) fragment.actionBar.getParent();
if (parent != null) {
parent.removeView(fragment.actionBar);
}
}
}
containerViewBack.setVisibility(View.GONE);
} | TelegramGallery | positive | 2,843 |
@Override
public void onScroll(AbsListView v, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (top != null) {
top.setVisibility(v.canScrollVertically(-1) ? View.VISIBLE : View.INVISIBLE);
}
if (bottom != null) {
bottom.setVisibility(v.canScrollVertically(1) ? View.VISIBLE : View.INVISIBLE);
}
} | @Override
public void onScroll(AbsListView v, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
<DeepExtract>
if (top != null) {
top.setVisibility(v.canScrollVertically(-1) ? View.VISIBLE : View.INVISIBLE);
}
if (bottom != null) {
bottom.setVisibility(v.canScrollVertically(1) ? View.VISIBLE : View.INVISIBLE);
}
</DeepExtract>
} | SamsungOneUi | positive | 2,844 |
@Override
public void onResponse(String response) {
Document doc = Jsoup.parse(response);
Elements elements = doc.select("div[class=zm-item-answer ]");
ZHAnswer answer = ParseUtils.parseHtmlToAnswer(elements.get(0));
mBus.post(new FetchAnswerHRE(answer));
} | @Override
public void onResponse(String response) {
<DeepExtract>
Document doc = Jsoup.parse(response);
Elements elements = doc.select("div[class=zm-item-answer ]");
ZHAnswer answer = ParseUtils.parseHtmlToAnswer(elements.get(0));
mBus.post(new FetchAnswerHRE(answer));
</DeepExtract>
} | ZhihuDemo | positive | 2,846 |
public static ConsentTask create(Context context, String taskId) {
Resources r = context.getResources();
List<Step> steps = new ArrayList<>();
ConsentSectionModel data = ResourceManager.getInstance().getConsentSections().create(context);
String participant = r.getString(R.string.rss_participant);
ConsentSignature signature = new ConsentSignature("participant", participant, null);
DocumentProperties properties = data.getDocumentProperties();
List<ConsentSection> sections = data.getSections();
ConsentQuizModel quiz = data.getQuiz();
signature.setRequiresSignatureImage(properties.requiresSignature());
signature.setRequiresName(properties.requiresName());
signature.setRequiresBirthDate(properties.requiresBirthdate());
ConsentDocument doc = new ConsentDocument();
doc.setTitle(r.getString(R.string.rsb_consent_form_title));
doc.setSignaturePageTitle(R.string.rsb_consent_form_title);
doc.setSignaturePageContent(r.getString(R.string.rsb_consent_signature_content));
doc.setSections(sections);
doc.addSignature(signature);
String htmlDocName = properties.getHtmlDocument();
String htmlFilePath = ResourceManager.getInstance().generatePath(ResourceManager.Resource.TYPE_HTML, htmlDocName);
doc.setHtmlReviewContent(ResourceManager.getResourceAsString(context, htmlFilePath));
for (int i = 0, size = doc.getSections().size(); i < size; i++) {
ConsentSection section = doc.getSections().get(i);
if (!TextUtils.isEmpty(section.getHtmlContent())) {
String htmlFilePath = ResourceManager.getInstance().generatePath(ResourceManager.Resource.TYPE_HTML, section.getHtmlContent());
section.setHtmlContent(ResourceManager.getResourceAsString(context, htmlFilePath));
}
ConsentVisualStep step = new ConsentVisualStep("consent_" + i);
step.setSection(section);
String nextString = context.getString(R.string.rsb_next);
if (section.getType() == ConsentSection.Type.Overview) {
nextString = context.getString(R.string.rsb_get_started);
} else if (i == size - 1) {
nextString = context.getString(R.string.rsb_done);
}
step.setNextButtonString(nextString);
steps.add(step);
}
String investigatorShortDesc = data.getDocumentProperties().getInvestigatorShortDescription();
if (TextUtils.isEmpty(investigatorShortDesc)) {
throw new IllegalArgumentException(INVALID_ARGUMENT_CANNOT_BE_NULL);
}
String investigatorLongDesc = data.getDocumentProperties().getInvestigatorLongDescription();
if (TextUtils.isEmpty(investigatorLongDesc)) {
throw new IllegalArgumentException(INVALID_ARGUMENT_CANNOT_BE_NULL);
}
String localizedLearnMoreHTMLContent = data.getDocumentProperties().getHtmlContent();
if (TextUtils.isEmpty(localizedLearnMoreHTMLContent)) {
throw new IllegalArgumentException(INVALID_ARGUMENT_CANNOT_BE_NULL);
}
ConsentSharingStep sharingStep = new ConsentSharingStep(ID_SHARING);
sharingStep.setOptional(false);
sharingStep.setStepTitle(R.string.rsb_consent);
String shareWidely = r.getString(R.string.rsb_consent_share_widely, investigatorLongDesc);
Choice<String> shareWidelyChoice = new Choice<>(shareWidely, "sponsors_and_partners", null);
String shareRestricted = r.getString(R.string.rsb_consent_share_only, investigatorShortDesc);
Choice<String> shareRestrictedChoice = new Choice<>(shareRestricted, "all_qualified_researchers", null);
sharingStep.setAnswerFormat(new ChoiceAnswerFormat(AnswerFormat.ChoiceAnswerStyle.SingleChoice, shareWidelyChoice, shareRestrictedChoice));
sharingStep.setTitle(r.getString(R.string.rsb_consent_share_title));
sharingStep.setText(r.getString(R.string.rsb_consent_share_description, investigatorLongDesc, localizedLearnMoreHTMLContent));
steps.add(sharingStep);
if (quiz == null) {
LogExt.d(ConsentTask.class, "No quiz specified in consent json, skipping");
return;
}
for (int i = 0; i < quiz.getQuestions().size(); i++) {
ConsentQuizModel.QuizQuestion question = quiz.getQuestions().get(i);
if (i == 0) {
question.setIdentifier(ID_FIRST_QUESTION);
}
ConsentQuizQuestionStep quizStep = new ConsentQuizQuestionStep(question);
steps.add(quizStep);
}
ConsentQuizEvaluationStep evaluationStep = new ConsentQuizEvaluationStep(ID_QUIZ_RESULT, quiz);
steps.add(evaluationStep);
StringBuilder docBuilder = new StringBuilder("</br><div style=\"padding: 10px 10px 10px 10px;\" class='header'>");
String title = context.getString(R.string.rsb_consent_review_title);
docBuilder.append(String.format("<h1 style=\"text-align: center; font-family:sans-serif-light;\">%1$s</h1>", title));
String detail = context.getString(R.string.rsb_consent_review_instruction);
docBuilder.append(String.format("<p style=\"text-align: center\">%1$s</p>", detail));
docBuilder.append("</div></br>");
docBuilder.append(doc.getHtmlReviewContent());
ConsentDocumentStep step = new ConsentDocumentStep(ID_CONSENT_DOC);
step.setConsentHTML(docBuilder.toString());
step.setConfirmMessage(context.getString(R.string.rsb_consent_review_reason));
steps.add(step);
boolean requiresName = doc.getSignature(0).requiresName();
boolean requiresBirthDate = doc.getSignature(0).requiresBirthDate();
if (requiresName || requiresBirthDate) {
List<QuestionStep> formSteps = new ArrayList<>();
if (requiresName) {
TextAnswerFormat format = new TextAnswerFormat();
format.setIsMultipleLines(false);
String placeholder = context.getResources().getString(R.string.rsb_consent_name_placeholder);
String nameText = context.getResources().getString(R.string.rsb_consent_name_full);
formSteps.add(new QuestionStep(ID_FORM_NAME, nameText, format));
}
if (requiresBirthDate) {
Calendar maxDate = Calendar.getInstance();
maxDate.add(Calendar.YEAR, -18);
DateAnswerFormat dobFormat = new BirthDateAnswerFormat(null, 18, 0);
String dobText = context.getResources().getString(R.string.rsb_consent_dob_full);
formSteps.add(new QuestionStep(ID_FORM_DOB, dobText, dobFormat));
}
String formTitle = context.getString(R.string.rsb_consent_form_title);
FormStep formStep = new FormStep(ID_FORM, formTitle, step.getText());
formStep.setStepTitle(R.string.rsb_consent);
formStep.setOptional(false);
formStep.setFormSteps(formSteps);
steps.add(formStep);
}
if (doc.getSignature(0).requiresSignatureImage()) {
ConsentSignatureStep signatureStep = new ConsentSignatureStep(ID_SIGNATURE);
signatureStep.setStepTitle(R.string.rsb_consent);
signatureStep.setTitle(context.getString(R.string.rsb_consent_signature_title));
signatureStep.setText(context.getString(R.string.rsb_consent_signature_instruction));
signatureStep.setOptional(false);
signatureStep.setSignatureDateFormat(doc.getSignature(0).getSignatureDateFormatString());
signatureStep.setStepLayoutClass(ConsentSignatureStepLayout.class);
steps.add(signatureStep);
}
return new ConsentTask(taskId, steps);
} | public static ConsentTask create(Context context, String taskId) {
Resources r = context.getResources();
List<Step> steps = new ArrayList<>();
ConsentSectionModel data = ResourceManager.getInstance().getConsentSections().create(context);
String participant = r.getString(R.string.rss_participant);
ConsentSignature signature = new ConsentSignature("participant", participant, null);
DocumentProperties properties = data.getDocumentProperties();
List<ConsentSection> sections = data.getSections();
ConsentQuizModel quiz = data.getQuiz();
signature.setRequiresSignatureImage(properties.requiresSignature());
signature.setRequiresName(properties.requiresName());
signature.setRequiresBirthDate(properties.requiresBirthdate());
ConsentDocument doc = new ConsentDocument();
doc.setTitle(r.getString(R.string.rsb_consent_form_title));
doc.setSignaturePageTitle(R.string.rsb_consent_form_title);
doc.setSignaturePageContent(r.getString(R.string.rsb_consent_signature_content));
doc.setSections(sections);
doc.addSignature(signature);
String htmlDocName = properties.getHtmlDocument();
String htmlFilePath = ResourceManager.getInstance().generatePath(ResourceManager.Resource.TYPE_HTML, htmlDocName);
doc.setHtmlReviewContent(ResourceManager.getResourceAsString(context, htmlFilePath));
for (int i = 0, size = doc.getSections().size(); i < size; i++) {
ConsentSection section = doc.getSections().get(i);
if (!TextUtils.isEmpty(section.getHtmlContent())) {
String htmlFilePath = ResourceManager.getInstance().generatePath(ResourceManager.Resource.TYPE_HTML, section.getHtmlContent());
section.setHtmlContent(ResourceManager.getResourceAsString(context, htmlFilePath));
}
ConsentVisualStep step = new ConsentVisualStep("consent_" + i);
step.setSection(section);
String nextString = context.getString(R.string.rsb_next);
if (section.getType() == ConsentSection.Type.Overview) {
nextString = context.getString(R.string.rsb_get_started);
} else if (i == size - 1) {
nextString = context.getString(R.string.rsb_done);
}
step.setNextButtonString(nextString);
steps.add(step);
}
String investigatorShortDesc = data.getDocumentProperties().getInvestigatorShortDescription();
if (TextUtils.isEmpty(investigatorShortDesc)) {
throw new IllegalArgumentException(INVALID_ARGUMENT_CANNOT_BE_NULL);
}
String investigatorLongDesc = data.getDocumentProperties().getInvestigatorLongDescription();
if (TextUtils.isEmpty(investigatorLongDesc)) {
throw new IllegalArgumentException(INVALID_ARGUMENT_CANNOT_BE_NULL);
}
String localizedLearnMoreHTMLContent = data.getDocumentProperties().getHtmlContent();
if (TextUtils.isEmpty(localizedLearnMoreHTMLContent)) {
throw new IllegalArgumentException(INVALID_ARGUMENT_CANNOT_BE_NULL);
}
ConsentSharingStep sharingStep = new ConsentSharingStep(ID_SHARING);
sharingStep.setOptional(false);
sharingStep.setStepTitle(R.string.rsb_consent);
String shareWidely = r.getString(R.string.rsb_consent_share_widely, investigatorLongDesc);
Choice<String> shareWidelyChoice = new Choice<>(shareWidely, "sponsors_and_partners", null);
String shareRestricted = r.getString(R.string.rsb_consent_share_only, investigatorShortDesc);
Choice<String> shareRestrictedChoice = new Choice<>(shareRestricted, "all_qualified_researchers", null);
sharingStep.setAnswerFormat(new ChoiceAnswerFormat(AnswerFormat.ChoiceAnswerStyle.SingleChoice, shareWidelyChoice, shareRestrictedChoice));
sharingStep.setTitle(r.getString(R.string.rsb_consent_share_title));
sharingStep.setText(r.getString(R.string.rsb_consent_share_description, investigatorLongDesc, localizedLearnMoreHTMLContent));
steps.add(sharingStep);
if (quiz == null) {
LogExt.d(ConsentTask.class, "No quiz specified in consent json, skipping");
return;
}
for (int i = 0; i < quiz.getQuestions().size(); i++) {
ConsentQuizModel.QuizQuestion question = quiz.getQuestions().get(i);
if (i == 0) {
question.setIdentifier(ID_FIRST_QUESTION);
}
ConsentQuizQuestionStep quizStep = new ConsentQuizQuestionStep(question);
steps.add(quizStep);
}
ConsentQuizEvaluationStep evaluationStep = new ConsentQuizEvaluationStep(ID_QUIZ_RESULT, quiz);
steps.add(evaluationStep);
<DeepExtract>
StringBuilder docBuilder = new StringBuilder("</br><div style=\"padding: 10px 10px 10px 10px;\" class='header'>");
String title = context.getString(R.string.rsb_consent_review_title);
docBuilder.append(String.format("<h1 style=\"text-align: center; font-family:sans-serif-light;\">%1$s</h1>", title));
String detail = context.getString(R.string.rsb_consent_review_instruction);
docBuilder.append(String.format("<p style=\"text-align: center\">%1$s</p>", detail));
docBuilder.append("</div></br>");
docBuilder.append(doc.getHtmlReviewContent());
ConsentDocumentStep step = new ConsentDocumentStep(ID_CONSENT_DOC);
step.setConsentHTML(docBuilder.toString());
step.setConfirmMessage(context.getString(R.string.rsb_consent_review_reason));
steps.add(step);
boolean requiresName = doc.getSignature(0).requiresName();
boolean requiresBirthDate = doc.getSignature(0).requiresBirthDate();
if (requiresName || requiresBirthDate) {
List<QuestionStep> formSteps = new ArrayList<>();
if (requiresName) {
TextAnswerFormat format = new TextAnswerFormat();
format.setIsMultipleLines(false);
String placeholder = context.getResources().getString(R.string.rsb_consent_name_placeholder);
String nameText = context.getResources().getString(R.string.rsb_consent_name_full);
formSteps.add(new QuestionStep(ID_FORM_NAME, nameText, format));
}
if (requiresBirthDate) {
Calendar maxDate = Calendar.getInstance();
maxDate.add(Calendar.YEAR, -18);
DateAnswerFormat dobFormat = new BirthDateAnswerFormat(null, 18, 0);
String dobText = context.getResources().getString(R.string.rsb_consent_dob_full);
formSteps.add(new QuestionStep(ID_FORM_DOB, dobText, dobFormat));
}
String formTitle = context.getString(R.string.rsb_consent_form_title);
FormStep formStep = new FormStep(ID_FORM, formTitle, step.getText());
formStep.setStepTitle(R.string.rsb_consent);
formStep.setOptional(false);
formStep.setFormSteps(formSteps);
steps.add(formStep);
}
if (doc.getSignature(0).requiresSignatureImage()) {
ConsentSignatureStep signatureStep = new ConsentSignatureStep(ID_SIGNATURE);
signatureStep.setStepTitle(R.string.rsb_consent);
signatureStep.setTitle(context.getString(R.string.rsb_consent_signature_title));
signatureStep.setText(context.getString(R.string.rsb_consent_signature_instruction));
signatureStep.setOptional(false);
signatureStep.setSignatureDateFormat(doc.getSignature(0).getSignatureDateFormatString());
signatureStep.setStepLayoutClass(ConsentSignatureStepLayout.class);
steps.add(signatureStep);
}
</DeepExtract>
return new ConsentTask(taskId, steps);
} | ResearchStack | positive | 2,847 |
@Test
public void getOnceAndStream_WithId_WithNoData_ReturnsNoneValue_AndDoesNotComplete() {
Consumer<String> insert = value -> getProvider().insert(core.getUriForId(SimpleMockStore.getIdFor(value)), core.getContentValuesForItem(value));
try {
insert.accept("parsnip");
insert.accept("lettuce");
insert.accept("spinach");
} catch (Exception ignored) {
}
return this;
store.getOnceAndStream(SimpleMockStore.getIdFor("bacon")).test().awaitDone(50, TimeUnit.MILLISECONDS).assertNotComplete().assertNoErrors().assertValue(SimpleMockStore.NONE);
} | @Test
public void getOnceAndStream_WithId_WithNoData_ReturnsNoneValue_AndDoesNotComplete() {
<DeepExtract>
Consumer<String> insert = value -> getProvider().insert(core.getUriForId(SimpleMockStore.getIdFor(value)), core.getContentValuesForItem(value));
try {
insert.accept("parsnip");
insert.accept("lettuce");
insert.accept("spinach");
} catch (Exception ignored) {
}
return this;
</DeepExtract>
store.getOnceAndStream(SimpleMockStore.getIdFor("bacon")).test().awaitDone(50, TimeUnit.MILLISECONDS).assertNotComplete().assertNoErrors().assertValue(SimpleMockStore.NONE);
} | reark | positive | 2,848 |
@Override
public HasClickHandlers drawCircle(StyleMapShape<Circle> circle, String text) {
drawCircle(circle);
TextOverlay textOverlay = new TextOverlay(GoogleMapsAdapters.getLatLng(circle.getMapShape().getCenter()), text);
addOverlay(textOverlay);
return textOverlay.getTextWidget();
} | @Override
public HasClickHandlers drawCircle(StyleMapShape<Circle> circle, String text) {
drawCircle(circle);
<DeepExtract>
TextOverlay textOverlay = new TextOverlay(GoogleMapsAdapters.getLatLng(circle.getMapShape().getCenter()), text);
addOverlay(textOverlay);
return textOverlay.getTextWidget();
</DeepExtract>
} | linked-data-visualization-tools | positive | 2,850 |
public boolean isExecutable() {
if (released) {
return false;
}
if (buildStatusMap == null) {
Map<CLDevice, Status> map = new HashMap<CLDevice, Status>();
CLDevice[] devices = getCLDevices();
for (CLDevice device : devices) {
Status status = getBuildStatus(device);
if (status == Status.BUILD_SUCCESS) {
executable = true;
}
map.put(device, status);
}
this.buildStatusMap = Collections.unmodifiableMap(map);
}
return executable;
} | public boolean isExecutable() {
if (released) {
return false;
}
<DeepExtract>
if (buildStatusMap == null) {
Map<CLDevice, Status> map = new HashMap<CLDevice, Status>();
CLDevice[] devices = getCLDevices();
for (CLDevice device : devices) {
Status status = getBuildStatus(device);
if (status == Status.BUILD_SUCCESS) {
executable = true;
}
map.put(device, status);
}
this.buildStatusMap = Collections.unmodifiableMap(map);
}
</DeepExtract>
return executable;
} | jocl | positive | 2,851 |
public static void queueMessage(TextChannel channel, String message) {
if (channel == null) {
DiscordSRV.debug("Tried sending a message to a null channel");
return;
}
return translateEmotes(message, channel.getGuild().getEmotes());
if (StringUtils.isBlank(message))
return;
queueMessage(channel, new MessageBuilder().append(message).build(), false);
} | public static void queueMessage(TextChannel channel, String message) {
if (channel == null) {
DiscordSRV.debug("Tried sending a message to a null channel");
return;
}
<DeepExtract>
return translateEmotes(message, channel.getGuild().getEmotes());
</DeepExtract>
if (StringUtils.isBlank(message))
return;
queueMessage(channel, new MessageBuilder().append(message).build(), false);
} | DiscordSRV | positive | 2,852 |
private void login(final String myChannelJid, final String passwordTxt) {
if (isEmpty(myChannelJid)) {
showErrorToolTip(mUsernameErrorTooltip, getString(R.string.message_account_username_mandatory));
return;
}
if (isEmpty(passwordTxt)) {
showErrorToolTip(mPasswordErrorTooltip, getString(R.string.message_account_password_mandatory));
return;
}
String[] myChannelJidSplit = myChannelJid.split("@");
if (myChannelJidSplit.length < 2) {
showErrorToolTip(mUsernameErrorTooltip, getString(R.string.login_error_bad_channel_format));
return;
}
Preferences.setPreference(LoginActivity.this, Preferences.MY_CHANNEL_JID, myChannelJid);
Preferences.setPreference(LoginActivity.this, Preferences.PASSWORD, passwordTxt);
if (mUsernameErrorTooltip != null && mPasswordErrorTooltip != null) {
mUsernameErrorTooltip.setVisibility(View.GONE);
mPasswordErrorTooltip.setVisibility(View.GONE);
}
InputUtils.hideKeyboard(LoginActivity.this);
mProgressDialog.show();
DNSUtils.resolveAPISRV(new ModelCallback<String>() {
@Override
public void success(String apiAddress) {
Preferences.setPreference(LoginActivity.this, Preferences.API_ADDRESS, apiAddress);
SSLUtils.checkSSL(LoginActivity.this, apiAddress, new ModelCallback<Void>() {
@Override
public void success(Void response) {
checkCredentials();
}
@Override
public void error(Throwable throwable) {
clearAPIAddress();
mProgressDialog.dismiss();
}
});
}
@Override
public void error(Throwable throwable) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), getString(R.string.login_error_wrong_credentials), Toast.LENGTH_LONG).show();
}
private void checkCredentials() {
LoginModel.getInstance().getFromServer(LoginActivity.this, new ModelCallback<Void>() {
@Override
public void success(Void response) {
mProgressDialog.dismiss();
setResult(LOGGED_IN_RESULT);
finish();
}
@Override
public void error(Throwable throwable) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), getString(R.string.login_error_wrong_credentials), Toast.LENGTH_LONG).show();
}
});
}
}, myChannelJidSplit[1]);
} | private void login(final String myChannelJid, final String passwordTxt) {
if (isEmpty(myChannelJid)) {
showErrorToolTip(mUsernameErrorTooltip, getString(R.string.message_account_username_mandatory));
return;
}
if (isEmpty(passwordTxt)) {
showErrorToolTip(mPasswordErrorTooltip, getString(R.string.message_account_password_mandatory));
return;
}
String[] myChannelJidSplit = myChannelJid.split("@");
if (myChannelJidSplit.length < 2) {
showErrorToolTip(mUsernameErrorTooltip, getString(R.string.login_error_bad_channel_format));
return;
}
Preferences.setPreference(LoginActivity.this, Preferences.MY_CHANNEL_JID, myChannelJid);
Preferences.setPreference(LoginActivity.this, Preferences.PASSWORD, passwordTxt);
<DeepExtract>
if (mUsernameErrorTooltip != null && mPasswordErrorTooltip != null) {
mUsernameErrorTooltip.setVisibility(View.GONE);
mPasswordErrorTooltip.setVisibility(View.GONE);
}
</DeepExtract>
InputUtils.hideKeyboard(LoginActivity.this);
mProgressDialog.show();
DNSUtils.resolveAPISRV(new ModelCallback<String>() {
@Override
public void success(String apiAddress) {
Preferences.setPreference(LoginActivity.this, Preferences.API_ADDRESS, apiAddress);
SSLUtils.checkSSL(LoginActivity.this, apiAddress, new ModelCallback<Void>() {
@Override
public void success(Void response) {
checkCredentials();
}
@Override
public void error(Throwable throwable) {
clearAPIAddress();
mProgressDialog.dismiss();
}
});
}
@Override
public void error(Throwable throwable) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), getString(R.string.login_error_wrong_credentials), Toast.LENGTH_LONG).show();
}
private void checkCredentials() {
LoginModel.getInstance().getFromServer(LoginActivity.this, new ModelCallback<Void>() {
@Override
public void success(Void response) {
mProgressDialog.dismiss();
setResult(LOGGED_IN_RESULT);
finish();
}
@Override
public void error(Throwable throwable) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), getString(R.string.login_error_wrong_credentials), Toast.LENGTH_LONG).show();
}
});
}
}, myChannelJidSplit[1]);
} | buddycloud-android | positive | 2,853 |
private void autofitParam(DataSheet dataSheet, Parameter parameter) {
Parameter parameter = getParameterForAxis(parameter);
setMin(parameter, dataSheet.getMinValueOf(parameter));
Parameter parameter = getParameterForAxis(parameter);
setMax(parameter, dataSheet.getMinValueOf(parameter));
} | private void autofitParam(DataSheet dataSheet, Parameter parameter) {
Parameter parameter = getParameterForAxis(parameter);
setMin(parameter, dataSheet.getMinValueOf(parameter));
<DeepExtract>
Parameter parameter = getParameterForAxis(parameter);
setMax(parameter, dataSheet.getMinValueOf(parameter));
</DeepExtract>
} | xdat | positive | 2,854 |
@Override
public void print(String string) {
if (realPrinter == null) {
realPrinter = new Printer(name);
}
realPrinter.print(string);
} | @Override
public void print(String string) {
<DeepExtract>
if (realPrinter == null) {
realPrinter = new Printer(name);
}
</DeepExtract>
realPrinter.print(string);
} | Java-Notes | positive | 2,855 |
@Override
protected void doPush(final int down, final V value) {
if (arraySize == array.length)
array = Arrays.copyOf(array, arraySize + SIZE_INCREASE);
System.arraycopy(array, down, array, down + 1, arraySize - down);
array[down] = value;
arraySize++;
} | @Override
protected void doPush(final int down, final V value) {
<DeepExtract>
if (arraySize == array.length)
array = Arrays.copyOf(array, arraySize + SIZE_INCREASE);
</DeepExtract>
System.arraycopy(array, down, array, down + 1, arraySize - down);
array[down] = value;
arraySize++;
} | grappa | positive | 2,856 |
@Test
public void getFriendIdsInCursor_byUserId_appAuthorization() {
appAuthMockServer.expect(requestTo("https://api.twitter.com/1.1/friends/ids.json?cursor=123456&user_id=98765")).andExpect(method(GET)).andExpect(header("Authorization", "Bearer APP_ACCESS_TOKEN")).andRespond(withSuccess(jsonResource("friend-or-follower-ids"), APPLICATION_JSON));
CursoredList<Long> friendIds = appAuthTwitter.friendOperations().getFriendIdsInCursor(98765L, 123456);
assertEquals(2, friendIds.size());
assertEquals(14846645L, (long) friendIds.get(0));
assertEquals(14718006L, (long) friendIds.get(1));
assertEquals(112233, friendIds.getPreviousCursor());
assertEquals(332211, friendIds.getNextCursor());
} | @Test
public void getFriendIdsInCursor_byUserId_appAuthorization() {
appAuthMockServer.expect(requestTo("https://api.twitter.com/1.1/friends/ids.json?cursor=123456&user_id=98765")).andExpect(method(GET)).andExpect(header("Authorization", "Bearer APP_ACCESS_TOKEN")).andRespond(withSuccess(jsonResource("friend-or-follower-ids"), APPLICATION_JSON));
CursoredList<Long> friendIds = appAuthTwitter.friendOperations().getFriendIdsInCursor(98765L, 123456);
<DeepExtract>
assertEquals(2, friendIds.size());
assertEquals(14846645L, (long) friendIds.get(0));
assertEquals(14718006L, (long) friendIds.get(1));
assertEquals(112233, friendIds.getPreviousCursor());
assertEquals(332211, friendIds.getNextCursor());
</DeepExtract>
} | spring-social-twitter | positive | 2,857 |
public static void nextSlide() {
if (slideShowSlides != null) {
if (slideShowIndex < slideShowSlides.size()) {
slideShowIndex++;
} else {
slideShowIndex = 1;
}
}
ActionListener listener = null;
if (slideShowSlides != null) {
listener = getCurrentSlideAction();
}
if (listener != null) {
listener.actionPerformed(null);
}
} | public static void nextSlide() {
<DeepExtract>
if (slideShowSlides != null) {
if (slideShowIndex < slideShowSlides.size()) {
slideShowIndex++;
} else {
slideShowIndex = 1;
}
}
</DeepExtract>
ActionListener listener = null;
if (slideShowSlides != null) {
listener = getCurrentSlideAction();
}
if (listener != null) {
listener.actionPerformed(null);
}
} | java-concurrent-animated | positive | 2,858 |
public EntityEntitySimilarity getEntityEntitySimilarity(String eeIdentifier, Entities entities, Tracer tracer) throws Exception {
EntityEntitySimilarity eeSim = null;
EntitiesContextSettings settings = new EntitiesContextSettings();
settings.setEntityCoherenceKeyphraseAlpha(entityCohKeyphraseAlpha);
settings.setEntityCoherenceKeywordAlpha(entityCohKeywordAlpha);
this.keyphraseSourceExclusion = keyphraseSourceExclusion;
settings.setUseConfusableMIWeight(useConfusableMIWeights);
settings.setShouldNormalizeWeights(normalizeCoherenceWeights);
settings.setShouldAverageWeights(shouldAverageCoherenceWeights);
settings.setNgramLength(nGramLength);
this.lshBandCount = lshBandCount;
this.lshBandSize = lshBandSize;
this.lshDatabaseTable = lshDatabaseTable;
if (eeIdentifier.equals("MilneWittenEntityEntitySimilarity")) {
return EntityEntitySimilarity.getMilneWittenSimilarity(entities, tracer);
} else if (eeIdentifier.equals("InlinkOverlapEntityEntitySimilarity")) {
return EntityEntitySimilarity.getInlinkOverlapSimilarity(entities, tracer);
} else if (eeIdentifier.equals("KeyphraseBasedNGDEntityEntitySimilarity")) {
return EntityEntitySimilarity.getKeyphraseBasedNGDEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("WeightedKeyphraseBasedNGDEntityEntitySimilarity")) {
return EntityEntitySimilarity.getWeightedKeyphraseBasedNGDEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("JaccardKeywordEntityEntitySimilarity")) {
return EntityEntitySimilarity.getJaccardKeywordEntityEntitySimilarity(entities, tracer);
} else if (eeIdentifier.equals("WeightedJaccardKeyphraseEntityEntitySimilarity")) {
return EntityEntitySimilarity.getWeightedJaccardKeyphraseEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("KeyphraseBasedEntityEntitySimilarity")) {
return EntityEntitySimilarity.getKeyphraseBasedEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("FastPartialMaxMinKeyphraseEntityEntitySimilarity")) {
return EntityEntitySimilarity.getFastPartialMaxMinKeyphraseEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("KOREEntityEntitySimilarity")) {
return EntityEntitySimilarity.getKOREEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("TopKeyphraseBasedEntityEntitySimilarity")) {
return EntityEntitySimilarity.getTopKeyphraseBasedEntityEntitySimilarity(entities, numberOfEntityKeyphrase, tracer);
} else {
logger.error("EESimilarity '" + eeIdentifier + "' undefined");
return eeSim;
}
} | public EntityEntitySimilarity getEntityEntitySimilarity(String eeIdentifier, Entities entities, Tracer tracer) throws Exception {
EntityEntitySimilarity eeSim = null;
EntitiesContextSettings settings = new EntitiesContextSettings();
settings.setEntityCoherenceKeyphraseAlpha(entityCohKeyphraseAlpha);
settings.setEntityCoherenceKeywordAlpha(entityCohKeywordAlpha);
this.keyphraseSourceExclusion = keyphraseSourceExclusion;
settings.setUseConfusableMIWeight(useConfusableMIWeights);
settings.setShouldNormalizeWeights(normalizeCoherenceWeights);
settings.setShouldAverageWeights(shouldAverageCoherenceWeights);
settings.setNgramLength(nGramLength);
this.lshBandCount = lshBandCount;
this.lshBandSize = lshBandSize;
<DeepExtract>
this.lshDatabaseTable = lshDatabaseTable;
</DeepExtract>
if (eeIdentifier.equals("MilneWittenEntityEntitySimilarity")) {
return EntityEntitySimilarity.getMilneWittenSimilarity(entities, tracer);
} else if (eeIdentifier.equals("InlinkOverlapEntityEntitySimilarity")) {
return EntityEntitySimilarity.getInlinkOverlapSimilarity(entities, tracer);
} else if (eeIdentifier.equals("KeyphraseBasedNGDEntityEntitySimilarity")) {
return EntityEntitySimilarity.getKeyphraseBasedNGDEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("WeightedKeyphraseBasedNGDEntityEntitySimilarity")) {
return EntityEntitySimilarity.getWeightedKeyphraseBasedNGDEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("JaccardKeywordEntityEntitySimilarity")) {
return EntityEntitySimilarity.getJaccardKeywordEntityEntitySimilarity(entities, tracer);
} else if (eeIdentifier.equals("WeightedJaccardKeyphraseEntityEntitySimilarity")) {
return EntityEntitySimilarity.getWeightedJaccardKeyphraseEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("KeyphraseBasedEntityEntitySimilarity")) {
return EntityEntitySimilarity.getKeyphraseBasedEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("FastPartialMaxMinKeyphraseEntityEntitySimilarity")) {
return EntityEntitySimilarity.getFastPartialMaxMinKeyphraseEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("KOREEntityEntitySimilarity")) {
return EntityEntitySimilarity.getKOREEntityEntitySimilarity(entities, settings, tracer);
} else if (eeIdentifier.equals("TopKeyphraseBasedEntityEntitySimilarity")) {
return EntityEntitySimilarity.getTopKeyphraseBasedEntityEntitySimilarity(entities, numberOfEntityKeyphrase, tracer);
} else {
logger.error("EESimilarity '" + eeIdentifier + "' undefined");
return eeSim;
}
} | aida | positive | 2,859 |
protected void _test(EXIFactory exiFactory, byte[] isBytes, int numberOfEXIDocuments) throws AssertionFailedError, Exception {
ByteArrayOutputStream osEXI = new ByteArrayOutputStream();
for (int i = 0; i < numberOfEXIDocuments; i++) {
EXIResult exiResult = new EXIResult(exiFactory);
exiResult.setOutputStream(osEXI);
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setContentHandler(exiResult.getHandler());
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", exiResult.getLexicalHandler());
xmlReader.parse(new InputSource(new ByteArrayInputStream(isBytes)));
}
InputStream isEXI = new ByteArrayInputStream(osEXI.toByteArray());
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
for (int i = 0; i < numberOfEXIDocuments; i++) {
InputSource is = new InputSource(new PushbackInputStream(isEXI, DecodingOptions.PUSHBACK_BUFFER_SIZE));
SAXSource exiSource = new SAXSource(is);
XMLReader exiReader = new SAXFactory(exiFactory).createEXIReader();
exiSource.setXMLReader(exiReader);
ByteArrayOutputStream xmlOutput = new ByteArrayOutputStream();
Result result = new StreamResult(xmlOutput);
transformer.transform(exiSource, result);
byte[] xmlDec = xmlOutput.toByteArray();
ByteArrayInputStream baisControl = new ByteArrayInputStream(isBytes);
checkXMLEquality(exiFactory, baisControl, new ByteArrayInputStream(xmlDec));
}
} | protected void _test(EXIFactory exiFactory, byte[] isBytes, int numberOfEXIDocuments) throws AssertionFailedError, Exception {
ByteArrayOutputStream osEXI = new ByteArrayOutputStream();
for (int i = 0; i < numberOfEXIDocuments; i++) {
EXIResult exiResult = new EXIResult(exiFactory);
exiResult.setOutputStream(osEXI);
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setContentHandler(exiResult.getHandler());
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", exiResult.getLexicalHandler());
xmlReader.parse(new InputSource(new ByteArrayInputStream(isBytes)));
}
InputStream isEXI = new ByteArrayInputStream(osEXI.toByteArray());
<DeepExtract>
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
for (int i = 0; i < numberOfEXIDocuments; i++) {
InputSource is = new InputSource(new PushbackInputStream(isEXI, DecodingOptions.PUSHBACK_BUFFER_SIZE));
SAXSource exiSource = new SAXSource(is);
XMLReader exiReader = new SAXFactory(exiFactory).createEXIReader();
exiSource.setXMLReader(exiReader);
ByteArrayOutputStream xmlOutput = new ByteArrayOutputStream();
Result result = new StreamResult(xmlOutput);
transformer.transform(exiSource, result);
byte[] xmlDec = xmlOutput.toByteArray();
ByteArrayInputStream baisControl = new ByteArrayInputStream(isBytes);
checkXMLEquality(exiFactory, baisControl, new ByteArrayInputStream(xmlDec));
}
</DeepExtract>
} | exificient | positive | 2,860 |
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mHeader != null) {
final int width = getMeasuredWidth() - mPaddingLeft - mPaddingRight;
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
measureChild(mHeader, parentWidthMeasureSpec, parentHeightMeasureSpec);
}
} | @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
<DeepExtract>
if (mHeader != null) {
final int width = getMeasuredWidth() - mPaddingLeft - mPaddingRight;
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
measureChild(mHeader, parentWidthMeasureSpec, parentHeightMeasureSpec);
}
</DeepExtract>
} | MobileSafeApp | positive | 2,862 |
public Criteria andDropLessThan(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "drop" + " cannot be null");
}
criteria.add(new Criterion("`drop` <", value));
return (Criteria) this;
} | public Criteria andDropLessThan(String value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "drop" + " cannot be null");
}
criteria.add(new Criterion("`drop` <", value));
</DeepExtract>
return (Criteria) this;
} | mybatis-generator-gui-extension | positive | 2,863 |
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
switch(mState) {
case STATE_PREVIEW:
{
break;
}
case STATE_WAITING_LOCK:
{
Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
if (afState == null) {
captureStillPicture();
} else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState || CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
if (aeState == null || aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
mState = STATE_PICTURE_TAKEN;
captureStillPicture();
} else {
runPrecaptureSequence();
}
}
break;
}
case STATE_WAITING_PRECAPTURE:
{
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
if (aeState == null || aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE || aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
mState = STATE_WAITING_NON_PRECAPTURE;
}
break;
}
case STATE_WAITING_NON_PRECAPTURE:
{
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
mState = STATE_PICTURE_TAKEN;
captureStillPicture();
}
break;
}
}
} | @Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
<DeepExtract>
switch(mState) {
case STATE_PREVIEW:
{
break;
}
case STATE_WAITING_LOCK:
{
Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
if (afState == null) {
captureStillPicture();
} else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState || CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
if (aeState == null || aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
mState = STATE_PICTURE_TAKEN;
captureStillPicture();
} else {
runPrecaptureSequence();
}
}
break;
}
case STATE_WAITING_PRECAPTURE:
{
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
if (aeState == null || aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE || aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
mState = STATE_WAITING_NON_PRECAPTURE;
}
break;
}
case STATE_WAITING_NON_PRECAPTURE:
{
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
mState = STATE_PICTURE_TAKEN;
captureStillPicture();
}
break;
}
}
</DeepExtract>
} | Trycorder5 | positive | 2,865 |
public void lookupAsMethod(Symbols syms) {
Symbols newSyms = new Symbols(syms);
newSyms.putNew(SymbolThis.NAME);
size = newSyms.size();
} | public void lookupAsMethod(Symbols syms) {
<DeepExtract>
</DeepExtract>
Symbols newSyms = new Symbols(syms);
<DeepExtract>
</DeepExtract>
newSyms.putNew(SymbolThis.NAME);
<DeepExtract>
</DeepExtract>
size = newSyms.size();
<DeepExtract>
</DeepExtract>
} | Stone-language | positive | 2,866 |
@Override
public void onClick(View view) {
if (mode == MODE_MULTI) {
new SubscriptionEditTask(global, SubredditSelectActivity.this, SubredditSelectActivity.this, SubscriptionEditTask.ACTION_MULTI_SUB_REMOVE).execute(multiPath, subreddit);
} else {
if (global.mRedditData.isLoggedIn())
new SubscriptionEditTask(global, SubredditSelectActivity.this, null, SubscriptionEditTask.ACTION_FILTER_SUB_REMOVE).execute("all", subreddit);
subsList.remove(subreddit);
global.getSubredditManager().setAllFilter(subsList);
if ("all".equals(global.getSubredditManager().getCurrentFeedName(mAppWidgetId)))
needsFeedUpdate = true;
notifyDataSetChanged();
}
} | @Override
public void onClick(View view) {
<DeepExtract>
if (mode == MODE_MULTI) {
new SubscriptionEditTask(global, SubredditSelectActivity.this, SubredditSelectActivity.this, SubscriptionEditTask.ACTION_MULTI_SUB_REMOVE).execute(multiPath, subreddit);
} else {
if (global.mRedditData.isLoggedIn())
new SubscriptionEditTask(global, SubredditSelectActivity.this, null, SubscriptionEditTask.ACTION_FILTER_SUB_REMOVE).execute("all", subreddit);
subsList.remove(subreddit);
global.getSubredditManager().setAllFilter(subsList);
if ("all".equals(global.getSubredditManager().getCurrentFeedName(mAppWidgetId)))
needsFeedUpdate = true;
notifyDataSetChanged();
}
</DeepExtract>
} | reddinator | positive | 2,867 |
@Test
public void deleteNode1() {
node = new ListNode<>(10);
expected = LinkedListUtil.createLinkedList(1, 2, 3, 4, 5);
listToDeleteFrom = LinkedListUtil.createLinkedList(1, 2, 3, 4, 5);
listToDeleteFrom.get(3).insertAfter(node);
DeleteNode.deleteNode(node);
LinkedListUtil.assertSameList(expected, listToDeleteFrom);
} | @Test
public void deleteNode1() {
node = new ListNode<>(10);
expected = LinkedListUtil.createLinkedList(1, 2, 3, 4, 5);
listToDeleteFrom = LinkedListUtil.createLinkedList(1, 2, 3, 4, 5);
listToDeleteFrom.get(3).insertAfter(node);
<DeepExtract>
DeleteNode.deleteNode(node);
LinkedListUtil.assertSameList(expected, listToDeleteFrom);
</DeepExtract>
} | Elements-of-programming-interviews | positive | 2,868 |
public Criteria andMarketingSmallLabel1NotBetween(String value1, String value2) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "marketingSmallLabel1" + " cannot be null");
}
criteria.add(new Criterion("marketing_small_label_1 not between", value1, value2));
return (Criteria) this;
} | public Criteria andMarketingSmallLabel1NotBetween(String value1, String value2) {
<DeepExtract>
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "marketingSmallLabel1" + " cannot be null");
}
criteria.add(new Criterion("marketing_small_label_1 not between", value1, value2));
</DeepExtract>
return (Criteria) this;
} | uccn | positive | 2,869 |
public void openElement(String name, int indent, Attribute... attrs) throws TechnicalException {
try {
indent(indent);
myWriter.append("<");
myWriter.append(name);
for (Attribute a : attrs) {
myWriter.append(" ");
myWriter.append(a.myName);
myWriter.append("=\"");
myWriter.append(a.myValue.replaceAll("\"", """));
myWriter.append("\"");
}
if (false) {
myWriter.append("/>");
} else {
myWriter.append(">");
}
} catch (IOException ex) {
String msg = "Internal error, writing to the file: " + myPath;
throw new TechnicalException(msg, ex);
}
} | public void openElement(String name, int indent, Attribute... attrs) throws TechnicalException {
<DeepExtract>
try {
indent(indent);
myWriter.append("<");
myWriter.append(name);
for (Attribute a : attrs) {
myWriter.append(" ");
myWriter.append(a.myName);
myWriter.append("=\"");
myWriter.append(a.myValue.replaceAll("\"", """));
myWriter.append("\"");
}
if (false) {
myWriter.append("/>");
} else {
myWriter.append(">");
}
} catch (IOException ex) {
String msg = "Internal error, writing to the file: " + myPath;
throw new TechnicalException(msg, ex);
}
</DeepExtract>
} | servlex | positive | 2,870 |
@Override
public MediaCodecInfo next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
mIndex++;
return MediaCodecList.getCodecInfoAt(mIndex);
} | @Override
public MediaCodecInfo next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
mIndex++;
<DeepExtract>
return MediaCodecList.getCodecInfoAt(mIndex);
</DeepExtract>
} | DogCamera | positive | 2,871 |
public Criteria andRatioGreaterThanOrEqualTo(Integer value) {
if (value == null) {
throw new RuntimeException("Value for " + "ratio" + " cannot be null");
}
criteria.add(new Criterion("ratio >=", value));
return (Criteria) this;
} | public Criteria andRatioGreaterThanOrEqualTo(Integer value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "ratio" + " cannot be null");
}
criteria.add(new Criterion("ratio >=", value));
</DeepExtract>
return (Criteria) this;
} | jtt808-simulator | positive | 2,872 |
public static void notifyContainerAboutLogin(Subject clientSubject, CallbackHandler handler, Principal callerPrincipal, Set<String> groups) {
if (clientSubject == null) {
throw new IllegalArgumentException("Null clientSubject!");
}
if (handler == null) {
throw new IllegalArgumentException("Null callback handler!");
}
try {
if (groups == null || isEmpty(groups) || (new CallerPrincipalCallback(clientSubject, callerPrincipal).getPrincipal() == null && new CallerPrincipalCallback(clientSubject, callerPrincipal).getName() == null)) {
handler.handle(new Callback[] { new CallerPrincipalCallback(clientSubject, callerPrincipal) });
} else {
handler.handle(new Callback[] { new CallerPrincipalCallback(clientSubject, callerPrincipal), new GroupPrincipalCallback(clientSubject, groups.toArray(new String[groups.size()])) });
}
} catch (IOException | UnsupportedCallbackException e) {
throw new IllegalStateException(e);
}
} | public static void notifyContainerAboutLogin(Subject clientSubject, CallbackHandler handler, Principal callerPrincipal, Set<String> groups) {
<DeepExtract>
if (clientSubject == null) {
throw new IllegalArgumentException("Null clientSubject!");
}
if (handler == null) {
throw new IllegalArgumentException("Null callback handler!");
}
try {
if (groups == null || isEmpty(groups) || (new CallerPrincipalCallback(clientSubject, callerPrincipal).getPrincipal() == null && new CallerPrincipalCallback(clientSubject, callerPrincipal).getName() == null)) {
handler.handle(new Callback[] { new CallerPrincipalCallback(clientSubject, callerPrincipal) });
} else {
handler.handle(new Callback[] { new CallerPrincipalCallback(clientSubject, callerPrincipal), new GroupPrincipalCallback(clientSubject, groups.toArray(new String[groups.size()])) });
}
} catch (IOException | UnsupportedCallbackException e) {
throw new IllegalStateException(e);
}
</DeepExtract>
} | soteria | positive | 2,874 |
@Override
protected void afterShowing() {
portLabel.setText("" + streamConfiguration.servicePort);
parallelInstancesLabel.setText("" + streamConfiguration.maximumParallelInstances);
timeFractionLabel.setText("" + streamConfiguration.timeFractionBeforeNewTrace);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
BPMNVisualizer v = new BPMNVisualizer(process);
processPreviewContainer.removeAll();
processPreviewContainer.add(v, c);
processPreviewContainer.updateUI();
v.fit();
this.process = process;
if (streamer != null) {
streamer.updateProcess(process);
}
streamerForPreview.updateProcess(process);
streamerForPreview.clearBuffer();
streamerForPreview.initialBufferPopulation();
streamPreview.updateUI();
processCombo.setEnabled(false);
processCombo.removeAllItems();
for (Process p : ApplicationController.instance().processes().getProcesses()) {
ProcessSelector ps = new ProcessSelector(p);
processCombo.addItem(ps);
if (p.equals(process)) {
processCombo.setSelectedItem(ps);
}
}
processCombo.setEnabled(true);
} | @Override
protected void afterShowing() {
portLabel.setText("" + streamConfiguration.servicePort);
parallelInstancesLabel.setText("" + streamConfiguration.maximumParallelInstances);
timeFractionLabel.setText("" + streamConfiguration.timeFractionBeforeNewTrace);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
BPMNVisualizer v = new BPMNVisualizer(process);
processPreviewContainer.removeAll();
processPreviewContainer.add(v, c);
processPreviewContainer.updateUI();
v.fit();
this.process = process;
if (streamer != null) {
streamer.updateProcess(process);
}
streamerForPreview.updateProcess(process);
streamerForPreview.clearBuffer();
streamerForPreview.initialBufferPopulation();
streamPreview.updateUI();
<DeepExtract>
processCombo.setEnabled(false);
processCombo.removeAllItems();
for (Process p : ApplicationController.instance().processes().getProcesses()) {
ProcessSelector ps = new ProcessSelector(p);
processCombo.addItem(ps);
if (p.equals(process)) {
processCombo.setSelectedItem(ps);
}
}
processCombo.setEnabled(true);
</DeepExtract>
} | plg | positive | 2,875 |
public void land() throws IOException {
cmd_queue.add(new LandCommand());
if (State.LANDING == State.ERROR)
changeToErrorState(null);
synchronized (state_mutex) {
if (state != State.LANDING) {
log.fine("State changed from " + state + " to " + State.LANDING);
state = State.LANDING;
if (state == State.BOOTSTRAP)
sendDemoNavigationData();
state_mutex.notifyAll();
}
}
if (State.LANDING == State.DEMO) {
synchronized (status_listeners) {
for (DroneStatusChangeListener l : status_listeners) l.ready();
}
}
} | public void land() throws IOException {
cmd_queue.add(new LandCommand());
<DeepExtract>
if (State.LANDING == State.ERROR)
changeToErrorState(null);
synchronized (state_mutex) {
if (state != State.LANDING) {
log.fine("State changed from " + state + " to " + State.LANDING);
state = State.LANDING;
if (state == State.BOOTSTRAP)
sendDemoNavigationData();
state_mutex.notifyAll();
}
}
if (State.LANDING == State.DEMO) {
synchronized (status_listeners) {
for (DroneStatusChangeListener l : status_listeners) l.ready();
}
}
</DeepExtract>
} | javadrone | positive | 2,876 |
@Test
public void testCircleDateLineWrapping() {
JtsShapeFactory shapeFactory = JtsSpatialContext.GEO.getShapeFactory();
Circle circle = shapeFactory.circle(-179.99, 51.22, DistanceUtils.dist2Degrees(5, DistanceUtils.EARTH_MEAN_RADIUS_KM));
Geometry geom = shapeFactory.getGeometryFrom(circle);
assertTrue(circle.getBoundingBox().getCrossesDateLine());
assertEquals("MultiPolygon", geom.getGeometryType());
GeodesicSphereDistCalc distCalc = new GeodesicSphereDistCalc.Haversine();
double maxDeltaKm = 5 / 100;
for (Coordinate c : geom.getCoordinates()) {
Point point = new PointImpl(c.x, c.y, SpatialContext.GEO);
double distance = distCalc.distance(point, -179.99, 51.22);
double distanceKm = DistanceUtils.degrees2Dist(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM);
assertEquals(String.format("Distance from point to center: %.2f km. Expected: %.2f km", distanceKm, 5), 5, distanceKm, maxDeltaKm);
}
JtsShapeFactory shapeFactory = JtsSpatialContext.GEO.getShapeFactory();
Circle circle = shapeFactory.circle(179.99, -35.6, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_KM));
Geometry geom = shapeFactory.getGeometryFrom(circle);
assertTrue(circle.getBoundingBox().getCrossesDateLine());
assertEquals("MultiPolygon", geom.getGeometryType());
GeodesicSphereDistCalc distCalc = new GeodesicSphereDistCalc.Haversine();
double maxDeltaKm = 10 / 100;
for (Coordinate c : geom.getCoordinates()) {
Point point = new PointImpl(c.x, c.y, SpatialContext.GEO);
double distance = distCalc.distance(point, 179.99, -35.6);
double distanceKm = DistanceUtils.degrees2Dist(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM);
assertEquals(String.format("Distance from point to center: %.2f km. Expected: %.2f km", distanceKm, 10), 10, distanceKm, maxDeltaKm);
}
} | @Test
public void testCircleDateLineWrapping() {
JtsShapeFactory shapeFactory = JtsSpatialContext.GEO.getShapeFactory();
Circle circle = shapeFactory.circle(-179.99, 51.22, DistanceUtils.dist2Degrees(5, DistanceUtils.EARTH_MEAN_RADIUS_KM));
Geometry geom = shapeFactory.getGeometryFrom(circle);
assertTrue(circle.getBoundingBox().getCrossesDateLine());
assertEquals("MultiPolygon", geom.getGeometryType());
GeodesicSphereDistCalc distCalc = new GeodesicSphereDistCalc.Haversine();
double maxDeltaKm = 5 / 100;
for (Coordinate c : geom.getCoordinates()) {
Point point = new PointImpl(c.x, c.y, SpatialContext.GEO);
double distance = distCalc.distance(point, -179.99, 51.22);
double distanceKm = DistanceUtils.degrees2Dist(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM);
assertEquals(String.format("Distance from point to center: %.2f km. Expected: %.2f km", distanceKm, 5), 5, distanceKm, maxDeltaKm);
}
<DeepExtract>
JtsShapeFactory shapeFactory = JtsSpatialContext.GEO.getShapeFactory();
Circle circle = shapeFactory.circle(179.99, -35.6, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_KM));
Geometry geom = shapeFactory.getGeometryFrom(circle);
assertTrue(circle.getBoundingBox().getCrossesDateLine());
assertEquals("MultiPolygon", geom.getGeometryType());
GeodesicSphereDistCalc distCalc = new GeodesicSphereDistCalc.Haversine();
double maxDeltaKm = 10 / 100;
for (Coordinate c : geom.getCoordinates()) {
Point point = new PointImpl(c.x, c.y, SpatialContext.GEO);
double distance = distCalc.distance(point, 179.99, -35.6);
double distanceKm = DistanceUtils.degrees2Dist(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM);
assertEquals(String.format("Distance from point to center: %.2f km. Expected: %.2f km", distanceKm, 10), 10, distanceKm, maxDeltaKm);
}
</DeepExtract>
} | spatial4j | positive | 2,877 |
protected void checkOperationMembers(LiveDownloadOperation operation, String method, String path, Object userState) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method));
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
assertEquals(operation.getMethod(), sb.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(path));
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
assertEquals(operation.getPath(), sb.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(userState));
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
assertEquals(operation.getUserState(), sb.toString());
} | protected void checkOperationMembers(LiveDownloadOperation operation, String method, String path, Object userState) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method));
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
assertEquals(operation.getMethod(), sb.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(path));
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
assertEquals(operation.getPath(), sb.toString());
<DeepExtract>
BufferedReader reader = new BufferedReader(new InputStreamReader(userState));
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
assertEquals(operation.getUserState(), sb.toString());
</DeepExtract>
} | LiveSDK-for-Android | positive | 2,881 |
public Criteria andUserIdEqualTo(Integer value) {
if (value == null) {
throw new RuntimeException("Value for " + "userId" + " cannot be null");
}
criteria.add(new Criterion("user_id =", value));
return (Criteria) this;
} | public Criteria andUserIdEqualTo(Integer value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "userId" + " cannot be null");
}
criteria.add(new Criterion("user_id =", value));
</DeepExtract>
return (Criteria) this;
} | library_manager_system | positive | 2,882 |
public void visitModule(ModuleTree node, TreeVisitor<?, ?> visitor) {
var name;
switch(node.getName().getKind()) {
case IDENTIFIER:
name = ((IdentifierTree) node.getName()).getName().toString();
case MEMBER_SELECT:
var select = (MemberSelectTree) node.getName();
name = qualifiedString(select.getExpression()) + '.' + select.getIdentifier().toString();
default:
throw new AssertionError(node.getName().toString());
}
var flags = node.getModuleType() == ModuleKind.OPEN ? ACC_OPEN : 0;
mv = moduleClassVisitor.visitModule(name, flags, null);
node.getDirectives().forEach(n -> accept(visitor, n));
} | public void visitModule(ModuleTree node, TreeVisitor<?, ?> visitor) {
<DeepExtract>
var name;
switch(node.getName().getKind()) {
case IDENTIFIER:
name = ((IdentifierTree) node.getName()).getName().toString();
case MEMBER_SELECT:
var select = (MemberSelectTree) node.getName();
name = qualifiedString(select.getExpression()) + '.' + select.getIdentifier().toString();
default:
throw new AssertionError(node.getName().toString());
}
</DeepExtract>
var flags = node.getModuleType() == ModuleKind.OPEN ? ACC_OPEN : 0;
mv = moduleClassVisitor.visitModule(name, flags, null);
node.getDirectives().forEach(n -> accept(visitor, n));
} | pro | positive | 2,883 |
@Override
public void onViewDetachedFromWindow(View v) {
mSceneRoot.getViewTreeObserver().removeOnPreDrawListener(this);
mSceneRoot.removeOnAttachStateChangeListener(this);
sPendingTransitions.remove(mSceneRoot);
ArrayList<Transition> runningTransitions = getRunningTransitions().get(mSceneRoot);
if (runningTransitions != null && runningTransitions.size() > 0) {
for (Transition runningTransition : runningTransitions) {
runningTransition.resume(mSceneRoot);
}
}
mTransition.clearValues(true);
} | @Override
public void onViewDetachedFromWindow(View v) {
<DeepExtract>
mSceneRoot.getViewTreeObserver().removeOnPreDrawListener(this);
mSceneRoot.removeOnAttachStateChangeListener(this);
</DeepExtract>
sPendingTransitions.remove(mSceneRoot);
ArrayList<Transition> runningTransitions = getRunningTransitions().get(mSceneRoot);
if (runningTransitions != null && runningTransitions.size() > 0) {
for (Transition runningTransition : runningTransitions) {
runningTransition.resume(mSceneRoot);
}
}
mTransition.clearValues(true);
} | TransitionsDemo | positive | 2,885 |
static Element getOptionalChildElement(Element parent, String tagName) {
NodeList nodes = parent.getElementsByTagName(tagName);
if (nodes == null || nodes.getLength() == 0) {
if (false) {
throw new IllegalStateException(String.format("Missing tag %s in element %s.", tagName, parent));
} else {
return null;
}
}
return (Element) nodes.item(0);
} | static Element getOptionalChildElement(Element parent, String tagName) {
<DeepExtract>
NodeList nodes = parent.getElementsByTagName(tagName);
if (nodes == null || nodes.getLength() == 0) {
if (false) {
throw new IllegalStateException(String.format("Missing tag %s in element %s.", tagName, parent));
} else {
return null;
}
}
return (Element) nodes.item(0);
</DeepExtract>
} | appengine-java-vm-runtime | positive | 2,886 |
@Test
public void testMethodArrayParamType() throws Exception {
Class<?> longClass = Long.class;
Class<?> numberClass = Number.class;
Class<?> stringClass = String.class;
Class<?> objectClass = Object.class;
assert (numberClass.isAssignableFrom(longClass));
assert (objectClass.isAssignableFrom(numberClass));
assert (objectClass.isAssignableFrom(stringClass));
ExpressRunner runner = new ExpressRunner();
IExpressContext<String, Object> expressContext = new DefaultContext<>();
runner.addFunctionOfServiceMethod("integerArrayInvoke", this, "integerArrayInvoke", new Class[] { Integer[].class }, null);
runner.addFunctionOfServiceMethod("objectArrayInvokeWithHead", this, "objectArrayInvokeWithHead", new Class[] { String.class, Integer[].class }, null);
runner.addFunctionOfServiceMethod("objectArrayInvoke", this, "objectArrayInvoke", new Class[] { Object[].class }, null);
runner.addFunctionOfServiceMethod("objectArrayInvoke_Integer", this, "objectArrayInvoke", new Class[] { Integer[].class }, null);
Object r = runner.execute("integerArrayInvoke([1,2,3,4])", expressContext, null, false, false);
assert (r.toString().equals("10"));
Object r = runner.execute("integerArrayInvoke(null)", expressContext, null, false, false);
assert (r.toString().equals("0"));
Object r = runner.execute("integerArrayInvoke([null,1,2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("10"));
Object r = runner.execute("integerArrayInvoke([null,null])", expressContext, null, false, false);
assert (r.toString().equals("0"));
Object r = runner.execute("objectArrayInvoke([null,null])", expressContext, null, false, false);
assert (r.toString().equals(""));
Object r = runner.execute("objectArrayInvoke([1,2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("1,2,3,4,"));
Object r = runner.execute("objectArrayInvoke_Integer([1,2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("10"));
Object r = runner.execute("objectArrayInvoke(['1',2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("1,2,3,4,"));
Object r = runner.execute("objectArrayInvokeWithHead('hello:',[1,2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("hello:10"));
} | @Test
public void testMethodArrayParamType() throws Exception {
Class<?> longClass = Long.class;
Class<?> numberClass = Number.class;
Class<?> stringClass = String.class;
Class<?> objectClass = Object.class;
assert (numberClass.isAssignableFrom(longClass));
assert (objectClass.isAssignableFrom(numberClass));
assert (objectClass.isAssignableFrom(stringClass));
ExpressRunner runner = new ExpressRunner();
IExpressContext<String, Object> expressContext = new DefaultContext<>();
runner.addFunctionOfServiceMethod("integerArrayInvoke", this, "integerArrayInvoke", new Class[] { Integer[].class }, null);
runner.addFunctionOfServiceMethod("objectArrayInvokeWithHead", this, "objectArrayInvokeWithHead", new Class[] { String.class, Integer[].class }, null);
runner.addFunctionOfServiceMethod("objectArrayInvoke", this, "objectArrayInvoke", new Class[] { Object[].class }, null);
runner.addFunctionOfServiceMethod("objectArrayInvoke_Integer", this, "objectArrayInvoke", new Class[] { Integer[].class }, null);
Object r = runner.execute("integerArrayInvoke([1,2,3,4])", expressContext, null, false, false);
assert (r.toString().equals("10"));
Object r = runner.execute("integerArrayInvoke(null)", expressContext, null, false, false);
assert (r.toString().equals("0"));
Object r = runner.execute("integerArrayInvoke([null,1,2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("10"));
Object r = runner.execute("integerArrayInvoke([null,null])", expressContext, null, false, false);
assert (r.toString().equals("0"));
Object r = runner.execute("objectArrayInvoke([null,null])", expressContext, null, false, false);
assert (r.toString().equals(""));
Object r = runner.execute("objectArrayInvoke([1,2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("1,2,3,4,"));
Object r = runner.execute("objectArrayInvoke_Integer([1,2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("10"));
Object r = runner.execute("objectArrayInvoke(['1',2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("1,2,3,4,"));
<DeepExtract>
Object r = runner.execute("objectArrayInvokeWithHead('hello:',[1,2,3,null,4])", expressContext, null, false, false);
assert (r.toString().equals("hello:10"));
</DeepExtract>
} | QLExpress | positive | 2,888 |
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
for (int i = 0; i < radioGroup.getChildCount(); i++) {
View view = radioGroup.getChildAt(i);
if (view instanceof RadioButton) {
RadioButton radioButton = (RadioButton) view;
if (radioButton.getText().equals(getPersistedString("Male"))) {
radioButton.setChecked(true);
}
}
}
} | @Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
<DeepExtract>
for (int i = 0; i < radioGroup.getChildCount(); i++) {
View view = radioGroup.getChildAt(i);
if (view instanceof RadioButton) {
RadioButton radioButton = (RadioButton) view;
if (radioButton.getText().equals(getPersistedString("Male"))) {
radioButton.setChecked(true);
}
}
}
</DeepExtract>
} | meiShi | positive | 2,889 |
@Test
public void readAttributesAllBasic() throws IOException {
AmazonS3ClientMock client = AmazonS3MockFactory.getAmazonClientMock();
Files.write(client.bucket("bucketA").dir("dir").resolve("dir/file"), "sample".getBytes());
FileSystem fs;
try {
fs = s3fsProvider.getFileSystem(S3EndpointConstant.S3_GLOBAL_URI_TEST);
} catch (FileSystemNotFoundException e) {
fs = (S3FileSystem) FileSystems.newFileSystem(S3EndpointConstant.S3_GLOBAL_URI_TEST, null);
}
Path file = fs.getPath("/bucketA/dir/file");
Map<String, Object> fileAttributes = s3fsProvider.readAttributes(file, "basic:*");
Map<String, Object> fileAttributes2 = s3fsProvider.readAttributes(file, "*");
assertArrayEquals(fileAttributes.values().toArray(new Object[] {}), fileAttributes2.values().toArray(new Object[] {}));
assertArrayEquals(fileAttributes.keySet().toArray(new String[] {}), fileAttributes2.keySet().toArray(new String[] {}));
} | @Test
public void readAttributesAllBasic() throws IOException {
AmazonS3ClientMock client = AmazonS3MockFactory.getAmazonClientMock();
Files.write(client.bucket("bucketA").dir("dir").resolve("dir/file"), "sample".getBytes());
<DeepExtract>
FileSystem fs;
try {
fs = s3fsProvider.getFileSystem(S3EndpointConstant.S3_GLOBAL_URI_TEST);
} catch (FileSystemNotFoundException e) {
fs = (S3FileSystem) FileSystems.newFileSystem(S3EndpointConstant.S3_GLOBAL_URI_TEST, null);
}
</DeepExtract>
Path file = fs.getPath("/bucketA/dir/file");
Map<String, Object> fileAttributes = s3fsProvider.readAttributes(file, "basic:*");
Map<String, Object> fileAttributes2 = s3fsProvider.readAttributes(file, "*");
assertArrayEquals(fileAttributes.values().toArray(new Object[] {}), fileAttributes2.values().toArray(new Object[] {}));
assertArrayEquals(fileAttributes.keySet().toArray(new String[] {}), fileAttributes2.keySet().toArray(new String[] {}));
} | nifi-minio | positive | 2,890 |
@Test
public void testJsonBundleStrings() {
JavaRDD<String> jsonBundlesRdd = spark.sparkContext().wholeTextFiles("src/test/resources/json/bundles", 1).toJavaRDD().map(tuple -> tuple._2());
Dataset<String> jsonBundles = spark.createDataset(jsonBundlesRdd.rdd(), Encoders.STRING());
jsonBundles.write().saveAsTable("json_bundle_table");
JavaRDD<BundleContainer> bundlesRdd = bundles.fromJson(spark.sql("select value from json_bundle_table"), "value");
Dataset<Row> patients = BundlesTest.bundles.extractEntry(spark, bundlesRdd, Patient.class);
checkPatients(patients, patientConverter);
} | @Test
public void testJsonBundleStrings() {
JavaRDD<String> jsonBundlesRdd = spark.sparkContext().wholeTextFiles("src/test/resources/json/bundles", 1).toJavaRDD().map(tuple -> tuple._2());
Dataset<String> jsonBundles = spark.createDataset(jsonBundlesRdd.rdd(), Encoders.STRING());
jsonBundles.write().saveAsTable("json_bundle_table");
JavaRDD<BundleContainer> bundlesRdd = bundles.fromJson(spark.sql("select value from json_bundle_table"), "value");
Dataset<Row> patients = BundlesTest.bundles.extractEntry(spark, bundlesRdd, Patient.class);
<DeepExtract>
checkPatients(patients, patientConverter);
</DeepExtract>
} | bunsen | positive | 2,891 |
public <T> UpdateResults updateAll() {
MorphiaQuery q = new MorphiaQuery(c_).findBy((QueryImpl) ds().createQuery(c_), (UpdateOperations<T>) u_);
return ds().update((Query<T>) q.getMorphiaQuery(), (UpdateOperations<T>) u_);
} | public <T> UpdateResults updateAll() {
<DeepExtract>
MorphiaQuery q = new MorphiaQuery(c_).findBy((QueryImpl) ds().createQuery(c_), (UpdateOperations<T>) u_);
return ds().update((Query<T>) q.getMorphiaQuery(), (UpdateOperations<T>) u_);
</DeepExtract>
} | play-morphia | positive | 2,892 |
public void testSequenceFileWriter() throws Exception {
PropertiesConfiguration properties = new PropertiesConfiguration();
properties.addProperty("secor.file.reader.writer.factory", "com.pinterest.secor.io.impl.SequenceFileReaderWriterFactory");
mConfig = new SecorConfig(properties);
Path fsPath = (!false) ? new Path(PATH) : new Path(PATH_GZ);
SequenceFile.Reader reader = PowerMockito.mock(SequenceFile.Reader.class);
PowerMockito.whenNew(SequenceFile.Reader.class).withParameterTypes(FileSystem.class, Path.class, Configuration.class).withArguments(Mockito.any(FileSystem.class), Mockito.eq(fsPath), Mockito.any(Configuration.class)).thenReturn(reader);
Mockito.<Class<?>>when(reader.getKeyClass()).thenReturn((Class<?>) LongWritable.class);
Mockito.<Class<?>>when(reader.getValueClass()).thenReturn((Class<?>) BytesWritable.class);
if (!false) {
PowerMockito.mockStatic(SequenceFile.class);
SequenceFile.Writer writer = Mockito.mock(SequenceFile.Writer.class);
Mockito.when(SequenceFile.createWriter(Mockito.any(FileSystem.class), Mockito.any(Configuration.class), Mockito.eq(fsPath), Mockito.eq(LongWritable.class), Mockito.eq(BytesWritable.class))).thenReturn(writer);
Mockito.when(writer.getLength()).thenReturn(123L);
} else {
PowerMockito.mockStatic(SequenceFile.class);
SequenceFile.Writer writer = Mockito.mock(SequenceFile.Writer.class);
Mockito.when(SequenceFile.createWriter(Mockito.any(FileSystem.class), Mockito.any(Configuration.class), Mockito.eq(fsPath), Mockito.eq(LongWritable.class), Mockito.eq(BytesWritable.class), Mockito.eq(SequenceFile.CompressionType.BLOCK), Mockito.any(GzipCodec.class))).thenReturn(writer);
Mockito.when(writer.getLength()).thenReturn(12L);
}
FileWriter writer = ReflectionUtil.createFileWriter(mConfig.getFileReaderWriterFactory(), mLogFilePath, null, mConfig);
assert writer.getLength() == 123L;
Path fsPath = (!true) ? new Path(PATH) : new Path(PATH_GZ);
SequenceFile.Reader reader = PowerMockito.mock(SequenceFile.Reader.class);
PowerMockito.whenNew(SequenceFile.Reader.class).withParameterTypes(FileSystem.class, Path.class, Configuration.class).withArguments(Mockito.any(FileSystem.class), Mockito.eq(fsPath), Mockito.any(Configuration.class)).thenReturn(reader);
Mockito.<Class<?>>when(reader.getKeyClass()).thenReturn((Class<?>) LongWritable.class);
Mockito.<Class<?>>when(reader.getValueClass()).thenReturn((Class<?>) BytesWritable.class);
if (!true) {
PowerMockito.mockStatic(SequenceFile.class);
SequenceFile.Writer writer = Mockito.mock(SequenceFile.Writer.class);
Mockito.when(SequenceFile.createWriter(Mockito.any(FileSystem.class), Mockito.any(Configuration.class), Mockito.eq(fsPath), Mockito.eq(LongWritable.class), Mockito.eq(BytesWritable.class))).thenReturn(writer);
Mockito.when(writer.getLength()).thenReturn(123L);
} else {
PowerMockito.mockStatic(SequenceFile.class);
SequenceFile.Writer writer = Mockito.mock(SequenceFile.Writer.class);
Mockito.when(SequenceFile.createWriter(Mockito.any(FileSystem.class), Mockito.any(Configuration.class), Mockito.eq(fsPath), Mockito.eq(LongWritable.class), Mockito.eq(BytesWritable.class), Mockito.eq(SequenceFile.CompressionType.BLOCK), Mockito.any(GzipCodec.class))).thenReturn(writer);
Mockito.when(writer.getLength()).thenReturn(12L);
}
writer = ReflectionUtil.createFileWriter(mConfig.getFileReaderWriterFactory(), mLogFilePathGz, new GzipCodec(), mConfig);
assert writer.getLength() == 12L;
} | public void testSequenceFileWriter() throws Exception {
PropertiesConfiguration properties = new PropertiesConfiguration();
properties.addProperty("secor.file.reader.writer.factory", "com.pinterest.secor.io.impl.SequenceFileReaderWriterFactory");
mConfig = new SecorConfig(properties);
Path fsPath = (!false) ? new Path(PATH) : new Path(PATH_GZ);
SequenceFile.Reader reader = PowerMockito.mock(SequenceFile.Reader.class);
PowerMockito.whenNew(SequenceFile.Reader.class).withParameterTypes(FileSystem.class, Path.class, Configuration.class).withArguments(Mockito.any(FileSystem.class), Mockito.eq(fsPath), Mockito.any(Configuration.class)).thenReturn(reader);
Mockito.<Class<?>>when(reader.getKeyClass()).thenReturn((Class<?>) LongWritable.class);
Mockito.<Class<?>>when(reader.getValueClass()).thenReturn((Class<?>) BytesWritable.class);
if (!false) {
PowerMockito.mockStatic(SequenceFile.class);
SequenceFile.Writer writer = Mockito.mock(SequenceFile.Writer.class);
Mockito.when(SequenceFile.createWriter(Mockito.any(FileSystem.class), Mockito.any(Configuration.class), Mockito.eq(fsPath), Mockito.eq(LongWritable.class), Mockito.eq(BytesWritable.class))).thenReturn(writer);
Mockito.when(writer.getLength()).thenReturn(123L);
} else {
PowerMockito.mockStatic(SequenceFile.class);
SequenceFile.Writer writer = Mockito.mock(SequenceFile.Writer.class);
Mockito.when(SequenceFile.createWriter(Mockito.any(FileSystem.class), Mockito.any(Configuration.class), Mockito.eq(fsPath), Mockito.eq(LongWritable.class), Mockito.eq(BytesWritable.class), Mockito.eq(SequenceFile.CompressionType.BLOCK), Mockito.any(GzipCodec.class))).thenReturn(writer);
Mockito.when(writer.getLength()).thenReturn(12L);
}
FileWriter writer = ReflectionUtil.createFileWriter(mConfig.getFileReaderWriterFactory(), mLogFilePath, null, mConfig);
assert writer.getLength() == 123L;
<DeepExtract>
Path fsPath = (!true) ? new Path(PATH) : new Path(PATH_GZ);
SequenceFile.Reader reader = PowerMockito.mock(SequenceFile.Reader.class);
PowerMockito.whenNew(SequenceFile.Reader.class).withParameterTypes(FileSystem.class, Path.class, Configuration.class).withArguments(Mockito.any(FileSystem.class), Mockito.eq(fsPath), Mockito.any(Configuration.class)).thenReturn(reader);
Mockito.<Class<?>>when(reader.getKeyClass()).thenReturn((Class<?>) LongWritable.class);
Mockito.<Class<?>>when(reader.getValueClass()).thenReturn((Class<?>) BytesWritable.class);
if (!true) {
PowerMockito.mockStatic(SequenceFile.class);
SequenceFile.Writer writer = Mockito.mock(SequenceFile.Writer.class);
Mockito.when(SequenceFile.createWriter(Mockito.any(FileSystem.class), Mockito.any(Configuration.class), Mockito.eq(fsPath), Mockito.eq(LongWritable.class), Mockito.eq(BytesWritable.class))).thenReturn(writer);
Mockito.when(writer.getLength()).thenReturn(123L);
} else {
PowerMockito.mockStatic(SequenceFile.class);
SequenceFile.Writer writer = Mockito.mock(SequenceFile.Writer.class);
Mockito.when(SequenceFile.createWriter(Mockito.any(FileSystem.class), Mockito.any(Configuration.class), Mockito.eq(fsPath), Mockito.eq(LongWritable.class), Mockito.eq(BytesWritable.class), Mockito.eq(SequenceFile.CompressionType.BLOCK), Mockito.any(GzipCodec.class))).thenReturn(writer);
Mockito.when(writer.getLength()).thenReturn(12L);
}
</DeepExtract>
writer = ReflectionUtil.createFileWriter(mConfig.getFileReaderWriterFactory(), mLogFilePathGz, new GzipCodec(), mConfig);
assert writer.getLength() == 12L;
} | secor | positive | 2,893 |
public List<Long> getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
getSimDocuments_result result = new getSimDocuments_result();
receiveBase(result, "getSimDocuments");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getSimDocuments failed: unknown result");
} | public List<Long> getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
<DeepExtract>
getSimDocuments_result result = new getSimDocuments_result();
receiveBase(result, "getSimDocuments");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getSimDocuments failed: unknown result");
</DeepExtract>
} | news-duplicated | positive | 2,894 |
private boolean hasLock(boolean skipShared) throws ServerException {
if (activeLocks == null) {
String activeLocksJson = ExtendedAttributesExtension.getExtendedAttribute(getFullPath().toString(), activeLocksAttribute);
activeLocks = new ArrayList<>(SerializationUtils.deserializeList(LockInfo.class, activeLocksJson));
} else {
activeLocks = new LinkedList<>();
}
return activeLocks.stream().filter(x -> System.currentTimeMillis() < x.getTimeout()).map(lock -> new LockInfo(lock.isShared(), lock.isDeep(), lock.getToken(), (lock.getTimeout() < 0 || lock.getTimeout() == Long.MAX_VALUE) ? lock.getTimeout() : (lock.getTimeout() - System.currentTimeMillis()) / 1000, lock.getOwner())).collect(Collectors.toList());
return !activeLocks.isEmpty() && !(skipShared && activeLocks.get(0).isShared());
} | private boolean hasLock(boolean skipShared) throws ServerException {
<DeepExtract>
if (activeLocks == null) {
String activeLocksJson = ExtendedAttributesExtension.getExtendedAttribute(getFullPath().toString(), activeLocksAttribute);
activeLocks = new ArrayList<>(SerializationUtils.deserializeList(LockInfo.class, activeLocksJson));
} else {
activeLocks = new LinkedList<>();
}
return activeLocks.stream().filter(x -> System.currentTimeMillis() < x.getTimeout()).map(lock -> new LockInfo(lock.isShared(), lock.isDeep(), lock.getToken(), (lock.getTimeout() < 0 || lock.getTimeout() == Long.MAX_VALUE) ? lock.getTimeout() : (lock.getTimeout() - System.currentTimeMillis()) / 1000, lock.getOwner())).collect(Collectors.toList());
</DeepExtract>
return !activeLocks.isEmpty() && !(skipShared && activeLocks.get(0).isShared());
} | WebDAVServerSamplesJava | positive | 2,895 |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCl = (CoordinatorLayout) findViewById(R.id.main_cl);
mCoverIv = (AppCompatImageView) findViewById(R.id.main_tb_cover);
mTb = (Toolbar) findViewById(R.id.main_tb);
mTl = (TabLayout) findViewById(R.id.main_tab_layout);
mVp = (ViewPager) findViewById(R.id.main_view_pager);
mCoverLayout = findViewById(R.id.main_cover_layout);
mTb.setNavigationIcon(R.mipmap.ic_launcher_round);
setSupportActionBar(mTb);
mPapers[0] = new RandomFragment();
mPapers[1] = new LatestFragment();
mPapers[2] = new PopularFragment();
mAdapter = new PaperAdapter(getSupportFragmentManager());
mVp.setAdapter(mAdapter);
mVp.setOffscreenPageLimit(mPapers.length);
mVp.setCurrentItem(1);
mTl.setupWithViewPager(mVp);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
mTl.addOnTabSelectedListener(mTabListener);
if (Auth.hasMe(this)) {
showMe(Auth.getMe(this));
}
Auth.syncMe(this, new Auth.UserListener() {
@Override
public void onUserInfo(User user) {
showMe(user);
}
@Override
public void onUserNotExist() {
}
});
final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
final Drawable wallpaperDrawable = wallpaperManager.getDrawable();
mCoverIv.setImageDrawable(wallpaperDrawable);
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED));
LocalBroadcastManager.getInstance(this).registerReceiver(mLogoutReceiver, new IntentFilter(Finals.ACTION_LOGOUT));
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
ViewGroup.LayoutParams params = mCoverLayout.getLayoutParams();
params.height = UiHelper.getStatusBarHeight(MainActivity.this) + UiHelper.getActionBarSize(MainActivity.this);
mCoverLayout.setLayoutParams(params);
}
});
} | @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCl = (CoordinatorLayout) findViewById(R.id.main_cl);
mCoverIv = (AppCompatImageView) findViewById(R.id.main_tb_cover);
mTb = (Toolbar) findViewById(R.id.main_tb);
mTl = (TabLayout) findViewById(R.id.main_tab_layout);
mVp = (ViewPager) findViewById(R.id.main_view_pager);
mCoverLayout = findViewById(R.id.main_cover_layout);
mTb.setNavigationIcon(R.mipmap.ic_launcher_round);
setSupportActionBar(mTb);
mPapers[0] = new RandomFragment();
mPapers[1] = new LatestFragment();
mPapers[2] = new PopularFragment();
mAdapter = new PaperAdapter(getSupportFragmentManager());
mVp.setAdapter(mAdapter);
mVp.setOffscreenPageLimit(mPapers.length);
mVp.setCurrentItem(1);
mTl.setupWithViewPager(mVp);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
mTl.addOnTabSelectedListener(mTabListener);
if (Auth.hasMe(this)) {
showMe(Auth.getMe(this));
}
Auth.syncMe(this, new Auth.UserListener() {
@Override
public void onUserInfo(User user) {
showMe(user);
}
@Override
public void onUserNotExist() {
}
});
<DeepExtract>
final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
final Drawable wallpaperDrawable = wallpaperManager.getDrawable();
mCoverIv.setImageDrawable(wallpaperDrawable);
</DeepExtract>
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED));
LocalBroadcastManager.getInstance(this).registerReceiver(mLogoutReceiver, new IntentFilter(Finals.ACTION_LOGOUT));
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
ViewGroup.LayoutParams params = mCoverLayout.getLayoutParams();
params.height = UiHelper.getStatusBarHeight(MainActivity.this) + UiHelper.getActionBarSize(MainActivity.this);
mCoverLayout.setLayoutParams(params);
}
});
} | DelegateAdapter | positive | 2,896 |
public void union(BitSet other) {
int newLen = Math.max(wlen, other.wlen);
if (bits.length < newLen) {
bits = grow(bits, newLen);
}
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos = Math.min(wlen, other.wlen);
while (--pos >= 0) {
thisArr[pos] |= otherArr[pos];
}
if (this.wlen < newLen) {
System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen - this.wlen);
}
this.wlen = newLen;
} | public void union(BitSet other) {
int newLen = Math.max(wlen, other.wlen);
<DeepExtract>
if (bits.length < newLen) {
bits = grow(bits, newLen);
}
</DeepExtract>
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos = Math.min(wlen, other.wlen);
while (--pos >= 0) {
thisArr[pos] |= otherArr[pos];
}
if (this.wlen < newLen) {
System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen - this.wlen);
}
this.wlen = newLen;
} | hppc | positive | 2,897 |
private Component createUserIsRegisteredQuestion() {
Container container = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 3));
container.add(new JLabel("Do you want to create a new WatchDog " + this.getRegistrationType() + " registration?"));
ButtonGroup buttons = new ButtonGroup();
JRadioButton yes = new JRadioButton("Yes");
container.add(yes);
buttons.add(yes);
yes.addItemListener(itemEvent -> {
if (yes.isSelected()) {
this.panel.remove(this.dynamicContent);
this.recreateDynamicContent(getRegistrationPanel().apply(hasValidUserId -> {
this.hasValidUserId = hasValidUserId;
this.dynamicContent.updateUI();
wizard.updateButtons();
}));
this.panel.revalidate();
this.panel.repaint();
}
});
JRadioButton no = new JRadioButton("No");
container.add(no);
buttons.add(no);
no.addItemListener(itemEvent -> {
if (no.isSelected()) {
this.panel.remove(this.dynamicContent);
this.recreateDynamicContent(getIdInputPanel().apply(hasValidUserId -> {
this.hasValidUserId = hasValidUserId;
this.dynamicContent.updateUI();
wizard.updateButtons();
}));
this.panel.revalidate();
this.panel.repaint();
}
});
return container;
} | private Component createUserIsRegisteredQuestion() {
Container container = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 3));
container.add(new JLabel("Do you want to create a new WatchDog " + this.getRegistrationType() + " registration?"));
ButtonGroup buttons = new ButtonGroup();
JRadioButton yes = new JRadioButton("Yes");
container.add(yes);
buttons.add(yes);
yes.addItemListener(itemEvent -> {
if (yes.isSelected()) {
this.panel.remove(this.dynamicContent);
this.recreateDynamicContent(getRegistrationPanel().apply(hasValidUserId -> {
this.hasValidUserId = hasValidUserId;
this.dynamicContent.updateUI();
wizard.updateButtons();
}));
this.panel.revalidate();
this.panel.repaint();
}
});
JRadioButton no = new JRadioButton("No");
container.add(no);
buttons.add(no);
<DeepExtract>
no.addItemListener(itemEvent -> {
if (no.isSelected()) {
this.panel.remove(this.dynamicContent);
this.recreateDynamicContent(getIdInputPanel().apply(hasValidUserId -> {
this.hasValidUserId = hasValidUserId;
this.dynamicContent.updateUI();
wizard.updateButtons();
}));
this.panel.revalidate();
this.panel.repaint();
}
});
</DeepExtract>
return container;
} | watchdog | positive | 2,898 |
@Override
public void sentEventWithClientContext(Event event, IResponseListener responseListener) {
DcsRequestBody dcsRequestBody = new DcsRequestBody(event);
dcsRequestBody.setClientContext(clientContexts());
dcsClient.sendRequest(dcsRequestBody, responseListener);
} | @Override
public void sentEventWithClientContext(Event event, IResponseListener responseListener) {
<DeepExtract>
DcsRequestBody dcsRequestBody = new DcsRequestBody(event);
dcsRequestBody.setClientContext(clientContexts());
dcsClient.sendRequest(dcsRequestBody, responseListener);
</DeepExtract>
} | dcs-sdk-java | positive | 2,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.