text stringlengths 14 410k | label int32 0 9 |
|---|---|
public String getB() {
return b;
} | 0 |
private void installTabContainer() {
if (JTattooUtilities.getJavaVersion() >= 1.6) {
for (int i = 0; i < tabPane.getTabCount(); i++) {
Component tabComponent = getTabComponentAt(i);
if (tabComponent != null) {
if (tabContainer == null) {
tabContainer = new TabContainer();
}
tabContainer.add(tabComponent);
addMyPropertyChangeListeners(tabComponent);
}
}
if (tabContainer == null) {
return;
}
if (scrollableTabLayoutEnabled()) {
tabScroller.tabPanel.add(tabContainer);
} else {
tabPane.add(tabContainer);
}
}
} | 6 |
@Test
public void testRemove() {
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
List<String> list2 = new ArrayList<String>(Arrays.asList("1", "2", "3", "4", "5"));
for (int i=0; i<list1.size(); i++) {
System.out.println("size:" + list1.size() + " " + i + "->" + list1.get(i));
if (list1.get(i) == 2 || list1.get(i) == 5) {
list1.remove(i);
list2.remove(i);
}
}
System.out.println(list1);
System.out.println(list2);
list2 = new ArrayList<String>(Arrays.asList("1", "2", "3", "4", "5"));
list2 = new CopyOnWriteArrayList<>(list2);
for (String string : list2) {
if ("2".equals(string)) {
list2.remove(string);
}
}
System.out.println(list2);
} | 5 |
public static File chooseSaveFileCheckOverwrite(Component parent,
JFileChooser chooser, final String suffix,
Preferences prefs, String prefsKey)
{
String path = null;
String fname = null;
if (prefs != null) {
String sdir = prefs.get(prefsKey, null);
if (sdir != null) chooser.setCurrentDirectory(new File(sdir));
}
for (;;) {
chooser.showSaveDialog(parent);
path = chooser.getCurrentDirectory().getAbsolutePath();
prefs.put(prefsKey, path);
if (chooser.getSelectedFile() == null) return null;
fname = chooser.getSelectedFile().getPath();
if (!fname.endsWith(suffix)) fname = fname + suffix;
File f = new File(fname);
if (!f.exists()) return f;
if (JOptionPane.showConfirmDialog(parent,
"The file " + f.getName() + " already exists.\nWould you like to ovewrite it?",
"Overwrite File?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) break;
}
return null;
// return chooser.getSelectedFile();
} | 7 |
public AbstractExpression LExpr(ProcedureBuilder pb) throws Exception {
Token l_token;
AbstractExpression RetValue = Expression(pb);
while (Current_Token == Token.TOK_GT
|| Current_Token == Token.TOK_LT
|| Current_Token == Token.TOK_GTE
|| Current_Token == Token.TOK_LTE
|| Current_Token == Token.TOK_NEQ
|| Current_Token == Token.TOK_EQ) {
l_token = Current_Token;
Current_Token = GetNext();
AbstractExpression e2 = Expression(pb);
RelationalOperators relop = GetRelationalOperator(l_token);
RetValue = new RelationalExpression(relop, RetValue, e2);
}
return RetValue;
} | 6 |
public int compare(Object o1, Object o2) {
// we swap the parameters so that sorting goes largest to smallest
String v1 = ((AbstractPolicy)o2).getVersion();
String v2 = ((AbstractPolicy)o1).getVersion();
// do a quick check to see if the strings are equal (note that
// even if the strings aren't equal, the versions can still
// be equal)
if (v1.equals(v2))
return 0;
// setup tokenizers, and walk through both strings one set of
// numeric values at a time
StringTokenizer tok1 = new StringTokenizer(v1, ".");
StringTokenizer tok2 = new StringTokenizer(v2, ".");
while (tok1.hasMoreTokens()) {
// if there's nothing left in tok2, then v1 is bigger
if (! tok2.hasMoreTokens())
return 1;
// get the next elements in the version, convert to numbers,
// and compare them (continuing with the loop only if the
// two values were equal)
int num1 = Integer.parseInt(tok1.nextToken());
int num2 = Integer.parseInt(tok2.nextToken());
if (num1 > num2)
return 1;
if (num1 < num2)
return -1;
}
// if there's still something left in tok2, then it's bigger
if (tok2.hasMoreTokens())
return -1;
// if we got here it means both versions had the same number of
// elements and all the elements were equal, so the versions
// are in fact equal
return 0;
} | 6 |
@Override
public void sort() {
// Create the heap
for (int i=1; i<this.arr.size(); i++) {
// i = right side of the heap
// Move the element upside
int moving = i;
int parent = (moving-1)/2;
while (parent>=0 && this.arr.getValue(moving).compareTo(this.arr.getValue(parent)) > 0) {
this.steps++;
// swap
T aux = this.arr.getValue(moving);
this.arr.setValue(moving, this.arr.getValue(parent));
this.arr.setValue(parent, aux);
moving = parent;
parent = (moving-1)/2;
}
}
// Replace the peak with the last
for (int i=this.arr.size()-1; i>0; i--) {
// Declare the new peak
this.arr.setValue(i, this.arr.getValue(0));
// Move the peak element downside
int mov = 0;
int ch1 = mov*2+1;
int ch2 = mov*2+2;
boolean swap = true;
while (swap) {
this.steps++;
if (ch1<=i && this.arr.getValue(mov).compareTo(this.arr.getValue(ch1)) < 0) {
swap = true;
mov = ch1;
T aux = this.arr.getValue(mov);
this.arr.setValue(mov, this.arr.getValue(ch1));
this.arr.setValue(ch1, aux);
} else if (ch2<=i && this.arr.getValue(mov).compareTo(this.arr.getValue(ch2)) < 0) {
swap = true;
mov = ch2;
T aux = this.arr.getValue(mov);
this.arr.setValue(mov, this.arr.getValue(ch2));
this.arr.setValue(ch2, aux);
} else {
swap = false;
}
ch1 = mov*2+1;
ch2 = mov*2+2;
}
}
} | 9 |
int readCorner1(int numRows, int numColumns) {
int currentByte = 0;
if (readModule(numRows - 1, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(2, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(3, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
return currentByte;
} | 8 |
public void setAlgorithm(String value) {
this.algorithm = value;
} | 0 |
public void setComando(List<?> list)
{
for(PComando e : this._comando_)
{
e.parent(null);
}
this._comando_.clear();
for(Object obj_e : list)
{
PComando e = (PComando) obj_e;
if(e.parent() != null)
{
e.parent().removeChild(e);
}
e.parent(this);
this._comando_.add(e);
}
} | 4 |
public void undo(){
if(getCell(0, 0).getundoListSize() < 0){
for(int i = 0; i < model.getWidth(); i++){
for(int j = 0; j < model.getHeight(); j++){
getCell(i, j).undo();
}
}
}
else{
System.out.println("Não há gerações passadas");
}
} | 3 |
private final boolean initialiseFullScreen() {
graphicsDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (!graphicsDevice.isFullScreenSupported()) {
logger.error("Full screen not supported by graphics device");
return false;
}
graphicsDevice.setFullScreenWindow(this);
if (setDisplayMode(gameSettings.gameWidth, gameSettings.gameHeight, gameSettings.gameDepth)) {
setBufferStrategy();
return true;
}
logger.error("Display mode not offered for FSEM mode");
return false;
} | 2 |
public PastPane(Configuration last) {
setConfiguration(last);
} | 0 |
public int[] getStats(boolean recursive){
int[] stats=new int[6];
HashSet<String> blankNodes=new HashSet<String>();
HashSet<String> USUs=new HashSet<String>();
//Triples
if (!triples.isEmpty()){
int[] r=getStatsTripleList(triples,blankNodes,USUs);
for (int i=0; i<stats.length; i++){
stats[i]+=r[i];
}
//MSGs
}else if(msgs!=null){
for (MSG msg:msgs){
int[] r=getStatsTripleList(msg.getTriples(),blankNodes,USUs);
for (int i=0; i<stats.length; i++){
stats[i]+=r[i];
}
}
}
//Sub Graphs
if (recursive){
for (NamedGraph subG:children){
int[] r=subG.getStats(recursive);
for (int i=0; i<stats.length; i++){
stats[i]+=r[i];
}
}
}
return stats;
} | 8 |
private void buildRightSideInfo(final JPanel right, final JList<FolderConfig> list) {
right.add(new JLabel("Artist URL"));
final JTextField artistUrlText = new JTextField();
if (GuiUtils.currentFolderConfig.getArtistUrl() != null) {
artistUrlText.setText(GuiUtils.currentFolderConfig.getArtistUrl());
}
artistUrlText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
updateArtistUrl();
}
@Override
public void insertUpdate(DocumentEvent e) {
updateArtistUrl();
}
@Override
public void changedUpdate(DocumentEvent e) {
updateArtistUrl();
}
private void updateArtistUrl() {
GuiUtils.currentFolderConfig.setArtistUrl(artistUrlText.getText());
list.updateUI();
}
});
right.add(artistUrlText);
right.add(new JLabel("Local Folder"));
final JTextField localFolderText = new JTextField();
if (GuiUtils.currentFolderConfig.getLocalFolder() != null) {
localFolderText.setText(GuiUtils.currentFolderConfig.getLocalFolder());
}
localFolderText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
updateLocalFolder();
}
@Override
public void insertUpdate(DocumentEvent e) {
updateLocalFolder();
}
@Override
public void changedUpdate(DocumentEvent e) {
updateLocalFolder();
}
private void updateLocalFolder() {
GuiUtils.currentFolderConfig.setLocalFolder(localFolderText.getText());
}
});
right.add(localFolderText);
right.add(new JLabel("Download Folder"));
final JTextField downloadFolderText = new JTextField();
if (GuiUtils.currentFolderConfig.getDownloadFolder() != null) {
downloadFolderText.setText(GuiUtils.currentFolderConfig.getDownloadFolder());
}
downloadFolderText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
updateDownloadFolder();
}
@Override
public void insertUpdate(DocumentEvent e) {
updateDownloadFolder();
}
@Override
public void changedUpdate(DocumentEvent e) {
updateDownloadFolder();
}
private void updateDownloadFolder() {
GuiUtils.currentFolderConfig.setDownloadFolder(downloadFolderText.getText());
}
});
right.add(downloadFolderText);
} | 3 |
private int read1(char[] cbuf, int off, int len) throws IOException {
if (nextChar >= nChars) {
/* If the requested length is at least as large as the buffer, and
if there is no mark/reset activity, and if line feeds are not
being skipped, do not bother to copy the characters into the
local buffer. In this way buffered streams will cascade
harmlessly. */
if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
return in.read(cbuf, off, len);
}
fill();
}
if (nextChar >= nChars) return -1;
if (skipLF) {
skipLF = false;
if (cb[nextChar] == '\n') {
nextChar++;
if (nextChar >= nChars)
fill();
if (nextChar >= nChars)
return -1;
}
}
int n = Math.min(len, nChars - nextChar);
System.arraycopy(cb, nextChar, cbuf, off, n);
nextChar += n;
return n;
} | 9 |
private void createDevicesSection() {
BasePanel deviceSection = new BasePanel();
deviceSection.setBorderSize(1);
deviceSection.setArc(10);
deviceSection.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
GridBagLayout deviceSectionLayout;
deviceSection.setLayout(deviceSectionLayout = new GridBagLayout());
Iterator<Device> i = host.getDevices().iterator();
if (!i.hasNext()) {
createInfoLine(
deviceSection,
deviceSectionLayout,
"",
RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.HostConfigurationDialog_NoDeviceMessage));
} else {
while (i.hasNext()) {
Device d = i.next();
createInfoLine(
deviceSection,
deviceSectionLayout,
RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.DeviceConfigurationDialog_DeviceName),
d.getName());
createInfoLine(
deviceSection,
deviceSectionLayout,
RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.DeviceConfigurationDialog_DeviceSerialNumber),
d.getSerialNumber());
createInfoLine(
deviceSection,
deviceSectionLayout,
RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.DeviceConfigurationDialog_DeviceHost),
d.getHost());
if (i.hasNext()) {
JSeparator separator = new JSeparator();
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.fill = GridBagConstraints.HORIZONTAL;
deviceSectionLayout.addLayoutComponent(separator,
constraints);
deviceSection.add(separator);
}
}
}
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.CENTER;
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = gridy++;
constraints.weightx = 1;
constraints.insets = new Insets(4, 4, 4, 4);
contentLayout.addLayoutComponent(deviceSection, constraints);
content.add(deviceSection);
} | 3 |
public void setX(int x)
{
for(int i=0;i<markers;i++)
{
if(marker[i].isSelectedDrag())
{
marker[i].setX(x);
// break;
}
}
} | 2 |
private static void saveMapToTextFile(String fileToSaveTo) {
FileWriter writeto = null;
try {
writeto = new FileWriter(fileToSaveTo, true);// true append
// text
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (writeto == null) {
System.out.println("file not initialized");
return;
}
for (Map.Entry<String, String> entry : rawMap.entrySet()) {
String textadd = entry.getKey() + SPLITTER + entry.getValue()
+ "\n";
char[] buffer = new char[textadd.length()];
textadd.getChars(0, textadd.length(), buffer, 0);
try {
writeto.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writeto.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 5 |
public Set<BankAccount> getAccountsSatisfying(Predicate<BankAccount> predicate) {
Set<BankAccount> result = new HashSet<>();
for (BankAccount account: accounts)
if (predicate.test(account))
result.add(account);
return result;
} | 2 |
public void gameRebounds() {
Collections.shuffle(rebounds);
for (int i = 0; i < 35; i++) {
Collections.shuffle(rebounds);
if(rebounds.get(0) == team.get(0).name) {
rebC++;
}
if(rebounds.get(0) == team.get(1).name) {
rebPF++;
}
if(rebounds.get(0) == team.get(2).name) {
rebSF++;
}
if(rebounds.get(0) == team.get(3).name) {
rebSG++;
}
if(rebounds.get(0) == team.get(4).name) {
rebPG++;
}
}
} | 6 |
public void createConstraints(Model m){
//Inventory balance
inventory= new QBnBconstr[psize][tsize];
for (int p = 0; p < psize; p++) {
for (int t = 0; t < tsize; t++) {
if(t==0){
QBnBLinExp le= new QBnBLinExp();
le.addTerm(1, Q[p][t]);
le.addTerm(-1, I[p][t]);
inventory[p][t]= new QBnBconstr(le, 0, D[p][t]-inInv[p], "inv"+p+","+t,m);
m.addConst(inventory[p][t]);
}
else{
QBnBLinExp le= new QBnBLinExp();
le.addTerm(1, Q[p][t]);
le.addTerm(-1, I[p][t]);
le.addTerm(1, I[p][t-1]);
inventory[p][t]= new QBnBconstr(le, 0, D[p][t], "D"+p+","+t, m);
m.addConst(inventory[p][t]);
}
}
}
//Capacity of inventory
invcapacity= new QBnBconstr[tsize];
for (int t = 0; t < tsize; t++) {
QBnBLinExp le= new QBnBLinExp();
for (int p = 0; p < psize; p++) {
le.addTerm(V[p], I[p][t]);
}
invcapacity[t]= new QBnBconstr(le, 1, K, "K"+t, m);
m.addConst(invcapacity[t]);
}
//production
production= new QBnBconstr[psize];
for (int p = 0; p < psize; p++) {
QBnBLinExp le= new QBnBLinExp();
for (int t = 0; t < tsize; t++) {
le.addTerm(1, Y[p][t]);
}
production[p]= new QBnBconstr(le, 1, N[p], "N"+p, m);
m.addConst(production[p]);
}
productionRel= new QBnBconstr[psize][tsize];
for (int p = 0; p < psize; p++) {
for (int t = 0; t < tsize; t++) {
QBnBLinExp le= new QBnBLinExp();
le.addTerm(1, Q[p][t]);
le.addTerm(-M[p], Y[p][t]);
productionRel[p][t]= new QBnBconstr(le, 1, 0, "pR"+p+","+t, m);
m.addConst(productionRel[p][t]);
}
}
} | 9 |
public void conectar(String AHC, String BHC){ //hashcode B y B
String Acode= null;
String Bcode= null;
for (Nodo<String> i = _ID_HASHCODE_IO.getHead(); i != null; i = i.getSiguiente()){
if(i.getDato().contains(AHC)){
Acode = i.getDato();
}
if(i.getDato().contains(BHC)){
Bcode = i.getDato();
}
}
System.out.println(Acode+" , conectando , "+Bcode);
Rama_Hoja NODOA =_circuito.getObjectoNombre(Acode.split("_")[0]);
if(NODOA == null){
for(Nodo<Rama_Hoja> i = _compuertasDesconectadas.getHead(); i != null; i= i.getSiguiente()){
if (Acode.contains(i.getDato().getIdentificador())){
NODOA = i.getDato();
}
}
}
Rama_Hoja NODOB =_circuito.getObjectoNombre(Bcode.split("_")[0]);
if(NODOB == null){
for(Nodo<Rama_Hoja> i = _compuertasDesconectadas.getHead(); i != null; i= i.getSiguiente())
if (Bcode.contains(i.getDato().getIdentificador())){
NODOB = i.getDato();
}
}
_circuito.conectarA_B(NODOA, AHC , NODOB, BHC);
} | 9 |
private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0 ?
'd' : this.stack[this.top - 1] == null ? 'a' : 'k';
} | 5 |
public void zoomToBestFit(Set<GeoPosition> positions, double maxFraction)
{
if (positions.isEmpty())
return;
if (maxFraction <= 0 || maxFraction > 1)
throw new IllegalArgumentException("maxFraction must be between 0 and 1");
TileFactory tileFactory = getTileFactory();
TileFactoryInfo info = tileFactory.getInfo();
if(info == null)
return;
// set to central position initially
Rectangle2D bounds=generateBoundingRect(positions, getZoom());
Point2D bc = new Point2D.Double(bounds.getCenterX(),bounds.getCenterY());
GeoPosition centre = tileFactory.pixelToGeo(bc, getZoom());
setCenterPosition(centre);
if (positions.size() == 1)
return;
// set map to maximum zoomed out
setZoom(info.getMaximumZoomLevel());
// repeatedly zoom in until we find the first zoom level where either the width or height
// of the points takes up more than the max fraction of the viewport
int bestZoom = getZoom();
Rectangle2D viewport = getViewportBounds();
while (true)
{
// is this zoom still OK?
bounds = generateBoundingRect(positions, getZoom());
if (bounds.getWidth() < viewport.getWidth() * maxFraction &&
bounds.getHeight() < viewport.getHeight()* maxFraction)
{
bestZoom = getZoom();
}
else
{
break;
}
if (getZoom() == info.getMinimumZoomLevel())
{
break;
}
else
{
setZoom(getZoom()-1);
}
}
setZoom(bestZoom);
} | 9 |
public void setId(int id) {
this.id = id;
} | 0 |
private int getStart(int offs) throws BadLocationException {
for (int i=offs;i>=0;i--){
if (endOfTokens.contains(getText(i, 1))){
return i+1;
}
}
return 0;
} | 2 |
public void setFunMm(BigInteger funMm) {
this.funMm = funMm;
} | 0 |
public void setRecordStatus(Integer recordStatus) {
this.recordStatus = recordStatus;
} | 0 |
static int mame_stats(int selected)
{
String buf="";
int sel, i;
sel = selected - 1;
if (dispensed_tickets!=0)
{
buf = "Tickets dispensed: " + sprintf("%d\n\n", dispensed_tickets);
}
for (i=0; i<COIN_COUNTERS; i++)
{
buf += sprintf("Coin %c: ", i + 'A');
if (coins[i]==0)
buf += "NA";
else
{
buf += sprintf("%d", coins[i]);
}
if (coinlockedout[i]!=0)
{
buf += " (locked)\n";
}
else
{
buf += "\n";
}
}
{
/* menu system, use the normal menu keys */
buf +="\n\t\u001a Return to Main Menu \u001b";
ui_displaymessagewindow(buf);
if (input_ui_pressed(IPT_UI_SELECT)!=0)
sel = -1;
if (input_ui_pressed(IPT_UI_CANCEL)!=0)
sel = -1;
if (input_ui_pressed(IPT_UI_CONFIGURE)!=0)
sel = -2;
}
if (sel == -1 || sel == -2)
{
/* tell updatescreen() to clean after us */
need_to_clear_bitmap = 1;
}
return sel + 1;
} | 9 |
public void start() {
ticks=System.currentTimeMillis();
} | 0 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost, msg))
return false;
if((msg.tool()==this)
&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
&&(msg.value()>0)
&&(msg.target() !=null)
&&(msg.target() instanceof MOB)
&&(weaponClassification()==Weapon.CLASS_THROWN))
{
msg.setValue(0);
}
return true;
} | 7 |
public void connect(TreeLinkNode root) {
if(root == null){
return;
}
LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
LinkedList<TreeLinkNode> childQueue = new LinkedList<TreeLinkNode>();
queue.add(root);
TreeLinkNode preNode = null;
while (!queue.isEmpty()){
TreeLinkNode node = queue.remove();
if(preNode != null){
preNode.next=node;
}
preNode = node;
if(node.left != null){
childQueue.add(node.left);
}
if(node.right!=null){
childQueue.add(node.right);
}
if(queue.isEmpty() && !childQueue.isEmpty()){
queue.addAll(childQueue);
childQueue.clear();
preNode=null;
}
}
} | 7 |
public ArrayList<Request> generateVirtualNetworks(int numberOfNetworks) {
ArrayList<Request> requests = new ArrayList<Request>();
int baseTime = 0;
int requestsPer100UnitsTime = randomizer.nextPoisson();
for(int idRequest = 0; idRequest < numberOfNetworks; idRequest++) {
HashMap<Integer,VirtualNode> nodes = new HashMap<Integer, VirtualNode>();
HashMap<String, VirtualLink> links = new HashMap<String, VirtualLink>();
int numberOfNodes = randomizer.nextInt(9) + 2;
int degreeSum = 0;
for(int i = 0; i < numberOfNodes; i++) {
VirtualNode newNode = nodeGenerator.generateVirtualNode(i);
while(newNode.getAttachedLinks().size() == 0 && i != 0) {
for(VirtualNode node : nodes.values()) {
if(degreeSum == 0 || randomizer.nextInt(degreeSum) < node.getAttachedLinks().size()) {
degreeSum += 2;
String newLinkId = String.format("%s:%s",
Math.max(node.getId(), newNode.getId()),
Math.min(node.getId(), newNode.getId()));
VirtualLink newLink = linkGenerator.generateVirtualLink(newLinkId,
newNode, node);
links.put(newLinkId, newLink);
}
}
}
nodes.put(i, newNode);
}
int creationTime = baseTime + randomizer.nextInt(100) + 1;
int lifeTime = randomizer.nextExponential();
requestsPer100UnitsTime--;
if(requestsPer100UnitsTime <= 0) {
requestsPer100UnitsTime = randomizer.nextPoisson();
baseTime = baseTime + 100;
}
requests.add(idRequest, new Request(idRequest, creationTime, lifeTime,
nodes, links));
}
return requests;
} | 8 |
@Override
public void nextStep() {
Resource res;
switch (this.step) {
case (0):
// Blokuotas, laukiam "Eilutė atmintyje" resurso
res = Core.resourceList.searchResource(ResourceType.LI_IN_MEM);
if (res != null) {
PrintDescriptor descriptor = (PrintDescriptor) res.getDescriptor();
res.setParent(this);
this.startAddress = descriptor.getStartAddress();
this.endAddress = descriptor.getEndAddress();
this.changeStep(1);
}
else {
this.changeStep(0);
}
break;
case (1):
// Blokuotas, laukiam "Kanalų įrenginio" resurso
res = Core.resourceList.searchResource(ResourceType.CH_DEV);
if (res != null) {
if (res.getParent() == null || res.getParent() == this) {
res.setParent(this);
this.changeStep(this.step + 1);
}
else {
this.changeStep(2);
}
}
else {
this.changeStep(2);
}
break;
case (2):
// Nustatinėjami įrenginio registra ir įvygdoma komanda XCHG
ChannelsDevice.ST = 2;
ChannelsDevice.DT = 4;
ChannelsDevice.startAddress = this.startAddress;
ChannelsDevice.endAddress = this.endAddress;
if (ChannelsDevice.XCHG()) {
this.changeStep(3);
} else {
this.changeStep(2);
}
break;
case (3):
// Atlaisvinamas "Kanalų įrenginys" resursas
res = Core.resourceList.searchResource(ResourceType.CH_DEV);
res.removeParent();
Core.resourceList.deleteChildResource(this, ResourceType.LI_IN_MEM);
this.changeStep(0);
break;
}
} | 9 |
@Override
public void paint(Graphics g) {
g.clearRect(0, 0, getWidth(), getHeight()); //clears the screen
int gridX = getWidth() / gridSizeX;
int gridY = getHeight() / gridSizeY;
int actual_grid_size = Math.min(gridX, gridY);
if (actual_grid_size == 0) {
return;
}
int tWidth = actual_grid_size * gridSizeX;
int tHeight = actual_grid_size * gridSizeY;
if (backgroundShow) {
g.setColor(Color.GRAY);
for (int i = 0; i < gridSizeX; i++) {
for (int j = 0; j < gridSizeY; j++) {
g.drawLine(i*actual_grid_size, j*actual_grid_size, (i+1)*actual_grid_size, (j+1)*actual_grid_size);
g.drawLine(i*actual_grid_size, (j+1)*actual_grid_size, (i+1)*actual_grid_size, j*actual_grid_size);
}
}
}
for (Layer l : layers) {
l.drawLayer(g, actual_grid_size, connectBox, gridSizeX, gridSizeY);
}
currentTool.paintSelf(g, actual_grid_size, null, curColor);
if (showGrid) {
g.setColor(Color.black);
for (int i = 0; i <= actual_grid_size * gridSizeX; i += actual_grid_size) {
g.drawLine(0, i, tWidth, i);
}
g.drawLine(tWidth - 1, 0, tWidth - 1, tHeight - 1);
for (int i = 0; i <= actual_grid_size * gridSizeY; i += actual_grid_size) {
g.drawLine(i, 0, i, tHeight);
}
g.drawLine(0, tHeight - 1, tWidth - 1, tHeight - 1);
}
} | 8 |
public Condition getCondition(String inName)
{
String strStore="Error opening file";
try
{
RandomAccessFile rafConditionDef = new RandomAccessFile("defConditions/"+inName.toLowerCase(), "r");
Condition cndStore = new Condition();
cndStore.NAME = inName;
strStore = rafConditionDef.readLine();
while (!(strStore == null || strStore.equals(".")))
{
if (strStore.equalsIgnoreCase("duration"))
{
cndStore.intDuration = Integer.parseInt(rafConditionDef.readLine());
}else if (strStore.equalsIgnoreCase("occurance"))
{
cndStore.intOccurance = Integer.parseInt(rafConditionDef.readLine());
}else if (strStore.equalsIgnoreCase("onstart"))
{
cndStore.strOnStart = rafConditionDef.readLine();
}else if (strStore.equalsIgnoreCase("onoccurance"))
{
cndStore.strOnOccurance = rafConditionDef.readLine();
}else if (strStore.equalsIgnoreCase("onend"))
{
cndStore.strOnEnd = rafConditionDef.readLine();
}else if (strStore.equalsIgnoreCase("nodisplay"))
{
cndStore.blnDisplay = false;
}
strStore = rafConditionDef.readLine();
}
rafConditionDef.close();
return cndStore;
}catch (Exception e)
{
LOG.printError("getCondition():Parsing \""+strStore+"\" for condition \""+inName+"\"", e);
}
return null;
} | 9 |
final void removeImageFetcher(Canvas canvas) {
do {
try {
anInt7906++;
if (((NativeToolkit) this).aCanvas7925 == canvas)
throw new RuntimeException();
if (!aHashtable8014.containsKey(canvas))
break;
method3911(canvas, 1, aHashtable8014.get(canvas));
aHashtable8014.remove(canvas);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
"wga.AG(" + (canvas != null
? "{...}"
: "null") + ')');
}
break;
} while (false);
} | 5 |
@Override
public void execute() {
try {
boolean newMember = false;
String membersList = controller.getConnection().get("members/list/?order=desc&sort=joindate");
Document doc = Jsoup.parse(membersList);
Elements links = doc.select("a.username");
Element link = links.first();
String username = link.text();
if (!username.equals(lastFoundUsername)) {
newMember = true;
lastFoundUsername = username;
}
if (newMember) {
logger.info("Found new user: " + lastFoundUsername);
String vcard = controller.getConnection().get("members/" + URLEncoder.encode(lastFoundUsername, "UTF-8") + "/?do=vcard");
BufferedReader reader = new BufferedReader(new StringReader(vcard));
String email = "";
String line;
while((line=reader.readLine()) != null) {
if (line.startsWith("EMAIL")) {
email = line.substring(line.indexOf(":") + 1);
}
}
JsonObject jsonObject = controller.member(lastFoundUsername);
JsonObject response = jsonObject.getAsJsonObject("response");
JsonObject prepared = response.getAsJsonObject("prepared");
int userId = prepared.get("userid").getAsInt();
Notifier.notify("\'" + lastFoundUsername + "\' Registered", email, new NotificationEventAdapter() {
@Override
public void clicked(NotificationEvent event) {
super.clicked(event);
DesktopUtilities.browse(controller.getUrl() + "/infraction.php?do=report&u=" + userId + "&evader=true");
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
} | 5 |
private void sendCommand(int level, String[] keywords, String hostname, String recipient) {
if (isAccountTypeOf(level, REGISTERED, MODERATOR, ADMIN)) {
if (keywords.length > 2) {
if (Functions.isNumeric(keywords[1])) {
int port = Integer.parseInt(keywords[1]);
String message = Functions.implode(Arrays.copyOfRange(keywords, 2, keywords.length), " ");
Server s = getServer(port);
if (s != null) {
if (Functions.getUserName(s.irc_hostname).equals(Functions.getUserName(hostname)) || isAccountTypeOf(level, MODERATOR)) {
s.in.println(message);
if (keywords[2].equalsIgnoreCase("sv_rconpassword") && keywords.length > 2) {
s.rcon_password = keywords[3];
}
sendMessage(recipient, "Command successfully sent.");
}
else
sendMessage(recipient, "You do not own this server.");
}
else
sendMessage(recipient, "Server does not exist.");
}
else
sendMessage(recipient, "Port must be a number!");
}
else
sendMessage(recipient, "Incorrect syntax! Correct syntax is .send <port> <command>");
}
} | 8 |
public WayOsm(List<Long> l){
if (l == null)
this.nodos = new ArrayList<Long>();
else
this.nodos = l;
shapes = new ArrayList<String>();
} | 1 |
public void connect() {
new Thread(new Runnable() {
@Override
public void run() {
if(isReconnectWorkerWorking()) {
reconnectWorker.shutdownNow();
}
preConnect();
sendNewInfo("Connecting to: " + host + ":" + port);
if(echoSocket == null) {
echoSocket = new Socket();
}
else {
disconnect();
echoSocket = new Socket();
}
try {
echoSocket.connect(new InetSocketAddress(host, port), 5000);
} catch (UnknownHostException e) {
sendNewInfo("Don't know about host: " + host + ":" + port);
resetConnection();
} catch (IOException e) {
sendNewInfo("Couldn't get I/O for the connection to: " + host + ":" + port);
resetConnection();
}
if(!echoSocket.isConnected()) {
resetConnection();
return;
}
sendNewInfo("Connected");
try {
sockObjOut = new ObjectOutputStream(echoSocket.getOutputStream());
sockObjOut.flush();
sockObjIn = new ObjectInputStream(echoSocket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
setConnectionChecker();
postConnect();
}
}).start();
//WindowController.getSendTextArea().setDisable(false);
//WindowController.getSubmitButton().setDisable(false);
} | 6 |
public ArrayList<String> loadBranch(){
ArrayList<String> branches = new ArrayList<String>();
int startLine = 0;
for(int lineNumber = 0;lineNumber < stringLines.size();lineNumber++){
String aString = stringLines.get(lineNumber);
if(aString.equals("branches:")){
startLine = lineNumber+1;
break;
}
}
for(int lineNumber = startLine;lineNumber < stringLines.size();lineNumber++){
String aString = stringLines.get(lineNumber);
if(aString == null){
break;
}else{
branches.add(aString);
}
}
return branches;
} | 4 |
public void createComponents() {
nextOutput = new JButton("Next");
previousOutput = new JButton("Previous");
deleteButton = new JButton("Delete");
leftPanel = new JPanel();
rightPanel = new JPanel();
mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
mainSplitPane.setContinuousLayout(true);
mainSplitPane.setOneTouchExpandable(true);
mainSplitPane.setResizeWeight(.5);
stdoutPanel = new JPanel(outputPanels);
stdoutPanel.setBorder(new TitledBorder(
new EtchedBorder(EtchedBorder.LOWERED), "Standard Output"));
stderrPanel = new JPanel(errorPanels);
stderrPanel.setBorder(new TitledBorder(
new EtchedBorder(EtchedBorder.LOWERED), "Standard Error"));
chainPanel = new FilterChainPanel(this);
clipboardPanel = new ClipboardPanel();
clipboardPanel.setBorder(new TitledBorder(
new EtchedBorder(EtchedBorder.LOWERED), "Clipboard"));
if (dataInput == null) {
//setSize(500, 500);
setSize(800, 800);
// Position
Dimension size = getSize();
Dimension screenSize = getToolkit().getScreenSize();
if (size.width > screenSize.width || size.height > screenSize.height) {
setLocation(0, 0);
} else {
setLocation((screenSize.width - size.width)/2,
(screenSize.height - size.height)/2);
}
} else {
try {
int version = dataInput.readInt();
switch(version) {
case 3:
setLocation(dataInput.readInt(), dataInput.readInt());
case 2:
Dimension size = new Dimension();
size.width = dataInput.readInt();
size.height = dataInput.readInt();
setSize(size);
break;
case 1:
setSize(300, 200);
}
clipboardPanel.readHistory(dataInput);
} catch (IOException e) {
// NYI
}
}
FilterEditPanel filterEditPanel = new FilterEditPanel(chainPanel);
commandPanel = new CommandPanel(this, directory, filterEditPanel);
setDefaultCommandHistory();
if (dataInput != null) {
commandPanel.readHistory(dataInput);
}
commandPanel.setBorder(new TitledBorder(
new EtchedBorder(EtchedBorder.LOWERED), "Command Entry"));
chainPanel.setSourceProvider(commandPanel.getSourceProvider());
chainPanel.setDestinationProvider(
commandPanel.getDestinationProvider());
chainPanel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String command = chainPanel.getSelectedValue();
commandPanel.setCommandLine(command);
}
});
} | 8 |
private void checkMeetings() {
Meeting holder = null;
if(!pastMeetingList.isEmpty()){
holder = pastMeetingList.get(0);
}
System.out.println("There are past meetings");
for(int i = 0; i < pastMeetingList.size(); i++){
if(holder.getDate().getTime().after(theCalendar.getTime())){
PastMeetingImpl newPast = (PastMeetingImpl) holder;
System.out.println("The Meeting " + newPast.getID() + " has now passed, please add notes:");
String notes = getInput();
addMeetingNotes(newPast.getID(), notes);
}
}
} | 3 |
public static double countOnes(double[] nums) {
int count = 0;
for (double num : nums) {
if (num == 1.0) {
count += 1;
}
}
// Return the negation of the count so we can still choose a hypothesis
// by the max
return -count;
} | 2 |
public void turn(long deltaMs) {
float targetAngleDeg = MathUtil.radToDeg(targetAngle);
float currentAngleDeg = MathUtil.radToDeg(angleRad);
WeaponsComponent wc = (WeaponsComponent)owner.getComponent("WeaponsComponent");
if(currentAngleDeg < targetAngleDeg - 1f) {
float amount = 0.0f;
if(targetAngleDeg - currentAngleDeg > 180) {
amount = -turnSpeed * deltaMs;
}
else {
amount = turnSpeed * deltaMs;
}
setAngleRad(angleRad + amount);
if(wc != null) {
wc.setReady(false);
}
}
else if(currentAngleDeg > targetAngleDeg + 1f) {
float amount = 0.0f;
if(currentAngleDeg - targetAngleDeg > 180) {
amount = turnSpeed * deltaMs;
}
else {
amount = -turnSpeed * deltaMs;
}
setAngleRad(angleRad + amount);
if(wc != null) {
wc.setReady(false);
}
}
else {
if(wc != null) {
wc.setReady(true);
}
}
if(angleRad < 0) {
angleRad += MathUtil.degToRad(360);
}
float over = angleRad - MathUtil.degToRad(360);
if(over > 0) {
angleRad = 0 + over;
}
} | 9 |
public Matrix _inverseSide() {
/**
* If the matrix has been augmented, solve so that the unaugmented
* portion is an identity matrix. Currently appears to be unable to
* handle zero entries - quite a problem if you ask me!
*/
if (augmented != null && rows == cols) {
Matrix matrix = duplicate();
for (int i = 0; i < cols; i++) {
matrix.print();
// Find largest value in column, then move that value to the top
// row.
int largest = 0;
float largestVal = -1;
for (int j = i; j < rows; j++) {
float val = Math.abs(matrix.get(j, i));
if (val > largest) {
largestVal = val;
largest = j;
}
}
if (largestVal == 0) {
return null; // Quit if col is all zeros.
}
if (largest != 0) {
matrix.flipRowsAug(i, largest);
}
scaleRowAug(i, 1 / get(i, i));
for (int j = 0; j < rows; j++) {
if (j != i) {
float scaleVal = matrix.get(j, i);
// Use i because matrix is square.
// Scale row, add to next row, then scale back. This can
// definitely be done faster.
matrix.scaleRowAug(i, -scaleVal);
matrix.addRowsAug(j, i);
matrix.scaleRowAug(i, -1 / scaleVal);
}
}
// Matrix is now upper triangle. Use backwards substitution to
// solve the rest.
}
return matrix;
} else {
return null;
}
} | 9 |
public void kirjoitaOikeanmuotoinenSisaltoTiedostolle(){
try {
PrintWriter kirjoitin = new PrintWriter(tiedosto);
kirjoitin.println("dog\t[dog]\tkoira\ttunniste1\tMELKEIN");
kirjoitin.println("cat\t[kät]\tkissa\ttunniste1\tEI");
kirjoitin.println("duck\t[dak]\tankka\ttunniste2\tOSATTU");
kirjoitin.close();
} catch (Exception e) {
}
} | 1 |
protected String getPackage(String uri) {
if (uri == null || uri.indexOf("/") == -1)
return "";
return uri.substring(0, uri.lastIndexOf("/"));
} | 2 |
public void run() throws IOException
{
Route53Driver driver = new Route53Driver(awsAccessKey, awsPrivateKey);
Zone zone = driver.zoneDetails(route53ZoneId);
if (cleanZone)
{
List<ZoneUpdateAction> deletes = new ArrayList<ZoneUpdateAction>();
for (ZoneResource resource : driver.listZoneRecords(zone))
{
if (!Arrays.asList(RecordType.NS, RecordType.SOA).contains(resource.getRecordType()))
{
ZoneUpdateAction zua = new ZoneUpdateAction.Builder().fromZoneResource(resource).buildDeleteAction();
deletes.add(zua);
}
}
for (List<ZoneUpdateAction> deleteChunk : ListUtil.split(deletes, 100))
{
ZoneChangeStatus status = driver.updateZone(zone, "Clean all zone records before re-import", deleteChunk);
driver.waitForSync(status);
}
}
if ("route53rrs".equals(nameServer))
{
queryService = new NameQueryByRoute53APIService(driver, zone);
}
else
{
queryService = new NameQueryServiceImpl(nameServer);
}
final List<ZoneUpdateAction> actions = createZoneUpdateActions(zone);
log.info("Zone Update Actions Created:\n{}", StringUtils.join(actions, "\n"));
if (dryRun)
{
log.info("Dry run complete.");
return;
}
int batch = 0;
final int MAX_CHANGE_RECORDS_ALLOWED = 100;
for (List<ZoneUpdateAction> processingList : ListUtil.split(actions, MAX_CHANGE_RECORDS_ALLOWED))
{
batch++;
ZoneChangeStatus sync = driver.updateZone(zone, "Sync zone records from file" + importFile + " batch " + batch, processingList);
driver.waitForSync(sync);
}
log.info("Zone import complete and INSYNC!");
} | 7 |
public void testWithFieldAdded7() {
Partial test = createHourMinPartial(23, 59, ISO_UTC);
try {
test.withFieldAdded(DurationFieldType.minutes(), 1);
fail();
} catch (IllegalArgumentException ex) {
// expected
}
check(test, 23, 59);
test = createHourMinPartial(23, 59, ISO_UTC);
try {
test.withFieldAdded(DurationFieldType.hours(), 1);
fail();
} catch (IllegalArgumentException ex) {
// expected
}
check(test, 23, 59);
} | 2 |
public Map(int width, int height, int current_x, int current_y, int heading) {
// System.out.println("Test1");
this.width = width;
this.heading = heading;
this.height = height;
mapNode = new Node[width][height];
for (int i = 0; i < this.width; i++) {// initilize nodes
for (int j = 0; j < this.height; j++) {
mapNode[i][j] = new Node(i, j);
}
}
for (int i = 0; i < this.width; i++) {// initilize node corridors
for (int j = 0; j < this.height; j++) {
int rightNode_i = i + 1;
int leftNode_i = i - 1;
int topNode_j = j - 1;
int bottomNode_j = j + 1;
if (rightNode_i < this.width) {// set node right
mapNode[i][j].getCorridor(3).setNode(
mapNode[rightNode_i][j]);
} else {
mapNode[i][j].getCorridor(3).setNode(null);
}
if (leftNode_i > -1) {// set node left
mapNode[i][j].getCorridor(1)
.setNode(mapNode[leftNode_i][j]);
} else {
mapNode[i][j].getCorridor(1).setNode(null);
}
if (topNode_j > -1) {
mapNode[i][j].getCorridor(0).setNode(mapNode[i][topNode_j]);
} else {
mapNode[i][j].getCorridor(0).setNode(null);
}
if (bottomNode_j < this.height) {
mapNode[i][j].getCorridor(2).setNode(
mapNode[i][bottomNode_j]);
} else {
mapNode[i][j].getCorridor(2).setNode(null);
}
}
}
current = mapNode[current_x][current_y];
} | 8 |
public long howMany(int size, int[] start, int[] end, int numMoves) {
long steps[][][] = new long[size][size][numMoves + 1];
steps[start[0]][start[1]][0] = 1;
for (int n = 1; n <= numMoves; n++) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (steps[i][j][n - 1] > 0) {
for (int m = 0; m < mx.length; m++) {
int nx = i + mx[m];
int ny = j + my[m];
if (nx < 0 || ny < 0 || nx >= size || ny >= size) continue;
steps[nx][ny][n] += steps[i][j][n - 1];
}
}
}
}
}
int a = 3;
return steps[end[0]][end[1]][numMoves];
} | 9 |
public void drawSquareCursor(int xc, int yc, byte size, Graphics bufferGraphics, int winZoom, int realZoom, int Zoom, int ScrollX, int ScrollY) {
for (int x = xc; x < xc + size; x++) {
if (x == xc || x == xc + size - 1)
{
for (int y = yc; y < yc + size; y++) {
drawCursorPoint(x, y, bufferGraphics, winZoom, realZoom, Zoom, ScrollX, ScrollY);
}
}
else
{
drawCursorPoint(x, yc, bufferGraphics, winZoom, realZoom, Zoom, ScrollX, ScrollY);
drawCursorPoint(x, yc + size - 1, bufferGraphics, winZoom, realZoom, Zoom, ScrollX, ScrollY);
}
}
if (size == 0)
drawCursorPoint(xc, yc, bufferGraphics, winZoom, realZoom, Zoom, ScrollX, ScrollY);
} | 5 |
public Object makeKey(byte[] uk, int bs) throws InvalidKeyException {
if (bs != DEFAULT_BLOCK_SIZE) {
throw new IllegalArgumentException();
}
if (uk == null) {
throw new InvalidKeyException("Empty key");
}
int len = uk.length;
if (len < 5 || len > 16) {
throw new InvalidKeyException("Key size (in bytes) is not in the range [5..16]");
}
Cast5Key result = new Cast5Key();
result.rounds = (len < 11) ? _12_ROUNDS : _16_ROUNDS;
byte[] kk = new byte[16];
System.arraycopy(uk, 0, kk, 0, len);
int z0z1z2z3, z4z5z6z7, z8z9zAzB, zCzDzEzF;
int z0, z1, z2, z3, z4, z5, z6, z7, z8, z9, zA, zB, zC, zD, zE, zF;
int x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, xA, xB, xC, xD, xE, xF;
int[] b;
int x0x1x2x3 = kk[ 0] << 24 | (kk[ 1] & 0xFF) << 16 | (kk[ 2] & 0xFF) << 8 | (kk[ 3] & 0xFF);
int x4x5x6x7 = kk[ 4] << 24 | (kk[ 5] & 0xFF) << 16 | (kk[ 6] & 0xFF) << 8 | (kk[ 7] & 0xFF);
int x8x9xAxB = kk[ 8] << 24 | (kk[ 9] & 0xFF) << 16 | (kk[10] & 0xFF) << 8 | (kk[11] & 0xFF);
int xCxDxExF = kk[12] << 24 | (kk[13] & 0xFF) << 16 | (kk[14] & 0xFF) << 8 | (kk[15] & 0xFF);
b = unscramble(x0x1x2x3); x0 = b[0]; x1 = b[1]; x2 = b[2]; x3 = b[3];
b = unscramble(x4x5x6x7); x4 = b[0]; x5 = b[1]; x6 = b[2]; x7 = b[3];
b = unscramble(x8x9xAxB); x8 = b[0]; x9 = b[1]; xA = b[2]; xB = b[3];
b = unscramble(xCxDxExF); xC = b[0]; xD = b[1]; xE = b[2]; xF = b[3];
z0z1z2z3 = x0x1x2x3 ^ S5[xD] ^ S6[xF] ^ S7[xC] ^ S8[xE] ^ S7[x8];
b = unscramble(z0z1z2z3); z0 = b[0]; z1 = b[1]; z2 = b[2]; z3 = b[3];
z4z5z6z7 = x8x9xAxB ^ S5[z0] ^ S6[z2] ^ S7[z1] ^ S8[z3] ^ S8[xA];
b = unscramble(z4z5z6z7); z4 = b[0]; z5 = b[1]; z6 = b[2]; z7 = b[3];
z8z9zAzB = xCxDxExF ^ S5[z7] ^ S6[z6] ^ S7[z5] ^ S8[z4] ^ S5[x9];
b = unscramble(z8z9zAzB); z8 = b[0]; z9 = b[1]; zA = b[2]; zB = b[3];
zCzDzEzF = x4x5x6x7 ^ S5[zA] ^ S6[z9] ^ S7[zB] ^ S8[z8] ^ S6[xB];
b = unscramble(zCzDzEzF); zC = b[0]; zD = b[1]; zE = b[2]; zF = b[3];
result.Km0 = S5[z8] ^ S6[z9] ^ S7[z7] ^ S8[z6] ^ S5[z2];
result.Km1 = S5[zA] ^ S6[zB] ^ S7[z5] ^ S8[z4] ^ S6[z6];
result.Km2 = S5[zC] ^ S6[zD] ^ S7[z3] ^ S8[z2] ^ S7[z9];
result.Km3 = S5[zE] ^ S6[zF] ^ S7[z1] ^ S8[z0] ^ S8[zC];
x0x1x2x3 = z8z9zAzB ^ S5[z5] ^ S6[z7] ^ S7[z4] ^ S8[z6] ^ S7[z0];
b = unscramble(x0x1x2x3); x0 = b[0]; x1 = b[1]; x2 = b[2]; x3 = b[3];
x4x5x6x7 = z0z1z2z3 ^ S5[x0] ^ S6[x2] ^ S7[x1] ^ S8[x3] ^ S8[z2];
b = unscramble(x4x5x6x7); x4 = b[0]; x5 = b[1]; x6 = b[2]; x7 = b[3];
x8x9xAxB = z4z5z6z7 ^ S5[x7] ^ S6[x6] ^ S7[x5] ^ S8[x4] ^ S5[z1];
b = unscramble(x8x9xAxB); x8 = b[0]; x9 = b[1]; xA = b[2]; xB = b[3];
xCxDxExF = zCzDzEzF ^ S5[xA] ^ S6[x9] ^ S7[xB] ^ S8[x8] ^ S6[z3];
b = unscramble(xCxDxExF); xC = b[0]; xD = b[1]; xE = b[2]; xF = b[3];
result.Km4 = S5[x3] ^ S6[x2] ^ S7[xC] ^ S8[xD] ^ S5[x8];
result.Km5 = S5[x1] ^ S6[x0] ^ S7[xE] ^ S8[xF] ^ S6[xD];
result.Km6 = S5[x7] ^ S6[x6] ^ S7[x8] ^ S8[x9] ^ S7[x3];
result.Km7 = S5[x5] ^ S6[x4] ^ S7[xA] ^ S8[xB] ^ S8[x7];
z0z1z2z3 = x0x1x2x3 ^ S5[xD] ^ S6[xF] ^ S7[xC] ^ S8[xE] ^ S7[x8];
b = unscramble(z0z1z2z3); z0 = b[0]; z1 = b[1]; z2 = b[2]; z3 = b[3];
z4z5z6z7 = x8x9xAxB ^ S5[z0] ^ S6[z2] ^ S7[z1] ^ S8[z3] ^ S8[xA];
b = unscramble(z4z5z6z7); z4 = b[0]; z5 = b[1]; z6 = b[2]; z7 = b[3];
z8z9zAzB = xCxDxExF ^ S5[z7] ^ S6[z6] ^ S7[z5] ^ S8[z4] ^ S5[x9];
b = unscramble(z8z9zAzB); z8 = b[0]; z9 = b[1]; zA = b[2]; zB = b[3];
zCzDzEzF = x4x5x6x7 ^ S5[zA] ^ S6[z9] ^ S7[zB] ^ S8[z8] ^ S6[xB];
b = unscramble(zCzDzEzF); zC = b[0]; zD = b[1]; zE = b[2]; zF = b[3];
result.Km8 = S5[z3] ^ S6[z2] ^ S7[zC] ^ S8[zD] ^ S5[z9];
result.Km9 = S5[z1] ^ S6[z0] ^ S7[zE] ^ S8[zF] ^ S6[zC];
result.Km10 = S5[z7] ^ S6[z6] ^ S7[z8] ^ S8[z9] ^ S7[z2];
result.Km11 = S5[z5] ^ S6[z4] ^ S7[zA] ^ S8[zB] ^ S8[z6];
x0x1x2x3 = z8z9zAzB ^ S5[z5] ^ S6[z7] ^ S7[z4] ^ S8[z6] ^ S7[z0];
b = unscramble(x0x1x2x3); x0 = b[0]; x1 = b[1]; x2 = b[2]; x3 = b[3];
x4x5x6x7 = z0z1z2z3 ^ S5[x0] ^ S6[x2] ^ S7[x1] ^ S8[x3] ^ S8[z2];
b = unscramble(x4x5x6x7); x4 = b[0]; x5 = b[1]; x6 = b[2]; x7 = b[3];
x8x9xAxB = z4z5z6z7 ^ S5[x7] ^ S6[x6] ^ S7[x5] ^ S8[x4] ^ S5[z1];
b = unscramble(x8x9xAxB); x8 = b[0]; x9 = b[1]; xA = b[2]; xB = b[3];
xCxDxExF = zCzDzEzF ^ S5[xA] ^ S6[x9] ^ S7[xB] ^ S8[x8] ^ S6[z3];
b = unscramble(xCxDxExF); xC = b[0]; xD = b[1]; xE = b[2]; xF = b[3];
result.Km12 = S5[x8] ^ S6[x9] ^ S7[x7] ^ S8[x6] ^ S5[x3];
result.Km13 = S5[xA] ^ S6[xB] ^ S7[x5] ^ S8[x4] ^ S6[x7];
result.Km14 = S5[xC] ^ S6[xD] ^ S7[x3] ^ S8[x2] ^ S7[x8];
result.Km15 = S5[xE] ^ S6[xF] ^ S7[x1] ^ S8[x0] ^ S8[xD];
// The remaining half is identical to what is given above, carrying on
// from the last created x0..xF to generate keys K17 - K32. These keys
// will be used as the 'rotation' keys and as such only the five least
// significant bits are to be considered.
z0z1z2z3 = x0x1x2x3 ^ S5[xD] ^ S6[xF] ^ S7[xC] ^ S8[xE] ^ S7[x8];
b = unscramble(z0z1z2z3); z0 = b[0]; z1 = b[1]; z2 = b[2]; z3 = b[3];
z4z5z6z7 = x8x9xAxB ^ S5[z0] ^ S6[z2] ^ S7[z1] ^ S8[z3] ^ S8[xA];
b = unscramble(z4z5z6z7); z4 = b[0]; z5 = b[1]; z6 = b[2]; z7 = b[3];
z8z9zAzB = xCxDxExF ^ S5[z7] ^ S6[z6] ^ S7[z5] ^ S8[z4] ^ S5[x9];
b = unscramble(z8z9zAzB); z8 = b[0]; z9 = b[1]; zA = b[2]; zB = b[3];
zCzDzEzF = x4x5x6x7 ^ S5[zA] ^ S6[z9] ^ S7[zB] ^ S8[z8] ^ S6[xB];
b = unscramble(zCzDzEzF); zC = b[0]; zD = b[1]; zE = b[2]; zF = b[3];
result.Kr0 = (S5[z8] ^ S6[z9] ^ S7[z7] ^ S8[z6] ^ S5[z2]) & 0x1F;
result.Kr1 = (S5[zA] ^ S6[zB] ^ S7[z5] ^ S8[z4] ^ S6[z6]) & 0x1F;
result.Kr2 = (S5[zC] ^ S6[zD] ^ S7[z3] ^ S8[z2] ^ S7[z9]) & 0x1F;
result.Kr3 = (S5[zE] ^ S6[zF] ^ S7[z1] ^ S8[z0] ^ S8[zC]) & 0x1F;
x0x1x2x3 = z8z9zAzB ^ S5[z5] ^ S6[z7] ^ S7[z4] ^ S8[z6] ^ S7[z0];
b = unscramble(x0x1x2x3); x0 = b[0]; x1 = b[1]; x2 = b[2]; x3 = b[3];
x4x5x6x7 = z0z1z2z3 ^ S5[x0] ^ S6[x2] ^ S7[x1] ^ S8[x3] ^ S8[z2];
b = unscramble(x4x5x6x7); x4 = b[0]; x5 = b[1]; x6 = b[2]; x7 = b[3];
x8x9xAxB = z4z5z6z7 ^ S5[x7] ^ S6[x6] ^ S7[x5] ^ S8[x4] ^ S5[z1];
b = unscramble(x8x9xAxB); x8 = b[0]; x9 = b[1]; xA = b[2]; xB = b[3];
xCxDxExF = zCzDzEzF ^ S5[xA] ^ S6[x9] ^ S7[xB] ^ S8[x8] ^ S6[z3];
b = unscramble(xCxDxExF); xC = b[0]; xD = b[1]; xE = b[2]; xF = b[3];
result.Kr4 = (S5[x3] ^ S6[x2] ^ S7[xC] ^ S8[xD] ^ S5[x8]) & 0x1F;
result.Kr5 = (S5[x1] ^ S6[x0] ^ S7[xE] ^ S8[xF] ^ S6[xD]) & 0x1F;
result.Kr6 = (S5[x7] ^ S6[x6] ^ S7[x8] ^ S8[x9] ^ S7[x3]) & 0x1F;
result.Kr7 = (S5[x5] ^ S6[x4] ^ S7[xA] ^ S8[xB] ^ S8[x7]) & 0x1F;
z0z1z2z3 = x0x1x2x3 ^ S5[xD] ^ S6[xF] ^ S7[xC] ^ S8[xE] ^ S7[x8];
b = unscramble(z0z1z2z3); z0 = b[0]; z1 = b[1]; z2 = b[2]; z3 = b[3];
z4z5z6z7 = x8x9xAxB ^ S5[z0] ^ S6[z2] ^ S7[z1] ^ S8[z3] ^ S8[xA];
b = unscramble(z4z5z6z7); z4 = b[0]; z5 = b[1]; z6 = b[2]; z7 = b[3];
z8z9zAzB = xCxDxExF ^ S5[z7] ^ S6[z6] ^ S7[z5] ^ S8[z4] ^ S5[x9];
b = unscramble(z8z9zAzB); z8 = b[0]; z9 = b[1]; zA = b[2]; zB = b[3];
zCzDzEzF = x4x5x6x7 ^ S5[zA] ^ S6[z9] ^ S7[zB] ^ S8[z8] ^ S6[xB];
b = unscramble(zCzDzEzF); zC = b[0]; zD = b[1]; zE = b[2]; zF = b[3];
result.Kr8 = (S5[z3] ^ S6[z2] ^ S7[zC] ^ S8[zD] ^ S5[z9]) & 0x1F;
result.Kr9 = (S5[z1] ^ S6[z0] ^ S7[zE] ^ S8[zF] ^ S6[zC]) & 0x1F;
result.Kr10 = (S5[z7] ^ S6[z6] ^ S7[z8] ^ S8[z9] ^ S7[z2]) & 0x1F;
result.Kr11 = (S5[z5] ^ S6[z4] ^ S7[zA] ^ S8[zB] ^ S8[z6]) & 0x1F;
x0x1x2x3 = z8z9zAzB ^ S5[z5] ^ S6[z7] ^ S7[z4] ^ S8[z6] ^ S7[z0];
b = unscramble(x0x1x2x3); x0 = b[0]; x1 = b[1]; x2 = b[2]; x3 = b[3];
x4x5x6x7 = z0z1z2z3 ^ S5[x0] ^ S6[x2] ^ S7[x1] ^ S8[x3] ^ S8[z2];
b = unscramble(x4x5x6x7); x4 = b[0]; x5 = b[1]; x6 = b[2]; x7 = b[3];
x8x9xAxB = z4z5z6z7 ^ S5[x7] ^ S6[x6] ^ S7[x5] ^ S8[x4] ^ S5[z1];
b = unscramble(x8x9xAxB); x8 = b[0]; x9 = b[1]; xA = b[2]; xB = b[3];
xCxDxExF = zCzDzEzF ^ S5[xA] ^ S6[x9] ^ S7[xB] ^ S8[x8] ^ S6[z3];
b = unscramble(xCxDxExF); xC = b[0]; xD = b[1]; xE = b[2]; xF = b[3];
result.Kr12 = (S5[x8] ^ S6[x9] ^ S7[x7] ^ S8[x6] ^ S5[x3]) & 0x1F;
result.Kr13 = (S5[xA] ^ S6[xB] ^ S7[x5] ^ S8[x4] ^ S6[x7]) & 0x1F;
result.Kr14 = (S5[xC] ^ S6[xD] ^ S7[x3] ^ S8[x2] ^ S7[x8]) & 0x1F;
result.Kr15 = (S5[xE] ^ S6[xF] ^ S7[x1] ^ S8[x0] ^ S8[xD]) & 0x1F;
return result;
} | 5 |
public boolean isIdentity() {
for (int x = 0; x < sizeX; ++x) {
for (int y = 0; y < sizeY; ++y) {
if (x == y) {
if ( Math.abs( values[ ( y * sizeX ) + x ] - 1.0f ) > 0.1f ) {
return false;
}
} else {
if (!Utils.eqFloat(0.0f, values[ ( y * sizeX ) + x ]))
return false;
}
}
}
return true;
} | 5 |
public static void loadLanguage(File file) {
String dirName = file.getParentFile().getName();
String fileName = file.getName();
String language = fileName.replace(Util.getFileExtension(fileName), "").replace(".", "");
if(!languages.containsKey(language)) {
languages.put(language, new Language(language));
}
try {
System.out.println("[LanguageManager] Loading language file: " + dirName + "/" + fileName);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while((line = reader.readLine()) != null) {
if(!line.startsWith("#") && line.contains("=")) {
String[] split = line.split("=");
if(split.length == 2) {
setLocatization(language, split[0], split[1]);
}
}
}
reader.close();
} catch(Exception e) {
System.err.println("[LanguageManger] Error while reading language file (" + fileName + "): ");
e.printStackTrace();
}
} | 6 |
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Action a = event.getAction();
ItemStack item = event.getItem();
if((a == Action.PHYSICAL) || (item == null) || (item.getType() == Material.AIR)) {
return;
}
if (item.getType() == Material.FIREWORK_CHARGE) {
}
} | 4 |
private boolean matches(ProcessingEnvironment procEnv, boolean strict,
List<? extends TypeMirror> parameterTypes,
List<? extends TypeMirror> expectedParameterTypes) {
if (parameterTypes.size() != expectedParameterTypes.size()) {
return false;
}
if (strict) {
for (int i = 0; i < parameterTypes.size(); i++) {
if (!procEnv.getTypeUtils().isSameType(
expectedParameterTypes.get(i), parameterTypes.get(i))) {
return false;
}
}
} else {
for (int i = 0; i < parameterTypes.size(); i++) {
if (!procEnv.getTypeUtils().isSubtype(
expectedParameterTypes.get(i), parameterTypes.get(i))) {
return false;
}
}
}
return true;
} | 8 |
public void pidWrite(double output) {
set(output);
} | 0 |
private void swap(int[] array, int left, int right){
int temp = array[left];
array[left] = array[right];
array[right] = temp;
} | 0 |
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
data = stream.readObject();
} | 0 |
public void run ()
{
while (true)
{
try
{
CommandSender sender = queue.take().get();
if (sender == null)
break;
autoUpdater.updateCheck();
autoUpdater.downloadLatestVersion();
sender.sendMessage(ChatColor.GREEN + "The latest version of "
+ ChatColor.RED + pluginName + ChatColor.GREEN
+ " has been downloaded! Reload for the changes to"
+ " take effect");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
} | 3 |
public void addHero(core.Hero hero)
{
if (lockCount != 0) return;
WidgetChooserButton button;
if (heroesSelected != -1) {
try {
button = (WidgetChooserButton)(heroesInner.itemAt(heroesSelected).widget());
button.setChecked(false);
} catch (NullPointerException e) {}
}
button = new WidgetChooserButton(hero, hero.getName(), true);
button.setChecked(true);
button.selected.connect(this, "selectHero(Object)");
heroesSelected = heroesInner.count();
heroesInner.insertWidget(-1, button);
heroes.add(hero);
minimap.repaint();
} | 3 |
public static ArrayList<ArrayList<Integer>> Biparticao(Graph grafo) {
int[] Cor = new int[grafo.getNlc()];
for (int i = 0; i < grafo.getNlc(); i++) {
if (Cor[i] == 0) {
Cor[i] = 1;
if (!Biparticao_Visit(grafo, i, Cor, 2)) {
return null;
}
}
}
ArrayList<ArrayList<Integer>> resultado = new ArrayList<ArrayList<Integer>>();
resultado.add(new ArrayList<Integer>());
resultado.add(new ArrayList<Integer>());
for (int i = 0; i < Cor.length; i++) {
if (Cor[i] == 1) {
resultado.get(0).add(i);
} else {
resultado.get(1).add(i);
}
}
return resultado;
} | 5 |
public Node removeFirst()
{
if(root == null) return null;
Node retNode = root;
root.next.prev = null;
root = root.next;
items--;
return retNode;
} | 1 |
public void run(){
BufferedReader br = null;
InetAddress addr = null;
ServerSocket servSock = null;
Socket cliSock = null;
try{
addr = InetAddress.getLocalHost();
servSock = new ServerSocket(3110, 5, addr);
}
catch(Exception e){
System.out.println("Creation of ServerSocket failed.");
System.exit(1);
}
while(true){
try{
cliSock = servSock.accept();
}
catch(Exception e){
System.out.println("Accept failed.");
System.exit(1);
}
try {
br = new BufferedReader(new InputStreamReader(cliSock.getInputStream()));
} catch (Exception e) {
System.out.println("Couldn't create socket input stream.");
System.exit(1);
}
try{
String fileName = br.readLine();
File file = new File(fileName);
if(file.isFile() && file.canRead()){
byte[] temp = new byte[(int)file.length()];
FileInputStream filestream = new FileInputStream(file);
BufferedInputStream bufstream = new BufferedInputStream(filestream);
bufstream.read(temp, 0, temp.length);
OutputStream outstream = cliSock.getOutputStream();
outstream.write(temp, 0, temp.length);
outstream.flush();
outstream.close();
bufstream.close();
filestream.close();
}
br.close();
cliSock.close();
}
catch(Exception e){
System.out.println("Error reading/writing file.");
System.exit(1);
}
}
} | 7 |
private void setupTopPanel() {
final Stage stage = view.getStage();
// File > Load File
view.topPanel.mItmLoadFile.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
FileChooser fileChooser = new FileChooser();
if (blueJInterface != null) { fileChooser.setInitialDirectory(blueJInterface.getWorkingDirectory()); }
FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("FXML files (*.fxml)", "*.fxml");
fileChooser.getExtensionFilters().add(filter);
File file = fileChooser.showOpenDialog(view.getStage());
openFile(file);
}
});
// File > Save File
view.topPanel.mItmSaveFile.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
saveFile();
}
});
// File > Close
view.topPanel.mItmClose.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
stage.close();
}
});
// File > Make Full Screen
view.topPanel.mItmFullScreen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
if (stage.isFullScreen()) {
stage.setFullScreen(false);
view.topPanel.mItmFullScreen.setText(LabelGrabber.getLabel("fullscreen.enable.text"));
} else {
stage.setFullScreen(true);
view.topPanel.mItmFullScreen.setText(LabelGrabber.getLabel("fullscreen.disable.text"));
}
}
});
//Add HistoryListener for the Undo/Redo menu items in the Edit menu
historyManager.addHistoryListener(new HistoryListener() {
@Override
public void historyUpdated(final HistoryUpdate historyUpdate) {
//Undo MenuItem
if (historyUpdate.canUndo()) {
view.topPanel.mItmUndo.setDisable(false);
view.topPanel.mItmUndo.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
historyManager.updateTo(historyUpdate.getCurrentIndex() - 1);
}
});
} else {
view.topPanel.mItmUndo.setDisable(true);
}
//Redo MenuItem
if (historyUpdate.canRedo()) {
view.topPanel.mItmRedo.setDisable(false);
view.topPanel.mItmRedo.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
historyManager.updateTo(historyUpdate.getCurrentIndex() + 1);
}
});
} else {
view.topPanel.mItmRedo.setDisable(true);
}
}
});
//Edit Menu > Delete button functionality
selectionManager.addSelectionListener(new SelectionListener() {
@Override
public void updateSelected(final GObject gObject) {
view.topPanel.mItmDelete.setDisable(false);
view.topPanel.mItmDelete.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
view.middleTabPane.viewPane.getChildren().remove(gObject);
selectionManager.clearSelection();
historyManager.addHistory(new HistoryItem() {
@Override
public void restore() {
view.middleTabPane.viewPane.getChildren().remove(gObject);
selectionManager.clearSelection();
}
@Override
public void revert() {
view.middleTabPane.viewPane.getChildren().add((Node) gObject);
selectionManager.updateSelected(gObject);
}
@Override
public String getAppearance() {
return gObject.getFieldName() + " deleted";
}
});
}
});
view.topPanel.mItmClearAll.setDisable(false);
view.topPanel.mItmClearAll.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
final List<Node> list = new ArrayList<>();
list.addAll(view.middleTabPane.viewPane.getChildren());
view.middleTabPane.viewPane.getChildren().clear();
selectionManager.clearSelection();
historyManager.addHistory(new HistoryItem() {
@Override
public void restore() {
for (Node n : list) {
view.middleTabPane.viewPane.getChildren().remove(n);
}
selectionManager.clearSelection();
}
@Override
public void revert() {
for (Node n : list) {
view.middleTabPane.viewPane.getChildren().add(n);
selectionManager.updateSelected((GObject) n);
}
}
@Override
public String getAppearance() {
return ("Clear All");
}
});
}
});
}
@Override
public void clearSelection() {
view.topPanel.mItmDelete.setDisable(true);
view.topPanel.mItmClearAll.setDisable(true);
}
});
// View > Show Hierarchy
view.topPanel.mItmHierarchy.setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
if (view.topPanel.mItmHierarchy.isSelected()) {
view.leftPanel.getItems().add(view.leftPanel.hierarchyTitledPane);
view.leftPanel.setDividerPosition(0, 0.6);
} else {
view.leftPanel.getItems().remove(view.leftPanel.hierarchyTitledPane);
}
}
});
// View > Show History
view.topPanel.mItmHistory.setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
toggleHistory();
}
});
view.topPanel.mItmAbout.setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
Stage stage = new Stage();
GridPane pane = new GridPane();
Label label = new Label(LabelGrabber.getLabel("about.text"));
label.setMaxWidth(300);
label.setWrapText(true);
label.setFont(new Font(18));
label.setTextAlignment(TextAlignment.CENTER);
ImageView imageview = new ImageView(new Image(getClass().getResourceAsStream("/bdl/icons/BlueJ_Orange_64.png")));
pane.add(imageview, 1, 1);
pane.add(label, 1, 2);
GridPane.setHalignment(imageview, HPos.CENTER);
stage.setScene(new Scene(pane));
stage.show();
}
});
} | 7 |
public static int getDirNr(Direction i) {
if (i == null) {
return 0;
}
switch (i) {
case TOP_LEFT:
return 0;
case TOP:
return 1;
case TOP_RIGHT:
return 2;
case BOT_RIGHT:
return 3;
case BOT:
return 4;
case BOT_LEFT:
return 5;
}
return 0;
} | 7 |
public void criarProjeto(Projeto projeto) throws SQLException {
Connection conexao = null;
PreparedStatement comando = null;
try {
conexao = BancoDadosUtil.getConnection();
comando = conexao.prepareStatement(SQL_INSERT_PROJETO);
comando.setString(1, projeto.getNome());
comando.setString(2, projeto.getDescricao());
comando.setDate(3, (Date) projeto.getDataInicio());
comando.setDate(4, (Date) projeto.getDataTermino());
comando.setString(5, projeto.getDepartamento().getCodigo());
comando.execute();
conexao.commit();
} catch (Exception e) {
if (conexao != null) {
conexao.rollback();
}
throw new RuntimeException(e);
} finally {
if (comando != null && !comando.isClosed()) {
comando.close();
}
if (conexao != null && !conexao.isClosed()) {
conexao.close();
}
}
} | 6 |
public static Document load(){
File folder = new File(SAVE_PATH);
System.out.println(folder.getAbsoluteFile());
File[] listOfFiles = folder.listFiles();
int count = 1;
ArrayList<String> files = new ArrayList<String>();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println(count + ") "+ listOfFiles[i].getName());
files.add(listOfFiles[i].getName());
count++;
}
}
System.out.println(count + ") Quit");
if (files.size()==0){
System.out.println("There are no documents to load");
return null;
}
int choice = InputHandler.getInt("", 1, count);
if (choice==count) return null;
try(
InputStream file = new FileInputStream(SAVE_PATH + files.get(choice-1));
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream (buffer);
){
Document document = (Document)input.readObject();
return document;
} catch (Exception e){
System.out.println("That is not a valid Document. ");
}
return null;
} | 5 |
public ArrayList<Advogado> Consultar(String id){
ArrayList<Advogado> advogados = new ArrayList<>();
if(id.equals("")){
try {
ConsultarSQL("SELECT * FROM tb_advogado", true);
while (rs.next()) {
Advogado advogado = new Advogado();
advogado.setIdAdvogado(rs.getString("id"));
advogado.setNome(rs.getString("nome"));
advogado.setCelular(rs.getString("cel"));
advogado.setCod(rs.getInt("cod"));
advogados.add(advogado);
}
} catch (SQLException ex) {
Logger.getLogger(DaoAdvogado.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
try {
ConsultarSQL("SELECT * FROM tb_advogado WHERE cod = '"+id+"'", true);
while (rs.next()) {
Advogado advogado = new Advogado();
advogado.setIdAdvogado(rs.getString("id"));
advogado.setNome(rs.getString("nome"));
advogado.setCelular(rs.getString("cel"));
advogado.setCod(rs.getInt("cod"));
advogados.add(advogado);
}
} catch (SQLException ex) {
Logger.getLogger(DaoAdvogado.class.getName()).log(Level.SEVERE, null, ex);
}
}
return advogados;
} | 5 |
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int cases = input.nextInt();
for (int q = 0; q < cases; ++q) {
int houses = input.nextInt();
int[] addresses = new int[houses];
for (int i = 0; i < houses; ++i) {
addresses[i] = input.nextInt();
}
Arrays.sort(addresses);
int median = (addresses[houses / 2] + addresses[(houses - 1) / 2]) / 2;
int median2 = (addresses[houses / 2] + addresses[(houses - 1) / 2]) / 2 + 1;
int distance = 0;
int distance2 = 0;
for (int i = 0; i < houses; ++i) {
distance += Math.abs(addresses[i] - median);
distance2 += Math.abs(addresses[i] - median2);
}
System.out.println(Math.min(distance, distance2));
}
} | 3 |
@Override
public boolean isOp() {
if(User.getOpChannels().contains(Message.getChannel())) return true;
else return false;
} | 1 |
public void getValues()
{
//Cost for printing
conf.printingCosts = new ArrayList<ItemStack>();
List<String> items = c.getStringList("PrintingCosts");
//Custom costs:
if (items != null)
for (String s : items)
conf.printingCosts.add(Utility.getItem(s));
//Default costs:
else
conf.printingCosts.add(new ItemStack(Material.INK_SACK, 1));
//Cost for clearing
conf.clearingCosts = new ArrayList<ItemStack>();
items = c.getStringList("ClearingCosts");
//Custom costs:
if (items != null)
for (String s : items)
conf.clearingCosts.add(Utility.getItem(s));
//Default costs:
else
conf.clearingCosts.add(new ItemStack(351, 3, (short)15));
conf.HungerLost = c.getInt("Player.HungerLost");
conf.MustBeAuthor= c.getBoolean("Player.MustBeAuthor");
conf.PressEffect = c.getBoolean("Press.Effect");
conf.DisableOnFactionLand = c.getBoolean("Protection.DisableOnFactionLand");
conf.DisableOnWorldGuardLand = c.getBoolean("Protection.DisableOnWorldGuardLand");
conf.Language = c.getString("Language");
//Attempt to load the language and display a message if it failed.
try
{
lang = Language.load(c.getString("Language"));
}
catch (FileNotFoundException e){this.getLogger().severe("Language file not found: languages/"+c.getString("Language")+".yml");e.printStackTrace(); }
catch (IOException e){this.getLogger().severe("Could not read language file: languages/"+c.getString("Language")+".yml");e.printStackTrace(); }
catch (InvalidConfigurationException e){this.getLogger().severe("Invalid language file: languages/"+c.getString("Language")+".yml");e.printStackTrace(); }
catch (IllegalArgumentException e){this.getLogger().severe("Illegal values in language file: languages/"+c.getString("Language")+".yml");e.printStackTrace(); }
catch (IllegalAccessException e){this.getLogger().severe("Can't access values in language file: languages/"+c.getString("Language")+".yml");e.printStackTrace(); }
conf.PressBlock = Utility.getMat(c.getString("Press.Block"));
conf.PressEffect = c.getBoolean("Press.Effect");
conf.CanClearWrittenBooks = c.getBoolean("Press.ClearingOptions.CanClearWrittenBooks");
conf.CanClearEnchantedBooks = c.getBoolean("Press.ClearingOptions.CanClearEnchantedBooks");
Bukkit.getPluginManager().registerEvents(new EventListener(), this);
} | 9 |
private void resetPosition(Tile current, int row, int col) {
if(current == null)return;
int x = getTileX(col);
int y = getTileY(row);
int distX = current.getX() - x;
int distY = current.getY() - y;
if(Math.abs(distX) < Tile.SLIDE_SPEED){
current.setX(current.getX() - distX);
}
if(Math.abs(distY) < Tile.SLIDE_SPEED){
current.setY(current.getY() - distY);
}
if(distX < 0){
current.setX(current.getX()+ Tile.SLIDE_SPEED);
}
if(distY < 0){
current.setY(current.getY() + Tile.SLIDE_SPEED);
}
if(distX > 0){
current.setX(current.getX() - Tile.SLIDE_SPEED);
}
if(distY > 0){
current.setY(current.getY() - Tile.SLIDE_SPEED);
}
} | 7 |
protected static void midpointDisplacement(final HeightField hf,
final int L, final int MX, final int MY, int range,
final float persist, final long seed) {
/*
* NOTE: A is (x1, y1) B is (x2, y2) A,B,C,D are the original "corner"
* points
*
* G
*
* B D
*
* H E I
*
* A C
*
* F
*/
Random r = new Random(seed);
for (int y = 0; y < MY; y += L) {
for (int x = 0; x < MX; x += L) {
hf.set(x, y, r.nextInt(256));
}
}
int step = L;
int halfStep = L / 2;
int x2, y2, midx, midy;
while (step >= 1) {
// Diamond step across entire array...
for (int y1 = 0; y1 < MY; y1 += step) {
for (int x1 = 0; x1 < MX; x1 += step) {
x2 = x1 + step;
y2 = y1 + step;
midx = x1 + halfStep;
midy = y1 + halfStep;
final int sum = hf.get(x1, y1) + hf.get(x1, y2)
+ hf.get(x2, y1) + hf.get(x2, y2);
hf.set(midx, midy, sum / 4 + perturb(r, range));
}
}
// Square step across entire array...
for (int y1 = 0; y1 < MY; y1 += step) {
for (int x1 = 0; x1 < MX; x1 += step) {
x2 = x1 + step;
y2 = y1 + step;
midx = x1 + halfStep;
midy = y1 + halfStep;
/*
* x1 mx x2 G
*
* B 4 D y2
*
* H 1 E 2 I midy
*
* A 3 C y1
*
* F
*/
int A = hf.get(x1, y1);
int B = hf.get(x1, y2);
int C = hf.get(x2, y1);
int D = hf.get(x2, y2);
int E = hf.get(midx, midy);
int F = hf.get(midx, y1 - halfStep);
int G = hf.get(midx, y2 + halfStep);
int H = hf.get(x1 - halfStep, midy);
int I = hf.get(x2 + halfStep, midy);
hf.set(x1, midy, (A + B + E + H) / 4); // 1
hf.set(x2, midy, (C + D + E + I) / 4); // 2
hf.set(midx, y1, (A + C + E + F) / 4); // 3
hf.set(midx, y2, (B + D + E + G) / 4); // 4
}
}
// Prepare for next iteration...
range *= persist;
step /= 2;
halfStep /= 2;
}
} | 7 |
private Handler parseRequest(InputStream inputStream) throws IOException, ServerException
{
String commandString = StreamUtil.readLine(inputStream);
if ("echo".equalsIgnoreCase(commandString)) {
Handler handler = new EchoHandler();
return handler;
}
else if ("reverse".equalsIgnoreCase(commandString)) {
Handler handler = new ReverseHandler();
return handler;
}
else if ("read".equalsIgnoreCase(commandString)) {
Handler handler = new ReadHandler();
return handler;
}
else if ("readObject".equalsIgnoreCase(commandString)) {
Handler handler = new ReadObjectHandler();
return handler;
}
else if ("write".equalsIgnoreCase(commandString)) {
Handler handler = new WriteHandler();
return handler;
}
else if ("writeObject".equalsIgnoreCase(commandString)) {
Handler handler = new WriteObjectHandler();
return handler;
}
else if ("delete".equalsIgnoreCase(commandString)) {
Handler handler = new DeleteHandler();
return handler;
}
else if ("directory".equalsIgnoreCase(commandString)) {
Handler handler = new DirectoryHandler();
return handler;
}
else {
throw new ServerException("Unknown Request: " + commandString);
}
} | 8 |
private boolean searchDownForPrevIntersectionNode( Node node, K key, Object[] ret ) {
while( true ) {
int c = mComp.compareMinToMax( node.mKey, key );
if( c < 0 ) {
// Node does not occur completely after mKey.
// Check if right subtree might intersect mKey.
if( node.mRight != null && mComp.compareMinToMax( key, node.mRight.mMaxStop.mKey ) < 0 ) {
node = node.mRight;
continue;
}
// Check if current node intersects.
if( mComp.compareMinToMax( key, node.mKey ) < 0 ) {
ret[0] = node;
return true;
}
}
// Check if left subtree might intersect.
if( node.mLeft != null && mComp.compareMinToMax( key, node.mLeft.mMaxStop.mKey ) < 0 ) {
node = node.mLeft;
continue;
}
// Request upward search from current node.
ret[0] = node;
return false;
}
} | 7 |
@Override
public void update(Observable obj, Object arg) {
if (arg instanceof IRemovable) {
if (((IRemovable) arg).needsRemoved()) {
// Stop observing this object as we no longer care about it
((IObservable) arg).deleteObserver(this);
remove(arg);
}
}
} | 2 |
public boolean deletePatient(Patient patient) {
if (nextPatient == null) {
return false;
} else if (nextPatient.name.equals(patient.name) && nextPatient.nextPatient != null) {
nextPatient = nextPatient.nextPatient;
nextPatient.previousPatient = this;
return true;
} else if (nextPatient.name.equals(patient.name) && nextPatient.nextPatient == null) {
nextPatient = null;
return true;
} else {
return nextPatient.deletePatient(patient);
}
} | 5 |
public Validator<T> getValidatorLHS() {
return validatorLHS;
} | 0 |
public List<Booking> getBookingsByDate(Calendar date) {
List<Booking> b = new ArrayList<Booking>();
Iterator<Booking> iter;
iter = bookings.iterator();
while (iter.hasNext()) {
Booking booking = iter.next();
if ((booking.getDate().get(Calendar.DAY_OF_MONTH) == date
.get(Calendar.DAY_OF_MONTH))
&& booking.getDate().get(Calendar.MONTH) == date
.get(Calendar.MONTH)
&& booking.getDate().get(Calendar.YEAR) == date
.get(Calendar.YEAR)) {
b.add(booking);
}
}
return b;
} | 4 |
private Language() {
supportedLanguages = new HashMap<String, Locale>();
supportedLanguages.put("language_english", Locale.ENGLISH);
supportedLanguages.put("language_german", Locale.GERMAN);
} | 0 |
static void checkAccess(final int access, final int possibleAccess) {
if ((access & ~possibleAccess) != 0) {
throw new IllegalArgumentException("Invalid access flags: "
+ access);
}
int pub = (access & Opcodes.ACC_PUBLIC) == 0 ? 0 : 1;
int pri = (access & Opcodes.ACC_PRIVATE) == 0 ? 0 : 1;
int pro = (access & Opcodes.ACC_PROTECTED) == 0 ? 0 : 1;
if (pub + pri + pro > 1) {
throw new IllegalArgumentException(
"public private and protected are mutually exclusive: "
+ access);
}
int fin = (access & Opcodes.ACC_FINAL) == 0 ? 0 : 1;
int abs = (access & Opcodes.ACC_ABSTRACT) == 0 ? 0 : 1;
if (fin + abs > 1) {
throw new IllegalArgumentException(
"final and abstract are mutually exclusive: " + access);
}
} | 8 |
public void setMetricType (SelectedTag d) {
if (d.getTags() == TAGS_SELECTION) {
m_metricType = d.getSelectedTag().getID();
}
if (m_significanceLevel != -1 && m_metricType != CONFIDENCE) {
m_metricType = CONFIDENCE;
}
if (m_metricType == CONFIDENCE) {
setMinMetric(0.9);
}
if (m_metricType == LIFT || m_metricType == CONVICTION) {
setMinMetric(1.1);
}
if (m_metricType == LEVERAGE) {
setMinMetric(0.1);
}
} | 7 |
public ConnectionLogger get_logger() {
return new ConsoleConnectionLogger("bogus_route", 0);
//throw new RuntimeException("not implemented");
} | 0 |
@Override
public boolean run() {
open(); // Open files
// Split size
long size = file.length();
if (verbose) Timer.showStdErr("Splitting file '" + fastqFile + "' into " + numSplits + " parts. File size: " + fileSizeStr(size) + " ( " + size + " bytes).");
long step = size / numSplits;
if (step < 0) error("Error: Split file size less than 1 byte!");
// Create each split
long start = 0, end = 0;
for (int i = 0; i < numSplits; i++) {
start = end; // Next byte
end = (i + 1) * step;
// Last split ends at file size or at record end
if (i == (numSplits - 1)) end = size;
else end = findRecordStart(end);
// Perform the split
split(i, start, end);
}
close();
if (verbose) Timer.showStdErr("Done.");
return true;
} | 5 |
public static void clearFolder(File folder){
if(folder.exists()) {
for(String file : folder.list()) {
if (new File(folder, file).isDirectory()){
//Logger.logInfo(new File(folder, file).toString());
clearFolder(new File(folder, file));
}
if(file.toLowerCase().endsWith(".zip") || file.toLowerCase().endsWith(".jar") || file.toLowerCase().endsWith(".disabled") || file.toLowerCase().endsWith(".litemod")) {
try {
boolean b = FileUtils.delete(new File(folder, file));
if(!b) Logger.logInfo("Error deleting " + file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} | 9 |
public Location findNearestCorner(Location destination){
//TOP LEFT
if (destination.mX < 300 && destination.mY < 300) {
return ContactList.cPERSONCORNERS.get(0);
}
//TOP RIGHT
if (destination.mX > 300 && destination.mY < 300) {
return ContactList.cPERSONCORNERS.get(1);
}
//BOTTOM RIGHT
if (destination.mX >= 300 && destination.mY > 300) {
return ContactList.cPERSONCORNERS.get(2);
}
//BOTTOM LEFT
if (destination.mX < 300 && destination.mY > 300) {
return ContactList.cPERSONCORNERS.get(3);
}
return null;
} | 8 |
public static RSInterface readHeaderChunk(JagexBuffer buffer) {
try {
int parentId = -1;
int interfaceId = buffer.getUnsignedShort();
if (interfaceId == 65535) {
parentId = buffer.getUnsignedShort();
interfaceId = buffer.getUnsignedShort();
}
RSInterface rsi = new RSInterface();
RSInterface.cache.put(interfaceId, rsi);
rsi.id = interfaceId;
rsi.parentId = parentId;
rsi.type = buffer.getUnsignedByte();
rsi.actionType = buffer.getUnsignedByte();
rsi.contentType = buffer.getUnsignedShort();
rsi.width = buffer.getUnsignedShort();
rsi.height = buffer.getUnsignedShort();
rsi.alpha = (byte) buffer.getUnsignedByte();
rsi.hoverId = buffer.getUnsignedByte();
if (rsi.hoverId != 0) {
rsi.hoverId = (rsi.hoverId - 1 << 8) + buffer.getUnsignedByte();
} else {
rsi.hoverId = -1;
}
int requiredmentIndex = buffer.getUnsignedByte();
if (requiredmentIndex > 0) {
rsi.valueCompareType = new int[requiredmentIndex];
rsi.requiredValues = new int[requiredmentIndex];
for (int index = 0; index < requiredmentIndex; index++) {
rsi.valueCompareType[index] = buffer.getUnsignedByte();
rsi.requiredValues[index] = buffer.getUnsignedShort();
}
}
int valueType = buffer.getUnsignedByte();
if (valueType > 0) {
rsi.valueIndexArray = new int[valueType][];
for (int valueIndex = 0; valueIndex < valueType; valueIndex++) {
int size = buffer.getUnsignedShort();
rsi.valueIndexArray[valueIndex] = new int[size];
for (int nextIndex = 0; nextIndex < size; nextIndex++) {
rsi.valueIndexArray[valueIndex][nextIndex] = buffer.getUnsignedShort();
}
}
}
return rsi;
} catch (Exception e) {
System.out.println("[Interface] An error occurred while reading the header chunk.");
e.printStackTrace();
}
return null;
} | 8 |
public Point2D echarAdvance(final char ech) {
// create a glyph vector for the char
float advance;
float advanceY;
// check cache for existing layout
String text = String.valueOf(ech);
Point2D.Float echarAdvance = echarAdvanceCache.get(text);
// generate metrics is needed
if (echarAdvance == null) {
// the glyph vector should be created using any toUnicode value if present, as this is what we
// are drawing, the method also does a check to apply differences if toUnicode is null.
char echGlyph = getCMapping(ech);
GlyphVector glyphVector = awtFont.createGlyphVector(
new FontRenderContext(new AffineTransform(), true, true),
String.valueOf(echGlyph));
FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
TextLayout textLayout = new TextLayout(String.valueOf(echGlyph), awtFont, frc);
// get bounds, only need to do this once.
maxCharBounds = awtFont.getMaxCharBounds(frc);
ascent = textLayout.getAscent();
descent = textLayout.getDescent();
GlyphMetrics glyphMetrics = glyphVector.getGlyphMetrics(0);
advance = glyphMetrics.getAdvanceX();
advanceY = glyphMetrics.getAdvanceY();
echarAdvanceCache.put(text,
new Point2D.Float(advance, advanceY));
}
// returned cashed value
else {
advance = echarAdvance.x;
advanceY = echarAdvance.y;
}
// widths uses original cid's, not the converted to unicode value.
if (widths != null && ech - firstCh >= 0 && ech - firstCh < widths.length) {
advance = widths[ech - firstCh] * awtFont.getSize2D();
} else if (cidWidths != null) {
Float width = cidWidths.get((int) ech);
if (width != null) {
advance = cidWidths.get((int) ech) * awtFont.getSize2D();
}
}
// find any widths in the font descriptor
else if (missingWidth > 0) {
advance = missingWidth / 1000f;
}
return new Point2D.Float(advance, advanceY);
} | 7 |
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
SeviceStrategy service = new MenuService();
String action = null;//action being performed
String[] delete = null;//array of deleted entrees
String name = null;//name of entree
String price = null;//price
String meal = null;//breakfast, lunch, or dinner
String id = null;//id of entree
int count = 0;//number of records updated
String cnt = null;//return to jsp page
action = request.getParameter("action");
/************** Delete Records *****************/
if(action.equalsIgnoreCase("delete")){
delete = request.getParameterValues("entree");
try{
count = service.deleteMenuItem(delete);
}catch(Exception e){
}
cnt = Integer.toString(count);
/*************** Add new Record ******************/
}else if(action.equalsIgnoreCase("new")){
name = request.getParameter("name");
price = request.getParameter("price");
meal = request.getParameter("meal");
try{
count = service.addNewMenuItem(price, meal, name);
cnt = Integer.toString(count);
}catch(Exception e){
}
/*************** Edit Record *********************/
}else if(action.equalsIgnoreCase("edit")){
id= request.getParameter("id");
name = request.getParameter("name");
price = request.getParameter("price");
meal = request.getParameter("meal");
try{
count = service.editEntreeItemById(id, price, meal, name);
}catch(Exception e){
}
cnt = Integer.toString(count);
}
/***************end of edit***********************/
if(cnt.equalsIgnoreCase("0")){
cnt = "Error";
}
request.setAttribute("cnt", cnt);
RequestDispatcher view =
request.getRequestDispatcher("/output.jsp");
view.forward(request, response);
} | 7 |
public static List<String> generateAllSentencesWithFilteredDefinitions(GRESCTask task) {
List<String> pSentences = new ArrayList<String>();
List<GRESCOption> options = task.getOptions().get(0);
for (GRESCOption option : options) {
String sentence = task.getSentence().replaceAll("%s", "\\(%s\\)");
String formattedSentence = String.format(sentence, option.getBlanks().toArray());
List<String> singleWord = new ArrayList<String>();
List<String> blank = new ArrayList<String>();
List<String> allWord = new ArrayList<String>();
// dictionary look up
for (String token : option.getBlanks()) {
if (!SparkUtils.isPhrase(token)) {
// it is a word
allWord.add("%s");
singleWord.add(token);
blank.add(token);
} else {
// it is a phrase
System.out.println(token);
allWord.add(token);
}
}
if (singleWord.size() > 0) {
String dictSentence = String.format(sentence, allWord.toArray());
List<String> singleWordTags = CoreNLPHelper.getHelper().tag(dictSentence, singleWord);
List<List<String>> singleWordDefinitions = new ArrayList<List<String>>();
// iterate the single word list and look up all single word using Pearson Dictionary
for (int i = 0; i < singleWord.size(); i++) {
PearsonHeadwordRequest request = new PearsonHeadwordRequest();
request.setHeadWord(singleWord.get(i));
try {
PearsonHeadwordResponse response = PearsonDictionary.getDictionary().lookupDictionary(request);
if (response != null) {
response.response(response.getJsonResponse());
List<PearsonDictionaryEntry> entries = response.getEntries();
Collection<PearsonDictionaryEntry> filteredEntries = new PearsonDictionaryEntryFilter(entries, singleWord.get(i)).
addPosTagFilter(PearsonDictionaryHelper.convert(singleWordTags.get(i))).
filter();
singleWordDefinitions.add(PearsonDictionary.getDictionary().getAllDefinitions(filteredEntries));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
singleWordDefinitions.get(i).add(singleWord.get(i));
}
// enumerate all possible combinations of the single word definitions
List<List<String>> enumerations = SparkUtils.enumerate(singleWordDefinitions);
for (List<String> ems : enumerations) {
StringBuilder dictFormattedSentence = new StringBuilder();
dictFormattedSentence.append(option.getOptionId());
dictFormattedSentence.append(":");
dictFormattedSentence.append(String.format(dictSentence, ems.toArray()));
pSentences.add(dictFormattedSentence.toString());
}
} else {
pSentences.add(formattedSentence);
}
}
return pSentences;
} | 9 |
ResultSetReference getResult(Connection conn, Parameter p) throws SQLException {
if (!p.has(1)) {
throw new UsageException(getUsage());
}
final String cmd = p.asString();
final String tableName = p.at(1);
final String option = p.at(2);
try {
DatabaseMetaData dbmeta = conn.getMetaData();
if (option.equalsIgnoreCase("FULL")) {
return getTableFullDescription(dbmeta, tableName, cmd);
} else if (option.equalsIgnoreCase("PK")) {
return getPrimaryKeyInfo(dbmeta, tableName, cmd);
} else if (option.equalsIgnoreCase("INDEX")) {
return getIndexInfo(dbmeta, tableName, cmd);
}
return getTableDescription(dbmeta, tableName, cmd);
} catch (Throwable th) {
if (th instanceof SQLException) {
throw (SQLException)th;
} else if (th instanceof RuntimeException) {
throw (RuntimeException)th;
}
throw new CommandException(th);
}
} | 7 |
public void mouseMoved(MouseEvent paramMouseEvent) {
if (ImageButton.this.Enabled)
{
if ((ImageButton.this.MouseOverImage != null) &&
(ImageButton.this.ImageMap != null))
{
if (ImageButton.this.checkMap(paramMouseEvent.getX(), paramMouseEvent.getY()) != null)
{
if (ImageButton.this.CurrentImage != ImageButton.this.MouseOverImage) {
ImageButton.this.rawSetImage(ImageButton.this.MouseOverImage);
return;
}
}
else if ((ImageButton.this.On) && (ImageButton.this.OnImage != null))
{
if (ImageButton.this.CurrentImage != ImageButton.this.OnImage) {
ImageButton.this.rawSetImage(ImageButton.this.OnImage);
return;
}
}
else if (ImageButton.this.CurrentImage != ImageButton.this.NormalImage)
ImageButton.this.rawSetImage(ImageButton.this.NormalImage);
}
}
} | 9 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Pessoa other = (Pessoa) obj;
if (this.idPessoa != other.idPessoa && (this.idPessoa == null || !this.idPessoa.equals(other.idPessoa))) {
return false;
}
return true;
} | 5 |
public void laggTillFramfor(Punkt horn, String hornNamn)
{
Punkt[] h = new Punkt[this.horn.length + 1];
for(int i = 0, i2 = 0; i < this.horn.length; i++, i2++)
{
if(i == findPunkt(hornNamn))
{
h[i] = horn;
i++;
}
h[i] = this.horn[i2];
}
this.horn = h;
} | 2 |
public DrawableComponent drawData()
{
if (opaque)
{
RenderUtil.setRenderingMode(this, RenderUtil.NORMAL_MODE);
}
else if (!opaque && loadAsModel)
{
RenderUtil.setRenderingMode(this, RenderUtil.MODEL_MODE);
}
else
{
System.err.println("Error: Can't specify rendering mode.");
System.exit(1);
}
return this;
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.