text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void setId(int id) throws ParkingException {
if (id < 0) {
throw new ParkingException("Id is under zero");
}
this.id = id;
} | 1 |
private ConfigManager() {
m_props = new Properties();
try {
m_props.load(this.getClass().getClassLoader()
.getResourceAsStream("config.property"));
} catch (FileNotFoundException e) {
getLogger().error(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
getLogger().error(e.getMessage());
e.printStackTrace();
}
} | 2 |
public boolean isAlive()
{
return alive;
} | 0 |
@Test
public void tosiPieniEsteOikealla() {
laitetaasPariPientaEstetta();
t.lisaaEste(new Este(0, 92, 1000, 200));
pe.liikuOikealle();
for (int i = 0; i < 100; i++) {
pe.eksistoi();
}
assertTrue("Hahmo ei päässyt matalan esteen yli. x = "
+ pe.getX(), pe.getX() > 600);
} | 1 |
public String getRoomNameInDirection(String direction) {
switch (direction.toLowerCase()) {
case "north":
return this.north[0];
case "east":
return this.east[0];
case "south":
return this.south[0];
case "west":
return this.west[0];
default:
System.out.println("Valid options are: North, East, South, West!");
return "FEL";
}
} | 4 |
public void successResponseReceived(String localAddress,
String remoteAddress, int remotePort, Codec codec) {
switch (userAgent.getMediaMode()) {
case captureAndPlayback:
//TODO this could be optimized, create captureRtpSender at stack init
// and just retrieve it here
SoundManager soundManager = userAgent.getSoundManager();
soundManager.openAndStartLines();
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(localAddress);
} catch (UnknownHostException e) {
logger.error("unknown host: " + localAddress, e);
return;
}
rtpSession = new RtpSession(inetAddress, userAgent.getRtpPort(),
userAgent.isMediaDebug(), logger, userAgent.getPeersHome());
try {
inetAddress = InetAddress.getByName(remoteAddress);
rtpSession.setRemoteAddress(inetAddress);
} catch (UnknownHostException e) {
logger.error("unknown host: " + remoteAddress, e);
}
rtpSession.setRemotePort(remotePort);
try {
captureRtpSender = new CaptureRtpSender(rtpSession,
soundManager, userAgent.isMediaDebug(), codec, logger,
userAgent.getPeersHome());
} catch (IOException e) {
logger.error("input/output error", e);
return;
}
try {
captureRtpSender.start();
} catch (IOException e) {
logger.error("input/output error", e);
}
try {
//TODO retrieve port from SDP offer
// incomingRtpReader = new IncomingRtpReader(localAddress,
// Utils.getInstance().getRtpPort(),
// remoteAddress, remotePort);
incomingRtpReader = new IncomingRtpReader(
captureRtpSender.getRtpSession(), soundManager, codec,
logger);
} catch (IOException e) {
logger.error("input/output error", e);
return;
}
incomingRtpReader.start();
break;
case echo:
Echo echo;
try {
echo = new Echo(localAddress, userAgent.getRtpPort(),
remoteAddress, remotePort, logger);
} catch (UnknownHostException e) {
logger.error("unknown host amongst "
+ localAddress + " or " + remoteAddress);
return;
}
userAgent.setEcho(echo);
Thread echoThread = new Thread(echo);
echoThread.start();
break;
case none:
default:
break;
}
} | 9 |
public void moveRight(Area currentWorld){
for(int count = stats.speed; count > 0; count--){
if(currentWorld.locWalkable(x + size + 1, y)
&& currentWorld.locWalkable(x + size + 1, y + size)
&& currentWorld.locWalkable(x + size + 1, y - size)){
x++;
}
}
} | 4 |
public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex){
case 0:
return pers[rowIndex].getNom();
case 1:
return pers[rowIndex].getNaissance();
case 2:
return pers[rowIndex].isMasculin();
case 3:
return pers[rowIndex].getPays();
default:
return null; //Ne devrait jamais arriver
}
} | 4 |
public void runTest(File f, AI ai, AI ai2) throws FileNotFoundException,
UnsupportedEncodingException,
IOException {
FileWriter out = new FileWriter(f, true);
int wins = 0;
int ties = 0;
int loss = 0;
for (int g = 0; g < numGames; g++) {
double[] board = new double[12 * 4];
int player = (Math.random() > .5) ? 1 : 2;
int player2 = (player == 1) ? 2 : 1;
do {
if (player == 1) {
board = ai.exploit(board, player);
if (Winchecker.check(board) > 0) {
break;
}
board = ai2.exploit(board, player2);
} else {
board = ai2.exploit(board, player2);
if (Winchecker.check(board) > 0) {
break;
}
board = ai.exploit(board, player);
}
} while (Winchecker.check(board) < 0);
if (Winchecker.check(board) == player) {
wins++;
} else {
if (Winchecker.check(board) == player2) {
loss++;
} else {
ties++;
}
}
}
System.out.println("Finished " + ai.getName() + " against " + ai2.getName());
out.write(ai2.getName() + "," + wins + "," + ties + "," + loss + "\n");
out.close();
} | 9 |
public String replaceObfuscation() {
String replaceObfuscatedCode = null;
/*
* 難読化に使用する文字の個数を乱数で決める。
* 個数は必ず4以上とする。
*/
int keyCharacterNumber = keyCharacterList.size();
int quantyKeyCharacter = 0;
Random random = new Random();
while (true) {
quantyKeyCharacter = random.nextInt(keyCharacterNumber);
if (3 < quantyKeyCharacter) {
break;
}
}
/*
* 難読化に使用する文字を決める。
* 難読化文字定義リストをシャッフルし、頭から先に決めた
* 使用個数分を難読化に使用する。
*/
String[] keyCharacters = new String[quantyKeyCharacter];
Collections.shuffle(keyCharacterList);
for (int i = 0; i < quantyKeyCharacter; i++) {
keyCharacters[i] = keyCharacterList.get(i);
}
/*
* 決まった難読化文字を用いてコードを難読化する。
* ここでは60%の確率で難読化文字が入る。
*/
StringBuilder stringBuilder = new StringBuilder();
char ch[] = code.toCharArray();
int threshold = 60;
int randomNumberForObfuscateRatio = 0;
int randomNumberForKeyCharacter = 0;
stringBuilder.append("'");
int counter = 0;
while (counter < ch.length) {
randomNumberForObfuscateRatio = random.nextInt(100);
randomNumberForKeyCharacter = random.nextInt(keyCharacters.length);
if (randomNumberForObfuscateRatio < threshold) {
stringBuilder.append(keyCharacters[randomNumberForKeyCharacter]);
} else {
stringBuilder.append(ch[counter]);
counter++;
}
}
/*
* エスケープ文字の挿入などのコード整形処理。
*/
stringBuilder.append("'.replace(/");
for (int i = 0; i < keyCharacters.length; i++) {
if (isNeedsEscape(keyCharacters[i])) {
stringBuilder.append("\\" + keyCharacters[i]);
} else {
stringBuilder.append(keyCharacters[i]);
}
if (i != keyCharacters.length - 1) {
stringBuilder.append("|");
}
}
stringBuilder.append("/ig, '');");
replaceObfuscatedCode = stringBuilder.toString();
return replaceObfuscatedCode;
} | 8 |
public void addInstance(GuideDecision decision) throws MaltChainedException {
if (decision instanceof SingleDecision) {
throw new GuideException("A branched decision model expect more than one decisions. ");
}
featureModel.update();
final SingleDecision singleDecision = ((MultipleDecision)decision).getSingleDecision(decisionIndex);
if (instanceModel == null) {
initInstanceModel(singleDecision.getTableContainer().getTableContainerName());
}
instanceModel.addInstance(singleDecision);
if (decisionIndex+1 < decision.numberOfDecisions()) {
if (singleDecision.continueWithNextDecision()) {
if (children == null) {
children = new HashMap<Integer,DecisionModel>();
}
DecisionModel child = children.get(singleDecision.getDecisionCode());
if (child == null) {
child = initChildDecisionModel(((MultipleDecision)decision).getSingleDecision(decisionIndex+1),
branchedDecisionSymbols+(branchedDecisionSymbols.length() == 0?"":"_")+singleDecision.getDecisionSymbol());
children.put(singleDecision.getDecisionCode(), child);
}
child.addInstance(decision);
}
}
} | 7 |
@Override
public void mouseExited(MouseEvent e) {
} | 0 |
@Override
public void onEnable() {
// 1.0.0.0 <-- Dev #
// 1.0.0 <-- Hotfix #
// 1.0 <-- Sub Version #
// 1 <-- Version #
if (DEBUG) {
NAME = "Cops And Robbers INDEV V1.0.0.1";
} else {
NAME = "Cops And Robbers v1.0.0";
}
// plugin enable stuff
getLogger().info(NAME + " is enabled!");
getServer().getPluginManager().registerEvents(this, this);
} | 1 |
@Override
public void caseAIfStmt(AIfStmt node)
{
for(int i=0;i<indent;i++) System.out.print(" ");
indent++;
System.out.println("(If");
inAIfStmt(node);
if(node.getIf() != null)
{
node.getIf().apply(this);
}
if(node.getLPar() != null)
{
node.getLPar().apply(this);
}
if(node.getExp() != null)
{
node.getExp().apply(this);
}
if(node.getRPar() != null)
{
node.getRPar().apply(this);
}
if(node.getIftrue() != null)
{
node.getIftrue().apply(this);
}
if(node.getElse() != null)
{
node.getElse().apply(this);
}
if(node.getIffalse() != null)
{
node.getIffalse().apply(this);
}
indent--;
for(int i=0;i<indent;i++) System.out.print(" ");
System.out.println(")");
outAIfStmt(node);
} | 9 |
public byte [] recvInterrupt ()
throws IOException
{
if ("interrupt" != getType ())
throw new IllegalArgumentException ();
if (spi == null)
spi = iface.getDevice ().getSPI ();
// FIXME getInterval() ms timeout (caller guarantees periodicity)
return spi.readIntr (getU8 (2), getMaxPacketSize ());
} | 2 |
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == left)
{
halign = Alignment.LEFT;
return;
}
if (e.getSource() == center)
{
halign = Alignment.CENTER;
return;
}
if (e.getSource() == right)
{
halign = Alignment.RIGHT;
return;
}
if (e.getSource() == top)
{
valign = Alignment.TOP;
return;
}
if (e.getSource() == middle)
{
valign = Alignment.MIDDLE;
return;
}
if (e.getSource() == bottom)
{
valign = Alignment.BOTTOM;
return;
}
if (e.getSource() == fButton)
{
Font newFont = FontDialog.getFont(font);
if (newFont == null)
return;
font = newFont;
fButton.setFont(font);
}
} | 8 |
public JSONWriter endObject() throws JSONException {
return this.end('k', '}');
} | 0 |
private void traiterFichier (File fichier)
{
int b = -1;
boolean pasFini = true;
try
{
//transfert en binaire
BufferedInputStream in = new BufferedInputStream(new FileInputStream(fichier));
BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream());
while (pasFini)
{
b = in.read();
if(b != -1)
{
out.write(b);
}
else
{
pasFini = false;
}
}
in.close();
out.close();
}
catch(IOException e) { e.printStackTrace(); }
} | 3 |
public static float findMinimum(Collection<Float> values) {
float MIN = Float.POSITIVE_INFINITY;
for (float f : values)
if (f < MIN)
MIN = f;
return MIN;
} | 2 |
public void print(){
for(int k=0;k<=cols;k++){
System.out.print(vnames[k]+"\t");
}
System.out.print("\n");
for(int k=0;k<=cols;k++){
System.out.print(vunits[k]+"\t");
}
System.out.print("\n");
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
System.out.print(vls[i][j]+"\t");
}
System.out.print("\n");
}
} | 4 |
public String readLine() //exclusively for NON-token
{
if(console)
{
try
{
return myInFile.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
if(!nonToken || isEOF)
return null;
if(current == null)
{
current = next;
try
{
next = myInFile.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
String answer = current + '\n';
current = null;
if(next == null)
{
isEOF = true;
}
return answer;
} | 7 |
private final String getChunk(String s, int slength, int marker)
{
StringBuilder chunk = new StringBuilder();
char c = s.charAt(marker);
chunk.append(c);
marker++;
if (isDigit(c))
{
while (marker < slength)
{
c = s.charAt(marker);
if (!isDigit(c))
break;
chunk.append(c);
marker++;
}
} else
{
while (marker < slength)
{
c = s.charAt(marker);
if (isDigit(c))
break;
chunk.append(c);
marker++;
}
}
return chunk.toString();
} | 5 |
public void run() {
int nf = 1;
int df = 1;
int n2, d2;
for(int n = 1; n < 100; n++) {
for(int d = n + 1; d < 100; d++) {
for(int i = 0; i < 10; i++) {
if(n == d || (n % 10 == 0 && d % 10 == 0)) {
continue;
}
if(containsDigit(n, i) && containsDigit(d, i)) {
n2 = strip(n, i);
d2 = strip(d, i);
// System.out.println(n + " " + d + " strip " + i + " => " + n2 + " " + d2);
if(equals((double) n / d, (double) n2 / d2 , 0.001)) {
// System.out.println(n + " / " + d);
nf *= n;
df *= d;
}
}
}
}
}
this.answer = df / Numbers.gcd(nf, df);
} | 9 |
@Test
public void testAddWhileQuery1() {
Bag<Integer> myList = new Bag<Integer>();
myList.add(1);
myList.add(2);
myList.reset();
assertTrue(myList.hasNext());
int x = myList.next();
assertTrue(x == 1 || x == 2);
myList.add(3);
assertTrue(myList.hasNext());
int y = myList.next();
assertTrue(x != y && (y == 1 || y == 2 || y == 3));
assertTrue(myList.hasNext());
int z = myList.next();
assertTrue(z != y && z != x && (z == 1 || z == 2 || z == 3));
assertFalse(myList.hasNext());
} | 8 |
public boolean isCorner(String m[]){
String rows[] = {"row1", "row3"};
String cols[] = {"0", "2"};
if(m[0] == null)
return false;
if(m[0].equals("row2") && m[1].equals("1")){
//center square
return false;
}
for(int i=0; i< rows.length; i++){
for(int j=0; j<cols.length; j++){
if( rows[i].equals(m[0]) && cols[j].equals(m[1]) ){
return true;
}
}
}
return false;
} | 7 |
public int getSouth(){
return this.south;
} | 0 |
@Override
public void windowOpened(WindowEvent arg0)
{
} | 0 |
@Override
public String getTmp() {return tmp;} | 0 |
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
Arrays.sort(num);
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
Set set = new HashSet();
for (int i = 0; i < num.length; i++) {
if (i < 0)
break;
int left = i + 1;
int right = num.length - 1;
while (left < right) {
int sum = num[left] + num[right] + num[i];
if (sum > 0)
right--;
else if (sum < 0)
left++;
else {
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(num[i]);
tmp.add(num[left]);
tmp.add(num[right]);
if(set.add(tmp))
result.add(tmp);
right--;
left++;
continue;
}
}
}
return result;
} | 6 |
@Test
public void testPercentageUpdate() throws Exception {
propertyChangeSupport.firePropertyChange(DialogWindowController.PERCENTAGE, 0, 10);
assertEquals(view.getProgressBar().getValue(), 10);
} | 0 |
@Override
public void execute(Joueur jou){
Joueur proprio = this.getProprietaire();
if(proprio == null){
propositionAchat(jou);
}
else if(proprio == jou && getRanking() < 5 && jou.possede(this.groupePropriete)){
propositionAmelioration(jou);
}
else if(proprio != jou)
{
if(getLoyerAPayer() <= jou.getCash()){
jou.setCash(jou.getCash() - getLoyerAPayer());
proprio.setCash(proprio.getCash() + getLoyerAPayer());
}
else{
proprio.setCash(proprio.getCash() + jou.getCash());
jou.faillite();}
}
else{return;}
} | 6 |
private String getLabelForState(IEntity entity) throws IOException {
final DrawFile cFile = entity.getImageFile();
final String stateBgcolor = getBackColorOfEntity(entity);
final String stereotype = entity.getStereotype() == null ? null : entity.getStereotype().getLabel();
final StringBuilder sb = new StringBuilder("<{<TABLE BGCOLOR=" + stateBgcolor
+ " BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"0\">");
sb.append("<TR><TD>"
+ manageHtmlIB(StringUtils.getMergedLines(entity.getDisplay2()), FontParam.STATE, stereotype)
+ "</TD></TR>");
sb.append("</TABLE>");
if (entity.getFieldsToDisplay().size() > 0) {
sb.append("|");
for (Member att : entity.getFieldsToDisplay()) {
sb.append(manageHtmlIB(att.getDisplay(true), FontParam.STATE_ATTRIBUTE, stereotype));
sb.append("<BR ALIGN=\"LEFT\"/>");
}
}
if (cFile != null) {
sb.append("|");
final String path = StringUtils.getPlateformDependentAbsolutePath(cFile.getPng());
final String bgcolor;
if (OptionFlags.PBBACK) {
bgcolor = stateBgcolor;
} else {
bgcolor = "\"" + getAsHtml(getData().getSkinParam().getBackgroundColor()) + "\"";
}
// PBBACK
sb.append("<TABLE BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\">");
sb.append("<TR>");
sb.append("<TD BGCOLOR=" + bgcolor + " BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"2\">");
sb.append("<IMG SRC=\"" + path + "\"/></TD></TR>");
sb.append("</TABLE>");
}
if (getData().isHideEmptyDescription() == false && entity.getFieldsToDisplay().size() == 0 && cFile == null) {
sb.append("|");
}
sb.append("}>");
return sb.toString();
} | 8 |
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
if (!this.isEmptyTable(tableSetUp) && this.txtnamefile.getText().length() != 0) {
this.getDataTable(tableSetUp);
this.datacompiler = new DataCompiler(lista, dataTable);
se.writeXml(datacompiler, this.txtnamefile.getText());
} else {
this.msg("Datos incompletos");
}
}//GEN-LAST:event_jButton1ActionPerformed | 2 |
public String monthInLetters(String field)
{
String newField = "";
if(field.length() > 2)
{
newField = String.valueOf(getMonth(field.substring(0, 3)));
System.out.println("month : " + getMonth(field.substring(0, 3)));
if(field.length() > 3)
{
if(field.substring(3, 4).equals(","))
{
System.out.println("and");
if(field.length() > 4)
{
newField = newField + monthAnd(field.substring(4));
}
else
{
newField = "~invalid~";
}
}
else if(field.substring(3, 4).equals("-"))
{
System.out.println("to");
if(field.length() > 4)
{
newField = newField + monthTo(field.substring(4));
}
else
{
newField = "~invalid~";
}
}
else if(field.substring(3, 4).equals("/"))
{
System.out.println("add");
if(field.length() > 4)
{
newField = "START " + newField + monthAdd(field.substring(4));
}
else
{
newField = "~invalid~";
}
}
else
{
newField = "~invalid~";
}
}
}
else
{
newField = "~invalid~";
}
return newField;
} | 8 |
public String getManifestMainAttribute(Attributes.Name name,
String defaultValue)
{
Attributes atts = _manifest.getMainAttributes();
Object value = atts.get(name);
return value != null ? value.toString() : defaultValue;
} | 1 |
public static boolean modificar(Recurso r) throws SQLException {
String queryRecurso = "UPDATE recurso SET isbn = ?, titulo = ?, fecha = ?, genero = ?,"
+ "num_ejemplar = ?, estado_conserva = ?, disponibilidad = ? WHERE id = ?";
String queryLibro = "UPDATE recurso_libro SET autor = ?, editorial = ? WHERE id = ?";
String queryOptico = "UPDATE recurso_optico SET autor = ? WHERE id = ?";
String queryRevista = "UPDATE recurso_revista SET editorial = ?, fasciculo = ? WHERE id = ?";
try {
if (r instanceof Libro) {
ConnectionManager.executeSentence(queryRecurso, r.getISBN(), r.getTitulo(), r.getFechaEdicion(), r.getGenero(), r.getNumEjemplar(), r.getEstadoConservacion(), r.isDisponible() ? 1 : 0, r.getID());
ConnectionManager.executeSentence(queryLibro, ((Libro) r).getAutor(), ((Libro) r).getEditorial(), r.getID());
} else if (r instanceof Revista) {
ConnectionManager.executeSentence(queryRecurso, r.getISBN(), r.getTitulo(), r.getFechaEdicion(), r.getGenero(), r.getNumEjemplar(), r.getEstadoConservacion(), r.isDisponible() ? 1 : 0, r.getID());
ConnectionManager.executeSentence(queryRevista, ((Revista) r).getEditorial(), ((Revista) r).getNumFasciculo(), r.getID());
} else if (r instanceof CdDvd) {
ConnectionManager.executeSentence(queryRecurso, r.getISBN(), r.getTitulo(), r.getFechaEdicion(), r.getGenero(), r.getNumEjemplar(), r.getEstadoConservacion(), r.isDisponible() ? 1 : 0, r.getID());
ConnectionManager.executeSentence(queryOptico, ((CdDvd) r).getAutor(), r.getID());
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
return false;
}
return true;
} | 7 |
protected CommandManager(PrintStream commandSender, int verbose) {
this.commandSender = commandSender;
this.verbose = verbose;
} | 0 |
public accept()
{
this.requireLogin = true;
this.addParamConstraint("id", ParamCons.INTEGER);
this.addRtnCode(405, "appointment not found");
this.addRtnCode(406, "illegal time");
this.addRtnCode(407, "user not waiting");
} | 0 |
private void btnRemoveTaskFromProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveTaskFromProjectActionPerformed
selectedTask = (Task)listTasksList.getSelectedValue();
if(selectedTask !=null && selectedElement !=null && selectedProject !=null && selectedAsset !=null)
{
deleteTask(selectedTask);
fillInTaskOnAssetList(selectedAsset);
}
listTasksList.repaint();
}//GEN-LAST:event_btnRemoveTaskFromProjectActionPerformed | 4 |
public void placeFlags(){
// Place random flags
Random randX = new Random();
Random randY = new Random();
int x, y;
for( int r = 0; r < NUM_OBJECTS; r++ ){
x = randX.nextInt( 1820 + 1 );
y = randY.nextInt( 980 + 1 );
// Make sure we don't place on land
double checkMask[] = maskMat.get( y, x );
if( checkMask[0] == 0.0 && checkMask[1] == 0.0 && checkMask[2] == 0.0){
System.out.println( "woops, on land" );
r--;
}else {
randomX[r] = x;
randomY[r] = y;
}
}
// // CURRENTLY USING FIXED POINTS JUST FOR DEMO PURPOSES:
// randomX[0] = 375;
// randomX[1] = 760;
// randomX[2] = 1100;
// randomX[3] = 1530;
// randomX[4] = 1090;
//
// randomY[0] = 300;
// randomY[1] = 750;
// randomY[2] = 800;
// randomY[3] = 480;
// randomY[4] = 280;
// Print out the flag locations AND MAKE FLAGS
for( int f = 0; f < flagImages.length; f++ ){
System.out.println( randomX[f] + ", " + randomY[f] );
flagImages[f] = new DebrisFlagger(randomX[f], randomY[f]);
}
// Print out the flag locations
for( int f = 0; f < flagImages.length; f++ ){
//System.out.println( randomX[f] + ", " + randomY[f] );
flagImages[f] = new DebrisFlagger(randomX[f], randomY[f]);
}
} | 6 |
private boolean read(){
try {
final URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000);
if (this.apiKey != null) {
conn.addRequestProperty("X-API-Key", this.apiKey);
}
conn.addRequestProperty("User-Agent", Updater.USER_AGENT);
conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.isEmpty()) {
this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id);
this.result = UpdateResult.FAIL_BADID;
return false;
}
JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
this.versionName = (String) latestUpdate.get(Updater.TITLE_VALUE);
this.versionLink = (String) latestUpdate.get(Updater.LINK_VALUE);
this.versionType = (String) latestUpdate.get(Updater.TYPE_VALUE);
this.versionGameVersion = (String) latestUpdate.get(Updater.VERSION_VALUE);
return true;
} catch (final IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) {
this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct.");
this.result = UpdateResult.FAIL_APIKEY;
} else {
this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating.");
this.plugin.getLogger().severe("If this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
this.result = UpdateResult.FAIL_DBO;
}
return false;
}
} | 4 |
public static boolean isPrime(long value){
if(value==2||value==3||value==5){
return true;
}
if(value%6==1||value%6==5){
for(long i=2; i*i<=value; i++){
if(value%i==0){
return false;
}
}
return true;
}
return false;
} | 7 |
private void textProveedorKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textProveedorKeyTyped
// TODO add your handling code here:
if (!Character.isLetter(evt.getKeyChar()) && !Character.isISOControl(evt.getKeyChar()) && !Character.isWhitespace(evt.getKeyChar()))
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
}
if(textProveedor.getText().length() == 45)
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
JOptionPane.showMessageDialog(this, "Nombre del proveedor demadiado largo.", "ADVERTENCIA", WIDTH);
}
}//GEN-LAST:event_textProveedorKeyTyped | 4 |
@Test
public void test_maxGold() {
Pawn p0 = mock(Pawn.class);
Pawn p1 = mock(Pawn.class);
board.removeAllPawns();
assertEquals(board.numberOfPawns(), 0);
board.addPawn(p0);
assertEquals(board.numberOfPawns(), 1);
when(p0.getX()).thenReturn(1);
when(p0.getY()).thenReturn(1);
board.addPawn(p1);
when(p1.getX()).thenReturn(2);
when(p1.getY()).thenReturn(1);
assertEquals(board.numberOfPawns(), 2);
when(p0.getGold()).thenReturn(1);
when(p1.getGold()).thenReturn(3);
board.maxGold();
assertEquals(board.maxGold(), 3);
InOrder mocksWithOrder = inOrder(p0, p1);
mocksWithOrder.verify(p0).getGold();
mocksWithOrder.verify(p1).getGold();
} | 0 |
public double[] calculateEnergyConsumptionW(SoftwareSystem system, FunctionalRequirement functionalRequirement, SequenceAlternative sequenceAlternative) {
double consumption[] = { 0, 0 };
for (HardwareSet hardwareSet : system.getActuallyUsedHardwareSets())
system.initializeTime(hardwareSet);
system.getActuallyUsedHardwareSets().clear();
for (Message message : sequenceAlternative.getMessages()) {
double[] componentConsumption = calculateComponentConsumptionW(message.getReceiver(), system);
if (componentConsumption[1] != -1) {
consumption[1] += componentConsumption[1];
consumption[0] += componentConsumption[0];
}
if (usesNetwork(message, system)) {
double[] networkConsumption = calculateNetworkConsumptionW(message, system);
if (networkConsumption[1] != -1) {
consumption[1] += networkConsumption[1];
consumption[0] += networkConsumption[0];
} else
project.setWReliable(false);
}
}
consumption[1] += calculatePlatformAndOtherConsuptionsW(system);
consumption[0] *= functionalRequirement.getCoefficient();
consumption[1] *= functionalRequirement.getCoefficient();
return consumption;
} | 5 |
public void collapseMenu() {
for(int i = 1; i < methodTree.getRowCount(); i++) methodTree.collapseRow(i);
} | 1 |
public static TagAndURISubModel launchPopupProfil(Component parent,
ProfilesSystemModel profiles) {
String profilName = (String) JOptionPane
.showInputDialog(parent,
"Nouveau profil :\n Veuillez saisir votre nom.",
"Nouveau Profil", JOptionPane.QUESTION_MESSAGE,
new ImageIcon(VitipiMenuConstantes.ICON_PROFIL_PATH),
null, "Default");
TagAndURISubModel newProfile = null;
if (profilName != null) {
if (!profilName.isEmpty() && VitipiTools.isWellFormed(profilName)) {
profilName = profilName.toLowerCase();
newProfile = new TagAndURISubModel(
VitipiXMLKeys.PROFILE_SYSTEM_SUBMODEL,
Constantes.PROFILE_FILE_NAME_BASE + profilName + ".xml",
profilName);
try {
profiles.addData(newProfile);
} catch (Exception e) {
JOptionPane.showMessageDialog(parent, e.getMessage(),
"Profil déjà pris!", JOptionPane.OK_OPTION);
}
} else if (!VitipiTools.isWellFormed(profilName)) {
JOptionPane
.showMessageDialog(
parent,
"Votre nom ne doit pas contenir les caractères suivants :\n \\/:*?\"<>|",
"Mauvais caractères dans le profil",
JOptionPane.OK_OPTION);
} else if (profilName.isEmpty()) {
JOptionPane.showMessageDialog(parent,
"Votre nom ne peut pas être vide!",
"Nom de profil vide", JOptionPane.OK_OPTION);
}
}
return newProfile;
} | 6 |
@Override
public void run() {
if (Updater.this.url != null) {
// Obtain the results of the project's file feed
if (Updater.this.read()) {
if (Updater.this.versionCheck(Updater.this.versionName)) {
if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) {
String name = Updater.this.file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name
if (Updater.this.versionLink.endsWith(".zip")) {
final String[] split = Updater.this.versionLink.split("/");
name = split[split.length - 1];
}
Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink);
} else {
Updater.this.result = UpdateResult.UPDATE_AVAILABLE;
}
}
}
}
} | 6 |
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i + 1).toLowerCase();
}
System.out.println(ext);
return ext.equals("sfp");
} | 3 |
private void writeBoolList(List<Boolean> boolList) throws IOException {
byte b = 0;
int mask = 0x80;
for (Boolean aBoolList : boolList) {
if (aBoolList)
b |= mask;
mask >>= 1;
if (mask == 0) {
writeByte(b);
mask = 0x80;
b = 0;
}
}
if (mask != 0x80)
writeByte(b);
} | 4 |
public static void main (String[] args) {
final byte[] data = {(byte) 189, (byte) 88, (byte) 128, (byte) 244, (byte) 156, (byte) 41, (byte) 17, (byte) 177,
(byte) 157, (byte) 173, (byte) 195, (byte) 121, (byte) 99, (byte) 111, (byte) 114, (byte) 112 };
final Guid guid1 = new Guid(data);
final Guid guid2 = new Guid("bd5880f4-9c29-11b1-9dad-c379636f7270");
System.out.println("guid1 = " + guid1);
System.out.println("guid2 = " + guid2);
if (!guid1.equals(guid2)) {
throw new RuntimeException(guid1 + " does not equal " + guid2);
}
} | 1 |
public void AnalyseDirectory(String dir){
File F = new File(dir);
String[] fi = F.list();
String of ;
File fil = new File(dir + "/dist/");
if(!fil.exists())
{
fil.mkdir();
}
for(String f : fi)
{
if(new File(f).isDirectory())
continue;
if(!f.endsWith(".res"))
continue;
of = dir + "/dist/" + f.substring(0,f.length()-4) + "_dist.txt";
StreamedLinkSet L = new StreamedLinkSet(dir+"/"+f);
LinkSetNode n;
L.initTreeTraversal();
Frequency Fr = new Frequency();
Set<Integer> S = new HashSet<Integer>();
System.out.println("Processing " + f);
while((n=L.getNextInOrder()) != null)
{
Fr.addValue(n.w);
S.add(n.w);
}
List<Integer> k = General.asSortedList(S);
try
{
FileWriter out = new FileWriter(of);
System.out.println("Writing to: " + of);
for(int i:k)
{
out.write(i + " " + Fr.getCumPct(i) + " " + Fr.getPct(i) + " " + Fr.getCount(i) + " \n");
}
out.flush();
out.close();
}
catch (IOException ex)
{
Logger.getLogger(LinkSetAnalyser.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | 7 |
public synchronized void gridletSubmit(Gridlet gl, boolean ack)
{
// update the current Gridlets in exec list up to this point in time
updateGridletProcessing();
// reset number of PE since at the moment, it is not supported
if (gl.getNumPE() > 1)
{
String userName = GridSim.getEntityName( gl.getUserID() );
logger.log(Level.INFO,super.get_name() + ".gridletSubmit(): " +
" Gridlet #" + gl.getGridletID() + " from " + userName +
" user requires " + gl.getNumPE() + " PEs.");
logger.log(Level.INFO,"--> Process this Gridlet to 1 PE only.");
// also adjusted the length because the number of PEs are reduced
int numPE = gl.getNumPE();
double len = gl.getGridletLength();
gl.setGridletLength(len*numPE);
gl.setNumPE(1);
}
ResGridlet rgl = new ResGridlet(gl);
boolean success = false;
// if there is an available PE slot, then allocate immediately
if (gridletInExecList_.size() < super.totalPE_) {
success = allocatePEtoGridlet(rgl);
}
// if no available PE then put the ResGridlet into a Queue list
if (!success)
{
rgl.setGridletStatus(Gridlet.QUEUED);
gridletQueueList_.add(rgl);
}
// sends back an ack if required
if (ack)
{
super.sendAck(GridSimTags.GRIDLET_SUBMIT_ACK, true,
gl.getGridletID(), gl.getUserID()
);
}
} | 4 |
private boolean jj_2_41(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_41(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(40, xla); }
} | 1 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaInicial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaInicial.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 TelaInicial().setVisible(true);
}
});
} | 6 |
@SuppressWarnings("empty-statement")
/**
* This method will generate a SHA-256 Scanner_Checksum of a given file
*
* @param hash - possible values: SHA-1, SHA-256, SHA-512 and MD5
* @param filename - the target filename, we also handle locked files
* @return - the resulting Scanner_Checksum or empty if not possible to compute
*/
public static String generateFileChecksum(String hash, File filename){
String checksum;
FileInputStream fis = null;
try { // SHA-256
MessageDigest md = MessageDigest.getInstance(hash);
// try {
fis = new FileInputStream(filename);
// } catch (Exception e) {
// //log("error", "No Scanner_Checksum performed for " + filename);
//
// return "";
// }
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
//fis.close();
byte[] mdbytes = md.digest();
//convert the byte to hex format method 1
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
checksum = sb.toString();
} catch (IOException ex) {
if(debug == true)
Logger.getLogger(checksum.class.getName()).log(Level.SEVERE, null, ex);
//log("error", "No Scanner_Checksum performed for " + filename);
return "";
} catch (NoSuchAlgorithmException ex) {
if(debug == true)
Logger.getLogger(checksum.class.getName()).log(Level.SEVERE, null, ex);
//log("error", "No Scanner_Checksum performed for " + filename);
return "";
} finally {
try {
if(fis!=null)
fis.close();
} catch (IOException ex) {
if(debug == true)
Logger.getLogger(checksum.class.getName()).log(Level.SEVERE, null, ex);
return "";
}
}
return checksum;
} | 9 |
@Override
public void update(GameContainer gc, int delta) {
// TODO Auto-generated method stub
Vector2 oldPos = position.copy();
Vector2 steeringForce = behavior.calculate();
Vector2 acceleration = steeringForce.divideBy(mass);
velocity.add(acceleration.multiply(delta * MOVEMENT_PER_MS));
velocity.truncate(maxSpeed);
position.add(velocity.multiply(delta * MOVEMENT_PER_MS));
this.heading = velocity.normalizeCopy();
this.side = this.heading.perp();
if(velocity.getX() > 0) {
currentAnimation = birdRight;
} else if(velocity.getX() < 0) { //do this so if velocity is 0, it stays at the last animation
currentAnimation = birdLeft;
}
} | 2 |
public boolean equals(Object other)
{
if (!(other instanceof Location))
return false;
Location otherLoc = (Location) other;
return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol();
} | 2 |
public void setTrajectory(Rectangle sling, Point releasePoint)
{
// don't update parameters if the ref point and release point are the same
if (_trajSet &&
_ref != null && _ref.equals(getReferencePoint(sling)) &&
_release != null && _release.equals(releasePoint))
return;
// set the scene parameters
_scale = sling.height + sling.width;
_ref = getReferencePoint(sling);
// set parameters for the trajectory
_release = new Point(releasePoint.x, releasePoint.y);
// find the launch angle
_theta = Math.atan2(_release.y - _ref.y, _ref.x - _release.x);
_theta = launchToActual(_theta);
// work out initial velocities and coefficients of the parabola
_velocity = getVelocity(_theta);
_ux = _velocity * Math.cos(_theta);
_uy = _velocity * Math.sin(_theta);
_a = -0.5 / (_ux * _ux);
_b = _uy / _ux;
// work out points of the trajectory
_trajectory = new ArrayList<Point>();
for (int x = 0; x < X_MAX; x++) {
double xn = x / _scale;
int y = _ref.y - (int)((_a * xn * xn + _b * xn) * _scale);
_trajectory.add(new Point(x + _ref.x, y));
}
// turn on the setTraj flag
_trajSet = true;
} | 6 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frm_CadStatusAtendimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_CadStatusAtendimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_CadStatusAtendimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_CadStatusAtendimento.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_CadStatusAtendimento().setVisible(true);
}
});
} | 6 |
protected void setup() {
System.out.println("This is patient agent called " + getLocalName());
Object[] arg = getArguments();
try {
int preference = 1;
for (Object o : arg) {
if (o.toString().equals("-")) {
preference++;
} else {
preferences.put(Integer.parseInt(o.toString()), preference);
}
}
// Build the description used as template for the subscription
DFAgentDescription dfd = new DFAgentDescription();
ServiceDescription sd = new ServiceDescription();
sd.setType("allocate-appointments");
// templateSd.addProperties(new Property("country",
// "United Kingdom"));
dfd.addServices(sd);
DFAgentDescription[] descriptions = DFService.search(this, dfd);
if(descriptions.length != 0){
setHospitalAgent(descriptions[0]);
}
addBehaviour(new RequestAppointment());
} catch (NumberFormatException e) {
System.out.println("Invalid input");
} catch (FIPAException e) {
e.printStackTrace();
}
// Make this agent terminate
//doDelete();
} | 5 |
@Test
public void testRemoveRedMarker() {
System.out.println("removeRedMarker");
Cell instance = new Cell(0,0);
instance.addRedMarker(0);
instance.addRedMarker(1);
instance.addRedMarker(2);
instance.addRedMarker(3);
instance.addRedMarker(4);
instance.addRedMarker(5);
boolean[] result = instance.getMarkers(false);
assertEquals(true, result[0]);
assertEquals(true, result[1]);
assertEquals(true, result[2]);
assertEquals(true, result[3]);
assertEquals(true, result[4]);
assertEquals(true, result[5]);
instance.removeRedMarker(0);
instance.removeRedMarker(1);
instance.removeRedMarker(2);
instance.removeRedMarker(3);
instance.removeRedMarker(4);
instance.removeRedMarker(5);
result = instance.getMarkers(false);
assertEquals(false, result[0]);
assertEquals(false, result[1]);
assertEquals(false, result[2]);
assertEquals(false, result[3]);
assertEquals(false, result[4]);
assertEquals(false, result[5]);
} | 0 |
public static Map loadYamlFromResource(String resource) {
InputStream yamlConfig = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
Yaml yaml = new Yaml();
Map mainYamlMap = (Map) yaml.load(yamlConfig);
Map resultYamlMap = new HashMap();
List<Map> imports = (List<Map>) mainYamlMap.get("imports");
if (imports != null) {
for (Map map : imports) {
System.out.println(map.get("resource"));
Map<String, Object> localYamlMap = loadYamlFromResource((String) map.get("resource"));
resultYamlMap = updateMap(resultYamlMap, localYamlMap);
}
}
resultYamlMap = updateMap(resultYamlMap, mainYamlMap);
return resultYamlMap;
} | 2 |
private void BestMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_BestMouseClicked
// TODO add your handling code here:
List<String> s = new Conectar().GetVendedor();
int t = s.size();
boolean b = true;
List<String> names = new ArrayList<>();
for(String s1: s){
if(names.isEmpty()){
names.add(s1);
b = false;
}else{
for(int i = 0; i < names.size();i++){
if(s1.equals(names.get(i))){
b = false;
}
}
}if(b){
names.add(s1);
}
b = true;
}
Map<String, Integer> nombreMap = new TreeMap<String, Integer>();
int cont = 1;
int total = 0;
for(String s1 : names){
for(String s2 : s){
if(s1.equals(s2)){
nombreMap.put(s2, cont);
cont++;
total += cont;
}
}
cont = 1;
}
new Formas().SetValues(nombreMap,total);
}//GEN-LAST:event_BestMouseClicked | 8 |
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(PropertyFilteringMessageBodyWriter.class);
return classes;
} | 3 |
public double getDouble(String key) throws JSONException {
Object o = get(key);
if(o==null) return 0;
try {
if(o instanceof Number){
return ((Number)o).doubleValue();
}else if(o.toString().length()>0){
return Double.valueOf((o.toString()));
}else
return 0;
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not a number.");
}
} | 4 |
private static void refresh(Entity entity) {
EntityTrackerEntry entry = (EntityTrackerEntry) ((WorldServer) ((CraftEntity) entity).getHandle().world).tracker.trackedEntities
.get(entity.getEntityId());
if (entry != null) {
EntityPlayer[] players = (EntityPlayer[]) entry.trackedPlayers.toArray(new EntityPlayer[entry.trackedPlayers.size()]);
for (EntityPlayer player : players) {
if (entity instanceof Player && !player.getBukkitEntity().canSee((Player) entity))
continue;
entry.clear(player);
entry.updatePlayer(player);
}
}
} | 4 |
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException
{
while (this.getLength() > 0 && this.getText(0, 1).equals("0"))
{
super.remove(0, 1);
if (offs > 0)
offs--;
}
super.insertString(offs, p.matcher(str).replaceAll(""), a);
//remove leading zeros
if (this.getLength() > 1 && this.getText(0, 1).equals("0"))
remove(0, 1);
else if (this.getLength() == 0)
super.insertString(0, "0", new SimpleAttributeSet());
} | 6 |
public String scriptsToString() {
int n = getChoiceCount();
if (n < 1)
return "";
if (scripts == null || scripts.length <= 0)
return "";
StringBuffer sb = new StringBuffer(scripts[0]);
if (getSingleSelection()) {
if (n < 2)
return sb.toString().trim();
for (int i = 1; i < n; i++) {
sb.append(" -choiceseparator- ");
sb.append(scripts[i]);
}
}
else {
if (scripts.length > 1) {
sb.append(" -choiceseparator- ");
sb.append(scripts[1]);
}
}
return sb.toString();
} | 7 |
static void testHigh()
{
Scanner in = new Scanner(System.in);
Board b = Board.readBoard(in);
ArrayList<Integer> nextPiece = new ArrayList<Integer>();
while(in.hasNextInt())
nextPiece.add(in.nextInt());
Searcher s;
for (int i = 9; i <13; i++){
for(int j= 5; j < i; j++){
s = new Jogger(new LinearWeightedSum(), i, j);
s.playGame(b, new ArrayList<Integer>(nextPiece));
}
}
} | 3 |
public boolean isKeyPressed(int keyEventKeyCode) {
if(keys.get(keyEventKeyCode) == null) return false;
return keys.get(keyEventKeyCode);
} | 1 |
protected void installListeners() {
super.installListeners();
if (AbstractLookAndFeel.getTheme().doShowFocusFrame()) {
focusListener = new FocusListener() {
public void focusGained(FocusEvent e) {
if (getComponent() != null) {
orgBorder = getComponent().getBorder();
LookAndFeel laf = UIManager.getLookAndFeel();
if (laf instanceof AbstractLookAndFeel && orgBorder instanceof UIResource) {
Border focusBorder = ((AbstractLookAndFeel)laf).getBorderFactory().getFocusFrameBorder();
getComponent().setBorder(focusBorder);
}
getComponent().invalidate();
getComponent().repaint();
}
}
public void focusLost(FocusEvent e) {
if (getComponent() != null) {
if (orgBorder instanceof UIResource) {
getComponent().setBorder(orgBorder);
}
getComponent().invalidate();
getComponent().repaint();
}
}
};
getComponent().addFocusListener(focusListener);
}
} | 6 |
@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 Usuario)) {
return false;
}
Usuario other = (Usuario) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
public void setRpcUser(String rpcUser) throws InvalidSettingException {
if (rpcUser != null) {
this.rpcUser = rpcUser;
} else {
throw new InvalidSettingException("Invalid User");
}
} | 1 |
private static <A, B, C> State resolvePair2(StatePair lr, Fst<A> left,
Fst<B> rigth, final Map<StatePair, State> chart, Fst<C> intersection) {
if (chart.containsKey(lr)) {
return chart.get(lr);
} else {
boolean isInit = left.isInitial(lr.fst) && rigth.isInitial(lr.snd);
boolean isAccept = left.isAccept(lr.fst) && rigth.isAccept(lr.snd);
State intersectionState = intersection.addState(
isInit ? StateFlag.INITIAL : null,
isAccept ? StateFlag.ACCEPT : null);
chart.put(lr, intersectionState);
return intersectionState;
}
} | 5 |
private boolean verificaiton(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
if (this.protocal == PROTOCAL.NOPROTOCAL) {
return sa.NOPROTOCOL(in, out);
} else if (this.protocal == PROTOCAL.T2) {
return sa.T2(in, out);
} else if (this.protocal == PROTOCAL.T3) {
return sa.T3(in, out);
} else if (this.protocal == PROTOCAL.T4) {
return sa.T4(in, out);
} else if (this.protocal == PROTOCAL.T5) {
return sa.T5(in, out);
}
return false;
} | 5 |
public void mousePressed(MouseEvent event) {
if (!controller.isObject(event.getPoint()) && !event.isControlDown()) {
controller.getCurrentGraph().deselectAll();
} else {
if (controller.checkSelectedObject(event.getPoint())) {
if (event.isControlDown()) {
isDeactive = true;
}
} else {
if (event.isControlDown()) {
controller.getCurrentGraph().select(event.getPoint());
} else {
controller.getCurrentGraph().deselectAll();
controller.getCurrentGraph().select(event.getPoint());
}
}
}
controller.repaint();
} | 5 |
static void Eval_pop(Neuron pop[]) {
int i, j, k;
//int spam2;
//float spam = 0;
int best[] = new int[Config.TOP_NETS];
float pop_average;
float total_fitness = 0.0F;
float the_best = -999999.0F;
String best_name;
Network net = new Network();
Neuron net_pop[] = new Neuron[Config.NUM_HIDDEN];
Neuron the_best_net[] = new Neuron[Config.NUM_HIDDEN];
/* make new file name for best network */
i = generation % 1000;
best_name = ("" + (i/100) + ((i%100)/10) + ((i%100)%10) + "best.bin");
/* reset fitness and test values of each neuron */
for (i=0; i<Config.POP_SIZE; ++i) {
pop[i].fitness = 0;
pop[i].ranking = 0;
pop[i].tests = 0;
}
/* eval stage */
for (i=0; i<Config.NUM_TRIALS; ++i) {
if ((i < Config.TOP_NETS) == true)
for (j=0; j<Config.NUM_HIDDEN; ++j) {
net_pop[j] = best_nets[i].neuron[j];
++net_pop[j].tests;
} /* end for-j */
else /* find random subpopulation */
for (j=0; j<Config.NUM_HIDDEN; ++j) {
net_pop[j] = pop[Math.abs(myRandom.nextInt()) % Config.POP_SIZE];
best_nets[i].neuron[j] = net_pop[j];
++net_pop[j].tests;
} /* end for-j */
Sane_NN.Build_net(net, net_pop);
best_nets[i].fitness = 0.0F;
/*evaluate network*/
for (j=0; j<Config.NUM_ATTEMPTS; ++j)
best_nets[i].fitness += Domain.Evaluate_net(net);
//debugging code
//for (spam2=0; spam2<Config.POP_SIZE; ++spam2)
//System.out.println("right after evaluate_net called- best_nets[" + i + "] fitness: " + best_nets[i].fitness);
total_fitness += best_nets[i].fitness;
} /* end for-i loop */
pop_average = total_fitness / Config.NUM_TRIALS;
Sane_EA.Sort_best_networks();
/* each neuron's fitness is determined from the best 5 networks */
/* it participated in. It may be better to use the best 3. */
for (j=0; j<Config.NUM_TRIALS; ++j)
for (k=0; k<Config.NUM_HIDDEN; ++k)
if (best_nets[j].neuron[k].ranking < 5) {
++best_nets[j].neuron[k].ranking;
best_nets[j].neuron[k].fitness += best_nets[j].fitness;
} /* end if <5 */
/* save best networks to a file */
Sane_Util.Save_partial(best_nets[0].neuron, best_name);
//debugging code
//for (i=0; i<Config.POP_SIZE; ++i)
// System.out.println("end of eval_pop- pop[" + i + "] fitness: " + pop[i].fitness);
} /* end Eval_pop */ | 9 |
public String asRegEx() {
StringBuilder sb = new StringBuilder().append("^")
.append(pattern(scheme, SCHEME_REGEX, "(%s):"))
.append(pattern(host, HOST_REGEX, "//(%s)"));
if (host == null || host.pattern().length() > 0) {
sb.append(port == null ? PORT_REGEX : ((port < 0) ? ""
: (":" + port)));
}
if (path != null && path.pattern().startsWith("/")) {
sb.append(pattern(path, PATH_REGEX, "((%s))"));
} else {
sb.append(pattern(path, PATH_REGEX, "(/?(%s))"));
}
sb.append(pattern(fragment, FRAGMENT_REGEX, "(#(%s))"));
return sb.append("$").toString();
} | 6 |
public List<Tiedote> haeTiedotteet()
throws DAOPoikkeus {
// luodaan tyhjä arraylist tiedotteille
List<Tiedote> tiedotteet = new ArrayList<Tiedote>();
try {
// haetaan tiedotteet tietokannasta
TiedoteDAO tDao = new TiedoteDAO();
tiedotteet = tDao.haeTiedotteet();
} catch (DAOPoikkeus p) {
throw new DAOPoikkeus(
"Tiedotteiden hakeminen tietokannasta ei onnistunut!", p);
}
// palautetaan tiedotteet ArrayListinä
return tiedotteet;
} | 1 |
public static void mate(ArrayList<ParkerPaulChicken> chickens) {
Random chickenGenerator = new Random(); // random number generator for generating chickens
// guard clause - no more chickens or only 1 chicken
if (chickens.isEmpty() || chickens.size() == 1) {
return;
}
// check if mating is successful
if (!isMatingSuccessful(chickens)) {
return;
}
// add a random number of chickens
for (int i = 0; i < chickenGenerator.nextInt(5); i++) {
chickens.add(new ParkerPaulChicken());
}
} // end of mate | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Bibliografia other = (Bibliografia) obj;
if (basicaOuNao != other.basicaOuNao)
return false;
if (livro == null) {
if (other.livro != null)
return false;
} else if (!livro.equals(other.livro))
return false;
if (quantidade != other.quantidade)
return false;
return true;
} | 8 |
public static boolean insert(Object bean) {
String sql;
PreparedStatement stmt=null;
try{
if(bean instanceof Patient){
sql = "INSERT into patients ("+Patient.getTableSchema()+") " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt=conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
return insertPatient((Patient)bean, stmt);
}
if(bean instanceof Employee){
sql = "INSERT into employees ("+Employee.getTableSchema()+") " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
stmt=conn.prepareStatement(sql);
return insertEmployee((Employee)bean, stmt);
}
if(bean instanceof Drug){
sql = "INSERT into drugs ("+Drug.getTableSchema()+") " +
"VALUES (?, ?, ?, ?, ?, ?)";
stmt=conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
return insertDrug((Drug)bean, stmt);
}
if(bean instanceof Prescription){
sql = "INSERT into prescriptions ("+Prescription.getTableSchema()+") " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt=conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
return insertPrescription((Prescription) bean, stmt);
}
if(bean instanceof Schedule){
sql = "INSERT into Schedules ("+Schedule.getTableSchema()+") " +
"VALUES (?, ?, ?, ?, ?, ?)";
stmt=conn.prepareStatement(sql);
return insertSchedule((Schedule)bean, stmt);
}
}catch(SQLException e){
System.out.println("sql exception within insert()");
System.out.println(e);
}finally{
if(stmt !=null)
try {
stmt.close();
} catch (SQLException e) {
System.out.println("error when closing stmt within insert()");
e.printStackTrace();
}
}
return false;
} | 8 |
@Override
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
// add key to queue for thread to send
keystr.add("false:"+e.getKeyCode());
} | 0 |
public void reserveSmallConstants(GrowableConstantPool gcp) {
next_instr: for (Iterator iter = instructions.iterator(); iter
.hasNext();) {
Instruction instr = (Instruction) iter.next();
if (instr.getOpcode() == opc_ldc) {
Object constant = instr.getConstant();
if (constant == null)
continue next_instr;
for (int i = 1; i < constants.length; i++) {
if (constant.equals(constants[i]))
continue next_instr;
}
if (constant instanceof Integer) {
int value = ((Integer) constant).intValue();
if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE)
continue next_instr;
}
gcp.reserveConstant(constant);
}
}
} | 8 |
public boolean unregisterCommands() {
CommandMap commandMap = getCommandMap();
List<String> toRemove = new ArrayList<String>();
Map<String, org.bukkit.command.Command> knownCommands = ReflectionUtil.getField(commandMap, "knownCommands");
Set<String> aliases = ReflectionUtil.getField(commandMap, "aliases");
if (knownCommands == null || aliases == null) {
return false;
}
for (Iterator<org.bukkit.command.Command> i = knownCommands.values().iterator(); i.hasNext();) {
org.bukkit.command.Command cmd = i.next();
if (cmd instanceof DynamicPluginCommand && ((DynamicPluginCommand) cmd).getOwner().equals(executor)) {
i.remove();
for (String alias : cmd.getAliases()) {
org.bukkit.command.Command aliasCmd = knownCommands.get(alias);
if (cmd.equals(aliasCmd)) {
aliases.remove(alias);
toRemove.add(alias);
}
}
}
}
for (String string : toRemove) {
knownCommands.remove(string);
}
return true;
} | 8 |
protected Object getChildPort(Object edge, boolean source) {
GraphModel model = getModel();
// Contains the parent of the port, eg. the group
Object parent = (source) ? DefaultGraphModel.getSourceVertex(model,
edge) : DefaultGraphModel.getTargetVertex(model, edge);
// Finds a vertex in the group
int c = model.getChildCount(parent);
for (int i = (source) ? c - 1 : 0; i < c && i >= 0; i += (source) ? -1
: +1) {
Object child = model.getChild(parent, i);
if (!model.isEdge(child) && !model.isPort(child)) {
// Finds a port in the vertex
for (int j = 0; j < model.getChildCount(child); j++) {
Object port = model.getChild(child, j);
if (model.isPort(port)) {
return port;
}
}
}
}
return null;
} | 9 |
@Test
public void testSocketThreadSetSocketTimeoutEx() {
LOGGER.log(Level.INFO, "----- STARTING TEST testSocketThreadSetSocketTimeoutEx -----");
String client_hash = "";
boolean exception_expected = false;
try {
server1.startThread();
} catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) {
exception = true;
}
waitListenThreadStart(server1);
try {
client_hash = server2.addSocket("127.0.0.1");
} catch (IOException | TimeoutException e) {
exception = true;
}
waitSocketThreadAddNotEmpty(server2);
waitSocketThreadState(server2, client_hash, SocketThread.CONFIRMED);
try {
server2.getSocketList().get(client_hash).setSocketTimeout(-10);
} catch (InvalidArgumentException e) {
exception_expected = true;
} catch (SocketException e) {
exception = true;
}
Assert.assertFalse(exception, "Unexpected exception found");
Assert.assertTrue(exception_expected, "Successfully ran setSocketTimeout, expected an exception");
LOGGER.log(Level.INFO, "----- TEST testSocketThreadSetSocketTimeoutEx COMPLETED -----");
} | 4 |
public GraphDrawer getDrawer() {
return drawer;
} | 0 |
private void postFile(String fileName) throws Exception {
PrintWriter fileWriter = new PrintWriter(fileName);
String str = "";
while ((str = in.readLine()) != null) {
fileWriter.println(str);
}
fileWriter.close();
} | 1 |
public static Object scan(String type, String line) {
Object ret = scanHelper(type, line);
if (ret instanceof Class<?>) {
Class<?> clazz = ((Class<?>)ret).getComponentType();
if (clazz == null) {
clazz = (Class<?>)ret;
}
return Array.newInstance(clazz,0);
}
return ret;
} | 6 |
private ArrayList<Individual> pickSimilarWithReplace(Population pop, Individual i1, int num) throws Exception {
int r = 0;
for (int i = 0; i < pop.size(); i++) {
if (i1 == pop.getIndividual(i)) {
r = i;
}
}
//modified indexies
ArrayList<Integer> modifiedIndexies = new ArrayList<Integer>();
ArrayList<Double> modifiedValues = new ArrayList<Double>();
ArrayList<Individual> individuals = new ArrayList<Individual>();
for (int j = 0; j < num; j++) {
int n = pop.size();
double min = Integer.MAX_VALUE;
int index = 0;
double temp;
for (int c = 0; c < pop.size(); c++) {
int i = FromMatrixToVector(r, c, n);
temp = distances[i];
if (min > temp && temp != 0.0) {
min = temp;
index = c;
}
}
int distancesIndex = FromMatrixToVector(r, index, n);
modifiedIndexies.add(distancesIndex);
modifiedValues.add(distances[distancesIndex]);
distances[distancesIndex] = Integer.MAX_VALUE;
individuals.add(pop.getIndividual(index));
}
for (int j = 0; j < modifiedIndexies.size(); j++) {
distances[modifiedIndexies.get(j)] = modifiedValues.get(j);
}
return individuals;
} | 7 |
private static String executeCreateTableCommand(DataBaseManager dbManager, Command command) {
List<String> args = command.getArgs();
String tableName = args.get(0);
List<String> columnNames = args.subList(1, args.size());
String msg = "";
try {
boolean result = dbManager.createTable(tableName, columnNames);
if (result) {
msg = "table " + tableName + " created successfully";
} else {
msg = "table " + tableName + " couldn't be created";
}
} catch (DataBaseTableException e) {
msg = e.getMessage();
}
return msg;
} | 2 |
public File encode(Serializable structure, File file, Map parameters) {
return file;
} | 0 |
public static void writeBytesToImage(BufferedImage bimg, byte[] msg, String filename, String key) throws ImageWriteException, IOException {
int w = bimg.getWidth();
int h = bimg.getHeight();
//System.out.println("[Key] " + key);
RC4 prng = new RC4(EncryptionProvider.sha256(key.getBytes()));
Set<Integer> usedBytes = new HashSet<>();
// Encode message length
int length = msg.length;
//System.out.println("[Actual length] " + length);
byte[] lengthBytes = new byte[4];
lengthBytes[0] = (byte) ((length >> 24) & 0xFF);
lengthBytes[1] = (byte) ((length >> 16) & 0xFF);
lengthBytes[2] = (byte) ((length >> 8) & 0xFF);
lengthBytes[3] = (byte) (length & 0xFF);
byte[] data = new byte[1 + 4 + length];
// Add a header byte to the nanopost to be able to check validity
byte[] header = new byte[1];
header[0] = prng.getByte();
//System.out.println("[Validation byte]: " + header[0]);
// Write header byte
System.arraycopy(header, 0, data, 0, 1);
// Write length to data array
System.arraycopy(lengthBytes, 0, data, 1, 4);
// Write data to data array
System.arraycopy(msg, 0, data, 5, msg.length);
//System.out.println("[Data array] " + Arrays.toString(data));
ByteArrayInputStream bais = new ByteArrayInputStream(data);
BitInputStream bis = new BitInputStream(bais);
// Write data bits as LSB for pixel bytes
int bitNumber = 0;
//System.out.println("[Index] ");
byte bit;
while ((bit = (byte) bis.readBits(1)) != -1 && bitNumber < data.length * 8) {
// Get image pixel
int index = nextPixelIndex(prng, usedBytes, h, w);
int x = getPixelX(index, h, w);
int y = getPixelY(index, h, w);
int byteNumber = getPixelZ(index, h, w);
////System.out.print(index + " x: " + x + " y: " + y + " b: " + byteNumber + " ");
int pixel = 0;
try {
pixel = bimg.getRGB(x, y);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("x: " + x + " y: " + y + " z: " + byteNumber);
}
// Write LSB to pixel
if (bit != 0) {
pixel |= 1 << byteNumber * 8;
} else {
pixel &= ~(1 << byteNumber * 8);
}
//System.out.println("lsb: " + bit + " = " + ((pixel >> (8 * byteNumber)) & 0x01));
bimg.setRGB(x, y, pixel);
bitNumber++;
}
try {
File outputfile = new File(filename);
ImageIO.write(bimg, "png", outputfile);
} catch (IOException e) {
throw new ImageWriteException("Error writing to file: " + e.getMessage());
}
} | 5 |
public static void floodfill( int a, int b , char s ){
Queue<Integer> xx = new LinkedList<Integer>();
Queue<Integer> yy = new LinkedList<Integer>();
xx.add(a);
yy.add(b);
v[a][b] = true;
while( !xx.isEmpty() ){
int x = xx.poll();
int y = yy.poll();
m[x][y] = '*';
for (int k = 0; k < dx.length; k++) {
int i = x + dx[k];
int j = y + dy[k];
if( i >= 0 && i < m.length && j >= 0 && j < m[0].length && !v[i][j] && m[i][j] == s ){
xx.add(i);
yy.add(j);
v[i][j] = true;
}
}
}
} | 8 |
public Ram produkujemyRam(){
return new DDR3();
} | 0 |
public Node<T> deleteNode(T data) {
if (_root == null) {
return null;
}
if (_root.Data == data) {
_root = _root.Next;
return _root;
}
Node<T> temp = _root;
while (temp.Next != null) {
if (temp.Next.Data == data) {
if (temp.Next == _end) {
_end = temp;
temp.Next = null;
} else {
temp.Next = temp.Next.Next;
}
break;
}
temp = temp.Next;
}
return _root;
} | 5 |
public VertexSet copy() {
VertexSet tmp = new VertexSet();
tmp.addVertexSet(this);
return tmp;
} | 0 |
@Override
public boolean runWithoutCheats() {
return true;
} | 0 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.