method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
1809b017-d341-4656-9033-8ae4a3387866 | 2 | public static String ConvertValueForIndexing(Object value)
{
if (value instanceof String)
return " " + value.toString().toUpperCase();
else if (value instanceof Date)
{
return value.toString();
}
else
{
return value.toString();
}
} |
07a05dad-1d34-4be5-80fd-a4b41ae68eb3 | 1 | @Override
public void fireEvent(UIEvent e) {
super.fireEvent(e);
if(e instanceof ValueChangeEvent) {
processValueChangeEvent((ValueChangeEvent) e);
}
} |
9d115c99-5745-403d-a3dd-3c6c878cf10d | 6 | public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* name: username, password
* return: [{"status":"", "reason":"", "data":""}]
*
* request: username, password
* response: status (create a session, insert uId into session)
*/
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println("[request.getReader().readLine()]: "); //+ request.getReader().readLine());
// read request body content
BufferedReader bf = request.getReader();
String line = bf.readLine();
StringBuilder sb = new StringBuilder();
while(line != null) {
sb.append(line);
line = bf.readLine();
}
String json = sb.toString();
out.println(json);
// decode the json text from the content of request
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(json);
} catch (ParseException e) {
e.printStackTrace();
}
JSONArray array = (JSONArray) obj;
out.println("======the 1 element of array======");
out.println(array.get(0));
out.println();
JSONObject obj2 = (JSONObject) array.get(0);
out.println("======field \"b\"==========");
out.println(obj2.get("id"));
out.println("======field \"id\"==========");
String ids = (String)obj2.get("id");
String[] id_array = ids.split(",");
for(String s : id_array) {
out.println(s);
}
DealsDAO dealsDAO = new DealsDAO();
List<Deals> deals = new ArrayList<Deals>();
for (String s : id_array) {
int id = parseInteger(s);
Deals deal = null;
if (id == -1) {
//TODO response err
}
else {
deal = dealsDAO.selectById(id);
}
deals.add(deal);
}
out.println("<h4>Deals:</h4>");
for (int i=0; i<deals.size(); i++){
out.println("Index "+ (i+1) +": ");
String str = deals.get(i).toString();
str=new String(str.getBytes("utf-8"),"8859_1");
out.println(str);
out.println("<br />");
}
out.println("=============================================");
out.println("<br />");
out.println(convertEncoding(convertDealsToJson(deals)));
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} |
5e75503f-6fcb-429c-a396-3e6a2d7b7a9a | 7 | public static boolean[] intToBoolean(int[] octets) throws SubneterException
{
if (octets.length != 4)
{
throw new SubneterException("Invalid IP adress too many or to less octets");
}
for (int i = 0; i < 4; i++)
{
if (octets[i] < 0 || octets[i] > 255)
{
throw new SubneterException("Invalid IP adress " + (i + 1) + ". octed is " + octets[i]);
}
}
boolean[] bits = new boolean[32];
for (int i = 0; i < 4; i++)
{
for (int ii = 0; ii < 8; ii++)
{
if (octets[i] >= Math.pow(2, 7 - ii))
{
bits[i * 8 + ii] = true;
octets[i] -= Math.pow(2, 7 - ii);
}
else
{
bits[i * 8 + ii] = false;
}
}
}
return bits;
} |
b5945c1d-ec41-43de-b7e3-1d369e31a8d1 | 6 | public void update() {
player.update();
player.checkAttack(enemies);
player.checkCoins(coins);
finish.update();
finish.checkGrab(player);
bg.setPosition(tileMap.getx(), 0);
tileMap.setPosition(
GamePanel.WIDTH / 2 - player.getx(),
GamePanel.HEIGHT / 2 - player.gety());
if(player.isDead()){
player.setPosition(100, 500);
player.reset();
//restart();
player.revive();
}
for(int i = 0; i < enemies.size(); i++){
Enemy e = enemies.get(i);
e.update();
if(player.isDrunk()){
e.kill();
}
if(e.isDead()){
enemies.remove(i);
e.addScore(Level2State.score);
i--;
}
}
for(int i = 0; i < coins.size(); i++){
Coin c = coins.get(i);
c.update();
if(c.shouldRemove()){
coins.remove(i);
c.addScore();
i--;
}
}
} |
848e00df-1ca0-41c5-9fba-31c9a41cc7ee | 2 | public void test_03() {
System.out.println("\n\nSuffixIndexerNmer: Add test");
String fastqFileName = "tests/short.fastq";
// Create indexer
SuffixIndexerNmer<DnaAndQualitySequence> seqIndexNmer = new SuffixIndexerNmer<DnaAndQualitySequence>(new DnaQualSubsequenceComparator(true), 15);
// Add all sequences from a file
for( Fastq fastq : new FastqFileIterator(fastqFileName, FastqVariant.FASTQ_ILLUMINA) ) {
String seq = fastq.getSequence();
if( seq.indexOf('N') < 0 ) {
// Create sequence and add it to indexer
String qual = fastq.getQuality();
DnaAndQualitySequence bseq = new DnaAndQualitySequence(seq, qual, FastqVariant.FASTQ_ILLUMINA);
seqIndexNmer.add(bseq);
}
}
// Sanity check
seqIndexNmer.sanityCheck();
} |
fd760471-1160-4550-a468-75776dd4ab94 | 3 | public void drawBackground(Graphics g) {
// draw the background graphics from the superclass
super.drawBackground(g);
ImageManager im = ImageManager.getSingleton();
Image img;
Position p;
// draw the map as a matrix of tiles with cities on top
for ( int r = 0; r < GameConstants.WORLDSIZE; r++ ) {
for ( int c = 0; c < GameConstants.WORLDSIZE; c++ ) {
p = new Position(r,c);
int xpos = GfxConstants.getXFromColumn(c);
int ypos = GfxConstants.getYFromRow(r);
// Draw proper terrain
Tile t = game.getTileAt(p);
String image_name = t.getTypeString();
// special handling of ocean coasts
if ( image_name == GameConstants.OCEANS ) {
image_name = image_name +
MapAlgorithms.getCoastlineCoding(game, p );
}
img = im.getImage( image_name );
g.drawImage( img, xpos, ypos, null );
}
}
} |
35be6fe8-b4ab-4b7f-8cb6-9c94ec984dc7 | 2 | private void readLimitedInto(HttpURLConnection conn, int limit, ByteArrayOutputStream read) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(getConnectionInputStream(conn)));
String line = null;
while ((line = in.readLine()) != null) {
read.write(line.getBytes());
if (read.size() > limit) {
return;
}
}
} |
e61e8618-f786-4437-b0f8-5990c2e79fe7 | 4 | public static byte[] mapleDecrypt(byte[] data) {
for (int j = 1; j <= 6; j++) {
byte remember = 0;
byte dataLength = (byte) (data.length & 0xFF);
byte nextRemember;
if (j % 2 == 0) {
for (int i = 0; i < data.length; i++) {
byte cur = data[i];
cur -= 0x48;
cur = ((byte) (~cur & 0xFF));
cur = ByteTool.rollLeft(cur, dataLength & 0xFF);
nextRemember = cur;
cur ^= remember;
remember = nextRemember;
cur -= dataLength;
cur = ByteTool.rollRight(cur, 3);
data[i] = cur;
dataLength--;
}
} else {
for (int i = data.length - 1; i >= 0; i--) {
byte cur = data[i];
cur = ByteTool.rollLeft(cur, 3);
cur ^= 0x13;
nextRemember = cur;
cur ^= remember;
remember = nextRemember;
cur -= dataLength;
cur = ByteTool.rollRight(cur, 4);
data[i] = cur;
dataLength--;
}
}
}
return data;
} |
a7a58c61-1ed5-44e5-9d40-ffed5f659a71 | 6 | public static void save(String filename, double[] input) {
// assumes 44,100 samples per second
// use 16-bit audio, mono, signed PCM, little Endian
AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
byte[] data = new byte[2 * input.length];
for (int i = 0; i < input.length; i++) {
int temp = (short) (input[i] * MAX_16_BIT);
data[2*i + 0] = (byte) temp;
data[2*i + 1] = (byte) (temp >> 8);
}
// now save the file
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais, format, input.length);
if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
}
else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));
}
else {
throw new RuntimeException("File format not supported: " + filename);
}
}
catch (Exception e) {
System.out.println(e);
System.exit(1);
}
} |
98421a04-7273-4fdc-a9fd-170cee34224f | 0 | public void setStart(int start) {this.start = start;} |
89acc7e6-9a80-4b3c-b602-cfe3368d5675 | 1 | @Override
public String toString() {
if (sb.length() >= delimiter.length())
sb.setLength(sb.length() - delimiter.length());
return sb.toString();
} |
4d21bd9f-ac97-45f5-8566-854b267e130d | 7 | public static boolean computeCell(boolean[][] world, int col, int row) {
boolean liveCell = getCell(world, col, row);
int neighbours = countNeighbours(world, col, row);
boolean nextCell = false;
if (neighbours < 2)
nextCell = false;
if (liveCell && (neighbours == 2 || neighbours == 3))
nextCell = true;
if (neighbours > 3)
nextCell = false;
if (!liveCell && (neighbours == 3))
nextCell = true;
return nextCell;
} |
22d6d5eb-4d30-4659-b485-2d513018eacf | 1 | public static void awardBonusInternal() {
BigInteger bonusReduction = BigInteger.valueOf(100);
// To be worked out.
System.out.print("Balances of all accounts (int): ");
for (BankAccount account: christmasBank.getAllAccounts())
System.out.print(" " + account.getBalance());
System.out.println();
} |
ed59b879-6679-415e-98e1-5c846d6ac868 | 7 | public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
ArrayList<TreeNode> levelNode = new ArrayList<TreeNode>();
levelNode.add(root);
while (!levelNode.isEmpty()) {
ArrayList<Integer> rr = new ArrayList<Integer>();
for (TreeNode t : levelNode) {
rr.add(t.val);
}
result.add(rr);
int originalSize = levelNode.size();
for (int i = 0; i < originalSize; i++) {
if (levelNode.get(i).left != null) {
levelNode.add(levelNode.get(i).left);
}
if (levelNode.get(i).right != null) {
levelNode.add(levelNode.get(i).right);
}
}
for (int i = 0; i < originalSize; i++) {
levelNode.remove(0);
}
}
return result;
} |
db1d74de-1f6b-49da-a482-ff66a624e9ed | 7 | @Override
public Boolean doStep() {
this.incrementStepNumber();
this.modelLogging("The step " + this.stepNumber + " is starting.\n" +
"The model is:\n", this.steppingModel);
this.notifyStatus("Step " + this.stepNumber + " started");
// ==> Convert the model into a standard linear model if it isn't valid
if (!this.steppingModel.isValid() && !this.solverStepHelper.fixModel()) {
this.notifyStatusAndLog("Cannot fix the input model");
return Boolean.FALSE;
}
// ==> If the solution is already optimal don't do nothing
if (this.solverStepHelper.isSolutionOptimal()) {
this.notifyStatusAndLog("The found solution is optimal. The solution is: " +
this.steppingModel.getCurrentSolution().getNonAugmentedSolution());
return Boolean.TRUE;
}
if (this.solverStepHelper.checkInitialSolution()) {
// ==> There is an initial solution => compute the current step for the current model
try {
Integer[] pivot = this.solverStepHelper.findPivot();
this.solverStepHelper.doPivot(pivot[0], pivot[1]);
logger.info("Completed the pivot step.\nThe model is:\n" + this.steppingModel.toString());
if (this.solverStepHelper.isSolutionOptimal()) {
// ==> The step computation returned an optimal solution
logger.info("The found solution is optimal");
this.notifyStatus("Completed the pivot step. The found solution is optimal: " +
this.steppingModel.getCurrentSolution().getNonAugmentedSolution());
} else {
// ==> The step computation returned a non-optimal solution
logger.info("The found solution isn't optimal. More steps are needed.");
this.notifyStatus("Completed the pivot step. The found solution isn't optimal. " +
"More steps are needed.");
}
} catch (UnlimitedProblemException exc) {
this.notifyStatusAndLog("The problem is unlimited");
}
} else {
// ==> There isn't a initial solution => create and compute a new simplex to get the initial
// solution
try {
this.solverStepHelper.findInitialSolution();
this.notifyStatusAndLog("Found the initial solution:\n" +
this.steppingModel.getCurrentSolution().toString());
} catch (UnlimitedProblemException exc) {
this.notifyStatusAndLog("The problem is unlimited");
}
}
return Boolean.TRUE;
} |
9ef73e1b-4ca7-4bfc-a44c-930919e2b320 | 5 | public Character() {
_level = 1;
_health = 0;
_initiative = 0;
_attributes = new Attributes();
_generator = new NormalSpread();
_race = new Deva();
_class = new Ardent();
_classMap = new Vector<>();
_setting = new DnD4e();
BaseGenerator g = new SpecialSpread();
for (BaseClass bc : _setting.getClasses()) {
for (BaseRace br : _setting.getRaces()) {
int[] attributes = g.getAttributes();
Vector<Integer> bonuses = br.getBonuses();
Vector<Integer> ranks = bc.getRanks();
Vector<Integer> preferred = bc.getPreferred();
int[] sums = {0, 0, 0, 0, 0, 0};
for (int i = 0; i < 6; i++) {
sums[i] += (bonuses.contains(i)) ? 2 : 0;
sums[i] += attributes[ranks.elementAt(i)];
}
float average = 0;
for (int index : preferred) {
average += sums[index];
}
average /= 3;
ClassMap cm = new ClassMap(bc, br, Math.round(average));
_classMap.add(cm);
}
}
} |
371bd995-47ae-485b-910b-c13b6ae3d9a6 | 6 | public boolean attackEntityAsMob(Entity par1Entity)
{
if (super.attackEntityAsMob(par1Entity))
{
if (par1Entity instanceof EntityLiving)
{
byte var2 = 0;
if (this.worldObj.difficultySetting > 1)
{
if (this.worldObj.difficultySetting == 2)
{
var2 = 7;
}
else if (this.worldObj.difficultySetting == 3)
{
var2 = 15;
}
}
if (var2 > 0)
{
((EntityLiving)par1Entity).addPotionEffect(new PotionEffect(Potion.poison.id, var2 * 20, 0));
}
}
return true;
}
else
{
return false;
}
} |
cb3279b6-c378-48e9-a82f-d5771d8960e4 | 9 | public List<List<Integer>> subsets(int[] S) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
quickSort(S);
int length = S.length;
int[] index = new int[length];
for (int i = 0; i < length; i++) {
index[i] = 0;
}
int currTurnLength = 0;
int eleHave = 0;
int lastTurnIndex = 0;
while (currTurnLength++ < length) {
eleHave = 0;
lastTurnIndex = -1;
while (true) {
while (eleHave < currTurnLength) {
lastTurnIndex++;
index[eleHave] = lastTurnIndex;
eleHave++;
}
Integer[] turnRet = new Integer[currTurnLength];
for (int i = 0; i < currTurnLength; i++) {
turnRet[i] = S[index[i]];
}
ret.add(Arrays.asList(turnRet));
boolean found = false;
while (eleHave-- > 0 && !found) {
if (length - index[eleHave] > (currTurnLength - eleHave)) {
lastTurnIndex = index[eleHave];
found = true;
break;
}
}
if (!found) {
break;
}
}
}
ret.add(new ArrayList<Integer>());
return ret;
} |
4c15b69f-d5ef-49d0-bc91-ce736df676cb | 1 | public Object getValueAt(int row, int col)
{
if (col == ENTITY) { // afficher l'entité dans laquelle la propriété est utilisée (Bug #712439).
return getEntityNameOfProperty(row);
} else {
return rows.get(row)[col];
}
} |
c0c12913-9680-4813-a174-00117858d4e2 | 8 | @SuppressWarnings("unchecked")
public static <VertexType extends BaseVertex, EdgeType extends BaseEdge<VertexType>>
boolean isBipartite(BaseGraph<VertexType, EdgeType> graph) {
//Copying to ColorableVertex
ColorableVertex<VertexType>[] CVArray = (ColorableVertex<VertexType>[])Array.newInstance(ColorableVertex.class , graph.getVerticesCount());
int i=0;
for (VertexType vm : graph)
{
CVArray[i] = new ColorableVertex<VertexType>(vm);
i++;
}
LinkedList<ColorableVertex<VertexType>> queue = new LinkedList<ColorableVertex<VertexType>>();
ColorableVertex<VertexType> cv = CVArray[0];
for (ColorableVertex<VertexType> v : CVArray)
{
if (v.color>0) continue;
v.color = 1;
queue.offer(v);
while (queue.size() != 0) {
cv = queue.poll();
for (ColorableVertex<VertexType> next : CVArray) {
if (graph.isEdge(cv.vm, next.vm))
{
if(next.color == 0)
{
next.color = 3 - cv.color;
queue.offer(next);
}
else if(cv.color == next.color)
return false;
}
}
}
}
return true;
} |
e4244eda-cb93-4728-9cc8-ba09eb36621a | 0 | @Test
public void eventBusNotNull()
{
assertNotNull( eventBus );
} |
bedd0848-7ccf-4470-95a1-a4a61ff6426d | 3 | public void open() {
JFileChooser FCdialog = new JFileChooser();
int opt = FCdialog.showOpenDialog(this);
if(opt == JFileChooser.APPROVE_OPTION){
this.textPane.setText("");
try {
this.console.setText("<html> Opening file: "+ FCdialog.getSelectedFile().getName());
Scanner scan = new Scanner(new FileReader(FCdialog.getSelectedFile().getPath()));
while (scan.hasNext()) {
//this.textPane.setFont(new Font(type, opt, opt));
this.textArea.insertString(textArea.getLength(), scan.nextLine() + "\n", defaultStyle);
}
scan.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
String[] name = FCdialog.getSelectedFile().getName().split("\\.");
this.type = name[name.length-1];
this.saved = true;
this._compiler.compile_text(this.textPane.getText(), this.type);
this.console.setText(this.console.getText() + "</html>");
/*if (this.type != null)
pp();*/
}
} |
ec3853f5-8840-4cf8-9c95-a43c97f36391 | 4 | private static Enumeration getResources(final ClassLoader loader,
final String name)
{
PrivilegedAction action =
new PrivilegedAction() {
public Object run() {
try {
if (loader != null) {
return loader.getResources(name);
} else {
return ClassLoader.getSystemResources(name);
}
} catch(IOException e) {
if (isDiagnosticsEnabled()) {
logDiagnostic(
"Exception while trying to find configuration file "
+ name + ":" + e.getMessage());
}
return null;
} catch(NoSuchMethodError e) {
// we must be running on a 1.1 JVM which doesn't support
// ClassLoader.getSystemResources; just return null in
// this case.
return null;
}
}
};
Object result = AccessController.doPrivileged(action);
return (Enumeration) result;
} |
1e1747f2-d43e-449b-94fc-75e320dac0c8 | 6 | public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (taskId >= 0) {
return true;
}
// Begin hitting the server with glorious data
taskId = plugin.getServer().getScheduler()
.scheduleAsyncRepeatingTask(plugin, new Runnable() {
private boolean firstPost = true;
@Override
public void run() {
try {
// This has to be synchronized or it can collide
// with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the
// server owner decided to opt-out
if (isOptOut() && taskId > 0) {
plugin.getServer().getScheduler()
.cancelTask(taskId);
taskId = -1;
// Tell all plotters to stop gathering
// information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it
// is the first time we are posting,
// it is not a interval ping, so it evaluates to
// FALSE
// Each time thereafter it will evaluate to
// TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + e.getMessage());
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} |
5f73ccfa-0076-4871-8f1c-3cb69f5ac695 | 9 | private Statement Statement(ProcedureBuilder pb) throws Exception {
Statement retval = null;
switch (this.Current_Token) {
case TOK_VAR_STRING:
case TOK_VAR_NUMBER:
case TOK_VAR_BOOL:
retval = ParseVariableDeclStatement(pb);
GetNext();
return retval;
case TOK_PRINT:
retval = ParsePrintStatement(pb);
GetNext();
break;
case TOK_PRINTLN:
retval = ParsePrintLNStatement(pb);
GetNext();
break;
case TOK_UNQUOTED_STRING:
retval = ParseAssignmentStatement(pb);
GetNext();
return retval;
case TOK_IF:
retval = ParseIfStatement(pb);
GetNext();
return retval;
case TOK_WHILE:
retval = ParseWhileStatement(pb);
GetNext();
return retval;
case TOK_RETURN:
retval = ParseReturnStatement(pb);
GetNext();
return retval;
default:
throw new Exception("Invalid statement");
}
return retval;
} |
cc1e778f-b3b8-43ac-9381-7f635e13f102 | 2 | public boolean validMove(int position, int player){
int[] field = getGameField();
if(field[position] == 0 && this.getTurn() == player){return true;}
else {return false;}
} |
fd62c9df-d7b2-4dc5-85ff-872e9e149d8b | 7 | private SingleTypeFactory(Object typeAdapter, TypeToken<?> exactType, boolean matchRawType,
Class<?> hierarchyType) {
serializer = typeAdapter instanceof JsonSerializer
? (JsonSerializer<?>) typeAdapter
: null;
deserializer = typeAdapter instanceof JsonDeserializer
? (JsonDeserializer<?>) typeAdapter
: null;
$Gson$Preconditions.checkArgument(serializer != null || deserializer != null);
this.exactType = exactType;
this.matchRawType = matchRawType;
this.hierarchyType = hierarchyType;
} |
5b7011b2-e17e-46f0-8bdc-68d27b60f18e | 7 | @Test
public void testImpossibleMove() {
try {
game = RulesParser.parse("./rules/Chess.xml");
Scanner sc = new Scanner(new File("./test/impossibleMoveBoard.txt"));
//
int xSize = 8;
int ySize = 8;
//
int [][] newField = new int[xSize][ySize];
for (int y = ySize - 1; y > -1; --y) {
for (int x = 0; x < xSize; ++x) {
newField[x][y] = sc.nextInt();
}
}
//
int [][] playersId = new int[xSize][ySize];
for (int y = ySize - 1; y > -1; --y) {
for (int x = 0; x < xSize; ++x) {
playersId[x][y] = sc.nextInt();
}
}
//
int [][] specialMovesId = new int[xSize][ySize];
for (int y = ySize - 1; y > -1; --y) {
for (int x = 0; x < xSize; ++x) {
specialMovesId[x][y] = sc.nextInt();
}
}
int ownTurn = sc.nextInt();
sc.close();
game.forcedMove(newField, playersId, specialMovesId, ownTurn);
} catch(Exception e) {
System.out.print("File not found");
}
boolean expected = false;
//Bishop
boolean result = game.move(new Position(4, 2), new Position(2, 0));
assertEquals("Bishop have captured own Pawn", expected, result);
result = game.move(new Position(4, 2), new Position(6, 1));
assertEquals("Bishops`s move is incorrect", expected, result);
result = game.move(new Position(4, 2), new Position(7, -1));
assertEquals("Bishop have moved out of board", expected, result);
//Knight
result = game.move(new Position(3, 2), new Position(2, 0));
assertEquals("Knight have captured own Pawn", expected, result);
result = game.move(new Position(3, 2), new Position(4, 0));
assertEquals("Knight have captured own Rock", expected, result);
result = game.move(new Position(6, 1), new Position(7, -1));
assertEquals("Knight have moved out of board", expected, result);
//Rock
result = game.move(new Position(4, 0), new Position(4, 2));
assertEquals("Rock have captured own Bishop", expected, result);
result = game.move(new Position(4, 0), new Position(4, 4));
assertEquals("Rock`s move is incorrect", expected, result);
//Pawn
result = game.move(new Position(2, 0), new Position(2, 1));
assertEquals("Pawns`s move is incorrect", expected, result);
result = game.move(new Position(2, 0), new Position(2, 2));
assertEquals("Pawns`s move is incorrect", expected, result);
result = game.move(new Position(2, 0), new Position(2, -1));
assertEquals("Pawn have moved out of board", expected, result);
} |
e0f2d7f3-969a-4476-a13a-3ebff5f95414 | 7 | public void printPercentages() {
// -- Percentages --
System.out.println(" == Percentages for individual elements ==");
System.out.println();
// Codon percentages
System.out.println(" -- Percentages for each codon composition --");
System.out.println("| - | -AA | -AC | -AG | -AT | -CA | -CC | -CG | -CT | -GA | -GC | -GG | -GT | -TA | -TC | -TG | -TT |");
System.out.print("| A |");
for (int i = 0; i < 16; i ++) {
System.out.print(String.format(" %5.1f |", percentageCodons[i])); }
System.out.println();
System.out.print("| C |");
for (int i = 16; i < 32; i ++) {
System.out.print(String.format(" %5.1f |", percentageCodons[i])); }
System.out.println();
System.out.print("| G |");
for (int i = 32; i < 48; i ++) {
System.out.print(String.format(" %5.1f |", percentageCodons[i])); }
System.out.println();
System.out.print("| T |");
for (int i = 48; i < 64; i ++) {
System.out.print(String.format(" %5.1f |", percentageCodons[i])); }
System.out.println();
System.out.println();
// Amino Acid Percentages
System.out.println(" -- Percentages for each amino acid --");
System.out.print("| Lys | Asp | Thr | Arg | Ser | Iso | Met | Glu |\n|");
for (int i = 0; i < 8; i ++) {
System.out.print(String.format(" %5.1f |", percentageAAs[i])); }
System.out.println();
System.out.print("| His | Pro | Leu | G'ate | A'ate | Ala | Gly | Val |\n|");
for (int i = 8; i < 16; i ++) {
System.out.print(String.format(" %5.1f |", percentageAAs[i])); }
System.out.println();
System.out.print("| och | Tyr | amb | opa | Cys | Try | Phe |\n|");
for (int i = 16; i < 23; i ++) {
System.out.print(String.format(" %5.1f |", percentageAAs[i])); }
System.out.println();
System.out.println();
// Class Percentages
System.out.println(" -- Percentages for each Class --");
System.out.println("| Aliphatic | Hydroxyl | Cyclic | Aromatic | Basic | Acidic | stop codon |");
System.out.print(String.format("| %5.1f |", percentageClasses[0]));
System.out.print(String.format(" %5.1f |", percentageClasses[1]));
System.out.print(String.format(" %5.1f |", percentageClasses[2]));
System.out.print(String.format(" %5.1f |", percentageClasses[3]));
System.out.print(String.format(" %5.1f |", percentageClasses[4]));
System.out.print(String.format(" %5.1f |", + percentageClasses[5]));
System.out.println(String.format(" %5.1f |", + percentageClasses[6]));
System.out.println();
System.out.println();
// Polarity Percentages
System.out.println(" -- Percentages for each Polarity --");
System.out.println("| Non-polar | Polar | Basic | Acidic | stop codon |");
System.out.print(String.format("| %5.1f |", percentagePolarities[0]));
System.out.print(String.format(" %5.1f |", percentagePolarities[1]));
System.out.print(String.format(" %5.1f |", percentagePolarities[2]));
System.out.print(String.format(" %5.1f |", percentagePolarities[3]));
System.out.println(String.format(" %5.1f |", percentagePolarities[4]));
System.out.println();
System.out.println();
// -- Repeats/Runs --
System.out.println(" == Percentage runs of elements ==");
System.out.println();
// Nucleotide repeat run
System.out.println(" -- Percentage runs of repeat nucelotides --");
runsPrint(percentageNucRuns);
// Nucleotide forward run
System.out.println(" -- Percentage runs of increasing value nucelotides --");
runsPrint(percentageForRuns);
// Nucleotide reverse run
System.out.println(" -- Percentage runs of reversing value nucelotides --");
runsPrint(percentageBackRuns);
// Codon run
System.out.println(" -- Percentage runs of repeat codons --");
runsPrint(percentageCodonRuns);
// Amino acid run
System.out.println(" -- Percentage runs of repeat amino acids --");
runsPrint(percentageAARuns);
// Class run
System.out.println(" -- Percentage runs of repeat classes --");
runsPrint(percentageClassRuns);
// Polarity run
System.out.println(" -- Percentage runs of repeat polarities --");
runsPrint(percentagePolarityRuns);
System.out.println();
System.out.println();
System.out.println();
} // Method - PrintPercentages |
5fc781f2-c4c7-47e0-b99f-694f74c9f696 | 3 | public void sendGlobalMessage (String sender, String message) {
for (Map.Entry<String, Socket> user : activeSockets.entrySet()) {
if (user.getKey() != sender) {
Socket socket = user.getValue();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("*** " + sender + " " + message);
} catch (IOException e) {
}
}
}
} |
1c95cd6b-9c00-46ec-991e-364fd84f4a42 | 8 | private static void writeResourceToFile(
String resourceName, File file) throws IOException
{
if (file == null)
{
throw new NullPointerException("Target file may not be null");
}
if (file.exists())
{
throw new IllegalArgumentException(
"Target file already exists: "+file);
}
InputStream inputStream =
LibUtils.class.getResourceAsStream(resourceName);
if (inputStream == null)
{
throw new IOException(
"No resource found with name '"+resourceName+"'");
}
OutputStream outputStream = null;
try
{
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[32768];
while (true)
{
int read = inputStream.read(buffer);
if (read < 0)
{
break;
}
outputStream.write(buffer, 0, read);
}
outputStream.flush();
}
finally
{
if (outputStream != null)
{
try
{
outputStream.close();
}
catch (IOException e)
{
logger.log(Level.SEVERE, e.getMessage(), e);
}
}
try
{
inputStream.close();
}
catch (IOException e)
{
logger.log(Level.SEVERE, e.getMessage(), e);
}
}
} |
ed72cb40-2cc2-47dc-8a80-b29782faa7ad | 4 | public static void Test()
{
int option=0;
Scanner Input = new Scanner (System.in);
while(option != 3)
{
System.out.println("Fight the Kobold?");
System.out.println("1) Yes");
System.out.println("2) Save Game");
System.out.println("3) exit");
option = Input.nextInt();
if (option == 1)
{
//fight code
}
if (option == 2)
{
FileOperations.Save(player);
}
if (option == 3)
{
System.out.println("END GAME");
System.exit(1);
}
}
} |
e40fe7b3-2255-4c3c-a7b5-7eba094b7c7f | 9 | public String generateQueryString() {
QueryString qs = new QueryString("page", Integer.toString(this.getPage()));
qs.add("limit",Integer.toString(this.getLimit()));
if (this.getKeyword() != null) qs.add("keyword", this.getKeyword());
if (this.getCreatedAtMin() != null) qs.add("created_at_min", DateMethods.toString(this.getCreatedAtMin()));
if (this.getCreatedAtMax() != null) qs.add("created_at_max", DateMethods.toString(this.getCreatedAtMax()));
if (this.getLang() != null)qs.add("lang", this.getLang());
if (this.getSlugs() != null) qs.add("slug",this.getSlugs());
if (this.getOrigin() != null) qs.add("origin", this.getOrigin());
if (this.getDestinations() != null) qs.add("destination",this.getDestinations());
if (this.getTags() != null) qs.add("tag",this.getTags());
if (this.getFields() != null) qs.add("fields",this.getFields());
//globalJSON.put("tracking", trackingJSON);
return qs.getQuery();
} |
f4ba5e2a-7eeb-4d8d-a23e-62139479e778 | 3 | @Override
public void actionPerformed(ActionEvent e) {
JTable productsTable = App.getInst().getView().getProductsTable();
JTable categoriesTable = App.getInst().getView().getCategoriesTable();
JComboBox<String> cmb = App.getInst().getView().getCountComboBox();
count = Integer.parseInt((String) cmb.getSelectedItem());
Integer left = Integer.parseInt(productsTable.getValueAt(productsTable.getSelectedRow(), 1).toString());
count = count>left?left:count;
count = count<0?0:count;
String eID = App.getInst().getView().getSellerComboBox().getSelectedItem().toString();
String employeeID = eID.substring(0, eID.indexOf(" "));
String cID = App.getInst().getView().getCustomerComboBox().getSelectedItem().toString();
String customerID = cID.substring(0, cID.indexOf(" "));
DateModel<?> jdMod = App.getInst().getView().getJdp().getModel();
Map<String, String> map = new HashMap<String,String>();
map.put(":categoryName", categoryName);
map.put(":productCount", count.toString());
map.put(":productName", productName);
map.put(":customerID", customerID);
map.put(":employeeID", employeeID);
map.put(":dateTime", String.valueOf(jdMod.getYear()+"-"+(jdMod.getMonth()+1)+"-"+jdMod.getDay()));
App.getInst().getExecuter().execQuery(QueryCluster.replaceAll(QueryCluster.PRODUCTS_DELETION, map),true);
//table updates
productsTable.getSelectionModel().clearSelection();
Object[][] data = App.getInst().getExecuter().getQueryResultAsObjectArray(replace(QueryCluster.PRODUCTS_LEFT, ":categoryInsert", replace(QueryCluster.INSERTION_PROD_BY_CAT_NAME, ":categoryName", categoryName)));
productsTable.setModel(new CustomTableModel(data,new String[] {"Наименование", "Остаток"}));
categoriesTable.getSelectionModel().clearSelection();
Object[][] categoryData = App.getInst().getExecuter().getQueryResultAsObjectArray(QueryCluster.CATEGORIES_LEFT);
categoriesTable.setModel(new CustomTableModel(categoryData,new String[] {"Наименование", "Остаток"}));
categoryName = null;
productName = null;
((JButton)e.getSource()).setEnabled(false);
} |
01d99733-de3c-4516-a66c-62cd892f64dd | 4 | private boolean checkUsage(AbstractCommand<P> command, String[] parameters) {
String[] commandParameters = command.getParameters();
int[] limits = new int[2];
for (String parameter : commandParameters) {
limits[1]++;
if (!parameter.matches("\\[.*\\]")) {
limits[0]++;
}
}
return parameters.length >= limits[0] && (command.hasInfiniteParameters() ? true : parameters.length <= limits[1]);
} |
10bdd8dc-15a5-4553-a90c-673e8962182b | 7 | public void create(CmProfesionales cmProfesionales) {
if (cmProfesionales.getPypAdmControlProfesionalesList() == null) {
cmProfesionales.setPypAdmControlProfesionalesList(new ArrayList<PypAdmControlProfesionales>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
ConfigDecripcionLogin idDescripcionLogin = cmProfesionales.getIdDescripcionLogin();
if (idDescripcionLogin != null) {
idDescripcionLogin = em.getReference(idDescripcionLogin.getClass(), idDescripcionLogin.getId());
cmProfesionales.setIdDescripcionLogin(idDescripcionLogin);
}
List<PypAdmControlProfesionales> attachedPypAdmControlProfesionalesList = new ArrayList<PypAdmControlProfesionales>();
for (PypAdmControlProfesionales pypAdmControlProfesionalesListPypAdmControlProfesionalesToAttach : cmProfesionales.getPypAdmControlProfesionalesList()) {
pypAdmControlProfesionalesListPypAdmControlProfesionalesToAttach = em.getReference(pypAdmControlProfesionalesListPypAdmControlProfesionalesToAttach.getClass(), pypAdmControlProfesionalesListPypAdmControlProfesionalesToAttach.getId());
attachedPypAdmControlProfesionalesList.add(pypAdmControlProfesionalesListPypAdmControlProfesionalesToAttach);
}
cmProfesionales.setPypAdmControlProfesionalesList(attachedPypAdmControlProfesionalesList);
em.persist(cmProfesionales);
if (idDescripcionLogin != null) {
idDescripcionLogin.getCmProfesionalesList().add(cmProfesionales);
idDescripcionLogin = em.merge(idDescripcionLogin);
}
for (PypAdmControlProfesionales pypAdmControlProfesionalesListPypAdmControlProfesionales : cmProfesionales.getPypAdmControlProfesionalesList()) {
CmProfesionales oldIdProfesionalOfPypAdmControlProfesionalesListPypAdmControlProfesionales = pypAdmControlProfesionalesListPypAdmControlProfesionales.getIdProfesional();
pypAdmControlProfesionalesListPypAdmControlProfesionales.setIdProfesional(cmProfesionales);
pypAdmControlProfesionalesListPypAdmControlProfesionales = em.merge(pypAdmControlProfesionalesListPypAdmControlProfesionales);
if (oldIdProfesionalOfPypAdmControlProfesionalesListPypAdmControlProfesionales != null) {
oldIdProfesionalOfPypAdmControlProfesionalesListPypAdmControlProfesionales.getPypAdmControlProfesionalesList().remove(pypAdmControlProfesionalesListPypAdmControlProfesionales);
oldIdProfesionalOfPypAdmControlProfesionalesListPypAdmControlProfesionales = em.merge(oldIdProfesionalOfPypAdmControlProfesionalesListPypAdmControlProfesionales);
}
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
} |
6e210bbc-6b2a-4a93-845d-bbd689c8d574 | 4 | public void readScores() {
Person second;
Person first;
Person temp;
if (people.size() > 0) {
for (int i = people.size() - 1; i > 0; i--) {
first = people.get(i);
second = people.get(i - 1);
if (first.getScore() > second.getScore()) {
temp = first;
people.set(i, second);
people.set(i - 1, temp);
}
}
}
if (people.size() > 6) {
// System.out.println("Entered");
people.remove(people.size() - 1);
}
} |
de36c3f4-3496-487b-9894-ccf8c5c8fd27 | 4 | private void sessionDelete(String cookie_vals){
String[] sTemp = cookie_vals.split("\\^");
String sID = sTemp[0];
int ver = Integer.parseInt(sTemp[1]);
String ipP = sTemp[2].split(":")[0];
int portP = Integer.parseInt(sTemp[2].split(":")[1]);
String ipB = sTemp[3].split(":")[0];
int portB = Integer.parseInt(sTemp[3].split(":")[1]);
if(!ipP.equals(IP_NULL)){
try {
RPCClient.sessionDelete(sID, ver, new Server(InetAddress.getByName(ipP), portP));
} catch (UnknownHostException e) {
System.out.println("Primary Server delete failed");
e.printStackTrace();
}
};
if(!ipP.equals(IP_NULL)){
try {
RPCClient.sessionDelete(sID, ver, new Server(InetAddress.getByName(ipP), portP));
} catch (UnknownHostException e) {
System.out.println("Backup Server delete failed");
e.printStackTrace();
}
};
} |
f483ee42-3ec9-4b0b-8c38-69ebcb87798d | 8 | final public Expression Expression(int str_type) throws ParseException {
final Variable v;
final String s;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case VARIABLE:
v = Variable();
{if (true) return new VariableExpression(v);}
break;
case STRING_END:
case STRING:
case IDENTIFIER:
case CHARACTER:
s = String(str_type);
{if (true) return Expression.createExpression( s );}
break;
default:
jj_la1[44] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
} |
57f17693-f200-4f37-b44d-b2dc954a02e9 | 9 | public static void main(String[] args)
{
File configPath = new File("AztecConfig.conf");
if ( args.length > 0 )
configPath = new File(args[0]);
if ( !configPath.exists() || !configPath.isFile() || !configPath.canRead() )
{
System.out.println("Unable to open config file: "+configPath.getAbsolutePath());
System.exit(0);
}
try {
Config.init(configPath.getAbsolutePath());
} catch (IOException e1) {
System.out.println("Reading of config file at "+configPath.getAbsolutePath()+" failed!");
e1.printStackTrace();
System.exit(0);
}
String globalDocroot = Config.getString("default", "docroot", "/var/www");
Iterator<String> domains = Config.getDomainSet().iterator();
while ( domains.hasNext() )
{
String thisDomain = (String) domains.next();
if ( !thisDomain.equals("global") && !thisDomain.equals("default") )
{
registerPlugin(new VirtualHost(thisDomain, Config.getString(thisDomain, "docroot", globalDocroot)));
}
}
registerPlugin(new VirtualHost(Config.getString("default", "docroot", "/var/www")));
try { start(); }
catch (IOException e)
{
System.out.println("Aztec failed to start!");
}
} |
87a3e719-1797-4c4b-92ba-2d8e8fac7125 | 0 | public byte[] getQ() {
return q;
} |
11938d13-09c0-4ae6-b258-cadfa2293c0e | 4 | public void act()
{
// spawn ships random
if(Greenfoot.getRandomNumber(10000) < 10) {
addObject(new ship1(), Greenfoot.getRandomNumber(900),10);
}
if(Greenfoot.getRandomNumber(10000) < 10) {
addObject(new ship2(), Greenfoot.getRandomNumber(900),10);
}
if(Greenfoot.getRandomNumber(10000) < 10) {
addObject(new ship3(), Greenfoot.getRandomNumber(900),10);
}
if(Greenfoot.getRandomNumber(10000) < 10) {
addObject(new ship4(), Greenfoot.getRandomNumber(900),10);
}
} |
37524da0-196e-48ca-b60d-74c47cd002a8 | 7 | @Before
public void setUp() throws SQLException {
// Setup a simple connection pool of size 10
source = new PGPoolingDataSource();
source.setDataSourceName("Mock DB Source");
source.setServerName("localhost:5432"); // Test server
source.setDatabaseName("MockDB"); // Test DB
source.setUser("user25"); // Group user
source.setPassword("dbaccess25"); // OMG! It's a password in the code!!
// It's ok we are protected files
source.setMaxConnections(10); // Try a maximum of 10 pooled connections
Connection conn = null;
try {
conn = source.getConnection();
conn.setAutoCommit(false);
// Tear down what was there before
Destroy d = new Destroy();
d.execute(true, true, true, conn);
// Recreate the schema
Create c = new Create();
c.execute(true, true, true, conn);
conn.commit();
} catch (SQLException ex) {
fail("Got an SQL exception while tearing down the test.");
} finally {
if (conn != null)
conn.close();
}
try {
stuffDatabase(5, 2);
conn = source.getConnection();
conn.setAutoCommit(false);
ArrayList<String> evenQueues = new ArrayList<String>();
ArrayList<String> oddQueues = new ArrayList<String>();
for (int i = 1; i < 6; i++) {
if (i % 2 == 0)
evenQueues.add("Queue#" + i);
else
oddQueues.add("Queue#" + i);
}
CreateMessage cm = new CreateMessage();
cm.execute(1, "Queue#1", (short) 0, (short) 10, "Test msg 1", conn);
cm.execute(1, evenQueues, (short) 0, (short) 9, "Test msg 2", conn);
cm.execute(1, oddQueues, (short) 0, (short) 8, "Test msg 3", conn);
cm.execute(2, "Queue#5", (short) 1, (short) 7, "Test msg 4", conn);
cm.execute(2, evenQueues, (short) 1, (short) 6, "Test msg 5", conn);
cm.execute(2, oddQueues, (short) 1, (short) 5, "Test msg 6", conn);
cm.execute(1, "Client#2", "Queue#1", (short) 0, (short) 4,
"Test msg 7", conn);
cm.execute(2, "Client#1", oddQueues, (short) 1, (short) 3,
"Test msg 8", conn);
conn.commit();
} catch (Exception ex) {
if (conn != null)
conn.rollback();
fail("Got an exception during the test");
} finally {
if (conn != null)
conn.close();
}
} |
eeffef32-a576-4992-b642-1fc3ea968c04 | 3 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((location == null) ? 0 : location.hashCode());
result = prime * result + ((recipes == null) ? 0 : recipes.hashCode());
result = prime * result + toolID;
result = prime * result + ((toolName == null) ? 0 : toolName.hashCode());
return result;
} |
50222f3e-b7f9-4141-ab03-788de2ac900c | 6 | public void searchByID (LYNXsys system, String query, int page) { // search student by ID
displayedSearchResults.removeAll(displayedSearchResults);
for (int i = 0; i < system.getUsers().size(); i ++) { // loop through arraylist of students
if (system.getUsers().get(i).getID().equalsIgnoreCase(query)){ // check if book title matches search query
displayedSearchResults.add(new StudentSearchResult (system.getUsers().get(i), system.getUsers().get(i).getID() + ": " + system.getUsers().get(i).getLastName() + ", " + system.getUsers().get(i).getFirstName() + ". "));
}
}
for(int i = ((page-1)*13); i < page*13; i++){
if (i < displayedSearchResults.size()) {
displayedSearchResults.get(i).getDisplayText().setEditable(false);
displayedSearchResults.get(i).getDisplayText().setBackground(Color.pink);
displayedSearchResults.get(i).getDisplayText().setBounds(500,270 + (21*(i-(13*(page-1)))),400,20);
displayedSearchResults.get(i).getUserButton().setBounds(460,270 + (21*(i-(13*(page-1)))),32,20);
add(displayedSearchResults.get(i).getDisplayText(),0);
add(displayedSearchResults.get(i).getUserButton(),0);
}
}
for (int i = 12; i < displayedSearchResults.size(); i = i + 13) {
if (displayedSearchResults.size() > i) {
pages.add(new JButton());
pages.get(pages.size() - 1).setBounds(620 + (45*(((i-12)/13)+1)),547,43,19);
add(pages.get((((i-12)/13)+1)),0);
pages.get((((i-12)/13)+1)).addActionListener(getAction());
}
}
lastSearch = 2;
repaint(460,270,510,500);
} |
686d750d-6349-405d-9c5b-2546c85285c1 | 9 | Space[] won() {
int n = numToWin - 1;
if (lastSpaceMoved == null)
return null;
int[] pos = lastSpaceMoved.getPos();
for (int i = 0, rowInd = pos[0]; i <= n; i++, rowInd = pos[0] - i)
for (int j = 0, colInd = pos[1]; j <= n; j++, colInd = pos[1] - j) {
boolean outOfBounds = rowInd < 0 || colInd < 0
|| rowInd + n >= rows || colInd + n >= cols;
if (outOfBounds)
continue;
ExpBoard sub = new ExpBoard(this, rowInd, colInd, new int[] {
i, j });
Space[] winningSet = sub.subWon();
if (winningSet!=null){
for(Space sp : winningSet)
sp.setPos(sp.getRow()+rowInd,sp.getCol()+colInd);
return winningSet;
}
}
return null;
} |
1c2018ee-af9f-4ddf-8e79-bd0b01271942 | 9 | public static ButtonImage getTypeFromInt(int index) {
switch (index) {
case 0:
return EMPTY;
case 1:
return ONE;
case 2:
return TWO;
case 3:
return TREE;
case 4:
return FOUR;
case 5:
return FIVE;
case 6:
return SIX;
case 7:
return SEVEN;
case 8:
return EIGHT;
default:
return EMPTY;
}
} |
514477a5-9faf-48f2-9a41-aab375326c49 | 7 | private static void readFromFile(String filename){
BufferedReader br = null;
String line;
if(filename == null){
System.out.println("No file path specified!");
return;
}
File AddFile = new File(filename);
if(!AddFile.exists())
{
System.out.println("File " + filename + " not found!");
return;
}
try
{
FileInputStream file = new FileInputStream(new File(filename));
InputStreamReader InputReader = new InputStreamReader(file);
br = new BufferedReader(InputReader);
while((line = br.readLine()) != null)
{
String[] tokens = line.split("\\s+");
int length = tokens.length;
int maxLength = 0;
String longestWord = "";
for(int i =0; i<length; i++){
if(tokens[i].length()>maxLength){
maxLength = tokens[i].length();
longestWord = tokens[i];
}
}
System.out.println(longestWord);
}
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
7807b5bc-a332-4764-8ef1-50f70588dda1 | 9 | @Override
public void update(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(Color.gray);
g2.fillRect(0,0,getWidth(),getHeight());
drawCommandCircle(g2, new PointF(.5f, .5f), 2.5d, Color.white);
// Show current Calibration Circle
if ((systemCalibrationIndex != null) && (systemCalibrationMap != null)) {
g2.setColor(Color.black);
g2.fillRect(0,0,getWidth(),getHeight());
CalibrationValue cv = systemCalibrationMap.get(systemCalibrationIndex);
if (cv != null) {
drawCommandCircle(g2, systemCalibrationMap.get(systemCalibrationIndex).display, 1d, Color.magenta);
}
}
else if ((toolkitCalibrationIndex != null) && (tangibles != null)) {
Tangible tangible = tangibles.get(toolkitCalibrationIndex);
if (tangible != null) {
if (lastDelay == TOOLKIT_CALIBRATION_DELAY_SETUP) {
drawCommandCircle(g2, new PointF(.5f, .5f), 2.5d, Color.cyan);
drawTangibleAtCenter(g2, tangible);
drawCalibrateInstructions(g2, tangible, .15f);
} else if (lastDelay == TOOLKIT_CALIBRATION_DELAY_READ) {
drawCommandCircle(g2, new PointF(.5f, .5f), 2.5d, Color.cyan);
drawCalibrateInstructions(g2, tangible, .15f);
} else if (lastDelay == TOOLKIT_CALIBRATION_DELAY_NOTIFY) {
drawCommandCircle(g2, new PointF(.5f, .5f), 2.5d, Color.yellow);
drawCalibrateSuccess(g2, tangible, .15f);
}
}
}
} |
9d9e6987-0439-476e-99e9-bfc9e4b15cb6 | 0 | public void setPostNote(String postNote) {
this.postNote = postNote;
} |
56c1bbaf-a261-48da-bec8-e368654c8139 | 1 | public void mouseRelease(int x, int y){
if(movingInputTime){
movingInputTime = false;
ArrayList<Integer> times = loop.getTimes();
loop.setNewTime(node.getIndex(), (int) node.getTime());
//times.set(node.getIndex(), (int) node.getTime());
System.out.println(times.size());
}
} |
d0a2dfb0-2180-471f-90b6-811e697f0dd4 | 2 | private void mkCfg () {
for (String qp : qps) {
try {
File h265Cfg = new File("./Cfg/h265/"+seqName+qp+".cfg");
File psvdCfg = new File("./Cfg/psvd/"+seqName+"Residue"+qp+".cfg");
DirMaker.createFile(h265Cfg);
DirMaker.createFile(psvdCfg);
writeParaToCfg(h265Cfg, this.srcSeqPath, "Out/h265/", seqName, frameRate, frameSkip, width, height, String.valueOf(Integer.parseInt(totalFrames) - Integer.parseInt(gopSize)), qp);
writeParaToCfg(psvdCfg, "common/yuv/", "Out/psvd/", seqName+"Residue", frameRate, "0", width, height, String.valueOf(Integer.parseInt(totalFrames) - Integer.parseInt(gopSize)), qp);
}
catch (IOException e) {
System.out.println("Can't create cfg files: "+e.getMessage());
}
}
} |
38a50ffa-9604-4323-87de-6817d785c9cb | 8 | private void completeCursorMessage() {
Vector<OSCMessage> messageList = new Vector<OSCMessage>();
OSCMessage frameMessage = new OSCMessage("/tuio/2Dcur");
frameMessage.addArgument("fseq");
frameMessage.addArgument(-1);
OSCMessage aliveMessage = new OSCMessage("/tuio/2Dcur");
aliveMessage.addArgument("alive");
Enumeration<Integer> cursorList = manager.cursorList.keys();
while (cursorList.hasMoreElements()) {
Integer s_id = cursorList.nextElement();
aliveMessage.addArgument(s_id);
Finger cursor = manager.cursorList.get(s_id);
Point point = cursor.getPosition();
float xpos = point.x/(float)window_width;
if (manager.invertx) xpos = 1 - xpos;
float ypos = point.y/(float)window_height;
if (manager.inverty) ypos = 1 - ypos;
OSCMessage setMessage = new OSCMessage("/tuio/2Dcur");
setMessage.addArgument("set");
setMessage.addArgument(s_id);
setMessage.addArgument(xpos);
setMessage.addArgument(ypos);
setMessage.addArgument(cursor.xspeed);
setMessage.addArgument(cursor.yspeed);
setMessage.addArgument(cursor.maccel);
messageList.addElement(setMessage);
}
int i;
for (i=0;i<(messageList.size()/10);i++) {
OSCBundle oscBundle = new OSCBundle();
oscBundle.addPacket(aliveMessage);
for (int j=0;j<10;j++)
oscBundle.addPacket((OSCPacket)messageList.elementAt(i*10+j));
oscBundle.addPacket(frameMessage);
sendOSC(oscBundle);
}
if ((messageList.size()%10!=0) || (messageList.size()==0)) {
OSCBundle oscBundle = new OSCBundle();
oscBundle.addPacket(aliveMessage);
for (int j=0;j<messageList.size()%10;j++)
oscBundle.addPacket((OSCPacket)messageList.elementAt(i*10+j));
oscBundle.addPacket(frameMessage);
sendOSC(oscBundle);
}
} |
dd051eab-f4bd-49a4-93fa-f93c2ad114b9 | 6 | public void saveGraphAs(Graph graph, Component c) {
this.graph = graph;
JFileChooser fileChooser = new JFileChooser();
if (graph instanceof PetriNet) {
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Danes PetriNet files", "dpn"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("CoBA PetriNet files", "pn2"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("CPN Tools PetriNet files", "cpn"));
} else {
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PrecedenceGraph", "dpg"));
}
int showOpenDialog = fileChooser.showSaveDialog(c);
setSelectedFile(fileChooser.getSelectedFile());
if (selectedFile == null) {
return;
}
if (!selectedFile.exists()) {
setSelectedFile(new File(getSelectedFile().getAbsolutePath()));
try {
getSelectedFile().createNewFile();
} catch (IOException e) {
System.out.print("Chyba pri praci so suborom");
}
}
FileFilter ff = fileChooser.getFileFilter();
if (getSelectedFile() != null) {
getInfoAboutFile(getSelectedFile());
if (showOpenDialog != JFileChooser.APPROVE_OPTION) {
return;
}
checkAndSave(getSelectedFile(), ff);
}
} |
ea4316d0-0019-4670-bccd-71b26d6280f1 | 9 | public int[] search (ASEvaluation ASEval, Instances data)
throws Exception {
double best_merit = -Double.MAX_VALUE;
double temp_merit;
BitSet temp_group, best_group=null;
if (!(ASEval instanceof SubsetEvaluator)) {
throw new Exception(ASEval.getClass().getName()
+ " is not a "
+ "Subset evaluator!");
}
m_SubsetEval = ASEval;
m_Instances = data;
m_numAttribs = m_Instances.numAttributes();
/* if (m_ASEval instanceof AttributeTransformer) {
throw new Exception("Can't use an attribute transformer "
+"with RankSearch");
} */
if (m_ASEval instanceof UnsupervisedAttributeEvaluator ||
m_ASEval instanceof UnsupervisedSubsetEvaluator) {
m_hasClass = false;
/* if (!(m_SubsetEval instanceof UnsupervisedSubsetEvaluator)) {
throw new Exception("Must use an unsupervised subset evaluator.");
} */
}
else {
m_hasClass = true;
m_classIndex = m_Instances.classIndex();
}
if (m_ASEval instanceof AttributeEvaluator) {
// generate the attribute ranking first
Ranker ranker = new Ranker();
m_ASEval.buildEvaluator(m_Instances);
if (m_ASEval instanceof AttributeTransformer) {
// get the transformed data a rebuild the subset evaluator
m_Instances = ((AttributeTransformer)m_ASEval).
transformedData(m_Instances);
((ASEvaluation)m_SubsetEval).buildEvaluator(m_Instances);
}
m_Ranking = ranker.search(m_ASEval, m_Instances);
} else {
GreedyStepwise fs = new GreedyStepwise();
double [][]rankres;
fs.setGenerateRanking(true);
((ASEvaluation)m_ASEval).buildEvaluator(m_Instances);
fs.search(m_ASEval, m_Instances);
rankres = fs.rankedAttributes();
m_Ranking = new int[rankres.length];
for (int i=0;i<rankres.length;i++) {
m_Ranking[i] = (int)rankres[i][0];
}
}
// now evaluate the attribute ranking
for (int i=m_startPoint;i<m_Ranking.length;i+=m_add) {
temp_group = new BitSet(m_numAttribs);
for (int j=0;j<=i;j++) {
temp_group.set(m_Ranking[j]);
}
temp_merit = ((SubsetEvaluator)m_SubsetEval).evaluateSubset(temp_group);
if (temp_merit > best_merit) {
best_merit = temp_merit;;
best_group = temp_group;
}
}
m_bestMerit = best_merit;
return attributeList(best_group);
} |
139f0dad-9bbf-4cfd-a862-1a537d95167d | 4 | @Override
public boolean isVisibleAt(int posX, int posY) {
if((posX/zoom) > originX && (posX/zoom) < (originX + width))
if((posY/zoom) > originY && (posY/zoom) < (originY + height))
return true;
return false;
} |
fc7de137-d50e-4c95-9c4a-66c17d36841e | 7 | private static int subStringForAcharAtAnIndex(String s, String set, List<String> subStrings, char ipChar, int index) {
index = s.indexOf(ipChar, index + 1);
int x = 1;
int l = index - x;
int r = index + x + 1;
while (l >= 0 || r <= s.length()) {
l = l < 0 ? 0 : l;
r = r > s.length() ? s.length() : r;
String subStr = s.substring(l, r);
// System.out.println("ip = " + s + ", Sol = " + subStr);
char[] charArray = set.toCharArray();
boolean containsAll = true;
for (char c : charArray) {
if (!StringUtils.contains(subStr, c)) {
// this substring does not contain all the chars, increase the size of substring
containsAll = false;
break;
}
}
if (containsAll) {
subStr = ltrim(subStr, charArray);
subStr = rtrim(subStr, charArray);
subStrings.add(subStr);
break;
}
x += 1;
l = index - x;
r = index + x + 1;
}
return index;
} |
9cdd86a8-af7e-498b-8f3c-e5ad6e6623cb | 5 | public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) { // important to check when you are done coding
return "";
}
String first = strs[0];
int i = 0;
char tmp;
while (i < first.length()) {
tmp = first.charAt(i);
for (int j = 1; j < strs.length; j++) {
// the first word may longer or shorter,
// if longer, must check the compared ones
// if shorter, done checking
if (i >= strs[j].length() || tmp != strs[j].charAt(i)) {
return first.substring(0, i);
}
}
i++;
}
return first;
} |
51589040-a37c-4680-b412-2296e4a0a3e0 | 0 | public int getValue(int skill)
{
return skillValues[skill];
} |
328117b2-37ae-4ec9-be49-4d7623177d56 | 4 | public void initResources(Display display) {
if (stockImages == null) {
stockImages = new Image[stockImageLocations.length];
for (int i = 0; i < stockImageLocations.length; ++i) {
Image image = createStockImage(display, stockImageLocations[i]);
if (image == null) {
freeResources();
throw new IllegalStateException(
FileViewer.getResourceString("error.CouldNotLoadResources"));
}
stockImages[i] = image;
}
}
if (stockCursors == null) {
stockCursors = new Cursor[] {
null,
display.getSystemCursor(SWT.CURSOR_WAIT)
};
}
iconCache = new Hashtable<Program, Image>();
} |
69b894d1-0a4c-4e02-b327-d999bb05f0e9 | 3 | @Override
public void run(){
byte[] byteTosend = new byte[1*1024];
try {
for (int k = 0; k < 2/*200000*/; k++) {
nioClientMT.publish(null, byteTosend, "#testtag");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} |
3360bfe1-d19d-438a-ab37-aba3f50f154e | 2 | public Map<Integer, InventoryItem> GrabFloors()
{
Map<Integer, InventoryItem> Items = new HashMap<Integer, InventoryItem>();
for(InventoryItem Item : this.Inventory.values())
{
if (Item.GrabBaseItem().Type.contains("s"))
{
Items.put(Item.ID, Item);
}
}
return Items;
} |
1a7a2ce8-8d54-4267-b12f-eb1b3ac06603 | 3 | @Test
public void testChangeInterfaceOfProperty() throws Exception
{
// connect to database
PersistenceManager pm = new PersistenceManager(driver, database, login, password);
// drop all tables
pm.dropTable(Object.class);
// create test objects
OriginalObject one = new OriginalObject();
one.setValue(1);
OriginalObject two = new OriginalObject();
two.setValue(2);
ChangedInheritance three = new ChangedInheritance();
three.setValue(3);
// create external reference for object two
pm.saveObject(two);
ObjectContainerObject coOne = new ObjectContainerObject();
coOne.setFoo(one);
ObjectContainerObject coTwo = new ObjectContainerObject();
coTwo.setFoo(two);
ObjectContainerObject coThree = new ObjectContainerObject();
coThree.setFoo(three);
pm.saveObject(coOne);
pm.saveObject(coTwo);
pm.saveObject(coThree);
// make sure the right number of OriginalObjects were stored
List<OriginalObject> ooList = pm.getObjects(OriginalObject.class, new All());
assertEquals(2, ooList.size());
// make sure the right number of ChangedInheritance objects were stored
List<ChangedInheritance> ciList = pm.getObjects(ChangedInheritance.class, new All());
assertEquals(1, ciList.size());
// make sure the Serializable object was stored
List<Serializable> serList = pm.getObjects(Serializable.class, new All());
assertEquals(1, serList.size());
// make sure the containers are saved
List<ObjectContainerObject> contList = pm.getObjects(ObjectContainerObject.class, new All());
assertEquals(3, contList.size());
assertNotNull(contList.get(0).getFoo());
assertNotNull(contList.get(1).getFoo());
assertNotNull(contList.get(2).getFoo());
pm.close();
// re-connect to database
pm = new PersistenceManager(driver, database, login, password);
// change ContainerObject to ChangedInheritanceContainer
new TestTools(pm.getPersist()).changeName(ObjectContainerObject.class, ChangedInheritanceContainer.class);
pm.close();
// re-connect to database
pm = new PersistenceManager(driver, database, login, password);
// update schema
pm.updateSchema(ChangedInheritanceContainer.class);
pm.close();
// re-connect to database
pm = new PersistenceManager(driver, database, login, password);
// make sure the externally referenced OriginalObject survived intact
ooList = pm.getObjects(OriginalObject.class, new All());
assertEquals(1, ooList.size());
assertEquals(2, ooList.get(0).getValue());
// make sure the ChangedInheritance object survived intact
ciList = pm.getObjects(ChangedInheritance.class, new All());
assertEquals(1, ciList.size());
assertEquals(3, ciList.get(0).getValue());
// make sure all containers survived
List<ChangedInheritanceContainer> containerList = pm.getObjects(ChangedInheritanceContainer.class, new All());
assertEquals(3, containerList.size());
// check for the correct three values
int nullFoundCount = 0;
boolean chngFound = false;
for (ChangedInheritanceContainer cont : containerList)
{
if (cont.getFoo() == null)
{
nullFoundCount++;
} else if (cont.getFoo() instanceof ChangedInheritance)
{
chngFound = true;
assertEquals(3, ((ChangedInheritance) cont.getFoo()).getValue());
} else
{
fail("Unknown foo reference in container object.");
}
}
assertEquals(2, nullFoundCount);
assertTrue(chngFound);
pm.close();
} |
b51c5fa3-8b38-44c8-9925-80adcca91dfc | 6 | @Override
public void execute(Profile profile, String[] args) {
final int RATE = 10;
try {
Twitter twitter = profile.getTwitter();
TwitterBrain brain = profile.getMind();
brain.updateFriends();
logger.info("total friends count: "
+ brain.getFriends().size());
int count = 25;
int countTotal = 25;
if(args.length > 1) {
count = Integer.parseInt(args[1]);
countTotal=count;
}
while(count > 0) {
int less = count > RATE ? RATE : count;
logger.info("go for "+(countTotal-count)+"/"+countTotal+" by "+RATE);
try {
Set<Long> newFriends = findNewFriend(brain, twitter, less);
for (Long nfid : newFriends) {
brain.addFriend(nfid);
}
brain.save();
logger.info("save state");
count-=less;
} catch(Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} |
798cd211-a45e-4745-9fc8-46163b5503c3 | 6 | private void processBranches(FileData coverageData, StringBuilder lcov) {
for (Integer lineNumber: coverageData.getBranchData().keySet()) {
List<BranchData> conditions = coverageData.getBranchData().get(lineNumber);
if (conditions != null) {
for (int j = 0; j < conditions.size(); j++) {
BranchData branch = conditions.get(j);
if (branch != null) {
//False path
String taken = branch.getEvalFalse() > 0 ? ""+branch.getEvalFalse() : "-";
lcov.append(format(branchData, lineNumber, j*2-1, taken));
//True path
taken = branch.getEvalTrue() > 0 ? ""+branch.getEvalTrue() : "-";
lcov.append(format(branchData, lineNumber, j*2, taken));
}
}
}
}
} |
8cc142bd-4b1d-49b0-9043-35c792b3946b | 9 | public static boolean addMail(MailItem mail) {
if (!initialised) return false;
Connection connection = null;
PreparedStatement statement = null;
ResultSet result = null;
try {
connection = DriverManager.getConnection(url, username, password);
statement = connection.prepareStatement(INSERT_MESSAGE_COMMAND, Statement.RETURN_GENERATED_KEYS);
// Columns: message_id, message, time, from
long fromId = getIdForPlayer(mail.getFrom().getPlayer(), connection);
long toId = getIdForPlayer(mail.getTo().getPlayer(), connection);
if (fromId == -1 || toId == -1) return false;
statement.setLong(1, 0); // 0 means auto-increment
statement.setString(2, mail.getMessage());
statement.setLong(3, mail.getTime());
statement.setLong(4, fromId);
statement.executeUpdate();
result = statement.getGeneratedKeys();
if (result.next()) {
mail.setMessageId(result.getLong(1));
statement.close();
statement = connection.prepareStatement(INSERT_MESSAGE_PLAYER_JOIN_COMMAND);
// Columns: message_id, player_id
statement.setLong(1, mail.getMessageId());
statement.setLong(2, toId);
statement.executeUpdate();
statement.close();
statement = connection.prepareStatement(INSERT_MESSAGE_TO_EMAIL_COMMAND);
statement.setLong(1, mail.getMessageId());
statement.executeUpdate();
return true;
} else {
throw new SQLException("Inserting message into database returned an empty ResultSet!");
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
connection = null;
}
if (result != null) {
result.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
873538ce-036e-4cd6-91fb-cb9c81bc54e4 | 0 | public Long getId()
{
return Id;
} |
aff3967a-9512-40a4-8ca6-663141bedec2 | 4 | public void genererTableau(String fonction, ArrayList<Photographe> listeP, ArrayList<Historien> listeH) {
String entete[] = {"ID", "Choisir " + fonction};
Photographe p;
Historien h;
jTable1.setToolTipText("Double clique pour choisir un utilisateur");
switch (fonction) {
case "Photographe":
jTable1.setModel(new DefaultTableModel(entete, listeP.size()) {
public boolean isCellEditable(int row, int column) {
return false;
}
});
for (int i = 0; i < listeP.size(); i++) {
p = listeP.get(i);
jTable1.setValueAt(p.getIdPhotographe(), i, 0);
jTable1.setValueAt(p.getNom(), i, 1);
}
break;
case "Historien":
jTable1.setModel(new DefaultTableModel(entete, listeH.size()) {
public boolean isCellEditable(int row, int column) {
return false;
}
});
for (int i = 0; i < listeP.size(); i++) {
h = listeH.get(i);
jTable1.setValueAt(h.getIdHistorien(), i, 0);
jTable1.setValueAt(h.getNom(), i, 1);
}
break;
default:
System.out.println("RAS");
}
} |
a0cebda1-8158-45c2-bca1-f5271bb27131 | 3 | public void BeginningThisHell(){ //Initialization of Stage objects massive
Judge judge = new Judge();
for (int itanks = 0; itanks < amountTanks; itanks++)
{
tanks[itanks] = new Tank();
for(int i = 0; i < amountStage; i++)
{
stage[i] = new Stage();
judge.MaxSpeedStage(tanks[itanks].GetSpeedMax(),
stage[i].getPassability());
}
for(int i = 0; i < amountFL; i++)
{ // -//- FL obj mass
FL[i] = new FiringLine();
}
}
} |
692193c7-b245-42a5-bba1-503728a57283 | 8 | public void viewBoard(Board board) {
int x, y;
String row;
Disc disc;
int[] rowCount = {1,2,3,4,5,6,7,8};
int[] contents = board.getContents();
System.out.println(" A B C D E F G H");
for (y=1; y < BOARD_SIZE+1; y++) {
row = "";
for (x=0; x < BOARD_SIZE+1; x++) {
disc = new Disc(x, y, 0);
switch (contents[disc.getPos()]) {
case WALL:
if (x == 0) {
row += ("" + y);
}
break;
case BLACK: row += "x "; break;
case WHITE: row += "o "; break;
case EMPTY: row += " "; break;
}
}
System.out.println(row);
}
row = "x: " + board.getCountDiscs(BLACK) + " ";
row += "o: " + board.getCountDiscs(WHITE) + " ";
row += "EMPTY: " + board.getCountDiscs(EMPTY);
System.out.println(row);
row = "turn=" + (board.getTurn() + 1) + " ";
if (board.getCurrentColor() == BLACK) {
row += "Black(x)";
} else {
row += "White(o)";
}
System.out.println(row);
} |
a39bd0cd-4f99-41f0-bfde-25554d1b3b00 | 0 | public double getFitness() {
return fitness;
} |
8af4b985-19f4-4050-84c4-b09ce374047c | 6 | @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"})
public void testValueCollectionToArray() {
int element_count = 20;
int[] keys = new int[element_count];
String[] vals = new String[element_count];
TIntObjectMap<String> map = new TIntObjectHashMap<String>();
for ( int i = 0; i < element_count; i++ ) {
keys[i] = i + 1;
vals[i] = Integer.toString( i + 1 );
map.put( keys[i], vals[i] );
}
assertEquals( element_count, map.size() );
Collection<String> collection = map.valueCollection();
for ( int i = 0; i < collection.size(); i++ ) {
assertTrue( collection.contains( vals[i] ) );
}
assertFalse( collection.isEmpty() );
Object[] values_array = collection.toArray();
int count = 0;
Iterator<String> iter = collection.iterator();
while ( iter.hasNext() ) {
String value = iter.next();
assertTrue( collection.contains( value ) );
assertEquals( values_array[count], value );
count++;
}
values_array = collection.toArray( new String[0] );
count = 0;
iter = collection.iterator();
while ( iter.hasNext() ) {
String value = iter.next();
assertTrue( collection.contains( value ) );
assertEquals( values_array[count], value );
count++;
}
values_array = collection.toArray( new String[collection.size()] );
count = 0;
iter = collection.iterator();
while ( iter.hasNext() ) {
String value = iter.next();
assertTrue( collection.contains( value ) );
assertEquals( values_array[count], value );
count++;
}
values_array = collection.toArray( new String[collection.size() * 2] );
count = 0;
iter = collection.iterator();
while ( iter.hasNext() ) {
String value = iter.next();
assertTrue( collection.contains( value ) );
assertEquals( values_array[count], value );
count++;
}
assertNull( values_array[collection.size()] );
assertNull( values_array[collection.size()] );
Collection<String> other = new ArrayList<String>( collection );
assertFalse( collection.retainAll( other ) );
other.remove( vals[5] );
assertTrue( collection.retainAll( other ) );
assertFalse( collection.contains( vals[5] ) );
assertFalse( map.containsKey( keys[5] ) );
collection.clear();
assertTrue( collection.isEmpty() );
} |
35975e79-bf06-40ef-aff8-0bb28a2c99c8 | 5 | @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 Order)) {
return false;
}
Order other = (Order) object;
if ((this.orderid == null && other.orderid != null) || (this.orderid != null && !this.orderid.equals(other.orderid))) {
return false;
}
return true;
} |
c3da0fad-1484-49c5-802e-5d8d4391ed2c | 1 | public LocalInfo getReal() {
LocalInfo real = this;
while (real.shadow != null)
real = real.shadow;
return real;
} |
c73e878f-cb05-4931-ad5b-34e57f6cf3d5 | 5 | public static void main(String[] args){
Socket socket;
try {
socket = new Socket("localhost",1457);
//code du client
try
{
Thread.sleep(0);
PrintWriter socketOut = new PrintWriter(socket.getOutputStream(), true);
BufferedReader clavier = new BufferedReader(new InputStreamReader(System.in));
BufferedReader socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//System.out.print("Message : ");
while(true)
{
while(!socketIn.ready())
{
Thread.sleep(0);
}
while(socketIn.ready())
{
System.out.println(socketIn.readLine());
Thread.sleep(100);
}
String message = clavier.readLine();
socketOut.println(message);
}
//Frame frame = new Frame("Client Wumpus");
} catch (InterruptedException e) {
e.printStackTrace();
}
//socket.close();
} catch (IOException e) {
e.printStackTrace();
}
} |
7a1d80f1-2814-40a1-b786-1bd128d03cf6 | 6 | public static void main(String[] args) {
if (args.length < 1) {
System.out.println(usage);
System.exit(1);
}
int lines = 0;
try {
Class<?> c = Class.forName(args[0]);
Method[] methods = c.getMethods();
Constructor[] constructors = c.getConstructors();
if (args.length == 1) {
int index = 0;
for (Method method : methods) {
System.out.println(index++ + " " +
p.matcher(method.toString()).replaceAll(""));
}
index = 0;
for (Constructor constructor : constructors) {
System.out.println(index++ + " " +
p.matcher(constructor.toString()).replaceAll(""));
}
lines = methods.length + constructors.length;
} else {
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
99af7c7e-960c-4438-b00a-e61bbb37381d | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frm_CadEmpresa.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_CadEmpresa.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_CadEmpresa.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_CadEmpresa.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 Frm_CadEmpresa().setVisible(true);
}
});
} |
654ef734-5701-4e1c-8364-458592bebf6c | 2 | private static boolean isPalindrome(String s) {
char[] chs = s.toCharArray();
int i = 0;
int j = chs.length - 1;
while (i < j) {
if (!(chs[i] == chs[j])) {
return false;
}
i++;
j--;
}
return true;
} |
42c1288b-e2eb-4b7c-a9e3-46d2e41b3d99 | 7 | private void afterQueryProcess(Statement statement, Connection connection, ResultSet result) {
try {
if (result != null) {
result.close();
result = null;
}
} catch (SQLException ex) {
}
try {
if (statement != null) {
statement.close();
statement = null;
}
} catch (SQLException ex) {
}
try {
if (connection != null) {
if (!(connection.isClosed()))
connection.close();
connection = null;
}
} catch (SQLException ex) {
}
} |
d38178e9-de77-43b2-81c0-bdc7343b2f23 | 4 | public void modifyItem(Item item) {
Connection con = null;
PreparedStatement pstmt = null;
try {
DBconnection dbCon = new DBconnection();
Class.forName(dbCon.getJDBC_DRIVER());
con = DriverManager.getConnection(dbCon.getDATABASE_URL(),
dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD());
pstmt = con.prepareStatement("Update item Set itm_name=?, itm_barcode=?, itm_barcodeimgpath=?,"
+ "itm_imgpath=?,itm_description=?,"
+ "itm_avgunitcost=?,itm_salerentprice=?,"
+ "itm_minlimit=?,itm_maxlimit=?,itm_quantity=?,"
+ "itm_isavailable=?,itm_isactive=?,"
+ "itm_deactivationreason=?,itemCategory_id=? Where itm_id=?");
pstmt.setString(1, item.getName());
pstmt.setString(2, item.getBarcode());
pstmt.setString(3, item.getImgBracodePath());
pstmt.setString(4, item.getImgPath());
pstmt.setString(5, item.getDescription());
pstmt.setDouble(6, item.getAvgUnitCost());
pstmt.setDouble(7, item.getSaleRentPrice());
pstmt.setInt(8, item.getMinLimit());
pstmt.setInt(9, item.getMaxLimit());
pstmt.setInt(10, item.getQuantity());
pstmt.setBoolean(11, item.getIsAvailable());
pstmt.setBoolean(12, item.getIsActive());
pstmt.setString(13, item.getDeactivationReason());
pstmt.setLong(14, item.getItemCategory_id());
pstmt.executeUpdate();
} catch (SQLException | ClassNotFoundException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
}
}
} |
eee48bc3-6d22-4742-8dce-8160299240de | 2 | public void setName(String name)
throws ClusterException {
if(name == null || name.equals(""))
throw new ClusterException("The file name of the song cannot be null or empty string");
this.name= name;
} |
0677cd84-04be-420c-8c25-6d6bcdc2258d | 6 | public void placeObject(Objects o) {
for (Player p : Server.playerHandler.players){
if(p != null) {
removeAllObjects(o);
globalObjects.add(o);
Client person = (Client)p;
if(person != null){
if(person.heightLevel == o.getObjectHeight() && o.objectTicks == 0) {
if (person.distanceToPoint(o.getObjectX(), o.getObjectY()) <= 60) {
person.getPA().object(o.getObjectId(), o.getObjectX(), o.getObjectY(), o.getObjectFace(), o.getObjectType());
}
}
}
}
}
} |
d79cef21-8e01-459d-9c33-3ce382b94d1f | 9 | public boolean destroyItem(MOB mob, Environmental dropThis, boolean quiet, boolean optimize)
{
String msgstr=null;
final int material=(dropThis instanceof Item)?((Item)dropThis).material():-1;
if(!quiet)
switch(material&RawMaterial.MATERIAL_MASK)
{
case RawMaterial.MATERIAL_LIQUID:
msgstr=L("<S-NAME> pour(s) out <T-NAME>.");
break;
case RawMaterial.MATERIAL_PAPER:
msgstr=L("<S-NAME> tear(s) up <T-NAME>.");
break;
case RawMaterial.MATERIAL_GLASS:
msgstr=L("<S-NAME> smash(es) <T-NAME>.");
break;
default:
return false;
}
final CMMsg msg=CMClass.getMsg(mob,dropThis,null,CMMsg.MSG_NOISYMOVEMENT,(optimize?CMMsg.MASK_OPTIMIZE:0)|CMMsg.MASK_ALWAYS|CMMsg.MSG_DEATH,CMMsg.MSG_NOISYMOVEMENT,msgstr);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
return true;
}
if(dropThis instanceof Coins)
((Coins)dropThis).putCoinsBack();
if(dropThis instanceof RawMaterial)
((RawMaterial)dropThis).rebundle();
return false;
} |
da94fcd8-ed83-4ab0-afb8-65d79ccf5f0f | 4 | public static int getMTU() {
Enumeration<NetworkInterface> en = null;
int minMTU = Integer.MAX_VALUE;
try {
en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = en.nextElement();
int mtu = ni.getMTU();
if (mtu != -1 && mtu < minMTU)
minMTU = mtu;
}
} catch (SocketException e) {
e.printStackTrace();
}
return minMTU;
} |
465da3d0-366c-4ca6-a817-0d5219fb6ea6 | 0 | public void paint(Graphics g){
super.paint(g);
this.drawFields(g);
//System.out.println("paint activited");
calender = Calendar.getInstance();
this.drawTime(g);
} |
90904314-a41f-469e-9425-3f2b8ac624df | 4 | public static boolean isInt(String str)
{
if (str == null || "".equalsIgnoreCase(str))
{
return false;
}
for (String n : NUMBERS)
{
if (str.equalsIgnoreCase(n))
{
return true;
}
}
return false;
} |
b98167a9-798e-4771-96b2-fd41499d142b | 2 | public static void main(String[] args) {
EntityManager em = new JPAUtil().getEntityManager();
ContaDAO dao = new ContaDAO(em);
em.getTransaction().begin();
List<Conta> lista = dao.listaContaComGerente();
for (Conta conta : lista){
System.out.println(conta.getTitular());
if(conta.getGerente() != null)
System.out.println("Gerente: " +conta.getGerente().getNome());
// if(conta.getMovimentacoes() != null)
// System.out.println(conta.getMovimentacoes().size());
}
em.getTransaction().commit();
em.close();
} |
3d3194c9-7a31-4a54-bc22-7712c659538f | 1 | public CurlConnection(String endpoint, String user,String password, String curlCommand,String curlDrop,
String curlURL, String curlUpdate){
Logger log = Logger.getLogger(this.getClass().getName());
log.setLevel(Level.FINE);
this.setLogger(log);
LogHandler.initLogFileHandler(log, "Connection");
this.curlCommand = curlCommand;
this.curlDrop = curlDrop;
this.curlURL = curlURL!=null? curlURL : endpoint;
this.curlUpdate = curlUpdate;
} |
43741f9d-68e3-42f5-b654-6d33f3dea77a | 0 | private void readBlocks(Node parent, Automaton root, Set states,
Document document) {
Map i2b = new java.util.HashMap();
addBlocks(parent, root, states, i2b, document);
} |
2f88648b-7268-487c-baa6-6bd0b80d8184 | 1 | private void doUpdate() {
System.out.print("\n[Performing UPDATE] ... ");
try {
Statement st = conn.createStatement();
st.executeUpdate("UPDATE COFFEES SET PRICE = PRICE + 1");
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
} |
2d7c4422-b0e5-4952-865a-f4403e775b16 | 7 | public static List qualityList(Enumeration enm)
{
if(enm==null || !enm.hasMoreElements())
return Collections.EMPTY_LIST;
Object list=null;
Object qual=null;
// Assume list will be well ordered and just add nonzero
while(enm.hasMoreElements())
{
String v=enm.nextElement().toString();
Float q=getQuality(v);
if (q.floatValue()>=0.001)
{
list=LazyList.add(list,v);
qual=LazyList.add(qual,q);
}
}
List vl=LazyList.getList(list,false);
if (vl.size()<2)
return vl;
List ql=LazyList.getList(qual,false);
// sort list with swaps
Float last=__zero;
for (int i=vl.size();i-->0;)
{
Float q = (Float)ql.get(i);
if (last.compareTo(q)>0)
{
Object tmp=vl.get(i);
vl.set(i,vl.get(i+1));
vl.set(i+1,tmp);
ql.set(i,ql.get(i+1));
ql.set(i+1,q);
last=__zero;
i=vl.size();
continue;
}
last=q;
}
ql.clear();
return vl;
} |
1a12e546-2c91-41e9-86e7-2bd62ed9c678 | 8 | public Point[] findKClosestPoints(Point[] points, int k, final Point origin) {
if (points == null || points.length == 0 || points.length < k) {
return points;
}
Point[] result = new Point[k];
PriorityQueue<Point> queue = new PriorityQueue<Point>(k, new Comparator<Point>() {
@Override
public int compare(Point a, Point b) {
return b.distanceTo(origin) > a.distanceTo(origin) ? 1 : -1;
}
});
for (Point point : points) {
queue.offer(point);
if (queue.size() > k) {
queue.poll();
}
}
for (int i = 0; i < k; i++) {
if (!queue.isEmpty()) {
result[i] = queue.poll();
}
}
return result;
} |
0d885a66-ae0e-4f45-a443-37ce6097f021 | 7 | private void download(URL url, File file, int size)
{
System.out.println("Downloading: " + file.getName() + "...");
//minecraft.progressBar.setText(file.getName());
DataInputStream in = null;
DataOutputStream out = null;
try
{
byte[] data = new byte[4096];
in = new DataInputStream(url.openStream());
FileOutputStream fos = new FileOutputStream(file);
out = new DataOutputStream(fos);
int done = 0;
do
{
int length = in.read(data);
if(length < 0)
{
in.close();
out.close();
return;
}
out.write(data, 0, length);
done += length;
progress = (int)(((double)done / (double)size) * 100);
} while(!running);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try
{
if(in != null)
{
in.close();
}
if(out != null)
{
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//minecraft.progressBar.setText("");
progress = 0;
System.out.println("Downloaded: " + file.getName());
} |
a4a9d64c-a9b0-4e27-ab69-038dbfc3c696 | 7 | private static void writeTrace(final Trace trace, final int traceId,
final JsonGenerator generator) throws IOException
{
generator.writeStartObject();
generator.writeNumberField(JsonTraceCodec.TRACE_ID, traceId);
generator.writeStringField(JsonTraceCodec.TRACE_NAME, trace.getName());
generator.writeStringField(JsonTraceCodec.TRACE_RESULT_TYPE, trace.getResultType().toString());
generator.writeBooleanField(JsonTraceCodec.TRACE_HIDDEN, trace.getHidden());
generator.writeBooleanField(JsonTraceCodec.TRACE_SYSTEM_HIDDEN, trace.getSystemHidden());
if (trace.getValue() != null)
{
generator.writeStringField(JsonTraceCodec.TRACE_VALUE, trace.getValue());
}
if (trace.getStartNanos() != null)
{
generator.writeNumberField(JsonTraceCodec.TRACE_START_NANOS, trace.getStartNanos());
}
if (trace.getPendingNanos() != null)
{
generator.writeNumberField(JsonTraceCodec.TRACE_PENDING_NANOS, trace.getPendingNanos());
}
if (trace.getEndNanos() != null)
{
generator.writeNumberField(JsonTraceCodec.TRACE_END_NANOS, trace.getEndNanos());
}
if (trace.getAttributes() != null && trace.getAttributes().size() > 0)
{
generator.writeArrayFieldStart(JsonTraceCodec.TRACE_ATTRIBUTES);
for(Map.Entry<String, String> attribute : trace.getAttributes().entrySet())
{
generator.writeStartObject();
generator.writeStringField(JsonTraceCodec.TRACE_ATTRIBUTE_KEY, attribute.getKey());
generator.writeStringField(JsonTraceCodec.TRACE_ATTRIBUTE_VALUE, attribute.getValue());
generator.writeEndObject();
}
generator.writeEndArray();
}
generator.writeEndObject();
} |
76bbae57-e7d9-4c7f-b83c-061a946289ed | 1 | public static void main(String[] args) {
Heap h = Heap.make(S);
for (int i=0; i<N; i++) {
System.out.println("Allocating object " + i
+ " at address " + h.alloc(8));
}
h.dump();
System.out.println("Free space remaining = " + h.freeSpace());
} |
76b04c14-cf87-4d91-821d-808e8101db76 | 2 | public SignatureVisitor visitClassBound() {
if (state != FORMAL) {
throw new IllegalStateException();
}
state = BOUND;
SignatureVisitor v = sv == null ? null : sv.visitClassBound();
return new CheckSignatureAdapter(TYPE_SIGNATURE, v);
} |
b7363417-0a02-45f4-849c-38a3935e44c2 | 2 | public byte[] getGenotypesScores() {
int numSamples = getVcfFileIterator().getVcfHeader().getSampleNames().size();
// Not compressed? Parse codes
if (!isCompressedGenotypes()) {
byte gt[] = new byte[numSamples];
int idx = 0;
for (VcfGenotype vgt : getVcfGenotypes())
gt[idx++] = (byte) vgt.getGenotypeCode();
return gt;
}
//---
// Uncompress (HO/HE/NA in info fields)
//---
// Get 'sparse' matrix entries
String hoStr = getInfo(VCF_INFO_HOMS);
String heStr = getInfo(VCF_INFO_HETS);
String naStr = getInfo(VCF_INFO_NAS);
// Parse 'sparse' entries
byte gt[] = new byte[numSamples];
parseSparseGt(naStr, gt, -1);
parseSparseGt(heStr, gt, 1);
parseSparseGt(hoStr, gt, 2);
return gt;
} |
1d2f241d-10e0-46e4-b03b-89a24d32d26e | 7 | private Point searchSpace(Rectangle bounds, int sides, int i, double p)
{
// The bounds of the string
int str_X = bounds.width;
int str_Y = bounds.height;
str_Y = bounds.height;
int x=(int)(p*width);
int l = 0;
while (x > 0 && x< width - str_X)
{
int k = 0;
int y= p_cen.y;
while (y > 0 && y < height - str_Y)
{
if(isEmpty(x, y, str_X, str_Y, 0, i)) {
return new Point(x,y);
}
k++;
y += (k % 2 == 0 ? 1 : -1) * k * 3;
}
System.out.println(x+" , "+y);
l++;
x += (l % 2 == 0 ? 1 : -1) * l * 3;
}
return null;
} |
7f23b991-457e-41e6-ac51-208deb33caa4 | 5 | @Override
public FunctionEvaluator getClone() {
TabularFunction clonedT = new TabularFunction();
for (NodeVariable parameter : this.getParameters()) {
clonedT.addParameter(parameter);
}
if (debug >= 2) {
String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName();
String dclass = Thread.currentThread().getStackTrace()[2].getClassName();
System.out.println("---------------------------------------");
System.out.println("[class: " + dclass + " method: " + dmethod + "] " + "original parameters:");
System.out.print("Originals: ");
for (int i = 0; i < this.parameters.size(); i++) {
System.out.print(this.parameters.get(i) + ",");
}
System.out.println("\ncloned:");
System.out.print("Cloned: ");
for (int i = 0; i < clonedT.getParameters().size(); i++) {
System.out.print(clonedT.getParameters().get(i) + ",");
}
System.out.println("---------------------------------------");
}
for (Entry<NodeArgumentArray, Double> entry : this.costTable.entrySet()){
clonedT.addParametersCost(entry.getKey().getArray(), entry.getValue());
}
/*for (NodeArgument[] arguments : this.getParametersCost().keySet()) {
clonedT.addParametersCost(arguments, this.evaluate(arguments));
if (debug >= 3) {
String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName();
String dclass = Thread.currentThread().getStackTrace()[2].getClassName();
System.out.println("---------------------------------------");
System.out.print("[class: " + dclass + " method: " + dmethod + "] " + "adding for [");
for (NodeArgument arg : arguments) {
System.out.print(arg + ",");
}
System.out.println("] {" + this.evaluate(arguments) + "}");
System.out.print("Now is: [");
for (NodeArgument arg : arguments) {
System.out.print(arg + ",");
}
System.out.println("] {" + clonedT.evaluate(arguments) + "}");
if (this.evaluate(arguments) != clonedT.evaluate(arguments)) {
System.exit(-1);
}
System.out.println("---------------------------------------");
}
}*/
return clonedT;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.