Notebook fn + f1 to switch the display, so why would the letter p?
I use Dell notebook and Ubuntu 12.04. A few days ago fn+f1 suddenly type
letter p instead of switch display monitor.
Need your help please.
Monday, 30 September 2013
Why is one stack piece in the Stackoverflow logo slightly off=?iso-8859-1?Q?=3F_=96_meta.stackoverflow.com?=
Why is one stack piece in the Stackoverflow logo slightly off? –
meta.stackoverflow.com
I understand this question has already been asked but in this I have
expounded on the issue and explain more unsightly features of the
Stackoverflow logo. I'm not sure why but every time I visit ...
meta.stackoverflow.com
I understand this question has already been asked but in this I have
expounded on the issue and explain more unsightly features of the
Stackoverflow logo. I'm not sure why but every time I visit ...
How could I read a file with header and then save the final file with header again?
How could I read a file with header and then save the final file with
header again?
I'd like to read file1 with given header and then implement some
mathematical operations on , for example, the x and Imag columns. Finally
I want to save the final file with header again.
How could I do it?
File1:
#ID ra dec x y Umag Bmag Vmag Rmag
Imag
1.0 53.141 -27.7967 3491.37 4060.43 23.1612 23.7058 23.0223 22.5351
22.1785
2.0 53.140 -27.7956 3496.66 4076.57 24.1362 24.8441 25.0093 24.7304
24.5864
3.0 53.142 -27.8008 3471.25 3997.29 24.1729 25.3841 25.3501 25.1032
25.0042
4.0 53.138 -27.7891 3527.16 4175.46 24.4685 26.1972 26.1785 25.5567
25.3188
5.0 53.146 -27.8085 3424.83 3880.66 24.425 25.1966 25.2755 24.9514
24.3456
header again?
I'd like to read file1 with given header and then implement some
mathematical operations on , for example, the x and Imag columns. Finally
I want to save the final file with header again.
How could I do it?
File1:
#ID ra dec x y Umag Bmag Vmag Rmag
Imag
1.0 53.141 -27.7967 3491.37 4060.43 23.1612 23.7058 23.0223 22.5351
22.1785
2.0 53.140 -27.7956 3496.66 4076.57 24.1362 24.8441 25.0093 24.7304
24.5864
3.0 53.142 -27.8008 3471.25 3997.29 24.1729 25.3841 25.3501 25.1032
25.0042
4.0 53.138 -27.7891 3527.16 4175.46 24.4685 26.1972 26.1785 25.5567
25.3188
5.0 53.146 -27.8085 3424.83 3880.66 24.425 25.1966 25.2755 24.9514
24.3456
Force To Read HttpWebResponse.GetResponseStream() When Content-Length Is Zero
Force To Read HttpWebResponse.GetResponseStream() When Content-Length Is Zero
As title said.
Sometime an HTTP response from remote server includes Content-Length
header with zero value, but it still return HTTP body. The body can still
be obtained with jQuery in browser, but using
HttpWebResponse.GetResponseStream() can't read anything. How do I force to
read it? Thanks everyone.
Here's an example of HTTP response which I met.
HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache,no-store
Content-Type: text/plain Content-Length: 0 Date: Mon, 30 Sep 2013 09:34:21
GMT
As title said.
Sometime an HTTP response from remote server includes Content-Length
header with zero value, but it still return HTTP body. The body can still
be obtained with jQuery in browser, but using
HttpWebResponse.GetResponseStream() can't read anything. How do I force to
read it? Thanks everyone.
Here's an example of HTTP response which I met.
HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache,no-store
Content-Type: text/plain Content-Length: 0 Date: Mon, 30 Sep 2013 09:34:21
GMT
Sunday, 29 September 2013
JNDI resource lookup fails with Glassfish
JNDI resource lookup fails with Glassfish
Created a JNDI custom resource:
imageBasePath
java.lang.String
/home/user/NetBeansProjects/Builder/images
Tried looking it up as follows:
InitialContext ctx;
try {
ctx = new InitialContext();
Object o = ctx.lookup("imageBasePath");
} catch (NamingException ex) {
Logger.getLogger(blanketBean.class.getName()).log(Level.SEVERE, null,
ex);
}
It throws exception:
(javax.naming.CommunicationException) javax.naming.CommunicationException:
Communication exception for
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is
java.lang.IllegalArgumentException: type cannot be null]
What am I doing wrong?
Created a JNDI custom resource:
imageBasePath
java.lang.String
/home/user/NetBeansProjects/Builder/images
Tried looking it up as follows:
InitialContext ctx;
try {
ctx = new InitialContext();
Object o = ctx.lookup("imageBasePath");
} catch (NamingException ex) {
Logger.getLogger(blanketBean.class.getName()).log(Level.SEVERE, null,
ex);
}
It throws exception:
(javax.naming.CommunicationException) javax.naming.CommunicationException:
Communication exception for
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is
java.lang.IllegalArgumentException: type cannot be null]
What am I doing wrong?
In programming languages, what is typically the way used to represent binary values?
In programming languages, what is typically the way used to represent
binary values?
I'm not asking about a particular language, but just in general. I know
that, for example, #0x or simply 0x is put before the number, or an h is
placed after the number, to refer to hexadecimal.
Is there a similar "standard" for binary?
binary values?
I'm not asking about a particular language, but just in general. I know
that, for example, #0x or simply 0x is put before the number, or an h is
placed after the number, to refer to hexadecimal.
Is there a similar "standard" for binary?
Bitmap font glyph offset and x axis?
Bitmap font glyph offset and x axis?
I have a bitmapfont, created with the angel'scode bitmap generator. I have
a png with the texture and a .fnt with the information of the font
(texture coordinates, char width and height, offsets, advance, etc...).
That information is stored inside a struct called 'glyph'
I am rendering those glyphs with this code:
float x_cursor = 0.0f;
// Record each char of my string
for(int i=0; i < [mystring length];i++)
{
// Get the char id
int mychar = (int)[mystring characterAtIndex:i];
// Get the glyph information of the char to render
GlyphChar glyph;
if([GlpyhCharBuffer count] < (mychar-first_char)+1)
continue;
NSValue * valuegly = [GlpyhCharBuffer objectAtIndex:(mychar-first_char)];
if(valuegly == nil)
{
continue;
}
[valuegly getValue:&glyph];
// Start with the OpenGL Drawing
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
// Where to draw our char
float y_offsetpos = screen_point[1] + TOGLUNIT(glyph.y_offset) * -1.0f;
float x_glyphpos = screen_point[0] +
TOGLUNIT(x_cursor+(float)glyph.x_offset);
GLKMatrix4 model_modifier = GLKMatrix4MakeTranslation(x_glyphpos,
y_offsetpos, 0.0f);
float glyph_width = TOGLUNIT((float)glyph.char_width);
float glyph_height = TOGLUNIT((float)glyph.char_height);
// Move the cursor in the x axis for the following char
x_cursor += (float)glyph.x_advance;
// Create our model matrix, for scale and translate our char
GLKMatrix4 model_modifier = GLKMatrix4MakeTranslation(x_glyphpos,
y_offsetpos, 0.0f);
model_modifier = GLKMatrix4Scale(model_modifier, glyph_width,
glyph_height,0.0f);
GLuint uniform_dir = glGetUniformLocation(program, "model_matrix");
glUniformMatrix4fv(uniform_dir, 1, GL_FALSE, model_modifier.m);
glBindBuffer(GL_ARRAY_BUFFER, square_buff);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindBuffer(GL_ARRAY_BUFFER, glyph.uvscoord);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindTexture(tex_information.target, tex_information.name);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
}
the X Axis is not working good, it gives a bad result:
I already tried with a lot of fonts, generated by the angel'scode and
stills giving the same error. How the X Aligning on a bitmap font works?
I have a bitmapfont, created with the angel'scode bitmap generator. I have
a png with the texture and a .fnt with the information of the font
(texture coordinates, char width and height, offsets, advance, etc...).
That information is stored inside a struct called 'glyph'
I am rendering those glyphs with this code:
float x_cursor = 0.0f;
// Record each char of my string
for(int i=0; i < [mystring length];i++)
{
// Get the char id
int mychar = (int)[mystring characterAtIndex:i];
// Get the glyph information of the char to render
GlyphChar glyph;
if([GlpyhCharBuffer count] < (mychar-first_char)+1)
continue;
NSValue * valuegly = [GlpyhCharBuffer objectAtIndex:(mychar-first_char)];
if(valuegly == nil)
{
continue;
}
[valuegly getValue:&glyph];
// Start with the OpenGL Drawing
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
// Where to draw our char
float y_offsetpos = screen_point[1] + TOGLUNIT(glyph.y_offset) * -1.0f;
float x_glyphpos = screen_point[0] +
TOGLUNIT(x_cursor+(float)glyph.x_offset);
GLKMatrix4 model_modifier = GLKMatrix4MakeTranslation(x_glyphpos,
y_offsetpos, 0.0f);
float glyph_width = TOGLUNIT((float)glyph.char_width);
float glyph_height = TOGLUNIT((float)glyph.char_height);
// Move the cursor in the x axis for the following char
x_cursor += (float)glyph.x_advance;
// Create our model matrix, for scale and translate our char
GLKMatrix4 model_modifier = GLKMatrix4MakeTranslation(x_glyphpos,
y_offsetpos, 0.0f);
model_modifier = GLKMatrix4Scale(model_modifier, glyph_width,
glyph_height,0.0f);
GLuint uniform_dir = glGetUniformLocation(program, "model_matrix");
glUniformMatrix4fv(uniform_dir, 1, GL_FALSE, model_modifier.m);
glBindBuffer(GL_ARRAY_BUFFER, square_buff);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindBuffer(GL_ARRAY_BUFFER, glyph.uvscoord);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindTexture(tex_information.target, tex_information.name);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
}
the X Axis is not working good, it gives a bad result:
I already tried with a lot of fonts, generated by the angel'scode and
stills giving the same error. How the X Aligning on a bitmap font works?
perl if eq statement no work in array
perl if eq statement no work in array
I have a string
$seq1= 'ATCGATGCAATTCCGGAAAAAATTTTCCCGGGGGGGAAACCCGGGAAATTT'
so i want to find the frequence of char from user input in this string.
So i change this string to array
$base= <STDIN>; # you can input A or T or C or G
my @Freq1= split //, $seq1;
Then use for loop to calculate the total number of char
for(my $i=0;$i<@Freq1;$i++) {
if($Freq1[$i] eq chomp($base)) {
print "equals $i\n";
$numberbase++;
}
}
But the $Freq1[$i] eq chomp($base) can't work. I don't know why?
I have a string
$seq1= 'ATCGATGCAATTCCGGAAAAAATTTTCCCGGGGGGGAAACCCGGGAAATTT'
so i want to find the frequence of char from user input in this string.
So i change this string to array
$base= <STDIN>; # you can input A or T or C or G
my @Freq1= split //, $seq1;
Then use for loop to calculate the total number of char
for(my $i=0;$i<@Freq1;$i++) {
if($Freq1[$i] eq chomp($base)) {
print "equals $i\n";
$numberbase++;
}
}
But the $Freq1[$i] eq chomp($base) can't work. I don't know why?
Saturday, 28 September 2013
Android sqlite item not being deleted
Android sqlite item not being deleted
Here is my main class
public class HomeScreenActivity extends Activity {
private Button contactButton;
private Button groupContactButton;
private Button historyButton;
private Button optionsButton;
private ListView contactsView;
public static int selectedContactIndex = -1;
DatabaseHandler db;
List<Contact> contactList;
ArrayAdapter<Contact> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
contactButton = (Button) findViewById(R.id.contactButton);
contactButton.setSelected(true);
groupContactButton = (Button) findViewById(R.id.groupContactButton);
historyButton = (Button) findViewById(R.id.historyButton);
optionsButton = (Button) findViewById(R.id.optionsButton);
contactsView = (ListView) findViewById(R.id.contactsView);
// Set up contact adaptor so the contact list can be viewed in the
// homescreen
db = new DatabaseHandler(this);
contactList = db.getAllContacts();
adapter = new ArrayAdapter<Contact>(this,
R.layout.home_screen_contacts_view, contactList);
contactsView.setAdapter(adapter);
adapter.setNotifyOnChange(true);
// Set Listeners
contactButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setSelected(true);
groupContactButton.setSelected(false);
historyButton.setSelected(false);
}
});
groupContactButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setSelected(true);
historyButton.setSelected(false);
contactButton.setSelected(false);
}
});
historyButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setSelected(true);
groupContactButton.setSelected(false);
contactButton.setSelected(false);
}
});
optionsButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
openOptionsMenu();
}
});
contactsView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
selectedContactIndex = (int) arg3;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.viewContactDetails:
return true;
case R.id.editContactDetails:
if (selectedContactIndex == -1) {// When no contact is selected,
// inform user.
makeAToast("Please select a contact to edit!");
return true;
}
startActivity(new Intent(this, EditContactActivity.class));
return true;
case R.id.newContact:
startActivity(new Intent(this, NewContactActivity.class));
return true;
case R.id.deleteContact:
if (selectedContactIndex == -1) {// When no contact is selected,
// inform user.
makeAToast("Please select a contact to delete!");
return true;
}
// Create an alert asking for contact deletion confirmation.
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this,
AlertDialog.THEME_DEVICE_DEFAULT_DARK);
myAlertDialog.setTitle("Confirm Contact Deletion");
myAlertDialog.setMessage("Are you sure you want to delete "
+ db.getContact(selectedContactIndex).getFullName()
+"?"); //ADD THE CONTACT NAME
// Set listener for when they press yes, delete contact and
inform
// user.
myAlertDialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
db.deleteContact(db.getContact(selectedContactIndex
+ 1));
makeAToast("Contact successfully deleted.");
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,First
Name: " + cn.getFirstName()
+" ,Last Name: " + cn.getLastName()
+" ,Mobile Number: " +
cn.getMobileNumber()
+" ,Home Number: " +
cn.getHomeNumber()
+" ,Work Number: " +
cn.getWorkNumber()
+" ,Home Address: " +
cn.getHomeAddress()
+" ,Email Address: " +
cn.getEmailAddress()
+" ,Work Address: " +
cn.getWorkAddress()
+" ,Contact Notes: " +
cn.getContactNotes();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
});
And here is my database handler class:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_FIRST_NAME = "first_name";
private static final String KEY_LAST_NAME = "last_name";
private static final String KEY_MOB_NO = "mobile_number";
private static final String KEY_HOME_NO = "home_number";
private static final String KEY_WORK_NO = "work_number";
private static final String KEY_HOME_ADDR = "home_address";
private static final String KEY_EMAIL_ADDR = "email_address";
private static final String KEY_WORK_ADDR = "work_address";
private static final String KEY_NOTES = "notes";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FIRST_NAME + " TEXT," + KEY_LAST_NAME + " TEXT,"
+ KEY_MOB_NO + " TEXT," + KEY_HOME_NO + " TEXT," +
KEY_WORK_NO
+ " TEXT," + KEY_HOME_ADDR + " TEXT," + KEY_EMAIL_ADDR
+ " TEXT," + KEY_WORK_ADDR + " TEXT," + KEY_NOTES + " TEXT"
+ ");";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, Contact.totalContacts);
values.put(KEY_FIRST_NAME, contact.getFirstName());
values.put(KEY_LAST_NAME, contact.getLastName());
values.put(KEY_MOB_NO, contact.getMobileNumber());
values.put(KEY_HOME_NO, contact.getHomeNumber());
values.put(KEY_WORK_NO, contact.getWorkNumber());
values.put(KEY_HOME_ADDR, contact.getHomeAddress());
values.put(KEY_EMAIL_ADDR, contact.getEmailAddress());
values.put(KEY_WORK_ADDR, contact.getWorkAddress());
values.put(KEY_NOTES, contact.getContactNotes());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_FIRST_NAME, KEY_LAST_NAME, KEY_MOB_NO, KEY_HOME_NO,
KEY_WORK_NO, KEY_HOME_ADDR, KEY_EMAIL_ADDR, KEY_WORK_ADDR,
KEY_NOTES }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),
cursor.getString(3),
cursor.getString(4), cursor.getString(5),
cursor.getString(6),
cursor.getString(7), cursor.getString(8),
cursor.getString(9));
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setFirstName(cursor.getString(1));
contact.setLastName(cursor.getString(2));
contact.setMobileNumber(cursor.getString(3));
contact.setHomeNumber(cursor.getString(4));
contact.setWorkNumber(cursor.getString(5));
contact.setHomeAddress(cursor.getString(6));
contact.setEmailAddress(cursor.getString(7));
contact.setWorkAddress(cursor.getString(8));
contact.setContactNotes(cursor.getString(9));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FIRST_NAME, contact.getFirstName());
values.put(KEY_LAST_NAME, contact.getLastName());
values.put(KEY_MOB_NO, contact.getMobileNumber());
values.put(KEY_HOME_NO, contact.getHomeNumber());
values.put(KEY_WORK_NO, contact.getWorkNumber());
values.put(KEY_HOME_ADDR, contact.getHomeAddress());
values.put(KEY_EMAIL_ADDR, contact.getEmailAddress());
values.put(KEY_WORK_ADDR, contact.getWorkAddress());
values.put(KEY_NOTES, contact.getContactNotes());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Now, when I delete a contact, not only is it not updating the listview in
my main contacts screen, but when I write all my contacts to log cat, the
contact never even got deleted from the database. Any ideas as to why that
is?
Here is my main class
public class HomeScreenActivity extends Activity {
private Button contactButton;
private Button groupContactButton;
private Button historyButton;
private Button optionsButton;
private ListView contactsView;
public static int selectedContactIndex = -1;
DatabaseHandler db;
List<Contact> contactList;
ArrayAdapter<Contact> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
contactButton = (Button) findViewById(R.id.contactButton);
contactButton.setSelected(true);
groupContactButton = (Button) findViewById(R.id.groupContactButton);
historyButton = (Button) findViewById(R.id.historyButton);
optionsButton = (Button) findViewById(R.id.optionsButton);
contactsView = (ListView) findViewById(R.id.contactsView);
// Set up contact adaptor so the contact list can be viewed in the
// homescreen
db = new DatabaseHandler(this);
contactList = db.getAllContacts();
adapter = new ArrayAdapter<Contact>(this,
R.layout.home_screen_contacts_view, contactList);
contactsView.setAdapter(adapter);
adapter.setNotifyOnChange(true);
// Set Listeners
contactButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setSelected(true);
groupContactButton.setSelected(false);
historyButton.setSelected(false);
}
});
groupContactButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setSelected(true);
historyButton.setSelected(false);
contactButton.setSelected(false);
}
});
historyButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setSelected(true);
groupContactButton.setSelected(false);
contactButton.setSelected(false);
}
});
optionsButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
openOptionsMenu();
}
});
contactsView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
selectedContactIndex = (int) arg3;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.viewContactDetails:
return true;
case R.id.editContactDetails:
if (selectedContactIndex == -1) {// When no contact is selected,
// inform user.
makeAToast("Please select a contact to edit!");
return true;
}
startActivity(new Intent(this, EditContactActivity.class));
return true;
case R.id.newContact:
startActivity(new Intent(this, NewContactActivity.class));
return true;
case R.id.deleteContact:
if (selectedContactIndex == -1) {// When no contact is selected,
// inform user.
makeAToast("Please select a contact to delete!");
return true;
}
// Create an alert asking for contact deletion confirmation.
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this,
AlertDialog.THEME_DEVICE_DEFAULT_DARK);
myAlertDialog.setTitle("Confirm Contact Deletion");
myAlertDialog.setMessage("Are you sure you want to delete "
+ db.getContact(selectedContactIndex).getFullName()
+"?"); //ADD THE CONTACT NAME
// Set listener for when they press yes, delete contact and
inform
// user.
myAlertDialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
db.deleteContact(db.getContact(selectedContactIndex
+ 1));
makeAToast("Contact successfully deleted.");
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,First
Name: " + cn.getFirstName()
+" ,Last Name: " + cn.getLastName()
+" ,Mobile Number: " +
cn.getMobileNumber()
+" ,Home Number: " +
cn.getHomeNumber()
+" ,Work Number: " +
cn.getWorkNumber()
+" ,Home Address: " +
cn.getHomeAddress()
+" ,Email Address: " +
cn.getEmailAddress()
+" ,Work Address: " +
cn.getWorkAddress()
+" ,Contact Notes: " +
cn.getContactNotes();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
});
And here is my database handler class:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_FIRST_NAME = "first_name";
private static final String KEY_LAST_NAME = "last_name";
private static final String KEY_MOB_NO = "mobile_number";
private static final String KEY_HOME_NO = "home_number";
private static final String KEY_WORK_NO = "work_number";
private static final String KEY_HOME_ADDR = "home_address";
private static final String KEY_EMAIL_ADDR = "email_address";
private static final String KEY_WORK_ADDR = "work_address";
private static final String KEY_NOTES = "notes";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FIRST_NAME + " TEXT," + KEY_LAST_NAME + " TEXT,"
+ KEY_MOB_NO + " TEXT," + KEY_HOME_NO + " TEXT," +
KEY_WORK_NO
+ " TEXT," + KEY_HOME_ADDR + " TEXT," + KEY_EMAIL_ADDR
+ " TEXT," + KEY_WORK_ADDR + " TEXT," + KEY_NOTES + " TEXT"
+ ");";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, Contact.totalContacts);
values.put(KEY_FIRST_NAME, contact.getFirstName());
values.put(KEY_LAST_NAME, contact.getLastName());
values.put(KEY_MOB_NO, contact.getMobileNumber());
values.put(KEY_HOME_NO, contact.getHomeNumber());
values.put(KEY_WORK_NO, contact.getWorkNumber());
values.put(KEY_HOME_ADDR, contact.getHomeAddress());
values.put(KEY_EMAIL_ADDR, contact.getEmailAddress());
values.put(KEY_WORK_ADDR, contact.getWorkAddress());
values.put(KEY_NOTES, contact.getContactNotes());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_FIRST_NAME, KEY_LAST_NAME, KEY_MOB_NO, KEY_HOME_NO,
KEY_WORK_NO, KEY_HOME_ADDR, KEY_EMAIL_ADDR, KEY_WORK_ADDR,
KEY_NOTES }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),
cursor.getString(3),
cursor.getString(4), cursor.getString(5),
cursor.getString(6),
cursor.getString(7), cursor.getString(8),
cursor.getString(9));
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setFirstName(cursor.getString(1));
contact.setLastName(cursor.getString(2));
contact.setMobileNumber(cursor.getString(3));
contact.setHomeNumber(cursor.getString(4));
contact.setWorkNumber(cursor.getString(5));
contact.setHomeAddress(cursor.getString(6));
contact.setEmailAddress(cursor.getString(7));
contact.setWorkAddress(cursor.getString(8));
contact.setContactNotes(cursor.getString(9));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FIRST_NAME, contact.getFirstName());
values.put(KEY_LAST_NAME, contact.getLastName());
values.put(KEY_MOB_NO, contact.getMobileNumber());
values.put(KEY_HOME_NO, contact.getHomeNumber());
values.put(KEY_WORK_NO, contact.getWorkNumber());
values.put(KEY_HOME_ADDR, contact.getHomeAddress());
values.put(KEY_EMAIL_ADDR, contact.getEmailAddress());
values.put(KEY_WORK_ADDR, contact.getWorkAddress());
values.put(KEY_NOTES, contact.getContactNotes());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Now, when I delete a contact, not only is it not updating the listview in
my main contacts screen, but when I write all my contacts to log cat, the
contact never even got deleted from the database. Any ideas as to why that
is?
Cannot submit asp.net login form using $('form').submit();
Cannot submit asp.net login form using $('form').submit();
I have a function that 'pings' the server with a get request and if
successful submit the login form. However in setting the submit button to
return false, the form will not submit using $('form').submit(); The page
just seems to refresh, without actually logging the user in. Why is this?
<asp:Button ID="LoginButton" runat="server" CommandName="Login"
Text="Enter" ValidationGroup="LoginUserValidationGroup"
class="submitButton" />
submitButton.click(function () {
var url = 'https://examplesite.com/';
$.get(url).done(function () {
if (usernameBox.val() === '') {
usernameBox.attr('placeholder', 'Username Required');
passwordBox.attr('placeholder', '');
usernameBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val() === '') {
passwordBox.attr('placeholder', 'Password Required');
usernameBox.attr('placeholder', '');
passwordBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val().length <
6) {
passwordBox.focus();
return false;
}
else if (newPasswordBox.length &&
newPasswordBox.val().length < 6) {
passwordBox.focus();
return false;
}
else {
$('form').submit();
}
}).fail(function () {
errorMessage.text('Cannot Connect to Server - Please Try
Again Later').hide().fadeIn(350).delay(5000).fadeOut(350);
});
return false;
});
I have a function that 'pings' the server with a get request and if
successful submit the login form. However in setting the submit button to
return false, the form will not submit using $('form').submit(); The page
just seems to refresh, without actually logging the user in. Why is this?
<asp:Button ID="LoginButton" runat="server" CommandName="Login"
Text="Enter" ValidationGroup="LoginUserValidationGroup"
class="submitButton" />
submitButton.click(function () {
var url = 'https://examplesite.com/';
$.get(url).done(function () {
if (usernameBox.val() === '') {
usernameBox.attr('placeholder', 'Username Required');
passwordBox.attr('placeholder', '');
usernameBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val() === '') {
passwordBox.attr('placeholder', 'Password Required');
usernameBox.attr('placeholder', '');
passwordBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val().length <
6) {
passwordBox.focus();
return false;
}
else if (newPasswordBox.length &&
newPasswordBox.val().length < 6) {
passwordBox.focus();
return false;
}
else {
$('form').submit();
}
}).fail(function () {
errorMessage.text('Cannot Connect to Server - Please Try
Again Later').hide().fadeIn(350).delay(5000).fadeOut(350);
});
return false;
});
Find gateway of an interface
Find gateway of an interface
For a bash integration, i need to retrieve the default gateway from an
interface.
here is the output of the command route -n
Table de routage IP du noyau
Destination Passerelle Genmask Indic Metric Ref Use Iface
0.0.0.0 p.p.p.p 128.0.0.0 UG 0 0 0 tun0
0.0.0.0 x.x.x.x 0.0.0.0 UG 100 0 0 eth0
10.43.0.1 10.43.0.5 255.255.255.255 UGH 0 0 0 tun0
10.43.0.5 0.0.0.0 255.255.255.255 UH 0 0 0 tun0
31.220.30.224 88.191.142.1 255.255.255.255 UGH 0 0 0 eth0
x.x.x.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
128.0.0.0 10.43.0.5 128.0.0.0 UG 0 0 0 tun0
I try to capture gateway (Passerelle in French) for Iface tun0.
This regex is working on Rubular:
^[0\.]+\s+([\w\.]+)\s+.*UG.*tun0$
But this shell command doesn't work:
route -n |egrep -oh '^[0\.]+\s+([\w\.]+)\s+.*UG.*tun0$'
Please, tell me why ?
For a bash integration, i need to retrieve the default gateway from an
interface.
here is the output of the command route -n
Table de routage IP du noyau
Destination Passerelle Genmask Indic Metric Ref Use Iface
0.0.0.0 p.p.p.p 128.0.0.0 UG 0 0 0 tun0
0.0.0.0 x.x.x.x 0.0.0.0 UG 100 0 0 eth0
10.43.0.1 10.43.0.5 255.255.255.255 UGH 0 0 0 tun0
10.43.0.5 0.0.0.0 255.255.255.255 UH 0 0 0 tun0
31.220.30.224 88.191.142.1 255.255.255.255 UGH 0 0 0 eth0
x.x.x.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
128.0.0.0 10.43.0.5 128.0.0.0 UG 0 0 0 tun0
I try to capture gateway (Passerelle in French) for Iface tun0.
This regex is working on Rubular:
^[0\.]+\s+([\w\.]+)\s+.*UG.*tun0$
But this shell command doesn't work:
route -n |egrep -oh '^[0\.]+\s+([\w\.]+)\s+.*UG.*tun0$'
Please, tell me why ?
personalize mutt's subject with variable
personalize mutt's subject with variable
I've a script that send an email to user. I need to add a variable (name
of new user) to subject. My example:
a="John";echo|mutt -s welcome$a -e 'my_hdr From:info@example.com
<info@example.com>' test@example.com
Obviously this runs but the subject is: welcomeJohn. I need a space
between welcome and John. A real space doesn't works, change from a="John"
to a=" John" doesn'run... Either programmatically add a space to variable
or put all subject to variable.
I've a script that send an email to user. I need to add a variable (name
of new user) to subject. My example:
a="John";echo|mutt -s welcome$a -e 'my_hdr From:info@example.com
<info@example.com>' test@example.com
Obviously this runs but the subject is: welcomeJohn. I need a space
between welcome and John. A real space doesn't works, change from a="John"
to a=" John" doesn'run... Either programmatically add a space to variable
or put all subject to variable.
Friday, 27 September 2013
While Loop Condition in C
While Loop Condition in C
if (stock_choice == 'A'){
int positive = 0;
while (positive = 0){
printf("You Have Chosen ANNUAL, Please Enter the Amount of
Stock available: ");
scanf("%lf",&stock[0][1]);
if (stock[0][1] < 0){
printf("Stock Amount Must be Positive! Try Again.");
}
else{
positive = 1;
}
}
printf("Enter the Average Price of ANNUALs: ");
scanf("%lf",&stock[0][2]);
printf("Enter the percent Markup of ANNUALs: ");
scanf("%lf",&stock[0][3]);
printf("\nThe Amount of ANNUAL = %lf, AVG_Price = %lf, Markup =
%lf ",stock[0][1],stock[0][2],stock[0][3]);
}
I am having trouble with a while loop condition, i have tried everything
and cannot understand why the while loop does not run. Am I not see
something here or whats wrong?
if (stock_choice == 'A'){
int positive = 0;
while (positive = 0){
printf("You Have Chosen ANNUAL, Please Enter the Amount of
Stock available: ");
scanf("%lf",&stock[0][1]);
if (stock[0][1] < 0){
printf("Stock Amount Must be Positive! Try Again.");
}
else{
positive = 1;
}
}
printf("Enter the Average Price of ANNUALs: ");
scanf("%lf",&stock[0][2]);
printf("Enter the percent Markup of ANNUALs: ");
scanf("%lf",&stock[0][3]);
printf("\nThe Amount of ANNUAL = %lf, AVG_Price = %lf, Markup =
%lf ",stock[0][1],stock[0][2],stock[0][3]);
}
I am having trouble with a while loop condition, i have tried everything
and cannot understand why the while loop does not run. Am I not see
something here or whats wrong?
Client on node: Uncaught ReferenceError: require is not defined
Client on node: Uncaught ReferenceError: require is not defined
So, I am writing down an application with the node/express + jade combo.
I have a file called say, client.js, which is loaded on the client. In
that file I have code that calls functions from other javascript files. My
attempt was to use a statement of the form
var m = require('./messages');
in order to load the contents of the file messages.js (just like I do on
the server side) and later on call functions from that file. However,
clearly require is not defined on the client side, and it throws an error
of the form "Uncaught ReferenceError: require is not defined".
These other javascript files are also loaded on runtime at the client
because I place the links at the header of the webpage, so, clearly, the
client knows all the functions that are exported from these other files.
Hence, my question is:
How do I call these functions from these other javascript files (such as
messages.js) in the main client.js file that opens the socket to the
server and does all the job?
So, I am writing down an application with the node/express + jade combo.
I have a file called say, client.js, which is loaded on the client. In
that file I have code that calls functions from other javascript files. My
attempt was to use a statement of the form
var m = require('./messages');
in order to load the contents of the file messages.js (just like I do on
the server side) and later on call functions from that file. However,
clearly require is not defined on the client side, and it throws an error
of the form "Uncaught ReferenceError: require is not defined".
These other javascript files are also loaded on runtime at the client
because I place the links at the header of the webpage, so, clearly, the
client knows all the functions that are exported from these other files.
Hence, my question is:
How do I call these functions from these other javascript files (such as
messages.js) in the main client.js file that opens the socket to the
server and does all the job?
How to locate the first occurrence of a string in a string
How to locate the first occurrence of a string in a string
I need a function like memchr() but it should be able to locate a
substring(string), not an only single char. And it should return the first
occurrence found in string.
For example
p1 = afunclikememchr(str1,"here the function can localize this
substring",200);
To the mods: I added the C++ tag because this is also relevant to C++
In a nutshell; I want a function that should be called like memstr
I need a function like memchr() but it should be able to locate a
substring(string), not an only single char. And it should return the first
occurrence found in string.
For example
p1 = afunclikememchr(str1,"here the function can localize this
substring",200);
To the mods: I added the C++ tag because this is also relevant to C++
In a nutshell; I want a function that should be called like memstr
Qt VerticalTitleBar DockWidget with styleSheet doesn't work
Qt VerticalTitleBar DockWidget with styleSheet doesn't work
The problem is, with a vertical title bar on a dockwidget, the title text
is only partialy visible if I use a styleSheet.
in my dockWidget I do
features = self.features()
features = features | QtGui.QDockWidget.DockWidgetVerticalTitleBar #
self.setFeatures(features)
self.setWindowTitle("myTitle")
with only this, I have my dockWidget with my title visible, but if I add
some styleSheet on the subControl Title
QDockWidget { background-color:#f9cdcd; }
My title is not entirely visible, we can see only
myT
and I don't know why ? :(
the title is still write verticaly but cut.
this happen both isFloating or not.
pps : I'm on linux openSuse
Thanks for your Help.
The problem is, with a vertical title bar on a dockwidget, the title text
is only partialy visible if I use a styleSheet.
in my dockWidget I do
features = self.features()
features = features | QtGui.QDockWidget.DockWidgetVerticalTitleBar #
self.setFeatures(features)
self.setWindowTitle("myTitle")
with only this, I have my dockWidget with my title visible, but if I add
some styleSheet on the subControl Title
QDockWidget { background-color:#f9cdcd; }
My title is not entirely visible, we can see only
myT
and I don't know why ? :(
the title is still write verticaly but cut.
this happen both isFloating or not.
pps : I'm on linux openSuse
Thanks for your Help.
having a powers of 2 questions
having a powers of 2 questions
import acm.program.*;
public class Practice3 extends ConsoleProgram
{
public static int powersOf2(int k){
int x=0;
while (k < 1000){
x=k;
k*=2;
}
return x;
}
public void run()
{
println(powersOf2(1));
println(powersOf2(0));
println(powersOf2(2));
println(powersOf2(-1));
println(powersOf2(3000));
}
}
I don't think I really get right values from powersOf2. only 512 is
displayed when I run program. and if I run it by each println. it gives me
512 none 512 none 0
Is there something wrong? or values are correct?
import acm.program.*;
public class Practice3 extends ConsoleProgram
{
public static int powersOf2(int k){
int x=0;
while (k < 1000){
x=k;
k*=2;
}
return x;
}
public void run()
{
println(powersOf2(1));
println(powersOf2(0));
println(powersOf2(2));
println(powersOf2(-1));
println(powersOf2(3000));
}
}
I don't think I really get right values from powersOf2. only 512 is
displayed when I run program. and if I run it by each println. it gives me
512 none 512 none 0
Is there something wrong? or values are correct?
Thursday, 26 September 2013
Hide group of rows in excel
Hide group of rows in excel
I want to hide certain group of rows where 1st row after blank row is
"xyz" untill next blank row occours. eg
heloo a b
xyz as df
hello g j
xyz ghj gh jk jk
I want output to be as
heloo a b
hello g
I want to hide certain group of rows where 1st row after blank row is
"xyz" untill next blank row occours. eg
heloo a b
xyz as df
hello g j
xyz ghj gh jk jk
I want output to be as
heloo a b
hello g
Wednesday, 25 September 2013
Redirecting Output of PIPE to a FILE in python
Redirecting Output of PIPE to a FILE in python
Following code is to redirect the output of the Pipe to a file "CONTENT"
and it has some content, I want to overwrite it with output of "sort
CONTENT1 | uniq ".... But I'm not able overwrite it and also i don't know
weather following code is redirecting to CONTENT(ie correct or not) or
not. Please help me out....
f1=open('CONTENT','w')
sys.stdout=f1
p1 = subprocess.Popen(["sort", "CONTENT1"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["uniq"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
p2.communicate()
sys.stdout=sys.__stdout__
Following code is to redirect the output of the Pipe to a file "CONTENT"
and it has some content, I want to overwrite it with output of "sort
CONTENT1 | uniq ".... But I'm not able overwrite it and also i don't know
weather following code is redirecting to CONTENT(ie correct or not) or
not. Please help me out....
f1=open('CONTENT','w')
sys.stdout=f1
p1 = subprocess.Popen(["sort", "CONTENT1"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["uniq"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
p2.communicate()
sys.stdout=sys.__stdout__
Thursday, 19 September 2013
SQL query - Using timestamps in database to select only recent rows
SQL query - Using timestamps in database to select only recent rows
I have a table that records users answers for a number of questions:
tableA
user_id | question_id | date answered | correct?
66 345 timestamp 1
34 654 timestamp 0
34 654 timestamp 1
Every question attempt by every user is stored in the database.
I then also have a list of categories and the question_ids that go in that
category. e.g
tableB
category_id | question_id
1 34
1 44
1 23
2 99
2 44
I am trying to write a query to work out the percentage of questions in
the category that the user has previously answered correctly (where
correct? = 1) and also the percentage of questions correct of the last 20
questions answered in the category.
So far I can do the first part, but not the second
SELECT category_id, COUNT(*), COUNT(correct?)
FROM tableA LEFT JOIN tableB USING (question_id)
WHERE user_id = 1
this gives me the number of questions in total in the category and the
number of questions the user has answered correctly in the category.
I have a table that records users answers for a number of questions:
tableA
user_id | question_id | date answered | correct?
66 345 timestamp 1
34 654 timestamp 0
34 654 timestamp 1
Every question attempt by every user is stored in the database.
I then also have a list of categories and the question_ids that go in that
category. e.g
tableB
category_id | question_id
1 34
1 44
1 23
2 99
2 44
I am trying to write a query to work out the percentage of questions in
the category that the user has previously answered correctly (where
correct? = 1) and also the percentage of questions correct of the last 20
questions answered in the category.
So far I can do the first part, but not the second
SELECT category_id, COUNT(*), COUNT(correct?)
FROM tableA LEFT JOIN tableB USING (question_id)
WHERE user_id = 1
this gives me the number of questions in total in the category and the
number of questions the user has answered correctly in the category.
Downloading a file via FTP in VBA using wininet.dll not sending in ASCII
Downloading a file via FTP in VBA using wininet.dll not sending in ASCII
Im using the wininet.dll library to give some FTP functionality to my
Excel sheet.
Below is the ftpget function declaration. There is more to it, like
connecting to the FTP server but I have omitted that bit.
' Get a file using FTP
Private Declare Function FtpGetFile Lib "wininet.dll" Alias "FtpGetFileA" _
(ByVal hFtpSession As Long, ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, ByVal fFailIfExists As Boolean, _
ByVal dwFlagsAndAttributes As Long, ByVal dwFlags As Long, _
ByVal dwContext As Long) As Boolean
The code I have works in terms of downloading a file from the FTP server
by calling eg
RemoteFileStr = "filetoget.txt" ' file name on server, including directories
NewFileStr = "c:\filtetoget.txt" ' file name on MY system
FailIfExistsBool = False
FlagsAndAttributesLong = 128 ' Normal file, no special flags set.
FlagsLong = 1 ' FTP Transfer Type ASCII
ContextLong = 0 ' apparently not required.
FtpGetFile(MyFTPHandleLong, RemoteFileStr, NewFileStr, FailIfExistsBool,
FlagsAndAttributesLong, FlagsLong, ContextLong)
My problem is that the file is unreadable when I open it in notepad.
Using a proper ftp program and downloading the file in ASCII format it
works fine. But even though I have set the flag to force ASCII FlagsLong =
1, it seems to want to download it in binary format because it's all
symbols and glyphs and no english letters.
It also seems to ignore the FailIfExistsBool = False too, because if I
dont delete the file before I try again the FTP fails.
Any ideas on what is wrong?
Ref for ftpgetfile is below
http://msdn.microsoft.com/en-us/library/windows/desktop/aa384157(v=vs.85).aspx
Im using the wininet.dll library to give some FTP functionality to my
Excel sheet.
Below is the ftpget function declaration. There is more to it, like
connecting to the FTP server but I have omitted that bit.
' Get a file using FTP
Private Declare Function FtpGetFile Lib "wininet.dll" Alias "FtpGetFileA" _
(ByVal hFtpSession As Long, ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, ByVal fFailIfExists As Boolean, _
ByVal dwFlagsAndAttributes As Long, ByVal dwFlags As Long, _
ByVal dwContext As Long) As Boolean
The code I have works in terms of downloading a file from the FTP server
by calling eg
RemoteFileStr = "filetoget.txt" ' file name on server, including directories
NewFileStr = "c:\filtetoget.txt" ' file name on MY system
FailIfExistsBool = False
FlagsAndAttributesLong = 128 ' Normal file, no special flags set.
FlagsLong = 1 ' FTP Transfer Type ASCII
ContextLong = 0 ' apparently not required.
FtpGetFile(MyFTPHandleLong, RemoteFileStr, NewFileStr, FailIfExistsBool,
FlagsAndAttributesLong, FlagsLong, ContextLong)
My problem is that the file is unreadable when I open it in notepad.
Using a proper ftp program and downloading the file in ASCII format it
works fine. But even though I have set the flag to force ASCII FlagsLong =
1, it seems to want to download it in binary format because it's all
symbols and glyphs and no english letters.
It also seems to ignore the FailIfExistsBool = False too, because if I
dont delete the file before I try again the FTP fails.
Any ideas on what is wrong?
Ref for ftpgetfile is below
http://msdn.microsoft.com/en-us/library/windows/desktop/aa384157(v=vs.85).aspx
Writing a Top Score to a data file
Writing a Top Score to a data file
I am trying to create a file that will hold just one number; the highscore
to a game I am writing.
I have
f = open('hisc.txt', 'r+')
and
f.write(str(topScore))
What I want to know how to do is to:
Erase the entire file Get the number in the file and make it a variable in
the game Check if the topScore is higher than the number in the file, and
if so, replace it
I am trying to create a file that will hold just one number; the highscore
to a game I am writing.
I have
f = open('hisc.txt', 'r+')
and
f.write(str(topScore))
What I want to know how to do is to:
Erase the entire file Get the number in the file and make it a variable in
the game Check if the topScore is higher than the number in the file, and
if so, replace it
jpql subtract the results of two count functions
jpql subtract the results of two count functions
I have an entity which consists of two many-to-many relations: MainEntity
has many of As and MainEntity has many of Bs, where A and B is of the same
type. Example for the following JQL: If "ob" has got 4 "As" and 5 "Bs" i
need the result of -1 in the placeholder "difference" but it allways
returns 0.
String query = "SELECT ob, (COUNT(A) - COUNT(B)) difference" +
+ " FROM MainEntity ob "
+ " JOIN ob.listA A "
+ " JOIN ob.listB B "
+ " GROUP BY ob "
+ " WHERE ob=:PARAM ";
The Following Example is working:
"SELECT COUNT(A) FROM MainEntity ob JOIN ob.listA A "
+ "WHERE ob=:PARAM"
It returns 5 if ob has 5 items in its list "listA". Can anybody help me to
construct the right JPQL?
I have an entity which consists of two many-to-many relations: MainEntity
has many of As and MainEntity has many of Bs, where A and B is of the same
type. Example for the following JQL: If "ob" has got 4 "As" and 5 "Bs" i
need the result of -1 in the placeholder "difference" but it allways
returns 0.
String query = "SELECT ob, (COUNT(A) - COUNT(B)) difference" +
+ " FROM MainEntity ob "
+ " JOIN ob.listA A "
+ " JOIN ob.listB B "
+ " GROUP BY ob "
+ " WHERE ob=:PARAM ";
The Following Example is working:
"SELECT COUNT(A) FROM MainEntity ob JOIN ob.listA A "
+ "WHERE ob=:PARAM"
It returns 5 if ob has 5 items in its list "listA". Can anybody help me to
construct the right JPQL?
standard error page does not work for forwards in jsf
standard error page does not work for forwards in jsf
whenever i have a redirect and something goes wrong(eg: NullPointer) then
the configured error page is shown. However if i have a forward to certain
page then the standard error page is not shown but the current page
freezes i.e. the user will not be able to proceed further and there will
be no error message too.
when i say forward, it is a navigation rule without . when i say redirect,
it is new window opening up.
i am using IBM Websphere.
any pointer would be of great help. thanks.
whenever i have a redirect and something goes wrong(eg: NullPointer) then
the configured error page is shown. However if i have a forward to certain
page then the standard error page is not shown but the current page
freezes i.e. the user will not be able to proceed further and there will
be no error message too.
when i say forward, it is a navigation rule without . when i say redirect,
it is new window opening up.
i am using IBM Websphere.
any pointer would be of great help. thanks.
Using OR Condition in JOINS
Using OR Condition in JOINS
I'm fetching records by doing some multiple Joins. I need to add one more
with OR condition.
There is a table Payment. From Payment have to join with a table
Package1(if Payment.PaymentTypeID=1) OR with a table Package2(if
Payment.PaymentTypeID=3).
Both the tables Package1 and Package2 have a column VoucherID and have to
be fetched based on the above condition. I can do it by below query using
Union or Union All, but please let me know if I can do it without using
UNion or Union All.
select P1.VoucherID from Payment P inner join Package1 P1 on
P1.empid=P.empid and P.PaymentTypeID=1
union all
select P2.VoucherID from Payment P inner join Package1 P2 on
P2.empid=P.empid and P.PaymentTypeID=3
Thanks, Krishna
I'm fetching records by doing some multiple Joins. I need to add one more
with OR condition.
There is a table Payment. From Payment have to join with a table
Package1(if Payment.PaymentTypeID=1) OR with a table Package2(if
Payment.PaymentTypeID=3).
Both the tables Package1 and Package2 have a column VoucherID and have to
be fetched based on the above condition. I can do it by below query using
Union or Union All, but please let me know if I can do it without using
UNion or Union All.
select P1.VoucherID from Payment P inner join Package1 P1 on
P1.empid=P.empid and P.PaymentTypeID=1
union all
select P2.VoucherID from Payment P inner join Package1 P2 on
P2.empid=P.empid and P.PaymentTypeID=3
Thanks, Krishna
Is boost::uuids::random_generator thread safe?
Is boost::uuids::random_generator thread safe?
Consider this function compiling with g++ -std=c++11 (GCC 4.7.2):
boost::uuids::uuid getID()
{
static boost::uuids::random_generator generator;
return generator();
}
Is it safe to call getID from multiple threads?
As it is mentioned here the local static object definition at the first
line is thread safe according to the C++11 standard. The question is if
the call to boost::uuids::random_generator::operator() on the same object
generator at the second line is also thread safe. Will the returned UUIDs
be unique in the sense they would be in a single thread?
Consider this function compiling with g++ -std=c++11 (GCC 4.7.2):
boost::uuids::uuid getID()
{
static boost::uuids::random_generator generator;
return generator();
}
Is it safe to call getID from multiple threads?
As it is mentioned here the local static object definition at the first
line is thread safe according to the C++11 standard. The question is if
the call to boost::uuids::random_generator::operator() on the same object
generator at the second line is also thread safe. Will the returned UUIDs
be unique in the sense they would be in a single thread?
Wednesday, 18 September 2013
Trying to combine Users into the same marker using gmaps4rails
Trying to combine Users into the same marker using gmaps4rails
I can't figure out how to combine users into the same markers in
gmaps4rails. I feel like I'm somewhat close, but can't exactly figure out
what I'm doing wrong between using the gmaps4rails helper, converting to
JSON, and rendering by partial.
def map
distinct_locations = User.where("location IS NOT
NULL").select("DISTINCT(LOCATION)").map(&:location)
@markers = []
distinct_locations.each do |city|
temp_marker = User.where(:location => city).first.to_gmaps4rails
city_users = User.where(:location => city)
render_to_string(:partial => "/users/map_marker_info", :locals => {
:users => city_users})
@markers << temp_marker
end
@markers
end
As you can see, in my controller, I first get an array of
distinct_locations, which is just an array of city names (like "New York,
New York").
Then I create the @markers to hold the JSON I'll eventually return.
For each unique city that I found, I'm TRYING to first create a marker
using the to_gmaps4rails helper using the first User I find in that city.
Then I'm trying to find all the other users in the city (via city_users =
User.where(:location => city).
I'm then trying to render my partial using this collection of Users in the
same city with something like this for now (but eventually will pull
different attributes from Users):
#_map_marker_info.html.haml
.map_info_window
%h4
=users.first.location
%p
=users.count
Finally, I add the marker to @markers after each city is processed.
Eventually, I return @markers as a JSON that then becomes a beautiful map
thanks to the awesome gmaps4rails gem.
I'm sure I'm doing a lot of things wrong (and probably many things
inefficiently)...but can someone help me just to get it working?
I can't figure out how to combine users into the same markers in
gmaps4rails. I feel like I'm somewhat close, but can't exactly figure out
what I'm doing wrong between using the gmaps4rails helper, converting to
JSON, and rendering by partial.
def map
distinct_locations = User.where("location IS NOT
NULL").select("DISTINCT(LOCATION)").map(&:location)
@markers = []
distinct_locations.each do |city|
temp_marker = User.where(:location => city).first.to_gmaps4rails
city_users = User.where(:location => city)
render_to_string(:partial => "/users/map_marker_info", :locals => {
:users => city_users})
@markers << temp_marker
end
@markers
end
As you can see, in my controller, I first get an array of
distinct_locations, which is just an array of city names (like "New York,
New York").
Then I create the @markers to hold the JSON I'll eventually return.
For each unique city that I found, I'm TRYING to first create a marker
using the to_gmaps4rails helper using the first User I find in that city.
Then I'm trying to find all the other users in the city (via city_users =
User.where(:location => city).
I'm then trying to render my partial using this collection of Users in the
same city with something like this for now (but eventually will pull
different attributes from Users):
#_map_marker_info.html.haml
.map_info_window
%h4
=users.first.location
%p
=users.count
Finally, I add the marker to @markers after each city is processed.
Eventually, I return @markers as a JSON that then becomes a beautiful map
thanks to the awesome gmaps4rails gem.
I'm sure I'm doing a lot of things wrong (and probably many things
inefficiently)...but can someone help me just to get it working?
throwing new exceptions in catch()
throwing new exceptions in catch()
I'm trying to catch an exception, add information to it, and throw a new
(enhanced) exception for the calling module.
Example:
void CallingMethod()
{
try
{
doStuff();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
void doStuff()
{
try
{
// do something here that may throw an error
}
catch(Exception e)
{
Exception e2 = new Exception("new added info", e);
throw e2;
}
finally()
{
// cleanup
}
}
but when the error occurs and is written to the console, it is the
original error not my new error containing the string "new added info".
Is this expected? How should I throw a new error to be caught?
I'm trying to catch an exception, add information to it, and throw a new
(enhanced) exception for the calling module.
Example:
void CallingMethod()
{
try
{
doStuff();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
void doStuff()
{
try
{
// do something here that may throw an error
}
catch(Exception e)
{
Exception e2 = new Exception("new added info", e);
throw e2;
}
finally()
{
// cleanup
}
}
but when the error occurs and is written to the console, it is the
original error not my new error containing the string "new added info".
Is this expected? How should I throw a new error to be caught?
Fetching Firebase Data in an AngularFire callback
Fetching Firebase Data in an AngularFire callback
Every example I have ever seen of an Angular app with Firebase has had a
very static path.
Click Add -> Takes you to a New View
Click Save -> Saves Data and Routes you to a list view
Click on Item (from list view) -> Routes you to edit view of that object
using $routeparams
I'm trying to write a function that modifies some local data and adds it
to an fb collection AND route's the user to an edit view of that
particular object and in one action. AngularFire's add() method takes a
callback, if I could get the $id for the object that was just added in
that callback I could use $routeparams to perform the desired action.
Is this even possible?
Every example I have ever seen of an Angular app with Firebase has had a
very static path.
Click Add -> Takes you to a New View
Click Save -> Saves Data and Routes you to a list view
Click on Item (from list view) -> Routes you to edit view of that object
using $routeparams
I'm trying to write a function that modifies some local data and adds it
to an fb collection AND route's the user to an edit view of that
particular object and in one action. AngularFire's add() method takes a
callback, if I could get the $id for the object that was just added in
that callback I could use $routeparams to perform the desired action.
Is this even possible?
Jquery swing isnt working
Jquery swing isnt working
Hey guys I'm trying to make a small animation on my homepage, which im
redesigning.
I have two div-containers, one on the left and on on the right. If some
one comes to my site, I want them to swing in , I also want there to be a
loading bar when the site is first loaded. I have a working example on my
old site, but I'm doing a redesign and the script is not working anymore.
Here you can find a snipped version of the html, css and javascript.
`http://jsfiddle.net/D8Ruy/`
Hey guys I'm trying to make a small animation on my homepage, which im
redesigning.
I have two div-containers, one on the left and on on the right. If some
one comes to my site, I want them to swing in , I also want there to be a
loading bar when the site is first loaded. I have a working example on my
old site, but I'm doing a redesign and the script is not working anymore.
Here you can find a snipped version of the html, css and javascript.
`http://jsfiddle.net/D8Ruy/`
Facebook login with custom port
Facebook login with custom port
We have test web application that runs on not default port
(example.com:3567). For Facebook login we use hybridauth
application(http://hybridauth.sourceforge.net/) Problem is that when I
want to login to facebook with not dafault port in return link with port
80 (example.com)
In facebook app in Page url input I wrote page url with port
(http://example.com:3567).
So question is can I use not default port for facebook login or only
standard ports?
We have test web application that runs on not default port
(example.com:3567). For Facebook login we use hybridauth
application(http://hybridauth.sourceforge.net/) Problem is that when I
want to login to facebook with not dafault port in return link with port
80 (example.com)
In facebook app in Page url input I wrote page url with port
(http://example.com:3567).
So question is can I use not default port for facebook login or only
standard ports?
Execute C++ function from C# crashes
Execute C++ function from C# crashes
I need to call a function from a C++ dll file, in C#.
From the C++ Header file, I know:
typedef struct {
bool CashIn;
bool Surplus;
bool Fitness;
char Denomination[N_DIV][MAX_CURR_NAME];
byte DenominationNumber;
byte RollNumber;
bool CanbeChanged;
}NT_Roll;
extern "C" int WINAPI Cima_NT_GetRollsConfiguration(NT_Roll
*Configuration,int *CfgSize);
I used the following in C# application
[DllImport("Cima_NT_Drv")]
unsafe static extern int Cima_NT_GetRollsConfiguration( out NTRoll[]
ntRoll, ref int CfgSize);
[StructLayout(LayoutKind.Sequential)]
unsafe struct NTRoll
{
public byte CashIn;
public byte Surplus;
public byte Fitness;
public fixed byte Denomination[N_DIV * MAX_CURR_NAME];
public byte DenominationNumber;
public byte RollNumber;
public byte CanbeChanged;
}
And the function call is:
public unsafe int GetRollsConfiguration(out RollerConfig[] OutRolls)
{
NTRoll[] Rolls = null;
int configSize = 16;
int result = -1;
result = Cima_NT_GetRollsConfiguration(out Rolls, ref configSize);
return result;
}
I don't have the code of the C++ DLL. The execution of
Cima_NT_GetRollsConfiguration(out Rolls, ref configSize); makes the
application crashes without any error message.
Is there anything wrong with the C# code?
I need to call a function from a C++ dll file, in C#.
From the C++ Header file, I know:
typedef struct {
bool CashIn;
bool Surplus;
bool Fitness;
char Denomination[N_DIV][MAX_CURR_NAME];
byte DenominationNumber;
byte RollNumber;
bool CanbeChanged;
}NT_Roll;
extern "C" int WINAPI Cima_NT_GetRollsConfiguration(NT_Roll
*Configuration,int *CfgSize);
I used the following in C# application
[DllImport("Cima_NT_Drv")]
unsafe static extern int Cima_NT_GetRollsConfiguration( out NTRoll[]
ntRoll, ref int CfgSize);
[StructLayout(LayoutKind.Sequential)]
unsafe struct NTRoll
{
public byte CashIn;
public byte Surplus;
public byte Fitness;
public fixed byte Denomination[N_DIV * MAX_CURR_NAME];
public byte DenominationNumber;
public byte RollNumber;
public byte CanbeChanged;
}
And the function call is:
public unsafe int GetRollsConfiguration(out RollerConfig[] OutRolls)
{
NTRoll[] Rolls = null;
int configSize = 16;
int result = -1;
result = Cima_NT_GetRollsConfiguration(out Rolls, ref configSize);
return result;
}
I don't have the code of the C++ DLL. The execution of
Cima_NT_GetRollsConfiguration(out Rolls, ref configSize); makes the
application crashes without any error message.
Is there anything wrong with the C# code?
String or Binary Data Would Be Truncated on varchar(max)
String or Binary Data Would Be Truncated on varchar(max)
I've checked around and everyone seems to be running into issues with
column lengths being too small. I don't think that's my issue as
everything is a varchar max.
I have a large text string being stored in a column
Select len(templateDocument) from TemplateDocument
This Returns 5142610
I'm trying to do a replace of old text with new text and running into this
issues
UPDATE TemplateDocument
SET templateDocument = REPLACE(templateDocument, @BookmarkOldText,
@BookmarkNewText)
This is where my error get's thrown.
My NewText is of length 12067, the old text is of 14279. Seeing as my new
text is less than my new text, it should fit and shouldn't be throwing an
error. I can even double the current text in a varchar(max) and that fits
fine.
declare @fullItem varchar(max)
SELECT @fullItem = templateDocument from TemplateDocument
SET @fullItem = @fullItem + ' ' + @fullItem
Select LEN(@fullItem)
This Returns 10285221
Which is fine and it still fits into the datatype and then into the column.
So my question is why on the replace is it saying there's going to be
truncation? It looks as if the datatype is large enough to store the whole
document twice over. Is there a size limit on the replace function? If so,
is there a better way of going through and replacing this?
I've checked around and everyone seems to be running into issues with
column lengths being too small. I don't think that's my issue as
everything is a varchar max.
I have a large text string being stored in a column
Select len(templateDocument) from TemplateDocument
This Returns 5142610
I'm trying to do a replace of old text with new text and running into this
issues
UPDATE TemplateDocument
SET templateDocument = REPLACE(templateDocument, @BookmarkOldText,
@BookmarkNewText)
This is where my error get's thrown.
My NewText is of length 12067, the old text is of 14279. Seeing as my new
text is less than my new text, it should fit and shouldn't be throwing an
error. I can even double the current text in a varchar(max) and that fits
fine.
declare @fullItem varchar(max)
SELECT @fullItem = templateDocument from TemplateDocument
SET @fullItem = @fullItem + ' ' + @fullItem
Select LEN(@fullItem)
This Returns 10285221
Which is fine and it still fits into the datatype and then into the column.
So my question is why on the replace is it saying there's going to be
truncation? It looks as if the datatype is large enough to store the whole
document twice over. Is there a size limit on the replace function? If so,
is there a better way of going through and replacing this?
Tuesday, 17 September 2013
How to enable an Apple ID login within an app?
How to enable an Apple ID login within an app?
I'd like the user to do an apple id login before he can access some
features. This is mainly for parental controls.
Can this be done?
Thanks!
I'd like the user to do an apple id login before he can access some
features. This is mainly for parental controls.
Can this be done?
Thanks!
Remove method in HashMap java does not work
Remove method in HashMap java does not work
I have removed the map with the method "remove(key)" but just the value
was deleted. When I call the keySet() method. The key still there!!. The
below program, I want to find two groups (2 map in the HashMap) have
shortest distance. Then merge them, that mean I need to remove these two
groups and put the merged group to maps.
/* I have already initiate the HashMap groups*/
ArrayList<String> listGroupNames ;
while (currentNumberOfGroup > 1000){
System.out.println("Groups" + currentNumberOfGroup);
listGroupNames = new ArrayList<String>(groups.keySet());
/* Name of two groups will be merged*/
String candidate1 = "";
String candidate2 = "";
double maxSimilarity = 0;
/* finding two groups which have shortest distance*/
for(String event1 : listGroupNames){
for(String event2 : listGroupNames){
if(!event1.equalsIgnoreCase(event2)){
Group group1 = groups.get(event1);
Group otherGrp = groups.get(event2);
double similarity = group1.getMaxSimilarityWith(otherGrp,
simpledEvent);
if(similarity > maxSimilarity){
maxSimilarity = similarity;
candidate1 = event1;
candidate2 = event2;
}
}
}
}
/* 2 groups have shortest distance were found already*/
/* Merge 2 groups then replace these two groups by merged group*/
Group groupCandidate1 = groups.get(candidate1) ;
Group groupCandidate2 = groups.get(candidate2) ;
Group mergerdGroup = groupCandidate1.mergeToOtherGroup(groupCandidate2);
/*remove 2 found groups*/
groups.remove(candidate2);
groups.remove(candidate1);
groups.put(mergerdGroup.name, mergerdGroup);
listGroupNames.clear();
currentNumberOfGroup --;
}
I have removed the map with the method "remove(key)" but just the value
was deleted. When I call the keySet() method. The key still there!!. The
below program, I want to find two groups (2 map in the HashMap) have
shortest distance. Then merge them, that mean I need to remove these two
groups and put the merged group to maps.
/* I have already initiate the HashMap groups*/
ArrayList<String> listGroupNames ;
while (currentNumberOfGroup > 1000){
System.out.println("Groups" + currentNumberOfGroup);
listGroupNames = new ArrayList<String>(groups.keySet());
/* Name of two groups will be merged*/
String candidate1 = "";
String candidate2 = "";
double maxSimilarity = 0;
/* finding two groups which have shortest distance*/
for(String event1 : listGroupNames){
for(String event2 : listGroupNames){
if(!event1.equalsIgnoreCase(event2)){
Group group1 = groups.get(event1);
Group otherGrp = groups.get(event2);
double similarity = group1.getMaxSimilarityWith(otherGrp,
simpledEvent);
if(similarity > maxSimilarity){
maxSimilarity = similarity;
candidate1 = event1;
candidate2 = event2;
}
}
}
}
/* 2 groups have shortest distance were found already*/
/* Merge 2 groups then replace these two groups by merged group*/
Group groupCandidate1 = groups.get(candidate1) ;
Group groupCandidate2 = groups.get(candidate2) ;
Group mergerdGroup = groupCandidate1.mergeToOtherGroup(groupCandidate2);
/*remove 2 found groups*/
groups.remove(candidate2);
groups.remove(candidate1);
groups.put(mergerdGroup.name, mergerdGroup);
listGroupNames.clear();
currentNumberOfGroup --;
}
Ongoing dramas with epicurves date scales
Ongoing dramas with epicurves date scales
I'm attempting to use ggplot and R for analysing some epidemiologic data,
and I'm continuing to struggle with getting an epidemic curve to appear
properly.
Data is here
attach(epicurve)
head(epicurve)
onset age
1 21/12/2012 18
2 14/06/2013 8
3 10/06/2013 64
4 28/05/2013 79
5 14/04/2013 56
6 9/04/2013 66
epicurve$onset <- as.Date(epicurve$onset, format="%d/%m/%Y")
ggplot(epicurve, aes(onset)) + geom_histogram() +
scale_x_date(breaks=date_breaks("1 year"), minor_breaks=date_breaks("1
month"), labels = date_format("%b-%Y"))
gives this graph. This is fine, but the binwidths are not related to any
time period of note, and adjusting them is a bit trial and error.
For this particular dataset, I'd like to display the cases by month of onset.
One way I worked out how to do this is:
epicurve$monyr <- format(epicurve$onset, "%b-%Y")
epicurve$monyr <- as.factor(epicurve$monyr)
ggplot(epicurve, aes(monyr)) + geom_histogram()
Outputs a graph I can't post because of the reputation system. The bars
represent something meaningful, but the axis labels are a bomb-site. I
can't format the axes using scale_x_date because they aren't dates and I
can't work out what arguments to pass to scale_x_discrete to give useful
labels.
I have a feeling there should be an easier way to do this by doing an
operation on the onset column. Can anyone give me any pointers, please?
I'm attempting to use ggplot and R for analysing some epidemiologic data,
and I'm continuing to struggle with getting an epidemic curve to appear
properly.
Data is here
attach(epicurve)
head(epicurve)
onset age
1 21/12/2012 18
2 14/06/2013 8
3 10/06/2013 64
4 28/05/2013 79
5 14/04/2013 56
6 9/04/2013 66
epicurve$onset <- as.Date(epicurve$onset, format="%d/%m/%Y")
ggplot(epicurve, aes(onset)) + geom_histogram() +
scale_x_date(breaks=date_breaks("1 year"), minor_breaks=date_breaks("1
month"), labels = date_format("%b-%Y"))
gives this graph. This is fine, but the binwidths are not related to any
time period of note, and adjusting them is a bit trial and error.
For this particular dataset, I'd like to display the cases by month of onset.
One way I worked out how to do this is:
epicurve$monyr <- format(epicurve$onset, "%b-%Y")
epicurve$monyr <- as.factor(epicurve$monyr)
ggplot(epicurve, aes(monyr)) + geom_histogram()
Outputs a graph I can't post because of the reputation system. The bars
represent something meaningful, but the axis labels are a bomb-site. I
can't format the axes using scale_x_date because they aren't dates and I
can't work out what arguments to pass to scale_x_discrete to give useful
labels.
I have a feeling there should be an easier way to do this by doing an
operation on the onset column. Can anyone give me any pointers, please?
Getting illegal start of expression as error
Getting illegal start of expression as error
Im trying to run the program again, and now i'm getting this error.
here is my code:
public static void writeBirdtype() {
private String readFileAsString(String filePath) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader();
new FileReader(filePath);
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
error:
Oblig2.java:72: error: illegal start of expression
private String readFileAsString(String filePath) throws IOException {
^
Oblig2.java:72: error: ';' expected
private String readFileAsString(String filePath) throws IOException {
^
Oblig2.java:72: error: ';' expected
private String readFileAsString(String filePath) throws IOException {
^
Oblig2.java:72: error: not a statement
private String readFileAsString(String filePath) throws IOException {
^
Oblig2.java:72: error: ';' expected
private String readFileAsString(String filePath) throws IOException {
^
5 errors
How can I fix this?
Thanks alot for help
Im trying to run the program again, and now i'm getting this error.
here is my code:
public static void writeBirdtype() {
private String readFileAsString(String filePath) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader();
new FileReader(filePath);
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
error:
Oblig2.java:72: error: illegal start of expression
private String readFileAsString(String filePath) throws IOException {
^
Oblig2.java:72: error: ';' expected
private String readFileAsString(String filePath) throws IOException {
^
Oblig2.java:72: error: ';' expected
private String readFileAsString(String filePath) throws IOException {
^
Oblig2.java:72: error: not a statement
private String readFileAsString(String filePath) throws IOException {
^
Oblig2.java:72: error: ';' expected
private String readFileAsString(String filePath) throws IOException {
^
5 errors
How can I fix this?
Thanks alot for help
Regular 2D array vs Dynamically allocated 2D array
Regular 2D array vs Dynamically allocated 2D array
Does a regular array need to be initialized when it is created? If it is
default initialized is it not possible to change the elements in an array?
When creating a 2D array, all the examples I see are using dynamic memory.
Is it because the dynamically allocated 2D array does not need to be
initialized. Is it possible to fill the array elements after declaring a
regular 2D array?
Does a regular array need to be initialized when it is created? If it is
default initialized is it not possible to change the elements in an array?
When creating a 2D array, all the examples I see are using dynamic memory.
Is it because the dynamically allocated 2D array does not need to be
initialized. Is it possible to fill the array elements after declaring a
regular 2D array?
Python, Java, C: Pass by Reference or Pass by Value Differences
Python, Java, C: Pass by Reference or Pass by Value Differences
I just read the following article on what passing by reference and passing
by value means: http://qntm.org/call
So just to make sure I'm understanding correctly... Does that mean that
calling by value in functions will NOT alter the original inputs, only a
local copy of that input? However, since in Java and Python, the values
are actually references to values, does that mean calling by value in
functions WILL alter the original inputs?
I just read the following article on what passing by reference and passing
by value means: http://qntm.org/call
So just to make sure I'm understanding correctly... Does that mean that
calling by value in functions will NOT alter the original inputs, only a
local copy of that input? However, since in Java and Python, the values
are actually references to values, does that mean calling by value in
functions WILL alter the original inputs?
Sunday, 15 September 2013
PhpStorm: Importing overridden properties and associated PHPDoc blocks
PhpStorm: Importing overridden properties and associated PHPDoc blocks
In PhpStorm (6.0.3 here), you can "Implement methods" from an interface,
and PhpStorm will copy the PHPDoc block and the signature into your file.
However, is there a way to do that with properties (and/or methods) from
classes you're simply extending? It would be fantastic to have all of that
information imported in. The terms are a bit ambiguous to do a proper
search; just curious if anyone has done this.
Thanks!
In PhpStorm (6.0.3 here), you can "Implement methods" from an interface,
and PhpStorm will copy the PHPDoc block and the signature into your file.
However, is there a way to do that with properties (and/or methods) from
classes you're simply extending? It would be fantastic to have all of that
information imported in. The terms are a bit ambiguous to do a proper
search; just curious if anyone has done this.
Thanks!
How to update bunch of products using a single form?
How to update bunch of products using a single form?
I have two questions first question is that, when I use $ jsp shows the
required variable but when I use % it does not which is weird. The other
question is that how can I update a bunch of products, in following
example I have a table which shows different products user should be able
to edit the values and click on a single submit button to update all the
values that have been changed for each product.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<table border="1">
<tbody>
<form id="" action="edit">
<c:forEach var="products" items="${listOfProducts}">
<tr>
<td>${products.id}</td>
<td>${products.name}</td> <<shows the name of
product but the
following does not
<td><s:textfield name="Name"
value="%{products.name}"/></td>
<td>${products.price}</td>
</tr>
</c:forEach>
</form>
</tbody>
</table>
Output
1 Pro1 23
3 Pro3 45
As shown the third column is empty
I have two questions first question is that, when I use $ jsp shows the
required variable but when I use % it does not which is weird. The other
question is that how can I update a bunch of products, in following
example I have a table which shows different products user should be able
to edit the values and click on a single submit button to update all the
values that have been changed for each product.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<table border="1">
<tbody>
<form id="" action="edit">
<c:forEach var="products" items="${listOfProducts}">
<tr>
<td>${products.id}</td>
<td>${products.name}</td> <<shows the name of
product but the
following does not
<td><s:textfield name="Name"
value="%{products.name}"/></td>
<td>${products.price}</td>
</tr>
</c:forEach>
</form>
</tbody>
</table>
Output
1 Pro1 23
3 Pro3 45
As shown the third column is empty
PHP Syntax has to be off
PHP Syntax has to be off
So I have this code to name individual comments.
echo '<div class="leftpart"><a name="comment_'.$row["num"].'" ></a>';
The link that shows up like this...
?id=28#comment_34 />
What's up with the />
Should I show more code?
So I have this code to name individual comments.
echo '<div class="leftpart"><a name="comment_'.$row["num"].'" ></a>';
The link that shows up like this...
?id=28#comment_34 />
What's up with the />
Should I show more code?
Xamarin iTunes Affliate Links
Xamarin iTunes Affliate Links
My apps open iTunes Affliate links directly using the standard
sharedApplication.OpenURL. However, Apple recommends the following code.
Is there a C# version to support Xamarin?
// Process a LinkShare/TradeDoubler/DGM URL to something iPhone can handle
(void)openReferralURL:(NSURL *)referralURL
{
NSURLRequest *theRequest=[NSURLRequest requestWithURL:referralURL
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSURLConnection *conn = [[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
[conn release];
}
// Save the most recent URL in case multiple redirects occur
// "iTunesURL" is an NSURL property in your class declaration
(NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse
*)response
{
if (response) {
NSMutableURLRequest *r = [[request mutableCopy] autorelease]; //
original request
[r setURL: [request URL]];
self.iTunesURL = [r URL];
if ([self.iTunesURL.host hasSuffix:@"itunes.apple.com"]) {
[[UIApplication sharedApplication] openURL:self.iTunesURL];
}
return r;
} else {
return request;
}
}
My apps open iTunes Affliate links directly using the standard
sharedApplication.OpenURL. However, Apple recommends the following code.
Is there a C# version to support Xamarin?
// Process a LinkShare/TradeDoubler/DGM URL to something iPhone can handle
(void)openReferralURL:(NSURL *)referralURL
{
NSURLRequest *theRequest=[NSURLRequest requestWithURL:referralURL
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSURLConnection *conn = [[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
[conn release];
}
// Save the most recent URL in case multiple redirects occur
// "iTunesURL" is an NSURL property in your class declaration
(NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse
*)response
{
if (response) {
NSMutableURLRequest *r = [[request mutableCopy] autorelease]; //
original request
[r setURL: [request URL]];
self.iTunesURL = [r URL];
if ([self.iTunesURL.host hasSuffix:@"itunes.apple.com"]) {
[[UIApplication sharedApplication] openURL:self.iTunesURL];
}
return r;
} else {
return request;
}
}
Offline to Online Database Synchronization - PHP/MySQL
Offline to Online Database Synchronization - PHP/MySQL
I am developing a inventory management web application using php and
mysql. This application will runs on different locations. while any one
location disconnect internet at the time data will be land in database and
when active internet that data automatically synchronizing the remote
sever database. is there way pls let me know.
thanks and advance.
I am developing a inventory management web application using php and
mysql. This application will runs on different locations. while any one
location disconnect internet at the time data will be land in database and
when active internet that data automatically synchronizing the remote
sever database. is there way pls let me know.
thanks and advance.
How can i stop viewing source code when press Ctrl+U
How can i stop viewing source code when press Ctrl+U
i have a script which detects when ctrl or U is being pressed, but then
its shows the source code..
how can i disable the vieewing of source code
$(document).ready(function()
{
var ctrlDown = false;
var ctrlKey = 17, vKey = 86, cKey = 67, uKey = 85;
$(document).keydown(function(e)
{
if(e.ctrlKey || e.keyCode == 85)
{
alert("I've been pressed!");
e.preventDefault();
}
if(e.keyCode == 116)
{
e.preventDefault();
}
});
}
);
i have a script which detects when ctrl or U is being pressed, but then
its shows the source code..
how can i disable the vieewing of source code
$(document).ready(function()
{
var ctrlDown = false;
var ctrlKey = 17, vKey = 86, cKey = 67, uKey = 85;
$(document).keydown(function(e)
{
if(e.ctrlKey || e.keyCode == 85)
{
alert("I've been pressed!");
e.preventDefault();
}
if(e.keyCode == 116)
{
e.preventDefault();
}
});
}
);
Checking for multiple occurrence of character repeated or spread out in string with regex
Checking for multiple occurrence of character repeated or spread out in
string with regex
Having syntax trouble, I'm new to using regex. I'm coding in java.
I need to check if an apostrophe is used more than once in a string.
Multiple apostrophes can either be consecutive or spread out over the
string.
For example: Doesn't'work or Can''t
I have an if statement, and I want it to evaluate to true if there is more
than apostrophe
if(string.matches("\'")){ . . }
any help would be great!
string with regex
Having syntax trouble, I'm new to using regex. I'm coding in java.
I need to check if an apostrophe is used more than once in a string.
Multiple apostrophes can either be consecutive or spread out over the
string.
For example: Doesn't'work or Can''t
I have an if statement, and I want it to evaluate to true if there is more
than apostrophe
if(string.matches("\'")){ . . }
any help would be great!
Unable to read analyze 7.5 image in c
Unable to read analyze 7.5 image in c
I was trying to read voxel information of a 3D analyze image. Sample code:
#include <stdio.h>
void main() {
unsigned int R,G,B;
unsigned char data[3];
FILE *fp, *ft;
fp = fopen("67.img", "rb");
ft = fopen("OUT.txt", "w");
while (fread(data, 3, 1, fp) == 1) {
R = data[0];
G = data[1];
B = data[2];
fprintf(ft, "%u,%u,%u", R, G, B);
}
}
But in the "Out.txt" I am not getting expected RGB values. I am a newbie
in C. Please help me.
I was trying to read voxel information of a 3D analyze image. Sample code:
#include <stdio.h>
void main() {
unsigned int R,G,B;
unsigned char data[3];
FILE *fp, *ft;
fp = fopen("67.img", "rb");
ft = fopen("OUT.txt", "w");
while (fread(data, 3, 1, fp) == 1) {
R = data[0];
G = data[1];
B = data[2];
fprintf(ft, "%u,%u,%u", R, G, B);
}
}
But in the "Out.txt" I am not getting expected RGB values. I am a newbie
in C. Please help me.
Saturday, 14 September 2013
Mahout - Error while running trainnb
Mahout - Error while running trainnb
Using Mahout seq2sparse command, I manage to successfully create the
following folders in HDFS
df-count dictionary.file-0 frequency.file-0 tf-vectors tfidf-vectors
tokenized-documents wordcount
After that when I run the trainnb command with the following syntax
mahout trainnb -i tweet-vectors -el -li labelindex -o model -ow -c
I get the following error. Does anyone know resolution for the same?
Exception in thread "main" java.lang.IllegalStateException:
hdfs://machineinfo:8020/user/hhhh/tweetvectors/df-count
at
org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterator$1.apply(SequenceFileDirIterator.java:115)
at
org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterator$1.apply(SequenceFileDirIterator.java:106)
at
com.google.common.collect.Iterators$8.transform(Iterators.java:860)
at
com.google.common.collect.TransformedIterator.next(TransformedIterator.java:48)
at com.google.common.collect.Iterators$5.hasNext(Iterators.java:597)
at
com.google.common.collect.ForwardingIterator.hasNext(ForwardingIterator.java:43)
at
org.apache.mahout.classifier.naivebayes.BayesUtils.writeLabelIndex(BayesUtils.java:122)
at
org.apache.mahout.classifier.naivebayes.training.TrainNaiveBayesJob.createLabelIndex(TrainNaiveBayesJob.java:180)
at
org.apache.mahout.classifier.naivebayes.training.TrainNaiveBayesJob.run(TrainNaiveBayesJob.java:94)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
at
org.apache.mahout.classifier.naivebayes.training.TrainNaiveBayesJob.main(TrainNaiveBayesJob.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at
org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:68)
at
org.apache.hadoop.util.ProgramDriver.driver(ProgramDriver.java:139)
at org.apache.mahout.driver.MahoutDriver.main(MahoutDriver.java:194)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.apache.hadoop.util.RunJar.main(RunJar.java:160)
Caused by: java.io.FileNotFoundException: File does not exist:
/user/hhhh/tweet-vectors/df-count
at
org.apache.hadoop.hdfs.DFSClient$DFSInputStream.fetchLocatedBlocks(DFSClient.java:2006)
at
org.apache.hadoop.hdfs.DFSClient$DFSInputStream.openInfo(DFSClient.java:1975)
at
org.apache.hadoop.hdfs.DFSClient$DFSInputStream.<init>(DFSClient.java:1967)
at org.apache.hadoop.hdfs.DFSClient.open(DFSClient.java:735)
at
org.apache.hadoop.hdfs.DistributedFileSystem.open(DistributedFileSystem.java:165)
at
org.apache.hadoop.io.SequenceFile$Reader.openFile(SequenceFile.java:1499)
at
org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1486)
at
org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1479)
at
org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1474)
at
org.apache.mahout.common.iterator.sequencefile.SequenceFileIterator.<init>(SequenceFileIterator.java:63)
at
org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterator$1.apply(SequenceFileDirIterator.java:110)
... 22 more
Using Mahout seq2sparse command, I manage to successfully create the
following folders in HDFS
df-count dictionary.file-0 frequency.file-0 tf-vectors tfidf-vectors
tokenized-documents wordcount
After that when I run the trainnb command with the following syntax
mahout trainnb -i tweet-vectors -el -li labelindex -o model -ow -c
I get the following error. Does anyone know resolution for the same?
Exception in thread "main" java.lang.IllegalStateException:
hdfs://machineinfo:8020/user/hhhh/tweetvectors/df-count
at
org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterator$1.apply(SequenceFileDirIterator.java:115)
at
org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterator$1.apply(SequenceFileDirIterator.java:106)
at
com.google.common.collect.Iterators$8.transform(Iterators.java:860)
at
com.google.common.collect.TransformedIterator.next(TransformedIterator.java:48)
at com.google.common.collect.Iterators$5.hasNext(Iterators.java:597)
at
com.google.common.collect.ForwardingIterator.hasNext(ForwardingIterator.java:43)
at
org.apache.mahout.classifier.naivebayes.BayesUtils.writeLabelIndex(BayesUtils.java:122)
at
org.apache.mahout.classifier.naivebayes.training.TrainNaiveBayesJob.createLabelIndex(TrainNaiveBayesJob.java:180)
at
org.apache.mahout.classifier.naivebayes.training.TrainNaiveBayesJob.run(TrainNaiveBayesJob.java:94)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
at
org.apache.mahout.classifier.naivebayes.training.TrainNaiveBayesJob.main(TrainNaiveBayesJob.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at
org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:68)
at
org.apache.hadoop.util.ProgramDriver.driver(ProgramDriver.java:139)
at org.apache.mahout.driver.MahoutDriver.main(MahoutDriver.java:194)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.apache.hadoop.util.RunJar.main(RunJar.java:160)
Caused by: java.io.FileNotFoundException: File does not exist:
/user/hhhh/tweet-vectors/df-count
at
org.apache.hadoop.hdfs.DFSClient$DFSInputStream.fetchLocatedBlocks(DFSClient.java:2006)
at
org.apache.hadoop.hdfs.DFSClient$DFSInputStream.openInfo(DFSClient.java:1975)
at
org.apache.hadoop.hdfs.DFSClient$DFSInputStream.<init>(DFSClient.java:1967)
at org.apache.hadoop.hdfs.DFSClient.open(DFSClient.java:735)
at
org.apache.hadoop.hdfs.DistributedFileSystem.open(DistributedFileSystem.java:165)
at
org.apache.hadoop.io.SequenceFile$Reader.openFile(SequenceFile.java:1499)
at
org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1486)
at
org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1479)
at
org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1474)
at
org.apache.mahout.common.iterator.sequencefile.SequenceFileIterator.<init>(SequenceFileIterator.java:63)
at
org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterator$1.apply(SequenceFileDirIterator.java:110)
... 22 more
Rails Unicorn server crashing?
Rails Unicorn server crashing?
Trying to deploy my Rails app on DigitalOcean using a Unicorn Rails
server, and getting some error I can't interpret:
root@blog:/home/rails# tail -40 /home/unicorn/log/unicorn.log
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/definition.rb:148:in
`requested_specs'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/environment.rb:18:in
`requested_specs'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:13:in
`setup'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler.rb:120:in
`setup'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/setup.rb:17:in
`<top (required)>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in
`require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in
`rescue in require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:35:in
`require'
/home/rails/config/boot.rb:6:in `<top (required)>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/home/rails/config/application.rb:1:in `<top (required)>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/home/rails/config/environment.rb:2:in `<top (required)>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
config.ru:4:in `block in <main>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/rack-
1.4.5/lib/rack/builder.rb:51:in `instance_eval'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/rack-1.4.5/lib/rack/builder.rb:51:in
`initialize'
config.ru:1:in `new'
config.ru:1:in `<main>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn.rb:48:in
`eval'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn.rb:48:in
`block in builder'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:722:in
`call'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:722:in
`build_app!'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:595:in
`init_worker_process'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:615:in
`worker_loop'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:500:in
`spawn_missing_workers'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:511:in
`maintain_worker_count'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:277:in
`join'
/usr/bin/unicorn:121:in `<main>'
E, [2013-09-15T00:28:11.016488 #11684] ERROR -- : reaped
#<Process::Status: pid 16029 exit 1> worker=1
I, [2013-09-15T00:28:11.016608 #11684] INFO -- : worker=1 spawning...
E, [2013-09-15T00:28:11.018269 #11684] ERROR -- : reaped
#<Process::Status: pid 16031 exit 1> worker=0
I, [2013-09-15T00:28:11.018385 #11684] INFO -- : worker=0 spawning...
I, [2013-09-15T00:28:11.019306 #16035] INFO -- : worker=1 spawned pid=16035
I, [2013-09-15T00:28:11.021522 #16037] INFO -- : worker=0 spawned pid=16037
I, [2013-09-15T00:28:11.023002 #16035] INFO -- : Refreshing Gem list
I, [2013-09-15T00:28:11.027851 #16037] INFO -- : Refreshing Gem list
I followed the tutorial here:
https://www.digitalocean.com/community/articles/how-to-launch-your-ruby-on-rails-app-with-the-digitalocean-one-click-image
Any idea what could be wrong or where to start looking?
Trying to deploy my Rails app on DigitalOcean using a Unicorn Rails
server, and getting some error I can't interpret:
root@blog:/home/rails# tail -40 /home/unicorn/log/unicorn.log
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/definition.rb:148:in
`requested_specs'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/environment.rb:18:in
`requested_specs'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:13:in
`setup'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler.rb:120:in
`setup'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/setup.rb:17:in
`<top (required)>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in
`require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in
`rescue in require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:35:in
`require'
/home/rails/config/boot.rb:6:in `<top (required)>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/home/rails/config/application.rb:1:in `<top (required)>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/home/rails/config/environment.rb:2:in `<top (required)>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
`require'
config.ru:4:in `block in <main>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/rack-
1.4.5/lib/rack/builder.rb:51:in `instance_eval'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/rack-1.4.5/lib/rack/builder.rb:51:in
`initialize'
config.ru:1:in `new'
config.ru:1:in `<main>'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn.rb:48:in
`eval'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn.rb:48:in
`block in builder'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:722:in
`call'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:722:in
`build_app!'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:595:in
`init_worker_process'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:615:in
`worker_loop'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:500:in
`spawn_missing_workers'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:511:in
`maintain_worker_count'
/usr/local/rvm/rubies/ruby-1.9.3-p429/lib/ruby/gems/1.9.1/gems/unicorn-4.6.3/lib/unicorn/http_server.rb:277:in
`join'
/usr/bin/unicorn:121:in `<main>'
E, [2013-09-15T00:28:11.016488 #11684] ERROR -- : reaped
#<Process::Status: pid 16029 exit 1> worker=1
I, [2013-09-15T00:28:11.016608 #11684] INFO -- : worker=1 spawning...
E, [2013-09-15T00:28:11.018269 #11684] ERROR -- : reaped
#<Process::Status: pid 16031 exit 1> worker=0
I, [2013-09-15T00:28:11.018385 #11684] INFO -- : worker=0 spawning...
I, [2013-09-15T00:28:11.019306 #16035] INFO -- : worker=1 spawned pid=16035
I, [2013-09-15T00:28:11.021522 #16037] INFO -- : worker=0 spawned pid=16037
I, [2013-09-15T00:28:11.023002 #16035] INFO -- : Refreshing Gem list
I, [2013-09-15T00:28:11.027851 #16037] INFO -- : Refreshing Gem list
I followed the tutorial here:
https://www.digitalocean.com/community/articles/how-to-launch-your-ruby-on-rails-app-with-the-digitalocean-one-click-image
Any idea what could be wrong or where to start looking?
How can I show a list of comma-separated related model titles using Phalcon's Volt templates?
How can I show a list of comma-separated related model titles using
Phalcon's Volt templates?
I want to display a list of related models in my view, as a
comma-separated list.
Say I have a Posts model, and related Tags, post.getTags() gets the
related models but I can't see how to then concatenate them in a way that
will produce the right output.
In plain PHP views, I'd simply put the HTML into an array and implode(',
', $tagLinks).
How can I achieve the same output with Volt?
Phalcon's Volt templates?
I want to display a list of related models in my view, as a
comma-separated list.
Say I have a Posts model, and related Tags, post.getTags() gets the
related models but I can't see how to then concatenate them in a way that
will produce the right output.
In plain PHP views, I'd simply put the HTML into an array and implode(',
', $tagLinks).
How can I achieve the same output with Volt?
Clear table settings from previous engine
Clear table settings from previous engine
I running MariaDB and on myisam tables try change engine to aria. After
changing it back, I have some errors with tables. I need to set
rowformat=fixed, phpadmin says ok but format is still dynamic :-/ in
console I get warning:
MariaDB [(none)]> ALTER TABLE test.mytable ROW_FORMAT=FIXED;
Query OK, 0 rows affected, 1 warning (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 1
Table storage engine 'MyISAM' does not support the create option
'TRANSACTIONAL=0'
transactional=0 is parameter from aria engine which stay on table after
change engine to myisam, but how to delete this?
if I make copy of table, settings is copied too...and re-create tables
manually is not possible, this problem affect large amount of tables :(
I running MariaDB and on myisam tables try change engine to aria. After
changing it back, I have some errors with tables. I need to set
rowformat=fixed, phpadmin says ok but format is still dynamic :-/ in
console I get warning:
MariaDB [(none)]> ALTER TABLE test.mytable ROW_FORMAT=FIXED;
Query OK, 0 rows affected, 1 warning (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 1
Table storage engine 'MyISAM' does not support the create option
'TRANSACTIONAL=0'
transactional=0 is parameter from aria engine which stay on table after
change engine to myisam, but how to delete this?
if I make copy of table, settings is copied too...and re-create tables
manually is not possible, this problem affect large amount of tables :(
Why wouldn't I disable MYSQL_ATTR_DIRECT_QUERY?
Why wouldn't I disable MYSQL_ATTR_DIRECT_QUERY?
I stumbled upon the (imho rather poorly documented) fact that by default
PHP PDO has the flag MYSQL_ATTR_DIRECT_QUERY enabled for its MySQL driver.
This means rather than actually use prepared statements, it emulates the
behaviour of prepared statements. This means it replaces the placeholders
client-side with escaped values and just sends the full query to the
database as-is.
There used to be a good reason to do this, as under older versions of
MySQL prepared statements would bypass the query cache. But this hasn't
been the case for a while now. There's still a slight performance
advantage, as it reduces the number of roundtrips from your app to the
database, but I'm not sure that's worth it?
The obvious downside to using this method is that we're still relying on
client-side escaping, which is usually a bad idea. I've run into weird
issues with mysqli_real_escape_string in the past where invalid characters
were allowed into a query due to some character set misconfiguration. I'd
rather not have something like that happen again.
I'm only finding half-truths and superficial comments on this issue (e.g.
'yeah, you can enable that' or 'it'll cause "issues"'). Looking for a real
reason why I wouldn't switch this off? Is using actual prepared statements
in MySQL/PDO in anyway incompatible with emulated prepared statements?
Part of the reason why I'm asking is because we use PHPActiverecord, which
relies on PDO. It doesn't ship with tests and I don't want it to suddenly
break in production because switching off emulated prepared statements
subtly changes behaviour in certain edge cases or something.
(as a side-note, before anyone brings it up: checking
PDO::ATTR_EMULATE_PREPARES won't work as it's not actually (fully)
implemented for the MySQL driver, you have to check
PDO::MYSQL_ATTR_DIRECT_QUERY instead. Yeah, that one took me a while.)
I stumbled upon the (imho rather poorly documented) fact that by default
PHP PDO has the flag MYSQL_ATTR_DIRECT_QUERY enabled for its MySQL driver.
This means rather than actually use prepared statements, it emulates the
behaviour of prepared statements. This means it replaces the placeholders
client-side with escaped values and just sends the full query to the
database as-is.
There used to be a good reason to do this, as under older versions of
MySQL prepared statements would bypass the query cache. But this hasn't
been the case for a while now. There's still a slight performance
advantage, as it reduces the number of roundtrips from your app to the
database, but I'm not sure that's worth it?
The obvious downside to using this method is that we're still relying on
client-side escaping, which is usually a bad idea. I've run into weird
issues with mysqli_real_escape_string in the past where invalid characters
were allowed into a query due to some character set misconfiguration. I'd
rather not have something like that happen again.
I'm only finding half-truths and superficial comments on this issue (e.g.
'yeah, you can enable that' or 'it'll cause "issues"'). Looking for a real
reason why I wouldn't switch this off? Is using actual prepared statements
in MySQL/PDO in anyway incompatible with emulated prepared statements?
Part of the reason why I'm asking is because we use PHPActiverecord, which
relies on PDO. It doesn't ship with tests and I don't want it to suddenly
break in production because switching off emulated prepared statements
subtly changes behaviour in certain edge cases or something.
(as a side-note, before anyone brings it up: checking
PDO::ATTR_EMULATE_PREPARES won't work as it's not actually (fully)
implemented for the MySQL driver, you have to check
PDO::MYSQL_ATTR_DIRECT_QUERY instead. Yeah, that one took me a while.)
Retrieve database value based on year?
Retrieve database value based on year?
I have a table named as holidays i want to filter the row based on the
year. My database table look like this,
2013-09-25
2013-09-12
2014-01-15
2014-05-15
i want only the column values whose year starts with 20013?
I have a table named as holidays i want to filter the row based on the
year. My database table look like this,
2013-09-25
2013-09-12
2014-01-15
2014-05-15
i want only the column values whose year starts with 20013?
Silverlight 4 to Silverlight 5 migration
Silverlight 4 to Silverlight 5 migration
I am starting to upgrade my Silverlight projects from SL4 to SL5, is there
any key points/best practices to keep in mind?
Any specific issues with Visual studio 2010 + Silverlight 5?
I am starting to upgrade my Silverlight projects from SL4 to SL5, is there
any key points/best practices to keep in mind?
Any specific issues with Visual studio 2010 + Silverlight 5?
Friday, 13 September 2013
Is mysql query in the php will not execute without phpmyadmin?
Is mysql query in the php will not execute without phpmyadmin?
I have recently taken VPS server. they have installed Mysql, PHP not the
PhpMyadmin. I can able to run sql commands from putty client terminal.and
also Php Script Like
echo "Hello";
But I am not able to run sql queries within php from browser. Simply i am
getting Server error. Is it due to phpMyadmin not installed?
I have recently taken VPS server. they have installed Mysql, PHP not the
PhpMyadmin. I can able to run sql commands from putty client terminal.and
also Php Script Like
echo "Hello";
But I am not able to run sql queries within php from browser. Simply i am
getting Server error. Is it due to phpMyadmin not installed?
Altering the Kinetic group childrens array
Altering the Kinetic group childrens array
Straight forward: How do I change the position of Kinetic.Group children
in the array? It is really important for me that I can alter the array and
the position of each children.
I tried to add a child with Array.splice on a specific position but
library crashed. So I sticked to the native .add() function, took the
child from the end of the array and spliced it on first place afterwards:
mapTilesContainer.add(image);
var tempChild =
mapTilesContainer.children[mapTilesContainer.children.length - 1];
// delete it from the last place
mapTilesContainer.children.splice(mapTilesContainer.children.length - 1, 1);
// add it to the first place
mapTilesContainer.children.splice(0, 0, tempChild);
which somehow works, but if I then want to destroy a child regularly with
.destroy() it crashes again:
mapTilesContainer.children[8].destroy();
Telling me: Uncaught TypeError: Cannot call method 'getLayer' of undefined
in kinetic.js:2
Adding and destroying without messing with splice works though. Any ideas?
Straight forward: How do I change the position of Kinetic.Group children
in the array? It is really important for me that I can alter the array and
the position of each children.
I tried to add a child with Array.splice on a specific position but
library crashed. So I sticked to the native .add() function, took the
child from the end of the array and spliced it on first place afterwards:
mapTilesContainer.add(image);
var tempChild =
mapTilesContainer.children[mapTilesContainer.children.length - 1];
// delete it from the last place
mapTilesContainer.children.splice(mapTilesContainer.children.length - 1, 1);
// add it to the first place
mapTilesContainer.children.splice(0, 0, tempChild);
which somehow works, but if I then want to destroy a child regularly with
.destroy() it crashes again:
mapTilesContainer.children[8].destroy();
Telling me: Uncaught TypeError: Cannot call method 'getLayer' of undefined
in kinetic.js:2
Adding and destroying without messing with splice works though. Any ideas?
Change scale UIImageView after rotation UIImageView
Change scale UIImageView after rotation UIImageView
Good morning. With the use of new scale to my picture, I then apply
rotation ale case of late scale image is getting old scale.
-(void)rotate:(UIRotationGestureRecognizer *)rotationRecognizer{
double rotation;
rotation=rotationRecognizer.rotation;
((UIImageView*)[rotationRecognizer view]).transform
=CGAffineTransformMakeRotation(rotation);
self.photoParent = [self.pictures objectAtIndex:0];
self.photoParent.rotation =[NSNumber numberWithDouble:rotation];
NSLog(@"rotation%@",self.photoParent);
}
Good morning. With the use of new scale to my picture, I then apply
rotation ale case of late scale image is getting old scale.
-(void)rotate:(UIRotationGestureRecognizer *)rotationRecognizer{
double rotation;
rotation=rotationRecognizer.rotation;
((UIImageView*)[rotationRecognizer view]).transform
=CGAffineTransformMakeRotation(rotation);
self.photoParent = [self.pictures objectAtIndex:0];
self.photoParent.rotation =[NSNumber numberWithDouble:rotation];
NSLog(@"rotation%@",self.photoParent);
}
Storing two pieces of data for a Javascript application
Storing two pieces of data for a Javascript application
I'm building an HTML5 / Javascript / jQuery application for personal use.
The application needs to literally just store two numbers in order to be
able to function. What is the absolute lightest way I can store two
numbers between script executions? Ideally, the solution would not require
the application to run on a server.
I'm building an HTML5 / Javascript / jQuery application for personal use.
The application needs to literally just store two numbers in order to be
able to function. What is the absolute lightest way I can store two
numbers between script executions? Ideally, the solution would not require
the application to run on a server.
Yii DB Connection Error
Yii DB Connection Error
I'm getting the following error from my page at http://ocytoronto.org/demo/.
CDbConnection failed to open the DB connection: SQLSTATE[HY000]: General
error: 1193 Unknown system variable 'NAMES'
What's more confusing is this used to work fine till yesterday. Any help?
I'm getting the following error from my page at http://ocytoronto.org/demo/.
CDbConnection failed to open the DB connection: SQLSTATE[HY000]: General
error: 1193 Unknown system variable 'NAMES'
What's more confusing is this used to work fine till yesterday. Any help?
Thursday, 12 September 2013
Drag and drop a file from a webpage into Outlook
Drag and drop a file from a webpage into Outlook
In Gmail, an email attachment can be downloaded by dragging the item from
the webpage into a folder. A solution for achieving this is described in
Case Study: Drag and Drop Download in Chrome on HTML5Rocks.
I'd like to drag an item from a web page and use it as an attachment in an
email. I've tried dragging items from Gmail into Outlook, but it won't
catch the attachment.
Is it possible to drag files from a web page into a drop area in an
application normally capable of catching files? If not, are there any
workarounds making it possible to create a more sexy user experience than
dragging the file to a folder and then drag it into an email application?
In Gmail, an email attachment can be downloaded by dragging the item from
the webpage into a folder. A solution for achieving this is described in
Case Study: Drag and Drop Download in Chrome on HTML5Rocks.
I'd like to drag an item from a web page and use it as an attachment in an
email. I've tried dragging items from Gmail into Outlook, but it won't
catch the attachment.
Is it possible to drag files from a web page into a drop area in an
application normally capable of catching files? If not, are there any
workarounds making it possible to create a more sexy user experience than
dragging the file to a folder and then drag it into an email application?
Access file from outside the project directory in Django python
Access file from outside the project directory in Django python
I have a file test.py outside my current Django project directory. How can
I import test.py into one of the python files(views.py) which are inside
my project directory?
test.py
def hello():
print 1+1
views.py
def dashboard(request):
a = hello();
print a
I have a file test.py outside my current Django project directory. How can
I import test.py into one of the python files(views.py) which are inside
my project directory?
test.py
def hello():
print 1+1
views.py
def dashboard(request):
a = hello();
print a
Java Eclipse: class cannot be resolved to a type inheritance
Java Eclipse: class cannot be resolved to a type inheritance
I've run into an issue where when I open projects in Eclipse there is
something wrong with the visibility of classes across packages.
Example:
package.a
- public abstract class clazz
package.b
- public abstract class clazzy extends clazz
In the above instance clazzy would have an error, where clazz wouldn't
available. If I move clazzy into package.a, and the move it back to
package.b everything is fine, but otherwise I can't get eclipse to
recognize that clazz exists at all.
EDIT 1:
Yes, I am importing the class. I also press ctrl-shift-o (import). If I
hand type out the import, eclipse still fails to recognize that clazz
exists. I have not tried importing the entire package, as generally I
avoid doing this for a whole variety of reasons.
I've run into an issue where when I open projects in Eclipse there is
something wrong with the visibility of classes across packages.
Example:
package.a
- public abstract class clazz
package.b
- public abstract class clazzy extends clazz
In the above instance clazzy would have an error, where clazz wouldn't
available. If I move clazzy into package.a, and the move it back to
package.b everything is fine, but otherwise I can't get eclipse to
recognize that clazz exists at all.
EDIT 1:
Yes, I am importing the class. I also press ctrl-shift-o (import). If I
hand type out the import, eclipse still fails to recognize that clazz
exists. I have not tried importing the entire package, as generally I
avoid doing this for a whole variety of reasons.
ExtJS: Excel-Style column functions
ExtJS: Excel-Style column functions
As a simple example, suppose I want to make a grid of mathematical products:
A | B | C
----------
7 | 2 | 14
1 | 5 | 5
2 | 4 | 8
6 | 0 | 0
3 | 3 | 9
...
Suppose my database only stores values for A and B. I then have 3 options:
Calculate C server-side, and use ExtJS models with A, B, C as fields
Calculate C client-side when initialing loading a record (via some
reader?) HOW TO DO THIS
Calculate C client-side, after the grid has rendered, by going row-by-row,
extracting A and B and setting the value of C
Just store A, B, C in the database
Thoughts? I don't know why, but I think (2) is the cleanest if I can find
a way of doing it..
As a simple example, suppose I want to make a grid of mathematical products:
A | B | C
----------
7 | 2 | 14
1 | 5 | 5
2 | 4 | 8
6 | 0 | 0
3 | 3 | 9
...
Suppose my database only stores values for A and B. I then have 3 options:
Calculate C server-side, and use ExtJS models with A, B, C as fields
Calculate C client-side when initialing loading a record (via some
reader?) HOW TO DO THIS
Calculate C client-side, after the grid has rendered, by going row-by-row,
extracting A and B and setting the value of C
Just store A, B, C in the database
Thoughts? I don't know why, but I think (2) is the cleanest if I can find
a way of doing it..
ConcurrentModificationException when using iterators
ConcurrentModificationException when using iterators
I have this java code that iterates over ArrayList of objects and remove
some records from it, but I have a ConcurrentModificationException, here
is my code.
for (ServiceWorkFlowStepModel s :
svcModel.getServiceModel().getWorkFlowSteps()) {
if (s.getStepOrder().equals(stepIndex + 1)) {
svcModel.getServiceModel().getWorkFlowSteps().remove(s);
}
Iterator<ActivityModel> iter = activities.iterator();
while (iter.hasNext()) {
ActivityModel am = iter.next();
if
(am.getComponentModel().getComponenetId().equals(s.getComponentId()))
{
iter.remove();
}
}
}
I have this java code that iterates over ArrayList of objects and remove
some records from it, but I have a ConcurrentModificationException, here
is my code.
for (ServiceWorkFlowStepModel s :
svcModel.getServiceModel().getWorkFlowSteps()) {
if (s.getStepOrder().equals(stepIndex + 1)) {
svcModel.getServiceModel().getWorkFlowSteps().remove(s);
}
Iterator<ActivityModel> iter = activities.iterator();
while (iter.hasNext()) {
ActivityModel am = iter.next();
if
(am.getComponentModel().getComponenetId().equals(s.getComponentId()))
{
iter.remove();
}
}
}
XSLT enumerate each child element
XSLT enumerate each child element
I am trying to create a super generic XSLT that basically can only count
on the table & row elements being there. I have the following sample XML I
am trying to make an XSLT for:
<?xml version="1.0" encoding="UTF-8"?>
<table>
<row>
<id>5311</id>
<status>Active</status>
<id_vendor>Verizon</id_vendor>
<mobile_number>555123456</mobile_number>
</row>
<row>
<id>5312</id>
<status>Inactive</status>
<id_vendor>Sprint</id_vendor>
<mobile_number>555123457</mobile_number>
</row>
<row>
<id>5313</id>
<status>Active</status>
<id_vendor>ATT</id_vendor>
<mobile_number>555123458</mobile_number>
</row>
</table>
The problem is that I do not know what the fields are going to end up
being (id, status, id_vendor, mobile_number, etc. are all subject to
change.
I want to make pleasant to look at view such as:
<div style="background-color:#E3CA87;padding:.2em">
<div style="background-color:#F1E2BB;padding:.2em">
<div>id: x<div>
<div>status: active<div>
<div>id_vendor: Verizon<div>
<div>mobile_number: 555123456<div>
<div>
<div>
Here is what I have so far.. but I can't get the anonymous elements going
right:
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<body style="background-color:#eee;font-size:12pt;font-family:Arial;">
<xsl:for-each select="table/row">
<div style="background-color:#eee;padding:.5em">
<xsl:for-each select="/*">
<div style="background-color:#E3CA87;padding:.2em;border: 1px solid
black">
<xsl:for-each select="/*">
<div style="background-color:#F1E2BB;padding:.2em">
<xsl:value-of select="*" />
</div>
</xsl:for-each>
</div>
</xsl:for-each>
</div>
</xsl:for-each>
</body>
</html>
I am trying to create a super generic XSLT that basically can only count
on the table & row elements being there. I have the following sample XML I
am trying to make an XSLT for:
<?xml version="1.0" encoding="UTF-8"?>
<table>
<row>
<id>5311</id>
<status>Active</status>
<id_vendor>Verizon</id_vendor>
<mobile_number>555123456</mobile_number>
</row>
<row>
<id>5312</id>
<status>Inactive</status>
<id_vendor>Sprint</id_vendor>
<mobile_number>555123457</mobile_number>
</row>
<row>
<id>5313</id>
<status>Active</status>
<id_vendor>ATT</id_vendor>
<mobile_number>555123458</mobile_number>
</row>
</table>
The problem is that I do not know what the fields are going to end up
being (id, status, id_vendor, mobile_number, etc. are all subject to
change.
I want to make pleasant to look at view such as:
<div style="background-color:#E3CA87;padding:.2em">
<div style="background-color:#F1E2BB;padding:.2em">
<div>id: x<div>
<div>status: active<div>
<div>id_vendor: Verizon<div>
<div>mobile_number: 555123456<div>
<div>
<div>
Here is what I have so far.. but I can't get the anonymous elements going
right:
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<body style="background-color:#eee;font-size:12pt;font-family:Arial;">
<xsl:for-each select="table/row">
<div style="background-color:#eee;padding:.5em">
<xsl:for-each select="/*">
<div style="background-color:#E3CA87;padding:.2em;border: 1px solid
black">
<xsl:for-each select="/*">
<div style="background-color:#F1E2BB;padding:.2em">
<xsl:value-of select="*" />
</div>
</xsl:for-each>
</div>
</xsl:for-each>
</div>
</xsl:for-each>
</body>
</html>
triangulation without long triangles
triangulation without long triangles
In python, for a set of points, With
import matplotlib.tri as tri
triang = tri.Triangulation(x, y)
How I can make a mask for eliminate the triangles with long edges ?
In python, for a set of points, With
import matplotlib.tri as tri
triang = tri.Triangulation(x, y)
How I can make a mask for eliminate the triangles with long edges ?
JS How to make button connect with script
JS How to make button connect with script
How to make connect button with my javascript ?
My JS compares 2 times and display greater, but i see result when edit
object, i need help with, how connect my script with button.
When i click button then achieve my scripy and display alert with message.
How to make connect button with my javascript ?
My JS compares 2 times and display greater, but i see result when edit
object, i need help with, how connect my script with button.
When i click button then achieve my scripy and display alert with message.
Wednesday, 11 September 2013
WCF Service exporting 1 Interface with 2 Implementation classes
WCF Service exporting 1 Interface with 2 Implementation classes
I'm new to WCF and C#.
I'm trying to create a WCF Service with 1 Interface (IA) with 1 method
(Do) which has 2 implementations (A1 & A2).
A silly example:
IA.cs:
namespace IA_NS
{
[ServiceContract]
public interface IA
{
[OperationContract]
int Do(B b);
}
[DataContract]
public class B
{
[DataMember]
public string b1 { get; set; }
}
}
A1.cs:
namespace A1_NS
{
public class A1 : A
{
public int Do(B b) {...}
}
}
A2.cs:
namespace A2_NS
{
public class A2 : A
{
public int Do(B b) {...}
}
}
I want my WCF Client to be able to call both classes:
Client.cs:
namespace Client_NS
{
class Program
{
static void Main(string[] args)
{
...
B myB;
if (...)
A1.Do(myB);
else
A2.Do(myB);
}
}
}
No luck ;-(
I tried putting 2 elements in my WCF-Service app.config:
<service name="A1_NS.A1" >
<endpoint address="http://localhost/A1"
contract="IA_NS.IA" />
</service>
<service name="A2_NS.A2" >
<endpoint address="http://localhost/A2"
contract="IA_NS.IA" />
contract="IA_NS.IA" />
</service>
When running the debugger - the debugging app (WCF Service Host) lets me
test the Do() method of both classes.
I can't get my Client to do it. I added Service References for both
services. Is it the Client app.config or am I misunderstanding something?
I'm new to WCF and C#.
I'm trying to create a WCF Service with 1 Interface (IA) with 1 method
(Do) which has 2 implementations (A1 & A2).
A silly example:
IA.cs:
namespace IA_NS
{
[ServiceContract]
public interface IA
{
[OperationContract]
int Do(B b);
}
[DataContract]
public class B
{
[DataMember]
public string b1 { get; set; }
}
}
A1.cs:
namespace A1_NS
{
public class A1 : A
{
public int Do(B b) {...}
}
}
A2.cs:
namespace A2_NS
{
public class A2 : A
{
public int Do(B b) {...}
}
}
I want my WCF Client to be able to call both classes:
Client.cs:
namespace Client_NS
{
class Program
{
static void Main(string[] args)
{
...
B myB;
if (...)
A1.Do(myB);
else
A2.Do(myB);
}
}
}
No luck ;-(
I tried putting 2 elements in my WCF-Service app.config:
<service name="A1_NS.A1" >
<endpoint address="http://localhost/A1"
contract="IA_NS.IA" />
</service>
<service name="A2_NS.A2" >
<endpoint address="http://localhost/A2"
contract="IA_NS.IA" />
contract="IA_NS.IA" />
</service>
When running the debugger - the debugging app (WCF Service Host) lets me
test the Do() method of both classes.
I can't get my Client to do it. I added Service References for both
services. Is it the Client app.config or am I misunderstanding something?
Exercise (Big-Oh): How do find intersection of two functions where n = 100 for example
Exercise (Big-Oh): How do find intersection of two functions where n = 100
for example
I am trying to understand how n^2 is faster than nlogn for n < 100 and
opposite when n >= 100. In general this is not the case but this is an
exercise that I do not want an answer for but to lead me to the right
direction. I can picture two function in a graph that intersection at n =
100 as n < 100 O(n^2) is faster and as n > 100 O(nlogn) is faster.
I came up with an^2+b and c*nlog(n)+d
The key to my understanding here is constant that makes the differences.
But what is hard is that I need to come up with constants that will
satisfy the above scenario. Is there a way or technique that is done or am
I going correctly on the wrong direction?
Original question: James and Brad are arguing about the performance of
their sorting algorithms. James claims that hisO(N logN)-time algorithm is
always faster than Brad's O(N2)-time algorithm. To settle the issue, they
implement and run the two algorithms on many randomly generated data sets.
To James' dismay, they find that if N < 100 the O(N2)-time algorithm
actually runs faster, and only when
N >= 100 the O(N logN)-time one
is better. Explain why the above scenario is possible. You may give
numerical examples.
for example
I am trying to understand how n^2 is faster than nlogn for n < 100 and
opposite when n >= 100. In general this is not the case but this is an
exercise that I do not want an answer for but to lead me to the right
direction. I can picture two function in a graph that intersection at n =
100 as n < 100 O(n^2) is faster and as n > 100 O(nlogn) is faster.
I came up with an^2+b and c*nlog(n)+d
The key to my understanding here is constant that makes the differences.
But what is hard is that I need to come up with constants that will
satisfy the above scenario. Is there a way or technique that is done or am
I going correctly on the wrong direction?
Original question: James and Brad are arguing about the performance of
their sorting algorithms. James claims that hisO(N logN)-time algorithm is
always faster than Brad's O(N2)-time algorithm. To settle the issue, they
implement and run the two algorithms on many randomly generated data sets.
To James' dismay, they find that if N < 100 the O(N2)-time algorithm
actually runs faster, and only when
N >= 100 the O(N logN)-time one
is better. Explain why the above scenario is possible. You may give
numerical examples.
Example of how to use bind_result vs get_result
Example of how to use bind_result vs get_result
I would like to see an example of how to call using bind_result vs.
get_result and what would be the purpose of using one over the other.
Also the pro and cons of using each.
What is the limitation of using either and is there a difference.
I would like to see an example of how to call using bind_result vs.
get_result and what would be the purpose of using one over the other.
Also the pro and cons of using each.
What is the limitation of using either and is there a difference.
How to download a file from an ajax call to a controller?
How to download a file from an ajax call to a controller?
I am making a GET ajax call to an mvc controller that returns a
FileStreamResult. Now when I look at the network traffic of the browser, I
see a XMLHttpRequest being made which comes back with a 200 result.
In ie f12 tool if I go to the response body tab I see a Save as link,
which when clicked gives the correct file
How do I instead give them an option to download the file?
I am making a GET ajax call to an mvc controller that returns a
FileStreamResult. Now when I look at the network traffic of the browser, I
see a XMLHttpRequest being made which comes back with a 200 result.
In ie f12 tool if I go to the response body tab I see a Save as link,
which when clicked gives the correct file
How do I instead give them an option to download the file?
Is it possible to use an existing webjar in your jruby on rails applications?
Is it possible to use an existing webjar in your jruby on rails applications?
Is it possible to use an existing webjar in your jruby on rails applications?
If a webjar cannot be used directly in a JRoR application, is it possible
to access a webjar from your rails application which is deployed via .war
file to glassfish or tomcat?
I'm not very familiar with Java webjars, so I apologize if I'm not asking
the right questions here. The goal, however, is code reuse.
Is it possible to use an existing webjar in your jruby on rails applications?
If a webjar cannot be used directly in a JRoR application, is it possible
to access a webjar from your rails application which is deployed via .war
file to glassfish or tomcat?
I'm not very familiar with Java webjars, so I apologize if I'm not asking
the right questions here. The goal, however, is code reuse.
How to deploy War file in Fuse ESB
How to deploy War file in Fuse ESB
I have developed a webservice using Apache CXF and deployed it on Apache
Tomcat and its working fine.
Now i required to deploy it on Jboss Fuse. I tried to deploy it by copying
in deploy folder but not able to get ?wsdl and found following error in
fuse.log
16:28:49,889 | ERROR | Executor: 1 | ContextLoader | 174 -
org.springframework.web - 3.1.3.RELEASE | Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected
exception parsing XML document from ServletContext resource
[/WEB-INF/cxf-beans.xml]; nested exception is
org.springframework.beans.FatalBeanException: Class
[org.apache.cxf.jaxws.spring.NamespaceHandler] for namespace
[http://cxf.apache.org/jaxws] does not implement the
[org.springframework.beans.factory.xml.NamespaceHandler] interface at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412)[105:org.springframework.beans:3.1.3.RELEASE]
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)[105:org.springframework.beans:3.1.3.RELEASE]
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)[105:org.springframework.beans:3.1.3.RELEASE]
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)[105:org.springframework.beans:3.1.3.RELEASE]
Please guide how i can deploy it on Fuse and what kind of configuration
changes required.
Regards, imran
I have developed a webservice using Apache CXF and deployed it on Apache
Tomcat and its working fine.
Now i required to deploy it on Jboss Fuse. I tried to deploy it by copying
in deploy folder but not able to get ?wsdl and found following error in
fuse.log
16:28:49,889 | ERROR | Executor: 1 | ContextLoader | 174 -
org.springframework.web - 3.1.3.RELEASE | Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected
exception parsing XML document from ServletContext resource
[/WEB-INF/cxf-beans.xml]; nested exception is
org.springframework.beans.FatalBeanException: Class
[org.apache.cxf.jaxws.spring.NamespaceHandler] for namespace
[http://cxf.apache.org/jaxws] does not implement the
[org.springframework.beans.factory.xml.NamespaceHandler] interface at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412)[105:org.springframework.beans:3.1.3.RELEASE]
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)[105:org.springframework.beans:3.1.3.RELEASE]
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)[105:org.springframework.beans:3.1.3.RELEASE]
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)[105:org.springframework.beans:3.1.3.RELEASE]
Please guide how i can deploy it on Fuse and what kind of configuration
changes required.
Regards, imran
Failed to load the JNI Shared Library c:\APS\jdk1.5.0_22_x64/bin..\jre\bin\server\jvm.dll
Failed to load the JNI Shared Library
c:\APS\jdk1.5.0_22_x64/bin..\jre\bin\server\jvm.dll
While starting the Eclipse when ever u get above exception then
followbelow steps : 1. Here your windows on 64 bit. 2. Go to command
window and check the java version. 3. Here it will show different java
version e.g. In u'r machine u have installed java version 1.5 and same
updated in system variable but in command promt it will show u java
version as 1.6. 6. So Please go to below location in u'r system :
C:\Windows\System32 and delete or rename the java.exe and javaw.exe file.
7. Then restart the eclipse here eclipse will refer the java (version
should be compatible to 64 bit) path from system variable which is defined
. 8. And when u check the java version from command promt it will show u
the version which was installed by u.
c:\APS\jdk1.5.0_22_x64/bin..\jre\bin\server\jvm.dll
While starting the Eclipse when ever u get above exception then
followbelow steps : 1. Here your windows on 64 bit. 2. Go to command
window and check the java version. 3. Here it will show different java
version e.g. In u'r machine u have installed java version 1.5 and same
updated in system variable but in command promt it will show u java
version as 1.6. 6. So Please go to below location in u'r system :
C:\Windows\System32 and delete or rename the java.exe and javaw.exe file.
7. Then restart the eclipse here eclipse will refer the java (version
should be compatible to 64 bit) path from system variable which is defined
. 8. And when u check the java version from command promt it will show u
the version which was installed by u.
Tuesday, 10 September 2013
Archiving a record to mysql using php
Archiving a record to mysql using php
I'm developing a record management system, but i dont know how to archive
it's records. can somebody please give me an idea or logic on how to
archive records. thanks for your time & effort for helping me ..,
I'm developing a record management system, but i dont know how to archive
it's records. can somebody please give me an idea or logic on how to
archive records. thanks for your time & effort for helping me ..,
How to set environment variable in Ubuntu
How to set environment variable in Ubuntu
I am new to ubuntu. I am using matlab in ubuntu. I used 'mcc' command in
matlab(ubuntu) to create executable files.
Now to run those executables I need to set the 'MCR' directory path to the
environment variable. I used 'setenv' but, it says 'setenv is not found.
the following is what I did-
setenv PATH/<mcr root path>/v7.17: "$PATH"
And I get the following output-
No command 'setenv' found, did you mean command 'neten'
from package 'netenv'
setenv: commmand not found
Can you please help me telling how do I set the environment variable in
ubuntu to run my executable files.
Regards,
I am new to ubuntu. I am using matlab in ubuntu. I used 'mcc' command in
matlab(ubuntu) to create executable files.
Now to run those executables I need to set the 'MCR' directory path to the
environment variable. I used 'setenv' but, it says 'setenv is not found.
the following is what I did-
setenv PATH/<mcr root path>/v7.17: "$PATH"
And I get the following output-
No command 'setenv' found, did you mean command 'neten'
from package 'netenv'
setenv: commmand not found
Can you please help me telling how do I set the environment variable in
ubuntu to run my executable files.
Regards,
program to remove a row in excel baseed on cell value
program to remove a row in excel baseed on cell value
Can some one tell me how achieve the following task?
I have a excel and i want delete some rows based on the particular cell
value, but the excel is very very huge it has got around 75000 rows. I
tried writing a nomal function to loop through the sheet, check for the
cell value and delete the rows if matched. but it is taking very long
time. i waited for 30 min and program was still running can some one
suggest me how to achieve this.
Thanks in Advance. Veeresh
Can some one tell me how achieve the following task?
I have a excel and i want delete some rows based on the particular cell
value, but the excel is very very huge it has got around 75000 rows. I
tried writing a nomal function to loop through the sheet, check for the
cell value and delete the rows if matched. but it is taking very long
time. i waited for 30 min and program was still running can some one
suggest me how to achieve this.
Thanks in Advance. Veeresh
Apache Shiro- using DataBase to read users, roles and permissions
Apache Shiro- using DataBase to read users, roles and permissions
Currently I've a swing app and I wan't to implement Apache Shiro in order
to Authenticate and delegate permissions to certain roles. I've already
managed myself to read the users from the Shiro.ini file that I've created
for tests, it looks something like this
[users]
admin = 123456, Administrator
[role]
Administrator = *:*:*
However I've stored in a database a table with the info I need and it
looks something like this:
users (id,password,username) userRoles (userId, role) rolePermission
(permissionID,permission,roleID)
I've been trying to understand tutorials that use a JDBC realm, however
they use web applications or specials frameworks to manage their
connection to the DataBase like Apache Derby or BoneCP, and they confuse
me even more with these examples.
So what I'm asking it's how I need to configure the Shiro.ini file if I
wanna use a JDBC realm (with an oracle database) and what classes the
Shiro.ini needs. Any examples or explanation will be appreciated!
Currently I've a swing app and I wan't to implement Apache Shiro in order
to Authenticate and delegate permissions to certain roles. I've already
managed myself to read the users from the Shiro.ini file that I've created
for tests, it looks something like this
[users]
admin = 123456, Administrator
[role]
Administrator = *:*:*
However I've stored in a database a table with the info I need and it
looks something like this:
users (id,password,username) userRoles (userId, role) rolePermission
(permissionID,permission,roleID)
I've been trying to understand tutorials that use a JDBC realm, however
they use web applications or specials frameworks to manage their
connection to the DataBase like Apache Derby or BoneCP, and they confuse
me even more with these examples.
So what I'm asking it's how I need to configure the Shiro.ini file if I
wanna use a JDBC realm (with an oracle database) and what classes the
Shiro.ini needs. Any examples or explanation will be appreciated!
javascript jquery callback accumulates
javascript jquery callback accumulates
Issue: Each time div.a is clicked, the number of callbacks when div.b is
clicked,accumulates by 1.
var $=jQuery;
$(function(){
$("div.a").click(function(){cbf(trgmsg);});
});
function trgmsg(){
alert($.now());
}
function cbf(cb){
$("div.b").click(function(){cb()});
}
Result:
click div.a once and click div.b => alert() pops-up;
if i click div.a again and click div.b => alert() pops-up twice
consecutively;
if i click div.a another time and click div.b => alert() pops-up three
times consecutively;
..and so on
I have No idea what the cause of the problem is or if its simply my
misunderstanding/misuse of callback functions in JS. Any insights and/or
advice will be greatly appreciated. thanks
Issue: Each time div.a is clicked, the number of callbacks when div.b is
clicked,accumulates by 1.
var $=jQuery;
$(function(){
$("div.a").click(function(){cbf(trgmsg);});
});
function trgmsg(){
alert($.now());
}
function cbf(cb){
$("div.b").click(function(){cb()});
}
Result:
click div.a once and click div.b => alert() pops-up;
if i click div.a again and click div.b => alert() pops-up twice
consecutively;
if i click div.a another time and click div.b => alert() pops-up three
times consecutively;
..and so on
I have No idea what the cause of the problem is or if its simply my
misunderstanding/misuse of callback functions in JS. Any insights and/or
advice will be greatly appreciated. thanks
My program skip getting input data?
My program skip getting input data?
I have written a simple program to exchange currency and able to buy a beer.
But there something in program and I don't know why, it auto skips the
third input data -> end program.
Here my code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ex_rate_into_vnd = 20000; //! Exchange Rate
int beer = 7000; //! Local price of a beer
float in_c = 0; //! Input amount of money
float out_c = 2; //! Amount of currency to exchange !
float choice; //! Switch mode
char buy; //! Deal or not
//! Introduction
printf ("||---------------------------------------------------||\n");
printf ("|| Currency Exchange Machine beta ||\n");
printf ("||---------------------------------------------------||\n");
printf ("Please choose your option:\n");
printf("\t 1.Exchange VND to dollar\n");
printf("\t 2.Exchange Dollar to VND\n");
do
{
printf("Your choice: ",choice);
scanf("%f",&choice);
} while( choice != 1 && choice != 2);
printf ("Please enter amount of money:");
scanf("%f",&in_c);
if (choice == 1 )
{
out_c = in_c / ex_rate_into_vnd;
printf ("Your amount of money: %.2f",out_c);
}
else
{
out_c = in_c * ex_rate_into_vnd;
printf ("Your amount of money: %.0f",out_c);
}
//! End of Exchanging
printf ("\nWould you like to buy a beer (y/n) ?",buy);
scanf("%c", &buy);
if (buy == 'y')
{
if (out_c >= 7000)
{
out_c = out_c - 7000;
printf("Transactions success !\n");
printf("Your amount: %2.f",out_c);
}
}
printf ("\nWhy Stop ?");
return 0;
}
I have written a simple program to exchange currency and able to buy a beer.
But there something in program and I don't know why, it auto skips the
third input data -> end program.
Here my code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ex_rate_into_vnd = 20000; //! Exchange Rate
int beer = 7000; //! Local price of a beer
float in_c = 0; //! Input amount of money
float out_c = 2; //! Amount of currency to exchange !
float choice; //! Switch mode
char buy; //! Deal or not
//! Introduction
printf ("||---------------------------------------------------||\n");
printf ("|| Currency Exchange Machine beta ||\n");
printf ("||---------------------------------------------------||\n");
printf ("Please choose your option:\n");
printf("\t 1.Exchange VND to dollar\n");
printf("\t 2.Exchange Dollar to VND\n");
do
{
printf("Your choice: ",choice);
scanf("%f",&choice);
} while( choice != 1 && choice != 2);
printf ("Please enter amount of money:");
scanf("%f",&in_c);
if (choice == 1 )
{
out_c = in_c / ex_rate_into_vnd;
printf ("Your amount of money: %.2f",out_c);
}
else
{
out_c = in_c * ex_rate_into_vnd;
printf ("Your amount of money: %.0f",out_c);
}
//! End of Exchanging
printf ("\nWould you like to buy a beer (y/n) ?",buy);
scanf("%c", &buy);
if (buy == 'y')
{
if (out_c >= 7000)
{
out_c = out_c - 7000;
printf("Transactions success !\n");
printf("Your amount: %2.f",out_c);
}
}
printf ("\nWhy Stop ?");
return 0;
}
How to parse api response on table view?
How to parse api response on table view?
my json response data formate as :-
[{"0":"1","id":"1","1":"Pradeep","name":"Pradeep","2":null,"sender":null,"3":null,"
so to pharse the "name" on table view ?
my own implementation as:-
i am new i ios development please help me
i am new i ios development please help me i am new i ios development
please help me i am new i ios development please help me i am new i ios
development please help me i am new i ios development please help me i am
new i ios development please help me i am new i ios development please
help me i am new i ios development please help me
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization
JSONObjectWithData:webData
options:0 error:nil]; // response saved in allDataDictionary
NSDictionary *feed=[allDataDictionary objectForKey:@"feed"]; // feeds entry
NSArray *feedforentry=[feed objectForKey:@"entry"];
for(NSDictionary *diction in feedforentry)
{
NSDictionary *title=[diction objectForKey:@"title"];
NSString *label=[title objectForKey:@"label"];
[array addObject:label];
}
[[self JustConfesstable]reloadData]; // reload table
}
my json response data formate as :-
[{"0":"1","id":"1","1":"Pradeep","name":"Pradeep","2":null,"sender":null,"3":null,"
so to pharse the "name" on table view ?
my own implementation as:-
i am new i ios development please help me
i am new i ios development please help me i am new i ios development
please help me i am new i ios development please help me i am new i ios
development please help me i am new i ios development please help me i am
new i ios development please help me i am new i ios development please
help me i am new i ios development please help me
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization
JSONObjectWithData:webData
options:0 error:nil]; // response saved in allDataDictionary
NSDictionary *feed=[allDataDictionary objectForKey:@"feed"]; // feeds entry
NSArray *feedforentry=[feed objectForKey:@"entry"];
for(NSDictionary *diction in feedforentry)
{
NSDictionary *title=[diction objectForKey:@"title"];
NSString *label=[title objectForKey:@"label"];
[array addObject:label];
}
[[self JustConfesstable]reloadData]; // reload table
}
Monday, 9 September 2013
for what purpose # (hash) sign is used in MySql?
for what purpose # (hash) sign is used in MySql?
In joomla MVC i came around this SQL querry. I was unable to understand
the purpose of #sign ??
INSERT INTO `#__helloworld` (`greeting`) VALUES
('Hello World!'),
('Good bye World!');
In joomla MVC i came around this SQL querry. I was unable to understand
the purpose of #sign ??
INSERT INTO `#__helloworld` (`greeting`) VALUES
('Hello World!'),
('Good bye World!');
How to change banner after logging in?
How to change banner after logging in?
I am using a php log on system I found on this site and it works very well
but I want to change the banner after the user logs in. I have a set of
different images that are used for the banner right now and I would like
to change it so after you log in the user sees a different set. The banner
code is a simple map consisting of hot spots with onMousOver and
onMouseOut scripts.
This is the php code I use to see if the user is logged in
if(empty($_SESSION['user']))
When the user is logged in I want it to switch to show the other set. Then
when they log out it should go back to showing the original set.
Any help would be appreciated.
I am using a php log on system I found on this site and it works very well
but I want to change the banner after the user logs in. I have a set of
different images that are used for the banner right now and I would like
to change it so after you log in the user sees a different set. The banner
code is a simple map consisting of hot spots with onMousOver and
onMouseOut scripts.
This is the php code I use to see if the user is logged in
if(empty($_SESSION['user']))
When the user is logged in I want it to switch to show the other set. Then
when they log out it should go back to showing the original set.
Any help would be appreciated.
Make Counter consider two objects of the same class the same
Make Counter consider two objects of the same class the same
I'm using collections.Counter. It's great so far, except that I'd like it
to count objects of the same class as the same. How can I do this? I tried
overriding the hash() method on the class so that all instances would hash
the same. Right now, if I do Counter([Type1(), Type1(), Type2(), Type2()])
it will return {<Type1 object at...>:1,<Type1 object at...>:1,<Type2
object at...>:1,<Type2 object at...>:1} I would prefer it to return
something like {"Type1":2, "Type2":2} instead. Is this possible? I was
poking around the docs and couldn't figure out how to make it work.
I should add that the classes I'm using are essentially wrappers for
constant values. It's just more convenient to wrap them in a class. Under
no circumstances will one Type1 object ever differ from another Type1
object.
I'm using collections.Counter. It's great so far, except that I'd like it
to count objects of the same class as the same. How can I do this? I tried
overriding the hash() method on the class so that all instances would hash
the same. Right now, if I do Counter([Type1(), Type1(), Type2(), Type2()])
it will return {<Type1 object at...>:1,<Type1 object at...>:1,<Type2
object at...>:1,<Type2 object at...>:1} I would prefer it to return
something like {"Type1":2, "Type2":2} instead. Is this possible? I was
poking around the docs and couldn't figure out how to make it work.
I should add that the classes I'm using are essentially wrappers for
constant values. It's just more convenient to wrap them in a class. Under
no circumstances will one Type1 object ever differ from another Type1
object.
Foreign Key in MySQL : ERROR 1005
Foreign Key in MySQL : ERROR 1005
I'm a bit confused about adding foreign keys in MySQL
What I'm trying to do is reference the Students primary key with:
CREATE TABLE Enrolled(sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY
KEY (sid, cid), FOREIGN KEY (sid) REFERENCES Students);
However, what I get is
ERROR 1005 (HY000): Can't create table 'test_db.Enrolled' (errno: 150)
I searched around and found
MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"
However, my Students table already has a primary key so this should not be
an issue:
| Students | CREATE TABLE `Students` (
`sid` char(20) NOT NULL DEFAULT '',
`name` char(20) DEFAULT NULL,
`login` char(10) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`gpa` float DEFAULT NULL,
PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
I feel like I'm missing something fairly basic but I can't appear to spot
it. Any advice?
I'm a bit confused about adding foreign keys in MySQL
What I'm trying to do is reference the Students primary key with:
CREATE TABLE Enrolled(sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY
KEY (sid, cid), FOREIGN KEY (sid) REFERENCES Students);
However, what I get is
ERROR 1005 (HY000): Can't create table 'test_db.Enrolled' (errno: 150)
I searched around and found
MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"
However, my Students table already has a primary key so this should not be
an issue:
| Students | CREATE TABLE `Students` (
`sid` char(20) NOT NULL DEFAULT '',
`name` char(20) DEFAULT NULL,
`login` char(10) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`gpa` float DEFAULT NULL,
PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
I feel like I'm missing something fairly basic but I can't appear to spot
it. Any advice?
Split Active Admin index into two tables/panels based on a field
Split Active Admin index into two tables/panels based on a field
I want to do something like this:
ActiveAdmin.register Split do
index do
panel "Cute" do
if cute?
column :blah
default_actions
end
end
panel "Not so cute" do
if not cute?
column :toot
default_actions
end
end
end
end
Where there's the Cute table which lists all the objects which cute? is
true and then there's the Not so cute table where cute? is false.
The problem is that I can't figure out how to split it into two different
tables/panels. I'm getting the following error:
undefined method `column' for <div
class="index_as_table"></div>
:ActiveAdmin::Views::IndexAsTable
Which leads me to believe I shouldn't be using panel above column. I
searched through the ActiveAdmin docs and couldn't find anything about
splitting the index table view into two tables
I want to do something like this:
ActiveAdmin.register Split do
index do
panel "Cute" do
if cute?
column :blah
default_actions
end
end
panel "Not so cute" do
if not cute?
column :toot
default_actions
end
end
end
end
Where there's the Cute table which lists all the objects which cute? is
true and then there's the Not so cute table where cute? is false.
The problem is that I can't figure out how to split it into two different
tables/panels. I'm getting the following error:
undefined method `column' for <div
class="index_as_table"></div>
:ActiveAdmin::Views::IndexAsTable
Which leads me to believe I shouldn't be using panel above column. I
searched through the ActiveAdmin docs and couldn't find anything about
splitting the index table view into two tables
Subscribe to:
Comments (Atom)