method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
cca7ac81-ee80-41e6-ae1c-1655109bc11a
| 3 |
public void wdgmsg(Widget sender, String msg, Object... args) {
if (sender == leave) {
wdgmsg("leave");
return;
}
for (Member m : avs.keySet()) {
if (sender == avs.get(m)) {
wdgmsg("click", m.gobid, args[0]);
return;
}
}
super.wdgmsg(sender, msg, args);
}
|
9db86f62-2211-4f1f-b2ef-46d71a7b5814
| 0 |
public void setThreads(Integer threads) {
this.threads = threads;
}
|
0405e440-58ee-4062-b781-dcb4fa8bb9eb
| 5 |
@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
String password = value.toString();
UIInput uiInputConfirmPassword = (UIInput) component.getAttributes().get("pwd2");
String confirmPassword = uiInputConfirmPassword.getSubmittedValue().toString();
// Let required="true" do its job.
if (password == null || password.isEmpty() || confirmPassword == null
|| confirmPassword.isEmpty()) {
return;
}
if (!password.equals(confirmPassword)) {
FacesMessage msg =
new FacesMessage("Pwd validation failed.",
"Pwd Validation failed please follow the contraint");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
uiInputConfirmPassword.setValid(false);
throw new ValidatorException(msg);
}
}
|
2b22a6b0-230c-4dcd-8413-d183b4029b5d
| 2 |
int value(Board b, Side s) {
if (b.piecesContiguous(s)) {
return 1;
} else if (b.piecesContiguous(s.opponent())) {
return -1;
} else {
return 0;
}
}
|
abb0af40-b80d-4acb-b956-edc812cbc2bb
| 5 |
public boolean compBlock(Material block, Player play, String sAction, ArrayList<PaymentCache> aPayer) {
HashMap<String, ArrayList<Material>> hJobs = _jobsdata.getMatHash();
if(hJobs.isEmpty())
return false;
for(Map.Entry<String, ArrayList<Material>> e : hJobs.entrySet()) {
String tier = e.getKey();
ArrayList<Material> mats = e.getValue();
if(!tier.startsWith(sAction) || mats.isEmpty())
continue;
if(!mats.contains(block))
continue;
PaymentCache payment = new PaymentCache(play, _jobsdata.getTierPays().get(sAction + ".pays"), getInteger(tier.substring(tier.length()-1)), _jobsdata.getBasePay(), _jobsdata.getName().toLowerCase());
aPayer.add(payment);
return true;
}
return false;
}
|
f4acbf42-cd2e-40ec-850b-233fb52baf4e
| 4 |
public void reiniciar(){
if (comboBox_1.getSelectedItem() == "Universitario" || comboBox_1.getSelectedItem() == "<Selecciona>") {
comboBoxGrado.setSelectedItem("<Selecciona>");
comboBoxNivelAlcanzado.setSelectedItem("<Selecciona>");
comboBoxPostGrado.setSelectedItem("<Selecciona>");
comboBox_Certificaciones.setSelectedItem("<Selecciona>");
comboBoxEspecialidades.setSelectedItem("<Selecciona>");
comboBoxEstudiosTecnicos.setSelectedItem("<Selecciona>");
comboBoxDoctorado.setSelectedItem("<Selecciona>");
txtSuperlargoArchipielago.setText("");
textField_2.setText("");
formattedTextFieldPostal.setText("");
formattedTextFieldMob.setText("");
formattedTextFieldID.setText("");
textField_3.setText("");
comboBoxSexo.setSelectedItem("<Selecciona>");
comboBox_1_4.setSelectedItem("<Selecciona>");
textField_8.setText("");
textField_10.setText("");
textField_7.setText("");
formattedTextFieldPhone.setText("");
comboBox_1_1.setSelectedItem("<Selecciona>");
comboBox_1_3.setSelectedItem("<Selecciona>");
comboBox_1.setSelectedItem("<Selecciona>");
textField_9.setText("");
textField_11.setText("");
dateChooser.setDate(null);
error.setText(null);
error1.setText(null);
}
else if (comboBox_1.getSelectedItem() == "Técnico") {
comboBox.setSelectedItem("<Selecciona>");
comboBox_5_1.setSelectedItem("<Selecciona>");
comboBox_6_1.setSelectedItem("<Selecciona>");
comboBox_7_1.setSelectedItem("<Selecciona>");
txtSuperlargoArchipielago.setText("");
textField_2.setText("");
formattedTextFieldPostal.setText("");
formattedTextFieldMob.setText("");
formattedTextFieldID.setText("");
textField_3.setText("");
comboBoxSexo.setSelectedItem("<Selecciona>");
comboBox_1_4.setSelectedItem("<Selecciona>");
textField_8.setText("");
textField_10.setText("");
textField_7.setText("");
formattedTextFieldPhone.setText("");
comboBox_1_1.setSelectedItem("<Selecciona>");
comboBox_1_3.setSelectedItem("<Selecciona>");
comboBox_1.setSelectedItem("<Selecciona>");
textField_9.setText("");
textField_11.setText("");
dateChooser.setDate(null);
error.setText(null);
error1.setText(null);
}
else if (comboBox_1.getSelectedItem() == "Oficio") {
comboBox_8.setSelectedItem("<Selecciona>");
comboBox_9.setSelectedItem("<Selecciona>");
comboBox_10.setSelectedItem("<Selecciona>");
txtSuperlargoArchipielago.setText("");
textField_2.setText("");
formattedTextFieldPostal.setText("");
formattedTextFieldMob.setText("");
formattedTextFieldID.setText("");
textField_3.setText("");
comboBoxSexo.setSelectedItem("<Selecciona>");
comboBox_1_4.setSelectedItem("<Selecciona>");
textField_8.setText("");
textField_10.setText("");
textField_7.setText("");
formattedTextFieldPhone.setText("");
comboBox_1_1.setSelectedItem("<Selecciona>");
comboBox_1_3.setSelectedItem("<Selecciona>");
comboBox_1.setSelectedItem("<Selecciona>");
textField_9.setText("");
textField_11.setText("");
dateChooser.setDate(null);
error.setText(null);
error1.setText(null);
}
}
|
625990f7-3b18-4955-b403-738aca7472c8
| 9 |
private void order(String order, String location,
List<ServiceRequest> requests) {
if (order != null) {
if (order.equals("popular")) {
Collections.sort(requests, new Comparator<ServiceRequest>() {
@Override
public int compare(ServiceRequest sr1, ServiceRequest sr2) {
if (sr1.getVotes() == sr2.getVotes()) {
return 0;
} else if (sr1.getVotes() > sr2.getVotes()) {
return -1;
} else {
return 1;
}
}
});
} else if (order.equals("location")) {
if (location != null && !location.trim().equals("")) {
String[] coords = location.split(",");
final GeoPoint current = new GeoPoint(
Double.parseDouble(coords[0]),
Double.parseDouble(coords[1]));
// for (int i = 0; i < requests.size(); i++) {
// GeoPoint gp = new GeoPoint(requests.get(i).getLat(),
// requests.get(i).getLon());
// if (Utils.getDistance(current, gp) > 0.5) {
// requests.remove(i);
// i--;
// }
// }
Collections.sort(requests,
new Comparator<ServiceRequest>() {
@Override
public int compare(ServiceRequest sr1,
ServiceRequest sr2) {
GeoPoint gp1 = new GeoPoint(sr1.getLat(),
sr1.getLon());
GeoPoint gp2 = new GeoPoint(sr2.getLat(),
sr2.getLon());
double d1 = Utils.getDistance(current, gp1);
double d2 = Utils.getDistance(current, gp2);
if (d1 == d2) {
return 0;
} else if (d1 > d2) {
return -1;
} else {
return 1;
}
}
});
}
}
}
}
|
46adfe9f-f48f-4beb-8a92-557666d5cdef
| 4 |
public void paint(Graphics g) {
int frameHeight = getSize().height;
int frameWidth = getSize().width;
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.clearRect(0, 0, frameWidth, frameHeight);
switch (type) {
case FkSolution:
drawSolution1(g2d);
break;
case F2kSolution:
drawSolution2(g2d, frameWidth, frameHeight);
break;
case F3kSolution:
drawSolution3(g2d, frameWidth, frameHeight);
break;
case F4kSolution:
drawSolution4(g2d, frameWidth, frameHeight);
break;
default:
System.err
.println("unknown SolutionType\tpart2.AbstractSolution.paint()");
}
}
|
fc4aeda7-4311-4372-bc10-863c78dab93b
| 7 |
void addAlternative(){
String new_name = (String)JOptionPane.showInputDialog(
this,
"Alternative name:",
"Add New Alternative",
JOptionPane.PLAIN_MESSAGE,
null,
null,
"Alt(" + counter + ")");
if ((new_name != null) && (new_name.length() > 0)) {
//adding to data to update the current model
Vector data = new Vector();
data.addElement(new_name);
for (int i=0; i<objs.size(); i++){
JObjective obj = (JObjective)objs.get(i);
if (obj.getType()==JObjective.DISCRETE){
data.addElement("");
}
else
data.addElement("");
}
rows.add(data);
tabModel.fireTableRowsInserted(rows.size(), rows.size());
//adding to hashmap to update main model
HashMap datamap = new HashMap();
datamap.put("name", new_name);
//add new blank field for all objs
for (int i=0; i<all_objs.size(); i++){
JObjective obj = (JObjective)all_objs.get(i);
if (!obj.getName().equals("name")){
if (obj.getType()==JObjective.DISCRETE){
datamap.put(obj.getName(), "");
}
else
datamap.put(obj.getName(), Double.valueOf(obj.minC));
}
}
alts.add(datamap);
counter++;
num_alts++;
checkAlternativeCount();
}
}
|
7162dafd-baac-4338-8c99-a47980002725
| 4 |
public boolean doesDatabaseExist() {
try {
getConnection(true);
rs = getConn().getMetaData().getCatalogs();
while (rs.next()) {
String databaseName = rs.getString(1);
if(databaseName.equals(dbName)){
return true;
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
|
4041ddde-9798-4345-86b1-dca600dc7e5f
| 2 |
public NextVoteManager(final NextVote nvPlugin) {
this.plugin = nvPlugin;
try {
plugin.getDatabase().find(VoteHistory.class).findRowCount();
} catch (PersistenceException ex) {
log.log(Level.INFO, "Installing database for " + plugin.getDescription().getName() + " due to first time usage");
plugin.installDDL();
}
try {
plugin.getDatabase().find(VoteAggregate.class).findRowCount();
} catch (PersistenceException ex) {
log.log(Level.INFO, "Installing database for " + plugin.getDescription().getName() + " due to first time usage");
VoteAggregate.initView(plugin);
}
this.database = plugin.getDatabase();
}
|
87d72741-6257-42bb-8464-eadab0377acb
| 2 |
public synchronized static void renameBlob(String newName, String oldName) {
File file = new File(oldName);
if (file.isDirectory()) {
System.out.println("Blob is a directory");
renameBlobDir(oldName, newName);
}
if (file.isFile()) {
System.out.println("Blob is a file");
renameSingleBlob(oldName, newName);
}
}
|
8c4e5b0d-7c9a-42f0-b8c5-e0d155e537e0
| 3 |
@Override
public void body() {
loadResourcesIDs();
while (true)
{
printRuntimeMessage("Submitting next gridlets chunk...");
int submittedCount = submitGridletsChunk();
printRuntimeMessage(String.format("...%1$d gridlets submitted",
submittedCount));
if (submittedCount == 0)
break;
printRuntimeMessage(String.format("Receiving %1$d gridlets...",
submittedCount));
for (int i = 0; i < submittedCount; ++i){
super.gridletReceive();
// NOTE: Here we can write statistics for received gridlet
}
printRuntimeMessage("Received...");
}
super.shutdownGridStatisticsEntity();
super.shutdownUserEntity();
super.terminateIOEntities();
GridSimRunTime.getInstance().getOutput().setTotalSimulationTime(GridSim.clock());
}
|
62c01301-9ddd-4c8c-b19f-d36b7f238618
| 2 |
public static MetroSubmodesOfTransportEnumeration fromValue(String v) {
for (MetroSubmodesOfTransportEnumeration c: MetroSubmodesOfTransportEnumeration.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
|
7325e426-c65b-4998-9a38-50501fb1b0f2
| 1 |
public AlbumFeature(File song)
throws MP3Exception {
super(song);
this.obf= new ObjectFactory();
this.album= this.obf.createAlbumType();
this.getHttp= GetHttpPage.getInstance();
try {
this.log= AlbumLogger.getInstance().getLog();
} catch (LogException e) {
throw new MP3Exception("LogException "+e.getMessage(), e);
}
}
|
07772b9c-4909-40b8-8876-0c515898124b
| 5 |
public boolean postMortem(PostMortem pm) {
JSONzip that = (JSONzip) pm;
return this.namehuff.postMortem(that.namehuff)
&& this.namekeep.postMortem(that.namekeep)
&& this.stringkeep.postMortem(that.stringkeep)
&& this.substringhuff.postMortem(that.substringhuff)
&& this.substringkeep.postMortem(that.substringkeep)
&& this.values.postMortem(that.values);
}
|
afd591d0-0079-4aa7-9495-ac161cbd65bf
| 9 |
private boolean searchUpForPrevSubsetNode( Node node, K key, Object[] ret ) {
if( node.mLeft != null && mComp.compareMins( node.mKey, key ) >= 0 &&
mComp.compareMinToMax( key, node.mLeft.mMaxStop.mKey ) < 0 )
{
// Request downward searh on left subtree.
ret[0] = node.mLeft;
return false;
}
while( node.mParent != null ) {
if( node == node.mParent.mLeft ) {
node = node.mParent;
} else {
node = node.mParent;
// If we're coming from the right subtree, it means we haven't
// checked the
// current node or left subtree.
int c = mComp.compareMins( key, node.mKey );
if( c <= 0 ) {
if( mComp.compareMaxes( key, node.mKey ) >= 0 ) {
ret[0] = node;
return true;
}
// Check if the left node might contain a subset.
if( node.mLeft != null && mComp.compareMinToMax( key, node.mLeft.mMaxStop.mKey ) < 0 ) {
ret[0] = node.mLeft;
return false;
}
}
}
}
// Search is complete.
ret[0] = null;
return true;
}
|
14d628ca-1bdf-4b0e-9d20-2a8d2fda5ac3
| 0 |
public static int taxiCab(int color1, int color2) {
int dRed = Math.abs( ((color1 & RED_MASK) >> 16) - ((color2 & RED_MASK) >> 16));
int dGreen = Math.abs( ((color1 & GREEN_MASK) >> 8) - ((color2 & GREEN_MASK) >> 8));
int dBlue = Math.abs( (color1 & BLUE_MASK) - (color2 & BLUE_MASK));
int dist = dRed + dGreen + dBlue;
return dist;
}
|
008e1b3d-ecc9-43af-8fc9-cab5a32e1ea5
| 4 |
public static byte menuprincipal(){
byte op=0;
do{
System.out.println("1 Abrir cuenta bancaria");
System.out.println("2. Consultar saldo cuenta bancaria");
System.out.println("3. Extraer dinero cuenta bancaria");
System.out.println("4. Ingresar dinero cuenta bancaria");
System.out.println("5. Salir");
System.out.print("OP ==> ");
op=0;
try {
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
op=Byte.parseByte(stdin.readLine());
} catch (NumberFormatException e) {
System.out.println("Se espera un valor numerico "+e);
} catch (IOException e) {
e.printStackTrace();
}
}while(op<1 || op>5);
return op;
}
|
28e970d3-4142-4a3d-9163-0001485f9069
| 8 |
private double parseMulOrDiv() throws Exception{
char op; //
double result; //
double partialResult; //ӱʽĽ
//ָ㵱ǰӱʽֵ
result=this.parseExponent();
//ǰǵĵһĸdz˳ȡģг˳
while((op=this.token.charAt(0))=='*'||op=='/'||op=='%'){
this.getToken();//ȡһ
//ָ㵱ǰӱʽֵ
partialResult=this.parseExponent();
switch(op){
case '*':
//dz˷ѴʽֵԵǰӱʽֵ
result=result*partialResult;
break;
case '/':
//dzжϵǰӱʽֵǷΪ00׳0쳣
if(partialResult==0.0){
this.handleError(DIVBYZERO_ERROR);
}
//Ϊ0г
result=result/partialResult;
break;
case '%':
//ȡģ㣬ҲҪжϵǰӱʽֵǷΪ0
//Ϊ0׳쳣
if(partialResult==0.0){
this.handleError(DIVBYZERO_ERROR);
}
//ȡģ
result=result%partialResult;
break;
}
}
return result;
}
|
50bacd62-b1f0-4d9f-bb8b-b99f07afe0d7
| 0 |
public void setAdresse(String adresse) {
this.adresse = adresse;
}
|
ce7bb5f9-6239-406e-b4fa-95e91bc374e9
| 6 |
static public String numberToString(Number n)
throws JSONException {
if (n == null) {
throw new JSONException("Null pointer");
}
testValidity(n);
// Shave off trailing zeros and decimal point, if possible.
String s = n.toString();
if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
while (s.endsWith("0")) {
s = s.substring(0, s.length() - 1);
}
if (s.endsWith(".")) {
s = s.substring(0, s.length() - 1);
}
}
return s;
}
|
dcf476be-2688-4d2c-80d9-514ac9165561
| 7 |
public void mousePressed(MouseEvent e) {
JPanel panel = (JPanel)e.getSource();
Component component = panel.getComponentAt(e.getPoint());
if (component instanceof Field) {
Field field = (Field)component;
int x = field.getFieldX();
int y = field.getFieldY();
if (e.getButton() == MouseEvent.BUTTON1 && (game.getNumber(x, y) == 0 || field.getForeground().equals(Color.BLUE))) {
int number = game.getSelectedNumber();
if (number == -1)
return;
game.setNumber(x, y, number);
field.setNumber(number, true);
} else if (e.getButton() == MouseEvent.BUTTON3 && !field.getForeground().equals(Color.BLACK)) {
game.setNumber(x, y, 0);
field.setNumber(0, false);
}
sudokuPanel.update(game, UpdateAction.CANDIDATES);
}
}
|
e212d7d1-c3f3-460e-a129-67952bd37522
| 1 |
public Object get(int index) throws JSONException {
Object object = opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
}
|
f27a1485-5a59-4bcb-af89-cbc79b01b55b
| 0 |
public boolean isAlive()
{
return alive;
}
|
3ea4108a-c59b-49b3-b8a7-c8f336847639
| 2 |
public CodeRunResult run(CodeRunParams params) {
CodeRunResult result;
Class clazz = params.getCompilationResult().getCompiledClasses().get(TestClassCodeBuilder.TEST_CLASS);
try {
Object o = clazz.getConstructor().newInstance();
Method m = clazz.getDeclaredMethod("execute");
result = runExecuteMethod(o, m);
if (result.getExceptionMessage() == null) {
result.setPass(result.getFailedTestMessages().size() == 0);
}
} catch (Exception e) {
result = new CodeRunResult();
result.setExceptionMessage(e.toString());
}
return result;
}
|
eb0b042b-cfb3-4317-b332-b4eec725dbfb
| 0 |
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
|
02487ef9-c00f-44b2-8fd1-435d875f5633
| 0 |
public void setOtherTlvArray(Tlv[] otherTlvArray) {
OtherTlvArray = otherTlvArray;
}
|
8465e41a-3391-419b-9291-57580e5f6cba
| 6 |
public synchronized double compute() {
if ((getChild1() != null) && (getChild2() != null)) {
double val1 = getChild1().compute();
double val2 = getChild2().compute();
if (getOperator().equals(ADD)) {
setValue(val1 + val2);
} else if (getOperator().equals(SUBTRACT)) {
setValue(val1 - val2);
} else if (getOperator().equals(MULTIPLY)) {
setValue(val1 * val2);
} else if (getOperator().equals(DIVIDE)) {
setValue(val1 / val2);
}
}
return getValue();
}
|
92be7b65-7593-4731-8f78-7663017d4f87
| 6 |
@Override
public void setPixel(int x, int y, int c)
{
if (x < 0 || x >= width)
return;
if (y < 0 || y >= height)
return;
if (format == 1)
{
c &= 0x1F;
c |= getPixelVal(x, y) & (~0x1F);
}
if (format == 6)
{
c &= 0x07;
c |= getPixelVal(x, y) & (~0x07);
}
setPixelVal(x, y, c);
}
|
58f2875e-c467-4945-b98b-40c043c23e61
| 7 |
public static int jump_greedy(int[] A) {
// try greedy
if(A==null || A.length<=1) return 0;
int cnt = 0;
int start = 0;
int end = 0;
while(true) {
int curMaxEnd=end;
cnt++;
for(int i=start;i<=end;++i) {
if((A[i]+i)>curMaxEnd) curMaxEnd=A[i]+i;
if(curMaxEnd>= A.length-1) return cnt;
}
start = end+1;
end = curMaxEnd;
if(end<start) return -1;
}
}
|
c6e8df94-5f78-4b82-9b68-ca5547f01071
| 6 |
public boolean isYourMove() throws InterruptedException {
boolean test = false;
if (test || m_test) {
System.out.println("ConnectFourAI :: isYourMove() BEGIN");
}
setYourTurn(true);
if (!(getGame().getPlayer1() instanceof Human ||
getGame().getPlayer2() instanceof Human)){
sendMove();
}
if (test || m_test) {
System.out.println("ConnectFourAI :: isYourMove() END");
}
return true;
}
|
233731db-ad0b-45b8-9f5f-9c3485ef87bd
| 6 |
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage pokemonSpriteSheet = null;
try {
pokemonSpriteSheet = ImageIO.read(new File("Images/CondensedOverworldSprites.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int spriteColumns =16;
int spriteRows = 7;
int spriteWidth = 20;
int spriteHeight = 20;
int offset = 0;
BufferedImage[] sprites = new BufferedImage[(spriteRows+1)*(spriteColumns+1)];
System.out.println("Rows: "+ spriteRows + " Columns: " + spriteColumns);
for(int i = 0; i<spriteColumns;i++)
{
for(int j = 0; j<spriteRows;j++)
{
sprites[(i*spriteRows)+j] = pokemonSpriteSheet.getSubimage(
j*spriteWidth,
i*spriteHeight+offset,
spriteWidth,
spriteHeight);
}
}
//g.setColor(Color.green);
//TowerBuilder b = new TowerBuilder();
//Tile t = new Tile(0,0,0);
//Map m = new Level1(new Game());
//BufferedImage charmander = b.buildTower(TowerID.CHARMANDER, t, m).getImage();
//g.drawImage(sprites[10],60,60,60,60,this);
//prints out sprite sheet individual sprites
for(int i = 0;i<spriteRows;i++)
{
for(int j = 0;j<spriteColumns;j++)
{
g.drawImage(sprites[(i*spriteRows)+j],i*20,j*20,20,20,this);//i*spriteRows)+j
g.drawString(""+((i*spriteRows)+j),i*20 ,j*20 );
}
}
for(int k =0;k<=spriteRows*spriteColumns;k++)
{
//g.drawImage(sprites[k],k*20,0,20,20,this);
}
}
|
2dc23bc3-3343-4d98-b133-090052c0ef4c
| 8 |
private int minDistance_dp(String word1, String word2) {
if (word1.equals(word2)) {
return 0;
}
int M = word1.length(), N = word2.length();
if (M == 0 || N == 0) {
return Math.abs(M - N);
}
// init P
int[][] P = new int[M + 1][N + 1];
P[0][0] = 0;
for (int i = 1; i <= M; i++) {
P[i][0] = i;
}
for (int i = 1; i <= N; i++) {
P[0][i] = i;
}
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++) {
char c1 = word1.charAt(i - 1);
char c2 = word2.charAt(j - 1);
if (c1 == c2) {
P[i][j] = P[i - 1][j - 1];
} else {
P[i][j] = Math.min(P[i - 1][j - 1], Math.min(P[i - 1][j], P[i][j - 1])) + 1;
}
}
}
return P[M][N];
}
|
01b78040-0761-4235-afd8-2e39293c0e27
| 4 |
public InstrumentInfo(String symbol) {
m_symbol = symbol;
final String url = "http://download.finance.yahoo.com/q?s=" + symbol + "&d=t";
try {
Document doc = Jsoup.connect(url).get();
Elements table = doc.select("body table:nth-child(2) > tbody > tr > td > table > tbody");
m_name = table.select("tbody tr[bgcolor=#dcdcdc] b").text();
m_lastTradePrice = Double.parseDouble(table.select("table tr:nth-child(2) b").text().replace(",", ""));
Elements news = doc.select("body table table:nth-child(6) tr[valign=top]");
if (news != null) {
for (final Element e : news) {
m_news.add(e.html());
}
}
final String text = table.select("table tr td:nth-child(2) font font").text();
if (text == null)
m_change = 0;
else
m_change = Double.parseDouble(text.split(" ")[0]);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
|
3385397b-f9e2-439e-abe1-3d24679d32cc
| 7 |
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DistanceFilter)) return false;
DistanceFilter other = (DistanceFilter) o;
if (this.distance != other.distance ||
this.lat != other.lat ||
this.lng != other.lng ||
!this.latField.equals(other.latField) ||
!this.lngField.equals(other.lngField)) {
return false;
}
return true;
}
|
9bca5ef5-04ca-4ebc-aec6-049af68d0afe
| 5 |
public String get(int i) {
NodoListaDiccionario aux;
if(i>size || i < 0)
return null;
if(i>size/2) {
aux = ultimo;
for(int j = size-1; j>i; j--)
aux = aux.getAnterior();
return aux.getPalabra();
} else {
aux = primero;
for(int j = 0; j<i; j++)
aux = aux.getSiguiente();
return aux.getPalabra();
}
}
|
ec6d5705-d27f-44d4-8984-6b9add852209
| 9 |
protected void eraseFromScrollItem(Scroll buildingI, Ability theSpell, int level)
{
if(buildingI == null)
return;
StringBuilder newList=new StringBuilder();
for(Ability A : buildingI.getSpells())
{
if(!A.ID().equalsIgnoreCase(theSpell.ID()))
newList.append(A.ID()).append(";");
if(buildingI.isGeneric())
{
final String testName=L(" OF @x1",A.Name().toUpperCase());
if(buildingI.Name().toUpperCase().endsWith(testName))
buildingI.setName(buildingI.Name().substring(0,buildingI.Name().length()-testName.length()));
}
}
buildingI.setSpellList(newList.toString());
if(buildingI.isGeneric())
{
if(buildingI.getSpells().size()==1)
{
if(buildingI.name().toUpperCase().endsWith(L(" SCROLL")))
buildingI.setName(L("@x1 of @x2",buildingI.name(),buildingI.getSpells().get(0).name().toLowerCase()));
buildingI.setDisplayText(L("@x1 sits here.",buildingI.Name()));
}
}
if(buildingI.usesRemaining()>0)
buildingI.setUsesRemaining(buildingI.usesRemaining()-1);
buildingI.text();
}
|
b5a98012-c84f-4dbc-9819-8f009cab9315
| 0 |
public void setAge(int age)
{
Age = age;
}
|
07bd71c1-2e01-4421-8833-ffbc21b08c14
| 7 |
private TLanguageFile initSingle( Element node, String workDir, String projectDir)
{
TLanguageFile back = null ;
String filename = node.getAttribute("filename") ;
if (filename != null)
{
if (filename.length() > 0)
{
File workFile = new File( filename ) ;
// file doesn't exists => look at a static path
if ( !workFile.exists() )
{
workFile = new File( workDir, filename ) ;
// try the xml project path
if (!workFile.exists() )
{
workFile = new File(projectDir, filename) ;
}
}
// last hope: found?
if ( workFile.exists() )
{
back = createFileHandle( workFile ) ;
// read some extra properties
NodeList nList = node.getElementsByTagName("properties") ;
if (nList != null)
{
if (nList.getLength() > 0)
{
back.initFromXml( (Element) nList.item(0) ) ;
}
}
}
else
{
Logger.global.warning( "file not found " +filename ) ;
}
}
}
return back ;
}
|
5f2a6534-4c09-444d-a372-656fa72899a4
| 2 |
public MemberResolver.Method atMethodCallCore(CtClass targetClass,
String mname, ASTList args)
throws CompileError
{
int nargs = getMethodArgsLength(args);
int[] types = new int[nargs];
int[] dims = new int[nargs];
String[] cnames = new String[nargs];
atMethodArgs(args, types, dims, cnames);
MemberResolver.Method found
= resolver.lookupMethod(targetClass, thisClass, thisMethod,
mname, types, dims, cnames);
if (found == null) {
String clazz = targetClass.getName();
String signature = argTypesToString(types, dims, cnames);
String msg;
if (mname.equals(MethodInfo.nameInit))
msg = "cannot find constructor " + clazz + signature;
else
msg = mname + signature + " not found in " + clazz;
throw new CompileError(msg);
}
String desc = found.info.getDescriptor();
setReturnType(desc);
return found;
}
|
d793deb3-2513-4d1b-8791-0ae294c4e19f
| 0 |
public void setReasonForStopping(String reason) {
reasonForStopping = reason;
}
|
35cc79ae-2b92-47de-ad1d-fe3206001113
| 3 |
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
for(ListIterator<PVar> i = this._var_.listIterator(); i.hasNext();)
{
if(i.next() == oldChild)
{
if(newChild != null)
{
i.set((PVar) newChild);
newChild.parent(this);
oldChild.parent(null);
return;
}
i.remove();
oldChild.parent(null);
return;
}
}
throw new RuntimeException("Not a child.");
}
|
fe561049-cfc7-4d40-800f-1292c2cd80f9
| 2 |
@Override
public double[][] solve(double[] f, int n, double k, double u, double dt, double dx) {
int m = f.length;
double[][] ans = new double[n][];
ans[0] = f;
for (int i = 1; i < n; i++) {
double[] prevLayer = ans[i - 1], curLayer = new double[m];
for (int j = 0; j < m; j++) {
curLayer[j] = prevLayer[(j + m - 10) % m];
}
ans[i] = curLayer;
}
return ans;
}
|
a31fd5e5-a037-4037-b965-7c3c842ced2d
| 6 |
public void visitIfStmt(final IfStmt stmt) {
if (stmt.trueTarget() == oldDst) {
if (FlowGraph.DEBUG) {
System.out.print(" replacing " + stmt);
}
stmt.setTrueTarget(newDst);
if (FlowGraph.DEBUG) {
System.out.println(" with " + stmt);
}
}
if (stmt.falseTarget() == oldDst) {
if (FlowGraph.DEBUG) {
System.out.print(" replacing " + stmt);
}
stmt.setFalseTarget(newDst);
if (FlowGraph.DEBUG) {
System.out.println(" with " + stmt);
}
}
}
|
9e8d49b6-91e4-490e-acd5-0d1c2f5a4a71
| 7 |
@Override
public void setTemperature(int i, int j, double value) {
if (i >= 0 && i < numLongCells && j >= 0 && j < numLatCells) {
cellValues[i][j] = value;
}
// Allow overrunning the "size" of the grid. We are on
// a sphere, after all. This is convenient for checking neighbors
// at boundaries.
int iIndex = i % numLongCells;
int jIndex = j % (2 * numLatCells);
// Translate a negative index to its positive equivalent.
if (iIndex < 0) { iIndex += numLongCells; }
if (jIndex < 0) { jIndex += 2 * numLatCells; }
// If we have not circled past the pole or have circled all the
// way back, past two poles, the latitude and longitude are simple.
if (jIndex < numLatCells) {
cellValues[iIndex][jIndex] = value;
} else {
// Otherwise, we have crossed the poles an odd number of times, and
// the latitude and longitude are more complicated.
cellValues[Math.abs(iIndex - (numLongCells / 2))][(2 * numLatCells - 1) - jIndex] = value;
}
}
|
45487c9d-7bc9-4101-8545-463c6886f8a2
| 5 |
private void finFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_finFieldActionPerformed
// TODO add your handling code here:
String OneLine;
String word;
int occurrences;
int lines = 0;
int i, j;
StringTokenizer strtok;
HashTable ht = new HashTable();
try
{
System.out.println(finField.getText());
FileInputStream instream = new FileInputStream(finField.getText());
DataInputStream DataFile = new DataInputStream(instream);
while((OneLine = (String)DataFile.readLine()) != null)
{
ht.setCurrentLine(++lines);
strtok = new StringTokenizer(OneLine);
while (strtok.hasMoreTokens())
{
ht.insert(strtok.nextToken());
}
}//while
instream.close();
}//try
catch (Exception e)
{System.out.println("Error");}
for(i = 0; i < ht.getDictionary().length; i++)
{
if (ht.getDictionary()[i].getWord()!=null)
{
word = ht.getDictionary()[i].getWord();
occurrences = ht.getDictionary()[i].getLines().getCount();
concordanceTA.append("\n" + word + " - Occurrences: " + occurrences + "Lines:" + ht.getDictionary()[i].getLines().display());
}
}
}//GEN-LAST:event_finFieldActionPerformed
|
f09cb521-fa39-4ba5-ab9e-f9e7cfa1eb91
| 5 |
@Override
public void renderControl(Graphics2D g) {
BufferedImage Control = new BufferedImage(this.getSize().getWidth(), this.getSize().getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) Control.getGraphics();
if(this.getBackgroundColor() != null)
{
g2d.setColor(this.getBackgroundColor());
g2d.fillRect(0,0,this.getSize().getWidth(), this.getSize().getHeight());
}
for(int i = 0; i < this.Matrix.size(); i++)
{
Rectangle rect = this.Matrix.get(i);
if(!this.Toolitems.isEmpty() && i < this.Toolitems.size())
{
Item item = this.Toolitems.get(i);
g2d.drawImage(item.getImage(),rect.x, rect.y, rect.width, rect.height, null);
}
if(this.BorderColor != null)
{
g2d.setColor(this.BorderColor);
g2d.drawRect(rect.x, rect.y, rect.width -1, rect.height -1);
}
}
g.drawImage(Control, this.getLocation().getX(), this.getLocation().getY(), this.getSize().getWidth(), this.getSize().getHeight(), null);
}
|
7734db90-fd53-4f91-99cc-0f6bced8dbcb
| 9 |
protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
|
004fdeda-af11-4ee3-b0cf-40c69685034e
| 8 |
private void balanceAfterInsert(AVLNode<T> node) {
int balanceFactor = node.getBalanceFactor();
if (balanceFactor > 1 || balanceFactor < -1) {
AVLNode<T> parent = null;
AVLNode<T> child = null;
Balance balance = null;
if (balanceFactor < 0) {
parent = (AVLNode<T>) node.lesser;
balanceFactor = parent.getBalanceFactor();
if (balanceFactor < 0) {
child = (AVLNode<T>) parent.lesser;
balance = Balance.LEFT_LEFT;
} else {
child = (AVLNode<T>) parent.greater;
balance = Balance.LEFT_RIGHT;
}
} else {
parent = (AVLNode<T>) node.greater;
balanceFactor = parent.getBalanceFactor();
if (balanceFactor < 0) {
child = (AVLNode<T>) parent.lesser;
balance = Balance.RIGHT_LEFT;
} else {
child = (AVLNode<T>) parent.greater;
balance = Balance.RIGHT_RIGHT;
}
}
if (balance == Balance.LEFT_RIGHT) {
// Left-Right (Left rotation, right rotation)
rotateLeft(parent);
rotateRight(node);
} else if (balance == Balance.RIGHT_LEFT) {
// Right-Left (Right rotation, left rotation)
rotateRight(parent);
rotateLeft(node);
} else if (balance == Balance.LEFT_LEFT) {
// Left-Left (Right rotation)
rotateRight(node);
} else {
// Right-Right (Left rotation)
rotateLeft(node);
}
node.updateHeight(); // New child node
child.updateHeight(); // New child node
parent.updateHeight(); // New Parent node
}
}
|
0b6b430f-d40b-4559-bd7f-6e068e950fda
| 5 |
public List<Proveedor> getListaProveedor(){
List<Proveedor> ListaProveedor = new LinkedList();
Conexionbd.conexion bd = new Conexionbd.conexion();
List<producto> lp = new LinkedList();
try{
bd.conectarBase();
ResultSet rs = bd.sentencia.executeQuery("SELECT * FROM USUARIOS WHERE TIPO = 'p'");
while (rs.next()){
Proveedor prov = new Proveedor();
prov.setNick(rs.getString("NICK"));
prov.setApellido(rs.getString("APELLIDO"));
// System.out.print(prov.getNick());
prov.setEmail(rs.getString("EMAIL"));
prov.setImagen(rs.getString("IMAGEN"));
prov.setLinkPagina(rs.getString("LINK_COMP"));
prov.setNombre(rs.getString("NOMBRE"));
prov.setNombreCompañia(rs.getString("NOM_COMP"));
prov.setContraseña(rs.getString("CONTRASEÑA"));
java.sql.Date sqldate = rs.getDate("NACIMIENTO");
Date d = new Date(sqldate.getTime());
prov.setFnac(d);
ResultSet rs2 = bd.sentencia.executeQuery("SELECT * FROM PRODUCTO WHERE NOMBRE_PROV = "
+ "'"+prov.getNick()+"'");
while(rs2.next()){
producto prod = new producto();
prod.setNombre(rs2.getString("NOMBRE"));
prod.setDescripcion(rs2.getString("DESCRIPCION"));
prod.setNumRef(rs2.getInt("NUM_REF"));
String imag = rs2.getString("IMAGENES");
//JOptionPane.showMessageDialog(null, imag);
List<String> imagenes = new LinkedList();
StringTokenizer st2 = new StringTokenizer(imag,"-");
while(st2.hasMoreTokens()){
imagenes.add(st2.nextToken());
//JOptionPane.showMessageDialog(null, st2.nextToken());
}
prod.setImagen(imagenes);
double i = Double.parseDouble(rs2.getString("PRECIO"));
Money prec = new Money();
prec.setValor(i);
prec.setTipo("USD");
prod.setPrecio(prec);
prod.setProvee(prov);
ResultSet rs3 = bd.sentencia.executeQuery("SELECT * FROM CATxPROD WHERE NOMBRE_PROD = "
+ "'"+prod.getNombre()+"'");
List<Hoja> hojas = new LinkedList();
while(rs3.next()){
String categ = rs3.getString("NOMBRE_CAT");
Hoja hoja = new Hoja();
hoja.SetNombre(categ);
hojas.add(hoja);
//JOptionPane.showMessageDialog(null, hoja.GetNombre());
prod.setCategorias(hojas);
}
lp.add(prod);
}
prov.setListaproductos(lp);
ListaProveedor.add(prov);
}
}catch (Exception e){
}
bd.desconectarBaseDeDatos();
return ListaProveedor;
}
|
85489d72-d3f2-48b1-80ea-e027bd69582e
| 9 |
public void render() {
if(blocksBackground != null){
for(int x = 0; x < blocksBackground.length; x++){
for(int y = 0; y < blocksBackground[x].length; y++){
if(blocksBackground[x][y] != null){
blocksBackground[x][y].render();
}
}
}
}
if(blocksForeground != null){
for(int x = 0; x < blocksForeground.length; x++){
for(int y = 0; y < blocksForeground[x].length; y++){
if(blocksForeground[x][y] != null){
blocksForeground[x][y].render();
}
}
}
}
for(Entity entity : entities){
entity.render();
}
}
|
20eb047f-cc4e-443b-aa7d-0ddce3195580
| 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(ChoixOrdreCarteEnnemi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChoixOrdreCarteEnnemi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChoixOrdreCarteEnnemi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChoixOrdreCarteEnnemi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the dialog
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ChoixOrdreCarteEnnemi dialog = new ChoixOrdreCarteEnnemi(new javax.swing.JFrame(), true, pileCarteEnnemis);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
|
5a59961a-e62e-41e3-afe8-654aabc04e03
| 2 |
@Override
public Case getCaseForIA(Joueur joueurAdverse) {
Random rand = new Random();
Case caseTouchee;
int x = rand.nextInt(this._parametre.getNbCaseX());
int y = rand.nextInt(this._parametre.getNbCaseY());
while (((Case) (joueurAdverse.getCases().get(x + y * this._parametre.getNbCaseX()))).isEtat()) {
x = rand.nextInt(this._parametre.getNbCaseX());
y = rand.nextInt(this._parametre.getNbCaseY());
}
caseTouchee = joueurAdverse.getCases().get(x + y * this._parametre.getNbCaseX());
if (caseTouchee.getClass().getSimpleName().equalsIgnoreCase("CaseBateau")) {
casesATester(joueurAdverse, caseTouchee);
}
return caseTouchee;
}
|
a77aed0e-ba72-4ca4-bb52-04c28caae832
| 8 |
public Map<String, TestScript> getTestScripts() throws Exception{
File[] scriptFiles = this.file.getTestScripts();
Map<String, TestScript> allScripts = new HashMap<String, TestScript>();
for(File script : scriptFiles){
ExcelReader reader = new ExcelReader(script);
ExcelModel excel = reader.loadExcel();
List<TestScriptItem> items = new ArrayList<TestScriptItem>();
Map<String, DataItem> sheetData = new HashMap<String, DataItem>();
//TODO Validate header
for(int i = 0; i < excel.getSheets().size(); i++){
if(i == 0){
for(RowModel row : excel.getSheets().get(i).getBody()){
List<String> v = row.getCells();
if(this.isEmpty(this.getValue(v, 1))){
//BPC Name is required, or else no new item create
continue;
}
TestScriptItem singleScript = new TestScriptItem();
singleScript.setNeedOrNot(this.toBoolean(getValue(v, 0)));
singleScript.setBPCName(getValue(v, 1));
singleScript.setComments(getValue(v, 2));
items.add(singleScript);
}
} else {
Map<String, String> keyV = new HashMap<String, String>();
SheetModel st = excel.getSheets().get(i);
if(!st.getHeader().isEmpty() && !st.getBody().isEmpty()){
List<String> keys = excel.getSheets().get(i).getHeader();
List<String> vals = excel.getSheets().get(i).getBody().get(0).getCells(); //By default, it at least have 2nd row.
for(int k = 0; k < keys.size(); k++){
keyV.put(getValue(keys,k), getValue(vals,k));
}
sheetData.put(excel.getSheets().get(i).getName(), new DataItem(keyV));
}
}
}
allScripts.put(this.getName(script.getName()), new TestScript(items, sheetData));
}
return allScripts;
}
|
e062f871-a118-4317-b6d2-90d8b80f214c
| 4 |
public void definirTerrain(int[][] je){
if (jeu.length != je.length && jeu[0].length != je[0].length)
throw new TailleErreur();
for (int i = 0; i<je.length; i++){
for (int j=0; j<je[0].length; j++){
jeu[i][j]=je[i][j];
}
}
}
|
f37fe7cc-9c1a-4ca3-a8c6-7820aeb1771f
| 1 |
public void campaign2Clicked()
{
WindowStack ws = WindowStack.getLastInstance();
System.out.println(ws);
if (ws != null) {
WindowCampaign campaign = new WindowCampaign(2);
ws.push(campaign);
}
}
|
b63eb789-574c-4afb-ab80-26338c417909
| 6 |
private void select(){
switch(currentChoice){
case 0:
if(!glitches)glitches = true;
else glitches = false;
Player.setGlitch(glitches);
System.out.println(glitches);
System.out.println("2: "+ Player.isGlitch());
break;
case 1:
gsm.setState(GameStateManager.OPTIONSSTATE);
break;
case 2:
starsChoice++;
if(starsChoice==starsColor.length)starsChoice = 0;
Bullet.setStar(starsColor[starsChoice]);
break;
case 3:
gsm.setState(GameStateManager.MENUSTATE);
}
}
|
65e662db-3dbb-4411-b5d8-46455dc44370
| 5 |
public static File getFileChoice(Component owner, String defaultPath,
FileFilter filter, String title) {
//
// There is apparently a bug in the native Windows FileSystem class that
// occurs when you use a file chooser and there is a security manager
// active. An error dialog is displayed indicating there is no disk in
// Drive A:. To avoid this, the security manager is temporarily set to
// null and then reset after the file chooser is closed.
//
File defaultSelection = new File(defaultPath);
SecurityManager sm = null;
File choice = null;
JFileChooser chooser = null;
sm = System.getSecurityManager();
System.setSecurityManager(null);
chooser = new JFileChooser();
if (defaultSelection.isDirectory()) {
chooser.setCurrentDirectory(defaultSelection);
} else {
chooser.setSelectedFile(defaultSelection);
}
chooser.setFileFilter(filter);
chooser.setDialogTitle(title);
chooser.setApproveButtonText("OK");
int v = chooser.showOpenDialog(owner);
owner.requestFocus();
switch (v) {
case JFileChooser.APPROVE_OPTION:
if (chooser.getSelectedFile() != null) {
choice = chooser.getSelectedFile();
}
break;
case JFileChooser.CANCEL_OPTION:
case JFileChooser.ERROR_OPTION:
}
chooser.removeAll();
chooser = null;
System.setSecurityManager(sm);
return choice;
}
|
0a8836b3-faf3-4674-9386-c59bf5a40328
| 4 |
public static void main( String [ ] args )
{
int numItems = 10000;
BinomialQueue<Integer> h = new BinomialQueue<>( );
BinomialQueue<Integer> h1 = new BinomialQueue<>( );
int i = 37;
System.out.println( "Starting check." );
for( i = 37; i != 0; i = ( i + 37 ) % numItems )
if( i % 2 == 0 )
h1.insert( i );
else
h.insert( i );
h.merge( h1 );
for( i = 1; i < numItems; i++ )
if( h.deleteMin( ) != i )
System.out.println( "Oops! " + i );
System.out.println( "Check done." );
}
|
744a65db-0ba0-4407-b2e9-3e7d838e4cc6
| 4 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
if (!productCode.equals(product.productCode)) return false;
return true;
}
|
681253ad-cf05-4b1e-8f19-0e55ceafa9de
| 2 |
public String getColumnName(int column) {
if (column == 0)
return " ";
if (column == terminals.length + 1)
return "$";
return terminals[column - 1];
}
|
9763776b-2b3c-4976-a4a8-c75f46daf64b
| 4 |
public void create(String path) {
// Set base url to the Wiki URL (for images that we didn't catch, etc.)
prince.setBaseURL(config.getBaseUrl());
File output = new File(path).getAbsoluteFile();
File temp = new File(path + ".pdf").getAbsoluteFile();
if(!output.getParentFile().exists())
output.getParentFile().mkdirs();
// Init builder
StringBuilder htmlBuilder = new StringBuilder();
initBuilder(htmlBuilder);
// Compile color images
BakaTsuki.info("Creating color pages...");
for (Image image : config.getImages())
{
htmlBuilder.append(image.getHtml());
}
BakaTsuki.info("Compiling chapters...");
// Compile Html
for (Page page : config.getPages())
{
htmlBuilder.append(page.getHtml());
}
closeBuilder(htmlBuilder);
BakaTsuki.info(String.format("Writing PDF to %s...", path));
try ( InputStream in = new ByteArrayInputStream(htmlBuilder.toString().getBytes("UTF-8"));
OutputStream out = new FileOutputStream(temp))
{
prince.convert(in, out);
} catch (IOException e) {
e.printStackTrace();
}
BakaTsuki.info("Cleaning...");
moveDisclaimer(temp, output);
temp.delete();
BakaTsuki.info("Your PDF is ready.");
}
|
d41f522d-a390-42c4-922b-4729a50cb051
| 1 |
private int evalState(State s, State ls) {
//attack + defense
int weight[] = {4,4,3};
int atk = weight[0]*attack(s,ls);
int def = weight[1]*defense(s);
int diff = weight[2]*difference(s);
int score = atk + def + diff;
//System.out.println("Attack = "+atk+" | Defense = "+def+" Difference = "+diff+" Sum = "+score );
return (me.equals("red"))?score:-score;
}
|
0123a99a-7bfb-42b8-80a0-d0c542513d4e
| 1 |
protected Integer calcBPB_FATSz16() throws UnsupportedEncodingException {
byte[] bTemp = new byte[2];
for (int i = 22;i < 24; i++) {
bTemp[i-22] = imageBytes[i];
}
BPB_FATSz16 = byteArrayToInt(bTemp);
System.out.println(BPB_FATSz16);
return BPB_FATSz16;
}
|
58918842-3a6e-422b-ac50-a67d832b2ad9
| 3 |
public void encode(String message) throws IOException {
char[] msgChars = message.toCharArray();
for(int i = 0; i < this.width; i++) {
if(i < message.length()) {
this.picture.setRGB(i, 0, (int) msgChars[i]);
} else {
this.picture.setRGB(i, 0, 0); // Set to nothing
}
}
if(this.filename.getAbsolutePath().endsWith(".png")) {
ImageIO.write(this.picture, "png", this.filename);
} else {
ImageIO.write(this.picture, "png", new File(this.filename.getAbsolutePath() + ".png"));
}
}
|
fddc406f-d9af-4a63-a88d-02174d1f41d0
| 9 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Board other = (Board) obj;
if (this.boardHeight != other.boardHeight) {
return false;
}
if (this.boardWidth != other.boardWidth) {
return false;
}
if (!Arrays.deepEquals(this.topLabels, other.topLabels)) {
return false;
}
if (!Arrays.deepEquals(this.sideLabels, other.sideLabels)) {
return false;
}
if (this.lightsOnStart != other.lightsOnStart) {
return false;
}
if (!Objects.equals(this.light, other.light)) {
return false;
}
if (!Arrays.deepEquals(this.boardArray, other.boardArray)) {
return false;
}
return true;
}
|
0597ed06-35a1-43e4-8d4c-90fa5ce4f58a
| 7 |
public boolean isValidMove(int startCol, int startRow, int endCol, int endRow)
{
//Works
return ((startRow == endRow && Math.abs(startCol - endCol) <= 1) || (startCol == endCol && Math.abs(startRow - endRow) <= 1) ||
(endCol != startCol && startRow != endRow && ((Math.abs(startRow - endRow) == 1 && Math.abs(startCol - endCol) == 1))));
}
|
cef17cb7-5ba2-48e4-b10b-5ad837efe0d8
| 7 |
public int getScoreEndGame(BufferedImage screenshot) {
// crop score image
BufferedImage scoreImage = screenshot.getSubimage(370, 265, 100, 32);
// transform template images into black-white format
BufferedImage[] endGameNumberTemplates = { extractNumber(_endGame0),
extractNumber(_endGame1), extractNumber(_endGame2),
extractNumber(_endGame3), extractNumber(_endGame4),
extractNumber(_endGame5), extractNumber(_endGame6),
extractNumber(_endGame7), extractNumber(_endGame8),
extractNumber(_endGame9) };
// extract characters
int mask[][] = new int[scoreImage.getHeight()][scoreImage.getWidth()];
for (int y = 0; y < scoreImage.getHeight(); y++) {
for (int x = 0; x < scoreImage.getWidth(); x++) {
final int colour = scoreImage.getRGB(x, y);
mask[y][x] = (((colour & 0x00ff0000) >> 16) > 192) ? 1 : -1;
}
}
scoreImage = VisionUtils.int2image(mask);
mask = VisionUtils.findConnectedComponents(mask);
Rectangle[] letters = VisionUtils.findBoundingBoxes(mask);
Arrays.sort(letters, new RectLeftOf());
// decode letters
int score = 0;
for (int i = 0; i < letters.length; i++) {
if (letters[i].width < 2)
continue;
BufferedImage letterImage = scoreImage.getSubimage(letters[i].x,
letters[i].y, letters[i].width, letters[i].height);
int value = 0;
//init min different between target number and template
int minDiff = Integer.MAX_VALUE;
//loop to find a template with minimum difference
for (int j = 0; j < 10; j++) {
int diff = getPixelDifference(letterImage, endGameNumberTemplates[j]);
if(diff < minDiff){
minDiff = diff;
value = j;
}
}
score = 10 * score + value;
}
/*
if (score != prevScore)
{
saved = false;
repeatCount = 0;
prevScore = score;
}
else if (score != 0 && !saved)
{
repeatCount++;
if (repeatCount > 0)
{
saved = true;
try {
File outputfile = new File("scoreImage/" + score + ".png");
ImageIO.write(saveImage, "png", outputfile);
} catch (IOException e) {
}
}
}*/
/*
* VisionUtils.drawBoundingBoxes(scoreImage, letters, Color.BLUE); if
* (_debug == null) { _debug = new ShowDebuggingImage("score",
* scoreImage); } else { _debug.refresh(scoreImage); }
*/
return score;
}
|
71aa0c5b-3f80-4b04-b64c-17f1c9a6a442
| 2 |
private boolean jj_3_55() {
if (jj_scan_token(POINT)) return true;
if (jj_3R_72()) return true;
return false;
}
|
1b2f82cf-0f33-48ac-b429-823a986cbe97
| 5 |
@Override
public boolean executeMouvement() {
Carte carte = null;
int x=0,y=0;
if (Carte.isCreated()){
carte = Carte.getInstance(0, 0, 0, null);
}
if (carte!=null){
x= chevalier.getPositionX();
y=chevalier.getPositionY();
carte.getCartePanel().deplacementPossible(chevalier);
while ((chevalier.getPositionX()==x) && (y==chevalier.getPositionY())){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
chevalier.setNivVie(chevalier.getNivVie() - chevalier.getSacChevalier().getPoids());
}
return true;
}
|
179599db-2cd2-4df4-a312-41c8b367a7f8
| 8 |
public void save() {
if (ChristmasCrashers.isDebugModeEnabled())
System.out.println("Saving level " + ID + " in world " + worldID + ".");
File dataFile = new File(getDiskLocation());
if (!dataFile.exists()) {
System.out.println("Data file for level " + ID + " in world " + worldID + " does not exist - creating it now.");
dataFile.mkdirs();
try {
dataFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to save level " + ID + " in world" + worldID + " - could not create data file.");
return;
}
}
FileWriter fw = null;
try {
fw = new FileWriter(getDiskLocation());
} catch (IOException e) {
e.printStackTrace();
}
if (fw == null)
return;
PrintWriter pw = new PrintWriter(fw);
for (int j = HEIGHT - 1; j >= 0; j--) { // See comment in load() method about the order of i and j being inverted
StringBuilder sb = new StringBuilder();
for (int i = 0; i < WIDTH; i++)
sb.append(objects[i][j].getType().getDataChar());
pw.println(sb.toString());
}
pw.close();
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
|
dc87c826-e16c-4c59-a1da-0f315c11b13d
| 0 |
synchronized public void terminate() {
gameThread.setMessage(TERMINATE_MESSAGE);
notify();
gameThread.doDelay(25);
board = null;
}
|
c13d18ec-308c-40f7-a214-d9a397dc4794
| 9 |
public void skillCheck(String attribute, int skill,
int difficulty) {
Result r = Dice.contest(skill, difficulty);
while (r.equals(Result.TIE)) {
r = Dice.contest(skill, difficulty);
}
if (r.equals(Result.FAILURE)) {
switch (attribute) {
case "stamina":
pc.increaseStat(AbilityType.STAMINA, 1);
break;
case "agility":
pc.setAgility(skill + 1);
break;
case "logic":
pc.setLogic(skill + 1);
break;
case "creativity":
pc.setCreativity(skill + 1);
break;
case "wisdom":
pc.setWisdom(skill + 1);
break;
case "charisma":
pc.setCharisma(skill + 1);
break;
default:
break;
}
} else if (r.equals(Result.SUCCESS))
pc.setBits(pc.getBits() + 1);
}
|
64fae314-e958-4c8f-9811-51651928bd63
| 1 |
public boolean canStart() {
return !(isStarted || preStart);
}
|
97af7d35-cc9b-4ed5-a913-7225f2319e87
| 9 |
private void injectObject() {
for(BeanDefinition beanDefinition : beanDefines){
Object bean = sigletons.get(beanDefinition.getId());
if(bean!=null){
try {
PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
for(PropertyDefinition propertyDefinition : beanDefinition.getPropertys()){
for(PropertyDescriptor properdesc : ps){
if(propertyDefinition.getName().equals(properdesc.getName())){
Method setter = properdesc.getWriteMethod();//获取属性的setter方法 ,private
if(setter!=null){
Object value = null;
if(propertyDefinition.getRef()!=null && !"".equals(propertyDefinition.getRef().trim())){
value = sigletons.get(propertyDefinition.getRef());
}else{
value = ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
}
setter.setAccessible(true);
setter.invoke(bean, value);//把引用对象注入到属性
}
break;
}
}
}
} catch (Exception e) {
}
}
}
}
|
d2cdd356-81e1-40dc-a933-9a405b2604bf
| 6 |
private void stopPosition() {
StreamsterApiInterfaceProxy proxy = new StreamsterApiInterfaceProxy();
Position[] positions = new Position[0];
try {
positions = proxy.getPositions();
} catch (RemoteException ex) {
Logger.getLogger(JobTradeUpGBPJPY.class.getName()).log(Level.SEVERE, null, ex);
}
for (Position position : positions) {
if (position.getStatus().equalsIgnoreCase("OPEN")) {
if (position.getPoints().compareTo(new BigDecimal(5)) == 0 || position.getPoints().compareTo(new BigDecimal(5)) == 1) {
try {
proxy.closePosition(position.getPositionID());
} catch (RemoteException ex) {
Logger.getLogger(JobTradeUpGBPJPY.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
|
5f9799bb-4e78-4f7f-a5dd-0d67e16d4354
| 5 |
public void addTile(Tile tile) {
//Si la pioche a ete verrouillee
if (isClose)
return ;
//Si il s'agit d'une pioche ouverte
if (isOpen && tile != null) {
JLabel tmp = new JLabel(tile.getIcon());
tmp.addMouseListener(this);
this.tileList.put( tile.getType(), tmp);
}
//Apparence de la pioche
if (tile != null) {
this.isEmpty = false;
if(isOpen) {
this.setIcon(tile.getIcon());
}
else {
this.setIcon(new ImageIcon(closedPick));
}
} else {
this.isEmpty = true;
this.setIcon(new ImageIcon(nullPick));
}
}
|
800d58f1-e5fb-40c7-a076-635ddc117548
| 5 |
private DetachedCriteria makeCriteria(Map<String, Object> condition) {
DetachedCriteria criteria = DetachedCriteria.forClass(Class.class);
if (condition == null) {
return criteria;
}
criteria.createAlias("grade", "g");
criteria.createAlias("g.specialty", "s");
criteria.createAlias("s.college", "c");
if (condition.containsKey("college_id")) {
criteria.add(Restrictions.eq("c.id", condition.get("college_id")));
} else if (condition.containsKey("specialty_id")) {
criteria.add(Restrictions.eq("s.id", condition.get("specialty_id")));
} else if (condition.containsKey("grade_id")) {
criteria.add(Restrictions.eq("g.id", condition.get("grade_id")));
}
if (condition.containsKey("class_name")) {
criteria.add(Restrictions.ilike("className", condition.get("class_name").toString(), MatchMode.ANYWHERE));
}
return criteria;
}
|
12266279-5472-49d1-b8a8-2679fff1b28c
| 0 |
public PrimitiveUndoableMove(CompoundUndoableMove undoable, Node node, int index, int targetIndex) {
this.undoable = undoable;
this.node = node;
this.index = index;
this.targetIndex = targetIndex;
}
|
5d195972-e978-49ee-bf49-d3273f58d5d6
| 8 |
public void die()
{
xDeathPos = (int) x;
yDeathPos = (int) y;
world.paused = true;
deathTime = 1;
Art.stopMusic();
world.sound.play(Art.samples[Art.SAMPLE_MARIO_DEATH], this, 1, 1, 1);
if(world.recorder != null){
if(running)
world.recorder.endRunningRecord();
if(large && !fire){
world.recorder.endLargeRecord();
}
if(fire){
world.recorder.endFireRecord();
}
if(!large && !fire)
world.recorder.endLittleRecord();
if(ducking)
world.recorder.endDuckRecord();
world.recorder.endTime();
world.recorder.recordJumpLand();
}
large = false;
fire = false;
}
|
3382ca3d-2d1b-47c1-a62c-80eca3c2a0b1
| 3 |
private void checkMaxFlow(long vID, IAIGraph yolo) {
// die drei beispielgraphen sind so gebaut, dass
// der maximale flow bei graph 9 und graph 20
// daran ueberprueft werden kann, ob alle von der Quelle
// ausgehende Kanten voll ausgeschoepft sind
// unser graph 21 wurde so gebaut, dass er mit eiem schlechten
// fluss initialisiert uebergeben wird und
// wir dann pruefen, dass am Ende der Fluss zum destination maximal ist.
if (graphname == "graph21.graph") {
for (long eID : yolo.getIncident(senkeID)) {
assertEquals(c(eID, yolo), f(eID, yolo));
}
} else {
for (long eID : yolo.getIncident(quelleID)) {
assertEquals(c(eID, yolo), f(eID, yolo));
}
}
}
|
1d1f0cfa-71ab-432e-899c-ca12df0faa31
| 6 |
public void drawRadar(FrameBuffer buffer, Car car) {
float xf=0;
float zf=0;
SimpleVector carPos=car.getTransformedCenter();
SimpleVector temp=new SimpleVector();
float rot=car.getDirection();
float dx=(float) buffer.getOutputWidth()/10f;
float dy=(float) buffer.getOutputHeight()/10f;
float carPosX=(buffer.getOutputWidth()-dx-50);
float carPosY=dy+50;
for (int i=0; i<MAX_PLANTS; i++) {
if (!plants[i].isDead()) {
temp.x=positions[i].x-carPos.x;
temp.z=positions[i].z-carPos.z;
temp.rotateY(rot);
xf=temp.x;
zf=temp.z;
if (xf>-600&&xf<600&&zf>-600&&zf<600) {
int x=(int) (carPosX+((xf/600f)*(float) dx));
int z=(int) (carPosY+((zf/600f)*-(float) dy));
buffer.blit(radar, 0, 0, x, z, 4, 4, FrameBuffer.OPAQUE_BLITTING);
}
}
}
// Finally, a small red dot is blitted to show where the car is located
buffer.blit(radar, 0, 0, (int) carPosX, (int) carPosY, 2, 2, FrameBuffer.OPAQUE_BLITTING);
}
|
225383f0-9a14-4581-bfe5-bab685afd445
| 9 |
private void scrollAndAnimateBy(int increment) {
if (scrollerTimer == null || !scrollerTimer.isRunning()) {
int index = itemIndex + increment;
if (index < 0) {
index = 0;
} else if (index >= dataModel.getSize()) {
index = dataModel.getSize() - 1;
}
if (index == itemIndex) {
return;
}
DrawableItem drawable = null;
if (drawableItems != null) {
for (DrawableItem item : drawableItems) {
if (item.index == index) {
drawable = item;
break;
}
}
}
if (drawable != null) {
scrollAndAnimate(drawable);
}
}
}
|
66c17df2-e5f9-4a89-9cda-5e8db95066af
| 5 |
public void updateStockPrices() throws Exception{
PreparedStatement ps = null;
ResultSet rs = null;
List<String> tickers = new ArrayList<String>();
boolean oldAutoCommitState = con.getAutoCommit();
con.setAutoCommit(false);
//Gets List of Stock Tickers
try {
ps = _preparedStatements.get(PreparedStatementID.GET_STOCK_TICKERS);
rs = ps.executeQuery();
while (rs.next()) {
tickers.add(rs.getString(1));
}
}catch (SQLException e) {
throw e;
}finally {
// if (rs != null) try { rs.close(); } catch (SQLException ignore) {}
// if (ps != null) try { ps.close(); } catch (SQLException ignore) {}
}
//Updates Prices for the List of Stock Tickers
try {
ps = null;
rs = null;
List<BigDecimal> prices = YAPI_Reader.getPrices(tickers);
for (int i = 0; i < tickers.size(); i++){
ps = _preparedStatements.get(PreparedStatementID.UPDATE_PRICES);
ps.setBigDecimal(1, prices.get(i));
ps.setString(2, tickers.get(i));
ps.executeUpdate();
}
con.commit();
} catch (SQLException e) {
con.rollback();
}
finally {
try {con.setAutoCommit(oldAutoCommitState); } catch (SQLException ignore) {}
}
}
|
c60c9b77-845e-4adf-94d7-fc018a366bc0
| 8 |
public void editCard()
{
if (selectedCard != null)
{
if (selectedCard instanceof HeroFrontCard)
{
frame.newWindow(CreatorFrame.FILE_NEW_HERO_FRONT, selectedCard);
}
if (selectedCard instanceof HeroBackCard)
{
frame.newWindow(CreatorFrame.FILE_NEW_HERO_BACK, selectedCard);
}
if (selectedCard instanceof HeroCard)
{
frame.newWindow(CreatorFrame.FILE_NEW_HERO_CARD, selectedCard);
}
if (selectedCard instanceof BackCard)
{
frame.newWindow(CreatorFrame.FILE_NEW_CARD_BACK, selectedCard);
}
if (selectedCard instanceof VillainFrontCard)
{
frame.newWindow(CreatorFrame.FILE_NEW_VILLIAN_FRONT, selectedCard);
}
if (selectedCard instanceof VillainCard)
{
frame.newWindow(CreatorFrame.FILE_NEW_VILLIAN_CARD, selectedCard);
}
if (selectedCard instanceof EnvironmentCard)
{
frame.newWindow(CreatorFrame.FILE_NEW_ENVIRONMENT_CARD, selectedCard);
}
}
}
|
b66fb009-5ef0-4268-aa09-a43964da0a34
| 1 |
private static Properties loadProperties() throws Exception {
InputStream stream = Version.class.getResourceAsStream(POM_PATH);
Properties props = new Properties();
try {
props.load(stream);
return props;
} catch (Exception ex) {
throw ex;
}
}
|
b053b3a8-129c-44bd-a962-ea16a717d3d6
| 7 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Salle other = (Salle) obj;
if (this.id != other.id) {
return false;
}
if ((this.nom == null) ? (other.nom != null) : !this.nom.equals(other.nom)) {
return false;
}
if (this.capacite != other.capacite) {
return false;
}
if (this.getBatiment() != other.getBatiment()) {
return false;
}
return true;
}
|
7e5b6a09-6638-45c4-9e28-396f187122d8
| 4 |
public BufferedImage renderPrepared(int px, int pz, int sx, int sz, double min, double max)
{
BufferedImage res = new BufferedImage(sx, sz, BufferedImage.TYPE_INT_RGB);
double[] data = get2DData(px, pz, sx, sz);
for(int x = 0; x < sx; x++)
for(int z = 0; z < sz; z++)
{
double val = data[x*sz + z];
val = (val-min)/(max-min)*256;
int shade = (int) val;
int col = shade | (shade<<8) | (shade<<16);
if(shade < 0 || shade > 255)
col = 0x000000FF;
res.setRGB(x, z, col);
}
return res;
}
|
cc970716-eb2a-4782-801e-3406efcc0cbd
| 1 |
private void setTransform(boolean slide) {
if(slide) {
slideTransform.x = getBounds().getX();
slideTransform.y = getBounds().getY();
} else {
slideTransform.x = (getBounds().getX() + (getBounds().getWidth() * value) - (SpriteList.get(sliderKnob).getWidth() / 2f));
slideTransform.y = getBounds().getY();
}
}
|
8351b62f-c6fb-495f-adba-9910815a18bc
| 6 |
public static void main(String[] args) {
if (args.length <= 0) {
System.out.println("At least one arg (pebbler project) must be" +
"specified");
}
// Quarter-assed flag parsing.
String projectFileName = args[0];
String nextFlag = args.length > 1 ? args[1] : "";
boolean createBook = nextFlag.equals("--createBook") ? true : false;
File projectFile = new File(projectFileName);
if (!projectFile.exists() || !projectFile.isFile()) {
System.out.println("Couldn't find file: " + projectFile.getPath());
System.exit(-1);
}
System.out.println("Getting file from: " + projectFile.getPath());
PebblerProject project = PebblerProject.fromJson(
silentRead(projectFile));
File fullFile = new File(projectFile.getAbsolutePath());
String fullPath = fullFile.getParentFile().getAbsolutePath();
project.compile(fullPath);
if (createBook) {
TypeSetter typeSetter = new TypeSetter(project);
typeSetter.createBook(fullPath);
}
}
|
7124da5b-2f6b-4020-9af6-84046ad44d83
| 2 |
@Override
protected MultiLevelCache getCurrentLevelCache(String poolName) {
String upperCase = poolName.toUpperCase();
SockIOPool pool = SockIOPool.getInstance(upperCase);
if (!pool.isInitialized()) {
try {
initializePool(pool);
} catch (Exception e) {
throw new CacheUnreachableException("创建Memcached实例失败");
}
}
return initializeClient(upperCase);
}
|
b697bec4-bd42-4088-8955-f231aa7c544d
| 7 |
private String[] findLinks(String pageHTML, String currentPageURL){
System.err.println("FindLinks : " + pageHTML);
ArrayList<String>links = new ArrayList<String>();
//imgur has changed their html classes, we'll use this to make changes easier
String postDelimiter = "id=\"imagelist";
if(pageHTML.contains(postDelimiter)){
sindex = pageHTML.indexOf(postDelimiter); //find where posts start
int oldsindex = sindex;
links.add(getNextLink(pageHTML)); //adds the next link to list
while(sindex >= oldsindex){
oldsindex = sindex;
links.add(getNextLink(pageHTML)); //adds the next link to list
updateStats();
if(queue.size() >= QUEUE_THRESH*2){
try {
//System.err.println("Main BIG Sleeping: " + TIME_PAUSE*queue.size()*queue.size());
Thread.sleep(TIME_PAUSE*queue.size()*queue.size());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(queue.size() >= QUEUE_THRESH){
try {
//System.err.println("Main Little Sleeping: " + TIME_PAUSE*queue.size());
Thread.sleep(TIME_PAUSE*queue.size());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
String[] foundLinks = new String[links.size()-1];
for(int i = 0; i < links.size()-1; i++){
foundLinks[i] = "http://";
foundLinks[i] += links.get(i);
}
return foundLinks;
}
|
84890313-c3c9-4fe8-8bd2-4c5c0ac14883
| 9 |
public void drawTrade(Graphics g)
{
g.setColor(new Color(255,126,0,200));
g.fillRect(0,0,getWidth(),getHeight());
g.setFont(new Font("Sanserif",Font.BOLD,18));
g.setColor(Color.WHITE);
g.drawString("You",50,70);
try
{
for(int i=0; i<partyPokemon.length; i++)
{
if(partyPokemon[i]!=null)
g.drawString(partyPokemon[i].nickname,50,20*i+100);
else
g.drawString("--------",50,20*i+100);
}
}
catch(Exception ignored){}
g.drawImage(icon,30,offerIndex*20+85,16,16,this);
if(tradeConfirm)
{
g.drawString("Trade!",50,230);
}
g.drawString("Friend: "+friendName,550,70);
try
{
for(int i=0; i<friendPokemon.length; i++)
{
if(!friendPokemon[i].equalsIgnoreCase("null")&&!friendPokemon[i].equals(""))
g.drawString(friendPokemon[i],550,20*i+100);
else
g.drawString("--------",550,20*i+100);
}
}
catch(Exception ignored){}
g.drawImage(icon,530,friendOfferIndex*20+85,16,16,this);
if(friendTradeConfirm)
{
g.drawString("Trade!",550,230);
}
}
|
4c4a281b-3332-4588-ac72-b67eca97b7d8
| 4 |
private static void handle(String argument) {
System.out.println("Handling '" + argument + "':");
Path path = Paths.get(argument);
if (!Files.exists(path)) {
System.out.println("The file '" + path + "' does not exist.");
return;
}
Element diagram;
try (XMLParser parser = new XMLParser(path)) {
diagram = parser.parseDiagram();
} catch (ParserException e) {
System.out.println("Error: " + e.getMessage());
return;
} catch (IOException | XMLStreamException e) {
System.out.println("An error occured while parsing the xml file.");
System.out.println();
e.printStackTrace();
return;
}
Path imagePath = getImagePath(path);
try (OutputStream out = Files.newOutputStream(imagePath)) {
new ImageSaver().save(diagram, out);
} catch (IOException e) {
System.out.println("An error occured while saving the image.");
System.out.println();
e.printStackTrace();
return;
}
System.out.println("Done writing " + imagePath + "!");
}
|
0210492d-eb0f-4618-9f81-a451a5c12bbb
| 4 |
public JSONWriter key(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
if (this.comma) {
this.writer.write(',');
}
this.writer.write(JSONObject.quote(string));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
}
|
684f4f1e-bb72-43a9-8a76-8a5ff1e3b763
| 1 |
public void append(String msg) {
if (win==true){textarea.append(msg+"\n");}
else{System.out.println(msg);}
}
|
aea2f156-7ee7-497c-8c63-d99da502a0c1
| 0 |
@Override
public Tile getTile() {
return tile;
}
|
9049cca5-64b4-4d4a-8f68-c68fb8f8597f
| 0 |
public AnswerCombination getAnswerCombinationFromGameMaster(Combination<Colors> attempt) {
return master.answer(attempt);
}
|
0b1566ea-b3b6-4889-9562-52b85e4026a9
| 1 |
@Test
public void testSerialization() throws IOException{
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ObjectOutputStream objOutput = new ObjectOutputStream(byteOutput);
objOutput.writeObject(alan);
objOutput.close();
ObjectInputStream objInput = new ObjectInputStream(new ByteArrayInputStream(byteOutput.toByteArray()));
Contact readCont = null;
try {
readCont = (Contact) objInput.readObject();
} catch (ClassNotFoundException ex){
ex.printStackTrace();
}
assertEquals(readCont,alan);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.