text stringlengths 14 410k | label int32 0 9 |
|---|---|
public Object nextValue() throws JSONException {
char c = nextClean();
String s;
switch (c) {
case '"':
case '\'':
return nextString(c);
case '{':
back();
return new JSONObject(this);
case '[':
case '(':
back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = next();
}
back();
s = sb.toString().trim();
if (s.equals("")) {
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(s);
} | 8 |
public void keyReleased(KeyEvent e){
KeyEvent nextPress = (KeyEvent)Toolkit.getDefaultToolkit().getSystemEventQueue().peekEvent(KeyEvent.KEY_PRESSED);
if ((nextPress == null) || (nextPress.getWhen() != e.getWhen()) || (nextPress.getKeyCode() != e.getKeyCode()))
{
for(ListenerQueuePair pair: this.handlers) {
pair.getQueue().add(new KeyReleaseEvent(
e.getKeyCode(),
(MinuetoKeyboardHandler)pair.getListener()));
}
}
} | 4 |
public void setSomeObjArray(SomeBean[] someObjArray) {
this.someObjArray = someObjArray;
} | 0 |
public String getEmail() {
return email;
} | 0 |
private void deliver (Message m) {
int source = m.getSource();
int destination = m.getDestination();
if (destination != -1) {
unicast(m, getDelay());
} else {
int delay;
boolean drop = false;
boolean first = true;
/* Broadcast. */
for (int i = 1; i <= r.n; i++) {
drop = (source == i && Utils.SELFMSGENABLED == false);
if (drop)
continue;
if (first) {
delay = getDelay();
first = false;
} else delay = -1;
m.setDestination(i);
unicast(m, delay);
}
}
} | 5 |
protected int completeLineComment(TokenizerProperty prop) throws TokenizerException {
String[] images = prop.getImages();
int len = images[0].length();
while (_currentReadPos + len < _currentWritePos || readMoreDataFromBase() > 0) {
switch (getChar(_currentReadPos + len)) {
case '\r':
len++;
if (_currentReadPos + len < _currentWritePos || readMoreDataFromBase() > 0) {
if (getChar(_currentReadPos + len) == '\n') {
len++;
}
}
return len;
case '\n':
len++;
return len;
default:
len++;
}
}
return len;
} | 7 |
public byte[] readArchive(ArchiveRequest query) {
int currentChunk = 0;
int nextSectorId = query.getStartSector();
ByteBuffer outputBuffer = ByteBuffer.allocate(query.getFileSize());
while (nextSectorId != 0) {
Sector sector;
try {
sector = readSector(query.getFileId(), nextSectorId);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
if (currentChunk++ != sector.getFileChunk())
throw new RuntimeException();
if (!query.checkSector(sector))
throw new RuntimeException();
outputBuffer.put(sector.getData(), sector.getDataOffset(),
Math.min(sector.getData().length - sector.getDataOffset(), outputBuffer.remaining()));
nextSectorId = sector.getNextSector();
}
if (outputBuffer.remaining() != 0)
throw new RuntimeException();
return outputBuffer.array();
} | 5 |
public void elevatorBoundary(Character c1)
{
if(c1.xCord<506)
{
c1.xCord = 506;
}
if(c1.xCord>782)
{
c1.xCord = 782;
}
if(c1.yCord < 349)
{
c1.yCord = 349;
}
if(c1.xCord>505 && c1.xCord<577 && c1.yCord>541)
{
c1.yCord = 541;
}
if(c1.xCord>714 && c1.xCord<783 && c1.yCord>541)
{
c1.yCord = 541;
}
} | 9 |
public FacesContext getFacesContext(Object context, Object request,
Object response,
Lifecycle lifecycle) throws FacesException {
// Select the appropriate MockExternalContext implementation class
Class clazz = MockExternalContext.class;
if (jsf12) {
try {
clazz = this.getClass().getClassLoader().loadClass
("org.apache.shale.test.mock.MockExternalContext12");
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
}
// Select the constructor we wish to call
Constructor mecConstructor = null;
try {
mecConstructor = clazz.getConstructor(externalContextSignature);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
// Construct an appropriate MockExternalContext instance
MockExternalContext externalContext = null;
try {
externalContext = (MockExternalContext) mecConstructor.newInstance
(new Object[] { context, request, response });
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
// Construct an appropriate MockFacesContext instance and return it
try {
return (MockFacesContext)
constructor.newInstance(new Object[] { externalContext, lifecycle });
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
} | 9 |
private boolean isOtherPunctuation(String str) {
char ch = str.charAt(0);
return ch == '~' || ch == '`' || ch == '!' || ch == '@' || ch == '#' || ch == '$' || ch == '%' || ch == '?';
} | 7 |
@Transient
public List<LabelValue> getRoleList() {
List<LabelValue> userRoles = new ArrayList<LabelValue>();
if (this.roles != null) {
for (Role role : roles) {
// convert the user's roles to LabelValue Objects
userRoles.add(new LabelValue(role.getName(), role.getName()));
}
}
return userRoles;
} | 2 |
public boolean equalsIntensities(Run r){
if (getRed() == r.getRed() && getGreen() == r.getGreen() && getBlue() == r.getBlue()){
return true;
}
return false;
} | 3 |
private void checkName(final String name) {
if (named && name == null) {
throw new IllegalArgumentException(
"Annotation value name must not be null");
}
} | 2 |
public static Kind parse(HtmlElement element, String str){
switch(str){
case "captions":
return CAPTIONS;
case "chapters":
return CHAPTERS;
case "descriptions":
return DESCRIPTIONS;
case "metadata":
return METADATA;
case "subtitles":
return SUBTITLES;
default:
return null;
}
} | 5 |
public void keyReleased(KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.VK_SHIFT:
b1 = false;
break;
case KeyEvent.VK_CONTROL:
b2 = false;
break;
case KeyEvent.VK_LEFT:
bl = false;
break;
case KeyEvent.VK_UP:
bu = false;
break;
case KeyEvent.VK_DOWN:
bd = false;
break;
case KeyEvent.VK_RIGHT:
br = false;
break;
default:
return;
}
clkcanvas.repaint();
onInput();
} | 6 |
public static void main(String[] args) {
//This program determines the even factorial of an even positive integer
//ie: n(n-2)(n-4)....4*2
int positiveInt;
Scanner input = new Scanner(System.in);
for (;;) {
System.out.print("Please enter a positive even integer (0 to exit): ");
positiveInt = input.nextInt();
if (positiveInt == 0) {
//terminal value
break;
} else if (positiveInt < 0) { //no negative values permitted
System.out.println("The number entered is negative.");
} else if ((positiveInt%2) != 0) { //no odd numbers permitted
System.out.println("The number entered in not an even number.");
} else {
//for even positive numbers, call the method even_factorial and display the results
System.out.println("The factorial value of " + positiveInt + " is " + even_factorial(positiveInt) + ".");
}
}
input.close();
} | 4 |
public List<User> getAll() {
Enumeration<User> elements = USER_MAP.elements();
List<User> users = new ArrayList<>();
while (elements.hasMoreElements()) {
users.add(elements.nextElement());
}
return users;
} | 1 |
private final double[][] readMatrixFromFile() throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(new File("C:/Users/Christina/Java1-workspace/AntColonyTest/src/AntColony/test.tsp")));
final LinkedList<Record> records = new LinkedList<Record>();
boolean readAhead = false;
String line;
while ((line = br.readLine()) != null) {
if (line.equals("EOF")) {
break;
}
if (readAhead) {
String[] split = line.trim().split(" ");
records.add(new Record(Double.parseDouble(split[1].trim()), Double
.parseDouble(split[2].trim())));
}
if (line.equals("NODE_COORD_SECTION")) {
readAhead = true;
}
}
br.close();
final double[][] localMatrix = new double[records.size()][records.size()];
int replace = 0;
int rIndex = 0;
for (Record r : records) {
int hIndex = 0;
for (Record h : records) {
// The first location in the input file is always replaced with the location of the mobile service request
if(replace == 0) {
r.x = request.getLocation().getLatitude();
r.y = request.getLocation().getLongitude();
h.x = request.getLocation().getLatitude();
h.y = request.getLocation().getLongitude();
replace = 1;
}
localMatrix[rIndex][hIndex] = calculateEuclidianDistance(r.x, r.y, h.x, h.y);
hIndex++;
}
rIndex++;
}
return localMatrix;
} | 7 |
@Override
public void run() {
Graphics g = bstrategy.getDrawGraphics();
if(bstrategy.contentsLost() == false){
Insets insets = frame1.getInsets();
g.translate(insets.left, insets.top);
if(isgameover == true){
g.setColor(Color.RED);
g.setFont(new Font("Sanserif", Font.BOLD, 80));
drawStringCenter("GAMEOVER", 200, g);
bstrategy.show();
g.dispose();
return;
}
if(spkey == true){
speed = speed - 0.25;
}else{
speed = speed + 0.25;
}
if(speed < -6) speed = -6;
if(speed > 6) speed = 6;
cy = cy + (int)speed;
if(cy < 0) cy = 0;
if(cy > 448) isgameover = true;
g.clearRect(0, 0, 600, 400);
g.drawImage(pimage, 270, cy, frame1);
for(int i = 0; i<karasus.length; i = i + 1){
karasus[i].draw(g, frame1);
}
bstrategy.show();
g.dispose();
System.out.println(cy + "." + speed);
}
} | 8 |
public void write(String fileName) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> pair = it.next();
String line = pair.getKey() + "=" + pair.getValue() + "\n";
bw.write(line);
}
}
} | 1 |
public synchronized void editar(int i)
{
try
{
new PesquisadorView(this, list.get(i));
}
catch (Exception e)
{
}
} | 1 |
String assemble(Decomp d, String reply[], Key gotoKey) {
String lines[] = new String[3];
d.stepRule();
String rule = d.nextRule();
if (EString.match(rule, "goto *", lines)) {
// goto rule -- set gotoKey and return false.
gotoKey.copy(keys.getKey(lines[0]));
if (gotoKey.key() != null) return null;
System.out.println("Goto rule did not match key: " + lines[0]);
return null;
}
String work = "";
while (EString.match(rule, "* (#)*", lines)) {
// reassembly rule with number substitution
rule = lines[2]; // there might be more
int n = 0;
try {
n = Integer.parseInt(lines[1]) - 1;
} catch (NumberFormatException e) {
System.out.println("Number is wrong in reassembly rule " + lines[1]);
}
if (n < 0 || n >= reply.length) {
System.out.println("Substitution number is bad " + lines[1]);
return null;
}
reply[n] = post.translate(reply[n]);
work += lines[0] + " " + reply[n];
}
work += rule;
if (d.mem()) {
mem.save(work);
return null;
}
return work;
} | 7 |
public static void main(String[] args) {
int N = 12;
double[] X = new double[N];
double sum = 0.0;
for(int i = 1; i < N-1; i ++){
X[i] = poisson(10, i);
sum += X[i];
System.out.println(i + " "+ X[i]);
}
for(int i = 1; i < N-1; i ++){
X[i] = X[i]/sum;
}
System.out.println("Normalizado");
sum = 0;
for(int i = 1; i < N-1; i++){
System.out.println(i + " "+ X[i]);
sum += X[i];
}
System.out.println("Normalizado "+sum);
Discrete d = new Discrete(X);
for (int i = 1; i < 10; i++)
System.out.println(i + " "+ d.random());
// /*int N = Integer.parseInt(args[0]);
// double[] X = { 0, .1, .4, .12, .38, 0 };
// int[] hist = new int[N + 2];
// Discrete d = new Discrete(X);
// for (int i = 0; i < N; i++)
// hist[d.random()]++;
//
// for (int i = 1; i <= X.length - 2; i++)
// System.out.println(i + ": " + X[i] + " " + (1.0 * hist[i] / N));*/
} | 4 |
public static void getFeaturesFromCDD(String queryString, Map<String, CyIdentifiable> reverseMap,
Map<CyIdentifiable, List<CDDFeature>> featureMap) throws Exception {
BufferedReader in = queryCDD("feats", queryString);
List<String> inputLines = new ArrayList<String>();
String line;
while ((line = in.readLine()) != null) {
// System.out.println("Feature line from CDD: "+line);
line = line.trim();
// Skip over the header lines
if (line.startsWith("#") || line.startsWith("Query") || line.length()==0) continue;
CDDFeature feature = new CDDFeature(line);
if (reverseMap.containsKey(feature.getProteinId())) {
CyIdentifiable cyId = reverseMap.get(feature.getProteinId());
if (!featureMap.containsKey(cyId))
featureMap.put(cyId, new ArrayList<CDDFeature>());
featureMap.get(cyId).add(feature);
}
}
return;
} | 6 |
public void testGoodAnswerGameToBeWon() {
System.out.println("Test 1 : gameToBeWon");
Game gameToBeWon = new Game(new GameMaster(
DefaultValues.DEFAULTATTEMPTCOMBINATION1), new Board());
int attemptsCount = 0;
// 1. Wrong combinations input.
Answer answer = gameToBeWon
.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION2);
attemptsCount++;
assertEquals(true, answer.more_attempts);
assertEquals(false, answer.target_found);
assertEquals(
gameToBeWon.getAnswerCombinationFromGameMaster(
DefaultValues.DEFAULTATTEMPTCOMBINATION2).getBlackCount(),
answer.nb_blacks);
assertEquals(
gameToBeWon.getAnswerCombinationFromGameMaster(
DefaultValues.DEFAULTATTEMPTCOMBINATION2).getWhiteCount(),
answer.nb_whites);
answer = gameToBeWon.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION3);
attemptsCount++;
answer = gameToBeWon.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION2);
attemptsCount++;
answer = gameToBeWon.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION3);
attemptsCount++;
assertEquals(true, answer.more_attempts);
assertEquals(false, answer.target_found);
assertEquals(
gameToBeWon.getAnswerCombinationFromGameMaster(
DefaultValues.DEFAULTATTEMPTCOMBINATION3).getBlackCount(),
answer.nb_blacks);
assertEquals(
gameToBeWon.getAnswerCombinationFromGameMaster(
DefaultValues.DEFAULTATTEMPTCOMBINATION3).getWhiteCount(),
answer.nb_whites);
// 2. Right combination input
answer = gameToBeWon.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION1);
attemptsCount++;
assertEquals(true, answer.more_attempts);
assertEquals(true, answer.target_found);
assertEquals(5, answer.nb_blacks);
assertEquals(0, answer.nb_whites);
assertEquals(attemptsCount, answer.remaining_attempts);
// 3. Another combination attempt (a wrong one).
answer = gameToBeWon.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION2);
attemptsCount++;
assertEquals(true, answer.more_attempts);
assertEquals(true, answer.target_found);
assertEquals(attemptsCount - 1, answer.remaining_attempts);
// 4. Another combination attempt the right one).
answer = gameToBeWon.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION1);
attemptsCount++;
assertEquals(true, answer.more_attempts);
assertEquals(true, answer.target_found);
assertEquals(attemptsCount - 2, answer.remaining_attempts);
} | 0 |
public static void exit() {
if (Game.client != null && Game.client.isConnected()) Game.client.disconnect();
if (Game.server != null) Game.server.shutdown();
running = false;
UpdateThread.requestStop = true;
Settings.saveSettings();
System.exit(0);
} | 3 |
private long getCPtrAddRefMarketData(MarketData element) {
// Whenever adding a reference to the list, I remove it first (if already there.)
// That way we never store more than one reference per actual contained object.
//
for(int intIndex = 0; intIndex < elementList.size(); intIndex++)
{
Object theObject = elementList.get(intIndex);
if ((theObject == null) || !(theObject instanceof MarketData))
continue;
MarketData tempRef = (MarketData)(theObject);
if ((MarketData.getCPtr(tempRef) == MarketData.getCPtr(element)))
{
elementList.remove(tempRef); // It was already there, so let's remove it before adding (below.)
break;
}
}
// Now we add it...
//
MarketData tempLocalRef = element;
elementList.add(tempLocalRef);
return MarketData.getCPtr(element);
} // Hope I get away with overloading this for every type. Otherwise, | 4 |
private void CheckConnection() throws IOException {
if(!ClientSocket.isConnected()){
String username = null;
for(int i=0 ; i<goChatServer.connectedSockets.size();i++){
if (goChatServer.connectedSockets.get(i) == ClientSocket){
goChatServer.connectedSockets.remove(i);
}
}
for(Map.Entry<String, Socket> user : goChatServer.connectedUserandSocket.entrySet()){
if(user.getValue() == ClientSocket){
username = user.getKey();
notifyDisconnect(username);
goChatServer.serverGUI.conversationTextArea.append(username+" disconnected \n");
}
}
goChatServer.connectedUsers.remove(username);
for(Socket connectedSocket : goChatServer.connectedSockets){
PrintWriter Out = new PrintWriter(connectedSocket.getOutputStream());
Out.println("VIS#$"+goChatServer.visibleUsers);
Out.flush();
}
for(String pair:goChatServer.connectedListPair){
if(pair.contains(username)){
goChatServer.connectedListPair.remove(pair);
break;
}
}
arrayPairs = goChatServer.connectedListPair.toArray(new String[goChatServer.connectedListPair.size()]);
goChatServer.serverGUI.chatPairList.setListData(arrayPairs);
}
} | 8 |
private static URLConnection fetchClass0(String host, int port,
String filename)
throws IOException
{
URL url;
try {
url = new URL("http", host, port, filename);
}
catch (MalformedURLException e) {
// should never reache here.
throw new IOException("invalid URL?");
}
URLConnection con = url.openConnection();
con.connect();
return con;
} | 1 |
public Behaviour jobFor(Actor actor) {
if (! structure.intact()) return null ;
//
// First and foremost, check to see whether a meltdown is in progress, and
// arrest it if possible:
final Choice choice = new Choice(actor) ;
if (meltdown > 0) {
final Action check = new Action(
actor, this,
this, "actionCheckMeltdown",
Action.LOOK,
meltdown < 0.5f ? "Correcting core condition" : "Containing Meltdown!"
) ;
check.setPriority(Action.ROUTINE * (meltdown + 1)) ;
choice.add(check) ;
}
if (! personnel.onShift(actor)) return choice.pickMostUrgent() ;
//
// Then check to see if anything needs manufacture-
final Manufacture m = stocks.nextManufacture(actor, METALS_TO_FUEL) ;
if (m != null && stocks.amountOf(METAL_ORES) >= 1) {
m.checkBonus = 5 * structure.upgradeLevel(ISOTOPE_CONVERSION) ;
choice.add(m) ;
}
final Manufacture o = stocks.nextSpecialOrder(actor) ;
if (o != null) {
o.checkBonus = 5 * structure.upgradeLevel(ISOTOPE_CONVERSION) ;
choice.add(o) ;
}
//
// Failing that, just keep the place in order-
choice.add(new Supervision(actor, this)) ;
return choice.weightedPick() ;
} | 7 |
public static long pop_xor(long A[], long B[], int wordOffset, int numWords) {
int n = wordOffset + numWords;
long tot = 0, tot8 = 0;
long ones = 0, twos = 0, fours = 0;
int i;
for( i = wordOffset; i <= n - 8; i += 8 ) {
/*** C macro from Hacker's Delight
#define CSA(h,l, a,b,c) \
{unsigned u = a ^ b; unsigned v = c; \
h = (a & b) | (u & v); l = u ^ v;}
***/
long twosA, twosB, foursA, foursB, eights;
// CSA(twosA, ones, ones, (A[i] ^ B[i]), (A[i+1] ^ B[i+1]))
{
long b = (A[i] ^ B[i]), c = (A[i + 1] ^ B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+2] ^ B[i+2]), (A[i+3] ^ B[i+3]))
{
long b = (A[i + 2] ^ B[i + 2]), c = (A[i + 3] ^ B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(twosA, ones, ones, (A[i+4] ^ B[i+4]), (A[i+5] ^ B[i+5]))
{
long b = (A[i + 4] ^ B[i + 4]), c = (A[i + 5] ^ B[i + 5]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
// CSA(twosB, ones, ones, (A[i+6] ^ B[i+6]), (A[i+7] ^ B[i+7]))
{
long b = (A[i + 6] ^ B[i + 6]), c = (A[i + 7] ^ B[i + 7]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u = twos ^ twosA;
foursB = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u = fours ^ foursA;
eights = (fours & foursA) | (u & foursB);
fours = u ^ foursB;
}
tot8 += pop(eights);
}
if( i <= n - 4 ) {
long twosA, twosB, foursA, eights;
{
long b = (A[i] ^ B[i]), c = (A[i + 1] ^ B[i + 1]);
long u = ones ^ b;
twosA = (ones & b) | (u & c);
ones = u ^ c;
}
{
long b = (A[i + 2] ^ B[i + 2]), c = (A[i + 3] ^ B[i + 3]);
long u = ones ^ b;
twosB = (ones & b) | (u & c);
ones = u ^ c;
}
{
long u = twos ^ twosA;
foursA = (twos & twosA) | (u & twosB);
twos = u ^ twosB;
}
eights = fours & foursA;
fours = fours ^ foursA;
tot8 += pop(eights);
i += 4;
}
if( i <= n - 2 ) {
long b = (A[i] ^ B[i]), c = (A[i + 1] ^ B[i + 1]);
long u = ones ^ b;
long twosA = (ones & b) | (u & c);
ones = u ^ c;
long foursA = twos & twosA;
twos = twos ^ twosA;
long eights = fours & foursA;
fours = fours ^ foursA;
tot8 += pop(eights);
i += 2;
}
if( i < n ) {
tot += pop((A[i] ^ B[i]));
}
tot += (pop(fours) << 2) + (pop(twos) << 1) + pop(ones) + (tot8 << 3);
return tot;
} | 4 |
public void RemoveStartMenuElement() {
if (elementStart != null) {
elementStart.RemoveFromMenu();
elementStart = null;
}
} | 1 |
@Override
public boolean isActive() {
final ReentrantLock l = lock;
l.lock();
try {
return active;
}
finally {
l.unlock();
}
} | 0 |
private void makeDropTarget( final java.io.PrintStream out, final java.awt.Component c, boolean recursive )
{
// Make drop target
final java.awt.dnd.DropTarget dt = new java.awt.dnd.DropTarget();
try
{ dt.addDropTargetListener( dropListener );
} // end try
catch( java.util.TooManyListenersException e )
{ e.printStackTrace();
log(out, "FileDrop: Drop will not work due to previous error. Do you have another listener attached?" );
} // end catch
// Listen for hierarchy changes and remove the drop target when the parent gets cleared out.
c.addHierarchyListener( new java.awt.event.HierarchyListener()
{ public void hierarchyChanged( java.awt.event.HierarchyEvent evt )
{ log( out, "FileDrop: Hierarchy changed." );
java.awt.Component parent = c.getParent();
if( parent == null )
{ c.setDropTarget( null );
log( out, "FileDrop: Drop target cleared from component." );
} // end if: null parent
else
{ new java.awt.dnd.DropTarget(c, dropListener);
log( out, "FileDrop: Drop target added to component." );
} // end else: parent not null
} // end hierarchyChanged
}); // end hierarchy listener
if( c.getParent() != null )
new java.awt.dnd.DropTarget(c, dropListener);
if( recursive && (c instanceof java.awt.Container ) )
{
// Get the container
java.awt.Container cont = (java.awt.Container) c;
// Get it's components
java.awt.Component[] comps = cont.getComponents();
// Set it's components as listeners also
for( int i = 0; i < comps.length; i++ )
makeDropTarget( out, comps[i], recursive );
} // end if: recursively set components as listener
} | 6 |
public boolean placeBet(Bet bet) {
boolean succes = false;
for (Player p : players) {
if(p.getId() == bet.getPlayerId()) {
if ((p.getStash() - bet.getValue()) >= 0
&& bet.getValue() >= minBet && bet.getValue() <= maxBet) {
bets.add(bet);
p.removeFromStash(bet.getValue());
succes = true;
}
}
}
return succes;
} | 5 |
public static ArrayList<String> makePanDigitals() {
char arr[] = new char[10];
for (int i = 0; i < 10; i++) {
arr[i] = (char) (i + 48);
}
ArrayList<String> retarr = new ArrayList<String>(3628800);
for (int i = 0; i < 3628800 - 1; i++) {
int j = arr.length - 1;
while (arr[j - 1] >= arr[j]) {
j--;
}
int q = arr.length;
while (arr[q - 1] <= arr[j - 1]) {
q--;
}
swap(j - 1, q - 1, arr);
j++;
q = arr.length;
while (j < q) {
swap(j - 1, q - 1, arr);
j++;
q--;
}
retarr.add(String.valueOf(arr));
}
return retarr;
} | 5 |
private void HTTP2WebApplication(String HostPath, String MODE) {
Connection conn = null;
PreparedStatement ps_http = null;
PreparedStatement ps =
null;
Statement s = null;
ResultSet rs = null;
String HTTP_REQUEST_HOST = "", HTTP_REQUEST_PATH = "", HTTP_REQUEST_FILE = "";
int TARGET_PHP_FILES_ID = 0;
File f;
DatabaseAccess JavaDBAccess2 = null;
try {
if ((conn = this.JavaDBAccess.setConn()) != null) {
System.out.println(
"Connected to database " + JavaDBAccess.getDatabaseName());
} else {
throw new Exception(
"Not connected to database " + JavaDBAccess.getDatabaseName());
}
conn.setAutoCommit(false);
// Start a transaction by inserting a record in the TARGET_PHP_FILES_FUNCTIONS table
ps_http = conn.prepareStatement("SELECT DISTINCT HTTP_REQUEST_HOST, HTTP_REQUEST_PATH, HTTP_REQUEST_FILE FROM TARGET_PHP_FILES_RUNS_FUNCTIONS WHERE MODE=?");
ps_http.setString(1, MODE);
rs = ps_http.executeQuery();
while (rs.next()) {
HTTP_REQUEST_HOST = rs.getString("HTTP_REQUEST_HOST");
HTTP_REQUEST_PATH = rs.getString("HTTP_REQUEST_PATH");
HTTP_REQUEST_FILE = rs.getString("HTTP_REQUEST_FILE");
f = new File(HostPath + HTTP_REQUEST_PATH + HTTP_REQUEST_FILE);
if ((TARGET_PHP_FILES_ID = JavaDBAccess.ReadFile2DB(f, HTTP_REQUEST_HOST, HostPath, HTTP_REQUEST_PATH, JavaDBAccess, false)) > 0) {
ps = conn.prepareStatement("UPDATE TARGET_PHP_FILES_RUNS_FUNCTIONS SET TARGET_PHP_FILE=? WHERE HTTP_REQUEST_HOST=? AND HTTP_REQUEST_PATH=? AND HTTP_REQUEST_FILE=? AND TARGET_PHP_FILE IS NULL");
ps.setInt(1, TARGET_PHP_FILES_ID);
ps.setString(2, HTTP_REQUEST_HOST);
ps.setString(3, HTTP_REQUEST_PATH);
ps.setString(4, HTTP_REQUEST_FILE);
ps.executeUpdate();
ps.close();
JavaDBAccess2 = new DatabaseAccess(DBprops);
PHPFile.AnalyzePHPFile(JavaDBAccess2, f.getAbsolutePath());
JavaDBAccess2 = null;
//Process the PHP files that are included in the PHP file
JavaDBAccess.PHPFileIncludes(TARGET_PHP_FILES_ID, JavaDBAccess, PHPFile);
}
}
rs.close();
ps_http.close();
s = conn.createStatement();
//Update the TARGET_PHP_FILES_VARIABLE of the TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES
s.executeUpdate("UPDATE TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES SET TARGET_PHP_FILES_VARIABLE=(SELECT TARGET_PHP_FILES_VARIABLES.ID FROM TARGET_PHP_FILES_RUNS_FUNCTIONS, TARGET_PHP_FILES, TARGET_PHP_FILES_VARIABLES WHERE TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.TARGET_PHP_FILES_RUNS_FUNCTION=TARGET_PHP_FILES_RUNS_FUNCTIONS.ID AND TARGET_PHP_FILES_RUNS_FUNCTIONS.TARGET_PHP_FILE=TARGET_PHP_FILES.ID AND TARGET_PHP_FILES_VARIABLES.TARGET_PHP_FILE=TARGET_PHP_FILES.ID AND '$'||TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.NAME=TARGET_PHP_FILES_VARIABLES.NAME AND TARGET_PHP_FILES.PATH LIKE '%'||TARGET_PHP_FILES_RUNS_FUNCTIONS.HTTP_REQUEST_PATH||TARGET_PHP_FILES_RUNS_FUNCTIONS.HTTP_REQUEST_FILE) WHERE TARGET_PHP_FILES_VARIABLE IS NULL");
//Update the AFFECT_SQL_DYNAMIC of the TARGET_PHP_FILES_VARIABLES
s.executeUpdate("UPDATE TARGET_PHP_FILES_VARIABLES SET AFFECT_SQL_DYNAMIC='N' WHERE AFFECT_SQL_DYNAMIC='U'");
ps = conn.prepareStatement("UPDATE TARGET_PHP_FILES_VARIABLES SET AFFECT_SQL_DYNAMIC='Y' WHERE ID IN (SELECT TARGET_PHP_FILES_VARIABLE FROM TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES,HTTP_VARIABLES_SQL_QUERIES WHERE ID=TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLE AND MODE=?)");
ps.setString(1, MODE);
ps.executeUpdate();
//Update the INPUT_VARIABLE of the TARGET_PHP_FILES_VARIABLES
s.executeUpdate("UPDATE TARGET_PHP_FILES_VARIABLES SET INPUT_VARIABLE='N' WHERE INPUT_VARIABLE='U'");
ps = conn.prepareStatement("UPDATE TARGET_PHP_FILES_VARIABLES SET INPUT_VARIABLE='Y' WHERE ID IN (SELECT TARGET_PHP_FILES_VARIABLE FROM TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES WHERE MODE=?)");
ps.setString(1, MODE);
ps.executeUpdate();
//Update the DATA_TYPE according to the values existing in the HTTP data
//DATA_TYPE CHAR is used in the cases where both NUMERIC and CHAR values are used in the variable
ps = conn.prepareStatement("UPDATE TARGET_PHP_FILES_VARIABLES SET DATA_TYPE=(SELECT MIN(DATA_TYPE) FROM TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES WHERE TARGET_PHP_FILES_VARIABLES.ID=TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.TARGET_PHP_FILES_VARIABLE AND MODE=?)");
ps.setString(1, MODE);
ps.executeUpdate();
ps.close();
s.close();
conn.commit();
conn.close();
} catch (Throwable e) {
InspectionTextArea.setText("Errors in HTTP2WebApplication executed!");
System.out.println(
"exception thrown:");
if (e instanceof SQLException) {
JavaDBAccess.printSQLError((SQLException) e);
} else {
e.printStackTrace();
}
}
} | 5 |
public void updateImage()
{
//we will update animation when delay counter reaches delay, then reset delay counter
delayCounter++;
if(delayCounter>delay)
{
delayCounter=0;
frameNumber++;//updates frame to next frame
frameNumber%=totalFrame;// if surpass 3rd frame, back to frameNumber 0
//sets image to specific frameNumber by multiplying it with 500, aka width of the image
this.setImage(frameNumber*65+frameNumber+5,yLocationSpriteSheet,width,height ,newWidth, newHeight );
}
} | 1 |
@Override
public SnpEffectPredictor create() {
// Create chromo
chromo = new Chromosome(genome, 0, 2 * maxGeneLen, 1, "chr1");
genome.add(chromo);
// Create sequence
chromoSequence = GprSeq.randSequence(random, chromo.size());
// Create gene
int start = random.nextInt(maxGeneLen);
int end = start + Math.max(minGeneSize, random.nextInt(maxGeneLen));
int strand = random.nextBoolean() ? 1 : -1;
if (forcePositive) strand = 1;
Gene gene = new Gene(chromo, start, end, strand, "gene1", "gene1", "gene");
add(gene);
// Create transcripts
int numTr = Math.max(random.nextInt(maxTranscripts), 1);
for (int nt = 0; nt < numTr; nt++)
createTranscript(gene, "" + nt);
return snpEffectPredictor;
} | 3 |
public boolean isMatch(String s, String p) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < p.length(); ++i){
if(p.charAt(i) != '*') sb.append(p.charAt(i));
else {
if(i == 0 || i > 0 && p.charAt(i-1) != '?'){
sb.append("?*");
}else{
sb.append("*");
}
}
}
return isMatchRec(s, sb.toString());
} | 5 |
public static int getFByYaw(float yaw) {
float f = (yaw * 4.0f / 360.0f);
if (f < 0) {
f = 4 - Math.abs(f);
}
return Math.round(f);
} | 1 |
public double getValueRomberg(double a, double b, double eps) {
int m, n, i, k;
double h, ep, p, x, s, q = 0;
double[] y = new double[10];
// 迭代初值
h = b - a;
y[0] = h * (func(a) + func(b)) * 0.5;
m = 1;
n = 1;
ep = eps + 1.0;
// 迭代计算
while ((ep >= eps) && (m <= 9)) {
p = 0.0;
for (i = 0; i <= n - 1; i++) {
x = a + (i + 0.5) * h;
p = p + func(x);
}
p = (y[0] + h * p) * 0.5;
s = 1.0;
for (k = 1; k <= m; k++) {
s = 4.0 * s;
q = (s * p - y[k - 1]) / (s - 1.0);
y[k - 1] = p;
p = q;
}
ep = Math.abs(q - y[m - 1]);
m = m + 1;
y[m - 1] = q;
n = n + n;
h = h * 0.5;
}
return (q);
} | 4 |
public void testCustomBroadcast () throws IOException {
ServerDiscoveryHandler serverDiscoveryHandler = new ServerDiscoveryHandler() {
@Override
public boolean onDiscoverHost (DatagramChannel datagramChannel, InetSocketAddress fromAddress,
Serialization serialization) throws IOException {
DiscoveryResponsePacket packet = new DiscoveryResponsePacket();
packet.id = 42;
packet.gameName = "gameName";
packet.playerName = "playerName";
ByteBuffer buffer = ByteBuffer.allocate(256);
serialization.write(null, buffer, packet);
buffer.flip();
datagramChannel.send(buffer, fromAddress);
return true;
}
};
ClientDiscoveryHandler clientDiscoveryHandler = new ClientDiscoveryHandler() {
private Input input = null;
@Override
public DatagramPacket onRequestNewDatagramPacket () {
byte[] buffer = new byte[1024];
input = new Input(buffer);
return new DatagramPacket(buffer, buffer.length);
}
@Override
public void onDiscoveredHost (DatagramPacket datagramPacket, Kryo kryo) {
if (input != null) {
DiscoveryResponsePacket packet;
packet = (DiscoveryResponsePacket)kryo.readClassAndObject(input);
info("test", "packet.id = " + packet.id);
info("test", "packet.gameName = " + packet.gameName);
info("test", "packet.playerName = " + packet.playerName);
info("test", "datagramPacket.getAddress() = " + datagramPacket.getAddress());
info("test", "datagramPacket.getPort() = " + datagramPacket.getPort());
assertEquals(42, packet.id);
assertEquals("gameName", packet.gameName);
assertEquals("playerName", packet.playerName);
assertEquals(udpPort, datagramPacket.getPort());
}
}
@Override
public void onFinally () {
if (input != null) {
input.close();
}
}
};
// This server exists solely to reply to Client#discoverHost.
// It wouldn't be needed if the real server was using UDP.
final Server broadcastServer = new Server();
broadcastServer.getKryo().register(DiscoveryResponsePacket.class);
broadcastServer.setDiscoveryHandler(serverDiscoveryHandler);
startEndPoint(broadcastServer);
broadcastServer.bind(0, udpPort);
final Server server = new Server();
startEndPoint(server);
server.bind(54555);
server.addListener(new Listener() {
public void disconnected (Connection connection) {
broadcastServer.stop();
server.stop();
}
});
// ----
Client client = new Client();
client.getKryo().register(DiscoveryResponsePacket.class);
client.setDiscoveryHandler(clientDiscoveryHandler);
InetAddress host = client.discoverHost(udpPort, 2000);
if (host == null) {
stopEndPoints();
fail("No servers found.");
return;
}
startEndPoint(client);
client.connect(2000, host, tcpPort);
client.stop();
waitForThreads();
} | 3 |
private void drawAllBonds() {
for (int i = 0; i < bonds.length; i++) {
int n = Integer.parseInt(bonds[i][0]);
if (bonds[i][1].equals("R")) {
drawBond(n, 0, false);
} else if (bonds[i][1].equals("L")) {
drawBond(n, Math.PI, true);
} else if (bonds[i][1].equals("D")) {
drawBond(n, Math.PI / 2, false);
} else if (bonds[i][1].equals("U")) {
drawBond(n, - Math.PI / 2, true);
} else if (bonds[i][1].equals("LU")) {
drawBond(n, -0.75 * Math.PI, true);
} else if (bonds[i][1].equals("RD")) {
drawBond(n, 0.25 * Math.PI, false);
} else if (bonds[i][1].equals("RU")) {
drawBond(n, -0.25 * Math.PI, false);
} else if (bonds[i][1].equals("LD")) {
drawBond(n, 0.75 * Math.PI, true);
}
}
} | 9 |
protected boolean writeDailyLog(String logStr, Time logTime) {
boolean ret = false;
Path logFilePath;
if ((logStr != null) && (logTime != null)) {
try {
if ((m_curLog == null) || (m_curLogTime == null) || (!m_curLogTime.isSameDay(logTime))) {
if (m_curLog != null) {
m_curLog.close();
m_curLog = null;
}
logFilePath = Paths.get(m_logFile, logTime.getDateFileName() + ".log");
if (Files.exists(logFilePath)) {
m_curLog = Files.newBufferedWriter(logFilePath, m_logCharSet, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
} else {
m_curLog = Files.newBufferedWriter(logFilePath, m_logCharSet, StandardOpenOption.CREATE_NEW);
}
m_curLogTime = logTime;
}
m_curLog.write(logStr);
} catch (IOException e) {
System.out.printf("Failed to operate log file by the reason %s", e);
}
}
return ret;
} | 8 |
private void ChooseAction(Socket s) throws IOException, ClassNotFoundException {
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
Message msg = (Message) in.readObject();
if (msg.getType().equals("CONNECT")) {
mypeer.addNeighbor(msg.getHost(), msg.getPort());
} else if (msg.getType().equals("SEARCH")) {
LinkedList<PeerInfo> returnList = new LinkedList<PeerInfo>();
/*search my files*/
if (mypeer.searchMyFiles(msg.getFilename()) == true) {
returnList.add(new PeerInfo(this.socket.getLocalPort(), String.valueOf(this.socket.getInetAddress())));
}
/*send request to neighbors except sender if ttl>0*/
if (msg.getTtl() > 0) {
for (int i = 0; i < mypeer.neighbours.size(); i++) {
if (!mypeer.neighbours.get(i).getUsername().equals(msg.getSender())) {
Socket socketToConnect = new Socket(mypeer.neighbours.get(i).getHost(), mypeer.neighbours.get(i).getPort());
ObjectOutputStream out2 = new ObjectOutputStream(socketToConnect.getOutputStream());
/*Send the request*/
Message msg2 = new Message("SEARCH", msg.getFilename(), null, 0, this.myusername, msg.getTtl() - 1, null);
out2.writeObject(msg2);
out2.flush();
/*Receive the response*/
ObjectInputStream in2 = new ObjectInputStream(socketToConnect.getInputStream());
Message msgres = (Message) in2.readObject();
if (msgres.getType().equals("SEARCHRES")) {
for (int j = 0; j < msgres.getSearchres().size(); j++) {
returnList.add(msgres.getSearchres().get(j));
}
}
out2.close();
in2.close();
socketToConnect.close();
}
}
}
/*send list to sender*/
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
/*Send the request*/
Message msgres = new Message("SEARCHRES", msg.getFilename(), null, 0, this.myusername, 0, returnList);
out.writeObject(msgres);
out.flush();
out.close();
} else if (msg.getType().equals("FILEREQ")) {
String fileName = mypeer.getSharedFolder() + msg.getFilename();
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
//Start a fileInputStream to read bytes from the requested file.
//System.out.println("sdfd"+myFile);
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
//Read as many bytes as the size of the file to be sent.
bis.read(mybytearray, 0, mybytearray.length);
out.write(mybytearray, 0, mybytearray.length);
out.flush();
out.close();
}
in.close();
} | 9 |
public int divide(int dividend, int divisor) {
if (divisor == 0)
throw new ArithmeticException("devide by zero");
// convert dividend and divisor to negative numbers a and b
int a = (dividend < 0) ? dividend : (0 - dividend);
int b = (divisor < 0) ? divisor : (0 - divisor);
// check the sign of the output
return (dividend ^ divisor) < 0 ? (0 - divideHelper(a, b))
: divideHelper(a, b);
} | 4 |
public void getTickets(String fechaDesde, String fechaHasta, String lineaAerea, String nfile, String numeroTicket) throws SQLException {
tickets = TicketDAO.getInstance().getTickets(fechaDesde, fechaHasta, lineaAerea, nfile, numeroTicket);
if (tickets.isEmpty()) {
JOptionPane.showMessageDialog(null, "No se han encotrado registros.");
}
} | 1 |
@Test
public void func1() throws Exception {
List<Compound> l = new ArrayList<Compound>();
for (int i = 0; i < 10; i++) {
HRU c = new HRU();
c.in = "1-" + i;
l.add(c);
}
// long start = System.currentTimeMillis();
// Runner.parallel2(l);
// long end = System.currentTimeMillis();
HRU c = new HRU();
c.in = "1";
c.execute();
Assert.assertEquals("CMD2(CMD1(1))", c.out);
} | 1 |
public void createRoster()
{
Calendar today = (Calendar) startDate.clone();
int count;
for(int i=0; i<numberOfDays; i++)
{
count = 0;
numberOfServices = getNumberOfServices(today.getTime());
driversUsed = new driverUsed[numberOfServices];
busesUsed = new busUsed[numberOfServices];
getServices(today); // correct it!
packs[i] = new Pack[numberOfServices];
for(int j=0; j<numberOfServices; j++)
{
packs[i][j] = new Pack();
packs[i][j].serv = getNextService();// correct it!
packs[i][j].driver_id = getLeastWorkingDriver(drivers, today.getTime(), packs[i][j].serv); // correct it!
packs[i][j].bus_id = getAvailableBus(buses, today.getTime(), packs[i][j].serv); // correct it!
int findDriver = 0;
int findBus = 0;
for(int k = 0; k < drivers.length; k++)
if(packs[i][j].driver_id == drivers[k])
{
findDriver = k;
}
for(int k = 0; k < buses.length; k++)
if(packs[i][j].bus_id == buses[k])
{
findBus = k;
}
minutesDriverWorked[findDriver] += (packs[i][j].serv.endtime) - (packs[i][j].serv.starttime);
minutesBusWorked[findBus] += (packs[i][j].serv.endtime) - (packs[i][j].serv.starttime);
}
today.add(Calendar.DAY_OF_MONTH, 1);
driversUsedIndex = 0;
busesUsedIndex = 0;
}
printPacks();
toDatabase(packs);
} | 6 |
private boolean checkStop(double[] rst, double minDL, double dl){
if(dl > minDL+MAX_DL_SURPLUS){
if(m_Debug)
System.err.println("DL too large: "+dl+" | "+minDL);
return true;
}
else
if(!Utils.gr(rst[2], 0.0)){// Covered positives
if(m_Debug)
System.err.println("Too few positives.");
return true;
}
else if((rst[4]/rst[0]) >= 0.5){// Err rate
if(m_CheckErr){
if(m_Debug)
System.err.println("Error too large: "+
rst[4] + "/" + rst[0]);
return true;
}
else
return false;
}
else{// Not stops
if(m_Debug)
System.err.println("Continue.");
return false;
}
} | 8 |
@Override
public void actionPerformed(ActionEvent event) {
if ((event.getSource().equals(btnOk)) || (event.getSource().equals(btnCancel))) {
modalResult = (event.getActionCommand().equals("ok"));
MainWindow.setupData.setEventStartDate(eventStart.getTime());
MainWindow.setupData.setEventEndDate(eventEnd.getTime());
setVisible(false);
}
} | 2 |
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(MasaKapatV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MasaKapatV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MasaKapatV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MasaKapatV.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 MasaKapatV().setVisible(true);
}
});
} | 6 |
public boolean containsAndDeletes(int fRow, int fCol, int toRow, int toCol, int [][] a) {
for (int i = 0; i < moveList.size(); i++){
if (moveList.get(i).getFromRow() == fRow && moveList.get(i).getFromCol() == fCol && moveList.get(i).getToRow() == toRow && moveList.get(i).getToCol() == toCol){
for (int p = 0; p < 8; p++){
for (int q = 0; q < 8; q++){
if (a [p][q] == moveList.get(i).getResultSq(p, q));
else return false;
}
}
moveList.remove(i);
return true;
}
}
return false;
} | 8 |
public void attackBuilding(Unit attacker, Building toBeAttacked,
boolean aiMove) {
if (aiMove || Teams.comparePlayers(this.getOwner(),game.getCurrentPlayer())) {
HashSet<Player> tmp = Teams.getTeamFriends(Teams
.getTeamOfPlayer(owner));
if (attacker.getAttacked() == true) {
game.mapPanel.Notify("A unit can only attack once per turn!");
} else if (tmp.contains(toBeAttacked.getOwner())) {
game.mapPanel.Notify("You cannot attack allied units!");
} else {
moveToCell(this, this.getCell(),
moveToAttack(toBeAttacked.getCell()), true);
toBeAttacked.attacked(attacker);
attacked = true;
}
} else {
game.mapPanel.Notify("You can only attack buildings with your units!");
}
} | 4 |
protected List refreshTicksVertical(Graphics2D g2,
Rectangle2D dataArea,
RectangleEdge edge) {
List result = new java.util.ArrayList();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
if (isAutoTickUnitSelection()) {
selectAutoTickUnit(g2, dataArea, edge);
}
DateTickUnit unit = getTickUnit();
Date tickDate = calculateLowestVisibleTickValue(unit);
//Date upperDate = calculateHighestVisibleTickValue(unit);
Date upperDate = getMaximumDate();
while (tickDate.before(upperDate)) {
if (!isHiddenValue(tickDate.getTime())) {
// work out the value, label and position
String tickLabel;
DateFormat formatter = getDateFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(tickDate);
}
else {
tickLabel = this.tickUnit.dateToString(tickDate);
}
TextAnchor anchor = null;
TextAnchor rotationAnchor = null;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
if (edge == RectangleEdge.LEFT) {
angle = -Math.PI / 2.0;
}
else {
angle = Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
}
else {
anchor = TextAnchor.CENTER_LEFT;
rotationAnchor = TextAnchor.CENTER_LEFT;
}
}
Tick tick = new DateTick(tickDate, tickLabel, anchor,
rotationAnchor, angle);
result.add(tick);
tickDate = unit.addToDate(tickDate);
}
else {
tickDate = unit.rollDate(tickDate);
}
}
return result;
} | 7 |
public List<Dependency> getRelocatedArtifacts() {
List<Dependency> artifacts = new ArrayList<Dependency>();
if (relocate != null) {
for (String element : relocate.split(",")) {
String[] coordinates = element.split(":");
if (coordinates.length < 2) {
throw new IllegalArgumentException("Malformed relocated artifact: " + element);
}
String groupId = coordinates[0];
String artifactId = coordinates[1];
String version = coordinates.length >= 3 ? coordinates[2] : "debian";
artifacts.add(new Dependency(groupId, artifactId, null, version));
}
}
return artifacts;
} | 4 |
@Test
public void branchInstrInvalidOpcodeTest_BRE() { //Tests instruction isn't created with illegal opcode for format
try {
instr = new BranchInstr(Opcode.BRE, 0); //BRE requires 3 parameters; the third representing a register
}
catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
assertNull(instr); //instr should be null if creation has failed, which it should because of invalid opcode
} | 1 |
public void enrgOffre(String v_titre, String v_region, int v_exp, int v_salMin, int v_salMax, HashMap<Competence, CompType> tblComps) {
try {
int compsSize = tblComps.size();
System.out.println("size" + tblComps.size());
System.out.println(tblComps);
String compstr = "";
//for(Competence comp:c)
// for(int i = 0; i < compsSize; i++){
// compstr += c.get(i).getNomComp() + m_compTypeDelim;
// System.out.println("compstr :" + compstr);
// if(c.get(i).isObligatoire()) {
// compstr += "1";
// }
// else {
// compstr += "0";
// }
// if(i < compsSize - 1){
// compstr += m_compDelim;
// }
// }
Iterator iter = tblComps.keySet().iterator();
while (iter.hasNext()) {
Competence key = (Competence) iter.next();
compstr += key.getNomComp() + m_compTypeDelim;
System.out.println("saved compstr :" + compstr);
compstr += tblComps.get(key).getLibType() + m_compDelim;
}
if (compstr.length() > 0 && compstr.charAt(compstr.length() - 1)==m_compDelim) {
compstr = compstr.substring(0, compstr.length()-1);
}
String content = v_titre + m_itemDelim
+ v_region + m_itemDelim
+ v_exp + m_itemDelim
+ v_salMin + m_itemDelim
+ v_salMax + m_itemDelim + compstr;
File file = new File(m_offreList);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.newLine();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} | 5 |
public Tree<String> buildAST( StringTokenizer st ) {
// make our tree... the root is the string "root"
// if a node has children then it is an application
// if not then it is a value
Tree<String> tree = new Tree<String>("root");
Tree.Node<String> node = tree.getNode();
String token = ""; // used for while loop below
boolean advanceOnNext = true; // used for the loop below
// go through each token
while( st.hasMoreTokens()) {
if ( advanceOnNext ) {
token = st.nextToken().trim();
}
advanceOnNext = true;
// if our token is a '('
if ( token.compareTo("(") == 0 ) {
// get our next token... to see if we have a lambda
if ( st.hasMoreTokens() ) {
token = st.nextToken().trim();
advanceOnNext = false;
}
// it's either a lambda or an application...
if ( token.compareTo("lambda") == 0 ) {
node = node.addChild( new Tree<String>("lambda").getNode() );
advanceOnNext = true;
} else {
node = node.addChild( new Tree<String>("@").getNode() );
}
}
// end lists, apps, and lambdas
else if ( token.compareTo(")") == 0 ) {
node = node.getParent();
}
// lists
else if ( token.compareTo("'") == 0 ) {
//get our next token... to see if its '('
if ( st.hasMoreTokens() ) {
token = st.nextToken().trim();
advanceOnNext = false;
// if the next token is a '('
if ( token.compareTo("(") == 0 ) {
node = node.addChild( new Tree<String>("'").getNode() );
advanceOnNext = true;
}
}
}
// otherwise... (ID's value's...)
else {
node.addChild( new Tree<String>( token ).getNode() );
}
}
return tree;
} | 9 |
public static String printCFGBody(Block root, String blockName, boolean wholeGraph) {
StringBuilder sb = new StringBuilder();
if (wholeGraph) {
sb.append("graph: {title: \"").append(blockName).append("CFG\"").append('\n');
// sb.append("layoutalgorithm:bfs").append('\n');
sb.append("manhattan_edges:yes").append('\n');
sb.append("smanhattan_edges:yes").append('\n');
}
Queue<Block> queue = new LinkedList<Block>();
HashSet<Block> visited = new HashSet<Block>();
queue.add(root);
while (!queue.isEmpty()) {
Block b = queue.remove();
if (b == null || visited.contains(b)) {
continue;
}
visited.add(b);
sb.append("node: {").append('\n');
sb.append("title: \"" + b.getID() + "\"").append('\n');
sb.append("label: \"" + b.getID() + "\n[");
sb.append(b.toString());
sb.append("]\"\n").append("}\n");
if (b.getNextBlock() != null) {
sb.append("edge: { sourcename: \"" + b.getID() + "\"").append('\n');
sb.append("targetname: \"" + b.getNextBlock().getID() + "\"").append('\n');
sb.append("label: \"" + b.getNextBlock().getID() + "\"").append('\n');
sb.append("}\n");
}
if (b.getNegBranchBlock() != null) {
sb.append("edge: { sourcename: \"" + b.getID() + "\"").append('\n');
sb.append("targetname: \"" + b.getNegBranchBlock().getID() + "\"").append('\n');
sb.append("label: \"" + b.getNegBranchBlock().getID() + "\"").append('\n');
sb.append("}\n");
}
queue.add(b.getNextBlock());
queue.add(b.getNegBranchBlock());
// print function branch
for (Entry<Block, Integer> entry : b.functionJumpToBlocks) {
sb.append("edge: { sourcename: \"" + b.getID() + "\"").append('\n');
sb.append("targetname: \"" + entry.getKey().getID() + "\"").append('\n');
sb.append("label: \"j" + entry.getValue() + "\"").append('\n');
sb.append("color:red");
sb.append("}\n");
queue.add(entry.getKey());
}
// // print dominator
// for (Block entry : b.dominators) {
// if (entry == b) {
// continue;
// }
// sb.append("edge: { sourcename: \"" + entry.getID() +
// "\"").append('\n');
// sb.append("targetname: \"" + b.getID() + "\"").append('\n');
// sb.append("color:green");
// sb.append("}\n");
// }
// for (Entry<Block, Integer> entry : b.functionPopBackToBlocks) {
// sb.append("edge: { sourcename: \"" + b.getID() +
// "\"").append('\n');
// sb.append("targetname: \"" + entry.getKey().getID() +
// "\"").append('\n');
// sb.append("label: \"p" + entry.getValue() + "\"").append('\n');
// sb.append("color:red");
// sb.append("}\n");
// queue.add(entry.getKey());
// }
}
if (wholeGraph) {
sb.append('}');
}
return sb.toString();
} | 8 |
public final void cleanUp() {
Bucket died;
while ((died = (Bucket) queue.poll()) != null) {
int diedSlot = Math.abs(died.hash % buckets.length);
if (buckets[diedSlot] == died)
buckets[diedSlot] = died.next;
else {
Bucket b = buckets[diedSlot];
while (b.next != died)
b = b.next;
b.next = died.next;
}
size--;
}
} | 3 |
public void click() {
JPopupMenu menu = new JPopupMenu();
List<DockTab> tabs = new ArrayList<>(mHidden);
Collections.sort(tabs);
for (DockTab tab : tabs) {
JMenuItem item = new JMenuItem(tab.getFullTitle(), tab.getIcon());
item.putClientProperty(this, tab.getDockable());
item.addActionListener(this);
menu.add(item);
}
menu.show(this, 0, 0);
} | 1 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
public static void main(String[] args) {
String[] hexList;
Scanner scanner = new Scanner(System.in);
do {
// Read input, until it has correct length (normally 8 bytes = 16 hex digits)
do {
// Read line
System.out.println("Please enter " + numberOfRows + " hexadecimal bytes:");
String line = scanner.nextLine();
// Split line into array
hexList = line.split("\\s+");
// Too many or too few bytes entered -> message
if (hexList.length != numberOfBytes) {
System.out.println("You have to enter exactly " + numberOfBytes + " bytes!");
}
}
while (hexList.length != numberOfBytes);
// Convert each byte to binary, create the string representation and print it out
// E.g. "FF" -> 255
int hexToDecimal;
// E.g. "11111111"
String binary;
for (int i = 0; i < hexList.length; i++) {
try {
hexToDecimal = Integer.parseInt(hexList[i], 16);
}
catch (NumberFormatException e) {
System.out.println(hexList[i] + " is not in hexadecimal format, line " + (i + 1) + " could not be created!");
continue;
}
binary = Integer.toBinaryString(hexToDecimal);
// Add leading zeros (if lost during conversion)
binary = String.format("%1$" + numberOfBytes + "s", binary).replace(' ', '0');
// Replace Ones and Zeros with corresponding symbols
binary = binary.replaceAll("1", outputSymbolOne).replaceAll("0", outputSymbolZero);
System.out.println(binary);
}
System.out.println("\nTry again? (y/n):");
}
while (scanner.nextLine().equals("y"));
// Input finished
scanner.close();
System.out.println("Program ended successfully!");
} | 5 |
public static TunableParameters getInstance(){
if(_currentInstance == null)
_currentInstance = new TunableParameters();
return _currentInstance;
} | 1 |
@Override
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (isVisible()
&& (e.getSource() == optionPane)
&& (JOptionPane.VALUE_PROPERTY.equals(prop)
|| JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
Object value = optionPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE) {
//ignore reset
return;
}
optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
if (OK_BUTTON.equals(value)) {
typedText = textField.getText();
if (nameValidator.isValid(typedText)) {
clearAndHide();
} else {
textField.selectAll();
JOptionPane.showMessageDialog(
CustomJDialog.this,
"Имя \"" + typedText + "\" использовать нельзя. Пожалуйста введите другое имя.",
"Ошибка",
JOptionPane.ERROR_MESSAGE);
typedText = null;
textField.requestFocusInWindow();
}
} else {
typedText = null;
clearAndHide();
}
}
} | 7 |
@Override
public double[] calculateFractal3DWithoutPeriodicity(Complex pixel) {
iterations = 0;
Complex tempz = new Complex(pertur_val.getPixel(init_val.getPixel(pixel)));
Complex[] complex = new Complex[2];
complex[0] = tempz;//z
complex[1] = new Complex(pixel);//c
Complex zold = new Complex();
if(parser.foundS()) {
parser.setSvalue(new Complex(complex[0]));
}
if(parser2.foundS()) {
parser2.setSvalue(new Complex(complex[0]));
}
if(parser.foundP()) {
parser.setPvalue(new Complex());
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex());
}
double temp;
for(; iterations < max_iterations; iterations++) {
if(bailout_algorithm.escaped(complex[0], zold)) {
Object[] object = {iterations, complex[0], zold};
temp = out_color_algorithm.getResult(object);
double[] array = {Math.abs(temp) - 100800, temp};
return array;
}
zold.assign(complex[0]);
function(complex);
if(parser.foundP()) {
parser.setPvalue(new Complex(zold));
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex(zold));
}
}
Object[] object = {complex[0], zold};
temp = in_color_algorithm.getResult(object);
double result = temp == max_iterations ? max_iterations : max_iterations + Math.abs(temp) - 100820;
double[] array = {result, temp};
return array;
} | 9 |
public void setId(int id) {
this.id = id;
} | 0 |
public int nextIndex() {
if (next == null) {
return size();
}
if (cache == null) {
cache = toArray();
}
return next.index;
} | 2 |
public T getAt(int row, int col) throws ArrayIndexOutOfBoundsException {
if (row>rows || col>columns || row<0 || col<0)
throw new ArrayIndexOutOfBoundsException();
if (RList.getHead()==null && CList.getHead()==null)
return null;
if (RList.isInList(row) && CList.isInList(col)){
Node<T> n = findNodeAt(row, col);
return n.getData();
}
else
return null;
} | 8 |
@Override
public Usuario findByLoginSenha(Usuario usuario) {
EntityManagerFactory factory = Persistence
.createEntityManagerFactory("classeEncanto");
EntityManager em = beginTransaction(factory);
try {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Usuario> criteria = builder
.createQuery(Usuario.class);
Root<Usuario> usuarioRoot = criteria.from(Usuario.class);
Predicate restricaoDeUsuarios = builder
.and(builder.equal(usuarioRoot.get("login"),
usuario.getLogin()),
builder.equal(usuarioRoot.get("senha"),
usuario.getSenha()));
if (usuario.isAdmin()) {
restricaoDeUsuarios = builder.and(
restricaoDeUsuarios,
builder.equal(usuarioRoot.get("admin"),
usuario.isAdmin()));
}
criteria.distinct(true).where(restricaoDeUsuarios);
TypedQuery<Usuario> query = em.createQuery(criteria);
List<Usuario> resultList = query.getResultList();
if (resultList != null && !resultList.isEmpty()) {
usuario = resultList.get(0);
for (UsuarioProduto usuarioProduto: usuario.getListaDeDesejos()){
usuarioProduto.setProduto(usuarioProduto.getProduto());
}
usuario.setListaDeDesejos(usuario.getListaDeDesejos());
} else {
usuario = null;
}
return usuario;
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
endTransaction(em, factory);
}
} | 5 |
public Object getValueAt(int row, int column) {
if (column == 0)
return variables[row];
return spaceSet(entries[row][column - 1]);
} | 1 |
public boolean addSignalisationRoute(String nomR, Signalisation s) {
if (mapRouteSignalisation.containsKey(nomR)) {
int index = 0;
boolean b = false;
for (int i = 0; i < this.listeRoutes.size(); i++) {
if (this.listeRoutes.get(i).getNomRoute().equals(nomR)) {
index = i;
}
}
if (listeRoutes.get(index).ajouterSignalisation(s)) {
List<Signalisation> signalisations = mapRouteSignalisation.get(nomR);
signalisations.add(s);
mapRouteSignalisation.put(nomR, signalisations);
return true;
}
}
return false;
} | 4 |
public void runFixedTimeSteps() {
long lastTime = System.nanoTime();
double lag = 0;
isPreRendering(true);
boolean doRendering = false;
while (isRunning && !Display.isCloseRequested()) {
long currentTime = System.nanoTime();
double timeDiff = (currentTime - lastTime) / 1000000d;
lastTime = currentTime;
lag += timeDiff;
doRendering = lag >= framePeriod;
if (doRendering) {
isPreRendering(false);
while (true) {
lag -= framePeriod;
if (lag < framePeriod) {
isPreRendering(true);
update(this);
break;
}
update(this);
}
}
if (Display.wasResized()) {
onSurfaceChanged(Display.getWidth(), Display.getHeight());
doRendering = true;
}
if (doRendering) {
render();
Display.update();
} else {
long sleep = Math.round(framePeriod - lag);
if (sleep == 0)
sleep = 1;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
}
}
}
Display.destroy();
} | 9 |
public static int isVersionGreater(String base, String test)
{
base = convertOldReleases(base);
test = convertOldReleases(test);
if(base.equalsIgnoreCase(test))
return 0;
StringTokenizer t1 = new StringTokenizer(base, ".");
StringTokenizer t2 = new StringTokenizer(test, ".");
while(t1.hasMoreTokens() || t2.hasMoreTokens())
{
int i1 = t1.hasMoreTokens() ? Integer.parseInt(t1.nextToken()) : 0;
int i2 = t2.hasMoreTokens() ? Integer.parseInt(t2.nextToken()) : 0;
if(i1 != i2)
return i2 - i1;
}
return test.compareTo(base);
} | 6 |
private void paintWrappedLineNumbers(Graphics g, Rectangle visibleRect) {
// The variables we use are as follows:
// - visibleRect is the "visible" area of the text area; e.g.
// [0,100, 300,100+(lineCount*cellHeight)-1].
// actualTop.y is the topmost-pixel in the first logical line we
// paint. Note that we may well not paint this part of the logical
// line, as it may be broken into many physical lines, with the first
// few physical lines scrolled past. Note also that this is NOT the
// visible rect of this line number list; this line number list has
// visible rect == [0,0, insets.left-1,visibleRect.height-1].
// - offset (<=0) is the y-coordinate at which we begin painting when
// we begin painting with the first logical line. This can be
// negative, signifying that we've scrolled past the actual topmost
// part of this line.
// The algorithm is as follows:
// - Get the starting y-coordinate at which to paint. This may be
// above the first visible y-coordinate as we're in line-wrapping
// mode, but we always paint entire logical lines.
// - Paint that line's line number and highlight, if appropriate.
// Increment y to be just below the are we just painted (i.e., the
// beginning of the next logical line's view area).
// - Get the ending visual position for that line. We can now loop
// back, paint this line, and continue until our y-coordinate is
// past the last visible y-value.
// We avoid using modelToView/viewToModel where possible, as these
// methods trigger a parsing of the line into syntax tokens, which is
// costly. It's cheaper to just grab the child views' bounds.
// Some variables we'll be using.
int width = getWidth();
RTextAreaUI ui = (RTextAreaUI)textArea.getUI();
View v = ui.getRootView(textArea).getView(0);
//boolean currentLineHighlighted = textArea.getHighlightCurrentLine();
Document doc = textArea.getDocument();
Element root = doc.getDefaultRootElement();
int lineCount = root.getElementCount();
int topPosition = textArea.viewToModel(
new Point(visibleRect.x,visibleRect.y));
int topLine = root.getElementIndex(topPosition);
FoldManager fm = ((RSyntaxTextArea)textArea).getFoldManager();
// Compute the y at which to begin painting text, taking into account
// that 1 logical line => at least 1 physical line, so it may be that
// y<0. The computed y-value is the y-value of the top of the first
// (possibly) partially-visible view.
Rectangle visibleEditorRect = ui.getVisibleEditorRect();
Rectangle r = LineNumberList.getChildViewBounds(v, topLine,
visibleEditorRect);
int y = r.y;
final int RHS_BORDER_WIDTH = getRhsBorderWidth();
int rhs;
boolean ltr = getComponentOrientation().isLeftToRight();
if (ltr) {
rhs = width - RHS_BORDER_WIDTH;
}
else { // rtl
rhs = RHS_BORDER_WIDTH;
}
int visibleBottom = visibleRect.y + visibleRect.height;
FontMetrics metrics = g.getFontMetrics();
// Keep painting lines until our y-coordinate is past the visible
// end of the text area.
g.setColor(getForeground());
while (y < visibleBottom) {
r = LineNumberList.getChildViewBounds(v, topLine, visibleEditorRect);
/*
// Highlight the current line's line number, if desired.
if (currentLineHighlighted && topLine==currentLine) {
g.setColor(textArea.getCurrentLineHighlightColor());
g.fillRect(0,y, width,(r.y+r.height)-y);
g.setColor(getForeground());
}
*/
// Paint the line number.
int index = (topLine+1) + getLineNumberingStartIndex() - 1;
String number = Integer.toString(index);
if (ltr) {
int strWidth = metrics.stringWidth(number);
g.drawString(number, rhs-strWidth,y+ascent);
}
else {
int x = RHS_BORDER_WIDTH;
g.drawString(number, x, y+ascent);
}
// The next possible y-coordinate is just after the last line
// painted.
y += r.height;
// Update topLine (we're actually using it for our "current line"
// variable now).
Fold fold = fm.getFoldForLine(topLine);
if (fold!=null && fold.isCollapsed()) {
topLine += fold.getCollapsedLineCount();
}
topLine++;
if (topLine>=lineCount)
break;
}
} | 6 |
public String getScript(String scriptName) {
InputStream stream = null;
try {
stream = ClassLoader.getSystemResourceAsStream(scriptName);
@SuppressWarnings("resource")
Scanner s = new Scanner(stream).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
} catch (Exception e) {
_logger.error("Failed to open the " + scriptName
+ " for processing");
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
_logger.error("Failed to close the script file Input Stream for file "
+ scriptName);
}
}
return "";
// throw new Exception("Script file is missing: " + scriptName);
} | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Antwort))
return false;
Antwort other = (Antwort) obj;
if (antwort == null) {
if (other.antwort != null)
return false;
} else if (!antwort.equals(other.antwort))
return false;
if (korrekt != other.korrekt)
return false;
return true;
} | 7 |
private static boolean isInUsefulVariableSet(char ch, Set set) {
Iterator it = set.iterator();
while (it.hasNext()) {
String variable = (String) it.next();
char var = variable.charAt(0);
if (ch == var) {
return true;
}
}
return false;
} | 2 |
@SuppressWarnings("unused")
private void Chrwood() {
if(this.vie <= 0){
this.killAgent(this);
this.curent.personne.remove(this);
}
switch(this.al.IA){
case 2 : IA2(); break;
case 3 : IA3(); break;
default : IA1(); break;
}
} | 3 |
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
JTextField editor = new JTextField();
if (value != null) {
editor.setText(value.toString());
}
editor.setForeground(Color.BLACK);
//if(Gui.getCurrentPrescription().getPayStatus()){
editor.setFont(new Font("Comic Sans",Font.BOLD, 13));
if(!table.getValueAt(row,6).toString().equals("0")){
if(table.getValueAt(row,7).equals(true)){
editor.setBackground(Color.green);
editor.setForeground(Color.BLACK);}
else if(table.getValueAt(row,7).equals(false)){
editor.setBackground(Color.red);
editor.setForeground(Color.WHITE);}}
else editor.setBackground(Color.GRAY);
return editor;
} | 4 |
public List<PlayerInfo> getPlayers() {
List<PlayerInfo> playersInfo = new ArrayList<PlayerInfo>();
for (Player p : players)
playersInfo.add(new PlayerInfo(p));
return playersInfo;
} | 1 |
public static void main(String[] args) {
ArrayList newWordList = new ArrayList();
ArrayList filteredWordList = new ArrayList();
try {
FileInputStream fstream = new FileInputStream("newword.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Lines contains special characters will be skipped
if (strLine.indexOf('/') > 0 || strLine.indexOf('�') > 0
|| strLine.indexOf(';') > 0 || strLine.indexOf('#') > 0
|| strLine.indexOf(']') > 0)
continue;
// Replacing all non-alphanumeric characters with empty strings
strLine = strLine.replaceAll("[^A-Za-z- ]", "");
// strLine = strLine.replaceAll(" ", "");
// Replacing multiple spaces with single space
// strLine = strLine.replaceAll("( )+", " ");
if (strLine.length() > 1) {
System.out.println(strLine + ": " + strLine.length());
newWordList.add(strLine.trim());
} else {
filteredWordList.add(strLine.trim());
}
}
// Close the input stream
in.close();
FileOutputStream out = new FileOutputStream("newoutput11.txt");
for (int i = 0; i < newWordList.size(); i++) {
out.write(newWordList.get(i).toString().getBytes());
out.write("\r\n".getBytes());
}
// Close the output stream
out.close();
// FileOutputStream fileredOut = new
// FileOutputStream("fileredOut.txt");
// for (int i = 0; i < filteredWordList.size(); i++) {
// fileredOut.write(filteredWordList.get(i).toString().getBytes());
// fileredOut.write("\r\n".getBytes());
// }
//
// fileredOut.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
} | 9 |
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(askWind.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(askWind.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(askWind.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(askWind.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
askWind dialog = new askWind(new javax.swing.JFrame(), true, "msg");
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} | 6 |
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (request.getParameter("question") != null
&& !request.getParameter("question").isEmpty()
&& request.getParameter("reponse") != null
&& !request.getParameter("reponse").isEmpty()) {
model.Faq f = new model.Faq();
f.setQuestion(request.getParameter("question"));
f.setReponse(request.getParameter("reponse"));
try {
f.save();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
try {
User user = new User();
String requete = "";
String isAdmin = request.getParameter("isadmin");
if (isAdmin.equals("0")) {
user.setId(Integer.parseInt(request.getParameter("userId")));
requete = "UPDATE utilisateur SET ESTADMIN = true WHERE ID_UTILISATEUR = "
+ user.getId() + ";";
} else if (isAdmin.equals("1")) {
user.setId(Integer.parseInt(request.getParameter("userId")));
requete = "UPDATE utilisateur SET ESTADMIN = false WHERE ID_UTILISATEUR = "
+ user.getId() + ";";
}
model.Connexion c = new model.Connexion();
c.executeUpdate(requete);
c.close();
} catch (Exception e) {
response.getWriter().write(e.toString());
}
}
RequestDispatcher d = request
.getRequestDispatcher("administration.jsp");
d.forward(request, response);
} | 8 |
private static void loot() throws Exception
{
int goldLooted = 0;
if(killConfirmed == true)
{
switch(enemyNumber)
{
case 0:
{
goldLooted = generator.nextInt(10) + 5;
}
break;
case 1:
{
goldLooted = generator.nextInt(10) + 20;
currentMessage = "You have absorbed the dragon's soul and now your magic is 50% more powerful.";
printMessage(currentMessage);
magic = magic + (magic / 2);
}
break;
case 2:
{
goldLooted = generator.nextInt(5) + 3;
}
break;
case 3:
{
goldLooted = generator.nextInt(15) + 15;
}
break;
case 4:
{
goldLooted = generator.nextInt(10) + 10;
currentMessage = "The Prince's boots look comfortable. You put them on. Your sneak increases by 5.";
printMessage(currentMessage);
sneak = sneak + 5;
}
break;
case 5:
{
goldLooted = generator.nextInt(10) + 5;
currentMessage = "You take a bite out of the Chef's freshly made sandwich. You gain 5 health.";
printMessage(currentMessage);
health = health + 5;
}
break;
case 6:
{
goldLooted = generator.nextInt(10) + 25;
currentMessage = "You have picked up the Sentry's sword and your attack has increased by 5.";
printMessage(currentMessage);
attack = attack + 5;
}
break;
case 7:
{
goldLooted = generator.nextInt(20) + 50;
}
break;
}
}
currentMessage = "You have looted " + goldLooted + " gold from the corpse.";
printMessage(currentMessage);
totalGold = totalGold + goldLooted;
killConfirmed = false;
} | 9 |
public synchronized void init() throws ServerAlreadyStartedException {
if (alreadyStarted) {
throw new ServerAlreadyStartedException();
}
// queue = new ArrayBlockingQueue<Runnable>(10);
// threadPool = new ThreadPoolExecutor(1,1,10,TimeUnit.SECONDS,queue);
try{
LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
}catch (IOException e){
e.printStackTrace();
}
serverState.notifyAllListener(BTServerStateObservable.SERVER_STARTED);
alreadyStarted = true;
} | 2 |
public BigInteger attack(BsGs_Key key) throws Error{
BigInteger t = sqrt(key.p.subtract(BigInteger.ONE)).add(BigInteger.ONE); // t>sqrt(p)
// -------------------------
// -- Hier programmieren ---
// -------------------------
List<BigInteger> babyStep = new ArrayList<BigInteger>();
List<BigInteger> giantStep = new ArrayList<BigInteger>();
int step = 0;
BigInteger x = BigInteger.ZERO;
Boolean hit = false;
for (BigInteger i = BigInteger.ZERO; i.compareTo(t) == -1; i = i.add(BigInteger.ONE)) {
babyStep.add(key.y.multiply(key.g.modPow(i.negate(), key.p)).mod(key.p));
giantStep.add(key.g.modPow(t.multiply(i), key.p));
}
giantStep.add(key.g.modPow(t.multiply(t), key.p));
while (step < babyStep.size() && !hit) {
if (giantStep.contains(babyStep.get(step))) {
int i = step;
int j = giantStep.indexOf(babyStep.get(step));
x = BigInteger.valueOf(j).multiply(t).add(BigInteger.valueOf(i));
hit = true;
}
step = step + 1;
}
return x;
} | 4 |
public JSONObject increment(String key) throws JSONException {
Object value = this.opt(key);
if (value == null) {
this.put(key, 1);
} else if (value instanceof Integer) {
this.put(key, ((Integer) value).intValue() + 1);
} else if (value instanceof Long) {
this.put(key, ((Long) value).longValue() + 1);
} else if (value instanceof Double) {
this.put(key, ((Double) value).doubleValue() + 1);
} else if (value instanceof Float) {
this.put(key, ((Float) value).floatValue() + 1);
} else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
} | 5 |
public PublicWorkType getPublicWorkType() {
double t = nextRand();
if ( t < 0.5 )
return PublicWorkType.PRESCRIBE;
else if ( t < 0.8 )
return PublicWorkType.HOSPTILIZE;
else
return PublicWorkType.REFER;
} | 2 |
public boolean addNode(UrlNode node){
if (node.parentUrl.equals(this.selfUrl)){
childNodes.add(node) ;
return true ;
}else{
for(UrlNode urlNode : childNodes){
if( urlNode.addNode(node) )
return true ;
}
}
return false ;
} | 3 |
protected void readScaleFactors()
{
for (int i = 0; i < num_subbands; ++i)
subbands[i].read_scalefactor(stream, header);
} | 1 |
public void incrementPlayerTrappedCount(Player player) {
if (player == null)
throw new IllegalArgumentException("The given arguments are invalid!");
if (trappedPlayerCount.containsKey(player)) {
int numberOfTimes = trappedPlayerCount.get(player);
numberOfTimes++;
trappedPlayerCount.remove(player);
trappedPlayerCount.put(player, numberOfTimes);
if (numberOfTimes >= maxNumberOfTimesTrapped)
player.setPlayerStatus(PlayerStatus.LOST);
} else
trappedPlayerCount.put(player, 1);
player.skipCurrentTurn();
} | 3 |
public static void pause(double seconds) {
if (!(instance != null && instance.screen != null)) {
return;
}
if (seconds == 0) {
// waiting for the user input (press any key);
long time1 = System.currentTimeMillis();
KeyEvent event = null;
while(event == null) {
if ((System.currentTimeMillis() - time1) > 5 * 60 * 1000) {
break; // 5 minutes timeout;
}
event = instance.screen.getConsole().getLastKeyboardEvent(100);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
else if (seconds > 0) {
try {
Thread.sleep((int)(seconds * 1000));
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
} | 8 |
public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} | 9 |
public void Run() {
int Grid [][] = {
{8,02,22,97,38,15,00,40,00,75,04,05,07,78,52,12,50,77,91,8},
{49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,04,56,62,00},
{81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,03,49,13,36,65},
{52,70,95,23,04,60,11,42,69,24,68,56,01,32,56,71,37,02,36,91},
{22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80},
{24,47,32,60,99,03,45,02,44,75,33,53,78,36,84,20,35,17,12,50},
{32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70},
{67,26,20,68,02,62,12,20,95,63,94,39,63,8,40,91,66,49,94,21},
{24,55,58,05,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72},
{21,36,23,9,75,00,76,44,20,45,35,14,00,61,33,97,34,31,33,95},
{78,17,53,28,22,75,31,67,15,94,03,80,04,62,16,14,9,53,56,92},
{16,39,05,42,96,35,31,47,55,58,88,24,00,17,54,24,36,29,85,57},
{86,56,00,48,35,71,89,07,05,44,44,37,44,60,21,58,51,54,17,58},
{19,80,81,68,05,94,47,69,28,73,92,13,86,52,17,77,04,89,55,40},
{04,52,8,83,97,35,99,16,07,97,57,32,16,26,26,79,33,27,98,66},
{88,36,68,87,57,62,20,72,03,46,33,67,46,55,12,32,63,93,53,69},
{04,42,16,73,38,25,39,11,24,94,72,18,8,46,29,32,40,62,76,36},
{20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74,04,36,16},
{20,73,35,29,78,31,90,01,74,31,49,71,48,86,81,16,23,57,05,54},
{01,70,54,71,83,51,54,69,16,92,33,48,61,43,52,01,89,19,67,48}
};
// visit every cell, calculate product of down, right, and diag down left & down right
int length = 20;
int max = 0;
for (int r = 0; r < length; ++r)
{
for (int c = 0; c < length; ++c)
{
// Right
if (c <= 16)
{
max = Math.max(max, Grid[r][c] * Grid[r][c+1] * Grid[r][c+2] * Grid[r][c+3]);
}
// Down
if (r <= 16)
{
max = Math.max(max, Grid[r][c] * Grid[r+1][c] * Grid[r+2][c] * Grid[r+3][c]);
}
// Down-Right
if (r <= 16 && c <= 16)
{
max = Math.max(max, Grid[r][c] * Grid[r+1][c+1] * Grid[r+2][c+2] * Grid[r+3][c+3]);
}
// Down-Left
if (r <= 16 && c >= 3)
{
max = Math.max(max, Grid[r][c] * Grid[r+1][c-1] * Grid[r+2][c-2] * Grid[r+3][c-3]);
}
}
}
System.out.println(max);
} | 8 |
public boolean isValidMove(int startCol, int startRow, int endCol, int endRow)
{
if(!hasMoved)
{
//If first move was successful
if((startCol == endCol && endRow - startRow <= 2)
|| (startCol == endCol && startRow - endRow <= 2))
{
hasMoved = true;
System.out.println("this pawn has moved: hasMoved = " + hasMoved);
return true;
}
//If first move was not successful
return false;
}
else
{
//Check for successful subsequent moves
return (startCol == endCol && Math.abs(startRow - endRow) <= 1)
|| (startCol == endCol && Math.abs(startRow + endRow) <= 1);
}
} | 8 |
public ArrayList<NbrCostPair> getData() {
return data;
} | 0 |
public ServerInputThread(Socket socket)
{
this.socket = socket;
} | 0 |
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.