samedi 28 février 2015

How to loop through an Json array in mustache template


Vote count:

0




I have an array with JSON object:



{result" : "OK","data":[
{"name" : "henrytest",
"id" : "9a3d1faaaac742889a940a6d9df49d16"},
{"name" : "henrytest",
"id" : "9a3d1faaaac742889a940a6d9df49d16"},
{"name" : "henrytest",
"id" : "9a3d1faaaac742889a940a6d9df49d16"}
]
}


I'm trying to loop through the array to get the 3 fields displayed in my table. However nothing is getting diplayed. Here is my mustache template:



<table style="width:100%;">
<thead>
<tr>
<th>Name</th>
<th>User ID</th>

</tr>
</thead>
<tbody>
{{#data}}
<tr>

<td>{{name}}</td>
<td>{{id}}</td>

</tr>
{{/data}}

</tbody>
</table>


I'm not able to display any fields in the table.Stuck badly with this..:( :(Any ideas how i can achieve this??



asked 43 secs ago







How to loop through an Json array in mustache template

Init localStorage after every refresh


Vote count:

0




I would like to initialize localStorage object every time a user does a refresh by F-5.


Can i do such a thing?


The localStorage object is working fine by setItem and getItem methods. However, I would like to know if i have the option to init this object every refresh action.



asked 15 secs ago

Aviade

318






Init localStorage after every refresh

disconnecting from Mutation Observers


Vote count:

0




I am having difficulty using the Mutation Observers and disconnecting on callback.



var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes)
{
var element = getElement(selectors);
if(element)
{
observer.disconnect();
return callback(element);
}
}
})
});

observer.observe(document.body, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});


observer.disconnect() is not stopping the listener, if I put it after the observer.observe then it will work but then I effectively a, not doing anything because it stops listening right away.


How do you disconnect inside the callback?



asked 37 secs ago







disconnecting from Mutation Observers

Autolayout UIButtons in a grid


Vote count:

0




I'm having trouble getting my UIButtons to align properly in my scrollview. I have tried aligned baselines, aligning each to a my UIView called contentView, etc. and nothing has worked.


Essentially I have a:



`UIView`

`UIScrollView` //320 x 708

`UIVew` //320 x 708 , called contentView


I have 8 UIButtons sizes 140x140, that are aligned two to a row as such:



|---8 pts--| UIButton |---8 pts--| UIButton |---8 pts--|
_
|
|
8 pts
_

|---8 pts--| UIButton |---8 pts--| UIButton |---8 pts--|


asked 1 min ago







Autolayout UIButtons in a grid

Why Tomcat's LifyCycleSupport.java use array to store listeners instead of any advanced containers(ArrayList)?


Vote count:

0




Im recently going through tomcat's source code, I found that in the LifecycleSupport.java class, it stores Listeners by simple arrays,



private LifecycleListener listeners[] = new LifecycleListener[0];


so the add() method has to create a new array to replace the old one:



public void addLifecycleListener(LifecycleListener listener) {
82
83 synchronized (listenersLock) {
84 LifecycleListener results[] =
85 new LifecycleListener[listeners.length + 1];
86 for (int i = 0; i < listeners.length; i++)
87 results[i] = listeners[i];
88 results[listeners.length] = listener;
89 listeners = results;
90 }
91
92 }


I wonder whats the purpose to use array instead of advanced java containers like ArrayList, since its much more convenient to perform add/remove action?


Thanks



asked 34 secs ago

Qing

100






Why Tomcat's LifyCycleSupport.java use array to store listeners instead of any advanced containers(ArrayList)?

what are they called and how to make it using css?


Vote count:

0




enter image description here


I am a not-native english speaker, I dont know what are these called, so cannot google it either :/ Can anyone tell me what are these called and how do I make them using css?


Thanks



asked 50 secs ago







what are they called and how to make it using css?

Display p tag as blog level element, good or bad?


Vote count:

0




I'm just curious about something. For a while now i've been wrapping p tags in a div which i use to position and size the text block, however, I've seen now that you can use css to turn a p tag or any other html text tags to a block level element by using display: block.



<p class="custom-text-block"></p>

p.custom-text-block {
display: block; }


Is this a good or bad thing to do ? because for me it seems as though it can save me from having to wrap the p tag in div, but i still get the flexibility to style the p.custom-text-block.



asked 58 secs ago

Dan

64






Display p tag as blog level element, good or bad?

Printing a c# winform application form


Vote count:

0




I'm amazed how difficult this seems to be. I 'just' want to print my form (it's an invoice), and ensure it prints the whole form (not just what is displayed on the screen)? I can alter anything I want on the form itself..so how do I set it all up so it prints perfectly to a standard letter sized sheet of paper, and doesn't let the user resize it, etc etc. They should see it just like it will print.. maybe they can zoom in and out, but no re-sizing, etc.


I thought a reportviewer control would be handy in order to handle all the printing and sizing stuff.. but that control doesn't seem to lend itself to a single record display. (maybe have a Header as the entire report! seems crazy)


so unless i'm wrong, maybe someone can just give me all the properties to set, etc, in order to make a regular form statically sized for a standard sheet of paper (8.5 x 11)? And then show me the way to print the entire thing rather then just a 'printscreen'.


I've read a bunch of ideas for using 'printscreen' and using GDI+ (i didn't fully understand how I could use that).. nothing seems to be standing out for me.



asked 22 secs ago







Printing a c# winform application form

AES encryption C++ (can't decrypt encrypted file)


Vote count:

0




I'm playing around with AES and write the iv and derived key to the file so that I use it later for decryption...


following function encrypts the file and saves the iv and derived key into the file, it also saves encrypted text into separate file:



void MainWindow::on_button_encrypt() try
{
using namespace std;
using namespace Gtk;
using namespace CryptoPP;

fstream file;

file.open(m_file_name + ".aes", std::ios::out | std::ios::trunc);
if (file.is_open())
{
// get the plain password:
SecByteBlock password;
password_dialog get_passwd(password);
get_passwd.run();


// generate random salt
const int SALT_SIZE = 32;
SecByteBlock salt(SALT_SIZE);
AutoSeededRandomPool prng;
prng.GenerateBlock(salt.BytePtr(), SALT_SIZE);


// derive a key from password and salt:
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
PKCS5_PBKDF2_HMAC<SHA512> gen;
gen.DeriveKey(key.BytePtr(), key.size(), 1, password.BytePtr(), password.size(), salt.BytePtr(), salt.size(), 200);


// genereate random iv:
SecByteBlock iv(AES::BLOCKSIZE);
OS_GenerateRandomBlock(false, iv.BytePtr(), AES::BLOCKSIZE);


// encrypt plain text:
AES::Encryption enc(key.BytePtr(), AES::DEFAULT_KEYLENGTH);
CBC_Mode_ExternalCipher::Encryption mode(enc, iv);

string cipher_text;
StringSink* sink = new StringSink(cipher_text);
StreamTransformationFilter encryptor(mode, sink);

string plain_text = m_file_buffer->get_text();
encryptor.Put(reinterpret_cast<const byte*>(plain_text.c_str()), plain_text.length() + 1);
encryptor.MessageEnd();

// write the result:
file << cipher_text.c_str();
file.close();
file.open(m_file_name + ".key", std::ios::out | std::ios::trunc);
file << key << '\n' << iv;
file.close();
}
}


The above function writes the iv and derived key to the file.



0000000002F9F140


0000000002F9F4E0



Following function is supposed to read the file and decrypt it by using the *.key file:



void MainWindow::on_button_decrypt()
{
using namespace std;
using namespace CryptoPP;
Gtk::MessageDialog info("Info");

fstream file;
file.open("decrypted.txt", ios::out | ios::trunc);
if (file.is_open())
{
// read the key:
fstream stream;
string input;

SecByteBlock key(AES::DEFAULT_KEYLENGTH);
SecByteBlock iv(AES::BLOCKSIZE);


stream.open("test.txt.key", std::ios::in);

if (stream.is_open())
{
getline(stream, input);
key.Assign(reinterpret_cast<const byte*>(input.c_str()), input.size());
input.clear();
getline(stream, input);
iv.Assign(reinterpret_cast<const byte*>(input.c_str()), input.size());
}
else
{
info.set_secondary_text("can't read key file");
info.run();
return;
}


// decrypt:
AES::Decryption dec(key, AES::DEFAULT_KEYLENGTH);
CBC_Mode_ExternalCipher::Decryption mode(dec, iv);

string plain_text;
StringSink* sink = new StringSink(plain_text);
StreamTransformationFilter decryptor(mode, sink);

try
{
// get encrypted text from buffer (obtained from other function):
string cipher_text = m_file_buffer->get_text();
decryptor.Put(reinterpret_cast<const byte*>(cipher_text.c_str()), cipher_text.size());
decryptor.MessageEnd();
file << plain_text;
file.close();
}
catch (CryptoPP::Exception& ex)
{
info.set_secondary_text(ex.what());
info.run();
}
}
}


CryptoPP trows an exception while decrypting saying this:


FileTransformationFilter: ciphertext length is not multiple of a block size.


How ever it does not throw anything if decryption process is done in first function ( on_btn_encrypt() ) no file is read there, so it looks I'm having problem with reading encrypted file but have no idea how?


This is content of encrypted file: &`OôÍoYjÜMe×Q°Þ


plaintext is: some text


Do you see what am I missing here? thanks so much!



asked 38 secs ago

codekiddy

1,382






AES encryption C++ (can't decrypt encrypted file)

TClientSocket and TServerSocket generating a corrupted file on upload


Vote count:

0




I'm needed of a Remote File Manager and I found a example on web, and now I'm working in the part of upload files; I saw some codes e tentei adapt for my project (only in the part of upload files), but the last code found generates a corrupted file in server side (on remote pc that I control). My project of exemplo is HERE. The stretch with this problem probably are theses follow, but I not know where are these erros :(. some friend help me, please?


CLIENT:


[code]



{ BLOCO DESTINADO A TESTE COM OS SOCKETS USANDO PORTAS DIFERENTES }

procedure SendFile(lpFileName: string; Socket1: TClientSocket);
var
F: file;
FileInfo: TFileInfo;
dwFileSize, dwBytesRead: DWORD;
Buffer: array[0..4096] of Char;
begin
{$I-}
AssignFile(F, lpFileName);
Reset(F, 1);
dwFileSize := FileSize(F);
FileInfo.FileName := lpFileName;
FileInfo.FileSize := dwFileSize;
Socket1.SendBuffer(FileInfo, SizeOf(FileInfo));
repeat
FillChar(Buffer, SizeOf(Buffer), 0);
BlockRead(F, Buffer, SizeOf(Buffer), dwBytesRead);
Socket1.SendBuffer(Buffer, dwBytesRead);
until (dwBytesRead = 0);
CloseFile(F);
{$I+}
end;

procedure Client(Thread: TThread);
var
ClientSocket: TClientSocket;
begin
ClientSocket := TClientSocket.Create;
ClientSocket.Connect('127.0.0.1', 1500);
if ClientSocket.Connected then
begin
SendFile(file_to_upload, ClientSocket);
end;
end;


{==================================================================}

9: begin
if Form2.OpenDlg.Execute then
File_to_Upload:= Form2.OpenDlg.FileName;
TThread.Create(@Client, 0);
end;


[/code]


SERVER:


[code]



///////////////////////////////////////////////////////////////////////////////////////////////////////////////

procedure ReceiveFile(Socket1: TClientSocket);
var
F: file;
lpFileName: string;
FileInfo: TFileInfo;
dwFileSize, dwBytesRead: DWORD;
Buffer: array[0..4096] of Char;
begin
Socket1.ReceiveBuffer(FileInfo, SizeOf(TFileInfo));
lpFileName := FileInfo.FileName;
dwFileSize := FileInfo.FileSize;
{$I-}
AssignFile(F, lpFileName);
ReWrite(F, 1);
repeat
FillChar(Buffer, SizeOf(Buffer), 0);
dwBytesRead := Socket1.ReceiveBuffer(Buffer, SizeOf(Buffer));
BlockWrite(F, Buffer, dwBytesRead);
Dec(dwFileSize, dwBytesRead);
until (dwFileSize <= 0);
CloseFile(F);
{$I+}
end;

procedure Client2(Thread: TThread);
var
ClientSocket: TClientSocket;
begin
Thread.Lock;
try
ClientSocket := ServerSocket.Accept;
finally
Thread.Unlock;
end;
ReceiveFile(ClientSocket);
MessageBeep($FFFFFFFF);
end;

procedure Server(Thread: TThread);
begin
ServerSocket := TServerSocket.Create;
ServerSocket.Listen(ServerPort);
while not Thread.Terminated do
begin
ServerSocket.Idle;
TThread.Create(@Client2, 0);
end;
end;


//////////////////////////////////////////////////////////////////////////////////////////////////////////////



while True do begin
TThread.Create(@Server, 0);

...


[/code]



asked 30 secs ago







TClientSocket and TServerSocket generating a corrupted file on upload

Custom PS1: usual PS1 for all directories excluding single directory with subdirectories


Vote count:

0




Consider fixed absolute path to some directory with arbitrary subdirectories:



/full/path/to/fixed/directory
/full/path/to/fixed/directory/first_subdirectory
/full/path/to/fixed/directory/first_subdirectory/second_subdirectory


and arbitrary other directory that is not subdirectory of foregoing directory: /other/path


I want see the following in the terminal:



user@host: .../directory$
user@host: .../directory/first_subdirectory
user@host: .../directory/first_subdirectory/second_subdirectory
user@host: /other/path$


where the last line is a typical case but other lines are instead of



user@host: /full/path/to/fixed/directory$
user@host: /full/path/to/fixed/directory/first_subdirectory
user@host: /full/path/to/fixed/directory/first_subdirectory/second_subdirectory


How to implement it?


P.S. Paths can contain whitespaces.



asked 1 min ago







Custom PS1: usual PS1 for all directories excluding single directory with subdirectories

Filtering Folders in Save File Dialog in Visual Basic


Vote count:

0




I am making an application in Visual Basic which creates a directory and places text files in them, but I want to view a directory in which the user wants the text files from. I have decided that using the OpenFileDialog option would work best. What filter would I use for the OpenFileDialog? Here's my code so far:


For the creation of the folder and documents:


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click My.Computer.FileSystem.CreateDirectory("C:/Organizer/" + BusinessName.Text)



Dim objWriter9 As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + "Address" + ".txt")
objWriter9.Write(Address.Text)
objWriter9.Close()

Dim objWriter As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + "BusinessName" + ".txt")
objWriter.Write(BusinessName.Text)
objWriter.Close()

Dim objWriter1 As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + "AssociateName" + ".txt")
objWriter1.Write(AssociateName.Text)
objWriter1.Close()

Dim objWriter2 As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + "PhoneNumber" + ".txt")
objWriter2.Write(PhoneNumber.Text)
objWriter2.Close()

Dim objWriter3 As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + "Email" + ".txt")
objWriter3.Write(Email.Text)
objWriter3.Close()

If CheckBox1.Checked Then
Dim objWriter4 As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + "Other" + ".txt")
objWriter4.Write(Other1.Text)
objWriter4.Close()
End If

If CheckBox5.Checked Then
Dim objWriter5 As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + BusinessName.Text + "Other1" + ".txt")
objWriter5.Write(Other3.Text)
objWriter5.Close()
End If

If CheckBox4.Checked Then
Dim objWriter6 As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + BusinessName.Text + "Other2" + ".txt")
objWriter6.Write(Other5.Text)
objWriter6.Close()
End If

If CheckBox3.Checked Then

End If
Dim objWriter7 As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + BusinessName.Text + "Other3" + ".txt")
objWriter7.Write(Other7.Text)
objWriter7.Close()

If CheckBox5.Checked Then
Dim objWriter8 As New System.IO.StreamWriter("C:/Organizer/" + BusinessName.Text + "/" + BusinessName.Text + "Other4" + ".txt")
objWriter8.Write(Other9.Text)
objWriter8.Close()
End If

End Sub


End Class`


And for the loading of it (so far):



` Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Hide()
Label1.Show()
Label2.Show()
Label3.Show()
Label4.Show()
Label5.Show()
Label6.Show()
Label7.Show()
Label8.Show()
Label9.Show()
Label10.Show()
Label11.Show()
Label12.Show()
Label13.Show()
Label14.Show()
Label15.Show()
Label16.Show()
Label17.Show()
OpenFileDialog1.InitialDirectory = "C:/Organizer"
OpenFileDialog1.Filter = "Folder|"
OpenFileDialog1.ShowDialog()
My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)`


Thanks for the help!



asked 1 min ago







Filtering Folders in Save File Dialog in Visual Basic

How to add line breaks to output fixed width flat file


Vote count:

0




I need to create a Flat file without column headers, no comma separated values but each column will have a fixed starting position and a fixed length in the text file. For example, below is the text file to be created with six columns


Column1 Column2 Column3 Column4 Column5 Column6


abc 1 New emp xxxx xxxx xxx


Fixed starting position and a fixed lenth values for these columns as are below;


Column1 : Starting Position -1, Fixed Length -4


Column2 : Starting Position - 8, Fixed Length - 2


Column3 : Starting Postion - 11, Fixed Length - 10


Column4 : Starting Position -1, Fixed Length -5


Column5 : Starting Position - 10, Fixed Length - 2


Column6 : Starting Postion - 15, Fixed Length - 5


The out put file each line have only 20 characters length.First 3 columns comes in first line and 4-6 columns comes in 2nd line.


OUTPUT FILE:


1234 89 11121314151617181920 12345 1011 151617181920



asked 22 secs ago







How to add line breaks to output fixed width flat file

error 1215 (hy000) cannot add foreign key constraint - mysql


Vote count:

0




I've googled this error a lot, but no solution found.



CREATE TABLE Student(id VARCHAR(30) NOT NULL, name VARCHAR(150), CONSTRAINT PK1 PRIMARY KEY(id));

CREATE TABLE Course (id VARCHAR(30) NOT NULL, name VARCHAR(150), CONSTRAINT PK2 PRIMARY KEY(id));

CREATE TABLE Enroll(studentId VARCHAR(30) NOT NULL, courseId VARCHAR(30) NOT NULL, PRIMARY KEY(studentId,courseId),
CONSTRAINT FK1 FOREIGN KEY (studentId) REFERENCES Student(id),
CONSTRAINT FK2 FOREIGN KEY (courseId) REFERENCES Course(courseId));


First 2 create statements are fine. 3rd statement generates error:



error 1215 (hy000) cannot add foreign key constraint



Kindly tell what's going wrong? Thanks!



asked 32 secs ago







error 1215 (hy000) cannot add foreign key constraint - mysql

I want to make logo smaller on mobile


Vote count:

0




newbius maximus here… I want to do css to make logo smaller for mobile , where to start, here is site: http://ift.tt/1K1Uw12



asked 32 secs ago







I want to make logo smaller on mobile

Android - Database sync, Client and Server, SyncAdapter? ContentProvider?


Vote count:

0




I have an android client and a arbitrary webb server. The client has a local SQLite database. The server has a MySQL database.


I want to synchronize the client database so that it is always up-to-date with the server database.


My concerns is on how i should do the synchronization on the client side. My current approach is using a syncAdapter and then I'm trying to somehow hook up a contentProvider to change the data in the SQLite database. From my reading on the android developer site i interpreter this is how you should do it. (As new to android development I feel the contentProvider is hard to understand)



  • Is this the best approach or is there some better/easier way to do it?


I have set up the sync adapter accordingly to this developer guide: http://ift.tt/1iPZgZz


I guess I have to set up the ContentProvider accordingly: http://ift.tt/1eNYhY6



asked 1 min ago







Android - Database sync, Client and Server, SyncAdapter? ContentProvider?

What mistake I'm making in formation of new array so the index is not being generated?


Vote count:

0




I've following $_POST array :



Array
(
[fileName] => Array
(
[0] => 8.png
[1] => 2_OnClick_OK.jpg
)

[fileLink] => Array
(
[0] => http://ift.tt/1AmgtNr
[1] => http://ift.tt/1BpSous
)

[Submit] => Submit File
)


I got the above output after execution of following statement:



print_r($_POST); die;//Code to print the $_POST array


Now from the above $_POST array I've to create a new desired array which should be structured as follows after printing it:



Array
(
[8.png] => Array
(
[0] => http://ift.tt/1AmgtNr
)
[2_OnClick_OK.jpg]
(
[0] => http://ift.tt/1BpSous
)

)


For this I tried following code.



$request_Arr = array_combine ( $_POST['fileName'], $_POST['fileLink'] );


After execution of above code if I print the array $request_Arr it prints following output:



Array (
[8.png] => http://ift.tt/1zt9jGS
[2_OnClick_OK.jpg] => http://ift.tt/1AHTrp8
)


So my issue is it's not generating the [0] index key for inner array. I want the new array with [0] index key present as follows :



Array
(
[8.png] => Array
(
[0] => http://ift.tt/1AmgtNr
)
[2_OnClick_OK.jpg]
(
[0] => http://ift.tt/1BpSous
)

)


Can someone please correct my mistake and help me in creating an array in desired format?


Thanks in advance.



asked 21 secs ago







What mistake I'm making in formation of new array so the index is not being generated?

Creating multiple data frames


Vote count:

0




I am attempting to create two separated data frames using the apply family however I run into trouble when attempting to create them as shown below.



X <- c(3,4,3,2,3,4,5,6,7,7,6,5,4,3,3,5,3,6,3,5,6,3,6,3,4,5,5,4,3,4,5,3,5,5,4)
Y <- c(3,2,1,3,4,2,1,2,3,5,4,3,2,1,1,3,4,5,6,7,6,5,4,3,2,3,4,3,4,2,4,3,NA,NA,NA)

mydata<-data.frame(X,Y)

L <- seq(1:length(mydata))
n <- function(x) length(na.omit(mydata[,x]))
n <- lapply(L,n)

# sequence each (Variable time)
x <- function(x) seq(1:n[[x]])
x <- lapply(L,x)
y <- function(x) na.omit(mydata[,x])
y <- lapply(L,y)

# create multiple data frames
Data <- function (x) data.frame(y[[x]], x[[x]])
Data <- lapply(L,Data)
# Error en x[[x]] : subíndice fuera de los límites

# what am I doing wrong I can not figure out how to do it using mapply
# However works if I do (when L is 1 and 2 referring to the x and x, for example

data.frame(y[[2]], x[[2]])


asked 17 secs ago







Creating multiple data frames

epoll or poll, which should be used in TCP long connection?


Vote count:

0




I am not very deep understanding of both, I think you should use epoll, but not as good as the use of poll. Because when using epoll, causing high CPU load. I do not know if it is so, or program bug.Can someone explain it?



asked 1 min ago







epoll or poll, which should be used in TCP long connection?

Test Class not working right within my Java


Vote count:

0




OK, I am working with test methods. I am trying to figure this out. Hopefully I enter enough code in here to determine where my mistake is.


This is what I am testing...



@Test
public void testComputePercent()
{
// Create
GradeCalculator gradeCalc = new GradeCalculator();
// Set
gradeCalc.accrueTotalScore(50);
gradeCalc.accrueMaximumScore(100);
// Test
assertEquals(.5, gradeCalc.computePercent(), .01);
}


I already know the answer will not be .5, but I am trying to figure out what is going on.


Here is the code.



public double computePercent()
{
if (this.totalScore == 0 || this.maximumScore == 0)
{
System.out.println("OH NO. You had a 0 in your score somewhere.");
}
double myGrade = (this.totalScore / this.maximumScore) * 100;
return myGrade;
}


Basically, if I scored 50 on my test (out of 100), the program will display a grade for me. 50/100 = .5 * 100 = 50%


For whatever reason, when I test the test, it says that .5 was expected (which I already know) and that 0.0 was entered. Which I am not too sure why as I am passing the right ints.


Below are my setters and getters.



public void accrueTotalScore(int inScore)
{
this.totalScore = inScore;
}

public void accrueMaximumScore (int inScore)
{
this.maximumScore = inScore;
}

public int getTotalScore()
{
return this.totalScore;
}

public int getMaximumScore()
{
return this.maximumScore;
}


Any help will be awesome.



asked 27 secs ago







Test Class not working right within my Java

Java Program debugging


Vote count:

0




So, for school I have to submit my source code to WebCat (an autograding program). It is giving me the following errors:



ArraySet test case - method equals(ArraySet<T> s) Verifying {1, 2, 3} equals {1, 2, 3} java.lang.ArrayIndexOutOfBoundsException: -1

ArraySet test case - method union(ArraySet<T> s) Verifying {1, 2, 3} union {1, 2, 3} is {1, 2, 3} java.lang.ArrayIndexOutOfBoundsException: -1

ArraySet test case - method intersection(ArraySet<T> s) Verifying {1, 2, 3} intersection {1, 2, 3} is {1, 2, 3} java.lang.ArrayIndexOutOfBoundsException: -1

ArraySet test case - method complement(ArraySet<T> s) Verifying {1, 2, 3} complement {1, 2, 3} is {} java.lang.ArrayIndexOutOfBoundsException: -1


But I cannot reproduce any of them in my own test cases for the life of me. Any insight?



asked 27 secs ago







Java Program debugging

My unicode(crylic) characters are auto changed


Vote count:

0




Sorry. My English is bad. I'm using ASP.NET VS2010, sql server 2008 R2, Windows server 2008. Server computer is located in my office. a few days later, my unicode(crylic) characters are replaced html tag. Fix it, repeated again in a few days. I havent any stored procedure "html tag to save sql server". Help me. http://ift.tt/1AHCxqH



asked 35 secs ago







My unicode(crylic) characters are auto changed

Missing return statement with switch


Vote count:

0





public AlertStatus nextStatus(){
int randNum = randNumGen.nextInt(3);
switch(randNum){
case 0: return new AlertStatusGreen();
case 1: return new AlertStatusYellow();
case 2: return new AlertStatusRed();
default: System.out.println("ERROR: no random number.");
}
}


This is a method in one of the classes for a program I have to make for school. The switch takes a random integer and uses it to return an object of a certain class that is derived from the class AlertStatus.


For some reason I keep getting an error saying "missing return statement }" for line 9 of the above block of code (the very last line in the above code). I don't understand why it's saying this though seeing as I already have return statements for each case.


Thanks!



asked 4 secs ago







Missing return statement with switch

Zend ajax form + first time populate


Vote count:

0




in my document/detail i have table with some users and on each row i have link to edit this user (form oppened in twitter bootstrap modal). In form submit i have parametr 'onclick' => 'return submitForm();' where submitForm() is an ajax action to resend data back to controller to dynamic zend validation. Problem is when I want to populate to edit form right users data after I open form in modal for first time. Probably i can do it by jquery so when i click on modal open link it will take data from table row and fill form elements...but here is problem that in table row I usually dont have all users data (minimalistic table) so i cannot populate all form elements.


controller:



public function detaillAction() {
$id = $this->_getParam("id", 0); //document id
$document = new Application_Model_DbTable_Document();
$doc = $document->findById($id);
//..and some another models

$this->view->headScript()->appendFile($this->view->baseUrl('/js/document-edit_user.js'));
$form_edit_users = new Application_Form_EditUsers();
if ($this->_request->isXmlHttpRequest()) {
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
//send json error messages here
}
}
else{
//First time populate form
$users = new Application_Model_DbTable_Users();
$user = $users->findById($user_id); //where to get this id?
$form_edit_users->populate($user);
$this->view->form_edit_users = $form_edit_users;
}
}


So what is best way how to get user_id for first time form render to this controller? Thx



asked 1 min ago







Zend ajax form + first time populate

How can I find CSS files using golang Gorilla mux


Vote count:

0




I'm using Go with Gorilla Mux.


This is my webserver.go file



package main

import (
"log"
"net/http"

"http://ift.tt/J9WoXt"
)

func HomeHandler(rw http.ResponseWriter, r *http.Request) {
http.ServeFile(rw, r, "index.html")
}

func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)

http.Handle("/", r)

log.Println("Server running on :8080")
err := http.ListenAndServe(":8080", r)
if err != nil {
log.Printf("Error: %s\n", err.Error())
}
}


In the same folder where the webserver.go file is located is the index.html file.


/ - here is the index.html


/css - All the CSS files


/images - All the images, resource files


I manage to load the index.html file using the above code but it doesn't seem to load the CSS files and images.


inside the index.html file I have.



<link rel="stylesheet" type="text/css" href="css/demo.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/animate-custom.css" />


So it should find the css files or do I have to make sure that "Go" can find the css and image folder? How?



asked 52 secs ago







How can I find CSS files using golang Gorilla mux

SwipeRefreshLayout pull up, how to do?


Vote count:

0




I want make SwipeRefreshLayout pull up, how to do? I would like to do an update on the basis of SwipeRefreshLayout. Is it possible to configure it SwipeRefreshLayout?



asked 54 secs ago







SwipeRefreshLayout pull up, how to do?

Importing an app-comat v7 library eclipse project to android studio


Vote count:

0




I have an android application created in eclipse, now I want to import it to android studio, when I import project I get the following error



Project FinalProject Integrate:/home/vishal/Android_Workspace/FinalProject Integrate/project.properties:
Library reference ../android-support-v7-appcompat could not be found
Path is /home/vishal/Android_Workspace/FinalProject Integrate/../android-support-v7-appcompat which resolves to /home/vishal/Android_Workspace/android-support-v7-appcompat


asked 34 secs ago







Importing an app-comat v7 library eclipse project to android studio

Load CSV file with Spark


Vote count:

0




I'm new to Spark and I'm trying to read CSV data from a file with Spark. Here's what I am doing :



sc.textFile('file.csv')
.map(lambda line: (line.split(',')[0], line.split(',')[1]))
.collect()


I would expect this call to give me a list of the two first columns of my file but I'm getting this error :



File "<ipython-input-60-73ea98550983>", line 1, in <lambda>
IndexError: list index out of range


although my CSV file as more than one column.



asked 28 secs ago







Load CSV file with Spark

MongoDB MonkAPI setting a variable based on find result that is available outside the db request


Vote count:

0




I'm trying to set a variable based on the result of a find through Monk API on MongoDB in a Node JS application (it's my first time of using MongoDB).


This is an example of the code I have;



var variableIWantToSet;
var collection = req.db.get('myCollection');
collection.find( { foo: 'bar' },{
fields : { myTargetField: 1, _id: 0},
limit : 1,
sort : {$natural : -1}
}
, function(err, doc) {
if (err) {
console.log(err);
}
variableIWantToSet = doc[0].myTargetField;
});
console.log(myTargetField);


If I console.log(doc[0].myTargetField) within the function I get the right value, but it doesn't set the variableIWantToSet.


Help appreciated. Thanks.



asked 1 min ago







MongoDB MonkAPI setting a variable based on find result that is available outside the db request

Globally replace NSPasteboard.generalPasteboard()


Vote count:

0




I want the NSPasteboard.generalPasteboard() to be temporarily switched to a custom one generated by my app using NSPasteboard.pasteboardWithUniqueName()


So that when the user presses Cmd+C/Cmd+V while the pasteboard is switched, my app's pasteboard gets used instead of the general pasteboard.


Is there a way to do this?



asked 38 secs ago







Globally replace NSPasteboard.generalPasteboard()

TextView fromHtml links broken on Lollypop


Vote count:

0




Our application had several instances of TextViews with its contents set by myTv.setText(Html.fromHtml()); that have been working for Android 4.4.0 and below.


Starting from 4.4.2 and Lollypop these links have stopped working. The text still appears underlined and with a hyperlink color, but tapping them yields no results.


It has to be said that those fields are marked as copy-pasteable, which is known to have interactions with those spannables.


Has anyone been able to solve this issue?



asked 40 secs ago







TextView fromHtml links broken on Lollypop

C# show data of ExpandoObject - Cannot convert lambda expression to type '…' because it is not a delegate


Vote count:

0




I have this method:



public ActionResult dataGrid()
{
List<ExpandoObject> list = new List<ExpandoObject>();

using (OdbcCommand DbCommand = repODBC.dbConnection.CreateCommand())
{
DbCommand.CommandText = "Select * From MyTable";
OdbcDataReader reader = DbCommand.ExecuteReader();

while (reader.Read())
{
dynamic obj = new ExpandoObject();
obj.name="Peter";
obj.num=123;
obj.id=1;
list.Add(obj);
}

return View(list);
}
}


I try to access data this way. I use Grid.Mvc... :



@Html.Grid((IEnumerable<System.Dynamic.ExpandoObject>)Model).Columns(columns =>
{
columns.Add(m => m.id).Titled("ID");
columns.Add(m => m.name).Titled("Name");
columns.Add(m => m.num).Titled("OS").Filterable(true);
})


but i get this error: Cannot convert lambda expression to type 'GridMvc.Columns.IGridColumn' because it is not a delegate


How can I add columns to grid to show data of ExpandoObject?



asked 1 min ago







C# show data of ExpandoObject - Cannot convert lambda expression to type '…' because it is not a delegate

creating a clickable php calendar


Vote count:

0




I am making a calendar in php. please help me because what I want to happen is that it should look like a real calendar and each day should be clickable and in that way, I can add info/note or a reminder to that day. I dont how to start with it. thanks



asked 57 secs ago







creating a clickable php calendar

OpenGl GluLookAt to GlRotated and GlTranslated


Vote count:

0




Actually, I try to solve a little problem and I dont understand how this GluLookAt works in OpenGl.


I would like to know how to transform this two lines :



gluLookAt(5.0, 15.0, 2.0, 0.0, 0.0, 0.0, 1.0, 0.0, -1.0);
gluLookAt(5.0, 0.0, 5.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0);


using glRotatef and glTranslatef.


After some searches, it seems to exist a way for making that thing :



glRotatef();
glRotatef();
glTranslatef(5.0,15.0,2.0);

glRotatef();
glRotatef();
glTranslatef(5.0,0.0,5.0);


So just by using two rotations and one translation. But I dont understand how can i find the angles and the axes of these rotations.


Ty in advance. I start becoming crazy with these rotations.



asked 1 min ago







OpenGl GluLookAt to GlRotated and GlTranslated

MATLAB: findpeaks function


Vote count:

0




I'm using MATLAB 2013a and trying to find peak points of my data. When I tried code example given in Find Peaks with Minimum Separation


I am getting the following error:



Error using uddpvparse (line 122)
Invalid Parameter/Value pairs.

Error in findpeaks>parse_inputs (line 84)
hopts = uddpvparse('dspopts.findpeaks',varargin{:});

Error in findpeaks (line 59)
[X,Ph,Pd,Th,Np,Str,infIdx] = parse_inputs(X,varargin{:});


I tried simple x and y vectors and got the same error. What can be the problem?



asked 29 secs ago







MATLAB: findpeaks function

Blender export to obj format not redered well on three.js


Vote count:

0




I am using Three.js to create a game, i load obj files with materials without problems if i download the as obj format but if i download a blender file and export it to obj format it be loaded and rendered without materials and textures


The file in Blender The rendered obj file



asked 36 secs ago







Blender export to obj format not redered well on three.js

Eloquent Join - where closure


Vote count:

0




Is there any way to use closure for where in join clause in Eloquent?


What I'm trying to do is:



$model = $model->leftJoin('history', function ($join) {
$join->on('history.record_id', '=', 'work_order.work_order_id');
$join->where('history.tablename', '=', 'test');
$join->where('history.columnname', '=', 'column');

$join->where(function ($q) {
$q->where('history.value_from', '=', '0')
->orWhere('history.value_from', '=', '');
});

$join->where('history.value_to', '>', '0');
});


but obviously the part:



$join->where(function ($q) {
$q->where('history.value_from', '=', '0')
->orWhere('history.value_from', '=', '');
});


doesn't work because JoinClause doesn't support closure for where



asked 19 secs ago







Eloquent Join - where closure

Call a function on each http request


Vote count:

0




In my Apigility project I have different Rest resources, all of them extends my class ResourseAbstract and in there I extend the AbstractResourceListener as Apigility needs.


So for example my resource User:



<?php
namespace Marketplace\V1\Rest\User;

use ZF\ApiProblem\ApiProblem;
use Marketplace\V1\Abstracts\ResourceAbstract;

class UserResource extends ResourceAbstract
{
public function fetch($id)
{
$result = $this->getUserCollection()->findOne(['id'=>$id]);
return $result;
}
}


And ResourceAbstract:



<?php

namespace Marketplace\V1\Abstracts;

use ZF\Rest\AbstractResourceListener;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZF\ApiProblem\ApiProblem;

class ResourceAbstract extends AbstractResourceListener implements ServiceLocatorAwareInterface {

}


Now, I need to run a function each time an http request is made, if I query /user in my browser the UserResource class will get instantiated and so the ResourceAbstract, my "solution" to get something to run on each call was to use a constructor inside ResourceAbstract, and this "works":



function __construct() {
$appKey = isset(getallheaders()['X-App-Key']) ? getallheaders()['X-App-Key'] : null;
$token = isset(getallheaders()['X-Auth-Token']) ? getallheaders()['X-Auth-Token'] : null;
//some code
return new ApiProblem(400, 'The request you made was malformed');
}


The thing is I need to return an ApiProblem in some cases (bad headers on the http request), but as you know constructor function does not return parameters. Another solution will be to thrown an exception but in Apigility you are supposed to ise ApiProblem when there is an api problem. Is the constructor approach correct? How will you solve this?



asked 56 secs ago

DomingoSL

3,062






Call a function on each http request

what and why are: Activity, Window, Display, Presentation and UI


Vote count:

0




I have been reading about these terms but I need help to understand why they all needed. Please explain with easy to understand analogies why each exists and how it is used to make an Android App.


Thank you



asked 1 min ago







what and why are: Activity, Window, Display, Presentation and UI

Try/Catch fails to catch exception in stored procedure


Vote count:

0




I'm struggling to get my try/catch to work with my stored procedure, it seems to not catch the error. I've been searching around, but no luck. What I'm trying to accomplish is to display the error number if an invalid value, no value, or null is given when the stored procedure is called. I've tried moving the try and catch it feels like everywhere, but it seems like the error may be on the "@SomeID as int" line. I appreciate any help I can get.





alter procedure DeleteAcct
@SomeID as int
as
begin try
declare @counter int
set @counter = (select count(SomeDate) from Table1 where SomeID = @SomeID group by SomeID)
begin
if(@counter > 0)
begin
Print 'Testing'
end
else
begin
delete from Table2
where SomeID = @SomeID
Print 'Delete successful'
end
end
end try
begin catch
print error_number()
end catch

<!-- calling the stored procedure -->
exec DeleteAcct '1231231231221'

<!-- Error received -->
Msg 8114, Level 16, State 5, Procedure DeleteAcct, Line 0
Error converting data type varchar to int.




asked 1 min ago







Try/Catch fails to catch exception in stored procedure

Multiple selection from Drop down List


Vote count:

0




Hie,I had asked this question already but I have make it briefly now please share some logic. 1st dropdown List-enter image description here Contain Class-1, class-2, class-3..etc. 2nd dropdown List-enter image description here Depends on class.If we chose class-1 and class-2 then respective Student Id will show on 2nd dropdown list. I want selected Classes in respective variables and selected turbines in respective variable. Then I will get this selected variables and use in another page.


I want multiple selection in each dropdown list. suppose I have select one Class-1 then, On the classId second dropdown list will fill with respective studentID,again I am select another class-2 then again Add respective studentID list in 2nd dropdown list.


In my databse script ClassId and StudentId this attribute present in same table only (not diffrent tables).


Table view somewhat like this->



ClassID StudentID StudentNm
1 101 abc
1 102 xyz
1 103 jkl
2 201 uio
2 202 tyu
3 302 qwe
3 305 zxc


asked 33 secs ago







Multiple selection from Drop down List

Showing a view controller from a parallel window (with the same parent)


Vote count:

0




I am trying to show a ViewController directly from its sibling window, the tree looks kinds like this: CalibrationVC<--- MainVC ---> Settings VC. The MainVC presents the other two modally, and over current context. Now what I want to do is click a button in SettingsVC, that would open the CalibrationVC for a specific device. I have managed to do so using unwind segues and a delegate from the SettingsVC, and it looks like this:



- (void)showViewForDeviceCalibration
{
[self performSegueWithIdentifier:@"showCalibrationViewFromSettings" sender:nil];
}

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"showCalibrationViewFromSettings"])
{
[_delegate calibrateDevice:deviceToConfigure];
}
}


The delegate implementation:



-(void)calibrateDevice:(Device *)device
{
dispatch_block_t autoinitService =
^{
deviceToCalibrateFromSettings = device;
[NSThread sleepForTimeInterval:0.2];
dispatch_async(dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:@"showCalibrationViewForDeviceFromSettings" sender:nil];
});

};

dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), autoinitService);
}


And the prepare for segue method:



- (void)prepareForSegue: (UIStoryboardSegue *)segue sender:(id) sender
{
if ([segue.identifier isEqualToString:@"showCalibrationViewForDeviceFromSettings"])
{
CalibrationViewController *destinationController = (CalibrationViewController*)segue.destinationViewController;
NSArray *devicesToCalibrate = [NSArray arrayWithObject:deviceToCalibrateFromSettings];
[destinationController setDevicesToCalibrate: devicesToCalibrate];
}


This works well, but is there a better way to do that? I am really concerned about the delegate implementation because it uses a separate thread only to wait for a moment and then use the main thread again. I had to do this because without it the CalibrationVC would not appear saying that the MainVC is already presenting. So to sum thing up, is there a better, more optimal/proper way to do this?



asked 49 secs ago







Showing a view controller from a parallel window (with the same parent)

save end of line to data base


Vote count:

0




C#



MySqlConnection connection = new MySqlConnection(myConnectionString);
string command = "update `triggers` set tri_webbot=@text where `triggers`.TRI_UID='" + TRI_UID + "'";
MySqlCommand myCommand = new MySqlCommand(command, connection);
myCommand.Parameters.AddWithValue("@text", text);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
connection.Close();


Text



test
test
test


when run query text save to field database as 'testtesttest' and does not save end of line and space.


Questino how can save space and EOF(end of line) to database field?



asked 50 secs ago







save end of line to data base

c# how to open another program from my first?


Vote count:

0




I want to open a second program from my first program and still be able to work on my first program. and another thing is to close the second program from my first. is there a way to this?



asked 30 secs ago







c# how to open another program from my first?

I am new to python.Please help me to do this


Vote count:

-1




shopping_list = ["banana", "orange", "apple"]


stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 }


prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 }


Want to calculate compute_bill function:


While you loop through each item of food, only add the price of the item to total if the item's stock count is greater than zero. If the item is in stock and after you add the price to the total, subtract one from the item's stock count.



asked 1 min ago







I am new to python.Please help me to do this

How to convert nested list strings to integers then sort them in python 3?


Vote count:

0




Not an experienced programmer! Currently studying a computing GCSE in school and need help with a problem.


I have a nested list that holds the information of student names and then their score in a text file, this file then needs to be imported into a nested list. I have done this using the code -



asked 28 secs ago







How to convert nested list strings to integers then sort them in python 3?

Return 0 when regex match is found (PHP)


Vote count:

0




I am hoping to return 0 when 2011-2016 is found in the string. For the life of me I cannot figure out a regex that will return 0 when a match is found and 1 when there is no match. Yes I could easily negate the entire statement but I was hoping to find a solution so that my code could stay tidy. Slightly OCD? yes, hope you can help, here's the PHP code. Be nice I am still learning. The code which I am hoping to change is in function passCheck variable $patternArray under the last element of the array. That is the pattern I have currently. I am hoping to return 0 when 2011-2016 is found in the string. I have looked into the looking ahead stuff and maybe its just late but I cant wrap my head around it (may not be the right approach).



<?php function digitsStr($pass)
{
$nums=array();
$splt=str_split($pass);
$count=count($splt);
for($i=0;$count>$i;$i++)
{
if(preg_match("/\d/", $splt[$i])==1)
{
array_push($nums, $splt[$i]);
unset($splt[$i]);
}
}
$nums=array_merge($nums, $splt);
$str=implode($nums);
return $str;
}
?>

<?php function passCheck($string)
{
$string=digitsStr($string);
$len=strlen($string);
$msgArray=array("Must be 8-16 characters long ",
"Cannot contain a white space ",
"Does not contain at least 2 digits ",
"Must contain at least 1 uppercase ",
"Must contain at least 1 lowercase ",
"Must contain one special charcter",
"Cannot contain years 2011-2016");
$patternArray=array("/^.{8,16}$/",
"/\S{".$len."}/",
"/\d{2,}/",
"/[A-Z]/",
"/[a-z]/",
"/([!-\/]|[:-@])/",
"/201(?![1-6])/");
for($i=0;count($patternArray)>$i;$i++)
{
if(preg_match($patternArray[$i], $string)==0)
{
echo $msgArray[$i];
}
}
}
?>

<?php
$string="#M2010ATt123";
passCheck($string)
?>


asked 28 secs ago







Return 0 when regex match is found (PHP)

use of hashCode() and equals() in TreeSet and TreeMap


Vote count:

0




From the following code, I understand that, there is no need of overriding equals() and hashCode() method for TreeSet and TreeMap, neither for sorting, nor searching.



public class ComparableTest implements Comparable<ComparableTest> {

private String username;

public ComparableTest(String name) {
this.username = name;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public int compareTo(ComparableTest o) {
return username.compareTo(o.getUsername());
}

@Override
public String toString() {
return this.getUsername();
}

@SuppressWarnings("unchecked")
public static void main(String[] args) {

ArrayList<ComparableTest> comparableTestsList = new ArrayList<ComparableTest>();
ArrayList<ComparableTest> comparableTestsList2;

comparableTestsList.add(new ComparableTest("Second Name"));
comparableTestsList.add(new ComparableTest("First name"));
System.out.println("Orignal Array List = " + comparableTestsList);

// making a clone to test this list in Treeset
comparableTestsList2 = (ArrayList<ComparableTest>) comparableTestsList
.clone();
// Sorting the first arraylist which works
Collections.sort(comparableTestsList);
System.out.println("Sorted Array List = " + comparableTestsList);

// searching the first array which does not work as equals method has
// not been overriden
int position = comparableTestsList.indexOf(new ComparableTest(
"First name"));
System.out.println("The position of First name is = " + position);

//using the cloned collection in TreeSet
TreeSet<ComparableTest> ts = new TreeSet<ComparableTest>(
comparableTestsList2);
System.out.println("The value in Tree Set is = " + ts);

System.out.println("The position of First name is = " + ts.contains(new ComparableTest("First name")));//works fine

//using the cloned collection in TreeMap
TreeMap<ComparableTest, String> tMap = new TreeMap<>();
for(ComparableTest ct: comparableTestsList2) {
tMap.put(ct, "anushree");
}
System.out.println("The value in Tree Map is = " + tMap);
System.out.println(tMap.get(new ComparableTest("First name")));//works fine
}


} this goes perfectly fine with what's there in javadoc http://ift.tt/1pDJ95b a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.


there is also written: Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface.


how equals() and hashCode() comes into picture for TreeSet and TreeMap? Can I get a code sample. Thanks!



asked 30 secs ago







use of hashCode() and equals() in TreeSet and TreeMap

Error: import read failed(-1) when using rpm --import command


Vote count:

0




I am trying to import gpg release key with following command.


rpm --import 'http://ift.tt/1u6f53F'.


but i am getting a error "import read failed (-1)". I checked /etc/pki/rpm-gpg file.but nothing is imported.


please help to solve out this problem.


thanks.



asked 26 secs ago







Error: import read failed(-1) when using rpm --import command

how to make a selection more specific?


Vote count:

0




why does this work :





.move {-moz-transition: all 1s ease-out;}
.one:hover .move {-moz-transform: scale(0.5);}



and this not :





.move {-moz-transition: scale 1s ease-out;}
.one:hover .move {-moz-transform: scale(0.5);}



i dont want to select "all" - i only want to select the attribute i want to change (i posted only the -moz- prefix to keep the code shorter)



asked 1 min ago







how to make a selection more specific?

vendredi 27 février 2015

SFTP disable password authentication


Vote count:

0




I'm setting up a Debian 7 server for home use. I didn't install any FTP service since I prefer to use SFTP who comes with SSH. It works perfectly but, since for SSH I disabled password authentication and left only KEY auth, I'd like to do the same for SFTP (currently I can connect using my username and password).



asked 42 secs ago







SFTP disable password authentication

setOnitemClicklistener not working for listview


Vote count:

0




I'm using this ListviewAnimations library for expanding list items as it is clicked. But Listener is not listening events as row is clicked. Below is related codes. Ontouch or onclick are also not working. No error is coming but onclick event are also not getting called. What could be the reason behind it?


Basically I want to change the height of the list view after row is selected so that layout looks properly. I have other controls as well below this Listview in my main layout.


Thanks in advance.


Code:



ListView Images_list_view;
mExpandableListItemAdapter = new MyExpandableListItemAdapter(this,no_of_images);
Images_list_view = (ListView)findViewById(R.id.Images);
AlphaInAnimationAdapter alphaInAnimationAdapter = new AlphaInAnimationAdapter(mExpandableListItemAdapter);
alphaInAnimationAdapter.setAbsListView(Images_list_view);
assert alphaInAnimationAdapter.getViewAnimator() != null;
alphaInAnimationAdapter.getViewAnimator().setInitialDelayMillis(500);
Images_list_view.setAdapter(alphaInAnimationAdapter);

Images_list_view.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub

Log.d("Clicked","clicked");
//changeheight();


}
});


My Adapter:



public class MyExpandableListItemAdapter extends ExpandableListItemAdapter<Integer> {

Context mContext;
int no;
protected MyExpandableListItemAdapter(Context context,int no_of_images) {
super(context,R.layout.activity_expandablelistitem_card, R.id.activity_expandablelistitem_card_title, R.id.activity_expandablelistitem_card_content);
this.mContext=context;
this.no=no_of_images;
for (int i = 0; i < no; i++) {
add(i);
}

// TODO Auto-generated constructor stub
}

@Override
@NonNull
public View getContentView(int position, @Nullable View convertView,
@NonNull ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) convertView;
if (imageView == null) {
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
int imageResId = R.drawable.no_media;
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), imageResId);

imageView.setImageBitmap(bitmap);


return imageView;
}

@Override
@NonNull
public View getTitleView(int position, @Nullable View convertView,
@NonNull ViewGroup arg2) {
// TODO Auto-generated method stub
TextView tv = (TextView) convertView;
if (tv == null) {
tv = new TextView(mContext);
}

tv.setText(R.string.productimage);
return tv;
}


}


and xml file:



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/card_background_white"
android:orientation="vertical"
android:padding="16dp"
tools:ignore="overdraw">

<FrameLayout
android:id="@+id/activity_expandablelistitem_card_title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<FrameLayout
android:id="@+id/activity_expandablelistitem_card_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="4dp" />

</LinearLayout>


asked 1 min ago







setOnitemClicklistener not working for listview

jsPlumb is not redrawn after view change in angular.js?


Vote count:

0




I made a two pages using angularjs ngRoute. On first page I show two connected jsPlumb objects. Second page does not contain an Plumb object. However, when I go from first page to second Plumb objects does not disappear. Do you know how to achieve proper jsPlumb refresh with ng-view update?


http://ift.tt/1G295Pw


script.js



var app;
app = angular.module('ironcoderApp', [
'ngRoute',
'appControllers'
]);

app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/page1', {
templateUrl: 'page1.html',
controller: 'Page1Controller'
}).
when('/page2', {
templateUrl: 'page2.html',
controller: 'Page1Controller'
}).
otherwise({
redirectTo: '/page1'
});
}]);

var appControllers = angular.module('appControllers', []);

app.controller('Page1Controller', ['$scope', '$rootScope', '$routeParams', '$location', '$timeout',

function($scope, $rootScope, $routeParams, $location, $timeout) {
$scope.text = 'page1';

$timeout(function(){
jsPlumb.connect({'source': $("#page1el1"), 'target': $("#page1el2"), 'label': 'te'});
}, 0);
}
]);

app.controller('Page2Controller', ['$scope', '$rootScope', '$routeParams', '$location',

function($scope, $rootScope, $routeParams, $location) {
$scope.text = 'page2';
}
]);

app.controller('MainController', ['$scope', '$rootScope', '$location',
function($scope, $rootScope, $location) {
$scope.text = 'main';
}
]);


page.html:



<script type="text/ng-template" id="page1.html">

<div id="page1el1" style="border: 1px red solid; width: 60px;">page1el1</div>
<br>
<div id="page1el2" style="border: 1px red solid; width: 60px;">page1el2</div>
<br>
page1

<a href="#/page2">go to page2</a>

</script>

<script type="text/ng-template" id="page2.html">

<br><br><br><br><br><br><br>
<div id="page2el1" style="border: 1px green solid; width: 60px;">page2el1</div>
<br>
<div id="page2el2" style="border: 1px green solid; width: 60px;">page2el2</div>
<br>

page2

<a href="#/page1">go to page1</a>
</script>


<div ng-view >

</div>


asked 1 min ago







jsPlumb is not redrawn after view change in angular.js?