before stringlengths 33 3.21M | after stringlengths 63 3.21M | repo stringlengths 1 56 | type stringclasses 1
value | __index_level_0__ int64 0 442k |
|---|---|---|---|---|
@OnClick(R.id.preview_finish)
void onFinishClick() {
mIsComposing = true;
mVideoView.stopPlay();
SimpleArrayMap<Integer, Object> retPropSet = new SimpleArrayMap<>();
for (PreviewRestartParams.PreviewRestartListener l : mRestartListener) {
l.onPreviewStop();
if (l.onPreviewGetPropSet() != null) {
retPropSet.putAll(l.onPreviewGetPropSet());
}
}
mRootLayout.setClickable(false);
mMusicIcon.setVisibility(View.INVISIBLE);
mChartIcon.setVisibility(View.INVISIBLE);
mEffectIcon.setVisibility(View.INVISIBLE);
mFinishImg.setVisibility(View.INVISIBLE);
mBackImg.setVisibility(View.INVISIBLE);
mRectProgressView.setVisibility(View.VISIBLE);
mLoadingView.setVisibility(View.VISIBLE);
doCompose(retPropSet);
} | @OnClick(R.id.preview_finish)
void onFinishClick() {
<DeepExtract>
mIsComposing = true;
mVideoView.stopPlay();
SimpleArrayMap<Integer, Object> retPropSet = new SimpleArrayMap<>();
for (PreviewRestartParams.PreviewRestartListener l : mRestartListener) {
l.onPreviewStop();
if (l.onPreviewGetPropSet() != null) {
retPropSet.putAll(l.onPreviewGetPropSet());
}
}
mRootLayout.setClickable(false);
mMusicIcon.setVisibility(View.INVISIBLE);
mChartIcon.setVisibility(View.INVISIBLE);
mEffectIcon.setVisibility(View.INVISIBLE);
mFinishImg.setVisibility(View.INVISIBLE);
mBackImg.setVisibility(View.INVISIBLE);
mRectProgressView.setVisibility(View.VISIBLE);
mLoadingView.setVisibility(View.VISIBLE);
doCompose(retPropSet);
</DeepExtract>
} | DogCamera | positive | 440,119 |
public int playAsset(String assetName, Controller controller) {
if (assetName == null) {
throw new NullPointerException();
}
int token = service.cue(assetName, this);
controllerMap.put(token, controller);
return token;
} | public int playAsset(String assetName, Controller controller) {
<DeepExtract>
if (assetName == null) {
throw new NullPointerException();
}
</DeepExtract>
int token = service.cue(assetName, this);
controllerMap.put(token, controller);
return token;
} | thread-weaver | positive | 440,122 |
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
mPaint = new Paint();
mColor = Color.parseColor(WEB_PROGRESS_COLOR);
mPaint.setAntiAlias(true);
this.mColor = mColor;
mPaint.setColor(mColor);
mPaint.setDither(true);
mPaint.setStrokeCap(Paint.Cap.SQUARE);
mTargetWidth = context.getResources().getDisplayMetrics().widthPixels;
final float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (WEB_PROGRESS_DEFAULT_HEIGHT * scale + 0.5f);
} | private void init(Context context, AttributeSet attrs, int defStyleAttr) {
mPaint = new Paint();
mColor = Color.parseColor(WEB_PROGRESS_COLOR);
mPaint.setAntiAlias(true);
this.mColor = mColor;
mPaint.setColor(mColor);
mPaint.setDither(true);
mPaint.setStrokeCap(Paint.Cap.SQUARE);
mTargetWidth = context.getResources().getDisplayMetrics().widthPixels;
<DeepExtract>
final float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (WEB_PROGRESS_DEFAULT_HEIGHT * scale + 0.5f);
</DeepExtract>
} | YCWebView | positive | 440,123 |
public Chunk getChunk(int x, int z) {
if (!active) {
throw new BlockModelNotHeldException("Block model holding is disabled, change block.holdModel to enable it");
}
return loadedChunks.get(encodeCoords(x, z));
} | public Chunk getChunk(int x, int z) {
<DeepExtract>
if (!active) {
throw new BlockModelNotHeldException("Block model holding is disabled, change block.holdModel to enable it");
}
</DeepExtract>
return loadedChunks.get(encodeCoords(x, z));
} | Angelia-core | positive | 440,125 |
@Override
protected void processFirstRow(CSVReader csvReader, String[] row) throws IOException {
String[] keys = rowToKeys(row);
importer.setEdgeKeys(keys);
} | @Override
protected void processFirstRow(CSVReader csvReader, String[] row) throws IOException {
<DeepExtract>
String[] keys = rowToKeys(row);
importer.setEdgeKeys(keys);
</DeepExtract>
} | bjoern | positive | 440,126 |
@Override
public void onCreate() {
super.onCreate();
Set<RequestListener> listeners = new HashSet<>();
listeners.add(new RequestLoggingListener());
ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this).setRequestListeners(listeners).setDownsampleEnabled(true).build();
Fresco.initialize(this, config);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
if (SPFManager.getPassword(this).equals("")) {
hasPassword = false;
} else {
hasPassword = true;
}
ThemeManager themeManager = ThemeManager.getInstance();
themeManager.setCurrentTheme(SPFManager.getTheme(this));
Locale locale;
switch(SPFManager.getLocalLanguageCode(this)) {
case 1:
locale = Locale.ENGLISH;
break;
case 2:
locale = Locale.JAPANESE;
break;
case 3:
locale = Locale.TRADITIONAL_CHINESE;
break;
case 4:
locale = Locale.SIMPLIFIED_CHINESE;
break;
case 5:
locale = Locale.KOREAN;
break;
case 6:
locale = new Locale("th", "");
break;
case 7:
locale = Locale.FRENCH;
break;
case 8:
locale = new Locale("es", "");
break;
default:
locale = Locale.getDefault();
break;
}
Locale.setDefault(locale);
Configuration config = getBaseContext().getResources().getConfiguration();
overwriteConfigurationLocale(config, locale);
} | @Override
public void onCreate() {
super.onCreate();
Set<RequestListener> listeners = new HashSet<>();
listeners.add(new RequestLoggingListener());
ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this).setRequestListeners(listeners).setDownsampleEnabled(true).build();
Fresco.initialize(this, config);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
if (SPFManager.getPassword(this).equals("")) {
hasPassword = false;
} else {
hasPassword = true;
}
ThemeManager themeManager = ThemeManager.getInstance();
themeManager.setCurrentTheme(SPFManager.getTheme(this));
<DeepExtract>
Locale locale;
switch(SPFManager.getLocalLanguageCode(this)) {
case 1:
locale = Locale.ENGLISH;
break;
case 2:
locale = Locale.JAPANESE;
break;
case 3:
locale = Locale.TRADITIONAL_CHINESE;
break;
case 4:
locale = Locale.SIMPLIFIED_CHINESE;
break;
case 5:
locale = Locale.KOREAN;
break;
case 6:
locale = new Locale("th", "");
break;
case 7:
locale = Locale.FRENCH;
break;
case 8:
locale = new Locale("es", "");
break;
default:
locale = Locale.getDefault();
break;
}
Locale.setDefault(locale);
Configuration config = getBaseContext().getResources().getConfiguration();
overwriteConfigurationLocale(config, locale);
</DeepExtract>
} | MyDiary | positive | 440,127 |
private void setupDialogValues() {
mHSV = new float[3];
Color.RGBToHSV(Color.red(mValue), Color.green(mValue), Color.blue(mValue), mHSV);
mAlpha = (float) Color.alpha(mValue) / 255.0f;
mValue = new float[] { mHSV[0] / 360.0f };
if (mColorView != null) {
mColorView.setColor(new float[] { mHSV[0] / 360.0f });
}
persistInt(new float[] { mHSV[0] / 360.0f });
notifyChanged();
mValue = new float[] { mAlpha };
if (mColorView != null) {
mColorView.setColor(new float[] { mAlpha });
}
persistInt(new float[] { mAlpha });
notifyChanged();
mAlphaSlider.setColor(mValue);
mValue = new float[] { mHSV[1], mHSV[2] };
if (mColorView != null) {
mColorView.setColor(new float[] { mHSV[1], mHSV[2] });
}
persistInt(new float[] { mHSV[1], mHSV[2] });
notifyChanged();
mSvMap.setHue(mHSV[0]);
mColorOld.setColor(mValue);
mColorNew.setColor(mValue);
} | private void setupDialogValues() {
mHSV = new float[3];
Color.RGBToHSV(Color.red(mValue), Color.green(mValue), Color.blue(mValue), mHSV);
mAlpha = (float) Color.alpha(mValue) / 255.0f;
mValue = new float[] { mHSV[0] / 360.0f };
if (mColorView != null) {
mColorView.setColor(new float[] { mHSV[0] / 360.0f });
}
persistInt(new float[] { mHSV[0] / 360.0f });
notifyChanged();
mValue = new float[] { mAlpha };
if (mColorView != null) {
mColorView.setColor(new float[] { mAlpha });
}
persistInt(new float[] { mAlpha });
notifyChanged();
mAlphaSlider.setColor(mValue);
<DeepExtract>
mValue = new float[] { mHSV[1], mHSV[2] };
if (mColorView != null) {
mColorView.setColor(new float[] { mHSV[1], mHSV[2] });
}
persistInt(new float[] { mHSV[1], mHSV[2] });
notifyChanged();
</DeepExtract>
mSvMap.setHue(mHSV[0]);
mColorOld.setColor(mValue);
mColorNew.setColor(mValue);
} | aix-weather-widget | positive | 440,129 |
public void display() {
for (int i = 0; i < tabCount; i++) {
buttons[i].display();
}
applet.strokeWeight(8);
applet.stroke(47, 54, 73);
applet.fill(0, 150);
for (int i = 0; i < tabCount; i++) {
if (activeButton != i) {
applet.rectMode(CENTER);
applet.rect(buttons[i].getX(), buttons[i].getY(), buttons[i].getW(), buttons[i].getH());
}
}
applet.strokeWeight(8);
applet.stroke(255, 255, 255);
applet.fill(0, 0);
if (buttonDistance == movingIncrement) {
applet.rectMode(CENTER);
applet.rect(buttons[activeButton].getX(), buttons[activeButton].getY(), buttons[activeButton].getW(), buttons[activeButton].getH());
movingIncrement = 0;
buttonDistance = 0;
setIncrementSpeed(1);
} else if (buttonDistance > movingIncrement) {
applet.rectMode(CENTER);
applet.rect(buttons[prevButton].getX() - movingIncrement, buttons[prevButton].getY(), buttons[prevButton].getW(), buttons[prevButton].getH());
movingIncrement += incrementSpeed;
setIncrementSpeed(movingIncrement);
if (movingIncrement > buttonDistance) {
movingIncrement = 0;
buttonDistance = 0;
setIncrementSpeed(1);
}
} else if (buttonDistance < movingIncrement) {
applet.rectMode(CENTER);
applet.rect(buttons[prevButton].getX() + movingIncrement, buttons[prevButton].getY(), buttons[prevButton].getW(), buttons[prevButton].getH());
movingIncrement += incrementSpeed;
setIncrementSpeed(movingIncrement);
if (movingIncrement > -buttonDistance) {
movingIncrement = 0;
buttonDistance = 0;
setIncrementSpeed(1);
}
}
} | public void display() {
for (int i = 0; i < tabCount; i++) {
buttons[i].display();
}
applet.strokeWeight(8);
applet.stroke(47, 54, 73);
applet.fill(0, 150);
for (int i = 0; i < tabCount; i++) {
if (activeButton != i) {
applet.rectMode(CENTER);
applet.rect(buttons[i].getX(), buttons[i].getY(), buttons[i].getW(), buttons[i].getH());
}
}
<DeepExtract>
applet.strokeWeight(8);
applet.stroke(255, 255, 255);
applet.fill(0, 0);
if (buttonDistance == movingIncrement) {
applet.rectMode(CENTER);
applet.rect(buttons[activeButton].getX(), buttons[activeButton].getY(), buttons[activeButton].getW(), buttons[activeButton].getH());
movingIncrement = 0;
buttonDistance = 0;
setIncrementSpeed(1);
} else if (buttonDistance > movingIncrement) {
applet.rectMode(CENTER);
applet.rect(buttons[prevButton].getX() - movingIncrement, buttons[prevButton].getY(), buttons[prevButton].getW(), buttons[prevButton].getH());
movingIncrement += incrementSpeed;
setIncrementSpeed(movingIncrement);
if (movingIncrement > buttonDistance) {
movingIncrement = 0;
buttonDistance = 0;
setIncrementSpeed(1);
}
} else if (buttonDistance < movingIncrement) {
applet.rectMode(CENTER);
applet.rect(buttons[prevButton].getX() + movingIncrement, buttons[prevButton].getY(), buttons[prevButton].getW(), buttons[prevButton].getH());
movingIncrement += incrementSpeed;
setIncrementSpeed(movingIncrement);
if (movingIncrement > -buttonDistance) {
movingIncrement = 0;
buttonDistance = 0;
setIncrementSpeed(1);
}
}
</DeepExtract>
} | Project-16x16 | positive | 440,132 |
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(name);
if (!aliases.isEmpty()) {
sb.append("(");
Iterator<String> aliasesIt = aliases.iterator();
while (aliasesIt.hasNext()) {
sb.append(aliasesIt.next());
if (aliasesIt.hasNext()) {
sb.append(",");
}
}
sb.append(")");
}
return sb.toString();
} | @Override
public String toString() {
<DeepExtract>
StringBuilder sb = new StringBuilder();
sb.append(name);
if (!aliases.isEmpty()) {
sb.append("(");
Iterator<String> aliasesIt = aliases.iterator();
while (aliasesIt.hasNext()) {
sb.append(aliasesIt.next());
if (aliasesIt.hasNext()) {
sb.append(",");
}
}
sb.append(")");
}
return sb.toString();
</DeepExtract>
} | jcommander | positive | 440,133 |
private static File unzip(File file) throws IOException {
File unzipped = new File("build", file.getName());
if (unzipped.isDirectory()) {
File[] entries = unzipped.listFiles();
for (File entry : entries) {
delete(entry);
}
}
unzipped.delete();
ZipUtils.unzipTo(new ZipFile(file), unzipped);
return unzipped;
} | private static File unzip(File file) throws IOException {
File unzipped = new File("build", file.getName());
<DeepExtract>
if (unzipped.isDirectory()) {
File[] entries = unzipped.listFiles();
for (File entry : entries) {
delete(entry);
}
}
unzipped.delete();
</DeepExtract>
ZipUtils.unzipTo(new ZipFile(file), unzipped);
return unzipped;
} | spring-migration-analyzer | positive | 440,134 |
private void _diff(CommandSender sender, final String name, final UUID uuid, String worldName, String filter, final String otherName, final UUID otherUuid, String[] regionNames) {
List<String> header = new ArrayList<>();
if (worldName == null) {
if (sender instanceof Player) {
worldName = ((Player) sender).getWorld().getName();
header.add(String.format(colorize("{GRAY}(Using current world: %s. Use -w to specify a world.)"), worldName));
} else {
List<World> worlds = Bukkit.getWorlds();
if (!worlds.isEmpty()) {
worldName = worlds.get(0).getName();
header.add(String.format(colorize("{GRAY}(Use -w to specify a world. Defaulting to \"%s\")"), worldName));
}
}
} else {
World world = Bukkit.getWorld(worldName);
if (world == null) {
sendMessage(sender, colorize("{RED}Invalid world."));
worldName = null;
}
}
return worldName;
if (worldName == null)
return;
if (!group) {
Utils.validatePlayer(storageStrategy.getPermissionService(), resolver.getDefaultGroup(), uuid, name, header);
Utils.validatePlayer(storageStrategy.getPermissionService(), resolver.getDefaultGroup(), otherUuid, otherName, header);
}
final Set<String> regions = new LinkedHashSet<>();
for (String region : regionNames) {
regions.add(region.toLowerCase());
}
final String lworldName = worldName.toLowerCase();
try {
rootPermissions = storageStrategy.getTransactionStrategy().execute(new TransactionCallback<Map<String, Boolean>>() {
@Override
public Map<String, Boolean> doInTransaction() throws Exception {
if (group) {
if (storageStrategy.getPermissionService().getEntity(name, null, true) == null)
throw new MissingGroupException(name);
return resolver.resolveGroup(name.toLowerCase(), lworldName, regions);
} else {
return resolver.resolvePlayer(uuid, lworldName, regions).getPermissions();
}
}
}, true);
} catch (MissingGroupException e) {
handleMissingGroup(sender, e);
return;
}
Map<String, Boolean> permissions = new HashMap<>();
Utils.calculateChildPermissions(permissions, rootPermissions, false);
try {
otherRootPermissions = storageStrategy.getTransactionStrategy().execute(new TransactionCallback<Map<String, Boolean>>() {
@Override
public Map<String, Boolean> doInTransaction() throws Exception {
if (group) {
if (storageStrategy.getPermissionService().getEntity(otherName, null, true) == null)
throw new MissingGroupException(otherName);
return resolver.resolveGroup(otherName.toLowerCase(), lworldName, regions);
} else {
return resolver.resolvePlayer(otherUuid, lworldName, regions).getPermissions();
}
}
}, true);
} catch (MissingGroupException e) {
handleMissingGroup(sender, e);
return;
}
Map<String, Boolean> otherPermissions = new HashMap<>();
Utils.calculateChildPermissions(otherPermissions, otherRootPermissions, false);
Utils.displayPermissionsDiff(plugin, sender, permissions, otherPermissions, header, String.format(colorize("%s%s {WHITE}adds {YELLOW}the following permissions:"), (group ? ChatColor.DARK_GREEN : ChatColor.AQUA), otherName), String.format(colorize("%s%s {WHITE}removes {YELLOW}the following permissions:"), (group ? ChatColor.DARK_GREEN : ChatColor.AQUA), otherName), String.format(colorize("%s%s {WHITE}changes {YELLOW}the following permissions:"), (group ? ChatColor.DARK_GREEN : ChatColor.AQUA), otherName), String.format(colorize("{YELLOW}%ss have identical effective permissions."), group ? "Group" : "Player"), filter);
} | private void _diff(CommandSender sender, final String name, final UUID uuid, String worldName, String filter, final String otherName, final UUID otherUuid, String[] regionNames) {
List<String> header = new ArrayList<>();
<DeepExtract>
if (worldName == null) {
if (sender instanceof Player) {
worldName = ((Player) sender).getWorld().getName();
header.add(String.format(colorize("{GRAY}(Using current world: %s. Use -w to specify a world.)"), worldName));
} else {
List<World> worlds = Bukkit.getWorlds();
if (!worlds.isEmpty()) {
worldName = worlds.get(0).getName();
header.add(String.format(colorize("{GRAY}(Use -w to specify a world. Defaulting to \"%s\")"), worldName));
}
}
} else {
World world = Bukkit.getWorld(worldName);
if (world == null) {
sendMessage(sender, colorize("{RED}Invalid world."));
worldName = null;
}
}
return worldName;
</DeepExtract>
if (worldName == null)
return;
if (!group) {
Utils.validatePlayer(storageStrategy.getPermissionService(), resolver.getDefaultGroup(), uuid, name, header);
Utils.validatePlayer(storageStrategy.getPermissionService(), resolver.getDefaultGroup(), otherUuid, otherName, header);
}
final Set<String> regions = new LinkedHashSet<>();
for (String region : regionNames) {
regions.add(region.toLowerCase());
}
final String lworldName = worldName.toLowerCase();
try {
rootPermissions = storageStrategy.getTransactionStrategy().execute(new TransactionCallback<Map<String, Boolean>>() {
@Override
public Map<String, Boolean> doInTransaction() throws Exception {
if (group) {
if (storageStrategy.getPermissionService().getEntity(name, null, true) == null)
throw new MissingGroupException(name);
return resolver.resolveGroup(name.toLowerCase(), lworldName, regions);
} else {
return resolver.resolvePlayer(uuid, lworldName, regions).getPermissions();
}
}
}, true);
} catch (MissingGroupException e) {
handleMissingGroup(sender, e);
return;
}
Map<String, Boolean> permissions = new HashMap<>();
Utils.calculateChildPermissions(permissions, rootPermissions, false);
try {
otherRootPermissions = storageStrategy.getTransactionStrategy().execute(new TransactionCallback<Map<String, Boolean>>() {
@Override
public Map<String, Boolean> doInTransaction() throws Exception {
if (group) {
if (storageStrategy.getPermissionService().getEntity(otherName, null, true) == null)
throw new MissingGroupException(otherName);
return resolver.resolveGroup(otherName.toLowerCase(), lworldName, regions);
} else {
return resolver.resolvePlayer(otherUuid, lworldName, regions).getPermissions();
}
}
}, true);
} catch (MissingGroupException e) {
handleMissingGroup(sender, e);
return;
}
Map<String, Boolean> otherPermissions = new HashMap<>();
Utils.calculateChildPermissions(otherPermissions, otherRootPermissions, false);
Utils.displayPermissionsDiff(plugin, sender, permissions, otherPermissions, header, String.format(colorize("%s%s {WHITE}adds {YELLOW}the following permissions:"), (group ? ChatColor.DARK_GREEN : ChatColor.AQUA), otherName), String.format(colorize("%s%s {WHITE}removes {YELLOW}the following permissions:"), (group ? ChatColor.DARK_GREEN : ChatColor.AQUA), otherName), String.format(colorize("%s%s {WHITE}changes {YELLOW}the following permissions:"), (group ? ChatColor.DARK_GREEN : ChatColor.AQUA), otherName), String.format(colorize("{YELLOW}%ss have identical effective permissions."), group ? "Group" : "Player"), filter);
} | zPermissions | positive | 440,136 |
public void cal(int digit, int left, int right) {
if (!check.contains(add(left, right))) {
check.add(add(left, right));
cache[digit].add(add(left, right));
}
if (!check.contains(sub(left, right))) {
check.add(sub(left, right));
cache[digit].add(sub(left, right));
}
if (!check.contains(mul(left, right))) {
check.add(mul(left, right));
cache[digit].add(mul(left, right));
}
if (!check.contains(div(left, right))) {
check.add(div(left, right));
cache[digit].add(div(left, right));
}
} | public void cal(int digit, int left, int right) {
if (!check.contains(add(left, right))) {
check.add(add(left, right));
cache[digit].add(add(left, right));
}
if (!check.contains(sub(left, right))) {
check.add(sub(left, right));
cache[digit].add(sub(left, right));
}
if (!check.contains(mul(left, right))) {
check.add(mul(left, right));
cache[digit].add(mul(left, right));
}
<DeepExtract>
if (!check.contains(div(left, right))) {
check.add(div(left, right));
cache[digit].add(div(left, right));
}
</DeepExtract>
} | Study-Book | positive | 440,137 |
public TreeDecomposition toTreeDecomposition() {
if (nestedBags == null) {
width = size - 1;
separatorWidth = 0;
return;
}
width = 0;
separatorWidth = 0;
for (Bag bag : nestedBags) {
if (bag.size - 1 > width) {
width = bag.size - 1;
}
}
for (Separator separator : separators) {
if (separator.size > separatorWidth) {
separatorWidth = separator.size;
}
}
if (separatorWidth > width) {
width = separatorWidth;
}
TreeDecomposition td = new TreeDecomposition(0, width, graph);
for (Bag bag : nestedBags) {
td.addBag(bag.vertexSet.toArray());
}
for (Separator separator : separators) {
VertexSet vs = separator.vertexSet;
Bag full = null;
for (Bag bag : separator.incidentBags) {
if (vs.isSubset(bag.vertexSet)) {
full = bag;
break;
}
}
if (full != null) {
int j = nestedBags.indexOf(full) + 1;
for (Bag bag : separator.incidentBags) {
if (bag != full) {
td.addEdge(j, nestedBags.indexOf(bag) + 1);
}
}
} else {
int j = td.addBag(separator.vertexSet.toArray());
for (Bag bag : separator.incidentBags) {
td.addEdge(j, nestedBags.indexOf(bag) + 1);
}
}
}
return td;
} | public TreeDecomposition toTreeDecomposition() {
<DeepExtract>
if (nestedBags == null) {
width = size - 1;
separatorWidth = 0;
return;
}
width = 0;
separatorWidth = 0;
for (Bag bag : nestedBags) {
if (bag.size - 1 > width) {
width = bag.size - 1;
}
}
for (Separator separator : separators) {
if (separator.size > separatorWidth) {
separatorWidth = separator.size;
}
}
if (separatorWidth > width) {
width = separatorWidth;
}
</DeepExtract>
TreeDecomposition td = new TreeDecomposition(0, width, graph);
for (Bag bag : nestedBags) {
td.addBag(bag.vertexSet.toArray());
}
for (Separator separator : separators) {
VertexSet vs = separator.vertexSet;
Bag full = null;
for (Bag bag : separator.incidentBags) {
if (vs.isSubset(bag.vertexSet)) {
full = bag;
break;
}
}
if (full != null) {
int j = nestedBags.indexOf(full) + 1;
for (Bag bag : separator.incidentBags) {
if (bag != full) {
td.addEdge(j, nestedBags.indexOf(bag) + 1);
}
}
} else {
int j = td.addBag(separator.vertexSet.toArray());
for (Bag bag : separator.incidentBags) {
td.addEdge(j, nestedBags.indexOf(bag) + 1);
}
}
}
return td;
} | PACE2017-TrackA | positive | 440,138 |
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null) {
Logging.info(this, "Received intent: " + intent);
if (intent.getDataString() != null) {
intentData = intent.getDataString();
final MessageScript ms = (intentData != null && !intentData.isEmpty()) ? new MessageScript(this, intentData) : null;
messageScript = ms != null && ms.isValid() ? ms : null;
} else {
intentData = intent.getAction();
}
setIntent(null);
}
} | @Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
<DeepExtract>
if (intent != null) {
Logging.info(this, "Received intent: " + intent);
if (intent.getDataString() != null) {
intentData = intent.getDataString();
final MessageScript ms = (intentData != null && !intentData.isEmpty()) ? new MessageScript(this, intentData) : null;
messageScript = ms != null && ms.isValid() ? ms : null;
} else {
intentData = intent.getAction();
}
setIntent(null);
}
</DeepExtract>
} | onpc | positive | 440,139 |
public static Fragment replaceFragment(@NonNull FragmentManager fragmentManager, @NonNull Fragment fragment, @IdRes int containerId, boolean isAddStack, SharedElement... sharedElement) {
Bundle bundle = fragment.getArguments();
if (bundle == null) {
bundle = new Bundle();
fragment.setArguments(bundle);
}
bundle.putInt(ARGS_ID, new Args(containerId, false, isAddStack).id);
bundle.putBoolean(ARGS_IS_HIDE, new Args(containerId, false, isAddStack).isHide);
bundle.putBoolean(ARGS_IS_ADD_STACK, new Args(containerId, false, isAddStack).isAddStack);
if (null == fragment) {
return null;
}
if (null != null && null.isRemoving()) {
Timber.e(null.getClass().getSimpleName() + " is isRemoving");
return null;
}
String name = fragment.getClass().getSimpleName();
Bundle args = fragment.getArguments();
FragmentTransaction ft = fragmentManager.beginTransaction();
if (sharedElement == null || sharedElement.length == 0) {
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
for (SharedElement element : sharedElement) {
ft.addSharedElement(element.sharedElement, element.name);
}
}
switch(TYPE_REPLACE_FRAGMENT) {
case TYPE_ADD_FRAGMENT:
if (null != null) {
ft.hide(null);
}
if (fragment.isAdded()) {
break;
}
ft.add(args.getInt(ARGS_ID), fragment, name);
if (args.getBoolean(ARGS_IS_HIDE)) {
ft.hide(fragment);
}
if (args.getBoolean(ARGS_IS_ADD_STACK)) {
ft.addToBackStack(name);
}
break;
case TYPE_REMOVE_FRAGMENT:
ft.remove(fragment);
break;
case TYPE_REMOVE_TO_FRAGMENT:
List<Fragment> fragments = getFragments(fragmentManager);
for (int i = fragments.size() - 1; i >= 0; --i) {
Fragment fragment = fragments.get(i);
if (fragment == fragment) {
if (null != null) {
ft.remove(fragment);
}
break;
}
ft.remove(fragment);
}
break;
case TYPE_REPLACE_FRAGMENT:
ft.replace(args.getInt(ARGS_ID), fragment, name);
if (args.getBoolean(ARGS_IS_ADD_STACK)) {
ft.addToBackStack(name);
}
break;
case TYPE_POP_ADD_FRAGMENT:
popFragment(fragmentManager);
ft.add(args.getInt(ARGS_ID), fragment, name);
if (args.getBoolean(ARGS_IS_ADD_STACK)) {
ft.addToBackStack(name);
}
break;
case TYPE_HIDE_FRAGMENT:
ft.hide(fragment);
break;
case TYPE_SHOW_FRAGMENT:
ft.show(fragment);
break;
case TYPE_HIDE_SHOW_FRAGMENT:
ft.hide(null).show(fragment);
break;
default:
break;
}
ft.commitAllowingStateLoss();
return fragment;
} | public static Fragment replaceFragment(@NonNull FragmentManager fragmentManager, @NonNull Fragment fragment, @IdRes int containerId, boolean isAddStack, SharedElement... sharedElement) {
Bundle bundle = fragment.getArguments();
if (bundle == null) {
bundle = new Bundle();
fragment.setArguments(bundle);
}
bundle.putInt(ARGS_ID, new Args(containerId, false, isAddStack).id);
bundle.putBoolean(ARGS_IS_HIDE, new Args(containerId, false, isAddStack).isHide);
bundle.putBoolean(ARGS_IS_ADD_STACK, new Args(containerId, false, isAddStack).isAddStack);
<DeepExtract>
if (null == fragment) {
return null;
}
if (null != null && null.isRemoving()) {
Timber.e(null.getClass().getSimpleName() + " is isRemoving");
return null;
}
String name = fragment.getClass().getSimpleName();
Bundle args = fragment.getArguments();
FragmentTransaction ft = fragmentManager.beginTransaction();
if (sharedElement == null || sharedElement.length == 0) {
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
for (SharedElement element : sharedElement) {
ft.addSharedElement(element.sharedElement, element.name);
}
}
switch(TYPE_REPLACE_FRAGMENT) {
case TYPE_ADD_FRAGMENT:
if (null != null) {
ft.hide(null);
}
if (fragment.isAdded()) {
break;
}
ft.add(args.getInt(ARGS_ID), fragment, name);
if (args.getBoolean(ARGS_IS_HIDE)) {
ft.hide(fragment);
}
if (args.getBoolean(ARGS_IS_ADD_STACK)) {
ft.addToBackStack(name);
}
break;
case TYPE_REMOVE_FRAGMENT:
ft.remove(fragment);
break;
case TYPE_REMOVE_TO_FRAGMENT:
List<Fragment> fragments = getFragments(fragmentManager);
for (int i = fragments.size() - 1; i >= 0; --i) {
Fragment fragment = fragments.get(i);
if (fragment == fragment) {
if (null != null) {
ft.remove(fragment);
}
break;
}
ft.remove(fragment);
}
break;
case TYPE_REPLACE_FRAGMENT:
ft.replace(args.getInt(ARGS_ID), fragment, name);
if (args.getBoolean(ARGS_IS_ADD_STACK)) {
ft.addToBackStack(name);
}
break;
case TYPE_POP_ADD_FRAGMENT:
popFragment(fragmentManager);
ft.add(args.getInt(ARGS_ID), fragment, name);
if (args.getBoolean(ARGS_IS_ADD_STACK)) {
ft.addToBackStack(name);
}
break;
case TYPE_HIDE_FRAGMENT:
ft.hide(fragment);
break;
case TYPE_SHOW_FRAGMENT:
ft.show(fragment);
break;
case TYPE_HIDE_SHOW_FRAGMENT:
ft.hide(null).show(fragment);
break;
default:
break;
}
ft.commitAllowingStateLoss();
return fragment;
</DeepExtract>
} | MVVMArms | positive | 440,140 |
public String toString(boolean cyrus) {
if (tophash != null)
return;
if (chars == null)
return;
setTopHash(!cyrus ? readHashMap(true) : readCyrusHash(true));
this.cyrus = false;
String str = (tophash != null) ? hashToString(tophash, 2, cyrus, false) : "";
chars = str.toCharArray();
chp = 0;
return new String(chars);
} | public String toString(boolean cyrus) {
if (tophash != null)
return;
if (chars == null)
return;
setTopHash(!cyrus ? readHashMap(true) : readCyrusHash(true));
<DeepExtract>
this.cyrus = false;
String str = (tophash != null) ? hashToString(tophash, 2, cyrus, false) : "";
chars = str.toCharArray();
chp = 0;
</DeepExtract>
return new String(chars);
} | NetMash | positive | 440,142 |
public FieldType getType(String key) {
Object o = fields.get(key);
if (o == null) {
return null;
}
return fields.get(key);
} | public FieldType getType(String key) {
<DeepExtract>
Object o = fields.get(key);
if (o == null) {
return null;
}
return fields.get(key);
</DeepExtract>
} | Elise | positive | 440,144 |
private static JmxMonitorMBean start(ExtendedServiceDiscoveryImpl instance) throws Exception {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance);
discovery.listen().subscribe(this::onDiscoveryEvent);
ObjectName objectName = new ObjectName(String.format(OBJECT_NAME_FORMAT, instance.cluster.member().id(), System.nanoTime()));
StandardMBean standardMBean = new StandardMBean(jmxMBean, MonitorMBean.class);
mbeanServer.registerMBean(standardMBean, objectName);
return jmxMBean;
} | private static JmxMonitorMBean start(ExtendedServiceDiscoveryImpl instance) throws Exception {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance);
<DeepExtract>
discovery.listen().subscribe(this::onDiscoveryEvent);
</DeepExtract>
ObjectName objectName = new ObjectName(String.format(OBJECT_NAME_FORMAT, instance.cluster.member().id(), System.nanoTime()));
StandardMBean standardMBean = new StandardMBean(jmxMBean, MonitorMBean.class);
mbeanServer.registerMBean(standardMBean, objectName);
return jmxMBean;
} | jetlinks-supports | positive | 440,146 |
@Override
protected Void doInBackground() throws Exception {
init();
if (reduction || contextReduction) {
state.saveConf();
}
if (!type && !contextReduction) {
context.transpose();
}
state.startCalculation(type ? StatusMessage.CLARIFYINGOBJECTS : contextReduction ? StatusMessage.CLARIFYING : StatusMessage.CLARIFYINGATTRIBUTES);
clarificationInProgress = true;
setProgressBarMessage(type ? StatusMessage.CLARIFYINGOBJECTS.toString() : contextReduction ? StatusMessage.CLARIFYING.toString() : StatusMessage.CLARIFYINGATTRIBUTES.toString());
int progress = 0;
setProgress(0);
IndexedSet<FullObject<String, String>> objects = context.getObjects();
ArrayList<FullObject<String, String>> toBeRemoved = new ArrayList<>();
for (int i = 0; i < context.getObjectCount(); i++) {
FullObject<String, String> o1 = objects.getElementAt(i);
for (int j = i + 1; j < context.getObjectCount(); j++) {
FullObject<String, String> o2 = objects.getElementAt(j);
if (context.getAttributesForObject(o1.getIdentifier()).equals(context.getAttributesForObject(o2.getIdentifier()))) {
toBeRemoved.add(o2);
}
}
setProgress((int) (((float) progress++ / context.getObjectCount()) * 100));
}
for (FullObject<String, String> o : toBeRemoved) {
context.removeObjectOnly(o);
}
state.endCalculation(type ? StatusMessage.CLARIFYINGOBJECTS : contextReduction ? StatusMessage.CLARIFYING : StatusMessage.CLARIFYINGATTRIBUTES);
clarificationInProgress = false;
if (reduction || contextReduction) {
reduce();
}
if (!type || contextReduction) {
context.transpose();
}
if (contextReduction) {
clarify();
reduce();
context.transpose();
}
return null;
} | @Override
protected Void doInBackground() throws Exception {
init();
if (reduction || contextReduction) {
state.saveConf();
}
if (!type && !contextReduction) {
context.transpose();
}
<DeepExtract>
state.startCalculation(type ? StatusMessage.CLARIFYINGOBJECTS : contextReduction ? StatusMessage.CLARIFYING : StatusMessage.CLARIFYINGATTRIBUTES);
clarificationInProgress = true;
setProgressBarMessage(type ? StatusMessage.CLARIFYINGOBJECTS.toString() : contextReduction ? StatusMessage.CLARIFYING.toString() : StatusMessage.CLARIFYINGATTRIBUTES.toString());
int progress = 0;
setProgress(0);
IndexedSet<FullObject<String, String>> objects = context.getObjects();
ArrayList<FullObject<String, String>> toBeRemoved = new ArrayList<>();
for (int i = 0; i < context.getObjectCount(); i++) {
FullObject<String, String> o1 = objects.getElementAt(i);
for (int j = i + 1; j < context.getObjectCount(); j++) {
FullObject<String, String> o2 = objects.getElementAt(j);
if (context.getAttributesForObject(o1.getIdentifier()).equals(context.getAttributesForObject(o2.getIdentifier()))) {
toBeRemoved.add(o2);
}
}
setProgress((int) (((float) progress++ / context.getObjectCount()) * 100));
}
for (FullObject<String, String> o : toBeRemoved) {
context.removeObjectOnly(o);
}
state.endCalculation(type ? StatusMessage.CLARIFYINGOBJECTS : contextReduction ? StatusMessage.CLARIFYING : StatusMessage.CLARIFYINGATTRIBUTES);
clarificationInProgress = false;
</DeepExtract>
if (reduction || contextReduction) {
reduce();
}
if (!type || contextReduction) {
context.transpose();
}
if (contextReduction) {
clarify();
reduce();
context.transpose();
}
return null;
} | conexp-ng | positive | 440,150 |
public Controller deleteWithRegEx(String regex, String method) {
regex = addPathPrefix(regex).replaceAll("\\/", "\\/");
String serviceMethod = this.getClass().getName() + "|" + method;
Set<Binding> bindings = uriBinding.get(serviceMethod);
if (bindings == null) {
bindings = new HashSet<>();
uriBinding.put(serviceMethod, bindings);
}
bindings.add(new Binding(HttpMethod.DELETE, Pattern.compile(regex), serviceMethod, actionType(serviceMethod)));
rm.deleteWithRegEx(regex, bindHandler(method));
return this;
} | public Controller deleteWithRegEx(String regex, String method) {
regex = addPathPrefix(regex).replaceAll("\\/", "\\/");
<DeepExtract>
String serviceMethod = this.getClass().getName() + "|" + method;
Set<Binding> bindings = uriBinding.get(serviceMethod);
if (bindings == null) {
bindings = new HashSet<>();
uriBinding.put(serviceMethod, bindings);
}
bindings.add(new Binding(HttpMethod.DELETE, Pattern.compile(regex), serviceMethod, actionType(serviceMethod)));
</DeepExtract>
rm.deleteWithRegEx(regex, bindHandler(method));
return this;
} | web-utils | positive | 440,152 |
final public Action OXPathActionVariable() throws ParseException {
Token oldToken;
if ((oldToken = token).next != null)
token = token.next;
else
token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == VARIABLE) {
jj_gen++;
t = token;
}
token = oldToken;
jj_kind = VARIABLE;
throw generateParseException();
{
if (true)
return new VariableAction(t.image);
}
throw new Error("Missing return statement in function");
} | final public Action OXPathActionVariable() throws ParseException {
<DeepExtract>
Token oldToken;
if ((oldToken = token).next != null)
token = token.next;
else
token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == VARIABLE) {
jj_gen++;
t = token;
}
token = oldToken;
jj_kind = VARIABLE;
throw generateParseException();
</DeepExtract>
{
if (true)
return new VariableAction(t.image);
}
throw new Error("Missing return statement in function");
} | OXPath | positive | 440,153 |
@Override
public void saveSourceResolution(Resolution sourceResolution) {
PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(project);
if (sourceResolution != null) {
propertiesComponent.setValue(SOURCE_RESOLUTION, sourceResolution.toString());
} else {
propertiesComponent.unsetValue(SOURCE_RESOLUTION);
}
} | @Override
public void saveSourceResolution(Resolution sourceResolution) {
<DeepExtract>
PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(project);
if (sourceResolution != null) {
propertiesComponent.setValue(SOURCE_RESOLUTION, sourceResolution.toString());
} else {
propertiesComponent.unsetValue(SOURCE_RESOLUTION);
}
</DeepExtract>
} | android-drawable-importer-intellij-plugin | positive | 440,154 |
@Subscribe
public void receiveCreatePin(CreatePin pinComplete) {
realm.beginTransaction();
Credentials credentials = realm.where(Credentials.class).findFirst();
if (credentials != null) {
credentials.setPin(pinComplete.getPin());
}
realm.commitTransaction();
Address destination = new Address(binding.sendAddress.getText().toString());
if (destination.isValidAddress()) {
RxBus.get().post(new ShowOverlay());
BigInteger sendAmount;
if (wallet.getSendRawAmount() != null) {
sendAmount = new BigInteger(wallet.getSendRawAmount());
} else {
sendAmount = NumberUtil.getAmountAsRawBigInteger(wallet.getSendNanoAmount());
}
accountService.requestSend(wallet.getFrontierBlock(), destination, sendAmount);
analyticsService.track(AnalyticsEvents.SEND_BEGAN);
} else {
showError(R.string.send_error_alert_title, R.string.send_error_alert_message);
}
} | @Subscribe
public void receiveCreatePin(CreatePin pinComplete) {
realm.beginTransaction();
Credentials credentials = realm.where(Credentials.class).findFirst();
if (credentials != null) {
credentials.setPin(pinComplete.getPin());
}
realm.commitTransaction();
<DeepExtract>
Address destination = new Address(binding.sendAddress.getText().toString());
if (destination.isValidAddress()) {
RxBus.get().post(new ShowOverlay());
BigInteger sendAmount;
if (wallet.getSendRawAmount() != null) {
sendAmount = new BigInteger(wallet.getSendRawAmount());
} else {
sendAmount = NumberUtil.getAmountAsRawBigInteger(wallet.getSendNanoAmount());
}
accountService.requestSend(wallet.getFrontierBlock(), destination, sendAmount);
analyticsService.track(AnalyticsEvents.SEND_BEGAN);
} else {
showError(R.string.send_error_alert_title, R.string.send_error_alert_message);
}
</DeepExtract>
} | nano-wallet-android | positive | 440,155 |
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_udisk, container, false);
mContext = getActivity();
btnGoback = (Button) view.findViewById(R.id.btn_goback);
btnUdisk = (Button) view.findViewById(R.id.btn_udisk);
btnSdcard = (Button) view.findViewById(R.id.btn_sdcard);
btnExit = (Button) view.findViewById(R.id.btn_exit);
btn_confirm = (Button) view.findViewById(R.id.btn_confirm);
tv_path = (TextView) view.findViewById(R.id.tv_path);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
btnGoback.setOnClickListener(this);
btnSdcard.setOnClickListener(this);
btnUdisk.setOnClickListener(this);
btnExit.setOnClickListener(this);
btn_confirm.setOnClickListener(this);
if (mSelectMode == SelectMode.SelectMultiFile) {
mFileItemRecyclerViewAdapter = new SelectMulstFileItemRecyclerViewAdapter(mContext, mSelectMode);
} else {
mFileItemRecyclerViewAdapter = new SelectSingleFileItemRecyclerViewAdapter(mContext, mSelectMode);
}
mFileItemRecyclerViewAdapter.setOnItemClickLitener(this);
UsbSdk.addRegister(this);
initSdcard();
return view;
} | @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_udisk, container, false);
mContext = getActivity();
<DeepExtract>
btnGoback = (Button) view.findViewById(R.id.btn_goback);
btnUdisk = (Button) view.findViewById(R.id.btn_udisk);
btnSdcard = (Button) view.findViewById(R.id.btn_sdcard);
btnExit = (Button) view.findViewById(R.id.btn_exit);
btn_confirm = (Button) view.findViewById(R.id.btn_confirm);
tv_path = (TextView) view.findViewById(R.id.tv_path);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
btnGoback.setOnClickListener(this);
btnSdcard.setOnClickListener(this);
btnUdisk.setOnClickListener(this);
btnExit.setOnClickListener(this);
btn_confirm.setOnClickListener(this);
if (mSelectMode == SelectMode.SelectMultiFile) {
mFileItemRecyclerViewAdapter = new SelectMulstFileItemRecyclerViewAdapter(mContext, mSelectMode);
} else {
mFileItemRecyclerViewAdapter = new SelectSingleFileItemRecyclerViewAdapter(mContext, mSelectMode);
}
mFileItemRecyclerViewAdapter.setOnItemClickLitener(this);
UsbSdk.addRegister(this);
initSdcard();
</DeepExtract>
return view;
} | usbdisklib | positive | 440,156 |
@Override
public void mousePressed(MouseEvent e) {
ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(JenkinsToolWindowFactory.JENKINS_BROWSER);
if (toolWindow == null) {
return;
}
toolWindow.activate(null);
} | @Override
public void mousePressed(MouseEvent e) {
<DeepExtract>
ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(JenkinsToolWindowFactory.JENKINS_BROWSER);
if (toolWindow == null) {
return;
}
toolWindow.activate(null);
</DeepExtract>
} | jenkins-control-plugin | positive | 440,157 |
public void tick() {
super.tick();
ItemStack itemstack = this.container.getSlot(0).getStack();
if (!ItemStack.areItemStacksEqual(itemstack, this.last)) {
this.last = itemstack;
do {
this.flipT += (float) (this.random.nextInt(4) - this.random.nextInt(4));
} while (this.flip <= this.flipT + 1.0F && this.flip >= this.flipT - 1.0F);
}
++this.ticks;
this.oFlip = this.flip;
this.oOpen = this.open;
boolean flag = false;
for (int i = 0; i < 3; ++i) {
if ((this.container).worldClue[i] != 0) {
flag = true;
}
}
if (flag) {
this.open += 0.2F;
} else {
this.open -= 0.2F;
}
this.open = MathHelper.clamp(this.open, 0.0F, 1.0F);
float f1 = (this.flipT - this.flip) * 0.4F;
float f = 0.2F;
f1 = MathHelper.clamp(f1, -0.2F, 0.2F);
this.flipA += (f1 - this.flipA) * 0.9F;
this.flip += this.flipA;
} | public void tick() {
super.tick();
<DeepExtract>
ItemStack itemstack = this.container.getSlot(0).getStack();
if (!ItemStack.areItemStacksEqual(itemstack, this.last)) {
this.last = itemstack;
do {
this.flipT += (float) (this.random.nextInt(4) - this.random.nextInt(4));
} while (this.flip <= this.flipT + 1.0F && this.flip >= this.flipT - 1.0F);
}
++this.ticks;
this.oFlip = this.flip;
this.oOpen = this.open;
boolean flag = false;
for (int i = 0; i < 3; ++i) {
if ((this.container).worldClue[i] != 0) {
flag = true;
}
}
if (flag) {
this.open += 0.2F;
} else {
this.open -= 0.2F;
}
this.open = MathHelper.clamp(this.open, 0.0F, 1.0F);
float f1 = (this.flipT - this.flip) * 0.4F;
float f = 0.2F;
f1 = MathHelper.clamp(f1, -0.2F, 0.2F);
this.flipA += (f1 - this.flipA) * 0.9F;
this.flip += this.flipA;
</DeepExtract>
} | eidolon | positive | 440,159 |
public void evaluate() {
if (!contentIs("name", currentname))
return;
setWorld(currentworld);
if (tickNum == 0) {
contentSetAddAll("players", getNewPlayers());
contentSetAddAll("entities", getNewNativeEntitiesAroundPlayers());
setAndGetWorldState();
evaluate();
}
if (world != currentworld)
return;
while (true) {
LinkedList uidpushing = pushingQ.poll();
if (uidpushing == null)
break;
String pusheruid = (String) uidpushing.get(0);
LinkedHashMap pushing = (LinkedHashMap) uidpushing.get(1);
doPushing(pusheruid, pushing);
}
while (true) {
LinkedList uidplacing = placingQ.poll();
if (uidplacing == null)
break;
String placeruid = (String) uidplacing.get(0);
LinkedHashMap placing = (LinkedHashMap) uidplacing.get(1);
boolean trail = getBooleanFrom(placing, "trail");
if (!trail) {
LinkedHashMap oldplacing = places.get(placeruid);
if (oldplacing != null) {
doPlacing(oldplacing, true);
}
}
places.put(placeruid, placing);
doPlacing(placing, false);
}
while (true) {
LinkedList uidenstate = enstateQ.poll();
if (uidenstate == null)
break;
String entityuid = (String) uidenstate.get(0);
LinkedHashMap enstate = (LinkedHashMap) uidenstate.get(1);
String type = getTypeFromIs(enstate);
if (type == null)
continue;
boolean foreign = getBooleanFrom(enstate, "foreign");
String name = getStringFromHash(enstate, "name", null);
LinkedList position = getListFromHash(enstate, "position");
if (position.size() != 3)
continue;
Integer psx = getIntFromList(position, 0);
Integer psy = getIntFromList(position, 1);
Integer psz = getIntFromList(position, 2);
if (psx == null || psy == null || psz == null)
continue;
Entity e = entities.get(entityuid);
if (e == null || e.isDead) {
e = doSpawnEntity(entityuid, type, foreign, name, psx, psy, psz);
if (e == null)
continue;
entities.put(entityuid, e);
if (!foreign)
contentSetAdd("entities", entityuid);
} else {
doUpdateEntity(e, psx, psy, psz);
}
}
} | public void evaluate() {
if (!contentIs("name", currentname))
return;
setWorld(currentworld);
if (tickNum == 0) {
contentSetAddAll("players", getNewPlayers());
contentSetAddAll("entities", getNewNativeEntitiesAroundPlayers());
setAndGetWorldState();
evaluate();
}
if (world != currentworld)
return;
while (true) {
LinkedList uidpushing = pushingQ.poll();
if (uidpushing == null)
break;
String pusheruid = (String) uidpushing.get(0);
LinkedHashMap pushing = (LinkedHashMap) uidpushing.get(1);
doPushing(pusheruid, pushing);
}
while (true) {
LinkedList uidplacing = placingQ.poll();
if (uidplacing == null)
break;
String placeruid = (String) uidplacing.get(0);
LinkedHashMap placing = (LinkedHashMap) uidplacing.get(1);
boolean trail = getBooleanFrom(placing, "trail");
if (!trail) {
LinkedHashMap oldplacing = places.get(placeruid);
if (oldplacing != null) {
doPlacing(oldplacing, true);
}
}
places.put(placeruid, placing);
doPlacing(placing, false);
}
<DeepExtract>
while (true) {
LinkedList uidenstate = enstateQ.poll();
if (uidenstate == null)
break;
String entityuid = (String) uidenstate.get(0);
LinkedHashMap enstate = (LinkedHashMap) uidenstate.get(1);
String type = getTypeFromIs(enstate);
if (type == null)
continue;
boolean foreign = getBooleanFrom(enstate, "foreign");
String name = getStringFromHash(enstate, "name", null);
LinkedList position = getListFromHash(enstate, "position");
if (position.size() != 3)
continue;
Integer psx = getIntFromList(position, 0);
Integer psy = getIntFromList(position, 1);
Integer psz = getIntFromList(position, 2);
if (psx == null || psy == null || psz == null)
continue;
Entity e = entities.get(entityuid);
if (e == null || e.isDead) {
e = doSpawnEntity(entityuid, type, foreign, name, psx, psy, psz);
if (e == null)
continue;
entities.put(entityuid, e);
if (!foreign)
contentSetAdd("entities", entityuid);
} else {
doUpdateEntity(e, psx, psy, psz);
}
}
</DeepExtract>
} | NetMash | positive | 440,161 |
@Override
public Adapter caseTransition(Transition object) {
return null;
} | @Override
public Adapter caseTransition(Transition object) {
<DeepExtract>
return null;
</DeepExtract>
} | Xtext-Sirius-integration | positive | 440,162 |
public void initBean() {
super.initBean();
DefaultListModel viewDefaultListModel = new DefaultListModel();
Iterator iterator = views.iterator();
while (iterator.hasNext()) {
viewDefaultListModel.add(iterator.next());
}
viewSelect = new SelectFieldEx(viewDefaultListModel);
viewSelect.setSelectedItem(views.getDefaultView());
viewSelect.setActionCommand("ViewSelect");
viewSelect.addActionListener(this);
Column optionsColumn = new Column();
optionsWindow = new WindowPane();
optionsWindow.setVisible(false);
optionsWindow.setTitle("Options");
optionsWindow.setTitleBackground(Echo2Application.getButtonBackgroundColor());
optionsWindow.setBorder(new FillImageBorder(Echo2Application.getButtonBackgroundColor(), new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0)));
optionsWindow.setWidth(new Extent(500));
optionsWindow.setHeight(new Extent(185));
optionsWindow.setInsets(new Insets(10, 5, 0, 0));
optionsWindow.add(optionsColumn);
optionsWindow.setDefaultCloseOperation(WindowPane.HIDE_ON_CLOSE);
super.init();
if (!initCalled) {
initCalled = true;
displayReports(true);
}
Column filterColumn = new Column();
filterWindow = new WindowPane();
filterWindow.setVisible(false);
filterWindow.setTitle("Filter");
filterWindow.setTitleBackground(Echo2Application.getButtonBackgroundColor());
filterWindow.setBorder(new FillImageBorder(Echo2Application.getButtonBackgroundColor(), new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0)));
filterWindow.setWidth(new Extent(600));
filterWindow.setHeight(new Extent(400));
filterWindow.setInsets(new Insets(10, 5, 0, 0));
filterWindow.add(filterColumn);
filterWindow.setDefaultCloseOperation(WindowPane.HIDE_ON_CLOSE);
super.init();
if (!initCalled) {
initCalled = true;
displayReports(true);
}
Column uploadColumn = new Column();
uploadWindow = new WindowPane();
uploadWindow.setVisible(false);
uploadWindow.setTitle("Upload");
uploadWindow.setTitleBackground(Echo2Application.getButtonBackgroundColor());
uploadWindow.setBorder(new FillImageBorder(Echo2Application.getButtonBackgroundColor(), new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0)));
uploadWindow.setWidth(new Extent(350));
uploadWindow.setHeight(new Extent(110));
uploadWindow.setInsets(new Insets(10, 0, 10, 0));
uploadWindow.add(uploadColumn);
uploadWindow.setDefaultCloseOperation(WindowPane.HIDE_ON_CLOSE);
super.init();
if (!initCalled) {
initCalled = true;
displayReports(true);
}
Row buttonRow = Echo2Application.getNewRow();
Button expandAllButton = new Button("Expand all");
expandAllButton.setActionCommand("ExpandAll");
Echo2Application.decorateButton(expandAllButton);
expandAllButton.addActionListener(this);
Button collapseAllButton = new Button("Collapse all");
collapseAllButton.setActionCommand("CollapseAll");
Echo2Application.decorateButton(collapseAllButton);
collapseAllButton.addActionListener(this);
Button closeAllButton = new Button("Close all");
closeAllButton.setActionCommand("CloseAll");
Echo2Application.decorateButton(closeAllButton);
closeAllButton.addActionListener(this);
Button openAllButton = new Button("Open all");
openAllButton.setActionCommand("OpenAll");
openAllButton.addActionListener(this);
Echo2Application.decorateButton(openAllButton);
Button downloadTableButton = new Button("Download table");
downloadTableButton.setActionCommand("DownloadTable");
downloadTableButton.addActionListener(this);
Echo2Application.decorateButton(downloadTableButton);
Button downloadTreeButton = new Button("Download tree");
downloadTreeButton.setActionCommand("DownloadTree");
downloadTreeButton.addActionListener(this);
Echo2Application.decorateButton(downloadTreeButton);
Button compareButton = new Button("Compare all");
compareButton.setActionCommand("CompareAll");
Echo2Application.decorateButton(compareButton);
compareButton.addActionListener(this);
Button prepareUploadButton = new Button("Upload...");
prepareUploadButton.setActionCommand("OpenUploadWindow");
Echo2Application.decorateButton(prepareUploadButton);
prepareUploadButton.addActionListener(this);
Button optionsButtonWindow = new Button("Options...");
optionsButtonWindow.setActionCommand("OpenOptionsWindows");
Echo2Application.decorateButton(optionsButtonWindow);
optionsButtonWindow.addActionListener(this);
Row optionsRow = null;
if (addSeparateOptionsRow) {
optionsRow = Echo2Application.getNewRow();
optionsRow.setInsets(new Insets(0, 5, 0, 0));
}
Row uploadSelectRow = new Row();
ReportUploadListener reportUploadListener = new ReportUploadListener();
reportUploadListener.setReportsComponent(this);
uploadSelect = new UploadSelect();
uploadSelect.setEnabledSendButtonText("Upload");
uploadSelect.setDisabledSendButtonText("Upload");
try {
uploadSelect.addUploadListener(reportUploadListener);
} catch (TooManyListenersException e) {
displayAndLogError(e);
}
Button buttonRefresh = new Button("Refresh");
buttonRefresh.setActionCommand("Refresh");
Echo2Application.decorateButton(buttonRefresh);
buttonRefresh.addActionListener(this);
downloadSelectField = new SelectField(new String[] { "Both", "Report", "Message" });
downloadSelectField.setSelectedIndex(0);
integerFieldMaxMetadataTableSize = new IntegerField();
integerFieldMaxMetadataTableSize.setActionCommand("Refresh");
integerFieldMaxMetadataTableSize.setWidth(new Extent(25));
this.defaultValue = defaultMaxMetadataTableSize;
integerFieldMaxMetadataTableSize.addActionListener(this);
numberOfMetadataRecords = new Label();
filterRow = Echo2Application.getNewRow();
filterRow.setInsets(new Insets(0, 5, 0, 0));
metadataTableModel = new DefaultTableModel();
metadataSortableTableModel = new DefaultSortableTableModel(metadataTableModel);
metadataTableHeaderRenderer = new MetadataTableHeaderRenderer();
metadataTableCellRenderer = new MetadataTableCellRenderer();
columnLayoutDataForTable = new ColumnLayoutData();
metadataTable = new SortableTable(metadataSortableTableModel);
metadataTable.setDefaultHeaderRenderer(metadataTableHeaderRenderer);
metadataTable.setDefaultRenderer(metadataTableCellRenderer);
metadataTable.setLayoutData(columnLayoutDataForTable);
metadataTable.setBorder(new Border(1, Color.BLACK, Border.STYLE_DOTTED));
metadataTable.setFont(DefaultTreeCellRenderer.DEFAULT_FONT);
metadataTable.setRolloverBackground(Echo2Application.getButtonRolloverBackgroundColor());
metadataTable.setRolloverEnabled(true);
metadataTable.setSelectionBackground(Echo2Application.getButtonBackgroundColor());
metadataTable.setSelectionEnabled(true);
metadataTable.addActionListener(this);
metadataTable.setActionCommand("OpenReport");
columnLayoutDataForTable.setInsets(new Insets(0, 5, 0, 0));
this.metadataExtractor = metadataExtractor;
metadataTableHeaderRenderer.getLayoutData().setInsets(new Insets(0, 0, 0, 0));
metadataTableHeaderRenderer.getLayoutData().setBackground(Echo2Application.getPaneBackgroundColor());
this.metadataExtractor = metadataExtractor;
nameLabel = Echo2Application.createInfoLabelWithColumnLayoutData();
numberOfReportsInProgressLabel = Echo2Application.createInfoLabelWithColumnLayoutData();
estimatedMemoryUsageReportsInProgressLabel = Echo2Application.createInfoLabelWithColumnLayoutData();
reportGeneratorEnabledSelectField = new SelectField(new String[] { "Yes", "No" });
reportGeneratorEnabledSelectField.setActionCommand("UpdateGeneratorEnabled");
reportGeneratorEnabledSelectField.addActionListener(this);
reportGeneratorEnabledErrorLabel = Echo2Application.createErrorLabelWithRowLayoutData();
reportGeneratorEnabledErrorLabel.setVisible(false);
filterValuesLabel = Echo2Application.createInfoLabelWithRowLayoutData();
filterValuesListBox = new ListBox();
filterValuesListBox.setSelectionMode(ListSelectionModel.MULTIPLE_SELECTION);
filterValuesListBox.setActionCommand("UpdateFilterValues");
filterValuesListBox.addActionListener(this);
filterValuesListBox.setHeight(new Extent(300));
Row reportGeneratorEnabledRow = Echo2Application.getNewRow();
reportGeneratorEnabledRow.setInsets(new Insets(0, 5, 0, 0));
reportGeneratorEnabledRow.add(new Label("Report generator enabled:"));
reportGeneratorEnabledRow.add(reportGeneratorEnabledSelectField);
reportGeneratorEnabledRow.add(reportGeneratorEnabledErrorLabel);
regexFilterField = new TextField();
regexFilterField.setWidth(new Extent(200));
regexFilterField.setToolTipText("Example 1 (only store report when name is Hello World):\n" + "Hello World\n" + "\n" + "Example 2 (only store report when name contains Hello or World):\n" + ".*(Hello|World).*\n" + "\n" + "Example 3 (only store report when name doesn't start with Hello World):\n" + "^(?!Hello World).*");
Button buttonRegexFilterField = new Button("Apply");
buttonRegexFilterField.setActionCommand("UpdateRegexValues");
Echo2Application.decorateButton(buttonRegexFilterField);
buttonRegexFilterField.addActionListener(this);
Row reportFilterRegexRow = Echo2Application.getNewRow();
reportFilterRegexRow.setInsets(new Insets(0, 5, 0, 0));
reportFilterRegexRow.add(new Label("Report filter (regex):"));
reportFilterRegexRow.add(regexFilterField);
reportFilterRegexRow.add(buttonRegexFilterField);
Row filterValuesLabelRow = Echo2Application.getNewRow();
filterValuesLabelRow.setInsets(new Insets(0, 5, 0, 0));
filterValuesLabelRow.add(filterValuesLabel);
Row filterValuesSelectRow = Echo2Application.getNewRow();
filterValuesSelectRow.setInsets(new Insets(0, 5, 0, 0));
filterValuesSelectRow.add(new Label("Select one or more of:"));
filterValuesSelectRow.add(filterValuesListBox);
checkBoxTransformReportXml = new CheckBox("Transform report xml");
checkBoxTransformReportXml.setInsets(new Insets(0, 5, 0, 0));
checkBoxTransformReportXml.setSelected(true);
Button buttonOpenTransformationWindow = new Button("Transformation...");
buttonOpenTransformationWindow.setActionCommand("OpenTransformationWindow");
Echo2Application.decorateButton(buttonOpenTransformationWindow);
buttonOpenTransformationWindow.addActionListener(this);
Row transformationRow = Echo2Application.getNewRow();
transformationRow.setInsets(new Insets(0, 5, 0, 0));
transformationRow.add(checkBoxTransformReportXml);
transformationRow.add(buttonOpenTransformationWindow);
Row openLatestReportsRow = Echo2Application.getNewRow();
openLatestReportsRow.setInsets(new Insets(0, 5, 0, 0));
Button buttonOpen = new Button("Open");
buttonOpen.setActionCommand("OpenLatestReports");
Echo2Application.decorateButton(buttonOpen);
buttonOpen.addActionListener(this);
integerFieldOpenLatest = new IntegerField();
integerFieldOpenLatest.setWidth(new Extent(25));
this.defaultValue = 10;
checkBoxExcludeReportsWithEmptyReportXml = new CheckBox("Exclude reports with empty report xml");
checkBoxExcludeReportsWithEmptyReportXml.setSelected(true);
Button buttonOpenReportInProgress = new Button("Open");
buttonOpenReportInProgress.setActionCommand("OpenReportInProgress");
Echo2Application.decorateButton(buttonOpenReportInProgress);
buttonOpenReportInProgress.addActionListener(this);
integerFieldOpenReportInProgress = new IntegerField();
integerFieldOpenReportInProgress.setWidth(new Extent(25));
this.defaultValue = 1;
Row openReportInProgressRow = Echo2Application.getNewRow();
openReportInProgressRow.setInsets(new Insets(0, 5, 0, 0));
openReportInProgressRow.add(buttonOpenReportInProgress);
openReportInProgressRow.add(new Label("report in progress number"));
openReportInProgressRow.add(integerFieldOpenReportInProgress);
buttonRow.add(buttonRefresh);
buttonRow.add(optionsButtonWindow);
if (addCompareButton) {
buttonRow.add(compareButton);
}
buttonRow.add(prepareUploadButton);
buttonRow.add(downloadTableButton);
buttonRow.add(downloadTreeButton);
buttonRow.add(openAllButton);
buttonRow.add(expandAllButton);
buttonRow.add(collapseAllButton);
buttonRow.add(closeAllButton);
uploadSelectRow.add(new Label("Upload"));
uploadSelectRow.add(uploadSelect);
uploadColumn.add(uploadSelectRow);
openLatestReportsRow.add(buttonOpen);
openLatestReportsRow.add(integerFieldOpenLatest);
openLatestReportsRow.add(new Label("latest reports"));
openLatestReportsRow.add(checkBoxExcludeReportsWithEmptyReportXml);
if (addSeparateOptionsRow) {
rowForAdditinalOptions = optionsRow;
} else {
rowForAdditinalOptions = buttonRow;
}
rowForAdditinalOptions.add(new Label("Download:"));
rowForAdditinalOptions.add(downloadSelectField);
rowForAdditinalOptions.add(new Label("View:"));
rowForAdditinalOptions.add(viewSelect);
rowForAdditinalOptions.add(integerFieldMaxMetadataTableSize);
rowForAdditinalOptions.add(numberOfMetadataRecords);
optionsColumn.add(reportGeneratorEnabledRow);
optionsColumn.add(reportFilterRegexRow);
optionsColumn.add(transformationRow);
optionsColumn.add(openLatestReportsRow);
optionsColumn.add(openReportInProgressRow);
filterColumn.add(filterValuesLabelRow);
filterColumn.add(filterValuesSelectRow);
add(buttonRow);
if (addSeparateOptionsRow) {
add(optionsRow);
}
add(errorLabel);
add(filterRow);
add(metadataTable);
add(nameLabel);
add(numberOfReportsInProgressLabel);
add(estimatedMemoryUsageReportsInProgressLabel);
} | public void initBean() {
super.initBean();
DefaultListModel viewDefaultListModel = new DefaultListModel();
Iterator iterator = views.iterator();
while (iterator.hasNext()) {
viewDefaultListModel.add(iterator.next());
}
viewSelect = new SelectFieldEx(viewDefaultListModel);
viewSelect.setSelectedItem(views.getDefaultView());
viewSelect.setActionCommand("ViewSelect");
viewSelect.addActionListener(this);
Column optionsColumn = new Column();
optionsWindow = new WindowPane();
optionsWindow.setVisible(false);
optionsWindow.setTitle("Options");
optionsWindow.setTitleBackground(Echo2Application.getButtonBackgroundColor());
optionsWindow.setBorder(new FillImageBorder(Echo2Application.getButtonBackgroundColor(), new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0)));
optionsWindow.setWidth(new Extent(500));
optionsWindow.setHeight(new Extent(185));
optionsWindow.setInsets(new Insets(10, 5, 0, 0));
optionsWindow.add(optionsColumn);
optionsWindow.setDefaultCloseOperation(WindowPane.HIDE_ON_CLOSE);
super.init();
if (!initCalled) {
initCalled = true;
displayReports(true);
}
Column filterColumn = new Column();
filterWindow = new WindowPane();
filterWindow.setVisible(false);
filterWindow.setTitle("Filter");
filterWindow.setTitleBackground(Echo2Application.getButtonBackgroundColor());
filterWindow.setBorder(new FillImageBorder(Echo2Application.getButtonBackgroundColor(), new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0)));
filterWindow.setWidth(new Extent(600));
filterWindow.setHeight(new Extent(400));
filterWindow.setInsets(new Insets(10, 5, 0, 0));
filterWindow.add(filterColumn);
filterWindow.setDefaultCloseOperation(WindowPane.HIDE_ON_CLOSE);
super.init();
if (!initCalled) {
initCalled = true;
displayReports(true);
}
Column uploadColumn = new Column();
uploadWindow = new WindowPane();
uploadWindow.setVisible(false);
uploadWindow.setTitle("Upload");
uploadWindow.setTitleBackground(Echo2Application.getButtonBackgroundColor());
uploadWindow.setBorder(new FillImageBorder(Echo2Application.getButtonBackgroundColor(), new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0)));
uploadWindow.setWidth(new Extent(350));
uploadWindow.setHeight(new Extent(110));
uploadWindow.setInsets(new Insets(10, 0, 10, 0));
uploadWindow.add(uploadColumn);
uploadWindow.setDefaultCloseOperation(WindowPane.HIDE_ON_CLOSE);
super.init();
if (!initCalled) {
initCalled = true;
displayReports(true);
}
Row buttonRow = Echo2Application.getNewRow();
Button expandAllButton = new Button("Expand all");
expandAllButton.setActionCommand("ExpandAll");
Echo2Application.decorateButton(expandAllButton);
expandAllButton.addActionListener(this);
Button collapseAllButton = new Button("Collapse all");
collapseAllButton.setActionCommand("CollapseAll");
Echo2Application.decorateButton(collapseAllButton);
collapseAllButton.addActionListener(this);
Button closeAllButton = new Button("Close all");
closeAllButton.setActionCommand("CloseAll");
Echo2Application.decorateButton(closeAllButton);
closeAllButton.addActionListener(this);
Button openAllButton = new Button("Open all");
openAllButton.setActionCommand("OpenAll");
openAllButton.addActionListener(this);
Echo2Application.decorateButton(openAllButton);
Button downloadTableButton = new Button("Download table");
downloadTableButton.setActionCommand("DownloadTable");
downloadTableButton.addActionListener(this);
Echo2Application.decorateButton(downloadTableButton);
Button downloadTreeButton = new Button("Download tree");
downloadTreeButton.setActionCommand("DownloadTree");
downloadTreeButton.addActionListener(this);
Echo2Application.decorateButton(downloadTreeButton);
Button compareButton = new Button("Compare all");
compareButton.setActionCommand("CompareAll");
Echo2Application.decorateButton(compareButton);
compareButton.addActionListener(this);
Button prepareUploadButton = new Button("Upload...");
prepareUploadButton.setActionCommand("OpenUploadWindow");
Echo2Application.decorateButton(prepareUploadButton);
prepareUploadButton.addActionListener(this);
Button optionsButtonWindow = new Button("Options...");
optionsButtonWindow.setActionCommand("OpenOptionsWindows");
Echo2Application.decorateButton(optionsButtonWindow);
optionsButtonWindow.addActionListener(this);
Row optionsRow = null;
if (addSeparateOptionsRow) {
optionsRow = Echo2Application.getNewRow();
optionsRow.setInsets(new Insets(0, 5, 0, 0));
}
Row uploadSelectRow = new Row();
ReportUploadListener reportUploadListener = new ReportUploadListener();
reportUploadListener.setReportsComponent(this);
uploadSelect = new UploadSelect();
uploadSelect.setEnabledSendButtonText("Upload");
uploadSelect.setDisabledSendButtonText("Upload");
try {
uploadSelect.addUploadListener(reportUploadListener);
} catch (TooManyListenersException e) {
displayAndLogError(e);
}
Button buttonRefresh = new Button("Refresh");
buttonRefresh.setActionCommand("Refresh");
Echo2Application.decorateButton(buttonRefresh);
buttonRefresh.addActionListener(this);
downloadSelectField = new SelectField(new String[] { "Both", "Report", "Message" });
downloadSelectField.setSelectedIndex(0);
integerFieldMaxMetadataTableSize = new IntegerField();
integerFieldMaxMetadataTableSize.setActionCommand("Refresh");
integerFieldMaxMetadataTableSize.setWidth(new Extent(25));
this.defaultValue = defaultMaxMetadataTableSize;
integerFieldMaxMetadataTableSize.addActionListener(this);
numberOfMetadataRecords = new Label();
filterRow = Echo2Application.getNewRow();
filterRow.setInsets(new Insets(0, 5, 0, 0));
metadataTableModel = new DefaultTableModel();
metadataSortableTableModel = new DefaultSortableTableModel(metadataTableModel);
metadataTableHeaderRenderer = new MetadataTableHeaderRenderer();
metadataTableCellRenderer = new MetadataTableCellRenderer();
columnLayoutDataForTable = new ColumnLayoutData();
metadataTable = new SortableTable(metadataSortableTableModel);
metadataTable.setDefaultHeaderRenderer(metadataTableHeaderRenderer);
metadataTable.setDefaultRenderer(metadataTableCellRenderer);
metadataTable.setLayoutData(columnLayoutDataForTable);
metadataTable.setBorder(new Border(1, Color.BLACK, Border.STYLE_DOTTED));
metadataTable.setFont(DefaultTreeCellRenderer.DEFAULT_FONT);
metadataTable.setRolloverBackground(Echo2Application.getButtonRolloverBackgroundColor());
metadataTable.setRolloverEnabled(true);
metadataTable.setSelectionBackground(Echo2Application.getButtonBackgroundColor());
metadataTable.setSelectionEnabled(true);
metadataTable.addActionListener(this);
metadataTable.setActionCommand("OpenReport");
columnLayoutDataForTable.setInsets(new Insets(0, 5, 0, 0));
this.metadataExtractor = metadataExtractor;
metadataTableHeaderRenderer.getLayoutData().setInsets(new Insets(0, 0, 0, 0));
metadataTableHeaderRenderer.getLayoutData().setBackground(Echo2Application.getPaneBackgroundColor());
this.metadataExtractor = metadataExtractor;
nameLabel = Echo2Application.createInfoLabelWithColumnLayoutData();
numberOfReportsInProgressLabel = Echo2Application.createInfoLabelWithColumnLayoutData();
estimatedMemoryUsageReportsInProgressLabel = Echo2Application.createInfoLabelWithColumnLayoutData();
reportGeneratorEnabledSelectField = new SelectField(new String[] { "Yes", "No" });
reportGeneratorEnabledSelectField.setActionCommand("UpdateGeneratorEnabled");
reportGeneratorEnabledSelectField.addActionListener(this);
reportGeneratorEnabledErrorLabel = Echo2Application.createErrorLabelWithRowLayoutData();
reportGeneratorEnabledErrorLabel.setVisible(false);
filterValuesLabel = Echo2Application.createInfoLabelWithRowLayoutData();
filterValuesListBox = new ListBox();
filterValuesListBox.setSelectionMode(ListSelectionModel.MULTIPLE_SELECTION);
filterValuesListBox.setActionCommand("UpdateFilterValues");
filterValuesListBox.addActionListener(this);
filterValuesListBox.setHeight(new Extent(300));
Row reportGeneratorEnabledRow = Echo2Application.getNewRow();
reportGeneratorEnabledRow.setInsets(new Insets(0, 5, 0, 0));
reportGeneratorEnabledRow.add(new Label("Report generator enabled:"));
reportGeneratorEnabledRow.add(reportGeneratorEnabledSelectField);
reportGeneratorEnabledRow.add(reportGeneratorEnabledErrorLabel);
regexFilterField = new TextField();
regexFilterField.setWidth(new Extent(200));
regexFilterField.setToolTipText("Example 1 (only store report when name is Hello World):\n" + "Hello World\n" + "\n" + "Example 2 (only store report when name contains Hello or World):\n" + ".*(Hello|World).*\n" + "\n" + "Example 3 (only store report when name doesn't start with Hello World):\n" + "^(?!Hello World).*");
Button buttonRegexFilterField = new Button("Apply");
buttonRegexFilterField.setActionCommand("UpdateRegexValues");
Echo2Application.decorateButton(buttonRegexFilterField);
buttonRegexFilterField.addActionListener(this);
Row reportFilterRegexRow = Echo2Application.getNewRow();
reportFilterRegexRow.setInsets(new Insets(0, 5, 0, 0));
reportFilterRegexRow.add(new Label("Report filter (regex):"));
reportFilterRegexRow.add(regexFilterField);
reportFilterRegexRow.add(buttonRegexFilterField);
Row filterValuesLabelRow = Echo2Application.getNewRow();
filterValuesLabelRow.setInsets(new Insets(0, 5, 0, 0));
filterValuesLabelRow.add(filterValuesLabel);
Row filterValuesSelectRow = Echo2Application.getNewRow();
filterValuesSelectRow.setInsets(new Insets(0, 5, 0, 0));
filterValuesSelectRow.add(new Label("Select one or more of:"));
filterValuesSelectRow.add(filterValuesListBox);
checkBoxTransformReportXml = new CheckBox("Transform report xml");
checkBoxTransformReportXml.setInsets(new Insets(0, 5, 0, 0));
checkBoxTransformReportXml.setSelected(true);
Button buttonOpenTransformationWindow = new Button("Transformation...");
buttonOpenTransformationWindow.setActionCommand("OpenTransformationWindow");
Echo2Application.decorateButton(buttonOpenTransformationWindow);
buttonOpenTransformationWindow.addActionListener(this);
Row transformationRow = Echo2Application.getNewRow();
transformationRow.setInsets(new Insets(0, 5, 0, 0));
transformationRow.add(checkBoxTransformReportXml);
transformationRow.add(buttonOpenTransformationWindow);
Row openLatestReportsRow = Echo2Application.getNewRow();
openLatestReportsRow.setInsets(new Insets(0, 5, 0, 0));
Button buttonOpen = new Button("Open");
buttonOpen.setActionCommand("OpenLatestReports");
Echo2Application.decorateButton(buttonOpen);
buttonOpen.addActionListener(this);
integerFieldOpenLatest = new IntegerField();
integerFieldOpenLatest.setWidth(new Extent(25));
this.defaultValue = 10;
checkBoxExcludeReportsWithEmptyReportXml = new CheckBox("Exclude reports with empty report xml");
checkBoxExcludeReportsWithEmptyReportXml.setSelected(true);
Button buttonOpenReportInProgress = new Button("Open");
buttonOpenReportInProgress.setActionCommand("OpenReportInProgress");
Echo2Application.decorateButton(buttonOpenReportInProgress);
buttonOpenReportInProgress.addActionListener(this);
integerFieldOpenReportInProgress = new IntegerField();
integerFieldOpenReportInProgress.setWidth(new Extent(25));
<DeepExtract>
this.defaultValue = 1;
</DeepExtract>
Row openReportInProgressRow = Echo2Application.getNewRow();
openReportInProgressRow.setInsets(new Insets(0, 5, 0, 0));
openReportInProgressRow.add(buttonOpenReportInProgress);
openReportInProgressRow.add(new Label("report in progress number"));
openReportInProgressRow.add(integerFieldOpenReportInProgress);
buttonRow.add(buttonRefresh);
buttonRow.add(optionsButtonWindow);
if (addCompareButton) {
buttonRow.add(compareButton);
}
buttonRow.add(prepareUploadButton);
buttonRow.add(downloadTableButton);
buttonRow.add(downloadTreeButton);
buttonRow.add(openAllButton);
buttonRow.add(expandAllButton);
buttonRow.add(collapseAllButton);
buttonRow.add(closeAllButton);
uploadSelectRow.add(new Label("Upload"));
uploadSelectRow.add(uploadSelect);
uploadColumn.add(uploadSelectRow);
openLatestReportsRow.add(buttonOpen);
openLatestReportsRow.add(integerFieldOpenLatest);
openLatestReportsRow.add(new Label("latest reports"));
openLatestReportsRow.add(checkBoxExcludeReportsWithEmptyReportXml);
if (addSeparateOptionsRow) {
rowForAdditinalOptions = optionsRow;
} else {
rowForAdditinalOptions = buttonRow;
}
rowForAdditinalOptions.add(new Label("Download:"));
rowForAdditinalOptions.add(downloadSelectField);
rowForAdditinalOptions.add(new Label("View:"));
rowForAdditinalOptions.add(viewSelect);
rowForAdditinalOptions.add(integerFieldMaxMetadataTableSize);
rowForAdditinalOptions.add(numberOfMetadataRecords);
optionsColumn.add(reportGeneratorEnabledRow);
optionsColumn.add(reportFilterRegexRow);
optionsColumn.add(transformationRow);
optionsColumn.add(openLatestReportsRow);
optionsColumn.add(openReportInProgressRow);
filterColumn.add(filterValuesLabelRow);
filterColumn.add(filterValuesSelectRow);
add(buttonRow);
if (addSeparateOptionsRow) {
add(optionsRow);
}
add(errorLabel);
add(filterRow);
add(metadataTable);
add(nameLabel);
add(numberOfReportsInProgressLabel);
add(estimatedMemoryUsageReportsInProgressLabel);
} | ibis-ladybug | positive | 440,163 |
public List<Resource> getContents() {
Map<String, Resource> result = new LinkedHashMap<String, Resource>();
if (getCoverPage() != null && (!result.containsKey(getCoverPage().getHref()))) {
result.put(getCoverPage().getHref(), getCoverPage());
}
for (SpineReference spineReference : getSpine().getSpineReferences()) {
addToContentsResult(spineReference.getResource(), result);
}
for (Resource resource : getTableOfContents().getAllUniqueResources()) {
addToContentsResult(resource, result);
}
for (GuideReference guideReference : getGuide().getReferences()) {
addToContentsResult(guideReference.getResource(), result);
}
return new ArrayList<Resource>(result.values());
} | public List<Resource> getContents() {
Map<String, Resource> result = new LinkedHashMap<String, Resource>();
<DeepExtract>
if (getCoverPage() != null && (!result.containsKey(getCoverPage().getHref()))) {
result.put(getCoverPage().getHref(), getCoverPage());
}
</DeepExtract>
for (SpineReference spineReference : getSpine().getSpineReferences()) {
addToContentsResult(spineReference.getResource(), result);
}
for (Resource resource : getTableOfContents().getAllUniqueResources()) {
addToContentsResult(resource, result);
}
for (GuideReference guideReference : getGuide().getReferences()) {
addToContentsResult(guideReference.getResource(), result);
}
return new ArrayList<Resource>(result.values());
} | epublib | positive | 440,164 |
@Test
public void testVersionNotIncreasedWhenSchemaChanged() {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("ReActiveAndroid cannot verify the data integrity. Looks like" + " you've changed schema but forgot to update the version number. You can" + " simply fix this by increasing the version number.");
DatabaseConfig databaseConfig = new DatabaseConfig.Builder(TestDatabaseV1.class).addModelClasses(Model1.class).build();
ReActiveAndroid.init(new ReActiveConfig.Builder(TestUtils.getApplication()).addDatabaseConfigs(databaseConfig).build());
ReActiveAndroid.destroy();
initDatabase(TestDatabaseV1.class, Model2.class, Model2.class);
} | @Test
public void testVersionNotIncreasedWhenSchemaChanged() {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("ReActiveAndroid cannot verify the data integrity. Looks like" + " you've changed schema but forgot to update the version number. You can" + " simply fix this by increasing the version number.");
<DeepExtract>
DatabaseConfig databaseConfig = new DatabaseConfig.Builder(TestDatabaseV1.class).addModelClasses(Model1.class).build();
ReActiveAndroid.init(new ReActiveConfig.Builder(TestUtils.getApplication()).addDatabaseConfigs(databaseConfig).build());
</DeepExtract>
ReActiveAndroid.destroy();
initDatabase(TestDatabaseV1.class, Model2.class, Model2.class);
} | ReActiveAndroid | positive | 440,165 |
public void stepDown() {
orbitEye.y -= -moveSpeed;
needUpdate = true;
} | public void stepDown() {
<DeepExtract>
orbitEye.y -= -moveSpeed;
needUpdate = true;
</DeepExtract>
} | jPCBSim | positive | 440,166 |
public Criteria andMenuNameEqualTo(String value) {
if (value == null) {
throw new RuntimeException("Value for " + "menuName" + " cannot be null");
}
criteria.add(new Criterion("MENU_NAME =", value));
return (Criteria) this;
} | public Criteria andMenuNameEqualTo(String value) {
<DeepExtract>
if (value == null) {
throw new RuntimeException("Value for " + "menuName" + " cannot be null");
}
criteria.add(new Criterion("MENU_NAME =", value));
</DeepExtract>
return (Criteria) this;
} | console | positive | 440,168 |
private void testConnectAttemptsByProtoclol(IpChannelType ipChannelType) throws Exception {
this.clientAssocUp = false;
this.serverAssocUp = false;
this.clientAssocDown = false;
this.serverAssocDown = false;
this.clientMessage = null;
this.serverMessage = null;
this.management = new NettySctpManagementImpl("ClientAssociationTest");
this.management.start();
this.management.setConnectDelay(10000);
this.management.removeAllResourses();
this.server = (NettyServerImpl) this.management.addServer(SERVER_NAME, SERVER_HOST, SERVER_PORT, ipChannelType, false, 0, null);
this.serverAssociation = (NettyAssociationImpl) this.management.addServerAssociation(CLIENT_HOST, CLIENT_PORT, SERVER_NAME, SERVER_ASSOCIATION_NAME, ipChannelType);
this.clientAssociation = (NettyAssociationImpl) this.management.addAssociation(CLIENT_HOST, CLIENT_PORT, SERVER_HOST, SERVER_PORT, CLIENT_ASSOCIATION_NAME, ipChannelType, null);
this.serverAssociation.setAssociationListener(new ServerAssociationListener());
this.management.startAssociation(SERVER_ASSOCIATION_NAME);
this.clientAssociation.setAssociationListener(new ClientAssociationListenerImpl());
this.management.startAssociation(CLIENT_ASSOCIATION_NAME);
Thread.sleep(1000 * 20);
assertFalse(clientAssocUp);
assertFalse(serverAssocUp);
this.management.startServer(SERVER_NAME);
Thread.sleep(1000 * 40);
assertTrue(clientAssocUp);
assertTrue(serverAssocUp);
this.management.stopAssociation(CLIENT_ASSOCIATION_NAME);
Thread.sleep(1000);
this.management.stopAssociation(SERVER_ASSOCIATION_NAME);
this.management.stopServer(SERVER_NAME);
Thread.sleep(1000 * 2);
assertTrue(Arrays.equals(SERVER_MESSAGE, clientMessage));
assertTrue(Arrays.equals(CLIENT_MESSAGE, serverMessage));
assertTrue(clientAssocDown);
assertTrue(serverAssocDown);
Runtime runtime = Runtime.getRuntime();
this.management.removeAssociation(CLIENT_ASSOCIATION_NAME);
this.management.removeAssociation(SERVER_ASSOCIATION_NAME);
this.management.removeServer(SERVER_NAME);
this.management.stop();
} | private void testConnectAttemptsByProtoclol(IpChannelType ipChannelType) throws Exception {
this.clientAssocUp = false;
this.serverAssocUp = false;
this.clientAssocDown = false;
this.serverAssocDown = false;
this.clientMessage = null;
this.serverMessage = null;
this.management = new NettySctpManagementImpl("ClientAssociationTest");
this.management.start();
this.management.setConnectDelay(10000);
this.management.removeAllResourses();
this.server = (NettyServerImpl) this.management.addServer(SERVER_NAME, SERVER_HOST, SERVER_PORT, ipChannelType, false, 0, null);
this.serverAssociation = (NettyAssociationImpl) this.management.addServerAssociation(CLIENT_HOST, CLIENT_PORT, SERVER_NAME, SERVER_ASSOCIATION_NAME, ipChannelType);
this.clientAssociation = (NettyAssociationImpl) this.management.addAssociation(CLIENT_HOST, CLIENT_PORT, SERVER_HOST, SERVER_PORT, CLIENT_ASSOCIATION_NAME, ipChannelType, null);
this.serverAssociation.setAssociationListener(new ServerAssociationListener());
this.management.startAssociation(SERVER_ASSOCIATION_NAME);
this.clientAssociation.setAssociationListener(new ClientAssociationListenerImpl());
this.management.startAssociation(CLIENT_ASSOCIATION_NAME);
Thread.sleep(1000 * 20);
assertFalse(clientAssocUp);
assertFalse(serverAssocUp);
this.management.startServer(SERVER_NAME);
Thread.sleep(1000 * 40);
assertTrue(clientAssocUp);
assertTrue(serverAssocUp);
this.management.stopAssociation(CLIENT_ASSOCIATION_NAME);
Thread.sleep(1000);
this.management.stopAssociation(SERVER_ASSOCIATION_NAME);
this.management.stopServer(SERVER_NAME);
Thread.sleep(1000 * 2);
assertTrue(Arrays.equals(SERVER_MESSAGE, clientMessage));
assertTrue(Arrays.equals(CLIENT_MESSAGE, serverMessage));
assertTrue(clientAssocDown);
assertTrue(serverAssocDown);
Runtime runtime = Runtime.getRuntime();
<DeepExtract>
this.management.removeAssociation(CLIENT_ASSOCIATION_NAME);
this.management.removeAssociation(SERVER_ASSOCIATION_NAME);
this.management.removeServer(SERVER_NAME);
this.management.stop();
</DeepExtract>
} | sctp | positive | 440,171 |
public Criteria andNsrsbh2In(List<String> values) {
if (values == null) {
throw new RuntimeException("Value for " + "nsrsbh2" + " cannot be null");
}
criteria.add(new Criterion("nsrsbh2 in", values));
return (Criteria) this;
} | public Criteria andNsrsbh2In(List<String> values) {
<DeepExtract>
if (values == null) {
throw new RuntimeException("Value for " + "nsrsbh2" + " cannot be null");
}
criteria.add(new Criterion("nsrsbh2 in", values));
</DeepExtract>
return (Criteria) this;
} | einvoice | positive | 440,172 |
public String nextValueAsString() {
int startIndex = index;
if (takeNextValueFromLastRead) {
takeNextValueFromLastRead = false;
return lastTokenType;
}
char c = this.nextClean();
lastTokenBeginIndex = index;
if (c == ':') {
lastTokenType = JsonTokenType.PROPERTY_NAME;
return nextToken();
} else if (c == ',') {
return nextToken();
} else if (c == '{') {
lastTokenType = JsonTokenType.OBJECT_START;
} else if (c == '}') {
lastTokenType = JsonTokenType.OBJECT_END;
} else if (c == '[') {
lastTokenType = JsonTokenType.ARRAY_START;
} else if (c == ']') {
lastTokenType = JsonTokenType.ARRAY_END;
} else if (c == 0) {
lastTokenType = JsonTokenType.END_OF_JSON;
} else if (lastTokenType == JsonTokenType.PROPERTY_NAME) {
lastTokenType = JsonTokenType.PROPERTY_VALUE;
lastTokenValue = getNextRawValue();
} else {
lastTokenType = JsonTokenType.PROPERTY_NAME_OR_RAW_VALUE;
lastTokenValue = getNextRawValue();
}
return lastTokenType;
if (lastTokenType == JsonTokenType.PROPERTY_NAME_OR_RAW_VALUE || lastTokenType == JsonTokenType.PROPERTY_VALUE) {
return lastTokenValue;
}
takeNextValueFromLastRead = true;
nextToken();
if (lastTokenType == JsonTokenType.PROPERTY_NAME_OR_RAW_VALUE || lastTokenType == JsonTokenType.PROPERTY_VALUE) {
return;
} else if (lastTokenType == JsonTokenType.OBJECT_START) {
fastForwardObject();
return;
} else if (lastTokenType == JsonTokenType.ARRAY_START) {
fastForwardArray();
return;
}
throw new DeserializationException("Corrupted json, value cannot start with type: " + lastTokenType);
return jsonAsText.substring(startIndex, index + 1);
} | public String nextValueAsString() {
int startIndex = index;
if (takeNextValueFromLastRead) {
takeNextValueFromLastRead = false;
return lastTokenType;
}
char c = this.nextClean();
lastTokenBeginIndex = index;
if (c == ':') {
lastTokenType = JsonTokenType.PROPERTY_NAME;
return nextToken();
} else if (c == ',') {
return nextToken();
} else if (c == '{') {
lastTokenType = JsonTokenType.OBJECT_START;
} else if (c == '}') {
lastTokenType = JsonTokenType.OBJECT_END;
} else if (c == '[') {
lastTokenType = JsonTokenType.ARRAY_START;
} else if (c == ']') {
lastTokenType = JsonTokenType.ARRAY_END;
} else if (c == 0) {
lastTokenType = JsonTokenType.END_OF_JSON;
} else if (lastTokenType == JsonTokenType.PROPERTY_NAME) {
lastTokenType = JsonTokenType.PROPERTY_VALUE;
lastTokenValue = getNextRawValue();
} else {
lastTokenType = JsonTokenType.PROPERTY_NAME_OR_RAW_VALUE;
lastTokenValue = getNextRawValue();
}
return lastTokenType;
if (lastTokenType == JsonTokenType.PROPERTY_NAME_OR_RAW_VALUE || lastTokenType == JsonTokenType.PROPERTY_VALUE) {
return lastTokenValue;
}
takeNextValueFromLastRead = true;
<DeepExtract>
nextToken();
if (lastTokenType == JsonTokenType.PROPERTY_NAME_OR_RAW_VALUE || lastTokenType == JsonTokenType.PROPERTY_VALUE) {
return;
} else if (lastTokenType == JsonTokenType.OBJECT_START) {
fastForwardObject();
return;
} else if (lastTokenType == JsonTokenType.ARRAY_START) {
fastForwardArray();
return;
}
throw new DeserializationException("Corrupted json, value cannot start with type: " + lastTokenType);
</DeepExtract>
return jsonAsText.substring(startIndex, index + 1);
} | bristleback | positive | 440,173 |
@Override
public void onContainersCompleted(List<ContainerStatus> completedContainers) {
LOG.info("onContainersCompleted called in RMCallbackHandler, completed containers size: " + completedContainers.size());
if (System.getenv(Constants.TEST_TASK_COMPLETION_NOTIFICATION_DELAYED) != null) {
LOG.info("Sleeping for 1 second to simulate task completion notification delay");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOG.error("Interrupted while sleeping", e);
}
}
for (ContainerStatus containerStatus : completedContainers) {
int exitStatus = containerStatus.getExitStatus();
String diagnostics = containerStatus.getDiagnostics();
String outputLog = "ContainerID = " + containerStatus.getContainerId() + ", state = " + containerStatus.getState() + ", exitStatus = " + exitStatus + ", diagnostics = " + diagnostics;
String errorInformation = null;
if (ContainerExitStatus.SUCCESS != exitStatus) {
errorInformation = diagnostics;
LOG.error(outputLog);
} else {
LOG.info(outputLog);
}
processFinishedContainer(containerStatus.getContainerId(), exitStatus, errorInformation);
}
} | @Override
public void onContainersCompleted(List<ContainerStatus> completedContainers) {
LOG.info("onContainersCompleted called in RMCallbackHandler, completed containers size: " + completedContainers.size());
<DeepExtract>
if (System.getenv(Constants.TEST_TASK_COMPLETION_NOTIFICATION_DELAYED) != null) {
LOG.info("Sleeping for 1 second to simulate task completion notification delay");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOG.error("Interrupted while sleeping", e);
}
}
</DeepExtract>
for (ContainerStatus containerStatus : completedContainers) {
int exitStatus = containerStatus.getExitStatus();
String diagnostics = containerStatus.getDiagnostics();
String outputLog = "ContainerID = " + containerStatus.getContainerId() + ", state = " + containerStatus.getState() + ", exitStatus = " + exitStatus + ", diagnostics = " + diagnostics;
String errorInformation = null;
if (ContainerExitStatus.SUCCESS != exitStatus) {
errorInformation = diagnostics;
LOG.error(outputLog);
} else {
LOG.info(outputLog);
}
processFinishedContainer(containerStatus.getContainerId(), exitStatus, errorInformation);
}
} | TonY | positive | 440,175 |
@Test
public void testFilePayload() throws PayloadNotFoundException {
FilePayload filePayload = new FilePayload(assetFile.getAbsolutePath());
assertEquals(assetFile.length(), filePayload.getLength(InstrumentationRegistry.getInstrumentation().getContext()));
String asUri = filePayload.toUri();
Payload newPayload = PayloadFactory.fromUri(asUri);
assertEquals(newPayload, filePayload);
} | @Test
public void testFilePayload() throws PayloadNotFoundException {
FilePayload filePayload = new FilePayload(assetFile.getAbsolutePath());
<DeepExtract>
assertEquals(assetFile.length(), filePayload.getLength(InstrumentationRegistry.getInstrumentation().getContext()));
String asUri = filePayload.toUri();
Payload newPayload = PayloadFactory.fromUri(asUri);
assertEquals(newPayload, filePayload);
</DeepExtract>
} | cloudinary_android | positive | 440,176 |
@Override
public Instant getNullableResult(ResultSet rs, String columnName) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnName);
if (timestamp != null) {
return timestamp.toInstant();
}
return null;
} | @Override
public Instant getNullableResult(ResultSet rs, String columnName) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnName);
<DeepExtract>
if (timestamp != null) {
return timestamp.toInstant();
}
return null;
</DeepExtract>
} | EasyJdbc | positive | 440,178 |
private void populateGenders(Element controlNode) {
ConceptService conceptService = Context.getConceptService();
Element itemNode = append(controlNode, NS_XFORMS, NODE_ITEM);
appendText(itemNode, NS_XFORMS, NODE_LABEL, getLabel(conceptService.getConcept(MALE_CONCEPT_ID)));
appendText(itemNode, NS_XFORMS, NODE_VALUE, "M");
return itemNode;
Element itemNode = append(controlNode, NS_XFORMS, NODE_ITEM);
appendText(itemNode, NS_XFORMS, NODE_LABEL, getLabel(conceptService.getConcept(FEMALE_CONCEPT_ID)));
appendText(itemNode, NS_XFORMS, NODE_VALUE, "F");
return itemNode;
} | private void populateGenders(Element controlNode) {
ConceptService conceptService = Context.getConceptService();
Element itemNode = append(controlNode, NS_XFORMS, NODE_ITEM);
appendText(itemNode, NS_XFORMS, NODE_LABEL, getLabel(conceptService.getConcept(MALE_CONCEPT_ID)));
appendText(itemNode, NS_XFORMS, NODE_VALUE, "M");
return itemNode;
<DeepExtract>
Element itemNode = append(controlNode, NS_XFORMS, NODE_ITEM);
appendText(itemNode, NS_XFORMS, NODE_LABEL, getLabel(conceptService.getConcept(FEMALE_CONCEPT_ID)));
appendText(itemNode, NS_XFORMS, NODE_VALUE, "F");
return itemNode;
</DeepExtract>
} | buendia | positive | 440,179 |
public static final void log(long __utcms, Enum<?> __v, String __n, char[] __c, int __o, int __l) throws IndexOutOfBoundsException {
LoggerExecution exec;
IOpipeExecution exec = IOpipeExecution.currentExecution();
if (exec == null)
exec = null;
try {
exec = exec.<LoggerExecution>plugin(LoggerExecution.class);
} catch (ClassCastException | NoSuchPluginException e) {
exec = null;
}
if (exec != null)
exec.log(__utcms, __v, __n, __c, __o, __l);
} | public static final void log(long __utcms, Enum<?> __v, String __n, char[] __c, int __o, int __l) throws IndexOutOfBoundsException {
<DeepExtract>
LoggerExecution exec;
IOpipeExecution exec = IOpipeExecution.currentExecution();
if (exec == null)
exec = null;
try {
exec = exec.<LoggerExecution>plugin(LoggerExecution.class);
} catch (ClassCastException | NoSuchPluginException e) {
exec = null;
}
</DeepExtract>
if (exec != null)
exec.log(__utcms, __v, __n, __c, __o, __l);
} | iopipe-java | positive | 440,180 |
public static void setCanvasSize(int canvasWidth, int canvasHeight) {
if (canvasWidth <= 0)
throw new IllegalArgumentException("width must be positive");
if (canvasHeight <= 0)
throw new IllegalArgumentException("height must be positive");
width = canvasWidth;
height = canvasHeight;
if (frame != null)
frame.setVisible(false);
frame = new JFrame();
offscreenImage = new BufferedImage(2 * width, 2 * height, BufferedImage.TYPE_INT_ARGB);
onscreenImage = new BufferedImage(2 * width, 2 * height, BufferedImage.TYPE_INT_ARGB);
offscreen = offscreenImage.createGraphics();
onscreen = onscreenImage.createGraphics();
offscreen.scale(2.0, 2.0);
setXscale();
setYscale();
offscreen.setColor(DEFAULT_CLEAR_COLOR);
offscreen.fillRect(0, 0, width, height);
setPenColor();
setPenRadius();
setFont();
clear();
keysTyped = new LinkedList<Character>();
keysDown = new TreeSet<Integer>();
RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
offscreen.addRenderingHints(hints);
RetinaImageIcon icon = new RetinaImageIcon(onscreenImage);
JLabel draw = new JLabel(icon);
draw.addMouseListener(std);
draw.addMouseMotionListener(std);
frame.setContentPane(draw);
frame.addKeyListener(std);
frame.setFocusTraversalKeysEnabled(false);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Standard Draw");
frame.setJMenuBar(createMenuBar());
frame.pack();
frame.requestFocusInWindow();
frame.setVisible(true);
} | public static void setCanvasSize(int canvasWidth, int canvasHeight) {
if (canvasWidth <= 0)
throw new IllegalArgumentException("width must be positive");
if (canvasHeight <= 0)
throw new IllegalArgumentException("height must be positive");
width = canvasWidth;
height = canvasHeight;
<DeepExtract>
if (frame != null)
frame.setVisible(false);
frame = new JFrame();
offscreenImage = new BufferedImage(2 * width, 2 * height, BufferedImage.TYPE_INT_ARGB);
onscreenImage = new BufferedImage(2 * width, 2 * height, BufferedImage.TYPE_INT_ARGB);
offscreen = offscreenImage.createGraphics();
onscreen = onscreenImage.createGraphics();
offscreen.scale(2.0, 2.0);
setXscale();
setYscale();
offscreen.setColor(DEFAULT_CLEAR_COLOR);
offscreen.fillRect(0, 0, width, height);
setPenColor();
setPenRadius();
setFont();
clear();
keysTyped = new LinkedList<Character>();
keysDown = new TreeSet<Integer>();
RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
offscreen.addRenderingHints(hints);
RetinaImageIcon icon = new RetinaImageIcon(onscreenImage);
JLabel draw = new JLabel(icon);
draw.addMouseListener(std);
draw.addMouseMotionListener(std);
frame.setContentPane(draw);
frame.addKeyListener(std);
frame.setFocusTraversalKeysEnabled(false);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Standard Draw");
frame.setJMenuBar(createMenuBar());
frame.pack();
frame.requestFocusInWindow();
frame.setVisible(true);
</DeepExtract>
} | CS112-Rutgers | positive | 440,182 |
protected void finalize() throws Throwable {
releaseNative(lock);
lock = 0;
super.finalize();
} | protected void finalize() throws Throwable {
<DeepExtract>
releaseNative(lock);
lock = 0;
</DeepExtract>
super.finalize();
} | firefox | positive | 440,184 |
public List<Integer> spiral(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
if (matrix.length == 0 || matrix[0].length == 0) {
return;
}
if (matrix.length == 1) {
for (int i = 0; i < matrix[0].length; i++) {
result.add(matrix[0][0 + i]);
}
return;
}
if (matrix[0].length == 1) {
for (int i = 0; i < matrix.length; i++) {
result.add(matrix[0 + i][0]);
}
return;
}
for (int i = 0; i < matrix[0].length; i++) {
result.add(matrix[0][0 + i]);
}
for (int i = 1; i < matrix.length - 1; i++) {
result.add(matrix[0 + i][0 + matrix[0].length - 1]);
}
for (int i = matrix[0].length - 1; i >= 0; i--) {
result.add(matrix[0 + matrix.length - 1][0 + i]);
}
for (int i = matrix.length - 2; i >= 1; i--) {
result.add(matrix[0 + i][0]);
}
spiralTraverse(matrix, result, 0 + 1, matrix.length - 2, matrix[0].length - 2);
return result;
} | public List<Integer> spiral(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
<DeepExtract>
if (matrix.length == 0 || matrix[0].length == 0) {
return;
}
if (matrix.length == 1) {
for (int i = 0; i < matrix[0].length; i++) {
result.add(matrix[0][0 + i]);
}
return;
}
if (matrix[0].length == 1) {
for (int i = 0; i < matrix.length; i++) {
result.add(matrix[0 + i][0]);
}
return;
}
for (int i = 0; i < matrix[0].length; i++) {
result.add(matrix[0][0 + i]);
}
for (int i = 1; i < matrix.length - 1; i++) {
result.add(matrix[0 + i][0 + matrix[0].length - 1]);
}
for (int i = matrix[0].length - 1; i >= 0; i--) {
result.add(matrix[0 + matrix.length - 1][0 + i]);
}
for (int i = matrix.length - 2; i >= 1; i--) {
result.add(matrix[0 + i][0]);
}
spiralTraverse(matrix, result, 0 + 1, matrix.length - 2, matrix[0].length - 2);
</DeepExtract>
return result;
} | coding-practice | positive | 440,185 |
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder(parent.getContext());
convertView = holder.view;
} else {
holder = (ViewHolder) convertView.getTag();
}
int color = colors[position];
int alpha = Color.alpha(color);
colorPanelView.setColor(color);
imageView.setImageResource(selectedPosition == position ? R.drawable.cpv_preset_checked : 0);
if (alpha != 255) {
if (alpha <= ColorPickerDialog.ALPHA_THRESHOLD) {
colorPanelView.setBorderColor(color | 0xFF000000);
imageView.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN);
} else {
colorPanelView.setBorderColor(originalBorderColor);
imageView.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
}
} else {
setColorFilter(position);
}
setOnClickListener(position);
return convertView;
} | @Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder(parent.getContext());
convertView = holder.view;
} else {
holder = (ViewHolder) convertView.getTag();
}
<DeepExtract>
int color = colors[position];
int alpha = Color.alpha(color);
colorPanelView.setColor(color);
imageView.setImageResource(selectedPosition == position ? R.drawable.cpv_preset_checked : 0);
if (alpha != 255) {
if (alpha <= ColorPickerDialog.ALPHA_THRESHOLD) {
colorPanelView.setBorderColor(color | 0xFF000000);
imageView.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN);
} else {
colorPanelView.setBorderColor(originalBorderColor);
imageView.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
}
} else {
setColorFilter(position);
}
setOnClickListener(position);
</DeepExtract>
return convertView;
} | MDWechat | positive | 440,186 |
@Override
public TridentChunk loadChunk(ChunkLocation location) {
Preconditions.checkArgument(world != null, "The current world must not be null");
return RegionFile.fromPath(world.name(), location).loadChunkData(world, location);
} | @Override
public TridentChunk loadChunk(ChunkLocation location) {
<DeepExtract>
Preconditions.checkArgument(world != null, "The current world must not be null");
</DeepExtract>
return RegionFile.fromPath(world.name(), location).loadChunkData(world, location);
} | Trident | positive | 440,187 |
public boolean setBitmap(Bitmap bitmap, int index, int token) {
if (token != mGeneration) {
return false;
}
if (!mPending.contains(index)) {
Log.e(TAG, "received unasked bitmap, index = " + index);
return false;
}
if (bitmap == null) {
Log.w(TAG, "receive null bitmap for index = " + index);
return false;
}
mPending.remove(index);
ThumbnailKey key = new ThumbnailKey(mMediaItem.getId(), index);
mCache.put(key, bitmap);
invalidate();
return true;
} | public boolean setBitmap(Bitmap bitmap, int index, int token) {
if (token != mGeneration) {
return false;
}
if (!mPending.contains(index)) {
Log.e(TAG, "received unasked bitmap, index = " + index);
return false;
}
if (bitmap == null) {
Log.w(TAG, "receive null bitmap for index = " + index);
return false;
}
mPending.remove(index);
ThumbnailKey key = new ThumbnailKey(mMediaItem.getId(), index);
<DeepExtract>
mCache.put(key, bitmap);
</DeepExtract>
invalidate();
return true;
} | VideoEditor | positive | 440,188 |
public static RuntimeException sneakyThrow(Throwable throwable) {
Preconditions.checkNotNull(throwable, "throwable");
throw (T) throwable;
return null;
} | public static RuntimeException sneakyThrow(Throwable throwable) {
Preconditions.checkNotNull(throwable, "throwable");
<DeepExtract>
throw (T) throwable;
</DeepExtract>
return null;
} | monasca-common | positive | 440,190 |
@Override
public LanguageDirection getValueFromString(String s) {
return LanguageDirection.parse(s);
} | @Override
public LanguageDirection getValueFromString(String s) {
<DeepExtract>
return LanguageDirection.parse(s);
</DeepExtract>
} | rhapsode | positive | 440,191 |
@Test
public void testManyRandom() {
int MAX_HASH_COUNT = 128;
Set<Integer> hashes = new HashSet<Integer>();
int collisions = 0;
while (randomKeys().hasNext()) {
hashes.clear();
for (int hashIndex : Filter.getHashBuckets(randomKeys().next(), MAX_HASH_COUNT, 1024 * 1024)) {
hashes.add(hashIndex);
}
collisions += (MAX_HASH_COUNT - hashes.size());
}
assertTrue("Collisions: " + collisions, collisions <= 100);
} | @Test
public void testManyRandom() {
<DeepExtract>
int MAX_HASH_COUNT = 128;
Set<Integer> hashes = new HashSet<Integer>();
int collisions = 0;
while (randomKeys().hasNext()) {
hashes.clear();
for (int hashIndex : Filter.getHashBuckets(randomKeys().next(), MAX_HASH_COUNT, 1024 * 1024)) {
hashes.add(hashIndex);
}
collisions += (MAX_HASH_COUNT - hashes.size());
}
assertTrue("Collisions: " + collisions, collisions <= 100);
</DeepExtract>
} | stream-lib | positive | 440,192 |
@Override
public void call(ResponseZerokitError responseZerokitError) {
Arrays.fill(password, (byte) 0);
Zerokit.this.log("onError " + responseZerokitError);
if (ids != null)
for (String id : ids) jsInterfaceByteArrayProvider.remove(id);
subscriber.onError(new ResponseZerokitError().parse(responseZerokitError));
} | @Override
public void call(ResponseZerokitError responseZerokitError) {
Arrays.fill(password, (byte) 0);
<DeepExtract>
Zerokit.this.log("onError " + responseZerokitError);
if (ids != null)
for (String id : ids) jsInterfaceByteArrayProvider.remove(id);
subscriber.onError(new ResponseZerokitError().parse(responseZerokitError));
</DeepExtract>
} | ZeroKit-Android-SDK | positive | 440,193 |
public static void main(String[] args) {
LocalDate anniversary = LocalDate.of(2000, Month.NOVEMBER, 11);
LocalDate today = LocalDate.now();
Period period = Period.between(anniversary, today);
System.out.println("Number of Days Difference: " + period.getDays());
System.out.println("Number of Months Difference: " + period.getMonths());
System.out.println("Number of Years Difference: " + period.getYears());
LocalDate anniversary = LocalDate.of(2000, Month.NOVEMBER, 11);
LocalDate today = LocalDate.now();
long yearsBetween = ChronoUnit.YEARS.between(anniversary, today);
System.out.println("Years between dates: " + yearsBetween);
long daysBetween = ChronoUnit.DAYS.between(anniversary, today);
System.out.println("Days between dates:" + daysBetween);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal2.set(2010, 0, 1, 12, 0);
Date date1 = cal2.getTime();
System.out.println(date1);
long mill = Math.abs(cal1.getTimeInMillis() - date1.getTime());
long hours = TimeUnit.MILLISECONDS.toHours(mill);
Long days = TimeUnit.HOURS.toDays(hours);
String diff = String.format("%d hour(s) %d min(s)", hours, TimeUnit.MILLISECONDS.toMinutes(mill) - TimeUnit.HOURS.toMinutes(hours));
System.out.println(diff);
diff = String.format("%d days", days);
System.out.println(diff);
int weeks = days.intValue() / 7;
diff = String.format("%d weeks", weeks);
System.out.println(diff);
} | public static void main(String[] args) {
LocalDate anniversary = LocalDate.of(2000, Month.NOVEMBER, 11);
LocalDate today = LocalDate.now();
Period period = Period.between(anniversary, today);
System.out.println("Number of Days Difference: " + period.getDays());
System.out.println("Number of Months Difference: " + period.getMonths());
System.out.println("Number of Years Difference: " + period.getYears());
LocalDate anniversary = LocalDate.of(2000, Month.NOVEMBER, 11);
LocalDate today = LocalDate.now();
long yearsBetween = ChronoUnit.YEARS.between(anniversary, today);
System.out.println("Years between dates: " + yearsBetween);
long daysBetween = ChronoUnit.DAYS.between(anniversary, today);
System.out.println("Days between dates:" + daysBetween);
<DeepExtract>
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal2.set(2010, 0, 1, 12, 0);
Date date1 = cal2.getTime();
System.out.println(date1);
long mill = Math.abs(cal1.getTimeInMillis() - date1.getTime());
long hours = TimeUnit.MILLISECONDS.toHours(mill);
Long days = TimeUnit.HOURS.toDays(hours);
String diff = String.format("%d hour(s) %d min(s)", hours, TimeUnit.MILLISECONDS.toMinutes(mill) - TimeUnit.HOURS.toMinutes(hours));
System.out.println(diff);
diff = String.format("%d days", days);
System.out.println(diff);
int weeks = days.intValue() / 7;
diff = String.format("%d weeks", weeks);
System.out.println(diff);
</DeepExtract>
} | java-8-recipes | positive | 440,194 |
@Override
public long expire(String key, Integer second) {
Jedis resource;
if (jedisPool == null) {
jedisPool = new JedisPool(host, port);
}
Jedis resource = jedisPool.getResource();
if (StringUtils.isBlank(password)) {
resource = resource;
} else {
resource.auth(password);
resource = resource;
}
Long expire = resource.expire(key, second);
resource.close();
return expire;
} | @Override
public long expire(String key, Integer second) {
<DeepExtract>
Jedis resource;
if (jedisPool == null) {
jedisPool = new JedisPool(host, port);
}
Jedis resource = jedisPool.getResource();
if (StringUtils.isBlank(password)) {
resource = resource;
} else {
resource.auth(password);
resource = resource;
}
</DeepExtract>
Long expire = resource.expire(key, second);
resource.close();
return expire;
} | ldbz-shop | positive | 440,196 |
public int getCanvasHeight() {
try {
return Math.abs(Integer.parseInt(this.settings.getProperty("canvas.height", Integer.toString(800))));
} catch (final NumberFormatException e) {
return 800;
}
} | public int getCanvasHeight() {
<DeepExtract>
try {
return Math.abs(Integer.parseInt(this.settings.getProperty("canvas.height", Integer.toString(800))));
} catch (final NumberFormatException e) {
return 800;
}
</DeepExtract>
} | Dayflower-Path-Tracer | positive | 440,197 |
public final void dumpLogs(LogLevel logLevel) {
mAccumulatingLog.flushTo(prefixLog(new StandardOutputLogger(logLevel)));
StackTraceElement callerStackTraceElement = getStackTraceElement(3);
StackTraceElement currentStackTraceElement = getStackTraceElement(2);
prefixLog(new StandardOutputLogger(logLevel)).info(currentStackTraceElement.getMethodName() + "() called at " + callerStackTraceElement.getClassName() + "." + callerStackTraceElement.getMethodName() + "(" + callerStackTraceElement.getFileName() + ":" + callerStackTraceElement.getLineNumber() + ")");
setLogger(prefixLog(new StandardOutputLogger(logLevel)));
} | public final void dumpLogs(LogLevel logLevel) {
<DeepExtract>
mAccumulatingLog.flushTo(prefixLog(new StandardOutputLogger(logLevel)));
StackTraceElement callerStackTraceElement = getStackTraceElement(3);
StackTraceElement currentStackTraceElement = getStackTraceElement(2);
prefixLog(new StandardOutputLogger(logLevel)).info(currentStackTraceElement.getMethodName() + "() called at " + callerStackTraceElement.getClassName() + "." + callerStackTraceElement.getMethodName() + "(" + callerStackTraceElement.getFileName() + ":" + callerStackTraceElement.getLineNumber() + ")");
setLogger(prefixLog(new StandardOutputLogger(logLevel)));
</DeepExtract>
} | rivr | positive | 440,198 |
public String getpermisdStr() {
StringBuilder permsidsSb = new StringBuilder();
return getIdArray(permsid);
if (null != permsids && !permsids.isEmpty()) {
boolean first = true;
for (Long id : permsids) {
if (first) {
first = false;
} else {
permsidsSb.append(",");
}
permsidsSb.append(id);
}
}
return permsidsSb.toString();
} | public String getpermisdStr() {
StringBuilder permsidsSb = new StringBuilder();
<DeepExtract>
return getIdArray(permsid);
</DeepExtract>
if (null != permsids && !permsids.isEmpty()) {
boolean first = true;
for (Long id : permsids) {
if (first) {
first = false;
} else {
permsidsSb.append(",");
}
permsidsSb.append(id);
}
}
return permsidsSb.toString();
} | portalSite | positive | 440,199 |
@Test
public void testNameOverwrites() throws Throwable {
assertNotEquals("moo", "jumbo");
final TupleType a = TypeFactory.createTupleTypeWithNames("(bool)", "moo");
assertEquals("moo", a.getElementName(0));
final TupleType b = TypeFactory.create("(bool)");
assertEquals("moo", a.getElementName(0));
assertNull(b.getElementName(0));
final TupleType c = TypeFactory.createTupleTypeWithNames("(bool)", "jumbo");
assertEquals("moo", a.getElementName(0));
assertNull(b.getElementName(0));
assertEquals("jumbo", c.getElementName(0));
assertNotEquals("moo", "jumbo");
final TupleType x = wrap(new String[] { "moo" }, a.get(0));
assertEquals("moo", x.getElementName(0));
final TupleType y = wrap(null, b.get(0));
assertEquals("moo", x.getElementName(0));
assertNull(y.getElementName(0));
final TupleType z = wrap(new String[] { "jumbo" }, c.get(0));
assertEquals("moo", x.getElementName(0));
assertNull(y.getElementName(0));
assertEquals("jumbo", z.getElementName(0));
assertNotEquals("zZz", "Jumb0");
final TupleType a = TypeFactory.createTupleTypeWithNames("(())", "zZz");
assertEquals("zZz", a.getElementName(0));
final TupleType b = TypeFactory.create("(())");
assertEquals("zZz", a.getElementName(0));
assertNull(b.getElementName(0));
final TupleType c = TypeFactory.createTupleTypeWithNames("(())", "Jumb0");
assertEquals("zZz", a.getElementName(0));
assertNull(b.getElementName(0));
assertEquals("Jumb0", c.getElementName(0));
assertNotEquals("zZz", "Jumb0");
final TupleType x = wrap(new String[] { "zZz" }, a.get(0));
assertEquals("zZz", x.getElementName(0));
final TupleType y = wrap(null, b.get(0));
assertEquals("zZz", x.getElementName(0));
assertNull(y.getElementName(0));
final TupleType z = wrap(new String[] { "Jumb0" }, c.get(0));
assertEquals("zZz", x.getElementName(0));
assertNull(y.getElementName(0));
assertEquals("Jumb0", z.getElementName(0));
assertThrown(IllegalArgumentException.class, "expected 2 element names but found 0", () -> TypeFactory.createTupleTypeWithNames("(bool,string)"));
assertThrown(IllegalArgumentException.class, "expected 3 element names but found 2", () -> TypeFactory.createTupleTypeWithNames("(bool,string,int)", "a", "b"));
assertThrown(IllegalArgumentException.class, "expected 2 element names but found 4", () -> TypeFactory.createTupleTypeWithNames("(bool,string)", new String[4]));
TupleType tt = TypeFactory.createTupleTypeWithNames("(bool,string)", "a", "b");
assertThrown(IllegalArgumentException.class, "index out of bounds: -1", () -> tt.getElementName(-1));
assertEquals("a", tt.getElementName(0));
assertEquals("b", tt.getElementName(1));
assertThrown(IllegalArgumentException.class, "index out of bounds: 2", () -> tt.getElementName(2));
} | @Test
public void testNameOverwrites() throws Throwable {
assertNotEquals("moo", "jumbo");
final TupleType a = TypeFactory.createTupleTypeWithNames("(bool)", "moo");
assertEquals("moo", a.getElementName(0));
final TupleType b = TypeFactory.create("(bool)");
assertEquals("moo", a.getElementName(0));
assertNull(b.getElementName(0));
final TupleType c = TypeFactory.createTupleTypeWithNames("(bool)", "jumbo");
assertEquals("moo", a.getElementName(0));
assertNull(b.getElementName(0));
assertEquals("jumbo", c.getElementName(0));
assertNotEquals("moo", "jumbo");
final TupleType x = wrap(new String[] { "moo" }, a.get(0));
assertEquals("moo", x.getElementName(0));
final TupleType y = wrap(null, b.get(0));
assertEquals("moo", x.getElementName(0));
assertNull(y.getElementName(0));
final TupleType z = wrap(new String[] { "jumbo" }, c.get(0));
assertEquals("moo", x.getElementName(0));
assertNull(y.getElementName(0));
assertEquals("jumbo", z.getElementName(0));
<DeepExtract>
assertNotEquals("zZz", "Jumb0");
final TupleType a = TypeFactory.createTupleTypeWithNames("(())", "zZz");
assertEquals("zZz", a.getElementName(0));
final TupleType b = TypeFactory.create("(())");
assertEquals("zZz", a.getElementName(0));
assertNull(b.getElementName(0));
final TupleType c = TypeFactory.createTupleTypeWithNames("(())", "Jumb0");
assertEquals("zZz", a.getElementName(0));
assertNull(b.getElementName(0));
assertEquals("Jumb0", c.getElementName(0));
assertNotEquals("zZz", "Jumb0");
final TupleType x = wrap(new String[] { "zZz" }, a.get(0));
assertEquals("zZz", x.getElementName(0));
final TupleType y = wrap(null, b.get(0));
assertEquals("zZz", x.getElementName(0));
assertNull(y.getElementName(0));
final TupleType z = wrap(new String[] { "Jumb0" }, c.get(0));
assertEquals("zZz", x.getElementName(0));
assertNull(y.getElementName(0));
assertEquals("Jumb0", z.getElementName(0));
</DeepExtract>
assertThrown(IllegalArgumentException.class, "expected 2 element names but found 0", () -> TypeFactory.createTupleTypeWithNames("(bool,string)"));
assertThrown(IllegalArgumentException.class, "expected 3 element names but found 2", () -> TypeFactory.createTupleTypeWithNames("(bool,string,int)", "a", "b"));
assertThrown(IllegalArgumentException.class, "expected 2 element names but found 4", () -> TypeFactory.createTupleTypeWithNames("(bool,string)", new String[4]));
TupleType tt = TypeFactory.createTupleTypeWithNames("(bool,string)", "a", "b");
assertThrown(IllegalArgumentException.class, "index out of bounds: -1", () -> tt.getElementName(-1));
assertEquals("a", tt.getElementName(0));
assertEquals("b", tt.getElementName(1));
assertThrown(IllegalArgumentException.class, "index out of bounds: 2", () -> tt.getElementName(2));
} | headlong | positive | 440,200 |
@Test
public void after_timeout_no_more_interval() {
if (WatchDogEventType.ACTIVE_WINDOW == WatchDogEventType.SUBSEQUENT_EDIT) {
WatchDogEventType.ACTIVE_WINDOW.process(new WatchDogEventType.EditorWithModCount(mockedTextEditor, 0));
} else {
WatchDogEventType.ACTIVE_WINDOW.process(mockedTextEditor);
}
if (WatchDogEventType.USER_ACTIVITY == WatchDogEventType.SUBSEQUENT_EDIT) {
WatchDogEventType.USER_ACTIVITY.process(new WatchDogEventType.EditorWithModCount(mockedTextEditor, 0));
} else {
WatchDogEventType.USER_ACTIVITY.process(mockedTextEditor);
}
Mockito.verify(intervalManager, Mockito.timeout(TIMEOUT_GRACE_PERIOD)).closeInterval(Mockito.isA(IntervalBase.class), Mockito.any(Date.class));
Assert.assertEquals(null, intervalManager.getEditorInterval());
} | @Test
public void after_timeout_no_more_interval() {
if (WatchDogEventType.ACTIVE_WINDOW == WatchDogEventType.SUBSEQUENT_EDIT) {
WatchDogEventType.ACTIVE_WINDOW.process(new WatchDogEventType.EditorWithModCount(mockedTextEditor, 0));
} else {
WatchDogEventType.ACTIVE_WINDOW.process(mockedTextEditor);
}
<DeepExtract>
if (WatchDogEventType.USER_ACTIVITY == WatchDogEventType.SUBSEQUENT_EDIT) {
WatchDogEventType.USER_ACTIVITY.process(new WatchDogEventType.EditorWithModCount(mockedTextEditor, 0));
} else {
WatchDogEventType.USER_ACTIVITY.process(mockedTextEditor);
}
</DeepExtract>
Mockito.verify(intervalManager, Mockito.timeout(TIMEOUT_GRACE_PERIOD)).closeInterval(Mockito.isA(IntervalBase.class), Mockito.any(Date.class));
Assert.assertEquals(null, intervalManager.getEditorInterval());
} | watchdog | positive | 440,203 |
public static String isEnabled(String elementExpr) {
Verify.verify(elementExpr.length == numArgs);
return fragment + '(' + ARG_JOINER.join(elementExpr) + ')';
} | public static String isEnabled(String elementExpr) {
<DeepExtract>
Verify.verify(elementExpr.length == numArgs);
return fragment + '(' + ARG_JOINER.join(elementExpr) + ')';
</DeepExtract>
} | devtools-driver | positive | 440,204 |
@Test
void constructorContext() {
PairNode node = (PairNode) Node.parse("foo: 'bar'", GyroParser::pair);
Node keyNode;
Node keyNode = mock(Node.class);
PairNode node = new PairNode(keyNode, mock(Node.class));
assertThat(node.getKey()).isEqualTo(keyNode);
Node valueNode = node.getValue();
assertThat(keyNode).isInstanceOf(ValueNode.class);
assertThat(((ValueNode) keyNode).getValue()).isEqualTo("foo");
assertThat(valueNode).isInstanceOf(ValueNode.class);
assertThat(((ValueNode) valueNode).getValue()).isEqualTo("bar");
} | @Test
void constructorContext() {
PairNode node = (PairNode) Node.parse("foo: 'bar'", GyroParser::pair);
<DeepExtract>
Node keyNode;
Node keyNode = mock(Node.class);
PairNode node = new PairNode(keyNode, mock(Node.class));
assertThat(node.getKey()).isEqualTo(keyNode);
</DeepExtract>
Node valueNode = node.getValue();
assertThat(keyNode).isInstanceOf(ValueNode.class);
assertThat(((ValueNode) keyNode).getValue()).isEqualTo("foo");
assertThat(valueNode).isInstanceOf(ValueNode.class);
assertThat(((ValueNode) valueNode).getValue()).isEqualTo("bar");
} | gyro | positive | 440,205 |
private Widget createAddButton(String value) {
FlowPanel ret = new FlowPanel();
final TextBox box = new TextBox();
ret.add(box);
groupedListBox1.setValue(value);
groupedListBox2.setValue(value);
Button add = new Button("Add");
add.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
setValue(box.getText());
}
});
ret.add(add);
return ret;
} | private Widget createAddButton(String value) {
FlowPanel ret = new FlowPanel();
final TextBox box = new TextBox();
ret.add(box);
<DeepExtract>
groupedListBox1.setValue(value);
groupedListBox2.setValue(value);
</DeepExtract>
Button add = new Button("Add");
add.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
setValue(box.getText());
}
});
ret.add(add);
return ret;
} | gwt-traction | positive | 440,206 |
@Override
public void captureStartValues(TransitionValues transitionValues) {
if (!(transitionValues.view instanceof TextView)) {
return;
}
final TextView view = (TextView) transitionValues.view;
final float fontSize = view.getTextSize();
transitionValues.values.put(FONT_SIZE, fontSize);
final TextResizeData data = new TextResizeData(view);
transitionValues.values.put(DATA, data);
} | @Override
public void captureStartValues(TransitionValues transitionValues) {
<DeepExtract>
if (!(transitionValues.view instanceof TextView)) {
return;
}
final TextView view = (TextView) transitionValues.view;
final float fontSize = view.getTextSize();
transitionValues.values.put(FONT_SIZE, fontSize);
final TextResizeData data = new TextResizeData(view);
transitionValues.values.put(DATA, data);
</DeepExtract>
} | animation-samples | positive | 440,207 |
@Override
public Single<byte[]> generateTransferAssetTransactionWithMessage(byte[] senderPublicKey, SignumAddress recipient, SignumID assetId, SignumValue quantity, SignumValue amount, SignumValue fee, int deadline, String message) {
return service -> service.generateTransferAssetTransactionWithMessage(senderPublicKey, recipient, assetId, quantity, amount, fee, deadline, message).apply(bestNode.get()).doOnError(throwable -> lastCheck.set(0L));
} | @Override
public Single<byte[]> generateTransferAssetTransactionWithMessage(byte[] senderPublicKey, SignumAddress recipient, SignumID assetId, SignumValue quantity, SignumValue amount, SignumValue fee, int deadline, String message) {
<DeepExtract>
return service -> service.generateTransferAssetTransactionWithMessage(senderPublicKey, recipient, assetId, quantity, amount, fee, deadline, message).apply(bestNode.get()).doOnError(throwable -> lastCheck.set(0L));
</DeepExtract>
} | signumj | positive | 440,209 |
private double[] calculate() {
this.sunrise = calculateMidDay(this.julianDate, this.timePortions[1]) - calculateSunDuration(0.8333, this.latitude, this.julianDate, this.timePortions[1]) / 2;
this.sunset = calculateMidDay(this.julianDate, this.timePortions[5]) + calculateSunDuration(0.8333, this.latitude, this.julianDate, this.timePortions[4]) / 2;
double equationOfTime = calculateEquationOfTime(this.julianDate, this.timePortions[2]);
this.thuhr = fixHours(12 - equationOfTime);
int m = 0;
switch(this.mazhab) {
case PTC_MAZHAB_SHAFEI:
m = 0;
break;
case PTC_MAZHAB_HANAFI:
m = 1;
break;
}
double d = calculateSunDeclination(this.julianDate, this.timePortions[3]);
double g = -PrayerTimesMath.dACot(m + 1 + PrayerTimesMath.dTan(Math.abs(this.latitude - d)));
double s = calculateSunDeclination(this.julianDate, this.timePortions[3]);
double z = calculateMidDay(this.julianDate, this.timePortions[3]);
double v = ((double) (1 / 15.0)) * PrayerTimesMath.dACos((-PrayerTimesMath.dSin(g) - PrayerTimesMath.dSin(s) * PrayerTimesMath.dSin(this.latitude)) / (PrayerTimesMath.dCos(s) * PrayerTimesMath.dCos(this.latitude)));
this.asr = z + (g > 90 ? -v : v);
this.maghreb = this.sunset;
if (this.latitude <= 50) {
switch(this.way) {
case PTC_WAY_EGYPT:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(19.5, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = calculateMidDay(this.julianDate, this.timePortions[6]) + calculateSunDuration(17.5, this.latitude, this.julianDate, this.timePortions[6]) / 2;
break;
case PTC_WAY_KARACHI:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(18, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = calculateMidDay(this.julianDate, this.timePortions[6]) + calculateSunDuration(18, this.latitude, this.julianDate, this.timePortions[6]) / 2;
break;
case PTC_WAY_ISNA:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(15, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = calculateMidDay(this.julianDate, this.timePortions[6]) + calculateSunDuration(15, this.latitude, this.julianDate, this.timePortions[6]) / 2;
break;
case PTC_WAY_UMQURA:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(18.5, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = maghreb + 1.5;
break;
case PTC_WAY_MWL:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(18, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = calculateMidDay(this.julianDate, this.timePortions[6]) + calculateSunDuration(17, this.latitude, this.julianDate, this.timePortions[6]) / 2;
break;
}
} else {
double p = 24 - (this.sunset - this.sunrise);
this.fajr = this.sunrise - 2 * p / 7.0 - 1 / 6.0;
this.isha = this.sunset + 2 * p / 7.0 - 1 / 15.0;
}
double[] prayers = new double[6];
prayers[0] = this.fajr;
prayers[1] = this.sunrise;
prayers[2] = this.thuhr;
prayers[3] = this.asr;
prayers[4] = this.maghreb;
prayers[5] = this.isha;
return prayers;
} | private double[] calculate() {
this.sunrise = calculateMidDay(this.julianDate, this.timePortions[1]) - calculateSunDuration(0.8333, this.latitude, this.julianDate, this.timePortions[1]) / 2;
this.sunset = calculateMidDay(this.julianDate, this.timePortions[5]) + calculateSunDuration(0.8333, this.latitude, this.julianDate, this.timePortions[4]) / 2;
double equationOfTime = calculateEquationOfTime(this.julianDate, this.timePortions[2]);
this.thuhr = fixHours(12 - equationOfTime);
int m = 0;
switch(this.mazhab) {
case PTC_MAZHAB_SHAFEI:
m = 0;
break;
case PTC_MAZHAB_HANAFI:
m = 1;
break;
}
double d = calculateSunDeclination(this.julianDate, this.timePortions[3]);
double g = -PrayerTimesMath.dACot(m + 1 + PrayerTimesMath.dTan(Math.abs(this.latitude - d)));
double s = calculateSunDeclination(this.julianDate, this.timePortions[3]);
double z = calculateMidDay(this.julianDate, this.timePortions[3]);
double v = ((double) (1 / 15.0)) * PrayerTimesMath.dACos((-PrayerTimesMath.dSin(g) - PrayerTimesMath.dSin(s) * PrayerTimesMath.dSin(this.latitude)) / (PrayerTimesMath.dCos(s) * PrayerTimesMath.dCos(this.latitude)));
this.asr = z + (g > 90 ? -v : v);
this.maghreb = this.sunset;
<DeepExtract>
if (this.latitude <= 50) {
switch(this.way) {
case PTC_WAY_EGYPT:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(19.5, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = calculateMidDay(this.julianDate, this.timePortions[6]) + calculateSunDuration(17.5, this.latitude, this.julianDate, this.timePortions[6]) / 2;
break;
case PTC_WAY_KARACHI:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(18, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = calculateMidDay(this.julianDate, this.timePortions[6]) + calculateSunDuration(18, this.latitude, this.julianDate, this.timePortions[6]) / 2;
break;
case PTC_WAY_ISNA:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(15, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = calculateMidDay(this.julianDate, this.timePortions[6]) + calculateSunDuration(15, this.latitude, this.julianDate, this.timePortions[6]) / 2;
break;
case PTC_WAY_UMQURA:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(18.5, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = maghreb + 1.5;
break;
case PTC_WAY_MWL:
this.fajr = calculateMidDay(this.julianDate, this.timePortions[0]) - calculateSunDuration(18, this.latitude, this.julianDate, this.timePortions[0]) / 2;
this.isha = calculateMidDay(this.julianDate, this.timePortions[6]) + calculateSunDuration(17, this.latitude, this.julianDate, this.timePortions[6]) / 2;
break;
}
} else {
double p = 24 - (this.sunset - this.sunrise);
this.fajr = this.sunrise - 2 * p / 7.0 - 1 / 6.0;
this.isha = this.sunset + 2 * p / 7.0 - 1 / 15.0;
}
</DeepExtract>
double[] prayers = new double[6];
prayers[0] = this.fajr;
prayers[1] = this.sunrise;
prayers[2] = this.thuhr;
prayers[3] = this.asr;
prayers[4] = this.maghreb;
prayers[5] = this.isha;
return prayers;
} | MuslimMateAndroid | positive | 440,210 |
@Before
public void generateJobName() {
sourceName = getRandomCrawlerName();
if (!testKeepData) {
try (WPSearchClient client = createClient()) {
List<String> sourceIds = client.getCustomSourcesByName(sourceName);
for (String sourceId : sourceIds) {
client.removeCustomSource(sourceId);
}
}
}
sourceId = null;
} | @Before
public void generateJobName() {
sourceName = getRandomCrawlerName();
<DeepExtract>
if (!testKeepData) {
try (WPSearchClient client = createClient()) {
List<String> sourceIds = client.getCustomSourcesByName(sourceName);
for (String sourceId : sourceIds) {
client.removeCustomSource(sourceId);
}
}
}
</DeepExtract>
sourceId = null;
} | fscrawler | positive | 440,214 |
public SparseMatrixLil neg() {
SparseMatrixLil result = new SparseMatrixLil(rows, cols);
if (size > this.capacity) {
int[] newrows = new int[size];
int[] newcols = new int[size];
double[] newvalues = new double[size];
for (int i = 0; i < this.size; i++) {
newrows[i] = rowIdx[i];
newcols[i] = colIdx[i];
newvalues[i] = values[i];
}
this.capacity = size;
this.rowIdx = newrows;
this.colIdx = newcols;
this.values = newvalues;
}
int count = size;
for (int i = 0; i < count; i++) {
int row = rowIdx[i];
int col = colIdx[i];
double value = values[i];
result.append(row, col, -value);
}
return result;
} | public SparseMatrixLil neg() {
SparseMatrixLil result = new SparseMatrixLil(rows, cols);
<DeepExtract>
if (size > this.capacity) {
int[] newrows = new int[size];
int[] newcols = new int[size];
double[] newvalues = new double[size];
for (int i = 0; i < this.size; i++) {
newrows[i] = rowIdx[i];
newcols[i] = colIdx[i];
newvalues[i] = values[i];
}
this.capacity = size;
this.rowIdx = newrows;
this.colIdx = newcols;
this.values = newvalues;
}
</DeepExtract>
int count = size;
for (int i = 0; i < count; i++) {
int row = rowIdx[i];
int col = colIdx[i];
double value = values[i];
result.append(row, col, -value);
}
return result;
} | swell | positive | 440,215 |
@Override
public boolean matches(final Object item) {
boolean matches = true;
final DecisionTreeRuleSet ruleSet = (DecisionTreeRuleSet) item;
matches &= ruleSet.equals(otherRuleSet);
matches &= ruleSet.getDriverNames().equals(otherRuleSet.getDriverNames());
boolean matches = true;
for (final InputValueType type : InputValueType.values()) {
final List<InputDriver> ruleSetDriversForType = ruleSet.getDriversByType(type);
final List<InputDriver> otherRuleSetDriversForType = otherRuleSet.getDriversByType(type);
for (final InputDriver driver : ruleSetDriversForType) {
final int index = otherRuleSetDriversForType.indexOf(driver);
if (index != -1) {
final InputDriver otherDriver = otherRuleSetDriversForType.get(index);
if (InputValueType.VALUE_GROUP.equals(driver.getType())) {
final List<InputDriver> subDrivers = Arrays.asList(((GroupDriver) driver).getSubDrivers(true));
final List<InputDriver> otherSubDrivers = Arrays.asList(((GroupDriver) otherDriver).getSubDrivers(true));
matches &= subDrivers.equals(otherSubDrivers);
}
} else {
matches = false;
break;
}
}
}
return matches;
if (matches) {
for (final DecisionTreeRule otherRule : otherRuleSet.getRules().values()) {
final DecisionTreeRule rule = ruleSet.getRules().get(otherRule.getRuleIdentifier());
matches &= DecisionTreeRuleMatcher.isSame(otherRule).matches(rule);
if (!matches) {
this.errorString = "Rule " + rule + " does not match " + otherRule;
break;
}
}
}
return matches;
} | @Override
public boolean matches(final Object item) {
boolean matches = true;
final DecisionTreeRuleSet ruleSet = (DecisionTreeRuleSet) item;
matches &= ruleSet.equals(otherRuleSet);
matches &= ruleSet.getDriverNames().equals(otherRuleSet.getDriverNames());
<DeepExtract>
boolean matches = true;
for (final InputValueType type : InputValueType.values()) {
final List<InputDriver> ruleSetDriversForType = ruleSet.getDriversByType(type);
final List<InputDriver> otherRuleSetDriversForType = otherRuleSet.getDriversByType(type);
for (final InputDriver driver : ruleSetDriversForType) {
final int index = otherRuleSetDriversForType.indexOf(driver);
if (index != -1) {
final InputDriver otherDriver = otherRuleSetDriversForType.get(index);
if (InputValueType.VALUE_GROUP.equals(driver.getType())) {
final List<InputDriver> subDrivers = Arrays.asList(((GroupDriver) driver).getSubDrivers(true));
final List<InputDriver> otherSubDrivers = Arrays.asList(((GroupDriver) otherDriver).getSubDrivers(true));
matches &= subDrivers.equals(otherSubDrivers);
}
} else {
matches = false;
break;
}
}
}
return matches;
</DeepExtract>
if (matches) {
for (final DecisionTreeRule otherRule : otherRuleSet.getRules().values()) {
final DecisionTreeRule rule = ruleSet.getRules().get(otherRule.getRuleIdentifier());
matches &= DecisionTreeRuleMatcher.isSame(otherRule).matches(rule);
if (!matches) {
this.errorString = "Rule " + rule + " does not match " + otherRule;
break;
}
}
}
return matches;
} | swblocks-decisiontree | positive | 440,216 |
private void writeDictionary(ZipOutputStream zipOut) throws IOException {
File file = new File(basename + "-dictionary.json");
if (zipOut != null) {
String subdir = null != null ? null.getName() + "/" : "";
log.info("Adding file " + subdir + file.getName());
} else {
log.info("Creating file " + file.getAbsolutePath());
}
String json;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
try {
json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(dictionary);
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
json = "";
}
if (zipOut != null) {
zipOut.putNextEntry(new ZipEntry(file.toString()));
zipOut.write(json.getBytes());
} else {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")))) {
writer.write(json);
}
}
} | private void writeDictionary(ZipOutputStream zipOut) throws IOException {
File file = new File(basename + "-dictionary.json");
if (zipOut != null) {
String subdir = null != null ? null.getName() + "/" : "";
log.info("Adding file " + subdir + file.getName());
} else {
log.info("Creating file " + file.getAbsolutePath());
}
<DeepExtract>
String json;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
try {
json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(dictionary);
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
json = "";
}
</DeepExtract>
if (zipOut != null) {
zipOut.putNextEntry(new ZipEntry(file.toString()));
zipOut.write(json.getBytes());
} else {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")))) {
writer.write(json);
}
}
} | Merlin | positive | 440,217 |
@Test
public void safeMaker_givenEncodingToken_encodesAsExpected() {
String iriSafeValue = makeSafe("100%", true);
assertEquals("100%25", iriSafeValue);
String iriSafeValue = makeSafe("1,2", false);
assertEquals("1%2c2", iriSafeValue);
} | @Test
public void safeMaker_givenEncodingToken_encodesAsExpected() {
String iriSafeValue = makeSafe("100%", true);
assertEquals("100%25", iriSafeValue);
<DeepExtract>
String iriSafeValue = makeSafe("1,2", false);
assertEquals("1%2c2", iriSafeValue);
</DeepExtract>
} | carml | positive | 440,220 |
@PostMapping("create")
public BaseMessage create(@RequestBody @Valid CreateOrderCommand command) {
log.info("Request to create order {}", command);
T handler = createOps.get(command.getClientName());
if (null == handler) {
throw new IllegalStateException("No handler");
}
return (handler, cmd) -> {
Optional<OrderCreatedDto> res = handler.create(cmd.getOrderId(), TradingCurrency.fromCode(cmd.getCurrencyFrom()), TradingCurrency.fromCode(cmd.getCurrencyTo()), cmd.getAmount(), cmd.getPrice());
log.info("Created {} for {} of {}", res, cmd.getId(), cmd.getClientName());
return res.map(id -> CreateOrderResponse.builder().clientName(cmd.getClientName()).id(cmd.getId()).requestOrderId(cmd.getId()).orderId(id.getAssignedId()).isExecuted(id.isExecuted()).build()).orElse(null);
}.apply(handler, command);
} | @PostMapping("create")
public BaseMessage create(@RequestBody @Valid CreateOrderCommand command) {
log.info("Request to create order {}", command);
<DeepExtract>
T handler = createOps.get(command.getClientName());
if (null == handler) {
throw new IllegalStateException("No handler");
}
return (handler, cmd) -> {
Optional<OrderCreatedDto> res = handler.create(cmd.getOrderId(), TradingCurrency.fromCode(cmd.getCurrencyFrom()), TradingCurrency.fromCode(cmd.getCurrencyTo()), cmd.getAmount(), cmd.getPrice());
log.info("Created {} for {} of {}", res, cmd.getId(), cmd.getClientName());
return res.map(id -> CreateOrderResponse.builder().clientName(cmd.getClientName()).id(cmd.getId()).requestOrderId(cmd.getId()).orderId(id.getAssignedId()).isExecuted(id.isExecuted()).build()).orElse(null);
}.apply(handler, command);
</DeepExtract>
} | GTC-all-repo | positive | 440,221 |
static void configure(EnvVars vars, ClientConfiguration config) {
if (Jenkins.getInstance() != null) {
hudson.ProxyConfiguration proxyConfiguration = Jenkins.getInstance().proxy;
if (proxyConfiguration != null) {
config.setProxyHost(proxyConfiguration.name);
config.setProxyPort(proxyConfiguration.port);
config.setProxyUsername(proxyConfiguration.getUserName());
config.setProxyPassword(proxyConfiguration.getPassword());
if (proxyConfiguration.noProxyHost != null) {
String[] noProxyParts = proxyConfiguration.noProxyHost.split("[ \t\n,|]+");
config.setNonProxyHosts(Joiner.on('|').join(noProxyParts));
}
}
}
if (config.getProtocol() == Protocol.HTTP) {
configureHTTP(vars, config);
} else {
configureHTTPS(vars, config);
}
String noProxy = vars.get(NO_PROXY, vars.get(NO_PROXY_LC));
if (noProxy != null) {
config.setNonProxyHosts(Joiner.on('|').join(noProxy.split(",")));
}
} | static void configure(EnvVars vars, ClientConfiguration config) {
if (Jenkins.getInstance() != null) {
hudson.ProxyConfiguration proxyConfiguration = Jenkins.getInstance().proxy;
if (proxyConfiguration != null) {
config.setProxyHost(proxyConfiguration.name);
config.setProxyPort(proxyConfiguration.port);
config.setProxyUsername(proxyConfiguration.getUserName());
config.setProxyPassword(proxyConfiguration.getPassword());
if (proxyConfiguration.noProxyHost != null) {
String[] noProxyParts = proxyConfiguration.noProxyHost.split("[ \t\n,|]+");
config.setNonProxyHosts(Joiner.on('|').join(noProxyParts));
}
}
}
if (config.getProtocol() == Protocol.HTTP) {
configureHTTP(vars, config);
} else {
configureHTTPS(vars, config);
}
<DeepExtract>
String noProxy = vars.get(NO_PROXY, vars.get(NO_PROXY_LC));
if (noProxy != null) {
config.setNonProxyHosts(Joiner.on('|').join(noProxy.split(",")));
}
</DeepExtract>
} | pipeline-aws-plugin | positive | 440,223 |
<T> void assertEventuallyEquals(final T expected, final Supplier<T> action, final String msg, final int retries, final long timeoutMs) {
int counter = 0;
boolean hasError = true;
AssertionFailedError exception = null;
while (counter < retries && hasError) {
try {
counter++;
() -> assertEquals(expected, action.get(), msg).run();
hasError = false;
} catch (AssertionFailedError e) {
LOGGER.debug("Failed assertion on attempt: {}", counter);
exception = e;
try {
Thread.sleep(timeoutMs);
} catch (InterruptedException interruptedException) {
}
}
}
if (hasError && exception != null) {
throw exception;
}
} | <T> void assertEventuallyEquals(final T expected, final Supplier<T> action, final String msg, final int retries, final long timeoutMs) {
<DeepExtract>
int counter = 0;
boolean hasError = true;
AssertionFailedError exception = null;
while (counter < retries && hasError) {
try {
counter++;
() -> assertEquals(expected, action.get(), msg).run();
hasError = false;
} catch (AssertionFailedError e) {
LOGGER.debug("Failed assertion on attempt: {}", counter);
exception = e;
try {
Thread.sleep(timeoutMs);
} catch (InterruptedException interruptedException) {
}
}
}
if (hasError && exception != null) {
throw exception;
}
</DeepExtract>
} | mongo-kafka | positive | 440,226 |
static void printFileRequest(LoggingInterceptor.Builder builder, Request request) {
String tag = builder.getTag(true);
if (builder.getLogger() == null)
I.log(builder.getType(), tag, REQUEST_UP_LINE);
for (String line : new String[] { URL_TAG + request.url() }) {
int lineLength = line.length();
int MAX_LONG_SIZE = false ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
if (builder.getLogger() == null) {
I.log(builder.getType(), tag, DEFAULT_LINE + line.substring(start, end));
} else {
builder.getLogger().log(builder.getType(), tag, line.substring(start, end));
}
}
}
for (String line : getRequest(request, builder.getLevel())) {
int lineLength = line.length();
int MAX_LONG_SIZE = true ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
if (builder.getLogger() == null) {
I.log(builder.getType(), tag, DEFAULT_LINE + line.substring(start, end));
} else {
builder.getLogger().log(builder.getType(), tag, line.substring(start, end));
}
}
}
if (request.body() instanceof FormBody) {
StringBuilder formBody = new StringBuilder();
FormBody body = (FormBody) request.body();
for (int i = 0; i < body.size(); i++) {
formBody.append(body.encodedName(i) + "=" + body.encodedValue(i) + "&");
}
formBody.delete(formBody.length() - 1, formBody.length());
logLines(builder.getType(), tag, new String[] { formBody.toString() }, builder.getLogger(), true);
}
if (builder.getLevel() == Level.BASIC || builder.getLevel() == Level.BODY) {
logLines(builder.getType(), tag, OMITTED_REQUEST, builder.getLogger(), true);
}
if (builder.getLogger() == null)
I.log(builder.getType(), tag, END_LINE);
} | static void printFileRequest(LoggingInterceptor.Builder builder, Request request) {
String tag = builder.getTag(true);
if (builder.getLogger() == null)
I.log(builder.getType(), tag, REQUEST_UP_LINE);
for (String line : new String[] { URL_TAG + request.url() }) {
int lineLength = line.length();
int MAX_LONG_SIZE = false ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
if (builder.getLogger() == null) {
I.log(builder.getType(), tag, DEFAULT_LINE + line.substring(start, end));
} else {
builder.getLogger().log(builder.getType(), tag, line.substring(start, end));
}
}
}
<DeepExtract>
for (String line : getRequest(request, builder.getLevel())) {
int lineLength = line.length();
int MAX_LONG_SIZE = true ? 110 : lineLength;
for (int i = 0; i <= lineLength / MAX_LONG_SIZE; i++) {
int start = i * MAX_LONG_SIZE;
int end = (i + 1) * MAX_LONG_SIZE;
end = end > line.length() ? line.length() : end;
if (builder.getLogger() == null) {
I.log(builder.getType(), tag, DEFAULT_LINE + line.substring(start, end));
} else {
builder.getLogger().log(builder.getType(), tag, line.substring(start, end));
}
}
}
</DeepExtract>
if (request.body() instanceof FormBody) {
StringBuilder formBody = new StringBuilder();
FormBody body = (FormBody) request.body();
for (int i = 0; i < body.size(); i++) {
formBody.append(body.encodedName(i) + "=" + body.encodedValue(i) + "&");
}
formBody.delete(formBody.length() - 1, formBody.length());
logLines(builder.getType(), tag, new String[] { formBody.toString() }, builder.getLogger(), true);
}
if (builder.getLevel() == Level.BASIC || builder.getLevel() == Level.BODY) {
logLines(builder.getType(), tag, OMITTED_REQUEST, builder.getLogger(), true);
}
if (builder.getLogger() == null)
I.log(builder.getType(), tag, END_LINE);
} | RxCore | positive | 440,229 |
@Override
protected void addPropertyInternal(String key, Object value) {
TypedOption<?, ?> option = OptionSpace.get(key);
if (option == null) {
LOG.warn("The config option '{}' is redundant, " + "please ensure it has been registered", key);
} else {
value = this.validateOption(key, value);
}
if (this.containsKey(key) && value instanceof List) {
for (Object item : (List<Object>) value) {
super.addPropertyDirect(key, item);
}
} else {
super.addPropertyDirect(key, value);
}
} | @Override
protected void addPropertyInternal(String key, Object value) {
<DeepExtract>
TypedOption<?, ?> option = OptionSpace.get(key);
if (option == null) {
LOG.warn("The config option '{}' is redundant, " + "please ensure it has been registered", key);
} else {
value = this.validateOption(key, value);
}
if (this.containsKey(key) && value instanceof List) {
for (Object item : (List<Object>) value) {
super.addPropertyDirect(key, item);
}
} else {
super.addPropertyDirect(key, value);
}
</DeepExtract>
} | hugegraph-common | positive | 440,231 |
void doMove() {
int m = JOptionPane.QUESTION_MESSAGE;
int y = JOptionPane.YES_NO_OPTION;
JOptionPane pane = new JOptionPane(null, m, y);
JDialog dialog = pane.createDialog(pan, "Rename or Move");
pane.setWantsInput(true);
File f = new File(path, file.getName());
String cmd = pan.move.getText();
String msg = cmd + "\n" + file + " to";
pane.setMessage(msg);
pane.setInitialSelectionValue(f.toString());
Scaler.scaleComp(pane);
dialog.pack();
dialog.setVisible(true);
saveProps();
super.dispose();
if (exit)
System.exit(0);
Object res = pane.getValue();
int k = (res instanceof Integer) ? ((Integer) res).intValue() : -1;
if (k != JOptionPane.YES_OPTION)
return;
File g = new File(pane.getInputValue().toString());
if (file.equals(g))
return;
if (!file.renameTo(g))
throw new RuntimeException(cmd + " failed");
System.out.println(cmd + " " + file + " to " + g);
file = g;
pan.setFileText(g);
makeRoot();
makeList(".");
if (g.getParentFile().equals(dir))
display(g.getName());
} | void doMove() {
int m = JOptionPane.QUESTION_MESSAGE;
int y = JOptionPane.YES_NO_OPTION;
JOptionPane pane = new JOptionPane(null, m, y);
JDialog dialog = pane.createDialog(pan, "Rename or Move");
pane.setWantsInput(true);
File f = new File(path, file.getName());
String cmd = pan.move.getText();
String msg = cmd + "\n" + file + " to";
pane.setMessage(msg);
pane.setInitialSelectionValue(f.toString());
Scaler.scaleComp(pane);
dialog.pack();
dialog.setVisible(true);
saveProps();
super.dispose();
if (exit)
System.exit(0);
Object res = pane.getValue();
int k = (res instanceof Integer) ? ((Integer) res).intValue() : -1;
if (k != JOptionPane.YES_OPTION)
return;
File g = new File(pane.getInputValue().toString());
if (file.equals(g))
return;
if (!file.renameTo(g))
throw new RuntimeException(cmd + " failed");
System.out.println(cmd + " " + file + " to " + g);
file = g;
pan.setFileText(g);
<DeepExtract>
makeRoot();
makeList(".");
if (g.getParentFile().equals(dir))
display(g.getName());
</DeepExtract>
} | SmallSimpleSafe | positive | 440,232 |
@Click(R.id.btn_option_2)
public void onOption2Click() {
for (int i = 0; i < 3; i++) {
Option option = mQuestion.getOptionList().get(i);
Button button = null;
switch(i) {
case 0:
button = mOption1Button;
break;
case 1:
button = mOption2Button;
break;
case 2:
button = mOption3Button;
break;
}
if (button != null) {
if (option.isCorrect()) {
button.setBackgroundColor(Color.GREEN);
} else {
button.setBackgroundColor(Color.RED);
}
}
}
} | @Click(R.id.btn_option_2)
public void onOption2Click() {
<DeepExtract>
for (int i = 0; i < 3; i++) {
Option option = mQuestion.getOptionList().get(i);
Button button = null;
switch(i) {
case 0:
button = mOption1Button;
break;
case 1:
button = mOption2Button;
break;
case 2:
button = mOption3Button;
break;
}
if (button != null) {
if (option.isCorrect()) {
button.setBackgroundColor(Color.GREEN);
} else {
button.setBackgroundColor(Color.RED);
}
}
}
</DeepExtract>
} | android-mvp-architecture | positive | 440,233 |
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Context context = getContext();
FrameLayout headViewLayout = new FrameLayout(context);
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
layoutParams.gravity = Gravity.TOP;
headViewLayout.setLayoutParams(layoutParams);
mHeadLayout = headViewLayout;
this.addView(mHeadLayout);
mChildView = getChildAt(0);
if (mChildView == null) {
return;
}
this.mWaveHeight = Util.dip2px(context, waveHeight);
this.mHeadHeight = Util.dip2px(context, headHeight);
materialHeadView = new MaterialHeadView(context);
this.waveColor = isShowWave ? waveColor : Color.WHITE;
materialHeadView.showProgressArrow(showArrow);
materialHeadView.setProgressSize(progressSize);
this.colorSchemeColors = colorSchemeColors;
materialHeadView.setProgressStokeWidth(PROGRESS_STOKE_WIDTH);
materialHeadView.setTextType(textType);
materialHeadView.setProgressTextColor(progressTextColor);
this.progressValue = progressValue;
materialHeadView.setProgressValue(progressValue);
materialHeadView.setProgressValueMax(progressMax);
materialHeadView.setIsProgressBg(showProgressBg);
materialHeadView.setProgressBg(progressBg);
post(new Runnable() {
@Override
public void run() {
mHeadLayout.addView(materialHeadView);
}
});
materialFoodView = new MaterialFoodView(context);
LayoutParams layoutParams2 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Util.dip2px(context, hIGHER_HEAD_HEIGHT));
layoutParams2.gravity = Gravity.BOTTOM;
materialFoodView.setLayoutParams(layoutParams2);
materialFoodView.showProgressArrow(showArrow);
materialFoodView.setProgressSize(progressSize);
this.colorSchemeColors = colorSchemeColors;
materialFoodView.setProgressStokeWidth(PROGRESS_STOKE_WIDTH);
materialFoodView.setTextType(textType);
this.progressValue = progressValue;
materialHeadView.setProgressValue(progressValue);
materialFoodView.setProgressValueMax(progressMax);
materialFoodView.setIsProgressBg(showProgressBg);
materialFoodView.setProgressBg(progressBg);
materialFoodView.setVisibility(View.GONE);
this.addView(materialFoodView);
} | @Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Context context = getContext();
FrameLayout headViewLayout = new FrameLayout(context);
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
layoutParams.gravity = Gravity.TOP;
headViewLayout.setLayoutParams(layoutParams);
mHeadLayout = headViewLayout;
this.addView(mHeadLayout);
mChildView = getChildAt(0);
if (mChildView == null) {
return;
}
this.mWaveHeight = Util.dip2px(context, waveHeight);
this.mHeadHeight = Util.dip2px(context, headHeight);
materialHeadView = new MaterialHeadView(context);
this.waveColor = isShowWave ? waveColor : Color.WHITE;
materialHeadView.showProgressArrow(showArrow);
materialHeadView.setProgressSize(progressSize);
this.colorSchemeColors = colorSchemeColors;
materialHeadView.setProgressStokeWidth(PROGRESS_STOKE_WIDTH);
materialHeadView.setTextType(textType);
materialHeadView.setProgressTextColor(progressTextColor);
this.progressValue = progressValue;
materialHeadView.setProgressValue(progressValue);
materialHeadView.setProgressValueMax(progressMax);
materialHeadView.setIsProgressBg(showProgressBg);
materialHeadView.setProgressBg(progressBg);
post(new Runnable() {
@Override
public void run() {
mHeadLayout.addView(materialHeadView);
}
});
materialFoodView = new MaterialFoodView(context);
LayoutParams layoutParams2 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Util.dip2px(context, hIGHER_HEAD_HEIGHT));
layoutParams2.gravity = Gravity.BOTTOM;
materialFoodView.setLayoutParams(layoutParams2);
materialFoodView.showProgressArrow(showArrow);
materialFoodView.setProgressSize(progressSize);
this.colorSchemeColors = colorSchemeColors;
materialFoodView.setProgressStokeWidth(PROGRESS_STOKE_WIDTH);
materialFoodView.setTextType(textType);
this.progressValue = progressValue;
materialHeadView.setProgressValue(progressValue);
materialFoodView.setProgressValueMax(progressMax);
materialFoodView.setIsProgressBg(showProgressBg);
materialFoodView.setProgressBg(progressBg);
materialFoodView.setVisibility(View.GONE);
<DeepExtract>
this.addView(materialFoodView);
</DeepExtract>
} | MousePaint | positive | 440,235 |
public static List<SpawnEntry> parse(InputSource is) throws Exception {
SpawnConfigParser parser = new SpawnConfigParser();
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(parser);
xmlReader.parse(is);
return result;
} | public static List<SpawnEntry> parse(InputSource is) throws Exception {
SpawnConfigParser parser = new SpawnConfigParser();
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(parser);
xmlReader.parse(is);
<DeepExtract>
return result;
</DeepExtract>
} | EnderZoo | positive | 440,236 |
@Override
public void stop() {
super.stop();
insertConsumer = null;
if (dataSource != null) {
try {
if (!dataSource.isClosed()) {
dataSource.close();
}
dataSource = null;
} catch (Exception e) {
addError("Exception closing datasource", e);
}
}
if (executorService == null || executorService.isTerminated()) {
return;
}
try {
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService = null;
} catch (InterruptedException e) {
}
initialized.set(false);
} | @Override
public void stop() {
super.stop();
insertConsumer = null;
if (dataSource != null) {
try {
if (!dataSource.isClosed()) {
dataSource.close();
}
dataSource = null;
} catch (Exception e) {
addError("Exception closing datasource", e);
}
}
<DeepExtract>
if (executorService == null || executorService.isTerminated()) {
return;
}
try {
executorService.awaitTermination(1, TimeUnit.SECONDS);
executorService = null;
} catch (InterruptedException e) {
}
</DeepExtract>
initialized.set(false);
} | terse-logback | positive | 440,237 |
@Override
public NBTTagCompound getUpdateTag() {
new NBTTagCompound().setInteger("timeout", timeout);
new NBTTagCompound().setByte("portalSide", portalSide == null ? 127 : (byte) portalSide.ordinal());
new NBTTagCompound().setLong("pos", other.getPos().toLong());
new NBTTagCompound().setInteger("dim", other.getDimension());
new NBTTagCompound().setByte("side", (byte) other.getSide().ordinal());
NBTTagList list = new NBTTagList();
for (UUID uuid : blackListed) {
NBTTagCompound tc = new NBTTagCompound();
tc.setLong("m", uuid.getMostSignificantBits());
tc.setLong("l", uuid.getLeastSignificantBits());
list.appendTag(tc);
}
new NBTTagCompound().setTag("bl", list);
return super.writeToNBT(new NBTTagCompound());
} | @Override
public NBTTagCompound getUpdateTag() {
<DeepExtract>
new NBTTagCompound().setInteger("timeout", timeout);
new NBTTagCompound().setByte("portalSide", portalSide == null ? 127 : (byte) portalSide.ordinal());
new NBTTagCompound().setLong("pos", other.getPos().toLong());
new NBTTagCompound().setInteger("dim", other.getDimension());
new NBTTagCompound().setByte("side", (byte) other.getSide().ordinal());
NBTTagList list = new NBTTagList();
for (UUID uuid : blackListed) {
NBTTagCompound tc = new NBTTagCompound();
tc.setLong("m", uuid.getMostSignificantBits());
tc.setLong("l", uuid.getLeastSignificantBits());
list.appendTag(tc);
}
new NBTTagCompound().setTag("bl", list);
return super.writeToNBT(new NBTTagCompound());
</DeepExtract>
} | MeeCreeps | positive | 440,238 |
public Criteria andOBorrowTimeNotBetween(String value1, String value2) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "oBorrowTime" + " cannot be null");
}
criteria.add(new Criterion("o_borrow_time not between", value1, value2));
return (Criteria) this;
} | public Criteria andOBorrowTimeNotBetween(String value1, String value2) {
<DeepExtract>
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + "oBorrowTime" + " cannot be null");
}
criteria.add(new Criterion("o_borrow_time not between", value1, value2));
</DeepExtract>
return (Criteria) this;
} | webike | positive | 440,239 |
public static void insertDocument(String collection, Document doc) throws CodecConfigurationException {
if (client == null) {
client = new MongoClient(LGProperties.get("mongo.hostname"), 27017);
db = client.getDatabase("lemongrenade");
jobs = db.getCollection("jobs");
tasks = db.getCollection("tasks");
dbValues = db.getCollection("dbValues");
}
MongoCollection<Document> coll = db.getCollection(collection);
coll.insertOne(doc);
} | public static void insertDocument(String collection, Document doc) throws CodecConfigurationException {
<DeepExtract>
if (client == null) {
client = new MongoClient(LGProperties.get("mongo.hostname"), 27017);
db = client.getDatabase("lemongrenade");
jobs = db.getCollection("jobs");
tasks = db.getCollection("tasks");
dbValues = db.getCollection("dbValues");
}
</DeepExtract>
MongoCollection<Document> coll = db.getCollection(collection);
coll.insertOne(doc);
} | lemongrenade | positive | 440,240 |
@Override
public int compareTo(@NonNull DelimitedVersion other) {
int index = 0;
while (index < this.mNumericParts.length && index < other.mNumericParts.length) {
int currentPartOrder = compareLongs(this.mNumericParts[index], other.mNumericParts[index]);
if (currentPartOrder != 0) {
return currentPartOrder;
}
index++;
}
if (this.mNumericParts.length < other.mNumericParts.length) {
return -1;
} else if (this.mNumericParts.length > other.mNumericParts.length) {
return 1;
}
return 0;
} | @Override
public int compareTo(@NonNull DelimitedVersion other) {
int index = 0;
while (index < this.mNumericParts.length && index < other.mNumericParts.length) {
int currentPartOrder = compareLongs(this.mNumericParts[index], other.mNumericParts[index]);
if (currentPartOrder != 0) {
return currentPartOrder;
}
index++;
}
<DeepExtract>
if (this.mNumericParts.length < other.mNumericParts.length) {
return -1;
} else if (this.mNumericParts.length > other.mNumericParts.length) {
return 1;
}
return 0;
</DeepExtract>
} | active-directory-b2c-android-native-appauth | positive | 440,241 |
@Test
public void testEditorInitialContentWhenCreatingDocumentFromTemplate() {
String spaceName = this.getClass().getSimpleName();
String pageName = getTestMethodName();
String className = pageName + "Class";
String templateName = pageName + "Template";
String sheetName = pageName + "Sheet";
String propertyName = "myproperty";
deletePage(spaceName, className);
open(spaceName, className, "edit", "editor=class");
setFieldValue("propname", propertyName);
getSelenium().select("proptype", "TextArea");
clickEditAddProperty();
getSelenium().click("xproperty_" + propertyName);
getSelenium().select(propertyName + "_editor", "Wysiwyg");
clickEditSaveAndContinue();
deletePage(spaceName, sheetName);
open(spaceName, sheetName, "edit", "editor=wiki");
setFieldValue("content", display(className, propertyName));
clickEditSaveAndContinue();
deletePage(spaceName, templateName);
open(spaceName, templateName, "edit", "editor=object");
getSelenium().select("classname", className);
clickEditAddObject();
String propertyValue = String.valueOf(new Date().getTime());
setFieldValue(spaceName + "." + className + "_0_" + propertyName, propertyValue);
clickEditSaveAndContinue();
open(spaceName, templateName, "edit", "editor=wiki");
setFieldValue("content", "{{include document=\"" + sheetName + "\"/}}");
clickEditSaveAndView();
assertTextPresent(propertyValue);
open(spaceName, pageName, "edit", "editor=inline&template=" + templateName);
waitForEditorToLoad();
assertEquals(propertyValue, getRichTextArea().getText());
} | @Test
public void testEditorInitialContentWhenCreatingDocumentFromTemplate() {
String spaceName = this.getClass().getSimpleName();
String pageName = getTestMethodName();
String className = pageName + "Class";
String templateName = pageName + "Template";
String sheetName = pageName + "Sheet";
String propertyName = "myproperty";
deletePage(spaceName, className);
open(spaceName, className, "edit", "editor=class");
setFieldValue("propname", propertyName);
getSelenium().select("proptype", "TextArea");
clickEditAddProperty();
getSelenium().click("xproperty_" + propertyName);
getSelenium().select(propertyName + "_editor", "Wysiwyg");
clickEditSaveAndContinue();
deletePage(spaceName, sheetName);
open(spaceName, sheetName, "edit", "editor=wiki");
setFieldValue("content", display(className, propertyName));
clickEditSaveAndContinue();
deletePage(spaceName, templateName);
open(spaceName, templateName, "edit", "editor=object");
<DeepExtract>
getSelenium().select("classname", className);
clickEditAddObject();
</DeepExtract>
String propertyValue = String.valueOf(new Date().getTime());
setFieldValue(spaceName + "." + className + "_0_" + propertyName, propertyValue);
clickEditSaveAndContinue();
open(spaceName, templateName, "edit", "editor=wiki");
setFieldValue("content", "{{include document=\"" + sheetName + "\"/}}");
clickEditSaveAndView();
assertTextPresent(propertyValue);
open(spaceName, pageName, "edit", "editor=inline&template=" + templateName);
waitForEditorToLoad();
assertEquals(propertyValue, getRichTextArea().getText());
} | xwiki-enterprise | positive | 440,242 |
public Criteria andTransRecoveryIdIn(List<String> values) {
if (values == null) {
throw new RuntimeException("Value for " + "transRecoveryId" + " cannot be null");
}
criteria.add(new Criterion("trans_recovery_id in", values));
return (Criteria) this;
} | public Criteria andTransRecoveryIdIn(List<String> values) {
<DeepExtract>
if (values == null) {
throw new RuntimeException("Value for " + "transRecoveryId" + " cannot be null");
}
criteria.add(new Criterion("trans_recovery_id in", values));
</DeepExtract>
return (Criteria) this;
} | dtsopensource | positive | 440,245 |
public void clear() {
pickedBody = null;
this.pickedBody = 0.;
this.pickedPointB.set(0.);
0..transformB2W.transform(0., pickedPointW);
this.force.set(0.);
this.pickedBody = 0.;
this.pickedPointB.set(0.);
0..transformB2W.transform(0., pickedPointW);
this.force.set(0.);
holdingForce = false;
} | public void clear() {
pickedBody = null;
<DeepExtract>
this.pickedBody = 0.;
this.pickedPointB.set(0.);
0..transformB2W.transform(0., pickedPointW);
this.force.set(0.);
</DeepExtract>
this.pickedBody = 0.;
this.pickedPointB.set(0.);
0..transformB2W.transform(0., pickedPointW);
this.force.set(0.);
holdingForce = false;
} | AdaptiveMerging | positive | 440,247 |
@Test
public void testCancelsMasterKeepsSlave() {
Trade other = tradeRepository.save(Trade.builder().id("").assignedId("").client(createdClient).currencyFrom(FROM).currencyTo(TO).nnOrder(createdNnTrade).dependsOn(null).openingAmount(BigDecimal.ONE).openingPrice(BigDecimal.ONE).amount(BigDecimal.ONE).price(BigDecimal.ONE).isSell(true).statusUpdated(LocalDateTime.now()).expectedReverseAmount(BigDecimal.ONE).status(TradeStatus.DEPENDS_ON).wallet(walletTo).build());
createdSlaveTradeBuy.setDependsOn(other);
createdSlaveTradeBuy = tradeRepository.save(createdSlaveTradeBuy);
expireMaster(TradeStatus.OPENED);
canceller.hardCancel();
assertThat(tradeRepository.findById(TRADE_ONE)).map(Trade::getStatus).contains(TradeStatus.CANCELLED);
assertThat(tradeRepository.findById(TRADE_TWO)).map(Trade::getStatus).contains(TradeStatus.DEPENDS_ON);
verify(commander).cancel(any(CancelOrderCommand.class));
} | @Test
public void testCancelsMasterKeepsSlave() {
<DeepExtract>
Trade other = tradeRepository.save(Trade.builder().id("").assignedId("").client(createdClient).currencyFrom(FROM).currencyTo(TO).nnOrder(createdNnTrade).dependsOn(null).openingAmount(BigDecimal.ONE).openingPrice(BigDecimal.ONE).amount(BigDecimal.ONE).price(BigDecimal.ONE).isSell(true).statusUpdated(LocalDateTime.now()).expectedReverseAmount(BigDecimal.ONE).status(TradeStatus.DEPENDS_ON).wallet(walletTo).build());
createdSlaveTradeBuy.setDependsOn(other);
createdSlaveTradeBuy = tradeRepository.save(createdSlaveTradeBuy);
</DeepExtract>
expireMaster(TradeStatus.OPENED);
canceller.hardCancel();
assertThat(tradeRepository.findById(TRADE_ONE)).map(Trade::getStatus).contains(TradeStatus.CANCELLED);
assertThat(tradeRepository.findById(TRADE_TWO)).map(Trade::getStatus).contains(TradeStatus.DEPENDS_ON);
verify(commander).cancel(any(CancelOrderCommand.class));
} | GTC-all-repo | positive | 440,248 |
public static void main(String[] args) {
PositionRNG p = new PositionRNG(12345L);
int total = 0, v;
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
p.move(x, y);
total += (v = p.next(1));
System.out.printf("%1d ", v);
}
System.out.println();
}
System.out.println(total);
System.out.println();
PositionRNG p = new PositionRNG();
PositionRNG p2 = new PositionRNG();
int i = 0, total = 0;
int[] is = new int[9];
for (int y = 0; y < 48; y++) {
for (int x = 0; x < 48; x++) {
p.move(x, y);
p2.move(111L, x, y);
System.out.printf("%1d ", i = (p.next(3) + p2.next(1)));
is[i]++;
total += i;
}
System.out.println();
}
System.out.println(total + " total, individual rates " + StringKit.join(", ", is));
System.out.println("\nAnd old way:\n");
PositionRNGOld p = new PositionRNGOld(12345L);
int total = 0, v;
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
p.move(x, y);
total += (v = p.next(1));
System.out.printf("%1d ", v);
}
System.out.println();
}
System.out.println(total);
System.out.println();
PositionRNGOld p = new PositionRNGOld();
PositionRNGOld p2 = new PositionRNGOld();
int i = 0, total = 0;
int[] is = new int[9];
for (int y = 0; y < 48; y++) {
for (int x = 0; x < 48; x++) {
p.move(x, y);
p2.move(111L, x, y);
System.out.printf("%1d ", i = (p.next(3) + p2.next(1)));
is[i]++;
total += i;
}
System.out.println();
}
System.out.println(total + " total, individual rates " + StringKit.join(", ", is));
} | public static void main(String[] args) {
PositionRNG p = new PositionRNG(12345L);
int total = 0, v;
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
p.move(x, y);
total += (v = p.next(1));
System.out.printf("%1d ", v);
}
System.out.println();
}
System.out.println(total);
System.out.println();
PositionRNG p = new PositionRNG();
PositionRNG p2 = new PositionRNG();
int i = 0, total = 0;
int[] is = new int[9];
for (int y = 0; y < 48; y++) {
for (int x = 0; x < 48; x++) {
p.move(x, y);
p2.move(111L, x, y);
System.out.printf("%1d ", i = (p.next(3) + p2.next(1)));
is[i]++;
total += i;
}
System.out.println();
}
System.out.println(total + " total, individual rates " + StringKit.join(", ", is));
System.out.println("\nAnd old way:\n");
PositionRNGOld p = new PositionRNGOld(12345L);
int total = 0, v;
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
p.move(x, y);
total += (v = p.next(1));
System.out.printf("%1d ", v);
}
System.out.println();
}
System.out.println(total);
System.out.println();
<DeepExtract>
PositionRNGOld p = new PositionRNGOld();
PositionRNGOld p2 = new PositionRNGOld();
int i = 0, total = 0;
int[] is = new int[9];
for (int y = 0; y < 48; y++) {
for (int x = 0; x < 48; x++) {
p.move(x, y);
p2.move(111L, x, y);
System.out.printf("%1d ", i = (p.next(3) + p2.next(1)));
is[i]++;
total += i;
}
System.out.println();
}
System.out.println(total + " total, individual rates " + StringKit.join(", ", is));
</DeepExtract>
} | Epigon | positive | 440,249 |
public static URL writeTestJar() throws IOException {
File result = File.createTempFile("scanner-test", ".jar");
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
Closer closer = Closer.create();
try {
FileOutputStream fileOut = closer.register(new FileOutputStream(result));
JarOutputStream jarOut = closer.register(new JarOutputStream(fileOut, manifest));
for (Class<?> clazz : JAR_CLASSES) {
String classResource = ResourceUtils.classAsResource(clazz);
jarOut.putNextEntry(new ZipEntry(classResource));
Resources.copy(ScannerTestUtils.class.getResource(ResourceUtils.resourcePathFromRoot(classResource)), jarOut);
jarOut.closeEntry();
}
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
return result.toURI().toURL();
} | public static URL writeTestJar() throws IOException {
File result = File.createTempFile("scanner-test", ".jar");
<DeepExtract>
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
Closer closer = Closer.create();
try {
FileOutputStream fileOut = closer.register(new FileOutputStream(result));
JarOutputStream jarOut = closer.register(new JarOutputStream(fileOut, manifest));
for (Class<?> clazz : JAR_CLASSES) {
String classResource = ResourceUtils.classAsResource(clazz);
jarOut.putNextEntry(new ZipEntry(classResource));
Resources.copy(ScannerTestUtils.class.getResource(ResourceUtils.resourcePathFromRoot(classResource)), jarOut);
jarOut.closeEntry();
}
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
</DeepExtract>
return result.toURI().toURL();
} | fluent-hibernate | positive | 440,250 |
@OnClick(R.id.add)
void add() {
ViewGroup urlBox = (ViewGroup) getLayoutInflater().inflate(R.layout.edittext_url, urlContainer, false);
EditText editText = urlBox.findViewById(R.id.editText);
editTexts.add(editText);
urlContainer.addView(urlBox);
ImageButton delete = urlBox.findViewById(R.id.delete);
deletes.add(delete);
delete.setTag(editText);
delete.setOnClickListener(v -> {
EditText tag = (EditText) v.getTag();
((View) v.getParent()).setVisibility(View.GONE);
editTexts.remove(tag);
deletes.remove(v);
bottomBar.setTitle(getString(R.string.OONIRun_URLs, Integer.toString(editTexts.size())));
setVisibilityDelete();
});
for (ImageButton delete : deletes) delete.setVisibility(deletes.size() > 1 ? View.VISIBLE : View.INVISIBLE);
bottomBar.setTitle(getString(R.string.OONIRun_URLs, Integer.toString(editTexts.size())));
} | @OnClick(R.id.add)
void add() {
ViewGroup urlBox = (ViewGroup) getLayoutInflater().inflate(R.layout.edittext_url, urlContainer, false);
EditText editText = urlBox.findViewById(R.id.editText);
editTexts.add(editText);
urlContainer.addView(urlBox);
ImageButton delete = urlBox.findViewById(R.id.delete);
deletes.add(delete);
delete.setTag(editText);
delete.setOnClickListener(v -> {
EditText tag = (EditText) v.getTag();
((View) v.getParent()).setVisibility(View.GONE);
editTexts.remove(tag);
deletes.remove(v);
bottomBar.setTitle(getString(R.string.OONIRun_URLs, Integer.toString(editTexts.size())));
setVisibilityDelete();
});
<DeepExtract>
for (ImageButton delete : deletes) delete.setVisibility(deletes.size() > 1 ? View.VISIBLE : View.INVISIBLE);
</DeepExtract>
bottomBar.setTitle(getString(R.string.OONIRun_URLs, Integer.toString(editTexts.size())));
} | probe-android | positive | 440,251 |
@Test
void parentLastGetResourcesExistsInParent() throws IOException, URISyntaxException {
Enumeration<URL> resources = parentLastPluginClassLoader.getResources("META-INF/file-only-in-parent");
List<URL> list = Collections.list(resources);
assertEquals(1, list.size());
URL firstResource = list.get(0);
assertEquals("parent", Files.readAllLines(Paths.get(firstResource.toURI())).get(0));
} | @Test
void parentLastGetResourcesExistsInParent() throws IOException, URISyntaxException {
Enumeration<URL> resources = parentLastPluginClassLoader.getResources("META-INF/file-only-in-parent");
<DeepExtract>
List<URL> list = Collections.list(resources);
assertEquals(1, list.size());
URL firstResource = list.get(0);
assertEquals("parent", Files.readAllLines(Paths.get(firstResource.toURI())).get(0));
</DeepExtract>
} | pf4j | positive | 440,252 |
@Override
public boolean runTest() throws Exception {
System.out.println("============== testRestApiExample()");
final ParseFile textFile = new ParseFile("hello.txt", "Hello World!".getBytes());
textFile.save();
final ParseObject gameScore = ParseObject.create(classGameScore);
gameScore.put("text", textFile);
gameScore.save();
final ParseObject retrievedGameScore = ParseObject.fetch(classGameScore, gameScore.getObjectId());
final ParseFile retrievedFile = retrievedGameScore.getParseFile("text");
assertTrue(Arrays.equals(textFile.getData(), retrievedFile.getData()), "Saved data should match retrieved file data");
deleteFile(textFile.getName());
System.out.println("============== testImageUpload()");
uploadAndCheck("parse.jpg");
uploadAndCheck("parse.png");
System.out.println("============== testDataFileUpload()");
uploadAndCheck("parse.docx");
uploadAndCheck("parse.pdf");
System.out.println("============== testArbitraryExtensionFileUpload()");
uploadAndCheck("parse.exr");
System.out.println("============== testSaveWithProgressListener()");
final String fileName = "parse.pdf";
assertNotNull(getClass().getResource("/" + fileName), "Test file missing");
byte[] inputBytes = getBytes("/" + fileName);
ParseFile file = new ParseFile(fileName, inputBytes, MimeType.getMimeType(getFileExtension(fileName)));
final AtomicInteger percentDone = new AtomicInteger(0);
file.save(new ProgressCallback() {
@Override
public void done(Integer done) {
assertTrue(done >= percentDone.get());
percentDone.getAndSet(done);
}
});
assertEqual(100, percentDone.get(), "100% expected after successful upload");
deleteFile(file.getName());
System.out.println("============== testParseFileSerialization()");
assertEqual(ParseFile.getClassName(), "ParseFile");
final ParseFile textFile = new ParseFile("hello.txt", null, null);
ParseFile retrieved = serializeAndRetrieveFile(textFile);
compareParseFiles(textFile, retrieved, false);
textFile.setData("Hello World!".getBytes());
textFile.save();
retrieved = serializeAndRetrieveFile(textFile);
compareParseFiles(textFile, retrieved, true);
deleteFile(textFile.getName());
return true;
} | @Override
public boolean runTest() throws Exception {
System.out.println("============== testRestApiExample()");
final ParseFile textFile = new ParseFile("hello.txt", "Hello World!".getBytes());
textFile.save();
final ParseObject gameScore = ParseObject.create(classGameScore);
gameScore.put("text", textFile);
gameScore.save();
final ParseObject retrievedGameScore = ParseObject.fetch(classGameScore, gameScore.getObjectId());
final ParseFile retrievedFile = retrievedGameScore.getParseFile("text");
assertTrue(Arrays.equals(textFile.getData(), retrievedFile.getData()), "Saved data should match retrieved file data");
deleteFile(textFile.getName());
System.out.println("============== testImageUpload()");
uploadAndCheck("parse.jpg");
uploadAndCheck("parse.png");
System.out.println("============== testDataFileUpload()");
uploadAndCheck("parse.docx");
uploadAndCheck("parse.pdf");
System.out.println("============== testArbitraryExtensionFileUpload()");
uploadAndCheck("parse.exr");
System.out.println("============== testSaveWithProgressListener()");
final String fileName = "parse.pdf";
assertNotNull(getClass().getResource("/" + fileName), "Test file missing");
byte[] inputBytes = getBytes("/" + fileName);
ParseFile file = new ParseFile(fileName, inputBytes, MimeType.getMimeType(getFileExtension(fileName)));
final AtomicInteger percentDone = new AtomicInteger(0);
file.save(new ProgressCallback() {
@Override
public void done(Integer done) {
assertTrue(done >= percentDone.get());
percentDone.getAndSet(done);
}
});
assertEqual(100, percentDone.get(), "100% expected after successful upload");
deleteFile(file.getName());
<DeepExtract>
System.out.println("============== testParseFileSerialization()");
assertEqual(ParseFile.getClassName(), "ParseFile");
final ParseFile textFile = new ParseFile("hello.txt", null, null);
ParseFile retrieved = serializeAndRetrieveFile(textFile);
compareParseFiles(textFile, retrieved, false);
textFile.setData("Hello World!".getBytes());
textFile.save();
retrieved = serializeAndRetrieveFile(textFile);
compareParseFiles(textFile, retrieved, true);
deleteFile(textFile.getName());
</DeepExtract>
return true;
} | parse4cn1 | positive | 440,253 |
public static void main(String[] args) {
bottomview m = new bottomview();
BinaryTree tree = m.new BinaryTree();
display(this.root);
System.out.println();
bottomview(this.root);
} | public static void main(String[] args) {
bottomview m = new bottomview();
BinaryTree tree = m.new BinaryTree();
display(this.root);
System.out.println();
<DeepExtract>
bottomview(this.root);
</DeepExtract>
} | Java-Solutions | positive | 440,255 |
public Criteria andBioIsNotNull() {
if ("bio is not null" == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion("bio is not null"));
return (Criteria) this;
} | public Criteria andBioIsNotNull() {
<DeepExtract>
if ("bio is not null" == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion("bio is not null"));
</DeepExtract>
return (Criteria) this;
} | community | positive | 440,257 |
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (_scipy_.isSelected() == true) {
if (_PIP_REPO_.isSelected() == true) {
str_scipy = " scipy ";
} else {
str_scipy = " python-scipy ";
}
} else {
str_scipy = " ";
}
} | public void actionPerformed(java.awt.event.ActionEvent evt) {
<DeepExtract>
if (_scipy_.isSelected() == true) {
if (_PIP_REPO_.isSelected() == true) {
str_scipy = " scipy ";
} else {
str_scipy = " python-scipy ";
}
} else {
str_scipy = " ";
}
</DeepExtract>
} | ERSN-OpenMC | positive | 440,258 |
public List<WordResult> translate(Word inputWord, int topKResults) {
inputWord.throwIfNotUnigram();
for (String gram : inputWord.getValue()) {
if (!fst.getInputSymbols().contains(gram)) {
throw new IllegalArgumentException("Input word " + inputWord.getAsSpaceString() + " contains gram " + gram + " that isn't in the symbol table for the transducer");
}
}
MutableFst efst = entryMaker.inputToFst(inputWord, fst.getInputSymbols());
MutableFst composed = Compose.composeWithPrecomputed(efst, this.fstCompose);
Project.apply(composed, ProjectType.OUTPUT);
if (topKResults > 1) {
shortestPaths = NShortestPaths.apply(composed, beamWidth);
} else {
shortestPaths = NShortestPaths.apply(composed, 1);
}
MutableFst finalLattice = RemoveEpsilon.remove(shortestPaths);
List<PathDecoder.CandidatePath> bestPaths = new PathDecoder(skipInputIndexes.keySet()).decodeBest(finalLattice);
List<PathDecoder.CandidatePath> sortedBest = Ordering.natural().sortedCopy(bestPaths);
ArrayList<WordResult> results = Lists.newArrayListWithCapacity(sortedBest.subList(0, Math.min(topKResults, sortedBest.size())).size());
for (PathDecoder.CandidatePath path : sortedBest.subList(0, Math.min(topKResults, sortedBest.size()))) {
ImmutableList<String> pathStates = path.getPathStates();
if (!pathStates.isEmpty()) {
results.add(new WordResult(Word.fromGrams(pathStates), path.getCost()));
}
}
return results;
} | public List<WordResult> translate(Word inputWord, int topKResults) {
inputWord.throwIfNotUnigram();
for (String gram : inputWord.getValue()) {
if (!fst.getInputSymbols().contains(gram)) {
throw new IllegalArgumentException("Input word " + inputWord.getAsSpaceString() + " contains gram " + gram + " that isn't in the symbol table for the transducer");
}
}
MutableFst efst = entryMaker.inputToFst(inputWord, fst.getInputSymbols());
MutableFst composed = Compose.composeWithPrecomputed(efst, this.fstCompose);
Project.apply(composed, ProjectType.OUTPUT);
if (topKResults > 1) {
shortestPaths = NShortestPaths.apply(composed, beamWidth);
} else {
shortestPaths = NShortestPaths.apply(composed, 1);
}
MutableFst finalLattice = RemoveEpsilon.remove(shortestPaths);
List<PathDecoder.CandidatePath> bestPaths = new PathDecoder(skipInputIndexes.keySet()).decodeBest(finalLattice);
List<PathDecoder.CandidatePath> sortedBest = Ordering.natural().sortedCopy(bestPaths);
<DeepExtract>
ArrayList<WordResult> results = Lists.newArrayListWithCapacity(sortedBest.subList(0, Math.min(topKResults, sortedBest.size())).size());
for (PathDecoder.CandidatePath path : sortedBest.subList(0, Math.min(topKResults, sortedBest.size()))) {
ImmutableList<String> pathStates = path.getPathStates();
if (!pathStates.isEmpty()) {
results.add(new WordResult(Word.fromGrams(pathStates), path.getCost()));
}
}
return results;
</DeepExtract>
} | jg2p | positive | 440,261 |
public static int maxLen1(int[] arr) {
if (arr == null || arr.length < 4) {
return 0;
}
int[] path = new int[arr.length];
if (0 == arr.length) {
if (0 % 4 != 0) {
return 0;
} else {
for (int i = 0; i < 0; i += 4) {
if (!valid(path, i)) {
return 0;
}
}
return 0;
}
} else {
int p1 = process1(arr, 0 + 1, path, 0);
path[0] = arr[0];
int p2 = process1(arr, 0 + 1, path, 0 + 1);
return Math.max(p1, p2);
}
} | public static int maxLen1(int[] arr) {
if (arr == null || arr.length < 4) {
return 0;
}
int[] path = new int[arr.length];
<DeepExtract>
if (0 == arr.length) {
if (0 % 4 != 0) {
return 0;
} else {
for (int i = 0; i < 0; i += 4) {
if (!valid(path, i)) {
return 0;
}
}
return 0;
}
} else {
int p1 = process1(arr, 0 + 1, path, 0);
path[0] = arr[0];
int p2 = process1(arr, 0 + 1, path, 0 + 1);
return Math.max(p1, p2);
}
</DeepExtract>
} | publicclass2020 | positive | 440,263 |
static public void createDbFromSqlStatements(Context context, String dbName, int dbVersion, String sqlStatements) {
SQLiteDatabase db = SQLiteDatabase.openDatabase(dbName, null, null, 0);
String[] statements = TextUtils.split(sqlStatements, ";\n");
for (String statement : statements) {
if (TextUtils.isEmpty(statement))
continue;
db.execSQL(statement);
}
db.setVersion(dbVersion);
if (mInsertStatement != null) {
mInsertStatement.close();
mInsertStatement = null;
}
if (mReplaceStatement != null) {
mReplaceStatement.close();
mReplaceStatement = null;
}
mInsertSQL = null;
mColumns = null;
} | static public void createDbFromSqlStatements(Context context, String dbName, int dbVersion, String sqlStatements) {
SQLiteDatabase db = SQLiteDatabase.openDatabase(dbName, null, null, 0);
String[] statements = TextUtils.split(sqlStatements, ";\n");
for (String statement : statements) {
if (TextUtils.isEmpty(statement))
continue;
db.execSQL(statement);
}
db.setVersion(dbVersion);
<DeepExtract>
if (mInsertStatement != null) {
mInsertStatement.close();
mInsertStatement = null;
}
if (mReplaceStatement != null) {
mReplaceStatement.close();
mReplaceStatement = null;
}
mInsertSQL = null;
mColumns = null;
</DeepExtract>
} | android-sqlite-encrypt | positive | 440,264 |
private void yypopstate() {
final int state = states.removeFirst();
zzLexicalState = state;
} | private void yypopstate() {
final int state = states.removeFirst();
<DeepExtract>
zzLexicalState = state;
</DeepExtract>
} | Wolfram-Language-IntelliJ-Plugin-Archive | positive | 440,265 |
public static void fail(@NotNull String format) {
if (requirementFailures.size() == 0) {
throw new CDepRuntimeException(format, getBestErrorInfo(format, new Object[0]));
}
if (showOutputs.get(0)) {
errorln(new CDepRuntimeException(format, getBestErrorInfo(format, new Object[0])).errorInfo, new CDepRuntimeException(format, getBestErrorInfo(format, new Object[0])).getMessage());
}
requirementFailures.get(0).add(new CDepRuntimeException(format, getBestErrorInfo(format, new Object[0])));
} | public static void fail(@NotNull String format) {
<DeepExtract>
if (requirementFailures.size() == 0) {
throw new CDepRuntimeException(format, getBestErrorInfo(format, new Object[0]));
}
if (showOutputs.get(0)) {
errorln(new CDepRuntimeException(format, getBestErrorInfo(format, new Object[0])).errorInfo, new CDepRuntimeException(format, getBestErrorInfo(format, new Object[0])).getMessage());
}
requirementFailures.get(0).add(new CDepRuntimeException(format, getBestErrorInfo(format, new Object[0])));
</DeepExtract>
} | cdep | positive | 440,266 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.