text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
protected void initVerifiers(int currVerSet) {
int idx = 0 ;
int currVerifierSet ;
if (currVerSet >=0 && currVerSet < NO_OF_LANGUAGES ) {
currVerifierSet = currVerSet ;
}
else {
currVerifierSet = nsPSMDetector.ALL ;
}
mVerifier = null ;
mStatisticsData = null ;
if ( currVerifierSet == nsPSMDetector.TRADITIONAL_CHINESE ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsBIG5Verifier(),
new nsISO2022CNVerifier(),
new nsEUCTWVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
mStatisticsData = new nsEUCStatistics[] {
null,
new Big5Statistics(),
null,
new EUCTWStatistics(),
null,
null,
null
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.KOREAN ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsEUCKRVerifier(),
new nsISO2022KRVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.SIMPLIFIED_CHINESE ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsGB2312Verifier(),
new nsGB18030Verifier(),
new nsISO2022CNVerifier(),
new nsHZVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.JAPANESE ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsSJISVerifier(),
new nsEUCJPVerifier(),
new nsISO2022JPVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.CHINESE ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsGB2312Verifier(),
new nsGB18030Verifier(),
new nsBIG5Verifier(),
new nsISO2022CNVerifier(),
new nsHZVerifier(),
new nsEUCTWVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
mStatisticsData = new nsEUCStatistics[] {
null,
new GB2312Statistics(),
null,
new Big5Statistics(),
null,
null,
new EUCTWStatistics(),
null,
null,
null
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.ALL ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsSJISVerifier(),
new nsEUCJPVerifier(),
new nsISO2022JPVerifier(),
new nsEUCKRVerifier(),
new nsISO2022KRVerifier(),
new nsBIG5Verifier(),
new nsEUCTWVerifier(),
new nsGB2312Verifier(),
new nsGB18030Verifier(),
new nsISO2022CNVerifier(),
new nsHZVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
mStatisticsData = new nsEUCStatistics[] {
null,
null,
new EUCJPStatistics(),
null,
new EUCKRStatistics(),
null,
new Big5Statistics(),
new EUCTWStatistics(),
new GB2312Statistics(),
null,
null,
null,
null,
null,
null
};
}
mClassRunSampler = ( mStatisticsData != null ) ;
mClassItems = mVerifier.length ;
}
| 8 |
private static FeatNode getNode(Long parentId, Long featId) {
if (containedFeats.contains(featId)) {
for (FeatNode n : nodes.values()) {
if (n.getFeat() == featId) {
nodes.get(n.getId()).getParents().add(parentId);
System.out.println("Node returned withour creating new");
System.out.println("Parents updates for: " + n.getFeat() + " New parents size: " + n.getParents().size());
return nodes.get(n.getId());
}
}
}
System.out.println("New feat created as child for " + nodes.get(parentId));
return new FeatNode(parentId, featId);
}
| 3 |
private String randomResource(int i) {
String resource; // String ressource a retourner
// Affecte la string ressource au cas par cas en fonction de la valeur de l'entier.
switch (i) {
case 0:
resource = "bois";
break;
case 1:
resource = "mouton";
break;
case 2:
resource = "ble";
break;
case 3:
resource = "argile";
break;
case 4:
resource = "minerai";
break;
default:
return "null";
}
return resource; // Retourne la string ressource.
}
| 5 |
public static String trimLeadingCharacter(String str, char leadingCharacter) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
sb.deleteCharAt(0);
}
return sb.toString();
}
| 3 |
public DetailedEditor(final Display display, final List<String> headerList,
final CSVRow row, String inCellDelimiter, String regexTableMarker) {
shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("Detailed CSV edition");
shell.setSize(800, 600);
// If there is more columns for the header than there is for the column,
// we had empty columns in the row
// It happen when the row's last columns are empty and separators are
// forgotten.
// The CSV reader can't guess there is a column to create
if (row.getNumberOfElements() > 0
&& headerList.size() > row.getNumberOfElements()) {
for (int i = row.getNumberOfElements() - 1; i < headerList.size(); i++) {
row.addElement("");
}
}
this.headerList = headerList;
this.row = row;
this.inCellDelimiter = inCellDelimiter;
this.regexTableMarker = regexTableMarker;
ScrolledComposite scrolledComposite = new ScrolledComposite(shell,
SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
Composite composite = new Composite(scrolledComposite, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
generateComponents(composite);
new Label(composite, SWT.NONE);
Composite compositeBtn = new Composite(composite, SWT.NONE);
GridData gd_compositeBtn = new GridData(SWT.LEFT, SWT.CENTER, false,
false, 1, 1);
gd_compositeBtn.heightHint = 55;
gd_compositeBtn.widthHint = 220;
compositeBtn.setLayoutData(gd_compositeBtn);
Button btnApply = new Button(compositeBtn, SWT.NONE);
btnApply.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
btnApply.setBounds(19, 14, 75, 30);
btnApply.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Selection:
updateRow();
shell.dispose();
break;
}
}
});
btnApply.setText("Apply");
Button btnCancel = new Button(compositeBtn, SWT.NONE);
btnCancel.setBounds(141, 14, 75, 30);
btnCancel.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Selection:
shell.dispose();
break;
}
}
});
btnCancel.setText("Cancel");
shell.setMinimumSize(400, 200);
scrolledComposite.setContent(composite);
scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT,
SWT.DEFAULT));
// The components must be filled only after the scrolled composite size
// has been set
// Otherwise the size of the scrolled composite would adapt its size to
// the content of its components
fillComponents();
}
| 5 |
static public boolean deleteDirectory(File path) {
if (path == null) return false;
try {
if( path.exists() ) {
Functions.clearDirectory(path);
}
return( path.delete() );
} catch (Throwable e) {
return false;
}
}
| 3 |
public synchronized void run() {
// go over all complete messages and process them.
while (_tokenizer.hasMessage()) {
String msg = _tokenizer.nextMessage();
String response = this._protocol.processMessage(msg);
if (response != null) {
try {
ByteBuffer bytes = _tokenizer.getBytesForMessage(response);
this._handler.addOutData(bytes);
} catch (CharacterCodingException e) { e.printStackTrace(); }
}
}
}
| 3 |
public boolean readFile(String filename, int k, BookmarkReader wikiReader, Integer minBookmarks, Integer maxBookmarks, Integer minResBookmarks, Integer maxResBookmarks) {
try {
this.filename = filename;
FileReader reader = new FileReader(new File("./data/results/" + filename + ".txt"));
BufferedReader br = new BufferedReader(reader);
String line = null;
while ((line = br.readLine()) != null) {
String[] lineParts = line.split("\\|");
String[] parts = lineParts[0].split("-");
int userID = Integer.parseInt(parts[0]);
int resID = -1;
if (parts.length > 1) {
resID = Integer.parseInt(parts[1]);
}
if (!Utilities.isEntityEvaluated(wikiReader, userID, minBookmarks, maxBookmarks, false) || !Utilities.isEntityEvaluated(wikiReader, resID, minResBookmarks, maxResBookmarks, true)) {
continue; // skip this user if it shoudln't be evaluated
}
List<String> realData = Arrays.asList(lineParts[1].split(", "));
if (lineParts.length > 2) {
List<String> predictionData = Arrays.asList(lineParts[2].split(", "));
if (predictionData.size() > 0) {
PredictionData data = new PredictionData(userID, realData, predictionData, k);
this.predictions.add(data);
this.predictionCount++;
} else {
//System.out.println("Line does not have predictions (inner)");
this.predictions.add(null);
}
} else {
//System.out.println("Line does not have predictions (outer)");
this.predictions.add(null);
}
}
if (k == 1) {
System.out.println("Number of users to predict: " + this.predictions.size());
}
br.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
| 8 |
public void testDividedBy_int() {
Years test = Years.years(12);
assertEquals(6, test.dividedBy(2).getYears());
assertEquals(12, test.getYears());
assertEquals(4, test.dividedBy(3).getYears());
assertEquals(3, test.dividedBy(4).getYears());
assertEquals(2, test.dividedBy(5).getYears());
assertEquals(2, test.dividedBy(6).getYears());
assertSame(test, test.dividedBy(1));
try {
Years.ONE.dividedBy(0);
fail();
} catch (ArithmeticException ex) {
// expected
}
}
| 1 |
protected void toString2(StringBuffer sbuf) {
super.toString2(sbuf);
sbuf.append(",\n stack={");
printTypes(sbuf, stackTop, stackTypes);
sbuf.append("}, locals={");
printTypes(sbuf, numLocals, localsTypes);
sbuf.append("}, inputs={");
if (inputs != null)
for (int i = 0; i < inputs.length; i++)
sbuf.append(inputs[i] ? "1, " : "0, ");
sbuf.append('}');
}
| 3 |
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ConsultaJogador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ConsultaJogador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ConsultaJogador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ConsultaJogador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
new ConsultaJogador().setVisible(true);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException ex) {
Logger.getLogger(ConsultaJogador.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(ConsultaJogador.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
| 8 |
public void actionPerformed(ActionEvent ev)
{
try
{
AreaFormacao objt = classeView();
if (obj == null)
{
long x = new AreaFormacaoDAO().inserir(objt);
objt.setId(x);
JOptionPane.showMessageDialog(null,
"Os dados foram inseridos com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
if (tabela != null)
tabela.adc(objt);
else
autocp.adicionar(objt);
}
else
{
new AreaFormacaoDAO().atualizar(objt);
JOptionPane.showMessageDialog(null,
"Os dados foram atualizados com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
tabela.edt(objt);
}
view.dispose();
}
catch (Exception e)
{
JOptionPane
.showMessageDialog(
null,
"Verifique se os campos estão preenchidos corretamente ou se estão repetidos",
"Alerta", JOptionPane.WARNING_MESSAGE);
}
}
| 3 |
@EventHandler
public void onItemSpawn(ItemSpawnEvent event)
{
SpoutBlock Block = (SpoutBlock) event.getLocation().getBlock();
Location loc = Block.getLocation();
loc.add(0, 1, 0);
SpoutBlock BlockAbove = (SpoutBlock) loc.getBlock();
CustomBlock CustomBlock = Block.getCustomBlock();
CustomBlock CustomBlockAbove = BlockAbove.getCustomBlock();
if(CustomBlock != null && CustomBlockAbove != null)
{
String[] SplitNameCustomBlock = CustomBlock.getFullName().split("\\.");
String[] SplitNameCustomBlockAbove = CustomBlockAbove.getFullName().split("\\.");
if(SplitNameCustomBlock[0].equals("CustomSlabs") && SplitNameCustomBlockAbove[0].equals("CustomSlabs"))
{
event.setCancelled(true);
}
}
}
| 4 |
public void setLoadOnDemand() {
if (loadOnDemand)
return;
loadOnDemand = true;
if ((Main.stripping & Main.STRIP_UNREACH) == 0) {
String fullNamePrefix = (fullName.length() > 0) ? fullName + "."
: "";
// Load all classes and packages now, so they don't get stripped
Enumeration enum_ = ClassInfo.getClassesAndPackages(getFullName());
while (enum_.hasMoreElements()) {
String subclazz = ((String) enum_.nextElement()).intern();
if (loadedClasses.containsKey(subclazz))
continue;
String subFull = (fullNamePrefix + subclazz).intern();
if (ClassInfo.isPackage(subFull)) {
PackageIdentifier ident = new PackageIdentifier(bundle,
this, subFull, subclazz);
loadedClasses.put(subclazz, ident);
swappedClasses = null;
ident.setLoadOnDemand();
} else {
ClassIdentifier ident = new ClassIdentifier(this, subFull,
subclazz, ClassInfo.forName(subFull));
if (GlobalOptions.verboseLevel > 1)
GlobalOptions.err
.println("preloading Class " + subFull);
loadedClasses.put(subclazz, ident);
swappedClasses = null;
bundle.addClassIdentifier(ident);
((ClassIdentifier) ident).initClass();
}
}
// Everything is loaded, we don't need to load on demand anymore.
loadOnDemand = false;
}
}
| 7 |
@Test
public void testOutputContacts() throws IOException {
cm.addFutureMeeting(contacts, new GregorianCalendar(2015,3,2));
cm.addNewPastMeeting(contacts, new GregorianCalendar(2013,5,3), "meeting");
cm.flush();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("contacts.txt"));
List inputData = null;
try {
inputData = (ArrayList) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException ex){
ex.printStackTrace();
}
}
List<Contact> inputContactList = (ArrayList) inputData.get(2);
assertEquals(inputContactList.get(0), alan);
}
| 2 |
public void run() {
RUNNING = true;
try {
notifier.setTimeCounter(notifier.getTimeCounter() - 1);
if (notifier.getTimeCounter() <= 0 && notifier.getOutputQ().size() > 0) {
List<EventBean> batch = new ArrayList<EventBean>();
notifier.getOutputQ().drainTo(batch);
for (EventBean evt : batch) {
evt.getHeader().setNotificationTime(System.currentTimeMillis());
}
EventBean[] evs = (EventBean[]) batch.toArray(new EventBean[0]);
notifier.getIoTerm().send(evs);
notifier.increaseNotificationCount(evs.length);
System.out.println("Timeout elapsed... " + evs.length + " events notified");
}
} catch (Exception ex) {
Logger.getLogger(Runner.class.getName()).log(Level.SEVERE, null, ex);
} finally {
RUNNING = false;
}
}
| 9 |
public void run() {
try {
while (this.dispatch()) {}
System.out.println("Finished queue");
} catch (IOException ex) {
Logger.getLogger(Queue.class.getName()).log(Level.SEVERE, null, ex);
}
}
| 2 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result
+ ((patronymic == null) ? 0 : patronymic.hashCode());
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
result = prime * result
+ ((userType == null) ? 0 : userType.hashCode());
return result;
}
| 5 |
public StorageDevice(String device) throws DBusException {
this.device = device;
boolean isOpticalDisc = false;
String connectionInterface = null;
/*
* The Udisks2 interface "Drive" reports *all* USB drives as removable,
* even those where /sys/block/[device]/removable is '0'.
* Because the value in /sys/block/[device]/removable is the correct one
* we use it instead of the more "modern" Udisks2 interface. :-P
*/
try {
removable = new FileReader(
"/sys/block/" + device + "/removable").read() == '1';
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "", ex);
}
boolean systemInternal = false;
if (DbusTools.DBUS_VERSION == DbusTools.DbusVersion.V1) {
vendor = DbusTools.getStringProperty(device, "DriveVendor");
model = DbusTools.getStringProperty(device, "DriveModel");
revision = DbusTools.getStringProperty(device, "DriveRevision");
serial = DbusTools.getStringProperty(device, "DriveSerial");
size = DbusTools.getLongProperty(device, "DeviceSize");
systemInternal = DbusTools.getBooleanProperty(
device, "DeviceIsSystemInternal");
connectionInterface = DbusTools.getStringProperty(
device, "DriveConnectionInterface");
isOpticalDisc = DbusTools.getBooleanProperty(
device, "DeviceIsOpticalDisc");
} else {
try {
List<String> interfaceNames
= DbusTools.getDeviceInterfaceNames(device);
String blockInterfaceName = "org.freedesktop.UDisks2.Block";
if (interfaceNames.contains(blockInterfaceName)) {
// query block device specific properties
systemInternal = DbusTools.getDeviceBooleanProperty(
device, blockInterfaceName, "HintSystem");
// query drive specific properties
String driveObjectPath = DbusTools.getDevicePathProperty(
device, blockInterfaceName, "Drive").toString();
if (driveObjectPath.equals("/")) {
// raid device
raid = true;
String raidObjectPath = DbusTools.getDevicePathProperty(
device, blockInterfaceName, "MDRaid").toString();
String raidInterface = "org.freedesktop.UDisks2.MDRaid";
raidLevel = DbusTools.getStringProperty(
raidObjectPath, raidInterface, "Level");
raidDeviceCount = DbusTools.getIntProperty(
raidObjectPath, raidInterface, "NumDevices");
size = DbusTools.getLongProperty(
raidObjectPath, raidInterface, "Size");
} else {
// non-raid device
String driveInterface = "org.freedesktop.UDisks2.Drive";
vendor = DbusTools.getStringProperty(
driveObjectPath, driveInterface, "Vendor");
model = DbusTools.getStringProperty(
driveObjectPath, driveInterface, "Model");
revision = DbusTools.getStringProperty(
driveObjectPath, driveInterface, "Revision");
serial = DbusTools.getStringProperty(
driveObjectPath, driveInterface, "Serial");
size = DbusTools.getLongProperty(
driveObjectPath, driveInterface, "Size");
connectionInterface = DbusTools.getStringProperty(
driveObjectPath, driveInterface, "ConnectionBus");
isOpticalDisc = DbusTools.getBooleanProperty(
driveObjectPath, driveInterface, "Optical");
}
}
} catch (SAXException | IOException |
ParserConfigurationException ex) {
LOGGER.log(Level.SEVERE, "", ex);
}
}
// little stupid heuristic to determine storage device type
if (isOpticalDisc) {
type = Type.OpticalDisc;
} else if (device.startsWith("mmcblk")) {
type = Type.SDMemoryCard;
} else if ((systemInternal == false)
&& "usb".equals(connectionInterface)) {
type = Type.USBFlashDrive;
} else {
type = Type.HardDrive;
}
}
| 9 |
public int GetBusCapacity()
{
//get the capacity of the bus
return busCapacity;
}
| 0 |
public void sortColors(int[] nums) {
int red = 0, white = 0, blue = 0;
for (int i=0; i<nums.length; i++) {
int j = nums[i];
if (j == 0)
red = red+1;
if (j == 1)
white = white + 1;
if (j == 2)
blue = blue + 1;
}
int tot = 0;
for (int i=0; i<red; i++, tot++)
nums[tot] = 0;
for (int i=0; i<white; i++, tot++)
nums[tot] = 1;
for (int i=0; i<blue; i++, tot++)
nums[tot] = 2;
}
| 7 |
public void addPatient(Patient newPatient){
if (this.nextPatient == null){
this.nextPatient = newPatient;
} else {
this.nextPatient.addPatient(newPatient);
}
}
| 1 |
protected void moveMinecartOnRail(int i, int j, int k)
{
int id = worldObj.getBlockId(i, j, k);
if (!BlockRail.isRailBlock(id))
{
return;
}
float railMaxSpeed = ((BlockRail)Block.blocksList[id]).getRailMaxSpeed(worldObj, this, i, j, k);
double maxSpeed = Math.min(railMaxSpeed, getMaxSpeedRail());
double mX = motionX;
double mZ = motionZ;
if(riddenByEntity != null)
{
mX *= 0.75D;
mZ *= 0.75D;
}
if(mX < -maxSpeed) mX = -maxSpeed;
if(mX > maxSpeed) mX = maxSpeed;
if(mZ < -maxSpeed) mZ = -maxSpeed;
if(mZ > maxSpeed) mZ = maxSpeed;
moveEntity(mX, 0.0D, mZ);
}
| 6 |
public String adding(String field, int min, int max)
{
String newField = "";
for(int i = 1; i <= field.length(); i++)
{
if(isNumber(field.substring(i - 1, i)))
{
newField = newField + field.substring(i - 1, i);
}
else
{
newField = "~invalid~";
break;
}
boolean over = false;
try
{
if(Integer.parseInt(newField) > max)
{
over = true;
}
}catch(Exception e)
{
System.out.println("not a integer");
}
if(over)
{
System.out.println(newField + " > " + max);
newField = "~invalid over~";
break;
}
}
boolean under = false;
try
{
if(Integer.parseInt(newField) < min)
{
under = true;
}
}catch(Exception e)
{
System.out.println("not a integer");
}
if(under)
{
newField = "~invalid under~";
}
newField = " ADD " + newField;
return newField;
}
| 8 |
public static void main(String[] args)
{
try {
PerlinGenerator perlin = new PerlinGenerator(new RNG(),100);
Display.setDisplayMode(new DisplayMode(1000,1000));
Display.create();
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight(), 0, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
int widthFactor = 1;
int[] classes = new int[1000];
for (int i =0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
double noise = perlin.noise(i, j, 0, 10);
classes[(int) Math.floor(noise*1000)]++;
}
}
/*for (int i = 1 ; i < classes.length; i++)
{
classes[i] += classes[i-1];
}*/
while(!Display.isCloseRequested())
{
// Clear the screen and depth buffer
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
for (int i = 0; i < classes.length; i++)
{
GL11.glColor3f(1-i/1000.0f,i/1000.0f,0);
// draw quad
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(widthFactor*i,Display.getDisplayMode().getHeight());
GL11.glVertex2f(widthFactor*(i+1),Display.getDisplayMode().getHeight());
GL11.glVertex2f(widthFactor*(i+1),Display.getDisplayMode().getHeight()-classes[i]*20);
GL11.glVertex2f(widthFactor*i,Display.getDisplayMode().getHeight()-classes[i]*20);
GL11.glEnd();
}
Display.update();
}
Display.destroy();
} catch (LWJGLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| 5 |
public static void main(String args[]) {
try {
System.out.println("RS2 user client - release #" + 317);
if (args.length != 5) {
System.out.println("Usage: node-id, port-offset, [lowmem/highmem], [free/members], storeid");
return;
}
Client.nodeID = Integer.parseInt(args[0]);
Client.portOff = Integer.parseInt(args[1]);
if (args[2].equals("lowmem")) {
Client.setLowMem();
} else if (args[2].equals("highmem")) {
Client.setHighMem();
} else {
System.out.println("Usage: node-id, port-offset, [lowmem/highmem], [free/members], storeid");
return;
}
if (args[3].equals("free")) {
Client.isMembers = false;
} else if (args[3].equals("members")) {
Client.isMembers = true;
} else {
System.out.println("Usage: node-id, port-offset, [lowmem/highmem], [free/members], storeid");
return;
}
Signlink.storeid = Integer.parseInt(args[4]);
Signlink.startpriv(InetAddress.getLocalHost());
Client client = new Client();
client.initGameFrame(503, 765);
} catch (Exception exception) {
}
}
| 6 |
public int getIntelligence(){
int value = 0;
for (Armor armor : armorList) {
if(armor != null) value += armor.getStats().getIntelligence();
}
return value;
}
| 2 |
public void removeActionListener(ActionListener l) {
if(l == null) {
return;
}
actionListener = null;
}
| 1 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Pontuacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Pontuacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Pontuacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Pontuacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Pontuacao().setVisible(true);
}
});
}
| 6 |
public static IList<Integer> merge(IList<Integer> l1, IList<Integer> l2) {
// If one of the two lists is empty return the other one
if (l1.isempty())
return l2;
if (l2.isempty())
return l1;
IList<Integer> merged = new MLinkedList<Integer>();
// Get the first Node as node object from both lists
INode<Integer> mint1 = l1.getFirst();
INode<Integer> mint2 = l2.getFirst();
// while the current node is not empty iterate over both lists and
// append
while (mint1 != null && mint2 != null) {
if (mint1.getElem() < mint2.getElem()) {
merged.append(mint1.getElem());
mint1 = mint1.getNext();
} else {
merged.append(mint2.getElem());
mint2 = mint2.getNext();
}
}
// The problem is that the while loop before could terminate before all
// elements of both lists are appended
// example: [1,2,3] [1,2,3,4] -> the while before terminates at idx=2,
// the second list still has a four at idx=3. For both cases we have to
// call next on the rest of the list until both are empty. In One case
// the while terminates without iteration and the other will append all
// of the elements.
while (mint1 != null) {
merged.append(mint1.getElem());
mint1 = mint1.getNext();
}
while (mint2 != null) {
merged.append(mint2.getElem());
mint2 = mint2.getNext();
}
return merged;
}
| 7 |
public static void main(String[] args) {
if(true || true){
System.out.println(1);
}
if(true || false){
System.out.println(2);
}
if(false || true){
System.out.println(3);
}
if(false || false){
System.out.println(4);
}
}
| 8 |
private int getNeighbours(int x, int y) {
int nNeighbours = 0;
for (int deltaX = -1; deltaX <= 1; deltaX++) {
int nextX = x + deltaX;
if (nextX == width) {
// nextX = 0;
continue;
} else if (nextX < 0) {
// nextX = width - 1;
continue;
}
for (int deltaY = -1; deltaY <= 1; deltaY++) {
if ((deltaX == 0) && (deltaY == 0)) {
continue;
}
int nextY = y + deltaY;
if (nextY == height) {
// nextY = 0;
continue;
} else if (nextY < 0) {
// nextY = height - 1;
continue;
}
if (getCellAt(nextX, nextY))
nNeighbours++;
}
}
return nNeighbours;
}
| 9 |
public void testCoherence() {
LinkedElement<E> elemf = first;
LinkedElement<E> elemb = last;
for (int i = 1; i < total; i++) {
System.out.println(elemf + "\t| " + elemb);
elemf = elemf.getNext();
elemb = elemb.getPrev();
}
System.out.println(elemf + "\t| " + elemb);
System.out.println("LL Coherence:\tforward: " + (elemf == last) + "\tbackward: " + (elemb == first));
}
| 1 |
void prepareData() {
int numPoints = Math.min(MAX_DATA_POINTS, x.length);
if( x.length > numPoints ) subsample(numPoints);
// Find min & max values
minX = Double.MAX_VALUE;
maxX = Double.MIN_VALUE;
minY = Double.MAX_VALUE;
maxY = Double.MIN_VALUE;
for( int i = 0; (i < x.length) && (i < numPoints); i++ ) {
double xx = x[i];
minX = Math.min(minX, xx);
maxX = Math.max(maxX, xx);
double yy = y[i];
minY = Math.min(minY, yy);
maxY = Math.max(maxY, yy);
}
if( minY == maxY ) minY = 0; // Otherwise the plot does not show anything when the variance is zero
// Iterate over all sorted keys
dataList = new ArrayList<Integer>();
labelList = new ArrayList<String>();
int labelEvery = Math.max(numPoints / numberLabelsXaxis, 10);
for( int i = 0; i < numPoints; i++ ) {
double xx = x[i];
// Make sure the last point has a coordinate
if( (i % labelEvery == 0) || (i == (x.length - 1)) || (i == (numPoints - 1)) ) labelList.add(Double.toString(xx));
else labelList.add("");
double yy = y[i];
int scaledY = (int) ((100.0 * (yy - minY)) / (maxY - minY)); // 'Count' scaled form 0 to 100
dataList.add(scaledY);
}
}
| 8 |
public static String getConstructorDescriptor(final Constructor<?> c) {
Class<?>[] parameters = c.getParameterTypes();
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < parameters.length; ++i) {
getDescriptor(buf, parameters[i]);
}
return buf.append(")V").toString();
}
| 3 |
public byte read() {
int value = 0;
value |= pins[0].read() ? 1 << 0 : 0;
value |= pins[1].read() ? 1 << 1 : 0;
value |= pins[2].read() ? 1 << 2 : 0;
value |= pins[3].read() ? 1 << 3 : 0;
value |= pins[4].read() ? 1 << 4 : 0;
value |= pins[5].read() ? 1 << 5 : 0;
value |= pins[6].read() ? 1 << 6 : 0;
value |= pins[7].read() ? 1 << 7 : 0;
return (byte) value;
}
| 8 |
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
//Set window properties
this.setLocationRelativeTo(null);
this.setIconImage(Resources.getImageResource("icon.png").getImage());
popupDialog.setIconImage(Resources.getImageResource("icon.png").getImage());
UpdateLogoLabel.setIcon(Resources.getImageResource("update.png"));
popupDialogImageLabel.setIcon(Resources.getImageResource("alert.png"));
SimpleSwingWorker worker = new SimpleSwingWorker() {
@Override
protected void task() {
//Copy updates
copyDirectoryAndBackUpOldFiles(new File("./launcherpatch"), new File(".."));
//Load version config
JSONObject versionConfig;
try {
versionConfig = (JSONObject)JSONValue.parse(FileUtils.readFileToString(new File("./version.json")));
} catch (IOException ex) {
showPopupDialog("Warning: The version file could not be updated! This may cause problems.");
System.exit(0);
return;
}
//Get new version from arguments
String newVersion = "0";
for (String arg : Arguments) {
if (arg.startsWith("--version=")) {
newVersion = arg.substring(10);
break;
}
}
//Save new version file
try {
versionConfig.put("moddleversion", newVersion);
FileUtils.writeStringToFile(new File("./version.json"), versionConfig.toJSONString());
} catch (IOException ex) {
showPopupDialog("Warning: The version file could not be updated! This may cause problems.");
System.exit(0);
return;
}
//Start Moddle
try {
ProcessBuilder moddle = new ProcessBuilder(new String[] { "javaw.exe", "-jar", "\"" + new File("../Moddle.jar").getCanonicalPath() + "\"" });
moddle.directory(new File(".."));
moddle.start();
} catch (IOException ex) {
try {
ProcessBuilder moddle = new ProcessBuilder(new String[] { "javaw.exe", "-jar", "\"../Moddle.jar\"" });
moddle.directory(new File(".."));
moddle.start();
} catch (IOException ex2) { showPopupDialog("Failed to start Moddle!"); }
}
//Exit
System.exit(0);
}
};
worker.execute();
}//GEN-LAST:event_formWindowOpened
| 6 |
@Override
public boolean equals(Object obj) {
if(obj == null || !(obj instanceof Triangle)) {
return false;
}
return this.side1.compareTo(((Triangle)obj).getSide1()) == 0
&& this.side2.compareTo(((Triangle)obj).getSide2()) == 0
&& this.side3.compareTo(((Triangle)obj).getSide3()) == 0;
}
| 4 |
public static void main(String[] args) {
Config.load();
String driver = "com.mysql.jdbc.Driver";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(Config.db_host+Config.db_db, Config.db_user, Config.db_password);
GameQueues.create();
ServerListener.start();
} catch(SQLException ex)
{
LOGGER.log(Level.SEVERE, "Couldn't connect to database (" + driver + ").");
} catch (Exception ex)
{
LOGGER.log(Level.SEVERE,ex.toString(),ex);
} finally {
try{
if(conn!=null)
conn.close();
} catch(SQLException se){
se.printStackTrace();
}
}
}
| 4 |
protected boolean isLastSignMathExpression()
{
return lastCharacter().equals("*") || lastCharacter().equals("/")
|| lastCharacter().equals("+") || lastCharacter().equals("-")
|| lastCharacter().equals("^");
}
| 4 |
public void destroy(String filename) throws Exception {
int fileDescriptorIndex = findIndexOfFileDescriptor(filename,true);
for(int i = 0; i < oft.index.length; i++) {
if (oft.index[i] == fileDescriptorIndex) {
System.out.println("Closing before destroying: " + i);
close(i);
}
}
FileDescriptor fd = FileDescriptor.getFileDescriptorInfo(fileDescriptorIndex);
//Clear bitmap
for(int i = 0; i <fd.blocks.length; i++){
if(fd.blocks[i] != -1){
setBitZero(fd.blocks[i]);
}
}
//Free file descriptor
int byteIndex = 1 * IOSystem.SIZE_OF_BLOCK_IN_BYTES + (fileDescriptorIndex * FileSystem.DESCRIPTOR_SIZE_IN_BYTES);
int blockNumber = (int) Math.floor(byteIndex/IOSystem.SIZE_OF_BLOCK_IN_BYTES); //Figure out which block this byte is in, and read in that block
int memIndex = byteIndex % IOSystem.SIZE_OF_BLOCK_IN_BYTES; //Beacuse we are reading in one block, we must offset the aboslute byte location by the read-in block's location
byte[] mem = IOSystem.readBlock(blockNumber);
for(int i = memIndex; i < memIndex + 4 * FileSystem.SIZE_OF_INT_IN_BYTES; i++) {
mem[i] = -1;
}
IOSystem.writeBlock(blockNumber, mem);
writer.write(filename + " destroyed");
writer.newLine();
}
| 5 |
public ArrayList<Airport> searchAirport(String searchString) {
ArrayList<Airport> result = new ArrayList<Airport>();
for (Airport a : getAirports()) {
if (a.getCity().contains(searchString)) {
result.add(a);
} else if (a.getCountry().getCountry().contains(searchString)) {
result.add(a);
} else if (a.getName().contains(searchString)) {
result.add(a);
} else if (a.getCode().contains(searchString)) {
result.add(a);
} else if (String.valueOf(a.getId()).contains(searchString)) {
result.add(a);
}
}
return result;
}
| 6 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VtnListaReproduccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VtnListaReproduccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VtnListaReproduccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VtnListaReproduccion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
VtnListaReproduccion dialog = new VtnListaReproduccion(new javax.swing.JFrame(), true);
public void run() {
VtnListaReproduccion dialog = new VtnListaReproduccion(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
| 6 |
public void play() {
long no = 1;
try {
while (true) {
if (1 == (no % 2)) {
JchessEntity jchess = new JchessEntity(data.generate(1));
Command cmd = player1.play(jchess);
if (cmd.isGiveup()) {
throw new CommandException(1, "܂B");
}
data.command(1, cmd);
} else {
JchessEntity jchess = new JchessEntity(data.generate(2));
Command cmd = player2.play(jchess);
if (cmd.isGiveup()) {
throw new CommandException(1, "܂B");
}
data.command(2, cmd);
}
no++;
}
} catch (CommandException ex) {
System.out.println(ex.getPlayer() + ":" + ex.getMessage());
}
}
| 5 |
public FieldAnalyzer(ClassAnalyzer cla, FieldInfo fd, ImportHandler i) {
clazz = cla;
imports = i;
modifiers = fd.getModifiers();
type = Type.tType(fd.getType());
fieldName = fd.getName();
constant = null;
this.isSynthetic = fd.isSynthetic();
this.isDeprecated = fd.isDeprecated();
if (fd.getConstant() != null) {
constant = new ConstOperator(fd.getConstant());
constant.setType(type);
constant.makeInitializer(type);
}
}
| 1 |
final void instrument(final Map<Integer, Set<Instrument>> instruments) {
int countTotal = 0;
for (final Set<Instrument> is : instruments.values()) {
for (final Instrument i : is) {
if (i.uniqueIdx()) {
final Integer countOld = this.countMap.get(i.type());
if (countOld == null) {
this.countMap.put(i.type(), 1);
} else {
this.countMap.put(i.type(), countOld.intValue() + 1);
}
++countTotal;
}
}
}
this.TOTAL_NUM.value(String.valueOf(countTotal));
this.map.putAll(instruments);
}
| 4 |
@Override
public String toString()
{
return "Item ID: \t" + iD + "\nName: \t\t" + name + "\nRange: \t\t" + minRange + "~" + maxRange + "\nAtt/M.Att: \t" + atk + "/" + mAtk + "\nAccuracy: \t" + acc + "\nCritical: \t" + crit + "\nSale Price: \t" + value;
}
| 0 |
protected static String parseAsBooleanString(String[] args) {
return parseAsBoolean(args)? Argument.argTrue:Argument.argFalse;
}
| 1 |
public static void readSort() {
try {
File file = new File("data/sort.txt");
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(
new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
dealSortStr(lineTxt);
}
read.close();
}
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println(map.size());
}
| 4 |
public static int[] selection(int[] array) {
if(array==null || array.length==0) return array;
int minIndex;
int tmp;
int cnt=0;
for(int i=0;i<array.length;++i) {
minIndex = i;
for(int j=i;j<array.length;++j) {
cnt++;
if(array[minIndex]>array[j]) minIndex=j;
}
tmp = array[i];
array[i]=array[minIndex];
array[minIndex]=tmp;
}
System.out.print("Selection sort, N="+array.length+", Excution times="+cnt+", Extra Space=0");
return array;
}
| 5 |
public Prime(int n) {
max = n;
bitSet = new BitSet(max + 1);
if (max > 1){
bitSet.set(0, 2, false);
bitSet.set(2, max + 1, true);
for (long i = 2; i * i <= max; ++i) {
if (isPrime((int) i)) {
for (long j = i * i; j <= max; j += i) {
bitSet.set((int) j, false);
}
}
}
}
primeCount = bitSet.cardinality();
}
| 4 |
@Override
public Auction bid(String username, int itemId) {
searches.get(searches.get(itemId));
for(Auction auc : searches.values()){
if(searches.get(itemId) != null){
auc.setCurrentBid(auc.getCurrentBid()+1);
// auc.currentBid++;
auc.setOwner(username);
return auc;
}
}
return null;
}
| 2 |
public CarBuilder setElectricBrakes(boolean electricBrakes) {
delegate.setElectricBrakes(electricBrakes);
return this;
}
| 0 |
public static void main(String[] args) {
// Teste de repositorio
// Teste 1100912
}
| 0 |
public Tile getTile(int i) {
try {
return tiles.get(i);
} catch (ArrayIndexOutOfBoundsException a) {}
return null;
}
| 1 |
public Gameplay(AntBrain red, AntBrain black) {
this.world = new World();
this.random = new RandomInt();
this.rand = new Random();
this.redFood = 0;
this.blackFood = 0;
this.redAntBrain = red;
this.blackAntBrain = black;
this.ants = new ArrayList<>();
}
| 0 |
public static String mksmiley(String str) {
synchronized (smileys) {
for (Pattern p : Config.smileys.keySet()) {
String res = Config.smileys.get(p);
str = p.matcher(str).replaceAll(res);
}
}
return str;
}
| 1 |
private void scanContainer(DockEvent event, boolean drop) {
Point p = event.getMouseEvent().getPoint();
Rectangle compBounds = getBounds();
int distTop = p.y;
int distLeft = p.x;
int min = Math.min(distTop, distLeft);
int distRight = compBounds.width - p.x;
int distBottom = compBounds.height - p.y;
int min2 = Math.min(distBottom, distRight);
min = Math.min(min, min2);
Dimension size = getSize();
Dockable dragged = event.getDragSource().getDockable();
// the drag size is the one of the parent dockable container
Dimension draggedSize = dragged.getComponent().getParent().getSize();
int bestHeight = (int) Math.min(draggedSize.height, size.height * 0.5);
int bestWidth = (int) Math.min(draggedSize.width, size.width * 0.5);
if(min == distTop) {
// dock on top
if(drop) {
acceptDrop(event, DockingConstants.SPLIT_TOP);
} else {
Rectangle2D r2d = new Rectangle2D.Float(0, 0, compBounds.width, bestHeight);
acceptDrag(event, DockingConstants.SPLIT_TOP, r2d);
}
} else if(min == distLeft) {
if(drop) {
acceptDrop(event, DockingConstants.SPLIT_LEFT);
} else {
Rectangle2D r2d = new Rectangle2D.Float(0, 0, bestWidth, compBounds.height);
acceptDrag(event, DockingConstants.SPLIT_LEFT, r2d);
}
} else if(min == distBottom) {
if(drop) {
acceptDrop(event, DockingConstants.SPLIT_BOTTOM);
} else {
Rectangle2D r2d = new Rectangle2D.Float(0, compBounds.height - bestHeight, compBounds.width, bestHeight);
acceptDrag(event, DockingConstants.SPLIT_BOTTOM, r2d);
}
} else { // right
if(drop) {
acceptDrop(event, DockingConstants.SPLIT_RIGHT);
} else {
Rectangle2D r2d = new Rectangle2D.Float(compBounds.width - bestWidth, 0, bestWidth, compBounds.height);
acceptDrag(event, DockingConstants.SPLIT_RIGHT, r2d);
}
}
}
| 7 |
public void run() {
updateScreen();
try {
while ((inputLine = in.readLine()) != null) {
if (inputLine.startsWith("DN")) {
// TODO
}
else if (inputLine.startsWith("D")) {
if (inputLine.equals("D"))
sim.setDisplayText("");
else
sim.setDisplayText(inputLine.substring(2, inputLine.length()));
updateScreen();
out.println("DB"+"\r\n");
}
else if (inputLine.startsWith("T")) {
out.println("T " + sim.getTara() + " kg "+"\r\n");
sim.setTara();
updateScreen();
}
else if (inputLine.startsWith("S")) {
updateScreen();
out.println("S " + sim.getNetto() + " kg " +"\r\n");
}
else if (inputLine.startsWith("B")) {
String temp = inputLine.substring(2, inputLine.length());
sim.setBrutto(Double.parseDouble(temp));
updateScreen();
out.println("DB"+"\r\n");
}
else if ((inputLine.startsWith("Q"))) {
System.out.println("");
System.out.println("Quitting...");
System.in.close();
System.out.close();
in.close();
out.close();
System.exit(0);
}
}
}
catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
| 9 |
public void removeImage(String name) {
if (IMAGE_URLS.containsKey(name)) IMAGE_URLS.remove(name);
if (IMAGES.containsKey(name)) IMAGES.remove(name);
}
| 2 |
public JSONObject putOpt(String key, Object value) throws JSONException {
if (key != null && value != null) {
put(key, value);
}
return this;
}
| 2 |
public Object getValueAt(int indiceLigne, int indiceColonne){
//System.out.println("ModeleListeVehicules::getValueAt()") ;
switch(indiceColonne){
case 0 :
return vehicules.get(indiceLigne).getImmatriculation() ;
case 1 :
return vehicules.get(indiceLigne).getModele() ;
case 2 :
return vehicules.get(indiceLigne).getAnnee() ;
case 3 :
return vehicules.get(indiceLigne).getCompteur() + " km" ;
case 4 :
return vehicules.get(indiceLigne).getSituation() ;
default :
return null ;
}
}
| 5 |
public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int n = to.length();
char[] circle = new char[n];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < n; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/*
* We will loop, possibly for all of the remaining characters.
*/
for (;;) {
j = offset;
b = true;
/*
* Compare the circle buffer with the to string.
*/
for (i = 0; i < n; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= n) {
j -= n;
}
}
/*
* If we exit the loop with b intact, then victory is ours.
*/
if (b) {
return true;
}
/*
* Get the next character. If there isn't one, then defeat is ours.
*/
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= n) {
offset -= n;
}
}
}
| 9 |
public CallExpr(final Expr[] params, final MemberRef method, final Type type) {
super(type);
this.params = params;
this.method = method;
for (int i = 0; i < params.length; i++) {
params[i].setParent(this);
}
}
| 1 |
public static void saveAs(Skin skin, String newName) {
if ((skin != null) && (model != null) && (newName != null) && !newName.equals("")) {
if (!model.saveAsSkinToDefaultDirectory(skin, newName)) {
showProblemMessage("Main.saveAs: Skin was not saved!");
}
} else {
throw new InvalidParameterException();
}
}
| 5 |
protected static Ptg calcAnd( Ptg[] operands )
{
boolean b = true;
Ptg[] alloperands = PtgCalculator.getAllComponents( operands );
for( Ptg alloperand : alloperands )
{
if( alloperand instanceof PtgBool )
{
PtgBool bo = (PtgBool) alloperand;
Boolean bool = (Boolean) bo.getValue();
if( bool == false )
{
return new PtgBool( false );
}
}
else
{
// probably a ref, hopefully to a bool
String s = String.valueOf( alloperand.getValue() );
if( s.equalsIgnoreCase( "false" ) )
{
return new PtgBool( false );
}
}
}
return new PtgBool( true );
}
| 4 |
public void addSlug(String slug) {
if (this.slugs == null) {
this.slugs = new ArrayList<String>();
this.slugs.add(slug);
} else {
this.slugs.add(slug);
}
}
| 1 |
public void method390(int i, int j, String s, int k, int i1)
{
if(s == null)
return;
aRandom1498.setSeed(k);
int j1 = 192 + (aRandom1498.nextInt() & 0x1f);
i1 -= anInt1497;
for(int k1 = 0; k1 < s.length(); k1++)
if(s.charAt(k1) == '@' && k1 + 4 < s.length() && s.charAt(k1 + 4) == '@')
{
int l1 = getColorByName(s.substring(k1 + 1, k1 + 4));
if(l1 != -1)
j = l1;
k1 += 4;
} else
{
char c = s.charAt(k1);
if(c != ' ')
{
method394(192, i + anIntArray1494[c] + 1, aByteArrayArray1491[c], anIntArray1492[c], i1 + anIntArray1495[c] + 1, anIntArray1493[c], 0);
method394(j1, i + anIntArray1494[c], aByteArrayArray1491[c], anIntArray1492[c], i1 + anIntArray1495[c], anIntArray1493[c], j);
}
i += anIntArray1496[c];
if((aRandom1498.nextInt() & 3) == 0)
i++;
}
}
| 8 |
@SuppressWarnings({ "unchecked" })
private boolean load() {
log.info("Loading config file \"" + configDir.getPath(configPath) + "\"");
Object obj;
ObjectInputStream os = null;
try {
try {
os = new ObjectInputStream(configDir.readFile(configPath));
} catch (IOException e) {
log.err("Failed to open config file: " + configPath);
//log.excp(e);
return false;
}
try {
obj = os.readObject();
} catch (ClassNotFoundException | IOException e) {
log.err("Failed to read config file: " + configPath);
log.excp(e);
return false;
}
} finally {
try {
if(os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
values = (HashMap<? super Object, ? super Object>)obj;
}catch(ClassCastException e) {
log.err("Failed to read expected datastructure!");
log.excp(e);
return false;
}
return true;
}
| 7 |
public Creature(int locx, int locy, String spriteFile) {
if(getSprite() == null){
try {
setSprite(ImageIO.read(new File(spriteFile)));
} catch (IOException e) {
e.printStackTrace();
}
}
x = locx;
y = locy;
stats = new Attributes(new int[]{5,5,5,5,5,5});
}
| 2 |
public static boolean available(int port) {
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
return false;
}
| 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RecordSelectorNode other = (RecordSelectorNode) obj;
if (selector == null) {
if (other.selector != null)
return false;
} else if (!selector.equals(other.selector))
return false;
if (subject == null) {
if (other.subject != null)
return false;
} else if (!subject.equals(other.subject))
return false;
return true;
}
| 9 |
public boolean pawnCapturing(int x1, int y1, int x2, int y2, String color, Square newSquare)
{
boolean capture = false;
if(color == "White")
{
if( (((x2 == x1 + PAWN_MOVEMENT_RESTRICTION) || (x2 == x1 - PAWN_MOVEMENT_RESTRICTION)) && y2 == y1 + PAWN_MOVEMENT_RESTRICTION)
&& newSquare.getPiece().getPieceType() != "-")
{
capture = true;
}
}
else
{
if( (((x2 == x1 + PAWN_MOVEMENT_RESTRICTION) || (x2 == x1 - PAWN_MOVEMENT_RESTRICTION)) && y2 == y1 - PAWN_MOVEMENT_RESTRICTION)
&& newSquare.getPiece().getPieceType() != "-")
{
capture = true;
}
}
return capture;
}
| 9 |
private static void readFile() {
while (scanner.hasNext()) {
lines.insert(scanner.nextLine());
}
}
| 1 |
public Boolean isDeleted() {
return isDeleted;
}
| 0 |
public TotalPane() {
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.setBorder(new TitledBorder("总流量统计"));
container.setLayout(new GridLayout(3, 2));
container.add(totaltitle);
totalnum.setText("43349");
container.add(totalnum);
container.add(tcptitle);
tcpnum.setText("23248");
container.add(tcpnum);
container.add(udptitle);
udpnum.setText("20884");
container.add(udpnum);
this.add(container);
}
| 0 |
@Override
public String processCommand(String[] arguments)
throws SystemCommandException {
String electionID = arguments[0];
facade.setCurrentElection(electionID);
Election election = facade.getCurrentElection();
if (election == null || !election.getEID().equals(electionID)){
throw new SystemCommandException(
"The current election could not be set to ID ["+
electionID+"] - is the ID valid?");
}else{
return "The current election was set to ID ["+electionID+"]";
}
}
| 2 |
@RequestMapping( ApplicationConstants.CREATE_USR)
@ResponseBody
public Object createUser(@RequestParam("name") String name,
@RequestParam("email") String email,
@RequestParam("password") String password) {
User user=new User();
Map<Object,String> errorMap=new HashMap<Object, String>();
if(name==null || "".equals(name)){
errorMap.put(1, "Please enter name");
}
if(email==null || "".equals(email)){
errorMap.put(2, "Please enter email");
}
if(password==null || "".equals(password)){
errorMap.put(3, "Please enter password");
}
if (errorMap.size()>0){
return errorMap;
}else{
user.setName(name);
user.setEmail(email);
user.setPassword(password);
user.setCreatedDate(new Date().toString());
user.setStatus(ApplicationConstants.STATUS_ACTIVE);
userDao.save(user);
return user;
}
}
| 7 |
public BufferedReader getBufferedReader() {
return _reader;
}
| 0 |
private EndPoint getEndPoint() {
return endPoint;
}
| 0 |
public int findMaxIndexDifferenceOrdering(int[] a) {
lMin = new int[a.length];
lMax = new int[a.length];
/* Keep track on MIN element until position i */
lMin[0] = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < lMin[i - 1]) {
lMin[i] = a[i];
} else {
lMin[i] = lMin[i - 1];
}
}
/* Keep track on MAX element until position j */
lMax[a.length - 1] = a[a.length - 1];
for (int j = a.length - 2; j >= 0; j--) {
if (a[j] > lMax[j + 1]) {
lMax[j] = a[j];
} else {
lMax[j] = lMax[j + 1];
}
}
PrintArray.print(lMin);
PrintArray.print(lMax);
/*
* Traverse both arrays LMIN and LMAX; The idea is that:
*
* (a) LMIN[j] <= LMIN[i] for all i < j
* (b) LMAX[j] >= LMAX[i] for all i < j
*
* KEY IDEA: assume that we are considering two elements A[i] and
* A[j] / A[i] < A[j]. Two considerations need to be taken into account:
*
* (a) If there exist an i' < i/ A[i'] <= A[i], then we should not
* consider i and a candidate left index: because A[i'] < A[j] and j -
* i' > j - i.
*
* (b) If there exist an index j' > j/ A[i] < A[j'], then we should not
* consider j as a candidate right index: because A[i] < A[j'] and j' -
* i > j - i
*
* While traversing the arrays, if LMIN[i] > LMAX[j], then do i++ since
* all elements to the left of i in LMIN are greater than LMIN[i]; if
* LMIN[i] < LMAX[j] then do j++
*/
int i = 0;
int j = 0;
int maxDiff = -1;
while (i < a.length && j < a.length) {
if (lMin[i] < lMax[j]) {
maxDiff = (maxDiff < (j - i))?(j - i):maxDiff;
j++;
}else {
i++;
}
}
return maxDiff;
}
| 8 |
public Transition transitionCreate(State from, State to) {
if (currentStep == TRANSITIONS_TO_SINGLE_FINAL) {
if (automaton.getFinalStates()[0] != to) {
JOptionPane.showMessageDialog(frame,
"Transitions must go to the new final state!",
"Bad Destination", JOptionPane.ERROR_MESSAGE);
return null;
}
if (!drawer.isSelected(from)) {
JOptionPane.showMessageDialog(frame,
"Transitions must come from an old final state!",
"Bad Source", JOptionPane.ERROR_MESSAGE);
return null;
}
Transition t = new FSATransition(from, to, "");
drawer.removeSelected(from);
automaton.addTransition(t);
frame.repaint();
if (drawer.numberSelected() == 0) {
nextStep();
}
return t;
}
if (currentStep == CREATE_EMPTY_TRANSITIONS) {
if (automaton.getTransitionsFromStateToState(from, to).length != 0) {
JOptionPane.showMessageDialog(frame,
"Transitions must go between"
+ "states with no transitions!",
"Transition Already Exists", JOptionPane.ERROR_MESSAGE);
return null;
}
Transition t = FSAToRegularExpressionConverter.addTransitionOnEmptySet(from, to, automaton);
remaining--;
nextStep();
frame.repaint();
return t;
}
outOfOrder();
return null;
}
| 6 |
public void solve(){
int timeoutCell = 40;
int timeoutGroup = 20;
ArrayList<Thread> allThreads = new ArrayList<Thread>();
for (int i=0; i < 81; i++){
int[] xy = indexToXY(i);
int x = xy[0];
int y = xy[1];
SudokuCellThread thread = new SudokuCellThread(this.sudokuField[y][x], timeoutCell);
allThreads.add(thread);
}
//First collect all indices.
//9 blocks 9 rows 9 colums are 27 groups
//each group has 9 elements
//each element has 2 components x and y to access it.
int[][][] sudokuGroups = new int[27][9][2];
for(int i = 0; i < 9; i++){
int blockTop = i/3*3;
int blockLeft = i%3*3;
for(int element=0; element < 9; element++){
//rows
sudokuGroups[i][element] = new int[]{i, element};
//columns
sudokuGroups[i+9][element] = new int[]{element, i};
//blocks
int y = element/3;
int x = element%3;
sudokuGroups[i+18][element] = new int[]{blockTop+y, blockLeft+x};
}
}
//Then get the groups of SudokuCells according to the indices
SudokuCell[][] sudokuCellGroups = new SudokuCell[27][9];
for (int group=0; group < 27; group++){
for(int element = 0; element < 9; element++){
int[] address = sudokuGroups[group][element];
int y = address[0];
int x = address[1];
sudokuCellGroups[group][element] = this.sudokuField[y][x];
}
}
for (SudokuCell[] sudokuCellGroup: sudokuCellGroups){
ArrayList<SudokuCell> sudokuCellGroupList = new ArrayList<SudokuCell>(Arrays.asList(sudokuCellGroup));
SudokuGroupThread thread = new SudokuGroupThread(sudokuCellGroupList, timeoutGroup);
allThreads.add(thread);
}
//StatusThread for debugging in test mode. Shows up the so far solved field when running mvn package.
//Running as daemon
//Thread statusThread = new SudokuFieldStatusThread(this.sudokuField);
//statusThread.start();
//Start all threads
for (Thread thread: allThreads.toArray(new Thread[allThreads.size()])){
thread.start();
}
//Wait for all threads to finish
for (Thread thread: allThreads.toArray(new Thread[allThreads.size()])){
try{
thread.join();
}
catch (InterruptedException e){
}
}
}
| 9 |
private void startInputMonitor(){
while(noStopRequested){
try{
//this.processRegisteAndOps();// 处理通道监听注册和读取事件注册
int num = 0;
//this.selector.selectedKeys().clear();// 清除所有key
// Wait for an event one of the registered channels
num = this.selector.select(50);
//num = this.selector.selectNow();
if (num > 0){
// Iterate over the set of keys for which events are available
Iterator selectedKeys = this.selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
Client sk = Client.getSockector(key);
if(sk != null){
sk.close();
}
continue;
}
if (key.isReadable()){
Client sockector = Client.getSockector(key);
sockector.unregisteRead();// 解除监听器对该连接输入数据的监听
//key.interestOps(key.interestOps() ^ SelectionKey.OP_READ);
addToReadPoll(key);// 添加到读取请求队列中
}
if (key.isWritable()){
Client.getSockector(key).sendMsgs();
}
}
}
this.processRegisteAndOps();// 处理通道监听注册和读取事件注册
}catch(Exception e){
e.printStackTrace();
}
}
}
| 8 |
@Override
public void endTurn() {
if (cooldown > 0) {
cooldown--;
if (cooldown == 0) {
tile = startingPosition;
tile.addBomber(this);
}
//other end-of-turn actions not possible if still dead.
}
}
| 2 |
private boolean jj_3R_73() {
if (jj_3R_49()) return true;
return false;
}
| 1 |
private boolean handleWithoutQueueing(final DataTelegram telegram) {
if(_mode == HANDLE_CONFIG_RESPONCES_MODE) {
if(telegram.getType() == DataTelegram.APPLICATION_DATA_TELEGRAM_TYPE) {
ApplicationDataTelegram applicationDataTelegram = (ApplicationDataTelegram)telegram;
BaseSubscriptionInfo info = applicationDataTelegram.getBaseSubscriptionInfo();
if(info != null) {
if(AttributeGroupUsageIdentifications.isConfigurationReply(info.getUsageIdentification())) {
SendDataObject receivedData = null;
int maxTelegramNumber = applicationDataTelegram.getTotalTelegramsCount();
if(maxTelegramNumber == 1) {
receivedData = TelegramUtility.getSendDataObject(applicationDataTelegram);
}
else {
ApplicationDataTelegram telegramArray[] = _splittedTelegramsTable.put(applicationDataTelegram);
if(telegramArray != null) {
receivedData = TelegramUtility.getSendDataObject(telegramArray);
}
}
if(receivedData != null) {
_highLevelComponent.updateConfigData(receivedData);
}
return true;
}
}
}
}
return false;
}
| 7 |
public boolean meleeHitDetection(int enemyPosX, int enemyPosY){
double distance = Math.sqrt( (enemyPosX-posX)*(enemyPosX-posX) + (enemyPosY-posY)*(enemyPosY-posY) );
if(distance<50){//50=meleerange
return true;
}else{
return false;
}
}
| 1 |
public static String getHost(String url){
if(url == null || url.length() == 0)
return "";
int doubleslash = url.indexOf("//");
if(doubleslash == -1)
doubleslash = 0;
else
doubleslash += 2;
int end = url.indexOf('/', doubleslash);
end = end >= 0 ? end : url.length();
int port = url.indexOf(':', doubleslash);
end = (port > 0 && port < end) ? port : end;
return url.substring(doubleslash, end);
}
| 6 |
public Class getTypeClass() throws ClassNotFoundException {
if (topType.isClassType() || !bottomType.isValidType())
return topType.getTypeClass();
else
return bottomType.getTypeClass();
}
| 2 |
public String getAlbumArtURL() {
String Albumarturl = null;
int length = getAlbumID().length();
switch (length) {
case 1:
Albumarturl = "http://image.melon.co.kr/cm/album/images/000/00/00" + getAlbumID().substring(0, 1) + "/" + getAlbumID() + "_500.jpg";
break;
case 2:
Albumarturl = "http://image.melon.co.kr/cm/album/images/000/00/0" + getAlbumID().substring(0, 2) + "/" + getAlbumID() + "_500.jpg";
break;
case 3:
Albumarturl = "http://image.melon.co.kr/cm/album/images/000/00/" + getAlbumID().substring(0, 3) + "/" + getAlbumID() + "_500.jpg";
break;
case 4:
Albumarturl = "http://image.melon.co.kr/cm/album/images/000" + "/0" + getAlbumID().substring(0, 1) + "/" + getAlbumID().substring(1, 4) + "/" + getAlbumID() + "_500.jpg";
break;
case 5:
Albumarturl = "http://image.melon.co.kr/cm/album/images/000" + "/" + getAlbumID().substring(0, 2) + "/" + getAlbumID().substring(2, 5) + "/" + getAlbumID() + "_500.jpg";
break;
case 6:
Albumarturl = "http://image.melon.co.kr/cm/album/images/00" + getAlbumID().substring(0, 1) + "/" + getAlbumID().substring(1, 3) + "/" + getAlbumID().substring(3, 6) + "/" + getAlbumID() + "_500.jpg";
break;
case 7:
Albumarturl = "http://image.melon.co.kr/cm/album/images/0" + getAlbumID().substring(0, 2) + "/" + getAlbumID().substring(2, 4) + "/" + getAlbumID().substring(4, 7) + "/" + getAlbumID() + "_500.jpg";
break;
}
return Albumarturl;
}
| 7 |
public int getHandCount(){
int total=0;
for (int i=0;i<hand.size();i++)
total+=hand.get(i).getValue21();
return total;
}
| 1 |
public static List<Element> mergeSort(List<Element> list) {
if (list.size() <= 1) {
return list;
}
// Make two arrays for range < pivot && range > pivot
List<Element> left = new ArrayList<Element>();
List<Element> right = new ArrayList<Element>();
int middle = list.size() / 2;
for (int i = 0; i < list.size(); i++) {
if (i < middle) {
left.add(list.get(i));
} else {
right.add(list.get(i));
}
}
// use recursion
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
}
| 3 |
private void importFiles() {
TreeItem[] selection = tree.getSelection();
if (selection.length != 1)
return;
TreeItem cur = selection[0];
while (cur != null && !(cur.getData() instanceof Project))
cur = cur.getParentItem();
if (cur == null)
return;
Project proj = (Project) cur.getData();
FileDialog dialog;
if (isCurrentItemLocal())
dialog = new FileDialog(shell, FileDialog.Mode.OPEN, getCurrentTreeDir());
else
dialog = new FileDialog(shell, FileDialog.Mode.OPEN, getCurrentTreeSym());
ArrayList<SymitarFile> files = dialog.open();
if (files != null) {
for (SymitarFile file : files) {
if (!proj.hasFile(file)) {
proj.addFile(file);
TreeItem item = new TreeItem(cur, SWT.NONE);
item.setText(file.getName());
item.setData(file);
item.setImage(getFileImage(file));
}
}
if (proj.isLocal())
ProjectManager.saveProjects(proj.getDir());
else
ProjectManager.saveProjects(proj.getSym());
}
}
| 9 |
public static HashMap<String, HashMap<String, Integer>> getMap(String filePath) throws Exception
{
HashMap<String, HashMap<String, Integer>> map =
new HashMap<String, HashMap<String,Integer>>();
BufferedReader reader = filePath.toLowerCase().endsWith("gz") ?
new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( filePath)))) :
new BufferedReader(new FileReader(new File(filePath
)));
String nextLine = reader.readLine();
int numDone =0;
while(nextLine != null)
{
StringTokenizer sToken = new StringTokenizer(nextLine, "\t");
String sample = sToken.nextToken();
String taxa= sToken.nextToken();
int count = Integer.parseInt(sToken.nextToken());
if( sToken.hasMoreTokens())
throw new Exception("No");
HashMap<String, Integer> innerMap = map.get(sample);
if( innerMap == null)
{
innerMap = new HashMap<String, Integer>();
map.put(sample, innerMap);
}
if( innerMap.containsKey(taxa))
throw new Exception("parsing error " + taxa);
innerMap.put(taxa, count);
nextLine = reader.readLine();
numDone++;
if( numDone % 1000000 == 0 )
System.out.println(numDone);
}
return map;
}
| 6 |
public void spawnEnemies(){
int startPositionX = (rd.nextInt(Math.abs(settings.screenWidth - 40)));
int startPositionY = rd.nextInt(350);
int checker = rd.nextInt(2000);
if(checker < 10){
for(int i = 0; i < munchkins.length; i++){
if(munchkins[i] == null){
munchkins[i] = new Munchkin(this, settings.enemyColor, settings.enemySpeed,
startPositionX, startPositionY, Math.PI, false, false);
break;
}
}
}
if(checker > 1990){
for(int i = 0; i < ufos.length; i++){
if(ufos[i] == null){
ufos[i] = new UFO(this, settings.enemyColor, settings.enemySpeed,
startPositionX, startPositionY, Math.PI, false, false);
break;
}
}
}
}
| 6 |
public void keyReleased(KeyEvent e) {
}
| 0 |
private void assignBlood(int x, int y){
if (x>9)
x = x-10;
else if (x<0)
x = 10+x;
if (y>9)
y = y-10;
else if (y<0)
y = 10+y;
if (grid[x][y]==RoomState.EMPTY)
grid[x][y] = RoomState.BLOOD;
else if (grid[x][y]==RoomState.SLIME)
grid[x][y] = RoomState.GOOP;
}
| 6 |
public void parser() throws Exception {
Connection conn = JDBC.createConnection();
Ngram ngram;
int count = 0;
Token pre = new Token(null, null);
String preWordWithAttr = null;
// for (int i = 0; i < 10; i++)
// list = lexer.nextTokenList();
while (list != null) {
System.out.println("sss" + list.size());
preWordWithAttr = null;
for (int i = 0; i < list.size(); i++) {
current = list.get(i);
if (current.getKind() == Token.Kind.TOKEN_WORD) {
if (pre.getKind() == Token.Kind.TOKEN_ATTRIBUTE) {
if (preWordWithAttr != null) {
String attrWithWord[] = preWordWithAttr.split("_");
ngram = new Ngram();
ngram.setWordAttribute(attrWithWord[0] + "_"
+ pre.getContent());
ngram.setWordGroup(attrWithWord[1] + "_"
+ current.getContent());
count++;
service.addNgrambyup(conn, ngram);
// service.deleteNgram(conn, ngram);
// if(hashNgram.get(ngram.getWordGroup().toLowerCase())
// == null){
// hashNgram.put(ngram.getWordGroup().toLowerCase(),
// ngram.getWordAttribute());
// listAfterHandle.add(ngram);
// }
// listAfterHandle.add(ngram);
preWordWithAttr = pre.getContent() + "_"
+ current.getContent();
// }
} else {
preWordWithAttr = pre.getContent() + "_"
+ current.getContent();
}
} else if (current.getKind() == Token.Kind.TOKEN_OTHERS
|| current.getKind() == Token.Kind.TOKEN_PUNCTION) {
preWordWithAttr = null;
}
}
pre = current;
}
list = null;
list = lexer.nextTokenList();
}
// service.batchAddNgram(listAfterHandle);
JDBC.close(conn);
System.out.println("add is done");
// service.deleteNgram();
}
| 7 |
synchronized public boolean accederAuTrain (Voyageurs voyageur, Train train) {
Iterator<Train> iteratrain = listeTrainQuai.iterator();
while (iteratrain.hasNext()) {
Train trainListe = iteratrain.next();
if (trainListe.equals(train)) {
train.embarquer(voyageur);
// Dire au train qu'un voyageur est monté.
return true;
}
}
return false;
}
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.