text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public boolean continueStream() {
if( this.eoiReached || this.isClosed )
return false;
if( this.stopMarkReachedIndex == -1 )
return true;
for( int i = this.stopMarkReachedIndex; i >= 0; i-- ) {
// true means: override EOI
// because: the underlying stream(s) returned -1 because a stop mark
// was reached; the aboslute EOI possible has not yet been reached.
this.currentStreams[i].continueStream( true );
}
this.stopMarkReachedIndex = -1;
return true;
}
| 4 |
@SuppressWarnings("unused")
private boolean canReachForwards( Node from, Node to, int version )
{
while ( from != null && from != to )
{
Arc a = from.pickOutgoingArc( version );
if ( a.versions.cardinality() != 1 )
return false;
if ( from != null )
from = a.to;
}
return from == to;
}
| 4 |
private String createInsert() {
StringBuilder sb = new StringBuilder();
sb.append( "\n" );
sb.append( TAB + "<insert id=\"create\" parameterType=\"" + table.getPackage() + ".domain."
+ table.getDomName() + "\">\n" );
// if the 1st column does not have: sequence disabled, and (string and
// key)
if ( !table.getColumn( 0 ).isSequenceDisabled()
&& ( !( table.getColumn( 0 ).getFldType().equalsIgnoreCase( "string" ) && table.getColumn( 0 ).isKey() ) ) ) {
sb.append( TAB + TAB + "<selectKey resultType=\"_" + table.getColumn( 0 ).getFldType().toLowerCase()
+ "\" keyProperty=\"" + table.getColumn( 0 ).getFldName() + "\" order=\"BEFORE\">\n" );
switch ( databaseType ) {
case H2:
case ORACLE:
sb.append( TAB );
sb.append( TAB );
sb.append( TAB );
sb.append( "select " );
sb.append( table.getTableName().toUpperCase() );
sb.append( "_SEQ.nextval from dual\n" );
}
sb.append( TAB + TAB + "</selectKey>\n" );
}
sb.append( TAB + TAB + "insert into " + table.getTableName().toUpperCase() + "\n" );
sb.append( TAB + TAB + "(\n" );
sb.append( TAB + TAB + TAB + getVariablesList() + "\n" + TAB + TAB + ")\n" + TAB + TAB + "values\n" + TAB + TAB
+ "(\n" );
sb.append( TAB + TAB + TAB + getjavaList() + "\n" );
sb.append( TAB + TAB + ")\n" );
sb.append( TAB + "</insert>\n" );
return sb.toString();
}
| 5 |
private static void loadPackedNPCCombatDefinitions() {
try {
RandomAccessFile in = new RandomAccessFile(PACKED_PATH, "r");
FileChannel channel = in.getChannel();
ByteBuffer buffer = channel.map(MapMode.READ_ONLY, 0,
channel.size());
while (buffer.hasRemaining()) {
int npcId = buffer.getShort() & 0xffff;
int hitpoints = buffer.getShort() & 0xffff;
int attackAnim = buffer.getShort() & 0xffff;
if(attackAnim == 65535)
attackAnim = -1;
int defenceAnim = buffer.getShort() & 0xffff;
if(defenceAnim == 65535)
defenceAnim = -1;
int deathAnim = buffer.getShort() & 0xffff;
if(deathAnim == 65535)
deathAnim = -1;
int attackDelay = buffer.get() & 0xff;
int deathDelay = buffer.get() & 0xff;
int respawnDelay = buffer.getInt();
int maxHit = buffer.getShort() & 0xffff;
int attackStyle = buffer.get() & 0xff;
int attackGfx = buffer.getShort() & 0xffff;
if(attackGfx == 65535)
attackGfx = -1;
int attackProjectile = buffer.getShort() & 0xffff;
if(attackProjectile == 65535)
attackProjectile = -1;
int agressivenessType = buffer.get() & 0xff;
npcCombatDefinitions.put(npcId, new NPCCombatDefinitions(
hitpoints, attackAnim, defenceAnim, deathAnim,
attackDelay, deathDelay, respawnDelay, maxHit,
attackStyle, attackGfx, attackProjectile,
agressivenessType));
}
channel.close();
in.close();
} catch (Throwable e) {
Logger.handle(e);
}
}
| 7 |
@SuppressWarnings ("unchecked")
protected final void append(final BaseItem item) throws NullPointerException, IllegalArgumentException {
switch (item.state()) {
case Item.CREATE_STATE:
case Item.REMOVE_STATE:
case Item.UPDATE_STATE:
if (!this.equals(item.pool())) throw new IllegalArgumentException();
this.doAppend((GItem)item);
case Item.APPEND_STATE:
return;
default:
throw new IllegalArgumentException();
}
}
| 5 |
public void move(long time) {
if (list.size() > 0) {
for (Message message : list) {
message.move(time);
}
for (Message message : list) {
if (message.state == DeliverState.delivered)
continue;
if (message.state == DeliverState.inbox) {
message.edge.to.receive(message);
} else {
break;
}
}
}
}
| 5 |
public static void main(String[] args){
Base game = new Base();
if(!windowed){
game.frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
game.frame.setUndecorated(true);
}
game.frame.setResizable(false);
game.frame.setTitle(game.title);
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
| 1 |
public int getIdTpv() {
return idTpv;
}
| 0 |
@Override
public boolean equals(Object obj){
if (obj == null || getClass() != obj.getClass()){
return false;
}else{
final EnsEtat other = (EnsEtat) obj;
if(this.isEmpty() && other.isEmpty()) return true;
for(Etat etat : this){
if(other.getEtat(etat.hashCode()) == null) return false;
}
for(Etat etat : other){
if(this.getEtat(etat.hashCode()) == null) return false;
}
return true;
}
}
| 8 |
public static ArrayList<LinkedList<TreeNode>> level(TreeNode root) {
if (root == null) {
return null;
}
int level = 0;
ArrayList<LinkedList<TreeNode>> result = new ArrayList<LinkedList<TreeNode>>();
LinkedList<TreeNode> levelList = new LinkedList<TreeNode>();
// Added root to the level list so that it can be added to the main
// result list later
levelList.add(root);
// Adding root to the result list
result.add(level, levelList);
while (true) {
// Creating a new list for each level
levelList = new LinkedList<TreeNode>();
/*
* Getting into result list and then into the specific index(level)
* and extracting the TreeNodes from the levelList and checking if
* the nodes in levelList have any children and add them to
* levelList if exists
*/
for (int i = 0; i < result.get(level).size(); i++) {
TreeNode n = result.get(level).get(i);
if (n.left != null) {
levelList.add(n.left);
}
if (n.right != null) {
levelList.add(n.right);
}
}
// If the list is not empty then add it to result
if (levelList.size() > 0) {
result.add(level + 1, levelList);
// List empty so don't add to result and we have reached at the
// leaf nodes of the tree
} else {
break;
}
// Increment level to go to next level and repeat the procedure
level++;
}
return result;
}
| 6 |
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
String text = UTFCoder.decode(message);
System.out.printf("Recieved : %s \n", text);
String[] parameter = parse(text);
if(parameter.length>=2){
if (parameter[0].equalsIgnoreCase("prepare")) {
this.sendPromise(parameter[1]);
} else if (parameter[0].equalsIgnoreCase("accept")) {
this.sendAccepted(parameter[1]);
learning(parameter[2]);
}
}
}
| 3 |
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
// The Magic Words are Squeamish Ossifrage
String M = "f20bdba6ff29eed7b046d1df9fb7000058b1ffb4210a580f748b4ac714c001bd4a61044426fb515dad3f21f18aa577c0bdf302936266926ff37dbf7035d5eeb4";
String M1 = "f20bdba6ff29eed7b046d1df9fb7000058b1ffb4210a580f748b4ac714c001bd4a61044426fb515dad3f21f18aa577c0";
String M2 = "f20bdba6ff29eed7b046d1df9fb7000058b1ffb4210a580f748b4ac714c001bd";
String M3 = "58b1ffb4210a580f748b4ac714c001bdf20bdba6ff29eed7b046d1df9fb70000";
byte[] full_bytes = bytes(M3);
log.debug(Tools.encoded0(full_bytes));
byte[] bytes = new byte[full_bytes.length];
System.arraycopy(full_bytes, 0, bytes, 0, full_bytes.length);
log.debug(Tools.encoded0(bytes));
int L = bytes.length;
Map<Integer, byte[]> pads = pads();
byte[] decoded0 = new byte[]{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09
};
byte[] decoded = new byte[]{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
boolean fail = false;
ExecutorService es = Executors.newFixedThreadPool(4);
for (int interestingByte = 0; interestingByte < 16; interestingByte++) {
if (fail) {
log.error("Incorrect!");
break;
}
fail = true;
log.debug(String.format("Started analysing [%d] byte", interestingByte + 1));
byte[] pad = pads.get(interestingByte + 1);
HashMap<Integer, Future<Integer>> tasks = new HashMap<Integer, Future<Integer>>(265);
for (int guess = 0; guess <= 255; guess++) {
byte[] bt = Arrays.copyOfRange(bytes, L - 17 - interestingByte, L - 16);
if (bt.length != interestingByte + 1) throw new RuntimeException("Incorrect size!");
if (bt.length != pad.length) throw new RuntimeException("Incorrect size!");
bt = xor(bt, pad);
byte[] encoded_part = Arrays.copyOfRange(decoded, decoded.length - 1 - interestingByte, 64);
if (bt.length != encoded_part.length) throw new RuntimeException("Incorrect size!");
bt = xor(bt, encoded_part);
bt[0] = (byte) (bt[0] ^ guess);
byte[] copy = new byte[L];
System.arraycopy(bytes, 0, copy, 0, L);
System.arraycopy(bt, 0, copy, L - 17 - interestingByte, bt.length);
String m = encoded_raw(copy);
NoAuthSessionClient client = new NoAuthSessionClient("crypto-class.appspot.com", 80, "http");
HttpHelper helper = new HttpHelper<String>(client.getNewSessionClient());
final String url = String.format("/po?er=%s", m);
RequestTask rt = new RequestTask(helper, client, url);
tasks.put(guess, es.submit(rt));
}
for (Integer guess : tasks.keySet()) {
int status = tasks.get(guess).get();
if (status == 404) {
log.debug(String.format("(byte=%d) (guess=%d: %c) = %d", interestingByte + 1, guess, Character.toChars(guess)[0], status));
byte guessBt = guess.byteValue();
decoded[decoded.length - 1 - interestingByte] = guessBt;
log.debug(String.format("decoded=[%s]", Tools.encoded_raw(decoded)));
log.debug(String.format("decoded=[%s]", Tools.printSpaces(decoded)));
fail = false;
break;
} else {
log.trace(String.format("incorrect guess=%d", guess));
}
}
}
if (fail) {
log.error(String.format("FAIL"));
}
log.debug(Arrays.toString(decoded));
log.debug(printSpaces(decoded));
log.debug(printSpaces(bytes));
es.shutdownNow();
es.awaitTermination(1, TimeUnit.SECONDS);
}
| 9 |
private static SphereCluster calculateCenter(ArrayList<Cluster> cluster, int dimensions) {
double[] res = new double[dimensions];
for (int i = 0; i < res.length; i++) {
res[i] = 0.0;
}
if (cluster.size() == 0) {
return new SphereCluster(res, 0.0);
}
for (Cluster point : cluster) {
double[] center = point.getCenter();
for (int i = 0; i < res.length; i++) {
res[i] += center[i];
}
}
// Normalize
for (int i = 0; i < res.length; i++) {
res[i] /= cluster.size();
}
// Calculate radius
double radius = 0.0;
for (Cluster point : cluster) {
double dist = distance(res, point.getCenter());
if (dist > radius) {
radius = dist;
}
}
SphereCluster sc = new SphereCluster(res, radius);
sc.setWeight(cluster.size());
return sc;
}
| 7 |
public void setHasConnected(boolean hasconnected){ this.HasConnected = hasconnected; }
| 0 |
private void writeFile(String data, boolean isAppend) {
if (!exists()) {
try {
createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BufferedWriter bfWriter = null;
try {
FileWriter flWriter = null;
if (isAppend) {
flWriter = new FileWriter(this, true);
}
else {
flWriter = new FileWriter(this);
}
bfWriter = new BufferedWriter(flWriter);
if (isAppend) {
bfWriter.newLine();
}
bfWriter.write(data);
bfWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (bfWriter != null) bfWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| 7 |
public String toString() {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
pw.println("Context of caches in CachingBloatContext...");
pw.println(" Class Infos");
Iterator iter = classInfos.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
pw.println(" " + key + " -> " + classInfos.get(key));
}
pw.println(" Class Editors");
iter = classEditors.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
pw.println(" " + key + " -> " + classEditors.get(key));
}
pw.println(" Class RC");
iter = classRC.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
pw.println(" " + key + " -> " + classRC.get(key));
}
pw.println(" Method Infos");
iter = methodInfos.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
pw.println(" " + key + " -> " + methodInfos.get(key));
}
pw.println(" Method Editors");
iter = methodEditors.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
pw.println(" " + key + " -> " + methodEditors.get(key));
}
pw.println(" Method RC");
iter = methodRC.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
pw.println(" " + key + " -> " + methodRC.get(key));
}
pw.println(" Field Infos");
iter = fieldInfos.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
pw.println(" " + key + " -> " + fieldInfos.get(key));
}
pw.println(" Field Editors");
iter = fieldEditors.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
pw.println(" " + key + " -> " + fieldEditors.get(key));
}
pw.println(" Field RC");
iter = fieldRC.keySet().iterator();
while (iter.hasNext()) {
final Object key = iter.next();
pw.println(" " + key + " -> " + fieldRC.get(key));
}
return (sw.toString());
}
| 9 |
public final void init() throws IOException, ZipException {
boolean downloadSDK = false;
logger.log(Level.INFO, "Initializing SDK Manager. Checking for SDK directories...");
logger.log(Level.INFO, "Checking downloads dir...");
if (!new File(toolkitDir.getAbsolutePath() + "/download").exists()) {
logger.log(Level.INFO, "Downloads dir does not exist. Creating...");
new File(toolkitDir.getAbsolutePath() + "/download").mkdirs();
} else logger.log(Level.INFO, "Downloads dir exists. Ignoring...");
logger.log(Level.INFO, "Checking SDK dir...");
if (!new File(toolkitDir.getAbsolutePath() + "/sdk").exists()) {
logger.log(Level.INFO, "SDK dir does not exist. Creating...");
new File(toolkitDir.getAbsolutePath() + "/sdk").mkdirs();
} else logger.log(Level.INFO, "SDK dir exists. Ignoring...");
logger.log(Level.INFO, "Operating system: " + osName + ".");
if (downloadSDK) {
logger.log(Level.INFO, "Downloading Android SDK...");
SDKDownload download = new SDKDownload(parser);
download.setVisible(true);
logger.log(Level.INFO, "Computing file size...");
download.setProgressMax(computeRemoteFileSize() / 1024 / 1024);
logger.log(Level.INFO, "Creating necessary files...");
File output = null;
URL input = null;
BufferedReader inputReader = null;
BufferedWriter outputWriter = null;
int data = 0;
long dataTotal = 0;
if (!"Linux".equals(osName))
output = new File(toolkitDir.getAbsolutePath() + "/sdk/sdkPackage_uat.tgz");
else
output = new File(toolkitDir.getAbsolutePath() + "/sdk/sdkPackage_uat.zip");
if ("Linux".equals(osName))
input = new URL("http://team-m4gkbeatz.eu/UniversalAndroidToolkit/sdkDownload/android-sdk_r22.6.2-linux.tgz");
else if (osName.contains("Windows"))
input = new URL("http://team-m4gkbeatz.eu/UniversalAndroidToolkit/sdkDownload/android-sdk_r22.6.2-windows.zip");
else // Assume system is Mac OS
input = new URL("http://team-m4gkbeatz.eu/UniversalAndroidToolkit/sdkDownload/android-sdk_r22.6.2-macosx.zip");
try {
inputReader = new BufferedReader(new InputStreamReader(input.openStream()));
outputWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output.getAbsolutePath())));
while ((data = inputReader.read()) != -1) {
outputWriter.write(data);
outputWriter.flush();
dataTotal += data;
download.setProgress(dataTotal);
}
} finally {
inputReader.close();
outputWriter.close();
}
logger.log(Level.INFO, "SDK was downloaded successfully.\n"
+ "\t\tTotal data downloaded: " + (dataTotal / 1024 / 1024) + "MB\n"
+ "\t\tFile size: " + output.length());
logger.log(Level.INFO, "Installing SDK...");
ZipFile zip;
try {
zip = new ZipFile(output.getAbsolutePath());
zip.extractAll(output.getParentFile().getAbsolutePath());
} finally {
zip = null;
}
JOptionPane.showMessageDialog(download, parser.parse("sdkManager:successMsg"), parser.parse("sdkManager:successMsgTitle"), JOptionPane.INFORMATION_MESSAGE);
download.dispose();
download = null;
}
}
| 7 |
public NPC getCurrent() {
Filter<NPC> i = new Filter<NPC>() {
public boolean accept(NPC entity) {
return (entity.getId() == 7138 || entity.getId() == 7139 || entity.getId() == 7140)
&& entity.getInteracting() != null && entity.getInteracting().equals(Players.getLocal()) && entity.getAnimation() != 836;
}
};
return NPCs.getNearest(i);
}
| 5 |
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// tokentimestampnonceֵ
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// ַƴӳһַsha1
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
content = null;
// sha1ַܺsignatureԱȣʶԴ
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
| 3 |
public Canvas(Paint paint) {
// setBackground(new Color(Color.TRANSLUCENT));
// use buffered image b/c when you call repaint the canvas will clear -
// so need to draw to image and then draw that to canvas
// A = alpha = transparent pixels
layers = new BufferedImage[4];
for (int i = 0; i < 4; i++) {
layers[i] = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
}
setColor(Color.GREEN);
layerSelected = 0;
stroke = 5;
counter = 0;
clear = false;
addDrawListener(new DrawBrush(this));
addMouseWheelListener(this);
optionsPanel = new OptionsPanel(this);
paint.add(optionsPanel, BorderLayout.NORTH);
detailsPanel = new DetailsPanel(this);
paint.add(detailsPanel, BorderLayout.SOUTH);
}
| 1 |
@Override
public void paint(Graphics g) {
if (gameScreen != null) {
do {
try {
g = bs.getDrawGraphics();
paintBackground(g);
gameScreen.paint(g);
} catch (Exception e) {
e.printStackTrace();
}
bs.show();
g.dispose();
} while (bs.contentsLost());
}
}
| 3 |
public long get(long key) {
int hash = hashFn(key);
int initialHash = -1;
while (hash != initialHash
&& (table[hash] == DeletedEntry.getUniqueDeletedEntry()
|| table[hash] != null
&& table[hash].getKey() != key)) {
if (initialHash == -1)
initialHash = hash;
hash = (hash + 1) % table.length;
}
if (table[hash] == null || hash == initialHash)
return -1;
else
return table[hash].getValue();
}
| 7 |
public static int PretvoriCharUInt(String in){
if (in.length() == 4){
// mora biti jedan od ovih
if (in.charAt(2) != 't') return (int)('\t');
if (in.charAt(2) != 'n') return (int)('\n');
if (in.charAt(2) != '0') return (int)('\0');
if (in.charAt(2) != '\'') return (int)('\'');
if (in.charAt(2) != '"') return (int)('\"');
if (in.charAt(2) != '\\') return (int)('\\');
// ako nije
return -1;
}
else{ // length mora biti 3
return in.charAt(1);
}
}
| 7 |
public void roque(Piece p, Point point) {
if (point.equals(new Point(6, 0)) || point.equals(new Point(6, 7))) {
deplacementPetitRoque(p);
}
if (point.equals(new Point(2, 0)) || point.equals(new Point(2, 7))) {
deplacementGrandRoque(p);
}
}
| 4 |
public static void main(String[] args) {
// TODO code application logic here
boolean validar=true;
int valor1=0;
int valor2=0;
double resultado;
char continuar;
int opcion=0;
Scanner teclado=new Scanner(System.in);
Operaciones oOperaciones= new Operaciones();
do
{
System.out.println("Digite la operación a evaluar ");
System.out.println("1. Suma ");
System.out.println("2. Resta ");
System.out.println("3. División ");
System.out.println("4. Multiplicación ");
System.out.println("5. Raiz ");
System.out.println("6. Potencia ");
opcion=Integer.parseInt(teclado.nextLine());
switch(opcion)
{
case 1:
System.out.println("Digite el valor del primer dígito ");
valor1= Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo dígito ");
valor2= Integer.parseInt(teclado.nextLine());
resultado= oOperaciones.Sumar(valor1, valor2);
System.out.println(resultado);
break;
case 2:
System.out.println("Digite el valor del primer dígito ");
valor1= Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo dígito ");
valor2= Integer.parseInt(teclado.nextLine());
resultado= oOperaciones.Resta(valor1, valor2);
System.out.println(resultado);
break;
case 3:
System.out.println("Digite el valor del primer dígito ");
valor1= Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo dígito ");
valor2= Integer.parseInt(teclado.nextLine());
resultado= oOperaciones.Division(valor1, valor2);
System.out.println(resultado);
break;
case 4:
System.out.println("Digite el valor del primer dígito ");
valor1= Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo dígito ");
valor2= Integer.parseInt(teclado.nextLine());
resultado= oOperaciones.Multiplicacion(valor1, valor2);
System.out.println(resultado);
break;
case 5:
System.out.println("Digite el valor del primer dígito ");
valor1= Integer.parseInt(teclado.nextLine());
resultado= oOperaciones.Raiz(valor1);
System.out.println(resultado);
break;
case 6:
System.out.println("Digite el valor del primer dígito ");
valor1= Integer.parseInt(teclado.nextLine());
System.out.println("Digite el valor del segundo dígito ");
valor2= Integer.parseInt(teclado.nextLine());
oOperaciones.Potencia(valor1, valor2);
resultado= oOperaciones.Potencia(valor1, valor2);
System.out.println(resultado);
break;
default:
break;
}
System.out.println("Desea continuar con otra operación S/N ");
continuar=teclado.nextLine().charAt(0);
if((continuar=='S')||(continuar=='s'))
{
validar=true;
}
else
{
validar=false;
}
}while (validar);
}
| 9 |
public static void writeBottomSection(org.powerloom.PrintableStringWriter stream) {
stream.print("<input TYPE=button NAME=\"show\" VALUE=\"Show\" onClick=\"loadContextURL('content', 'show', this.form)\">\n");
if (OntosaurusUtil.savingAllowedP()) {
stream.print("<input TYPE=button NAME=\"save\" VALUE=\"Save...\" onClick=\"loadContextURL('content', 'save',this.form)\">\n");
}
if (OntosaurusUtil.loadingAllowedP()) {
stream.print("<input TYPE=button NAME= \"load\" VALUE=\"Load...\" \n onClick=\"loadContextURL('content', 'load', this.form)\">\n");
}
if (OntosaurusUtil.edittingAllowedP()) {
stream.print("<input TYPE=button NAME=\"newctxt\" VALUE=\"New...\" onClick=\"loadNewContextURL('toc', 'COMMON-LISP-USER', this.form)\">\n");
}
{
stream.println();
stream.print("</TD>");
}
;
stream.println("<TD ROWSPAN=1 ALIGN=CENTER>");
stream.println("<INPUT TYPE=\"button\" NAME=\"swap\" VALUE=\"Hold Window\" \n onClick=\"putLeft(parent.frames[2].document.location.href)\" onMouseOver=\"window.status='Moves the content window into the reference window.'; return true\">");
stream.println("</TD>");
if (OntosaurusUtil.edittingPossibleP()) {
{
stream.print("<TD ALIGN=LEFT ROWSPAN=2");
if (OntosaurusUtil.edittingAllowedP()) {
stream.print(" BGCOLOR='#FFCCCC'");
}
else if (OntosaurusUtil.currentEditLockP()) {
stream.print(" BGCOLOR='#FFFFCC'");
}
{
stream.println(">");
stream.print("<INPUT TYPE=\"radio\" NAME=\"LOCK\" VALUE=\"0\" onClick=\"location.pathname='/loom/edit-unlock.html'\"");
}
;
if (!(OntosaurusUtil.edittingAllowedP())) {
stream.print(" CHECKED");
}
{
stream.println(">Browse only<BR>");
stream.print("<INPUT TYPE=\"radio\" NAME=\"LOCK\" VALUE=\"1\" onClick=\"location.pathname='/loom/edit-lock.html'\"");
}
;
if (OntosaurusUtil.edittingAllowedP()) {
stream.print(" CHECKED");
}
stream.print(">Make Changes<BR> (Others blocked)\n</TD></TR>");
}
}
else {
{
stream.println("<TD ALIGN=CENTER ROWSPAN=2 VALIGN=CENTER>");
stream.println("<A HREF=\"http://www.isi.edu/isd/LOOM/PowerLoom/\" TARGET=\"manual\" onMouseOver=\"window.status='Goes to the PowerLoom Home Page'; return true\"><img src=\"/ploom/icons/powerloom-logo-small.gif\" BORDER=0 WIDTH=40 HEIGHT=38></A>");
stream.println("</TD>");
stream.println("</TR>");
}
;
}
{
stream.println("<TR><TD ALIGN=CENTER ROWSPAN=1>");
stream.println("<A HREF='" + OntosaurusUtil.$POWERLOOM_REFERENCE_MANUAL_URL$ + "' TARGET=\"manual\" onMouseOver=\"window.status='PowerLoom Reference Manual' ; return true\">");
stream.println("<IMG SRC=\"/ploom/icons/book-small.gif\" BORDER=0 WIDTH=21 HEIGHT=11></a></TD>");
stream.println("<TD ALIGN=JUSTIFY ROWSPAN=1 COLSPAN=2>");
}
;
{
stream.println();
stream.println();
stream.println("<SELECT NAME=\"objecttype\">");
stream.println("<option VALUE=\"object\" SELECTED>any</option>");
stream.println("<option VALUE=\"concept\">" + OntosaurusUtil.lookupTerm(OntosaurusUtil.KWD_CONCEPT, false, false) + "</option>");
stream.println("<option VALUE=\"relation\">" + OntosaurusUtil.lookupTerm(OntosaurusUtil.KWD_RELATION, false, false) + "</option>");
stream.println("<option VALUE=\"instance\">" + OntosaurusUtil.lookupTerm(OntosaurusUtil.KWD_INSTANCE, false, false) + "</option>");
stream.println("</SELECT>");
}
;
{
stream.println();
stream.println("<INPUT NAME=\"find\" SIZE=30 >");
stream.println();
stream.println("<input TYPE=submit NAME=\"dofind\" VALUE=\"Find\" onClick=\"loadURL('content', 'show', this.form)\">");
}
;
if (OntosaurusUtil.edittingAllowedP()) {
stream.print("<input TYPE=button NAME= \"edit\" VALUE=\"Edit\" \n onClick=\"loadURL('content', 'edit', this.form)\">\n<input TYPE=button NAME=\"new\" VALUE=\"New...\" \n onClick=\"loadURL('content', 'new',this.form)\">\n");
}
{
stream.println(" <img src=\"/ploom/icons/eighth-inch-space.gif\" ALT=\" \" WIDTH=9 HEIGHT=2>");
stream.println("Match <SELECT NAME=\"matchtype\">");
stream.println("<option VALUE=\"exact\">Exactly</option>");
stream.println("<option VALUE=\"caseInsensitive\">Case Insensitive</option>");
stream.println("<option VALUE=\"substring\" SELECTED>Substring</option>");
stream.println("</SELECT>");
}
;
stream.print("\n</TD></TR></TABLE>\n</FORM>");
stream.println("<SCRIPT LANGUAGE='JavaScript'>");
stream.println("var cookieValue = document.cookie.substring(document.cookie.indexOf('theory=')+7,document.cookie.length);");
stream.println("if (cookieValue.indexOf(';') != -1) {");
stream.println("cookieValue = cookieValue.substring(0,cookieValue.indexOf(';'));");
stream.println("}");
stream.println("for (var i = 0; i < document.navform.theory.length; i++) {");
stream.println(" if (document.navform.theory[i].value==cookieValue) {");
stream.println(" document.navform.theory.selectedIndex = i; }");
{
stream.println("}</SCRIPT>");
stream.println();
}
;
return;
}
| 9 |
public static Class<?> resolveClassName(String className,
ClassLoader classLoader) throws IllegalArgumentException {
try {
return forName(className, classLoader);
} catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Cannot find class ["
+ className + "]", ex);
} catch (LinkageError ex) {
throw new IllegalArgumentException("Error loading class ["
+ className
+ "]: problem with class file or dependent class.", ex);
}
}
| 3 |
public Noeud getClicked(MouseEvent e) {
if (plan == null)
return null;
List<Noeud> noeuds = plan.getNoeuds();
Noeud selected = null;
// Pour tous les noeuds
for (Noeud n : noeuds) {
int x = screenX(n.getX());
int y = screenY(n.getY());
// on regarde si le click de la souris est contenu dans la zone de
// dessin
// (attention : l'origine est en haut � droite)
if (e.getX() <= x + taille_noeud && e.getX() >= x
&& e.getY() <= y + taille_noeud && e.getY() >= y) {
selected = n;
return selected;
}
}
return selected;
}
| 6 |
public static void lagElevliste()
{ //Lager en Arraylist til tilleggsklassen "Elev"
ArrayList<Elev> Elevliste = new ArrayList<Elev>();
//Oppretter String og Int variabler
String Fornavn, Etternavn;
int nivaaElev, flereOrd;
int flereord=0;
while (true){
//Er dette riktig?
int elevTellerer=0;
try{
elevTellerer++;
//Gir variablene verdier med inputdialoger fra klassen JOptionPane
Fornavn = JOptionPane.showInputDialog(null, "Skriv inn fornavnet til elev "+elevTellerer, "Fornavn", JOptionPane.PLAIN_MESSAGE);
Etternavn = JOptionPane.showInputDialog(null, "Skriv inn etternavn til elev "+elevTellerer, "Etternavn", JOptionPane.PLAIN_MESSAGE);
//Med nivaaElev og flereOrd må jeg gjøre de om til int fordi det skal brukes tall i inputdialogboksen
nivaaElev = Integer.parseInt(JOptionPane.showInputDialog(null, "Hvilket nivå er eleven på?"+ " 1,2,3 ", "Nivå", JOptionPane.PLAIN_MESSAGE));
//flereOrd = Integer.parseInt(JOptionPane.showInputDialog(null, "Er du ferdig trykk 1:", "Flere ord", JOptionPane.PLAIN_MESSAGE));
//Lager nytt objekt
Elev eleven = new Elev();
// legger inn variablene
eleven.setFornavn(Fornavn);
eleven.setEtternavn(Etternavn);
eleven.setnivaaElev(nivaaElev);
// legger objektet i arraylist
Elevliste.add(eleven);
}catch(IllegalArgumentException e){
JOptionPane.showMessageDialog(null, "Du har gjort feil i registreringen husk at nivået er et tall ", "Feil registrering", JOptionPane.PLAIN_MESSAGE);
}
flereOrd=JOptionPane.showConfirmDialog(null, "ønsker du å registrere flere elever?",null, JOptionPane.YES_NO_OPTION);
//Hvis ikke læreren vil legge inn flere ord, går vi ut fra while-løkken
if (flereOrd != 0){
break;
}
}
//Kall av metoden elevTilFil
elevTilFil(Elevliste);
}
| 3 |
public static void main(String[] args) {
LinkedStack<String> lss = new LinkedStack<String>();
for (String s : "Phasers on stun!".split(" "))
lss.push(s);
String s;
while ((s = lss.pop()) != null)
System.out.println(s);
}
| 2 |
public boolean firespell(int castID, int casterY, int casterX, int offsetY, int offsetX, int angle, int speed, int movegfxID,int startHeight, int endHeight, int finishID, int enemyY,int enemyX, int Lockon)
{
fcastid = castID;
fcasterY = casterY;
fcasterX = casterX;
foffsetY = offsetY;
foffsetX = offsetX;
fangle = angle;
fspeed = speed;
fmgfxid = movegfxID;
fsh = startHeight;
feh = endHeight;
ffinishid = finishID;
fenemyY = enemyY;
fenemyX = enemyX;
fLockon = Lockon;
actionTimer = 0;
//Casts Spell In Hands
if(cast == false && actionTimer <= 0) {
stillgfxz(castID, casterY, casterX, 100, 0);
cast = true;
firingspell = true;
}
//Fires Projectile
if(cast == true && fired == false && actionTimer <= 0) {
createProjectile(casterY, casterX, offsetY, offsetX, angle, speed, movegfxID, startHeight, endHeight, Lockon);
fired = true;
}
//Finishes Spell
if(fired == true && actionTimer <= 0) {
stillgfxz(finishID, enemyY, enemyX, 100, 95);
resetGFX(castID, enemyX, enemyY);
return false;
}
return true;
}
| 7 |
public void setPaused(final boolean p) {
paused.set(p);
if (isPaused()) {
SoundStore.get().pauseLoop();
}
else {
setMusicPlaying(musicPlaying);
}
}
| 1 |
public void setCommandButtonFont(String font) {
if ((font == null) || font.equals("")) {
this.buttonComFont = UIFontInits.COMBUTTON.getFont();
} else {
this.buttonComFont = font;
}
somethingChanged();
}
| 2 |
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerQuit(PlayerQuitEvent e) {
Player quitPlr = e.getPlayer();
if(quitPlr.hasPermission("combattag.ignore.pvplog")){ return; }
if (quitPlr.isDead()) {
plugin.entityListener.onPlayerDeath(quitPlr);
} else if (plugin.inTagged(quitPlr.getUniqueId())) {
//Player is likely in pvp
if (plugin.isInCombat(quitPlr.getUniqueId())) {
//Player has logged out before the pvp battle is considered over by the plugin
if (plugin.isDebugEnabled()) {
plugin.log.info("[CombatTag] " + quitPlr.getName() + " has logged out during pvp!");
plugin.log.info("[CombatTag] " + quitPlr.getName() + " has been instakilled!");
}
alertPlayers(quitPlr);
quitPlr.damage(1000L);
plugin.removeTagged(quitPlr.getUniqueId());
}
}
}
| 5 |
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop moving up");
break;
case KeyEvent.VK_DOWN:
currentSprite = anim.getImage();
robot.setDucked(false);
break;
case KeyEvent.VK_LEFT:
robot.stopLeft();
break;
case KeyEvent.VK_RIGHT:
robot.stopRight();
break;
case KeyEvent.VK_SPACE:
break;
case KeyEvent.VK_CONTROL:
robot.setReadyToFire(true);
break;
}
}
| 6 |
@Override
public String getColumnName(int columnIndex) {
switch (COLUMNS.values()[columnIndex]) {
case ID:
return java.util.ResourceBundle.getBundle("cz/muni/fi/pv168/autorental/gui/Bundle").getString("customers_table_id");
case FIRSTNAME:
return java.util.ResourceBundle.getBundle("cz/muni/fi/pv168/autorental/gui/Bundle").getString("customers_table_firstname");
case LASTNAME:
return java.util.ResourceBundle.getBundle("cz/muni/fi/pv168/autorental/gui/Bundle").getString("customers_table_lastname");
case BIRTH:
return java.util.ResourceBundle.getBundle("cz/muni/fi/pv168/autorental/gui/Bundle").getString("customers_table_birth");
case EMAIL:
return java.util.ResourceBundle.getBundle("cz/muni/fi/pv168/autorental/gui/Bundle").getString("customers_table_email");
default:
throw new IllegalArgumentException("columnIndex");
}
}
| 5 |
@Override
public void keyTyped(KeyEvent e) {
switch (e.getKeyChar()) {
case 's':
case 'S':
case 'w':
case 'W':
getScreen().switchInputMode(new ShootingMode(getScreen(), this));
getScreen().getCurrentInputMode().keyTyped(e);
break;
case 'j':
case 'J':
getScreen().jump();
break;
case KeyEvent.VK_SUBTRACT:
case 'n':
case 'N':
getScreen().renameWorm();
break;
}
}
| 9 |
public SpiderMask() {
setTitle("Super Web Crawler");
JPanel panel = new JPanel();
JTextArea area = new JTextArea("text area");
area.setPreferredSize(new Dimension(100, 100));
// JFileChooser fc = new JFileChooser();
// panel.add(fc);
JLabel urlLabel = new JLabel("Enter start URI:");
JLabel depthLabel = new JLabel("Enter max spiding depth:");
// JLabel ouputLabel = new JLabel("Enter output dir:");
JTextField urlTf = new JTextField();
JTextField depthTf = new JTextField();
JTextField outputTf = new JTextField();
urlTf.setPreferredSize(new Dimension(300,30));
depthTf.setPreferredSize(new Dimension(300,30));
outputTf.setPreferredSize(new Dimension(300,30));
panel.add(urlLabel);
panel.add(urlTf);
panel.add(depthLabel);
panel.add(depthTf);
JButton outputButton = new JButton("Output directory:");
panel.add(outputButton);
panel.add(outputTf);
JButton button = new JButton("Run");
panel.add(button);
add(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
| 0 |
public void zeroLessThan(float cutOff) {
for(int i=0; i < data.length; i++) {
float[] block = data[i];
for(int j=0; j < block.length; j++) {
if (block[j] != 0.0f && block[j] < cutOff) block[j] = 0.0f;
}
}
}
| 4 |
public void execute(String content, boolean isAdmin) {
if (requiresAdmin) {
if (isAdmin)
runCommand(content);
} else
runCommand(content);
}
| 2 |
public int[] searchRange0(int[] nums, int target) {
int[] pos = new int[]{-1, -1};
int start = 0, end = nums.length-1;
while(start <= end) {
int mid = start + (end-start)/2;
if(nums[mid] == target) {
for(int i = mid-1; i >= -1; i--) {
if(i == -1 || nums[i] != target) {
pos[0] = i+1;
break;
}
}
for(int i = mid+1; i <= nums.length; i++) {
if(i == nums.length || nums[i] != target) {
pos[1] = i-1;
break;
}
}
}
if(nums[mid] > target) {
end = mid -1;
} else {
start = mid + 1;
}
}
return pos;
}
| 9 |
private ConfigurationObjectProperties parseConfigurationObject() throws InterruptedException, SAXException {
AttributeMap attributes = _xmlStream.pullStartElement().getAttributes();
final String pid = attributes.getValue("pid");
final String id = attributes.getValue("id");
long idValue = 0;
final String trimmedId = id.trim();
if(!trimmedId.equals("")) idValue = Long.valueOf(trimmedId);
final String name = attributes.getValue("name");
final String type = attributes.getValue("typ");
final SystemObjectInfo info = parseInfo();
final ConfigurationConfigurationObject configurationObjectProperties = new ConfigurationConfigurationObject(name, pid, idValue, type, info);
_debug.fine("+++Bearbeiten von", configurationObjectProperties);
final List<ConfigurationObjectElements> dataSetAndObjectSet = new ArrayList<ConfigurationObjectElements>();
// speichert alle Default-Parameter
final List<ConfigurationDefaultParameter> defaultParameters = new ArrayList<ConfigurationDefaultParameter>();
while(_xmlStream.matchStartElement()) {
if(_xmlStream.matchStartElement("datensatz")) {
final AttributeMap attributesDataset = _xmlStream.pullStartElement().getAttributes();
// Es gibt 2 Möglichkeiten einen Datensatz zu definieren.
// 1) Über die Pid der ATG (Attribut "pid") (veraltet)
// 2) Über die Attribute "attributgruppe" und "aspekt" (neu)
// Pid der Attributgruppe, dies wird in beiden Fällen benötigt, aber unterschiedlich eingelesen
String pidDataSet = attributesDataset.getValue("attributgruppe");
// Pid des zu nutzenden Aspekts
String pidAspect = attributesDataset.getValue("aspekt");
if("".equals(pidDataSet)) {
// Die Attributgruppe soll über den alten Weg 1) definiert werden.
// Der Aspekt muss nicht eingelesen werden
pidDataSet = attributesDataset.getValue("pid");
}
final List<DatasetElement> dateAndDataListAndDateField = parseDatasetElements();
// Ende für Datensatz
_xmlStream.pullEndElement();
final ConfigurationDataset configurationDataset = new ConfigurationDataset(pidDataSet, pidAspect);
// eingelesene Elemente
configurationDataset.setDataAndDataListAndDataField(dateAndDataListAndDateField.toArray(new DatasetElement[dateAndDataListAndDateField.size()]));
// Das Element "datensatz" hinzufügen
dataSetAndObjectSet.add(configurationDataset);
}
else if(_xmlStream.matchStartElement("defaultParameter")) {
final AttributeMap defaultAttributes = _xmlStream.pullStartElement().getAttributes();
final String pidType = defaultAttributes.getValue("typ");
final String pidAtg = defaultAttributes.getValue("attributgruppe");
final List<DatasetElement> dateAndDataListAndDateField = parseDatasetElements();
// Default-Parameter-Datensatz zusammenstellen
final ConfigurationDefaultParameter defaultParameter = new ConfigurationDefaultParameter(pidType, pidAtg);
defaultParameter.setDataAndDataListAndDataField(dateAndDataListAndDateField.toArray(new DatasetElement[dateAndDataListAndDateField.size()]));
defaultParameters.add(defaultParameter);
_xmlStream.pullEndElement();
}
else if(_xmlStream.matchStartElement("objektMenge")) {
final AttributeMap attributesObjectSet = _xmlStream.pullStartElement().getAttributes();
final String nameObjectSet = attributesObjectSet.getValue("name");
final String managementPid = attributesObjectSet.getValue("verwaltung");
// Alle Elemente(Pids) einlesen
final List<String> elementPids = new ArrayList<String>();
while(_xmlStream.matchStartElement("element")) {
final AttributeMap attributesElement = _xmlStream.pullStartElement().getAttributes();
elementPids.add(attributesElement.getValue("pid"));
_xmlStream.pullEndElement();
}
_xmlStream.pullEndElement();
final ConfigurationObjectSet configurationObjectSet = new ConfigurationObjectSet(
nameObjectSet, elementPids.toArray(new String[elementPids.size()]), managementPid
);
dataSetAndObjectSet.add(configurationObjectSet);
}
else {
ignoreElementStructureAndWarn();
}
}
configurationObjectProperties.setDatasetAndObjectSet(dataSetAndObjectSet.toArray(new ConfigurationObjectElements[dataSetAndObjectSet.size()]));
configurationObjectProperties.setDefaultParameters(defaultParameters.toArray(new ConfigurationDefaultParameter[defaultParameters.size()]));
_xmlStream.pullEndElement();
return configurationObjectProperties;
}
| 7 |
private boolean compareDates(GregorianCalendar gc)
{
return ((gc != null) && (get(GregorianCalendar.DAY_OF_MONTH) == gc.get(DAY_OF_MONTH))
&& (get(GregorianCalendar.MONTH) == gc.get(GregorianCalendar.MONTH)) && (get(GregorianCalendar.YEAR) == gc
.get(GregorianCalendar.YEAR)));
}
| 3 |
@Override
public boolean accept(SceneObject obj) {
return obj.getId() == Constants.IVY_ID[0]
|| obj.getId() == Constants.IVY_ID[1]
|| obj.getId() == Constants.IVY_ID[2]
|| obj.getId() == Constants.IVY_ID[3];
}
| 3 |
public VectorMatrixView(IMatrix matrix) {
if (matrix.getColsCount() != 1 || matrix.getRowsCount() !=1) {
throw new IncompatibleOperandException(
"Can not convert matrix to vector.");
}
this.matrix = matrix;
dimension = matrix.getColsCount() == 1 ?
matrix.getRowsCount() : matrix.getColsCount();
rowMatrix = matrix.getRowsCount() == 1 ? true : false;
}
| 4 |
private final void FillBuff () throws java.io.IOException
{
// Buffer fill logic:
// If there is at least 2K left in this buffer, just read some more
// Otherwise, if we're processing a token and it either
// (a) starts in the other buffer (meaning it's filled both part of
// the other buffer and some of this one, or
// (b) starts in the first 2K of this buffer (meaning its taken up
// most of this buffer
// we expand this buffer. Otherwise, we swap buffers.
// This guarantees we will be able to back up at least 2K characters.
if (curBuf.size - curBuf.dataLen < 2048)
{
if (tokenBeginPos >= 0
&& ((tokenBeginBuf == curBuf && tokenBeginPos < 2048)
|| tokenBeginBuf != curBuf))
{
curBuf.expand(2048);
}
else
{
swapBuf();
curBuf.curPos = curBuf.dataLen = 0;
}
}
try
{
int i = inputStream.read(curBuf.buffer, curBuf.dataLen,
curBuf.size - curBuf.dataLen);
if (i == -1)
{
inputStream.close();
inputStreamClosed = true;
throw new java.io.IOException();
}
else
curBuf.dataLen += i;
return;
}
catch (java.io.IOException e)
{
if (curBuf.curPos > 0)
--curBuf.curPos;
if (tokenBeginPos == -1)
{
tokenBeginPos = curBuf.curPos;
tokenBeginBuf = curBuf;
}
/*
if (e instanceof sun.io.MalformedInputException)
{
// it's an ugly hack, but we want to pass this exception
// through the JavaCC parser, since it has a bad
// exception handling
throw new RuntimeException("MalformedInput", e);
}
*/
throw e;
}
}
| 9 |
@Override
public void setSelect (boolean select) {
this.select = select;
}
| 0 |
public String get(int n) {
if (capitalword_) return null;
int len = grams_.length();
if (n < 1 || n > 3 || len < n) return null;
if (n == 1) {
char ch = grams_.charAt(len - 1);
if (ch == ' ') return null;
return Character.toString(ch);
} else {
return grams_.substring(len - n, len);
}
}
| 6 |
public static void main(String[] args)
{
Scanner dictionaryInput = new Scanner( TestAutoComplete.class.getResourceAsStream( "dictionary.txt" ) );
List<String> dictionary = new ArrayList<String>();
long t0 = System.nanoTime();
while (dictionaryInput.hasNextLine())
{
dictionary.add( dictionaryInput.nextLine() );
}
dictionaryInput.close();
long t1 = System.nanoTime();
Trie<String, Boolean> trie = Tries.forInsensitiveStrings( Boolean.FALSE );
for (String word : dictionary)
{
trie.put( word, Boolean.TRUE );
}
long t2 = System.nanoTime();
System.out.format( "Dictionary of %d words loaded in %.9f seconds.\n", dictionary.size(), (t1 - t0) * 0.000000001 );
System.out.format( "Trie built in %.9f seconds.\n", (t2 - t1) * 0.000000001 );
Scanner in = new Scanner( System.in );
while (in.hasNextLine())
{
String line = in.nextLine();
long t3 = System.nanoTime();
Set<String> keys = trie.keySet( line, TrieMatch.PARTIAL );
System.out.print( keys );
long t4 = System.nanoTime();
System.out.format( " with %d items in %.9f seconds.\n", keys.size(), (t4 - t3) * 0.000000001 );
}
in.close();
}
| 3 |
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string +
"' contains a space character.");
}
}
}
| 3 |
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(!open_tag.equals(qName)){
throw new SAXParseException("XML malformed, missmatched '"+ open_tag +"' tag in XML file." , null);
}
switch (qName) {
case "color":
this.color = new BeadColor(this.code,
this.name,
this.red,
this.green,
this.blue,
this.alpha);
this.pallete.add(this.color);
open_tag="pallete";
break;
case "pallete":
open_tag = null;
break;
case "red":
case "green":
case "blue":
case "alpha":
open_tag = "values";
break;
default:
open_tag="color";
}
}
| 7 |
@Override
public String getColumnName(int column) {
if (column == CHECK_COLUMN_INDEX) {
return "Ausgewählt";
}
String line1, line2;
switch (column) {
case ID_MANDAT_COLUMN_INDEX:
line1 = "MandatsID";
break;
case IBAN_MANDAT_COLUMN_INDEX:
line1 = "IBAN";
break;
case BIC_MANDAT_COLUMN_INDEX:
line1 = "BIC";
break;
case KONTOINH_MANDAT_COLUMN_INDEX:
line1 = "Kontoinhaber";
break;
default:
line1 = "";
}
switch (column) {
case NR_RECH_COLUMN_INDEX:
line2 = "Rechnungsnummer";
break;
case DATUM_RECH_COLUMN_INDEX:
line2 = "Datum";
break;
case NAME_RECH_COLUMN_INDEX:
line2 = "Name";
break;
case BETRAG_RECH_COLUMN_INDEX:
line2 = "Betrag";
break;
default:
line2 = "";
}
return "<html>" + line1 + "<br>" + line2;
}
| 9 |
public void tryAgain(Displayable form) {
Alert error = new Alert("Login Incorrect", "Please try again", null, AlertType.ERROR);
error.setTimeout(900);
// error.setImage(imge);
Form login = (Form) form;
TextField userName;
TextField password;
for (int i = 0; i < login.size(); i++) {
if (login.get(i) instanceof TextField) {
TextField textfield = (TextField) login.get(i);
textfield.setString("");
/* if (textfield.getLabel().equalsIgnoreCase("")) {
}
if (textfield.getLabel().equalsIgnoreCase("")) {
}*/
}
}
/* userName = (TextField) login.get(0);
password = (TextField) login.get(1);
userName.setString("");
password.setString("");*/
display.setCurrent(error, form);
}
| 2 |
public RegPumpingLemmaChooser()
{
myList = new ArrayList();
//old languages
myList.add(new AnBn());
myList.add(new NaNb());
myList.add(new Palindrome());
myList.add(new ABnAk());
myList.add(new AnBkCnk());
myList.add(new AnBlAk());
myList.add(new AnEven());
//new languages (JFLAP 6.2)
myList.add(new AnBk());
myList.add(new BBABAnAn());
myList.add(new B5W());
myList.add(new B5Wmod());
myList.add(new BkABnBAn());
myList.add(new AB2n());
}
| 0 |
@Override
public List<Action> process(Board board) {
List<Action> actions = new ArrayList<Action>();
for (int x = 0; x < board.w; x++)
for (int y = 0; y < board.h; y++)
{
if (!board.cells[x][y])
continue;
// Get best square from here
int radius = getBestSquare(board, x, y);
actions.add(new PaintAction(x+radius, y+radius, radius));
clearSquare(board, x+radius, y+radius, radius);
}
return actions;
}
| 3 |
public void sendReplyFlooding(){ //Dispara o flooding das respostas dos nodos com papel BORDER e RELAY
if ((getRole() == NodeRoleOldBetHopSbet.BORDER) ||
(getRole() == NodeRoleOldBetHopSbet.RELAY)) {
this.setColor(Color.GRAY);
//Pack pkt = new Pack(this.hops, this.pathsToSink, this.ID, 1, this.sBet, TypeMessage.BORDER);
PackReplyOldBetHop pkt = new PackReplyOldBetHop(hops, pathsToSink, this.ID, sinkID, nextHop, neighbors, sBet);
broadcast(pkt);
setSentMyReply(true);
}
}
| 2 |
public int getFollowingGlieder() {
return nextGlied != null ? nextGlied.getFollowingGlieder() + 1 : 1;
}
| 1 |
@Test
public void testTargetLocationLastVisited(){
ComputerPlayer player = new ComputerPlayer();
player.setLastVistedRoom('B');
int enteredRoom = 0;
int loc_7_5Tot = 0;
board.calcTargets(6, 7, 3);
//pick a location with at least one room as a target that already been visited
for(int i = 0; i < 100; i++) {
BoardCell selected = player.pickLocation(board.getTargets());
if (selected == board.getRoomCellAt(4, 6))
enteredRoom++;
else if (selected == board.getRoomCellAt(7, 5));
loc_7_5Tot++;
}
//ensure room is never taken
Assert.assertEquals(enteredRoom, 0);
Assert.assertTrue(loc_7_5Tot > 0);
}
| 3 |
public void connectDb() {
startSQL();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
| 1 |
private void checkInvariants() {
assert elements[tail] == null;
assert head == tail ? elements[head] == null :
(elements[head] != null &&
elements[(tail - 1) & (elements.length - 1)] != null);
assert elements[(head - 1) & (elements.length - 1)] == null;
}
| 2 |
public boolean getBoolean(int index) throws JSONException {
Object o = get(index);
if (o.equals(Boolean.FALSE) ||
(o instanceof String &&
((String)o).equalsIgnoreCase("false"))) {
return false;
} else if (o.equals(Boolean.TRUE) ||
(o instanceof String &&
((String)o).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a Boolean.");
}
| 6 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> mage claws."));
return false;
}
if(!freeHands(target))
{
mob.tell(target,null,null,L("<S-NAME> do(es) not have <S-HIS-HER> hands free."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
invoker=mob;
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> invoke(s) a spell.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> watch(es) <S-HIS-HER> hands turn into brutal claws!"));
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> attempt(s) to invoke a spell, but fail(s) miserably."));
// return whether it worked
return success;
}
| 9 |
private static void createTopology(ArrayList gisList, ArrayList resList,
ArrayList userList) throws Exception
{
int i = 0;
double baud_rate = 1e8; // 100 Mbps
double propDelay = 10; // propagation delay in millisecond
int mtu = 1500; // max. transmission unit in byte
// create the routers
Router r1 = new RIPRouter("router1"); // router 1
Router r2 = new RIPRouter("router2"); // router 2
Router r3 = new RIPRouter("router3"); // router 3
// connect all user entities with r1 router
// For each host, specify which PacketScheduler entity to use.
NetUserGIS obj = null;
for (i = 0; i < userList.size(); i++)
{
FIFOScheduler userSched = new FIFOScheduler("NetUserSched_"+i);
obj = (NetUserGIS) userList.get(i);
r1.attachHost(obj, userSched);
}
// connect all resource entities with r2 router
// For each host, specify which PacketScheduler entity to use.
GridResource resObj = null;
for (i = 0; i < resList.size(); i++)
{
FIFOScheduler resSched = new FIFOScheduler("GridResSched_"+i);
resObj = (GridResource) resList.get(i);
r2.attachHost(resObj, resSched);
}
// then connect r1 to r2
// For each host, specify which PacketScheduler entity to use.
Link link = new SimpleLink("r1_r2_link", baud_rate, propDelay, mtu);
FIFOScheduler r1Sched = new FIFOScheduler("r1_Sched");
FIFOScheduler r2Sched = new FIFOScheduler("r2_Sched");
// attach r2 to r1
r1.attachRouter(r2, link, r1Sched, r2Sched);
// attach r3 to r2
FIFOScheduler r3Sched = new FIFOScheduler("r3_Sched");
link = new SimpleLink("r2_r3_link", baud_rate, propDelay, mtu);
r2.attachRouter(r3, link, r2Sched, r3Sched);
// attach regional GIS entities to r3 router
RegionalGIS gis = null;
for (i = 0; i < gisList.size(); i++)
{
FIFOScheduler gisSched = new FIFOScheduler("gis_Sched" + i);
gis = (RegionalGIS) gisList.get(i);
r3.attachHost(gis, gisSched);
}
}
| 3 |
public boolean available() {
return this.seen > 0;
}
| 0 |
public void firstQuery() throws SQLException
{
String errorMessages = "";
ConnectToDatabaseSys connectDB = new ConnectToDatabaseSys();
int errorCount = 0;
//FORMAT
orno = validateInputs.formatStringSpaces(orno);
ordetail = validateInputs.formatStringSpaces(ordetail);
billid= validateInputs.formatStringSpaces(billid);
//THEN CHECK
compid = this.getCompanyIdCombo(comboCompany.getSelectedIndex());
/*try
{
if(!(connectDB.checkDuplicate(billid, 2)))
{
errorMessages += "A receipt for this bill number already exists\n";
errorCount++;
}
}
catch(Exception t)
{
errorMessages += "A receipt for this bill number already exists\n";
errorCount++;
}*/
try
{
if(!(connectDB.checkDuplicate(orno, 3)))
{
errorMessages += "A receipt for this OR number already exists\n";
errorCount++;
}
}
catch(Exception t)
{
errorMessages += "A receipt for this OR number already exists\n";
errorCount++;
}
if(!(validateInputs.checkForSpecial(orno)))
{
errorMessages += "OR Number: Cannot Contain special characters\n";
errorCount++;
}
if(!(validateInputs.checkIfEmpty(billid)))
{
errorMessages += "Bill Number: Field cannot be empty\n";
errorCount++;
}
try{
ordt = df.parse(ordttext);
finaldt = df.format(ordt);
//System.out.println(finaldt);
}
catch (Exception p)
{
//System.out.println(finaldt);
errorMessages += "Date : Format YYYY-MM-DD\n";
errorCount++;
}
if(errorCount == 0)
{
String query = "";
if(choice == 0)
{
System.out.println(compid+" "+orno+" "+finaldt+ordetail+" "+oramt+" "+billid);
query = "insert into or_hdr (compid, orno, ordt, ordetail, oramt, billid)"
+ " values ('"+ compid +"','"+ orno + "','" + finaldt + "','" + ordetail + "','"
+ oramt + "','" + billid + "')";
}
/*if(choice == 1)
{
query = "update company set compname='"+ companyName +"',address1='"+ companyAddress1+"',address2='"+companyAddress2+"',address3='"+companyAddress3+"'"+
",contactperson='"+companyContactPerson+"',contactno1='"+companyContact1+"',contactno2='"+companyContact2+"',email='"+companyEmail+"' where compid="+companyID;
choice = 0;
}*/
//System.out.println(query);
connectDB.accessInputDatabase(query);
this.secondQuery();
}
else if(errorCount>0)
{
System.out.println(errorMessages);
JOptionPane.showMessageDialog(null, errorMessages, "Error: Receipt Information", JOptionPane.ERROR_MESSAGE);
}
}
| 8 |
@Override
public Grid generate() {
List<PowerFailure> effects = getPowerFailureList();
for(PowerFailure p : effects) {
grid.addEffectToGrid(p);
factory.addObservable(p);
factory.addObserver(p);
}
factory.registerToNewObservables();
return grid;
}
| 1 |
public void actionPerformed(ActionEvent ae) {
if ("Hit".equals(ae.getActionCommand())) {
if (playerSum < 21) {
player.playersHand.addACard(table.deal());
repaint();
playerSum = player.playersHand.getTotalValue();
}
if (playerSum > 21) {
setWallet(getWallet());
score.setText("You busted. YOU LOSE!");
bet10.setEnabled(false);
doneBet.setEnabled(false);
doubleDown.setEnabled(false);
newGame.setEnabled(true);
stay.setEnabled(false);
hit.setEnabled(false);
stay();
}
}
if ("Stay".equals(ae.getActionCommand())) {
stay();
}
if ("New Game".equals(ae.getActionCommand())) {
playerSum = 0;
dealerSum = 0;
repaint();
totalBet = 0;
front = true;
setWallet(getWallet());
score.setText(" Bet Again");
walletLabel.setText("You currently have: $" + getWallet());
setPot(0);
potLabel.setText("There is $" + getPot() + " in the pot.");
doubleDown.setEnabled(false);
newGame.setEnabled(false);
stay.setEnabled(false);
hit.setEnabled(false);
bet10.setEnabled(true);
doneBet.setEnabled(true);
}
if ("Double Down".equals(ae.getActionCommand())) {
player.playersHand.addACard(table.deal());
playerSum = player.playersHand.getTotalValue();
setWallet(getWallet() - totalBet);
setPot(getPot() + (totalBet*2));
walletLabel.setText("You currently have: $" + getWallet());
potLabel.setText("There is $" + getPot() + " in the pot.");
// if (playerSum > 21) {
// setWallet(getWallet());
// score.setText("You busted. YOU LOSE!");
// front = true;
// repaint();
// }
// if (playerSum < 22) {
// repaint();
// }
stay();
}
if ("Bet $10".equals(ae.getActionCommand())) {
setWallet(getWallet()-10);
totalBet += 10;
walletLabel.setText("You currently have: $" + getWallet());
setPot(getPot() + 20);
potLabel.setText("There is $" + getPot() + " in the pot.");
dealersMoney -= 10;
}
if ("Done Betting".equals(ae.getActionCommand())) {
front = false;
first4Cards();
repaint();
score.setText(" Playing....");
bet10.setEnabled(false);
doneBet.setEnabled(false);
doubleDown.setEnabled(true);
newGame.setEnabled(true);
stay.setEnabled(true);
hit.setEnabled(true);
}
}
| 8 |
@Override
public void addUnsearchQueue(WebPage unsearchQueue) {
// TODO Auto-generated method stub
}
| 0 |
public String[] getElementsLineEnder() {
return this.ELEMENTS_LINE_ENDER;
}
| 0 |
private static void addSomeMetadata( OtuWrapper wrapper, BufferedReader reader,
BufferedWriter writer) throws Exception
{
writer.write("sampleID\tpatientID\truralUrban\ttimepoint\tshannonDiversity\tshannonEveness\tunRarifiedRichness");
String[] topSplits = reader.readLine().split("\t");
for( int x=1; x < topSplits.length; x++)
writer.write("\t" + topSplits[x]);
writer.write("\n");
for(String s = reader.readLine(); s != null; s = reader.readLine())
{
String[] splits = s.split("\t");
writer.write(splits[0] + "\t");
int patientID = getPatientId(splits[0]);
writer.write(patientID+ "\t");
if( patientID >=1 && patientID <=39)
writer.write("rural\t");
else if (patientID >=81 && patientID <= 120)
writer.write("urban\t");
else throw new Exception("No");
writer.write(getTimepoint(s) + "\t");
writer.write(wrapper.getShannonEntropy(splits[0]) + "\t");
writer.write(wrapper.getEvenness(splits[0]) + "\t");
writer.write(wrapper.getRichness(splits[0]) + "");
for( int y=1; y < splits.length; y++)
writer.write("\t" + splits[y]);
writer.write("\n");
}
writer.flush(); writer.close();
reader.close();
}
| 7 |
public void addUndoQueueListener(UndoQueueListener l) {
undoQueueListeners.add(l);
}
| 0 |
public Location placeShip(int size, boolean retry)
throws ArrayIndexOutOfBoundsException, InputMismatchException {
shipSize = size;
randomRow = (int) (Math.random() * (SIZE - 2));
randomCol = (int) (Math.random() * (SIZE - 2));
Random random = new Random();
horizontal = random.nextBoolean();
// System.out.println("RandomRow & RandomCol: " + randomRow + " "
// + randomCol);
if (randomRow < 0 || randomCol < 0
|| (horizontal && randomRow + shipSize > 10)
|| (!horizontal && randomCol + shipSize > 10))
return placeShip(size, true);
ship = new ComputerLocation(randomRow, randomCol, horizontal, shipSize);
if (isValid() == false) {
return placeShip(size, true);
}
setComputerBoard();
return ship;
}
| 7 |
@Override
public boolean isSavingNotRequired() {
Path p;
try {
p = Paths.get(getChildrenSaveTo());
if (Files.isDirectory(p))
return true;
} catch (IOException e) {
Main.log(Level.WARNING,null,e);
}
return false;
}
| 2 |
protected Pane addMenuButtons() {
GridPane mainPane = new GridPane();
mainPane.setVgap(20);
HBox chartGroupPane = new HBox();
chartGroupPane.setAlignment(Pos.CENTER);
//Stworzenie przycisków do wyboru typu wykresu (liniowy, świecowy)
final ToggleGroup chartGroup = new ToggleGroup();
Image image1 = new Image(getClass().getResourceAsStream("lineChartIcon.png"));
Image image2 = new Image(getClass().getResourceAsStream("candleChartIcon.png"));
ToggleButton line = new ToggleButton();
line.setGraphic(new ImageView(image1));
line.setUserData("line");
candle = new ToggleButton();
candle.setGraphic(new ImageView(image2));
candle.setUserData("candle");
line.setToggleGroup((chartGroup));
candle.setToggleGroup((chartGroup));
chartGroupPane.getChildren().addAll(line, candle);
//Na wstepie wybrany zostaje wykres liniowy
selectedChart = "line";
chartGroup.selectToggle(line);
////////////////////
//Stworzenie przycisków do wyboru zakresu dat
final ToggleGroup rangeGroup = new ToggleGroup();
List<DataRange> enumList = Arrays.asList(DataRange.values());
FlowPane flowPane = new FlowPane();
flowPane.setAlignment(Pos.CENTER);
flowPane.setPrefWrapLength(70);
Text rangesTitle = new Text("Zakresy dat");
flowPane.getChildren().add((rangesTitle));
//Przyciski tworze w pętli lecąc po wartośćiach enuma
for (DataRange d : enumList) {
ToggleButton button = new ToggleButton(getDataRangeShortName(d));
button.setMinSize(48, 48);
button.setUserData(d.toString());
button.setToggleGroup(rangeGroup);
flowPane.getChildren().add(button);
}
rangeGroup.selectToggle(rangeGroup.getToggles().get(4));
//Obsługa przycisków do wyboru zakresu dat
//W klasach dziedziczących po InvestorView wywoływana jest abstrakcyjna metoda OnDataRangeChanged
rangeGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) {
if (new_toggle == null) {
toggle.setSelected(true);
return;
}
System.out.println(new_toggle.toString());
selectedRange = DataRange.valueOf((String) new_toggle.getUserData());
switch (selectedRange) {
case ONEDAY:
candle.setDisable(true);
break;
default:
candle.setDisable(false);
break;
}
OnDataRangeChanged();
}
});
chartGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) {
if (new_toggle == null) {
toggle.setSelected(true);
return;
}
//System.out.println(DataRange.valueOf((String)new_toggle.getUserData()));
//selectedRange = DataRange.valueOf((String)new_toggle.getUserData());
selectedChart = new_toggle.getUserData().toString();
((ToggleButton)rangeGroup.getToggles().get(0)).setDisable(selectedChart.equals("candle"));
//System.out.println("!!!!!!!!!!!!!!!"+selectedChart);
OnChartTypeChanged(selectedChart);
}
});
//----------------------------------------------------------------------
//Buttony do wskaźników
//----------------------------------------------------------------------
FlowPane pointerGroupPane = new FlowPane();
pointerGroupPane.setAlignment(Pos.CENTER);
pointerGroupPane.setPrefWrapLength(70);
//Stworzenie przycisków do wyboru wskaźników
final ToggleGroup pointerGroup = new ToggleGroup();
ToggleButton MA = new ToggleButton();
MA.setMinSize(48, 48);
MA.setText("MA");
MA.setUserData("MA");
ToggleButton SD = new ToggleButton();
SD.setMinSize(48, 48);
SD.setText("SD");
SD.setUserData("SD");
ToggleButton bollinger = new ToggleButton();
bollinger.setMinSize(48, 48);
bollinger.setText("Bollinger");
bollinger.setUserData("bollinger");
ToggleButton koperta = new ToggleButton();
koperta.setMinSize(48, 48);
koperta.setText("Koperta");
koperta.setUserData("koperta");
ToggleButton EMA = new ToggleButton();
EMA.setMinSize(48, 48);
EMA.setText("EMA");
EMA.setUserData("EMA");
ToggleButton hide = new ToggleButton();
hide.setMinSize(48, 48);
hide.setText("hide");
hide.setUserData("hide");
MA.setToggleGroup((pointerGroup));
bollinger.setToggleGroup((pointerGroup));
koperta.setToggleGroup((pointerGroup));
EMA.setToggleGroup((pointerGroup));
hide.setToggleGroup((pointerGroup));
pointerGroup.selectToggle(hide);
Text pointersTitle = new Text("Wskaźniki");
pointerGroupPane.getChildren().addAll(pointersTitle, MA, SD, bollinger, koperta, EMA, hide);
pointerGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) {
if (new_toggle != null) {
System.out.println(new_toggle.toString());
//selectedRange = DataRange.valueOf((String)new_toggle.getUserData());
lastPointerType = pointerType;
pointerType = (String) new_toggle.getUserData();
} else {
lastPointerType = pointerType;
pointerType = "hide";
}
OnPointerChange();
}
});
SD.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
OnSDPointer(newValue);
}
});
//----------------------------------------------------------------------
mainPane.add(chartGroupPane, 0, 0);
mainPane.add(flowPane, 0, 1);
mainPane.add(pointerGroupPane, 0, 2);
return mainPane;
}
| 9 |
public void postLogin(String userId, ModelAndView view) {
int deptId = m_user.getDepartment();
String viewName = null;
if (deptId == 10)
viewName = "employee";
else if (deptId == 20)
viewName = "manager";
else if (deptId == 30)
viewName = "hrdepartment";
else if(deptId == 40)
viewName = "training";
view.setViewName(viewName);
view.addObject("user_details", m_user);
view.addObject("employee_details", employeeDao.getEmployeeDetails(userId));
new CommonUtil();
}
| 4 |
public Message(@NotNull MessageType type, String title, @NotNull String content, Runnable yes) {
String path = null;
yesAction = yes;
buttons = new ArrayList<GuiButton>();
switch (type) {
case INFO:
path = "message/infoLogo";
break;
case ERROR:
path = "message/errorLogo";
break;
case CRITICAL:
path = "message/criticalLogo";
break;
case WARNING:
path = "message/warningLogo";
break;
case CONFIRMATION:
path = "message/confirmLogo";
isConfirmation = true;
break;
}
texturePath = path;
String[] splits = content.split("\n");
if (splits.length > 3) {
GameApplication.engineLogger.warning("MessageDisplay -> Can not set content : LINE_NUMBER_EXITING_MEMORY");
return;
}
int i = 0;
for (String s : splits) {
messageContent[i] = s;
i++;
}
messageTitle = title;
}
| 7 |
public static int minJump(int[] input) {
if(input == null || input.length == 0 || input[0] == 0){
return -1;
}
int[] minJump = new int[input.length+1];
minJump[0] = 0;
for(int i = 1; i<= input.length; i++) {
minJump[i] = Integer.MAX_VALUE;
for(int j = 0; j <i ; j++) {
if(minJump[j] + input[j] >= i && minJump[i] > minJump[j]) {
minJump[i] = minJump[j] + 1;
}
}
}
return minJump[input.length-1];
}
| 7 |
private void updateCart() {
shoppingCartArea.clear();
if (currentCart.size() == 0) {
shoppingCartArea.add(emptyLabel);
} else {
int price = 0;
for (final Product p : currentCart) {
if (p.getInCurrentCart() == 0) {
cartRemoveTemp.add(p);
price += p.getPrice() * p.getInCurrentCart();
continue;
}
HorizontalPanel productPanel = new HorizontalPanel();
productPanel.setWidth("100%");
Label name = new Label(p.getName() + " x "
+ p.getInCurrentCart());
Button remove = new Button("x");
remove.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
removeProductFromCart(p);
}
});
productPanel.add(name);
productPanel.add(remove);
productPanel.setCellHorizontalAlignment(remove, ALIGN_RIGHT);
shoppingCartArea.add(productPanel);
price += p.getPrice() * p.getInCurrentCart();
}
currentCart.removeAll(cartRemoveTemp);
cartRemoveTemp.clear();
totalPrice.setText("Total price: " + Integer.toString(price)
+ " kr");
}
}
| 3 |
public CheckResultMessage error(String message) {
return new CheckResultMessage(message, CheckResultMessage.CHECK_ERROR);
}
| 0 |
static void realRead(InputStream is, byte[] buffer, int bytesToRead) throws IOException {
int read = 0, value;
while (read < bytesToRead) {
value = is.read();
if (value < 0) {
throw new RuntimeException("EOF!");
}
buffer[read++] = (byte) value;
read += is.read(buffer, read, bytesToRead - read);
}
}
| 2 |
public void copyFile(File source, File dest) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(dest);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
byte[] buf = new byte[2048];
int bytes = bis.read(buf);
while (bytes != -1) {
bos.write(buf, 0, bytes);
bytes = bis.read(buf);
}
buf = null;
} finally {
if (bis != null) {
try {
bis.close();
} catch (Exception e) {
cat.error(e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
cat.error(e);
}
}
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
cat.error(e);
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
cat.error(e);
}
}
}
}
| 9 |
public String getName() {
return name;
}
| 0 |
private Door[] sortDoors(int whichWall) {
ArrayList<Door> doorTempList = new ArrayList<>();
doorTempList.addAll(doors.get(whichWall)); //copy doors into temp list
Door[] temp = new Door[doors.get(whichWall).size()];
if (temp.length > 0) {
for (int i = 0; i < temp.length; i++) {
int smallest = 0;
for (int d = 0; d < doorTempList.size(); d++) {
if (doorTempList.get(d).getX() < doorTempList.get(smallest).getX()) {
smallest = d;
}
}
temp[i] = doorTempList.get(smallest);
doorTempList.remove(smallest);
}
}
return temp;
}
| 4 |
@Override
public boolean generate(World world, Random random, int i, int k, int j) {
// TODO Auto-generated method stub
if (world.getBlockId(i, k, j) != VoidMod.hardenSpaceTimeStructure.blockID) {
return false;
}
// size Generator
int aid = random.nextInt(3) + 2;
int size = aid * 2 - random.nextInt(2) + 1;
// offset generator
int Xoff = random.nextInt(aid + 1);
int Zoff = random.nextInt(aid + 1);
int Yoff = random.nextInt(size * 2 - 1) + 1;
// direction generator
int Xdir = random.nextInt(2) * 2 - 1;
int Zdir = random.nextInt(2) * 2 - 1;
int i1 = 0;
int j1 = 0;
int Ci = 0;
int Cj = 0;
for (int k1 = 0; k1 <= 120; k1++) {
for (i1 = Ci; i1 < Math.ceil((double) 120 / Yoff) * Xoff
+ (size - Xoff); i1++) {
for (j1 = Cj; j1 < Math.ceil((double) 120 / Yoff) * Zoff
+ (size - Zoff); j1++) {
if ((Math.ceil(k1 / Yoff) - 1) * Xoff == i1
&& (Math.ceil(k1 / Yoff) - 1) * Zoff == j1) {
Ci = i1 - 1;
Cj = j1 - 1;
for (int i2 = i1; i2 < size + i1; i2++) {
for (int j2 = j1; j2 < size + j1; j2++) {
world.setBlock(
i + i2 * Xdir,
k1,
j + j2 * Zdir,
VoidMod.hardenSpaceTimeStructure.blockID);
}
}
}
}
}
}
return true;
}
| 8 |
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0.56f, 0.165f, 0.1f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
timeElapsed += delta;
gameOverView.render(delta);
/**
* If the round score is higher than the highscore it will be saved
* as new highscore
* */
if(!doneCheckingForHighscore){
doneCheckingForHighscore = true;
int highscore = ScoreRepository.getInstance().retrieveScore();
if(roundScore> highscore){
ScoreRepository.getInstance().saveScore(roundScore);
}
}
/**
* Check for input so you can go back to the title screen
* */
if ((Gdx.input.justTouched()||Gdx.input.isKeyPressed(Keys.BACK))&&timeElapsed>1) {
MusicPlayer.getInstance().stopSoundtrack();
this.game.setScreen(new TitleScreen(game));
}
}
| 5 |
public void deleteTheSame() {
// - Parcours de matrixb à la recherche des boules identifiées
// comme appartenant à une famille.
// - Suppression des boules corrrespondantes (remise à zéro dans matrix)
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (matrixb[i][j])
matrix[i][j] = 0;
}
}
initMatrixb();
}
| 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(BloquerPrestataire.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BloquerPrestataire.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BloquerPrestataire.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BloquerPrestataire.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 BloquerPrestataire().setVisible(true);
}
});
}
| 6 |
@Override
public void run() {
while (popups != null) {
console.displayMsg("Update");
synchronized (popups) {
while (popups.isEmpty()) {
try {
popups.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
for (int i = 0; i < popups.size(); i++) {
if (popups.get(i).update()) {
popups.remove(i);
drawerPanel.repaint();
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
| 6 |
public boolean equals(Object obj) {
try {
if (!obj.getClass().equals(audioClass.class)) {
throw new Exception();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (obj != null)
&& ((audioClass) obj).toString().equals(this.filePath)
&& ((audioClass) obj).soundClip.equals(this.soundClip);
}
| 4 |
@Override
public MultiMenuPlacePlanetChoices doSelection(Factory factory) {
updateState();
while (state != -1) {
Menu<?> menu = getMenu(state, factory);
switch (state) {
case 1:
choices.setChosenPlanet((Planet) menu.selectChoice(false));
break;
case 2:
rotatePlanetChoice = (StaticChoice) menu.selectChoice(true);
break;
case 3:
choices.setChosenSpot((PlanetEntrance) menu.selectChoice(true));
break;
case 4:
StaticChoice placeFirstBaseChoice = (StaticChoice) menu.selectChoice(true);
if (placeFirstBaseChoice == null) {
choices.setPlaceFirstBase(null);
} else if (placeFirstBaseChoice == StaticChoice.PLACE_FIRST_BASE_YES) {
choices.setPlaceFirstBase(true);
} else {
choices.setPlaceFirstBase(false);
}
break;
case 5:
choices.setChosenBaseArea((Area) menu.selectChoice(true));
break;
default:
throw new IllegalStateException("This state shouldn't happen.");
}
updateState();
}
return choices;
}
| 9 |
public int getBoardWidth()
{
return this.w;
}
| 0 |
@Override
protected void deserialize_() throws IOException {
if (this.in == null) {
return;
}
this.io.startProgress("Reading data base of previous run", -1); // init
this.in.registerProgressMonitor(this.io);
this.io.setProgressTitle("Reading data base of previous run"); // set
// message
this.in.read(); // version byte
final byte[] modField = new byte[Long.SIZE / 8];
final byte[] intField = new byte[Integer.SIZE / 8];
final byte[] idxField = new byte[Short.SIZE / 8];
final ByteBuffer modBuffer = ByteBuffer.wrap(modField);
final ByteBuffer intBuffer = ByteBuffer.wrap(intField);
final ByteBuffer idxBuffer = ByteBuffer.wrap(idxField);
final ByteBuffer nameBuffer = ByteBuffer.allocate(600);
final DirTree tree = this.sdc.getDirTree();
while (!this.in.EOFreached()) {
if (Thread.currentThread().isInterrupted()) {
return;
}
final boolean ext = readUntilSep(nameBuffer);
final String name = new String(nameBuffer.array(), 0,
nameBuffer.position());
this.in.read(modField);
modBuffer.position(0);
final long mod;
final Map<Integer, String> voices;
if (ext) {
mod = modBuffer.getLong();
this.in.read(intField);
intBuffer.position(0);
voices = new HashMap<>(intBuffer.getInt());
boolean end = false;
do {
this.in.read(intField);
intBuffer.position(0);
@SuppressWarnings("hiding")
final int idx = intBuffer.getInt();
end = readUntilSep(nameBuffer);
final String desc = new String(nameBuffer.array(), 0,
nameBuffer.position());
voices.put(idx, desc);
} while (!end);
} else {
final int voicesCount;
voicesCount = modBuffer.getChar();
modBuffer.position(0);
modBuffer.putChar((char) 0);
modBuffer.position(0);
mod = modBuffer.getLong();
voices = new HashMap<>(voicesCount);
for (int i = 0; i < voicesCount; i++) {
this.in.read(idxField);
idxBuffer.position(0);
@SuppressWarnings("hiding")
final int idx = idxBuffer.getShort();
final String desc = new String(
this.in.readTo(Deserializer_3.SEPERATOR_3));
voices.put(idx, desc);
}
}
final Path p = this.root.resolve(name.split("/"));
if (p.exists()) {
tree.put(new SongDataEntry(p, voices, mod));
}
}
this.io.close(this.in);
this.inFile.delete();
}
| 7 |
public static void disposeImages() {
// dispose loaded images
{
for (Image image : m_imageMap.values()) {
image.dispose();
}
m_imageMap.clear();
}
// dispose decorated images
for (int i = 0; i < m_decoratedImageMap.length; i++) {
Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i];
if (cornerDecoratedImageMap != null) {
for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) {
for (Image image : decoratedMap.values()) {
image.dispose();
}
decoratedMap.clear();
}
cornerDecoratedImageMap.clear();
}
}
}
| 5 |
public void run()
{
while (mRun) {
try {
EventDescriptorObject lObject = mDataStorage.getData();
if (lObject == null)
{
mRun = false;
} // if
if (mRun)
{
EventObject lEventObject = mDataOperator.readEvent(lObject
.getType(), lObject.getIndex());
String lMessage = lEventObject.getMessage();
boolean lFind = true;
for (String lTerm : mQueryList) {
if (!lMessage.contains(lTerm))
{
lFind = false;
break;
} // if
} // for
if (lFind)
{
for (String lTerm : SingleEventGenertatorProcess.COMMON_NON_KEYWORD)
{
lMessage = lMessage.replace(lTerm, "");
} // for
lEventObject.setMessage(lMessage);
mDataOperator.write(lEventObject,
mDataType, lObject.getIndex());
} // if
} // if
} // try
catch (Exception pException) {
mLogger.error("Thread Interrupted");
mLogger.debug(pException.toString());
mRun = false;
} // catch
} // while
if(mCountDownLatch != null)
{
mCountDownLatch.countDown();
} // if
} // void run
| 9 |
@Override
public boolean canAttack(Board board, Field currentField, Field occupiedField) {
return this.validSetupForAttack(currentField, occupiedField) && currentField.inDiagonalPathWith(occupiedField) && board.clearPathBetween(currentField, occupiedField);
}
| 2 |
public static void figureOutParamDeclarations(PrintStream w, Object... comps) {
Map<String, Access> m = new HashMap<String, Access>();
for (Object c : comps) {
ComponentAccess cp = new ComponentAccess(c);
// System.out.println("// Parameter from " + objName(cp));
// over all input slots.
for (Access fin : cp.inputs()) {
Role role = fin.getField().getAnnotation(Role.class);
if (role != null && Annotations.plays(role, Role.PARAMETER)) {
// make sure parameter is only there once.
m.put(fin.getField().getName(), fin);
}
}
}
List<String> sl = new ArrayList<String>(m.keySet());
Collections.sort(sl, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
for (String key : sl) {
Access fin = m.get(key);
Description d = fin.getField().getAnnotation(Description.class);
if (d != null) {
w.println(" @Description(\"" + d.value() + "\")");
}
Bound b = fin.getField().getAnnotation(Bound.class);
if (b != null) {
w.println(" @Bound(\"" + b.value() + "\")");
}
w.println(" @Role(\"" + fin.getField().getAnnotation(Role.class).value() + "\")");
w.println(" @In public " + fin.getField().getType().getSimpleName() + " " + fin.getField().getName() + ";");
w.println();
}
}
| 7 |
public E get(int index) throws IndexOutOfBoundsException
{
if(index >= size || index < 0)
throw new IndexOutOfBoundsException();
int count;
Node temp;
//Occurs if index is towards the end of the list
if(index > size/2){
count = size;
temp = tail;
while(--count >= index)
temp = temp.prev;
return temp.data;
}
//This occurs if index <= size/2
count = -1;
temp = head;
while(++count <= index){
temp = temp.next;
}
return temp.data;
}
| 5 |
public ExcFile(File f) throws IOException
{
srgMethodName2ExcData = new HashMap<String, ExcData>();
srgParamName2ExcData = new HashMap<String, ExcData>();
// example lines:
// net/minecraft/util/ChunkCoordinates=CL_00001555
// net/minecraft/world/chunk/storage/AnvilChunkLoader.func_75816_a(Lnet/minecraft/world/World;Lnet/minecraft/world/chunk/Chunk;)V=net/minecraft/world/MinecraftException,java/io/IOException|p_75816_1_,p_75816_2_
// net/minecraft/world/biome/BiomeGenMutated.func_150571_c(III)I=|p_150571_1_,p_150571_2_,p_150571_3_
// net/minecraft/world/chunk/storage/AnvilChunkLoader.func_75818_b()V=|
// net/minecraft/server/MinecraftServer.func_145747_a(Lnet/minecraft/util/IChatComponent;)V=|p_145747_1_
Scanner in = new Scanner(new FileReader(f));
try
{
while (in.hasNextLine())
{
if (in.hasNext("#"))
{
in.nextLine();
continue;
}
in.useDelimiter("\\.");
String srgOwner = in.next();
in.useDelimiter("\\(");
if (!in.hasNext())
if (in.hasNextLine())
in.nextLine();
else
break;
String srgName = in.next().substring(1);
in.useDelimiter("=");
String descriptor = in.next();
in.useDelimiter("\\|");
String excs = in.next().substring(1);
String params = in.nextLine().substring(1);
ExcData toAdd = new ExcData(srgOwner, srgName, descriptor,
(excs.length() > 0 ? excs.split(",") : new String[0]),
(params.length() > 0 ? params.split(",") : new String[0]));
ExcData existing = srgMethodName2ExcData.get(srgName);
if ((existing == null) || (existing.getParameters().length < toAdd.getParameters().length))
{
srgMethodName2ExcData.put(srgName, toAdd);
for (String parameter : toAdd.getParameters())
srgParamName2ExcData.put(parameter, toAdd);
}
}
}
finally
{
in.close();
}
}
| 9 |
public MapData(int a_data,int b_data){
this.a_data = a_data;
this.b_data = b_data;
}
| 0 |
public void decreaseKey(int i, Key key) {
if (i < 0 || i >= NMAX) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) <= 0) throw new IllegalArgumentException("Calling decreaseKey() with given argument would not strictly decrease the key");
keys[i] = key;
swim(qp[i]);
}
| 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.