method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
732ad089-6f7d-4bf7-969e-ccf8c57f50bf | 2 | public Head getHeadByName(String name){
for(Head u : allHeads){
if(u.getName() == name){
return u;
}
}
return null;
} |
34ec175f-28e8-40d8-a08b-c31a6554eb58 | 8 | private void regenerateContent()
{
StringBuilder sb = new StringBuilder();
switch(view)
{
case NOTES:
{
List<Note> notes = mon.getNotes();
content = "";
for(Note n : notes)
{
sb.append(n.getText());
sb.append('\n');
sb.append('\n');
}
content = sb.toString();
break;
}
case QUESTIONS:
{
List<Question> questions = mon.getQuestions();
content = "";
for(Question n : questions)
{
sb.append(n.getText());
sb.append('\n');
sb.append('\n');
}
content = sb.toString();
break;
}
case TAGS:
{
List<Tag> tags = mon.getTags();
content = "";
for(Tag n : tags)
{
sb.append(n.getName());
sb.append('\n');
sb.append('\n');
}
content = sb.toString();
break;
}
case TASKS:
{
List<Task> tags = mon.getTasks();
content = "";
for(Task t : tags)
{
sb.append(t.getText());
sb.append('\n');
sb.append('\n');
}
content = sb.toString();
break;
}
default:
{
break;
}
}
} |
2724c097-7457-49fc-92a5-9655bdf37b05 | 9 | public Queue<String> dobleAgenteXMLUnit (){
try {
path = new File(".").getCanonicalPath();
FileInputStream file =
new FileInputStream(new File(path + "/xml/papabicho.xml"));
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("************************************");
String expression01 = "/Units/Unit[@class='DobleAgente']";
NodeList nodeList;
Node node01 = (Node) xPath.compile(expression01)
.evaluate(xmlDocument, XPathConstants.NODE);
if(null != node01) {
nodeList = node01.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++){
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE){
System.out.println(nodeList.item(i).getNodeName()
+ " : " + nod.getFirstChild().getNodeValue());
list.append(nod.getFirstChild().getNodeValue());
}
}
}
System.out.println("************************************");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
} |
5acda8ea-0b64-4840-8506-411a900e513e | 1 | protected void processWindowEvent(
WindowEvent event )
{
if (event.getID() == WindowEvent.WINDOW_CLOSING)
{
actionCancel();
}
super.processWindowEvent(event);
} |
6c253ebf-4bfe-49e2-9fc7-618d1e66734b | 3 | private void lexicalAnalysis(String sourceCode) {
lexer = new EsperLexer(new ANTLRStringStream(sourceCode));
lexerSuccess = (lexerErrors = lexer.getNumberOfSyntaxErrors()) <= 0;
//Print output
if (flagLexerOutput) {
System.out.println("Lexer output: ");
Token token;
EsperLexer tokensOut = new EsperLexer(new ANTLRStringStream(sourceCode));
while ((token = tokensOut.nextToken()).getType() != -1) {
// Ignore whitespace
if (token.getType() != EsperLexer.WHITESPACE)
System.out.println("Token: " + token.getText() + " | "
+ getTokenName(token.getType()));
}
}
} |
462b4111-a223-4b7b-a364-2037d3b20b84 | 1 | public static MultipleChoiceQuestion getQuestionByQuestionID(int questionID) {
try {
String statement = new String("SELECT * FROM " + DBTable + " WHERE questionid = ?");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement);
stmt.setInt(1, questionID);
ResultSet rs = stmt.executeQuery();
rs.next();
ArrayList<String> questionStringList = getParsedStrings(rs.getString("question"));
String answerString = rs.getString("answer");
MultipleChoiceQuestion q = new MultipleChoiceQuestion(
rs.getInt("questionid"), rs.getInt("quizid"), rs.getInt("position"),
questionStringList, answerString, rs.getDouble("score"));
rs.close();
return q;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
} |
375eb57d-ab37-4b76-968f-e947654c9305 | 5 | public void reservedItem()
{
int tjek = 0;
for (int i = 0; i < orderlistWithDate.size(); i++)
{
for (int j = 0; j < orderlistWithDate.get(i).getItemlist().size(); j++)
{
for (int k = 0; k < itemlistReserved.size(); k++)
{
if (itemlistReserved.get(k).getItemNo() == orderlistWithDate.get(i).getItemlist().get(j).getItemNo())
{
itemlistReserved.get(k).setItemAmount(itemlistReserved.get(k).getItemAmount() + orderlistWithDate.get(i).getItemlist().get(j).getItemAmount());
tjek++;
}
}
if (tjek == 0)
{
itemlistReserved.add(orderlistWithDate.get(i).getItemlist().get(j));
}
tjek = 0;
}
}
loadAllOrders();
} |
65609140-f36b-49d0-a1f9-eb6111c2b166 | 1 | @Test
public void add_test() {
try{
double [][]mat1= {{1.0,2.0}, {3.0,1.0}};
double [][]mat2= {{2.0,1.0}, {1.0,3.0}};
double [][]result = Matrix.add(mat1, mat2);
double exp[][]={{3.0,3.0}, {4.0,4.0}};
Assert.assertEquals(result, exp);
}
catch (Exception e) {
// TODO Auto-generated catch block
fail("Not yet implemented");
}
} |
27a088e5-9cfd-450c-9926-efafd9e549ea | 9 | public List<TravelDataBean> getBoardCommentaryList(int idx) throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<TravelDataBean> commList = null;
String sql = "";
TravelDataBean comm = null;
try{
conn = getConnection();
sql = "select * from travelcommentary where idx=? order by num desc";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, idx);
rs = pstmt.executeQuery();
if(rs.next()){
commList = new ArrayList<TravelDataBean>();
do{
comm = new TravelDataBean();
comm.setComm_content(rs.getString("content"));
comm.setComm_nickname(rs.getString("nickname"));
comm.setComm_wdate(rs.getTimestamp("wdate"));
commList.add(comm);
}
while(rs.next());
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(rs!=null)try{rs.close();}catch(SQLException ex){}
if(pstmt!=null)try{pstmt.close();}catch(SQLException ex){}
if(conn!=null)try{conn.close();}catch(SQLException ex){}
}
return commList;
} |
6654c9b7-7d63-40c2-a332-ee87f5212612 | 7 | private long locateIP(byte[] ip) {
long m = 0;
int r;
// 比较第一个ip项
readIP(ipBegin, b4);
r = compareIP(ip, b4);
if (r == 0) return ipBegin;
else if (r < 0) return -1;
// 开始二分搜索
for (long i = ipBegin, j = ipEnd; i < j; ) {
m = getMiddleOffset(i, j);
readIP(m, b4);
r = compareIP(ip, b4);
// log.debug(Utils.getIpStringFromBytes(b));
if (r > 0)
i = m;
else if (r < 0) {
if (m == j) {
j -= IP_RECORD_LENGTH;
m = j;
} else
j = m;
} else
return readLong3(m + 4);
}
// 如果循环结束了,那么i和j必定是相等的,这个记录为最可能的记录,但是并非
// 肯定就是,还要检查一下,如果是,就返回结束地址区的绝对偏移
m = readLong3(m + 4);
readIP(m, b4);
r = compareIP(ip, b4);
if (r <= 0) return m;
else return -1;
} |
342be706-3f98-4e8d-a8b9-a50184155a54 | 0 | public long getCrc32() {
return crc32.getValue();
} |
9d8f80c1-22fd-42ac-b963-5496de1f76e1 | 4 | public static Side toSide( EndPointPosition position ){
switch( position ){
case LEFT: return Side.WEST;
case RIGHT: return Side.EAST;
case TOP: return Side.NORTH;
case BOTTOM: return Side.SOUTH;
default: throw new IllegalArgumentException();
}
} |
b9db25cc-1b61-4998-89c9-e07d07904290 | 2 | private void calculateEnabledState(JoeTree tree) {
if (tree.getComponentFocus() == OutlineLayoutManager.ICON) {
setEnabled(true);
} else {
if (tree.getCursorPosition() == tree.getCursorMarkPosition()) {
setEnabled(false);
} else {
setEnabled(true);
}
}
} |
71d629c5-6d98-4a6d-95b5-47d47182285d | 6 | public boolean func_48135_b(EntityAnimal par1EntityAnimal)
{
if (par1EntityAnimal == this)
{
return false;
}
else if (!this.isTamed())
{
return false;
}
else if (!(par1EntityAnimal instanceof EntityWolf))
{
return false;
}
else
{
EntityWolf var2 = (EntityWolf)par1EntityAnimal;
return !var2.isTamed() ? false : (var2.isSitting() ? false : this.isInLove() && var2.isInLove());
}
} |
97d9523f-9824-4434-b164-dc440c2435cd | 1 | public BreakBlock(BreakableBlock breaksBlock, boolean needsLabel) {
this.breaksBlock = (StructuredBlock) breaksBlock;
breaksBlock.setBreaked();
if (needsLabel)
label = breaksBlock.getLabel();
else
label = null;
} |
8e2b29a7-3ad6-426e-a0a1-a5e48d533d85 | 9 | public void checkOldGoals() {
LinkedList<Formula> temp = new LinkedList<Formula>();
Formula f;
while(!proven && !incompleteGoals.isEmpty()) {
f = incompleteGoals.poll();
Boolean clear = false;
for(Goal g : f.possibleGoals) {
if(inKnowledge(g.directGoals)) {
clear = true;
try {
Deduction d = g.rule.getConstructor(Formula.class).newInstance(f);
for(Formula know : getKnowledge()) {
for(Formula premise : g.directGoals) {
if(premise.equals(know)) {
d.addPremise(know);
}
}
}
add(d);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if(clear) {
f.possibleGoals.clear();
} else {
temp.add(f);
}
}
incompleteGoals = temp;
//TODO: Proof goals?
} |
51729c3e-2ce6-4573-9e4c-e9d00f7a67d9 | 6 | public void paste(String destinationPath) {
System.out.println("Paste requested to : " + destinationPath);
File destination = new File(destinationPath);
if (!destination.isDirectory()) {return;}
//If it is a new paste, we restart the queue stats
if (!busy) {
this.queueTotalSize = 0;
this.queueCurrentSize = 0;
}
Basket basketBackup = this.basket ;
this.basket = new Basket();
Iterator<String> basketContent = basketBackup.getIterator();
String filePath;
File item2add;
while (basketContent.hasNext()) {
filePath = basketContent.next();
item2add = new File(filePath);
if ((Configuration.symbolicLinkAction == 0) || isNotLink(item2add)) {
if (!item2add.isDirectory()) { //if the item is a file
System.out.println("adding file to main queue");
addFile2Queue(new FileToTransfer(filePath,destinationPath));
} else { //the item is a folder
//System.out.println("adding folder to main queue");
this.addFolder2Queue(item2add,destinationPath);
}
}
}
//We launch the treatment anyway, it will exit by
//itself if necessary
forceStart();
} |
b5852f6a-f70c-475a-952e-23d2328bb22e | 0 | protected void onUserList(String channel, User[] users) {} |
66dedcfe-8a09-45ec-8cb0-1c164596b704 | 3 | public void depthFirstTraversal()
{
boolean[] visited;
visited = new boolean[gSize];
for (int index = 0; index < gSize; index++)
visited[index] = false;
for (int index = 0; index < gSize; index++)
if (!visited[index])
dft(index, visited);
} |
8e782711-ec80-4f11-af7f-9ead289130fb | 0 | protected final static Logger getLogger() {
return LoggerFactory.getLogger(ConfigManager.class);
} |
cbb0ec56-8d3b-4c75-bf73-c46af752ab55 | 4 | @Override
public boolean activate() {
return (!Bank.isOpen()
&& !validate(Constants.WAITFOR_WIDGET)
&& !Widgets.get(13, 0).isOnScreen()
&& Inventory.contains(Settings.itemOneID)
&& Settings.usingHerb
);
} |
593204aa-fcf5-4c15-8e25-3b49b1ebac37 | 9 | @Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
if((msg.amITarget(this)
||((msg.tool()==this)&&(msg.target() instanceof Container)))
&&((getPackageFlagsBitmap()&PACKAGE_FLAG_TO_ITEMS_PROGRAMMATICALLY)==0)
&&((msg.targetMinor()==CMMsg.TYP_GET)||(msg.targetMinor()==CMMsg.TYP_DROP)))
{
ItemPossessor possessor = owner();
if((msg.targetMinor()==CMMsg.TYP_DROP)&&(msg.target() instanceof Room))
possessor=(Room)msg.target();
List<Item> items = unPackage(Integer.MAX_VALUE);
for(Item I : items)
possessor.addItem(I, ItemPossessor.Expire.Player_Drop);
destroy();
return;
}
super.executeMsg(myHost,msg);
} |
57317e26-fe33-4d83-b2b8-2ad9af176b37 | 2 | public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = new File(CONFIG_FILE);
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
} |
a8e20a47-4d4c-402e-8be1-919c56a136b3 | 6 | private void resize() {
size = getSkinnable().getWidth() < getSkinnable().getHeight() ? getSkinnable().getWidth() : getSkinnable().getHeight();
width = getSkinnable().getWidth();
height = getSkinnable().getHeight();
if (getSkinnable().isKeepAspect()) {
if (aspectRatio * width > height) {
width = 1 / (aspectRatio / height);
} else if (1 / (aspectRatio / height) > width) {
height = aspectRatio * width;
}
}
if (width > 0 && height > 0) {
segmentA1.setPrefSize(0.373134328358209 * width, 0.07282913165266107 * height);
segmentA1.setTranslateX(0.11567164179104478 * width);
segmentA2.setPrefSize(0.376865671641791 * width, 0.07282913165266107 * height);
segmentA2.setTranslateX(0.4962686567164179 * width);
segmentB.setPrefSize(0.14185691947367654 * width, 0.4743288184414391 * height);
segmentB.setTranslateX(0.7648594984367713 * width);
segmentB.setTranslateY(0.02474666777111235 * height);
segmentC.setPrefSize(0.14191687285010493 * width, 0.480032570889684 * height);
segmentC.setTranslateX(0.7200879338961929 * width);
segmentC.setTranslateY(0.5008913782798275 * height);
segmentD2.setPrefSize(0.3656716417910448 * width, 0.07282913165266107 * height);
segmentD2.setTranslateX(0.4216417910447761 * width);
segmentD2.setTranslateY(0.927170868347339 * height);
segmentD1.setPrefSize(0.3694029850746269 * width, 0.07282913165266107 * height);
segmentD1.setTranslateX(0.03731343283582089 * width);
segmentD1.setTranslateY(0.927170868347339 * height);
segmentE.setPrefSize(0.1381160536808754 * width, 0.4744872192040879 * height);
segmentE.setTranslateY(0.5008564583059787 * height);
segmentF.setPrefSize(0.14191658817120453 * width, 0.4800337676574536 * height);
segmentF.setTranslateX(0.04471146170772723 * width);
segmentF.setTranslateY(0.019075994731999245 * height);
segmentG.setPrefSize(0.26232508759000406 * width, 0.41364670868347336 * height);
segmentG.setTranslateX(0.17906029544659516 * width);
segmentG.setTranslateY(0.07340313139415923 * height);
segmentH.setPrefSize(0.13067467532940766 * width, 0.4583017472125569 * height);
segmentH.setTranslateX(0.41043147756092585 * width);
segmentH.setTranslateY(0.038707604929178706 * height);
segmentI.setPrefSize(0.33435482765311625 * width, 0.4141186198600534 * height);
segmentI.setTranslateX(0.46448468450290054 * width);
segmentI.setTranslateY(0.0736752731793401 * height);
segmentK.setPrefSize(0.3523415238109987 * width, 0.07563025210084033 * height);
segmentK.setTranslateX(0.45818246300540755 * width);
segmentK.setTranslateY(0.46218487394957986 * height);
segmentL.setPrefSize(0.25479484671977026 * width, 0.4144776074492297 * height);
segmentL.setTranslateX(0.465354407011573 * width);
segmentL.setTranslateY(0.5128619196702119 * height);
segmentM.setPrefSize(0.13061295694379665 * width, 0.46119950665813203 * height);
segmentM.setTranslateX(0.3656716417910448 * width);
segmentM.setTranslateY(0.5000929204689688 * height);
segmentN.setPrefSize(0.33414425067047576 * width, 0.4139740246684611 * height);
segmentN.setTranslateX(0.10799379491094332 * width);
segmentN.setTranslateY(0.5122721696100315 * height);
segmentP.setPrefSize(0.34861020899530665 * width, 0.07563025210084033 * height);
segmentP.setTranslateX(0.09992373879276105 * width);
segmentP.setTranslateY(0.46218487394957986 * height);
segmentDot.setPrefSize(0.13432835820895522 * width, 0.10084033613445378 * height);
segmentDot.setTranslateX(0.8656716417910447 * width);
segmentDot.setTranslateY(0.8991596638655462 * height);
}
} |
fdfe6f34-d83c-4b99-936c-33f463d2ac62 | 1 | public void visit_i2c(final Instruction inst) {
stackHeight -= 1;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} |
15b84ac9-72f1-4930-9d79-0d21e7a49bdd | 7 | public static void OBRADI_odnosni_izraz(boolean staviNaStog){
String linija = mParser.ParsirajNovuLiniju();
int trenLabela = mBrojacLabela++;
if (linija.equals("<aditivni_izraz>")){
OBRADI_aditivni_izraz(staviNaStog);
return;
}
if (linija.equals("<odnosni_izraz>")){
OBRADI_odnosni_izraz(true);
linija = mParser.ParsirajNovuLiniju(); // ucitaj (OP_LT | OP_GT | OP_LTE | OP_GTE)
UniformniZnak uz_operator = UniformniZnak.SigurnoStvaranje(linija);
linija = mParser.ParsirajNovuLiniju(); // ucitaj <aditivni_izraz>
OBRADI_aditivni_izraz(true);
mIspisivac.DodajKod("POP R1", "odnosni izraz " + uz_operator.mLeksickaJedinka + ": pocetak");
mIspisivac.DodajKod("POP R0");
if (uz_operator.mNaziv.equals("OP_LT")){
mIspisivac.DodajKod("CMP R0, R1", "usporedba");
mIspisivac.DodajKod("JR_SLT OI_ISTINA_" + trenLabela, "skoci na OI_ISTINA_ ako je R0 manji");
}else if (uz_operator.mNaziv.equals("OP_GT")){
mIspisivac.DodajKod("CMP R0, R1", "usporedba");
mIspisivac.DodajKod("JR_SGT OI_ISTINA_" + trenLabela, "skoci na OI_ISTINA_ ako je R0 veci");
}else if (uz_operator.mNaziv.equals("OP_LTE")){
mIspisivac.DodajKod("CMP R0, R1", "usporedba");
mIspisivac.DodajKod("JR_SLE OI_ISTINA_" + trenLabela, "skoci na OI_ISTINA_ ako je R0 manji ili jednak");
}else if (uz_operator.mNaziv.equals("OP_GTE")){
mIspisivac.DodajKod("CMP R0, R1", "usporedba");
mIspisivac.DodajKod("JR_SGE OI_ISTINA_" + trenLabela, "skoci na OI_ISTINA_ ako je R0 veci ili jednak");
}
mIspisivac.DodajKod("MOVE %D 0, R0", "izraz nije istinit");
mIspisivac.DodajKod("JR OI_DALJE_" + trenLabela, "preskoci postavljanje R0 u 1");
mIspisivac.PostaviSljedecuLabelu("OI_ISTINA_" + trenLabela);
mIspisivac.DodajKod("MOVE %D 1, R0", "izraz je istinit");
mIspisivac.PostaviSljedecuLabelu("OI_DALJE_" + trenLabela);
// makni 2 sa stoga i stavi novi ako je potrebno
NaredbenaStrukturaPrograma.mStog.remove(NaredbenaStrukturaPrograma.mStog.size()-1);
NaredbenaStrukturaPrograma.mStog.remove(NaredbenaStrukturaPrograma.mStog.size()-1);
if (staviNaStog){
mIspisivac.DodajKod("PUSH R0", "odnosni izraz: postavi rezultat na stog");
Ime_Velicina_Adresa novi = new Ime_Velicina_Adresa();
novi.mIme = null;
novi.mAdresa = false;
novi.mVelicina = 4;
NaredbenaStrukturaPrograma.mStog.add(novi);
}
return;
}
} |
f398ec9d-4ca4-46f6-a100-9aed1a5a94ba | 2 | public DiscreteUniform(int low, int high) throws ParameterException {
if (low < 1 || high <= low) {
throw new ParameterException("DiscreteUniform parameters a in N, b > a.");
} else {
this.low = low;
this.high = high;
unif = new ContinuousUniform(low, high + 1);
}
} |
96a20c9a-5861-4a12-92a1-b3cd6014bc76 | 7 | public boolean ComboBad( int col, int row, int val ) {
// check the row
for (int n = 0; n < 9; n++ ) {
if ( _board[row][n] == val ) {
System.out.println("Oops, there is already a " + val + " in row " + converter( row ) );
System.out.println("Try again!");
pause( 1 );
return true;
}
}
// check the column
for (int i = 0; i < 9; i++ ) {
if ( _board[i][col] == val ) {
System.out.println("Oops, there is already a " + val + " in column " + (col + 1) );
System.out.println("Try again!");
pause( 1 );
return true;
}
}
int firstRow = getFirst( row );
int firstCol = getFirst( col );
// check the square
for (int i = firstRow; i < (firstRow + 3); i++) {
for (int n = firstCol; n < (firstCol + 3); n++) {
if ( _board[i][n] == val ) {
System.out.println("Oops, there is already a " + val + " in that square");
System.out.println("Try again!");
pause( 1 );
return true;
}
}
}
return false;
} |
9b6fc0da-9a0a-4fbc-a69d-576792f954ae | 9 | private boolean checkTimer(String currentWeapon){
if (currentWeapon.equals("MachineGun")){
if (machineTimer < 0){
machineTimer = 10;
return true;
} else {return false;}
} else if (currentWeapon.equals("Pistol")){
return true;
}else if (currentWeapon.equals("Crowbar")){
if (crowbarTimer < 0){
crowbarTimer = 30;
return true;
} else {return false;}
} else if (currentWeapon.equals("Revolver")){
if (revolverTimer < 0){
revolverTimer = 30;
return true;
} else {return false;}
} else if (currentWeapon.equals("Shotgun")){
if (shotgunTimer < 0){
shotgunTimer = 30;
return true;
} else {return false;}
}
return false;
} |
8658156e-b686-444b-9a99-fefc5c9e3379 | 6 | public static void main(String[] args)
{
double[] a = new double[6];
int[] m = new int[6];
int s=0;
obrobka.test(args, a);
//
for (int i = 0; i < 6; i++){
int x = (int) a[i];
double y = a[i] - x;
if (y!=0){
s++;// , ;
} }
if(s==0){// ,
for (int i = 1; i < 6; i++){
m[i]=(int) a[i];
}
System.out.println(" int = " + getSumNumbers(m));
System.out.println("г int = " +getDiffNumbers(m));
System.out.println(" int = " +getProdNumbers(m));
System.out.println("Max int = " +getMaxNumbers(m));
System.out.println("Min int = " +getMinNumbers(m));
System.out.println(" int = " +getAverNumbers(m));
} else{// ,
//
System.out.print("[");
for (int i = 1; i < 6; i++){
System.out.print (a[i]+" ");
}
System.out.println("]");
System.out.println(" double = " + getSumNumbers(a));
System.out.println("г double = " +getDiffNumbers(a));
System.out.println(" double = " +getProdNumbers(a));
System.out.println("Max double = " +getMaxNumbers(a));
System.out.println("Min double = " +getMinNumbers(a));
System.out.println(" double = " +getAverNumbers(a));
}
//
System.out.print("[");
for (int i = 1; i < 6; i++){
System.out.print (m[i]+" ");
}
System.out.println("]");
} |
993d1064-2db3-4145-b49c-6152c259fdfc | 6 | static void merge(int[] leftArray, int[] rightArray, int[] newArray) {
int i = 0, j = 0, k = 0;
int leftLength = leftArray.length;
int rightLength = rightArray.length;
// Compare left and right and put the smaller value in the new array
while(i < leftLength && j < rightLength) {
if(leftArray[i] <= rightArray[j]) {
newArray[k] = leftArray[i];
i++;
}
else {
newArray[k] = rightArray[j];
j++;
}
k++;
}
// Work on the remaining elements on the left or right
while(i < leftLength) {
newArray[k] = leftArray[i];
i++;
k++;
}
while(j < rightLength) {
newArray[k] = rightArray[j];
j++;
k++;
}
System.out.println("=====================Sorting Complete=================");
for(int element : newArray) {
System.out.println(element);
}
} |
b8286fa6-0bd2-444f-953c-a902fef2c247 | 4 | @Override
public void addRow(IRow row) {
Sheet sheet = wb.getSheet(row.getSheetName());
if (sheet == null) {
sheet = wb.createSheet(row.getSheetName());
}
final int lastRow = sheet.getLastRowNum();
Row r = sheet.getRow(lastRow);
if (r == null) {
//we're here if this is the first row in the sheet
r = sheet.createRow(lastRow);
} else {
//we're here if the row already existed, create the next one
r = sheet.createRow(lastRow + 1);
}
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, "Adding row {0} to sheet {1}",
new Object[]{r.getRowNum(), sheet.getSheetName()});
}
for (ICell cell : row) {
Cell c = r.createCell(cell.getColumnNum());
c.setCellValue(cell.getValue());
}
} |
4e741a38-8f6d-4921-8fae-e8cac4983447 | 3 | private void go(){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
HashMap<Integer, HashMap<Integer, Integer>> g = new HashMap<Integer, HashMap<Integer, Integer>>();
int[] dist = new int[n+1];
for(int i=1;i<=n;i++){
dist[i]=Integer.MAX_VALUE;
g.put(i, new HashMap<Integer, Integer>());
}
for(int i=0;i<m;i++){
int a = in.nextInt();
int b = in.nextInt();
int edge = in.nextInt();
g.get(a).put(b, edge);
}
bellmanFord(4, dist, g);
for(int i=1;i<=n;i++){
System.out.printf("Node %d has shortest distance %d\n", i, dist[i]);
}
} |
0b58a292-e3f2-48ca-aeb6-30bf4cd6a555 | 9 | public MakingOffer makeOffer(Offer offer, PlayerPtrVector allPlayers,
News news) {
// called by CheckBuying() of own team, or by GUI
if (offer.getPlayer().getContracts().getNextContr().getTeam() != null
|| offer.getBuyer().equals(offer.getPlayer().getContracts().getCurrContr()
.getTeam())) {
// has already a new contract or same team
return MakingOffer.FAILED;
}
// unsigned
int nofOffers = getNofBuyNegOffers();
for (int i = 0; i < nofOffers; i++) {
Offer alreadyOffer = getBuyNegOffer(i);
if (offer.getPlayer().equals(alreadyOffer.getPlayer())) {
// already a pending offer to same player
return MakingOffer.FAILED;
}
}
if (offer.getSeller() == null) {
// free agent
// NYI AI of the free agent
if (Util.random(3) == 0
&& buyerNofPlayers(offer, allPlayers) < Team.TEAM_MAXTEAMPLAYER
+ Team.TEAM_MAXFARMPLAYER) {
String s = news.getTransfers();
s += offer.getPlayer().getLastName();
s += Util.getModelResourceBundle().getString("L_SIGNS_AT");
s += offer.getBuyer().getTeamName();
if (offer.isImmediately()) {
offer.getPlayer().getContracts().setCurrContr(new Contracts.TContract(
offer.getBuyer()));
offer.getPlayer().getContracts().setCurrContrYears(offer.getYears());
offer.getPlayer().getContracts().setCurrContrWage(offer.getWage());
offer.getPlayer().calcFee(false); // calc new fee after transferring
offer.getBuyer().addPlayer(offer.getPlayer());
s += Util.getModelResourceBundle().getString("L_IMMEDIATELY");
s += "\n";
news.setTransfers(s);
return MakingOffer.ACCEPTED_AND_DONE;
} else {
offer.getPlayer().getContracts().setNextContr(new Contracts.TContract(
offer.getBuyer()));
offer.getPlayer().getContracts().setNextContrYears(offer.getYears());
offer.getPlayer().getContracts().setNextContrWage(offer.getWage());
s += Util.getModelResourceBundle().getString("L_FOR_NEXT_SEASON");
s += "\n";
news.setTransfers(s);
return MakingOffer.ACCEPTED;
}
} else {
offer.getPlayer().getContracts().setNoContractThisRound(true);
return MakingOffer.FAILED;
}
} else {
buyNeg.add(offer);
offer.getSeller().getTransfer().sellNeg.add(offer);
String s;
s = offer.getBuyer().getTeamName();
s += Util.getModelResourceBundle().getString("L_IS_INTERESTED_IN");
if (offer.getPlayer().isMultipleName()) {
s += offer.getPlayer().getFirstName();
s += " ";
}
s += offer.getPlayer().getLastName();
offer.getSeller().getMessages().add(s);
}
return MakingOffer.SUCCEED;
} |
d941efa0-33ab-45c1-a66a-946aac1b761f | 5 | private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15ActionPerformed
// TODO add your handling code here:
liceu.Administrator admin = new liceu.Administrator(usernameElev.getText(), parolaElev.getText(),ncElev.getText(),cnpElev.getText(),"Elev",(String)clasaElev.getSelectedItem());
admin.addUser();
usernameElev.setText("");
parolaElev.setText("");
ncElev.setText("");
cnpElev.setText("");
int i;
BufferedReader fisier;
try {
fisier = new BufferedReader(new FileReader("credentials"));
listModelElevi.clear();
ArrayList<String> vector = new ArrayList<>();
for(String line; (line = fisier.readLine())!= null;){
vector.add(line);
}
for(i=0;i<vector.size();i=i+5){
if(vector.get(i+4).equals("Elev"))
listModelElevi.addElement(vector.get(i));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Administratorapp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Administratorapp.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton15ActionPerformed |
670597aa-3cd9-49d9-b9e7-b28285c55cd3 | 4 | public void toXML(){
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document out = docBuilder.newDocument();
Element rootElem = out.createElement("bill");
out.appendChild(rootElem);
for (Device dev : dept.getEquip()) {
rootElem.appendChild(createNode(dev, dev.getName(), out));
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource dom = new DOMSource(out);
StreamResult result = new StreamResult(new File("out.xml"));
transformer.transform(dom, result);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e){
e.printStackTrace();
} catch (TransformerException e){
e.printStackTrace();
}
} |
7e5579a1-4a7a-44c0-80eb-5a0453ed231a | 5 | public static void main(String[] args) throws FileNotFoundException {
String masterName = "masterServer";
String masterAdd = args[0];
int masterPort = new Integer(args[1]);
String dir = args[2];
File metaData = new File("metaData.txt");
File repServers = new File("repServers.txt");
TreeMap<String, ReplicaLoc> nameToLocMap = new TreeMap<String, ReplicaLoc>();
Scanner scanner = new Scanner(repServers);
while (scanner.hasNext()) {
String repName = scanner.next(), repAddress = scanner.next();
int repPort = scanner.nextInt();
nameToLocMap.put(repName, new ReplicaLoc(repAddress, repName,
repPort));
}
scanner.close();
try {
Registry registry = null;
try {
registry = LocateRegistry.createRegistry(masterPort);
} catch (Exception e) {
registry = LocateRegistry.getRegistry(masterPort);
}
MasterServerImpl masterServerObj = new MasterServerImpl(metaData,
nameToLocMap);
MasterServerClientInterface masterServerStub = (MasterServerClientInterface) UnicastRemoteObject
.exportObject(masterServerObj, 0);
registry.bind(masterName, masterServerStub);
} catch (Exception e) {
e.printStackTrace();
}
// pkill -f 'java.*ReplicaServerImpl'
try {
for (ReplicaLoc repLoc : nameToLocMap.values()) {
Process p = Runtime.getRuntime()
.exec("ssh " + repLoc.getHost());
PrintStream out = new PrintStream(p.getOutputStream(), true);
StreamReader ls = new StreamReader(p.getInputStream(), false);
StreamReader es = new StreamReader(p.getErrorStream(), true);
Thread t = new Thread(ls);
Thread t2 = new Thread(es);
t.start();
t2.start();
out.println("cd workspace/ReplicatedFS/src");
out.println("javac API/ReplicaServerClientInterface.java Impl/ReplicaServerImpl.java");
// args: name dir port masterName masterAddress masterPort
out.println("java Impl/ReplicaServerImpl " + repLoc.getName()
+ " " + dir + " " + repLoc.getPort() + " " + masterName
+ " " + masterAdd + " " + masterPort);
out.println("exit");
// t.join();
// t2.join();
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} |
2fb2f7fb-459f-463b-9552-a122869a45b8 | 7 | public static String timeIntervalToString(long millis) {
StringBuffer sb = new StringBuffer();
if (millis < 10 * Constants.SECOND) {
sb.append(millis);
sb.append("ms");
} else {
boolean force = false;
String stop = null;
for (int ix = 0; ix < units.length; ix++) {
UD iu = units[ix];
long n = millis / iu.millis;
if (force || n >= iu.threshold) {
millis %= iu.millis;
sb.append(n);
sb.append(iu.str);
force = true;
if (stop == null) {
if (iu.stop != null) {
stop = iu.stop;
}
} else {
if (stop.equals(iu.str)) {
break;
}
}
}
}
}
return sb.toString();
} |
df19d458-1590-445d-ab43-b9c3c8737a10 | 7 | public Object showEduFwContent() {
String cmd = "show;eduframework";
ArrayList<String> list = null;
String[][] content = null;
try {
NetService client = initNetService();
client.sendCommand(cmd);
list = client.receiveList();
client.shutDownConnection();
content = new String[list.size()][];
if (list.isEmpty()) {
return Feedback.LIST_EMPTY;
}
for (int i = 0; i < list.size(); i++) {
content[i] = list.get(i).split(";");
}
for (int i = 0; i < content.length; i++) {
for (int j = 0; j < content[i].length; j++) {
if (content[i][j].equals("null")) {
content[i][j] = "";
} else if (content[i][j].contains("0-0")) {
content[i][j] = content[i][j].replaceAll("0-0", "");
}
}
}
return content;
} catch (Exception e) {
e.printStackTrace();
return Feedback.INTERNET_ERROR;
}
} |
66751a59-ab20-4829-8be4-57678d50300c | 8 | public void createPlanetsPanel() {
planetsPanel.setLayout(new GridLayout(2, 2));
JPanel OU = new JPanel(); // OU Start
OU.setLayout(new BoxLayout(OU, BoxLayout.Y_AXIS));
JLabel OUPic = new JLabel(new ImageIcon("Icons/OU2.png"));
OUPic.setAlignmentX(CENTER_ALIGNMENT);
OU.add(OUPic);
JLabel OUTitleLabel = new JLabel("Ora Uhlsax"); // title start
OUTitleLabel.setFont(getFont("OTitle", 25).deriveFont(Font.ITALIC));
OUTitleLabel.setAlignmentX(CENTER_ALIGNMENT);
OU.add(OUTitleLabel); // title done
if (selectedPlanet == 1) {
if (!playedSound) {
playSound("OUSound.wav");
playedSound = true;
}
OUTitleLabel.setFont(getFont("OTitle", 40).deriveFont(Font.BOLD)); // bold
// it
JTextField OUBio = new JTextField();
OUBio.setText(OUBioText);
OUBio.setFont(getFont("OTitle", 20));
}
planetsPanel.add(OU); // OU Done
// Neslaou Start
JPanel Neslaou = new JPanel();
Neslaou.setLayout(new BoxLayout(Neslaou, BoxLayout.Y_AXIS));
JLabel nIcon = new JLabel(new ImageIcon("Icons/Neslaou.png"));
nIcon.setAlignmentX(CENTER_ALIGNMENT);
Neslaou.add(nIcon);
JLabel nTitle = new JLabel("Neslaou");
nTitle.setFont(getFont("Neslaou", 35).deriveFont(Font.ITALIC));
nTitle.setAlignmentX(CENTER_ALIGNMENT);
Neslaou.add(nTitle);
if (selectedPlanet == 2) {
if (!playedSound) {
playSound("NSound.wav");
playedSound = true;
}
nTitle.setFont(getFont("Neslaou", 60).deriveFont(Font.BOLD)); // bold
// it
JTextField NBio = new JTextField();
NBio.setText(NBioText);
NBio.setFont(getFont("Neslaou", 20));
}
planetsPanel.add(Neslaou); // Neslaou End
JPanel Earth = new JPanel(); // Earth Start
Earth.setLayout(new BoxLayout(Earth, BoxLayout.Y_AXIS));
JLabel eIcon = new JLabel(new ImageIcon("Icons/Earth.png"));
JLabel eTitle = new JLabel("Earth circa 2556 A.D.");
eTitle.setFont(getFont("Earth2", 25).deriveFont(Font.ITALIC));
eIcon.setAlignmentX(CENTER_ALIGNMENT);
eTitle.setAlignmentX(CENTER_ALIGNMENT);
Earth.add(eIcon);
Earth.add(eTitle);
if (selectedPlanet == 3) {
if (!playedSound) {
playSound("ESound.wav");
playedSound = true;
}
eTitle.setFont(getFont("Earth2", 40).deriveFont(Font.BOLD)); // bold
// it
JTextField EBio = new JTextField();
EBio.setText(EBioText);
EBio.setFont(getFont("Earth2", 20));
}
planetsPanel.add(Earth); // Earth End
// Gigolo Start
JPanel Gigolo = new JPanel();
Gigolo.setLayout(new BoxLayout(Gigolo, BoxLayout.Y_AXIS));
JLabel gIcon = new JLabel(new ImageIcon("Icons/Gigolo.png"));
JLabel gTitle = new JLabel("Gigolo");
gTitle.setFont(getFont("Gigolo", 25).deriveFont(Font.ITALIC));
gIcon.setAlignmentX(CENTER_ALIGNMENT);
gTitle.setAlignmentX(CENTER_ALIGNMENT);
if (selectedPlanet == 4) {
if (!playedSound) {
playSound("GSound.wav");
playedSound = true;
}
gTitle.setFont(getFont("Gigolo", 40).deriveFont(Font.BOLD)); // bold
// it
JTextField GBio = new JTextField();
GBio.setText(GBioText);
GBio.setFont(getFont("Gigolo", 20));
}
Gigolo.add(gIcon);
Gigolo.add(gTitle);
planetsPanel.add(Gigolo);
} |
923031ff-ec4a-406a-88de-0706a09e7692 | 0 | public int getZ(){
return zPos;
} |
a9ba333d-537d-40c5-8463-6b317e8691e5 | 9 | public static int getSpace(int i){
switch (i) {
case 1: return space[0][0];
case 2: return space[0][1];
case 3: return space[0][2];
case 4: return space[1][0];
case 5: return space[1][1];
case 6: return space[1][2];
case 7: return space[2][0];
case 8: return space[2][1];
case 9: return space[2][2];
}
return -1;
} |
488b77a4-2526-4ae0-9300-d879a361d4dc | 5 | public void writeToAdjacencyList(ArrayList<Node> network, String file){
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("#Number of nodes:\n" + network.size() + "\n");
out.write("#Node degrees:\n");
for(int i=0;i<network.size();i++)
{
out.write(i + " " + network.get(i).getDegree() + "\n");
}
out.write("#Links:\n");
Set<String> links = new HashSet<String>();
for(Node N : network)
{
for(int i=0;i<N.getDegree();i++)
{
if(!links.contains((N.getNeighbour(i).id + " " + N.id)))
{
links.add((N.id + " " + N.getNeighbour(i).id));
out.write(N.id + " " + N.getNeighbour(i).id + "\n");
}
}
}
out.flush();
out.close();
}
catch (Exception ex)
{
Logger.getLogger(NetworkGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
} |
8b66c7f6-80af-4b86-9426-d18237ebc2d8 | 0 | public Level(String ID, String level){
this.ID = ID;
path = level;
loadLevel(level);
} |
085607ed-8ef2-4ff7-a8a2-70754d235a69 | 2 | public void inserir(long pesquisaId, ArrayList<InstituicaoCooperadora> instituicoesCoopreadoras) throws Exception
{
String sql = "INSERT INTO Pesquisainstituicoes_cooperadoras(id1, id2) VALUES(?, ?)";
try
{
PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql);
for (InstituicaoCooperadora instCoop : instituicoesCoopreadoras)
{
stmt.setLong(1, pesquisaId);
stmt.setLong(2, instCoop.getId());
stmt.execute();
stmt.clearParameters();
}
}
catch (SQLException e)
{
throw e;
}
} |
b7085b20-92d5-4692-9c14-140880f22df9 | 4 | public static void main(String[] args) {
try {
int test = 0;
int rowsA = 10;
int colsA = 10;
int rowsB = colsA;
int colsB = rowsA;
String fileNameOfMatrixA = "A" + rowsA + "x" + colsA + ".txt";
String fileNameOfMatrixB = "B" + rowsB + "x" + colsB + ".txt";
Matrix A = null;
Matrix B = null;
Matrix C = null;
switch (test) {
case 0:
A = MatrixSelector.getMatrix(rowsA, colsA, DataType.DOUBLE);
A.initialize();
A.write(fileNameOfMatrixA);
//A = null;
B = MatrixSelector.getMatrix(rowsB, colsB, DataType.DOUBLE);
B.initialize();
B.write(fileNameOfMatrixB);
//B = null;
System.out.println(A.getDataType().equals(B.getDataType()));
//break;
case 1:
String fileNameOfMatrixCDouble1 = "C" + rowsA + "x" + colsB + "forJavaDouble" + ".txt";
A = MatrixSelector.getMatrix(rowsA, colsA, DataType.INTEGER);
B = MatrixSelector.getMatrix(rowsB, colsB, DataType.INTEGER);
A.read(fileNameOfMatrixA);
B.read(fileNameOfMatrixB);
A.print();
B.print();
C = A.multiply(B);
//C.print();
A = null;
B = null;
C.write(fileNameOfMatrixCDouble1);
C = null;
break;
case 2:
String fileNameOfMatrixCDouble2 = "C" + rowsA + "x" + colsB
+ "forJavaThreadDouble" + ".txt";
A = ReaderMatrix.readFromFile(fileNameOfMatrixA, DataType.DOUBLE);
B = ReaderMatrix.readFromFile(fileNameOfMatrixB, DataType.DOUBLE);
C = A.multiplyThread(B);
C.write(fileNameOfMatrixCDouble2);
//A.print();
//B.print();
//C.print();
break;
}
} catch (Exception x) {
System.out.println(x);
}
} |
5e755e52-4b2f-4928-bcb3-0fd01dcccd8f | 1 | public String getLabelState() {
if (state == DECONNECTED)
return "Déconnecté";
return "Connecté";
} |
a1ae5ed3-e304-4731-adfd-13dd9e55fc86 | 3 | public void shuffle()
{
//System.out.println("Shuffling");
cardsInDeck=cards.clone();
PlayingCard[] cardsNotInPlay=new PlayingCard[cardsInDeck.length];
int cardsOutofPlay=0;
for (PlayingCard c: cards)
{
if(c.placeInDeck())
{
cardsNotInPlay[cardsOutofPlay++]=c;
}
}
cardsInDeck=new PlayingCard[cardsOutofPlay];
for (PlayingCard c:cardsNotInPlay)
{
addCardAtRandom(c);
}
} |
6142c290-8469-4d97-8bdf-1a35d9ec737f | 7 | public static String textForFirstTag(Element element, String tag) {
if (!element.hasChildNodes())
return ""; // Should never happen if we are passed a valid Element
// node
NodeList tagList = element.getChildNodes();
int tagCount = tagList.getLength();
if (0 == tagCount) // No tags
return "";
for (int j = 0; j < tagCount; ++j) {
Node tagNode = tagList.item(j);
if (isMatchingNode(tagNode, tag)) {
// Look at the children of this tag element. There should be
// one or more Text nodes.
NodeList list = tagNode.getChildNodes();
int count = list.getLength();
for (int i = 0; i < count; ++i) {
Node node = list.item(i);
if (node instanceof Text) {
String value = trim((Text) node);
if (!("".equals(value)))
return value; // Return the trim()'d text of the
// first child text node
}
} // for i...
} // if match
} // for j...
return "";
} |
91b2d5da-99ed-42fc-8dbf-adeb19f49fed | 6 | public void stateChanged(ChangeEvent c) {
JSlider s = (JSlider) c.getSource();
if (s == speed) {
Game.gamedata.set_bpm(speed.getValue());
speedL.setText("Speed: " + speed.getValue() + " bpm");
} else if (s == diff) {
Game.gamedata.set_difficulty(diff.getValue());
if (diff.getValue() <= 1) {
System.out.println("I'm sleepy");
// stuff
}if (diff.getValue() <= 2) {
System.out.println("I'm sleepy for realz");
// stuff
} if (diff.getValue() <= 3) {
System.out.println("I'm sleepy for realzies, yo");
// stuff
} else {
// stuff
System.out.println("what am i doing with life");
}
diffL.setText("Difficulty: " + diff.getValue());
} else if (s == key) {
Game.gamedata.set_key(key.getValue());
keyL.setText("Key: " + Interpreter.get_note(key.getValue()));
}
} |
7b34005c-c332-40f4-b7f0-e6ae8a61269e | 1 | public Triple initFile(String fileName, String lang){
com.hp.hpl.jena.graph.Node s = NodeFactory.createURI("http://bla.example.com");
com.hp.hpl.jena.graph.Node p = NodeFactory.createURI("http://bla.example.com/#a");
com.hp.hpl.jena.graph.Node o = NodeFactory.createLiteral(String.valueOf(Math.random()*100));
Triple t = new Triple(s, p, o);
Model m = ModelFactory.createDefaultModel();
Graph g = m.getGraph();
g.add(t);
Model m1 = ModelFactory.createModelForGraph(g);
File f = new File(fileName);
try {
f.createNewFile();
m1.write(new FileOutputStream(f), lang);
} catch (IOException e) {
assertTrue(false);
}
return t;
} |
8bd1b085-aff2-4278-8886-7d15dce944e7 | 4 | private boolean requestCredentialsAndAuthenticate(Callback[] callbacks) throws LoginException
{
boolean authenticated = false;
try
{
callbackHandler.handle(callbacks);
username = ((NameCallback) callbacks[0]).getName();
password = loadPassword((PasswordCallback) callbacks[1]);
if (username == null || password.length == 0)
{
LOG.error("Callback handler does not return login data properly");
throw new LoginException("Callback handler does not return login data properly");
}
JdbcAuthenticationService authService = initAuthenticationService();
authenticated = authService.authenticate(username, new String(password));
}
catch (IOException ex)
{
LOG.error("Error during user login", ex);
throw new LoginException(ex.toString());
}
catch (UnsupportedCallbackException ex)
{
String msg = MessageFormat.format("{0} not available to garner authentication information from the user", ex
.getCallback().toString());
LOG.error(msg);
throw new LoginException("Error: " + msg);
}
return authenticated;
} |
0309e0ea-fb9b-4929-a483-7f19de5f9ebc | 3 | @Override
public Object getParent(Object element) {
if (element instanceof IFile) {
IFile file = (IFile) element;
return file.getProject();
} else if (element instanceof String) {
String task = (String) element;
return this.taskToFileMap.get(task);
} else if (element instanceof AliasTask) {
AliasTask alias = (AliasTask) element;
return this.taskToFileMap.get(alias.task);
}
return null;
} |
01464612-1002-4ebc-9b78-631f0fc4a13f | 8 | private void checkRight(TetrominoMoveSelector moves, Tetromino tetromino, int x, int y) {
//Si on est pas entrain de sortir de l'écran
if(x + tetromino.getWidth() >= width || y == -1){
moves.removeTranslateRight();
}else {
//Block nommé pour sortir de la boucle imbriquée
loop :
{
for (int i = 0; i < tetromino.getWidth() && x + i < width; i++) {
for (int j = 0; j < tetromino.getHeight() && y + j < height; j++) {
//Si on a un carré à cette position
if (tetromino.hasSquareAt(i, j)) {
if (getColorAt(x + i + 1, y + j) != EMPTY_CELL) {
moves.removeTranslateRight();
break loop; //on sort de la boucle
}
}
}
}
moves.addTranslateRight();
}
}
} |
5e55c300-d1dc-4b2a-9791-d8da771b8dce | 9 | public static void setLongBE(final byte[] array, final int index, final long value, final int size) {
switch (size) {
case 0:
return;
case 1:
Bytes.setInt1(array, index, (int)value);
break;
case 2:
Bytes.setInt2BE(array, index, (int)value);
break;
case 3:
Bytes.setInt3BE(array, index, (int)value);
break;
case 4:
Bytes.setInt4BE(array, index, (int)value);
break;
case 5:
Bytes.setLong5BE(array, index, value);
break;
case 6:
Bytes.setLong6BE(array, index, value);
break;
case 7:
Bytes.setLong7BE(array, index, value);
break;
case 8:
Bytes.setLong8BE(array, index, value);
break;
default:
throw new IllegalArgumentException();
}
} |
fcb6ab56-886b-43d9-bea4-2295bbcf3420 | 9 | @Override
public int hashCode() {
int result = creationTime != null ? creationTime.hashCode() : 0;
result = 31 * result + (groupName != null ? groupName.hashCode() : 0);
result = 31 * result + (lastAccessTime != null ? lastAccessTime.hashCode() : 0);
result = 31 * result + (lastModifiedTime != null ? lastModifiedTime.hashCode() : 0);
result = 31 * result + (origin != null ? origin.hashCode() : 0);
result = 31 * result + (permissions != null ? permissions.hashCode() : 0);
result = 31 * result + (relative != null ? relative.hashCode() : 0);
result = 31 * result + (size != null ? size.hashCode() : 0);
result = 31 * result + (userName != null ? userName.hashCode() : 0);
return result;
} |
07cce814-02ca-4e3d-9e9a-fc393eda1aeb | 8 | public void build(String type, Tile location) {
if (mana.hasEnough(costs.get(type)) && location.getConstruct()==null && (!updater.getGameState().equals("win") &&
!updater.getGameState().equals("lose"))) {
Construct construct = null;
if(type.equals("tower") && location.getType().equals("FieldTile")) {
construct = new Tower((FieldTile) location);
} else if(type.equals("barricade") && location.getType().equals("PathTile")) {
construct = new Barricade((PathTile) location);
} else
return;
location.addConstruct(construct);
mana.decrease(costs.get(type));
updater.addConstruct(construct);
}
} |
de5808c7-7628-4522-80f2-f8f315b4f178 | 8 | @Override
public boolean keyDown(int keycode) {
while (keyNotDown) {
if (MOVE_KEYS.containsKey(keycode)) {
final Direction dir = MOVE_KEYS.get(keycode);
if (dir.getXis().equals("HORIZONTAL")) {
player.setXD(dir.getSpeed());
} else if (dir.getXis().equals("VERTICAL")) {
player.setYD(dir.getSpeed());
}
keyNotDown = false;
player.changePlayerDirection(dir.getDirection());
} else {
keyNotDown = false;
}
}
switch (keycode) {
case Keys.SPACE:
playScreen.checkPlayerInteraction();
break;
case Keys.ENTER:
boolean visible = playScreen.isMenuVisible();
playScreen.setMenuVisible(!visible);
break;
case Keys.A:
boolean menuVisible = playScreen.isMenuVisible();
if (menuVisible) {
Gdx.app.log(ChromeGame.LOG, "Save Pressed");
// Gdx.app.log(ChromeGame.LOG, GameFile.playerName);
// Gdx.app.log(ChromeGame.LOG, GameFile.playerMoney
// + "");
//
// GameFile.playerPosition = new Vector2(
// player.getX(), player.getY());
// Gdx.app.log(ChromeGame.LOG,
// GameFile.playerPosition.x + ","
// + GameFile.playerPosition.y);
//
// GameFile.currentMap = playScreen.mapName;
// Gdx.app.log(ChromeGame.LOG, GameFile.currentMap);
//
// Gdx.app.log(ChromeGame.LOG, GameFile.musicName);
//
// GameSaver.save();
}
break;
}
return true;
} |
7a821d8f-31bb-40b1-95c7-4bf24ebe5c9d | 7 | static final boolean method2203(byte i) {
int i_1_ = 11 % ((12 - i) / 53);
anInt4802++;
try {
return Class348_Sub42_Sub8_Sub2.parseIncomingPacket(true);
} catch (java.io.IOException ioexception) {
Class272.method2049(106);
return true;
} catch (Exception exception) {
String string
= ("T2 - "
+ (Class348_Sub3.currentIncomingPacket != null
? Class348_Sub3.currentIncomingPacket.getOpcode((byte) 119)
: -1)
+ ","
+ (Class239.aClass114_3145 != null
? Class239.aClass114_3145.getOpcode((byte) 119) : -1)
+ ","
+ (Class348_Sub40_Sub36.aClass114_9456 == null ? -1
: Class348_Sub40_Sub36.aClass114_9456
.getOpcode((byte) 113))
+ " - " + Class348_Sub40_Sub25.currentPacketSize + ","
+ ((((Mob)
Class132.localPlayer)
.xList[0])
+ za_Sub2.baseRegionX)
+ ","
+ (Class90.baseRegionY
- -(((Mob)
Class132.localPlayer)
.yList[0]))
+ " - ");
for (int i_2_ = 0;
Class348_Sub40_Sub25.currentPacketSize > i_2_ && i_2_ < 50; i_2_++)
string
+= (((ByteBuffer) Class299.gameBuffer)
.payload[i_2_]) + ",";
Class156.method1242(string, exception, 15004);
Class348_Sub40_Sub34.method3141(false, (byte) 11);
return true;
}
} |
8edaaaa0-6af5-48d2-98cc-a3f4f61f4fa1 | 4 | public Direction directionContaining(Point p){
if(backWall.contains(p)) return forwardDir;
if(backDirRect.contains(p)) return backDir;
if(rightWall.contains(p)) return forwardDir.getRightDirection();
if(leftWall.contains(p)) return forwardDir.getLeftDirection();
return null;
} |
bf59c46e-d74c-429f-82f5-a02bf6cce221 | 4 | private static int getuid(String s) {
try {
File file = new File(s + "uid.dat");
if (!file.exists() || file.length() < 4L) {
DataOutputStream dataoutputstream = new DataOutputStream(new FileOutputStream(s + "uid.dat"));
dataoutputstream.writeInt((int) (Math.random() * 99999999D));
dataoutputstream.close();
}
} catch (Exception exception) {
}
try {
DataInputStream datainputstream = new DataInputStream(new FileInputStream(s + "uid.dat"));
int i = datainputstream.readInt();
datainputstream.close();
return i + 1;
} catch (Exception exception) {
return 0;
}
} |
91dd81f9-616e-459c-a9fb-9d5aa2164663 | 7 | public void insertTrainer(Trainer trainer){
//insert entry
int id = insertNamedEntity(trainer, "TRAINER");
//map its characteristics
// this.insertIntoTableAllValues(
// "entity_caracteristic",
// id,
// 9,//PASSWORD
// trainer.getPassword()
// );
/* map his/her pokemons */
String idChain ="";
//get the own string => structure like "pokeId(number),pokeId(number),pokeId(number)"...
ResultSet rs = this.getResultsOfQuery("SELECT * FROM "+megatable+" WHERE typeEntity='TRAINER' AND idC=13 AND valueEntity='"+trainer.getName()+"'" /*13=> OWNED POKEMON*/, true);
//count the results if any
int rowCount = 0;
try {
while (rs.next()) {
rowCount++;
}
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
if (rowCount > 0)
{
rs = this.getResultsOfQuery("SELECT * FROM "+megatable+" WHERE typeEntity='TRAINER' AND idC=13 AND valueEntity="+trainer.getName() /*13=> OWNED POKEMON*/, true);
String owned = extractString(rs, "value");
HashMap<Integer,Integer> pokemap = new HashMap<>();
for (String id_number : owned.split(","))//id_number structure : pokeId(number)
{
int ind = id_number.indexOf("(");
String poke_id = id_number.substring(0,ind);//pokeId
String poke_number = id_number.substring(ind);//(number)
poke_number = poke_number.replaceAll("[^0-9\\.]", "");//number
pokemap.put(Integer.valueOf(poke_id), Integer.valueOf(poke_number));
}
for (Pokemon p : trainer.pool)
{
idChain+=p.getId();
//check existence of the id of p
Integer ni = pokemap.get(p.getId());
if (ni!=null)//if exists => increment
{
ni++;
}
else
{
ni = 1;
}
idChain+="("+ni+"),";
}
}
else
{
for (Pokemon p : trainer.pool)
idChain+=p.getId()+"(1),";//TODO: add something to count
}
this.insertIntoTableAllValues("entity_caracteristic",id,13/*OWN*/,idChain);
} |
6ca94f99-fcdb-42d8-86d2-8118d562dc41 | 8 | private boolean reachBlockerByMaxGeneric(keyMap key, int maxReach,int max,int option) {
if(mapReachBlockerByMaxDate.size() >= intMaxMapSize){
mapReachBlockerByMaxDate.clear();
}
if (mapReachBlockerByMaxDate.containsKey(key)) {
long elapsedTime = 0;
switch (option) {
case 0:
elapsedTime = DateRange.elapsedTimeBtwDatesSeconds(mapReachBlockerByMaxDate.get(key).elapsedDate, new Date());
break;
case 1:
elapsedTime = DateRange.elapsedTimeBtwDatesMinutes(mapReachBlockerByMaxDate.get(key).elapsedDate, new Date())+1;
break;
case 2:
elapsedTime = DateRange.elapsedTimeBtwDatesHours(mapReachBlockerByMaxDate.get(key).elapsedDate, new Date())+1;
break;
case 3:
elapsedTime = DateRange.elapsedTimeBtwDatesDays(mapReachBlockerByMaxDate.get(key).elapsedDate, new Date())+1;
break;
default:
elapsedTime = DateRange.elapsedTimeBtwDatesDays(mapReachBlockerByMaxDate.get(key).elapsedDate, new Date())+1;
}
if ( elapsedTime <= max) {
if (mapReachBlockerByMaxDate.get(key).reach < maxReach) {
++ mapReachBlockerByMaxDate.get(key).reach;
return true;
} else {
System.out.println("reach the limit dude .....................");
return false;
}
} else {
mapReachBlockerByMaxDate.put(key, new Obj4Map(1, new Date()));
// System.out.println("elapse time expired .....................");
return true;
}
} else {
mapReachBlockerByMaxDate.put(key, new Obj4Map(1, new Date()));
return true;
}
} |
4cd80858-8471-4ffb-8aa3-9e7855045117 | 3 | public void updateProfile( Profile p ) {
ArrayList<AchievementRecord> newAchRecs = new ArrayList<AchievementRecord>();
newAchRecs.addAll( p.getAchievements() );
for ( Map.Entry<Achievement, JCheckBox> entry : generalAchBoxes.entrySet() ) {
String achId = entry.getKey().getId();
JCheckBox box = entry.getValue();
if ( box.isSelected() ) {
// Add selected achievement recs if not already present.
if ( !AchievementRecord.listContainsId( newAchRecs, achId ) ) {
newAchRecs.add( new AchievementRecord(achId, difficulty) );
}
} else {
// Remove achievement recs that are not selected.
AchievementRecord.removeFromListById( newAchRecs, achId );
}
}
p.setAchievements(newAchRecs);
} |
7437b8cd-0d15-4d6f-882b-1c06e957c74f | 9 | boolean isReferenceAttributeTypeDifferent(ConfigurationObjectReference configurationObjectReference, ReferenceAttributeType referenceAttributeType) {
if(_configurationImport.getConfigurationData(referenceAttributeType, getAttributeGroup("atg.objektReferenzAttributTypEigenschaften")) == null) {
return true;
}
// if(referenceAttributeType.getConfigurationData(getAttributeGroup("atg.objektReferenzAttributTypEigenschaften")) == null) return true;
// Referenzierungsart überprüfen
if(configurationObjectReference.getReferenceType() != referenceAttributeType.getReferenceType()) return true;
// Referenzierungs-Typ überprüfen
if(configurationObjectReference.getReferenceObjectType().equals("")) {
if(referenceAttributeType.getReferencedObjectType() != null) return true;
}
else {
if(getType(configurationObjectReference.getReferenceObjectType()) != referenceAttributeType.getReferencedObjectType()) return true;
}
// Prüfe, ob undefinierte Objekte erlaubt sind.
switch(configurationObjectReference.getUndefined()) {
case ALLOWED:
if(!referenceAttributeType.isUndefinedAllowed()) return true;
break;
case FORBIDDEN:
if(referenceAttributeType.isUndefinedAllowed()) return true;
break;
}
return false;
} |
78ab53ba-c7e0-4d08-b481-74fc7b711d32 | 2 | public static double getRate(String c1, String c2){
Connection conn = DBase.dbConnection();
PreparedStatement dbpst;
double dr =0;
try{
String query = "Select Rate FROM "+c1+ " where CountryCode = ?";
dbpst=conn.prepareStatement(query);
dbpst.setString(1, c2);
ResultSet rs = dbpst.executeQuery();
while(rs.next()){
dr=rs.getDouble(1);
}
dbpst.close();
conn.close();
}catch(SQLException e){System.err.println(e);}
return dr;
} |
2f699a4f-b573-4bd7-9fd9-4055edfbd73e | 1 | public void testWithFieldAdded3() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
try {
test.withFieldAdded(null, 6);
fail();
} catch (IllegalArgumentException ex) {}
} |
3419f156-2861-4a95-a1f5-40a24d07e0eb | 7 | @Override
public Query rewrite(IndexReader reader) throws IOException {
if(!termLongEnough) { // can only match if it's exact
return new TermQuery(term);
}
int maxSize = BooleanQuery.getMaxClauseCount();
PriorityQueue<ScoreTerm> stQueue = new PriorityQueue<ScoreTerm>();
FilteredTermEnum enumerator = getEnum(reader);
try {
ScoreTerm st = new ScoreTerm();
do {
final Term t = enumerator.term();
if (t == null) break;
final float score = enumerator.difference();
// ignore uncompetetive hits
if (stQueue.size() >= maxSize && score <= stQueue.peek().score)
continue;
// add new entry in PQ
st.term = t;
st.score = score;
stQueue.offer(st);
// possibly drop entries from queue
st = (stQueue.size() > maxSize) ? stQueue.poll() : new ScoreTerm();
} while (enumerator.next());
} finally {
enumerator.close();
}
BooleanQuery query = new BooleanQuery(true);
for (final ScoreTerm st : stQueue) {
TermQuery tq = new TermQuery(st.term); // found a match
tq.setBoost(getBoost() * st.score); // set the boost
query.add(tq, BooleanClause.Occur.SHOULD); // add to query
}
return query;
} |
b252158c-2c02-4075-9e8b-f337e1015852 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JuliaAlgorithm other = (JuliaAlgorithm) obj;
if (base == null) {
if (other.base != null)
return false;
} else if (!base.equals(other.base))
return false;
if (seed == null) {
if (other.seed != null)
return false;
} else if (!seed.equals(other.seed))
return false;
return true;
} |
13eb3823-e509-439c-a505-12ae6d29f8f2 | 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(BACMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BACMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BACMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BACMenu.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 BACMenu().setVisible(true);
}
});
} |
9bb5ab9f-f8e1-4fee-a3c1-2bc9f407128a | 6 | public static void main (String args[]) {
AppartamentoClass casa1 = new AppartamentoClass();
AppartamentoClass casa2 = new AppartamentoClass();
String casa1_name = new String();
String casa2_name = new String();
casa1_name = "Casa 1";
casa2_name = "Casa 2";
// Popolo Casa 1
casa1.leggiInput(casa1_name);
System.out.println("\n");
// Popolo Casa 2
casa2.leggiInput(casa2_name);
System.out.println("\n");
System.out.println("\n\n\n");
// Print Casa1
casa1.scriviOutput(casa1_name);
// Print Casa2
casa2.scriviOutput(casa2_name);
System.out.println("\n\n\n");
// Dimensioni
if ( casa1.area > casa2.area ) {
System.out.println ("Casa1, e' di " + casa1.area + " metri quadri e' la più grande");
}
if ( casa1.area < casa2.area ) {
System.out.println ("Casa2, che e' di " + casa2.area + " metri quadri e' la piu' grande");
}
if ( casa1.area == casa2.area ) {
System.out.println ("Casa1 e Casa2 sono della stessa dimensione di " + casa1.area + " metri quadri");
}
// Prezzi
if ( casa1.price > casa2.price ) {
System.out.println ("Casa1, che costa " + casa1.price + " € e' la più costosa");
}
if ( casa1.price < casa2.price ) {
System.out.println ("Casa2, che costa " + casa2.price + " € e' la più costosa");
}
if ( casa1.price == casa2.price ) {
System.out.println ("Casa1 e Casa2 costano uguali: " + casa1.price + " €");
}
System.out.println("\n\n\n");
} |
df037c67-2141-4cc8-8229-53c36a373314 | 5 | private byte[] pdf() {
// Make Nonce 16 bytes by prepending zeroes. done (see init())
// one AES invocation is enough for more than one PDF invocation
// number of index bits needed = 1
// Extract index bits and zero low bits of Nonce
BigInteger Nonce = new BigInteger(1, nonce);
int nlowbitsnum = Nonce.testBit(0) ? 1 : 0;
Nonce = Nonce.clearBit(0);
// Generate subkey, AES and extract indexed substring
IRandom kdf = new UMacGenerator();
Map map = new HashMap();
map.put(IBlockCipher.KEY_MATERIAL, K);
// map.put(IBlockCipher.CIPHER_BLOCK_SIZE, new Integer(128/8));
map.put(UMacGenerator.INDEX, new Integer(128));
// map.put(UMacGenerator.CIPHER, Registry.AES_CIPHER);
kdf.init(map);
byte[] Kp = new byte[KEY_LEN];
try {
kdf.nextBytes(Kp, 0, KEY_LEN);
} catch (IllegalStateException x) {
x.printStackTrace(System.err);
throw new RuntimeException(String.valueOf(x));
} catch (LimitReachedException x) {
x.printStackTrace(System.err);
throw new RuntimeException(String.valueOf(x));
}
IBlockCipher aes = CipherFactory.getInstance(Registry.AES_CIPHER);
map.put(IBlockCipher.KEY_MATERIAL, Kp);
try {
aes.init(map);
} catch (InvalidKeyException x) {
x.printStackTrace(System.err);
throw new RuntimeException(String.valueOf(x));
} catch (IllegalStateException x) {
x.printStackTrace(System.err);
throw new RuntimeException(String.valueOf(x));
}
byte[] T = new byte[16];
aes.encryptBlock(nonce, 0, T, 0);
byte[] result = new byte[OUTPUT_LEN];
System.arraycopy(T, nlowbitsnum, result, 0, OUTPUT_LEN);
return result;
} |
db6c0afb-990d-47e8-a4bf-a3e454dec543 | 3 | private Object sql(Method method, Object[] args, Sql annotation) throws Exception {
Connection c = connector.connect();
try {
try {
PreparedStatement st = statement(args, annotation, c);
Class ret = method.getReturnType();
if (ret != Void.TYPE) {
return select(st, ret);
}
else {
update(st);
return null;
}
}
finally {
c.close();
}
}
catch (SQLException e) {
//connection is closed here
if (handler.repeat(e))
return sql(method, args, annotation);
throw e;
}
} |
3a046ff0-4e0f-47b3-af41-224f0c21e748 | 1 | public void close() throws BitstreamException
{
try
{
source.close();
}
catch (IOException ex)
{
throw newBitstreamException(STREAM_ERROR, ex);
}
} |
871ef025-db86-44f3-916a-13942b5ffd1b | 1 | public int exprHashCode() {
if (value != null) {
return 10 + value.hashCode();
}
return 10;
} |
ee47731d-30a5-451b-8d27-111d6e6e9e50 | 7 | void parseDoctypedecl() throws java.lang.Exception
{
char c;
String doctypeName, ids[];
// Read the document type name.
requireWhitespace();
doctypeName = readNmtoken(true);
// Read the ExternalIDs.
skipWhitespace();
ids = readExternalIds(false);
// Look for a declaration subset.
skipWhitespace();
if (tryRead('[')) {
// loop until the subset ends
while (true) {
context = CONTEXT_DTD;
skipWhitespace();
context = CONTEXT_NONE;
if (tryRead(']')) {
break; // end of subset
} else {
context = CONTEXT_DTD;
parseMarkupdecl();
context = CONTEXT_NONE;
}
}
}
// Read the external subset, if any
if (ids[1] != null) {
pushURL("[external subset]", ids[0], ids[1], null, null, null);
// Loop until we end up back at '>'
while (true) {
context = CONTEXT_DTD;
skipWhitespace();
context = CONTEXT_NONE;
if (tryRead('>')) {
break;
} else {
context = CONTEXT_DTD;
parseMarkupdecl();
context = CONTEXT_NONE;
}
}
} else {
// No external subset.
skipWhitespace();
require('>');
}
if (handler != null) {
handler.doctypeDecl(doctypeName, ids[0], ids[1]);
}
// Expand general entities in
// default values of attributes.
// (Do this after the doctypeDecl
// event!).
// expandAttributeDefaultValues();
} |
7f1db35f-51d5-4823-b82c-e3650cbfe7dd | 2 | @Override
public String valueToString(Object value) throws ParseException {
LengthValue length = (LengthValue) value;
if (mBlankOnZero && length.getValue() == 0) {
return ""; //$NON-NLS-1$
}
return length.toString();
} |
c67c7a28-f1ee-429f-9a4e-f2c656e4adcc | 2 | private boolean createIndex(Connection connection) throws SQLException {
if (connection == null) {
throw new SQLException("You must establish a connection before creating the indexes");
}
Statement stmt = null;
try {
Run.addProcessStatus("Creating the database indexes");
String [] indexes = {"CREATE INDEX SongIndex ON ORG.MUSIC(song_name)",
"CREATE INDEX FolderIndex ON ORG.MUSIC(FOLDER_HASH)",
"CREATE INDEX CheckIndex ON ORG.MUSIC(FOLDER_HASH,FILE_NAME)"};
stmt = connection.createStatement();
for (String indexStmt : indexes) {
log.info("Executing: " + indexStmt);
stmt.executeUpdate(indexStmt);
}
return true;
} finally {
close(stmt);
}
} |
c723ee46-8490-481d-8a99-f0b6ea319808 | 8 | public void renderProjectile(int xp, int yp, Projectile p) {
xp -= xOffset;
yp -= yOffset;
for (int y = 0; y < p.getSpriteSize(); y++) {
int ya = y + yp;
for (int x = 0; x < p.getSpriteSize(); x++) {
int xa = x + xp;
if(xa < -p.getSpriteSize() || xa >= width || ya < 0 || ya >= height) break;
if(xa < 0) xa = 0;
int col = p.getSprite().pixels[x + y * p.getSprite().SIZE];
if (col != ALPHA_COL) pixels[xa + ya * width] = col;
}
}
} |
ac4393a3-bfa9-4833-89f1-78fd0eb833e5 | 2 | private String findName(String response, String elementTag, String elementType) throws Exception{
Document doc = RestClient.stringToXmlDocument(response);
NodeList list = doc.getElementsByTagName(elementTag);
for(int i=0; i < list.getLength();i++){
if(list.item(i).getAttributes().getNamedItem(Constants.TYPE).getTextContent().trim().equalsIgnoreCase(elementType)) {
return list.item(i).getAttributes().getNamedItem(Constants.NAME).getTextContent().trim();
}
}
//
// if it reaches the end without finding the element, throw exception
//
throw new InvalidObjectException("Item not found: " + elementType);
} |
df0d67fb-a283-4386-aacb-f9b25d98af6d | 3 | private static void validarCNPJ(String digits) throws ValidacaoException {
try {
boolean isvalid = false;
if (Long.parseLong(digits) % 10 == 0) {
isvalid = somaPonderadaCNPJ(digits) % 11 < 2;
} else {
isvalid = somaPonderadaCNPJ(digits) % 11 == 0;
}
if (!isvalid) {
throw new ValidacaoException("CNPJ Inválido!");
}
} catch (Exception ex) {
throw new ValidacaoException("CNPJ Inválido! \nVerifique: " + ex.getMessage() + "!");
}
} |
7bd5e7c9-a6eb-4ef8-b638-d011d38c8d1a | 2 | private void parseMethodNameAndParameters() {
methodName = method.getName();
for(Class<?> parameterClass: method.getParameterTypes()) {
parameterTypes.add(parameterClass.getSimpleName());
}
} |
cd6dbf95-b858-4d36-9f52-69923f566b85 | 8 | public boolean addComponentParts(World par1World, Random par2Random, StructureBoundingBox par3StructureBoundingBox)
{
if (averageGroundLevel < 0)
{
averageGroundLevel = getAverageGroundLevel(par1World, par3StructureBoundingBox);
if (averageGroundLevel < 0)
{
return true;
}
boundingBox.offset(0, ((averageGroundLevel - boundingBox.maxY) + 6) - 1, 0);
}
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 1, 3, 5, 4, 0, 0, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 0, 0, 3, 0, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 0, 1, 2, 0, 3, Block.dirt.blockID, Block.dirt.blockID, false);
if (isTallHouse)
{
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 4, 1, 2, 4, 3, Block.wood.blockID, Block.wood.blockID, false);
}
else
{
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 1, 2, 5, 3, Block.wood.blockID, Block.wood.blockID, false);
}
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 1, 4, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 2, 4, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 1, 4, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 2, 4, 4, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 0, 4, 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 0, 4, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 0, 4, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 3, 4, 1, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 3, 4, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 3, 4, 3, par3StructureBoundingBox);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 0, 0, 3, 0, Block.wood.blockID, Block.wood.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 3, 1, 0, 3, 3, 0, Block.wood.blockID, Block.wood.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 4, 0, 3, 4, Block.wood.blockID, Block.wood.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 3, 1, 4, 3, 3, 4, Block.wood.blockID, Block.wood.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 1, 0, 3, 3, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 3, 1, 1, 3, 3, 3, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 0, 2, 3, 0, Block.planks.blockID, Block.planks.blockID, false);
fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 4, 2, 3, 4, Block.planks.blockID, Block.planks.blockID, false);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 2, 2, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 3, 2, 2, par3StructureBoundingBox);
if (tablePosition > 0)
{
placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, tablePosition, 1, 3, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, Block.pressurePlatePlanks.blockID, 0, tablePosition, 2, 3, par3StructureBoundingBox);
}
placeBlockAtCurrentPosition(par1World, 0, 0, 1, 1, 0, par3StructureBoundingBox);
placeBlockAtCurrentPosition(par1World, 0, 0, 1, 2, 0, par3StructureBoundingBox);
placeDoorAtCurrentPosition(par1World, par3StructureBoundingBox, par2Random, 1, 1, 0, getMetadataWithOffset(Block.doorWood.blockID, 1));
if (getBlockIdAtCurrentPosition(par1World, 1, 0, -1, par3StructureBoundingBox) == 0 && getBlockIdAtCurrentPosition(par1World, 1, -1, -1, par3StructureBoundingBox) != 0)
{
placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 1, 0, -1, par3StructureBoundingBox);
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
clearCurrentPositionBlocksUpwards(par1World, j, 6, i, par3StructureBoundingBox);
fillCurrentPositionBlocksDownwards(par1World, Block.cobblestone.blockID, 0, j, -1, i, par3StructureBoundingBox);
}
}
spawnVillagers(par1World, par3StructureBoundingBox, 1, 1, 2, 1);
return true;
} |
4829450f-3383-431c-b91e-fe6c0f2ab138 | 7 | private void createDNAOutput(){
U.p("Max memory used during this run was: " + Driver.getMaxMem() + " GB");
//Create a header for the output file
annoHeader = "##Modified by annotationAlignmenttool on: " + sdf.format(Calendar.getInstance().getTime()) + "\n" + "##Modified from original to fit: " + DNAFile.substring(DNAFile.lastIndexOf('/') + 1) + "\n";
//Write the new predicted annotation to output
try {
U.p("Name of output file is: " + DNAFile.substring(DNAFile.lastIndexOf('/') + 1, DNAFile.lastIndexOf('.')));
BufferedWriter out = new BufferedWriter(new FileWriter(outputDirectory +"/" + DNAFile.substring(DNAFile.lastIndexOf('/') + 1, DNAFile.lastIndexOf('.')) + ".gtf" ));
//Write header information into the file
out.write(annoHeader);
//Output the new modified lines
for(int i = 0; i < GTFlist.size();i++){
out.write(GTFlist.get(i).toString() + "\n");
}
//Flush and close the writer to guarantee that the file was written to disk
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Write the mismatched lines to output
try {
BufferedWriter out = new BufferedWriter(new FileWriter(outputDirectory +"/" + "MismatchedLines.txt" ));
StringBuffer sb = new StringBuffer();
//Count keeps track of how many false matches occur, and it is used during the calculation of the statistics for the mismatched output file.
int count = 0;
for(AA_Line_Container aalc: GTFlist){
//Assume all predicted locations are false, until they can be verified
boolean match = false;
//Confirm that the original line matches up to the predicted locations
if(aalc.getGtfLine().getStartLocation() == aalc.getNewStarts().get(0) || aalc.getGtfLine().getStopLocation() == aalc.getNewStops().get(0)){
match = true;
}
//Output if
if(match == false){
sb.append("UpdatedLine: " + aalc.toString() + "\n");
sb.append("OriginalLine: " + aalc.getGtfLine().toString() + "\n");
count++;
}
}//Go through entire GTFlist
//Write out the output and close the file writer
out.write("##MismatchedLines/Total " + count + "/" + GTFlist.size() + "\n");
out.write("##PercentCorrect " + (1 - ((double)count) / GTFlist.size())*100 + "%" + "\n");
out.write(sb.toString());
//Flush and close the writer to guarantee that the file was written to disk
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//catch
}//createDNAOutput |
0f5c1c9a-d7d4-491f-a275-a36deaba6920 | 6 | protected void parseFeatures() {
// Empty?
if (featuresStr.length() <= 0) return;
String type = null;
String value = "";
StringBuilder values = new StringBuilder();
int lineNum = 0;
for (String line : featuresStr.toString().split("\n")) {
lineNum++;
// Feature start
if (isNewFeature(line)) {
String kv[] = line.trim().split(" ", 2);
if (kv.length > 1) {
// Previous feature data is available? => Add it
if (type != null) addFeature(type, values, lineNum);
// Parse new feature's name
type = kv[0];
value = kv[1].trim();
} else {
// New type
type = line.trim();
value = "";
}
// New values
values = new StringBuilder();
} else value = line.trim();
// Append values to feature
if (value.startsWith("/")) values.append("\n");
values.append(value);
}
// Add last feature
addFeature(type, values, lineNum);
} |
af3840e1-40c3-4adf-997f-2b6cc466ce95 | 1 | public static void main(String[] args) {
try {
int res;
res = ToolRunner
.run(new Configuration(), new WrokBench(), args);
System.exit(res);
} catch (Exception e) {
e.printStackTrace();
}
} |
d9148293-1cf2-4491-a6a6-0f67e101b23e | 2 | public void add(int newx, int newy, int newz) {
if (_level == null)
return;
if (_level.getTile(newx, newy, newz).getVisableBlock() == this.getVisableBlock())
return;
_level.setTile(this, newx, newy, newz, _server);
Player.GlobalBlockChange((short)newx, (short)newy, (short)newz, this, _level, _server, false);
} |
c5420600-d81f-465e-89c1-21a2f2d5d486 | 0 | public UDPChat() throws SocketException
{
new InterfaceSelector(this);
new IncomingListener(this);
} |
533d9355-485a-4607-ba8f-3fccb1a977e2 | 5 | public static void main(String[] args) {
System.out.print("Enter ten numbers: ");
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[10];
int distinctNumberCounter = 0;
for (int i = 0; i < numbers.length; i++) {
int number = scanner.nextInt();
int arrayIndex = 0;
for (arrayIndex = 0; arrayIndex < distinctNumberCounter; arrayIndex++) {
if (numbers[arrayIndex] == number) {
break;
}
}
if (arrayIndex == distinctNumberCounter) {
numbers[distinctNumberCounter] = number;
distinctNumberCounter = distinctNumberCounter + 1;
}
}
for (int arrayIndex = 0; arrayIndex < distinctNumberCounter; arrayIndex++) {
System.out.print(numbers[arrayIndex] + " ");
}
} |
f461e7c3-261d-49f6-93fd-53c0c671299d | 8 | @SuppressWarnings({ "unchecked", "rawtypes" })
private static final Object[] decodeDictionary(byte[] bencoded_bytes, int offset) throws BencodingException
{
HashMap map = new HashMap();
++offset;
ByteBuffer info_hash_bytes = null;
while(bencoded_bytes[offset] != (byte)'e')
{
// Decode the key, which must be a byte string
Object[] vals = decodeString(bencoded_bytes, offset);
ByteBuffer key = (ByteBuffer)vals[1];
offset = ((Integer)vals[0]).intValue();
boolean match = true;
for(int i = 0; i < key.array().length && i < 4; i++)
{
if(!key.equals(ByteBuffer.wrap(new byte[]{'i', 'n','f','o'})))
{
match = false;
break;
}
}
int info_offset = -1;
if(match)
info_offset = offset;
vals = decode(bencoded_bytes, offset);
offset = ((Integer)vals[0]).intValue();
if(match)
{
info_hash_bytes = ByteBuffer.wrap(new byte[offset - info_offset]);
info_hash_bytes.put(bencoded_bytes,info_offset, info_hash_bytes.array().length);
}
else if(vals[1] instanceof HashMap)
{
info_hash_bytes = (ByteBuffer)vals[2];
}
if(vals[1] != null)
map.put(key,vals[1]);
}
return new Object[] {new Integer(++offset), map, info_hash_bytes};
} |
77571580-ec51-45e8-a028-feff43ba42cd | 4 | @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel3 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jFTFTelefone = new javax.swing.JFormattedTextField();
jLabel5 = new javax.swing.JLabel();
jFTFRG = new javax.swing.JFormattedTextField();
jTFEndereco = new javax.swing.JTextField();
jBTImagem = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jCBSexo = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jCBUF = new javax.swing.JComboBox();
jLabel9 = new javax.swing.JLabel();
jFTFCPF = new javax.swing.JFormattedTextField();
jTFEmail = new javax.swing.JTextField();
jDCDataIngresso = new com.toedter.calendar.JDateChooser();
jDCDataNascimento = new com.toedter.calendar.JDateChooser();
jLabel17 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jCBEstadoCivil = new javax.swing.JComboBox();
jLabel15 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jDCDataDesligamento = new com.toedter.calendar.JDateChooser();
jLabel7 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jTFBairro = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
jCBTipoPessoa = new javax.swing.JComboBox();
jCBCidade = new javax.swing.JComboBox();
jLabel18 = new javax.swing.JLabel();
jTFNome = new javax.swing.JTextField();
jTFTCEP = new javax.swing.JFormattedTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel3.setPreferredSize(new java.awt.Dimension(600, 310));
jLabel8.setText("Telefone");
try {
jFTFTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##) ####-####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
jFTFTelefone.setText("(11) 1234-5678");
jLabel5.setText("Data de Desligamento");
try {
jFTFRG.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.###.###-#")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
jFTFRG.setText("12.345.678-9");
jTFEndereco.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jBTImagem.setText("Imagem");
jLabel6.setText("CPF");
jLabel16.setText("Tipo de Pessoa");
jCBSexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Feminino", "Masculino", " " }));
jLabel3.setText("Data de Ingresso");
jCBUF.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "São Paulo", "Paraná" }));
jLabel9.setText("E-mail");
try {
jFTFCPF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
jFTFCPF.setText("123.456.789-00");
jTFEmail.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel17.setText("CEP");
jLabel4.setText("Data de Nascimento");
jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel2.setPreferredSize(new java.awt.Dimension(150, 200));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 148, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 198, Short.MAX_VALUE)
);
jLabel10.setText("Sexo");
jLabel13.setText("Bairro");
jCBEstadoCivil.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Solteiro ", "Casado", "Divorciado", " " }));
jLabel15.setText("Estado");
jLabel11.setText("Estado Civil");
jLabel7.setText("RG");
jLabel14.setText("Cidade");
jTFBairro.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel12.setText("Endereço");
jCBTipoPessoa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Professor", "Aluno", "Funcionario", " " }));
jCBTipoPessoa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCBTipoPessoaActionPerformed(evt);
}
});
jCBCidade.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ponta Grossa" }));
jCBCidade.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCBCidadeActionPerformed(evt);
}
});
jLabel18.setText("Nome");
jTFNome.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
try {
jTFTCEP.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.###-###")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
jTFTCEP.setText("12.345-678");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(228, 228, 228)
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCBCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCBUF, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(251, 251, 251)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel17)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTFTCEP, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel13)
.addGap(18, 18, 18)
.addComponent(jTFBairro))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTFEndereco))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTFNome))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jFTFCPF, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCBSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jFTFRG, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel11)
.addGap(18, 18, 18)
.addComponent(jCBEstadoCivil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTFEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jFTFTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCBTipoPessoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel3))
.addComponent(jDCDataIngresso, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jDCDataNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel5))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jDCDataDesligamento, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jBTImagem)
.addGap(44, 44, 44))))))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap(13, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(jTFNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jFTFTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCBTipoPessoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel16))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jTFEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jLabel7)
.addComponent(jFTFCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jFTFRG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCBEstadoCivil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11)
.addComponent(jLabel10)
.addComponent(jCBSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(3, 3, 3)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jDCDataDesligamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jDCDataNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jDCDataIngresso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(15, 15, 15)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(jTFEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(jLabel13)
.addComponent(jTFBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTFTCEP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jBTImagem))
.addGap(8, 8, 8)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(jCBUF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(jCBCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(14, 14, 14))
);
getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents |
16c1a2a2-05e3-43f6-bca0-cc4b4e1bc0e2 | 7 | public void endLog() {
end = "\t<end date=\"" + getLogDate() + "\" time=\"" + getLogTime() + "\" />\n";
logfilename = "log/log_" + formatDateTime("dd-MM-yyyy_HH-mm") + ".xml";
try {
JFileChooser fc = new JFileChooser("log/");
fc.setFileFilter(new XMLFileFilter());
fc.setSelectedFile(new File(logfilename));
if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
logfilename = fc.getSelectedFile().getAbsolutePath();
File fLog = new File(logfilename);
if (!fLog.exists())
fLog.createNewFile();
oswLog = new OutputStreamWriter(new FileOutputStream(fLog), encoding);
/**
* build the basic header of a log file
*/
oswLog.write("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n");
oswLog.write("<!DOCTYPE pxchatlog SYSTEM \"pxchatlog.dtd\">\n");
oswLog.write("<?xml-stylesheet href=\"pxchatlog.xsl\" type=\"text/xsl\" ?>\n");
oswLog.write("<pxchatlog>\n");
oswLog.flush();
/**
* put all participants in the log This needs a closing of
* oswUser first!
*/
oswLog.write("\t<participants>\n");
for (int i = 0; i < participants.length; i++) {
oswLog.write("\t\t<name>" + participants[i] + "</name>\n");
}
oswLog.write("\t</participants>\n");
oswLog.flush();
/**
* let us write the duration of this chat
*/
oswLog.write(start);
oswLog.write(end);
oswLog.flush();
/**
* we can now append the temporary message log. again, we have
* to close that OutputStreamWriter first.
*/
oswMessage.close();
Scanner scanner;
oswLog.write("\t<chat>\n");
scanner = new Scanner(new FileInputStream(fMessages), encoding);
while (scanner.hasNextLine()) {
oswLog.write(scanner.nextLine() + "\n");
}
scanner.close();
oswLog.write("\t</chat>\n");
oswLog.flush();
fMessages.delete();
/**
* finish the complete log
*/
oswLog.write("</pxchatlog>\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (oswLog != null)
oswLog.close();
new File(msgfilename).delete();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
51212e3a-9ef1-4073-bafb-29a227f220cc | 3 | public void majFen(ArrayList<Message> message){
if (message.size() > 0){
for(Message tmp:message){
//System.out.println (tmp);
jTextArea3.setText(jTextArea3.getText()+tmp.toString());
}
try {
chat.nettoyerMessage(this.getPseudo());
} catch (RemoteException ex) {
Logger.getLogger(TchatRMI.class.getName()).log(Level.SEVERE, null, ex);
}
}
this.repaint();
} |
a648696f-e413-47af-a198-e45ba224533a | 9 | public void act()
{
if(Greenfoot.mousePressed(this)) {
startX = getX();
startY = getY();
}
//Enables the checker to respond to mouse drags
//Only moves the checker to diagonal posisitons
if(Greenfoot.mouseDragged(this)) {
MouseInfo mouse = Greenfoot.getMouseInfo();
setLocation(mouse.getX(), mouse.getY());
}
//gets performed when the user drops the checker on the board
if(Greenfoot.mouseDragEnded(this)){
if(isValidSpot(startX, startY, getX(), getY()) && ((CheckerBoard)getWorld()).playerTurn() == this.team){
//Eat players jumped over
jumpCheckers();
((CheckerBoard)getWorld()).nextPlayersTurn();
} else {
setLocation(startX, startY);
}
List<Object> objects = getIntersectingObjects(Object.class);
for(Object o : objects) {
if(o instanceof Bomb) {
getWorld().removeObject((Actor)o);
getWorld().removeObject(this);
break;
} else if(o instanceof Mushroom) {
o = (Mushroom)o;
((Mushroom)o).makeKing(this);
break;
} else if(o instanceof Tunnel) {
o = (Tunnel)o;
((Tunnel)o).transport(this);
((Tunnel)o).makeKing(this);
break;
}
}
}
} |
39f9380b-ad46-41d2-a4df-1591bcc04ea3 | 3 | @Override
public String execute() throws Exception {
try {
Map session = ActionContext.getContext().getSession();
session.put("User", null);
session.clear();
myDao.getDbsession().close();
addActionMessage("Successfully Logged Out.");
return "success";
} catch (HibernateException e) {
addActionError("Server Error Please Try Again ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Try Again ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Try Again ");
e.printStackTrace();
return "error";
}
} |
f44d359f-1256-412a-a803-8547c0fe9296 | 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(GUI_GestorInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI_GestorInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI_GestorInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI_GestorInfo.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 GUI_GestorInfo().setVisible(true);
}
});
} |
5a6d5c5c-5388-426d-a230-08aa68684569 | 5 | private void loadEmployeeDateFromFile(String staffRepository) {
InputStream is = getInputStreamForFile(staffRepository);
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
try {
XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is);
while (xmlEventReader.hasNext()) {
XMLEvent xmlEvent = xmlEventReader.nextEvent();
if (xmlEvent.isStartElement()){
StartElement startElement = xmlEvent.asStartElement();
if(startElement.getName().getLocalPart().equals("firstname")){
xmlEvent = xmlEventReader.nextEvent();
builder.identifiedByFirstName(xmlEvent.asCharacters().getData());
} else if (startElement.getName().getLocalPart().equals("lastname")) {
xmlEvent = xmlEventReader.nextEvent();
builder.identifiedByLastName(xmlEvent.asCharacters().getData());
}
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
}
} |
3fdafe36-77a8-4891-870a-bf59196e2712 | 5 | public int[] diceThrown() {
switch (turn % 5) {
case 1 :
return new int[] { 2, 3 };
case 2 :
return new int[] { 4, 4 };
case 3 :
return new int[] { 3, 6 };
case 4 :
return new int[] { 6, 1 };
case 0 :
return new int[] { 5, 3 };
default :
return new int[] { 2, 2 };
}
} |
77a00b0e-768b-4917-b60d-00534ecc1010 | 5 | protected boolean siirraVaakasuunnassa(int napinKorkeus, int napinLeveys, int suunta) {
if ((suunta == 1 && napinLeveys + 1 >= getLeveys()) || (suunta == -1 && napinLeveys - 1 < 0) ) {
return false;
}
if (getLauta()[napinKorkeus][napinLeveys + suunta].getTunniste() == -1) {
getLauta()[napinKorkeus][napinLeveys + suunta] = getLauta()[napinKorkeus][napinLeveys];
getLauta()[napinKorkeus][napinLeveys] = new Nappula(-1);
return true;
}
return false;
} |
aa30379a-46c1-49f1-9f1f-c03e152adf66 | 3 | private void init(){
Random rand = new Random(System.currentTimeMillis());
for (int x = 0; x < Standards.CHUNK_SIZE; x++){
for (int y = 0; y < Standards.CHUNK_SIZE; y++){
int tileX = (chunkX * Standards.CHUNK_SIZE) + x;
int tileY = (chunkY * Standards.CHUNK_SIZE) + y;
contents[x][y] = new Tile(2, tileX, tileY);
if (rand.nextInt(40) == 0){
contents[x][y].setMetadata(2);
}
}
}
isLoaded = true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.