setcontext always starts from function line
I am implementing a userthread library. When I try to swap the context
when the yield is called, the swapped function is always starting from the
first line. The program counter is not updated I guess. For Example,
consider there are two Threads, say
T1: {
printf("Inside T1. Yielding to Other \n");
ThreadYield();
MyThreadExit();
}
T2: {
ThreadCreate(t1, 0);
printf("Inside T2. Yielding to Other \n");
ThreadYield();
}
In this case, when I use the setcontext/swapcontext, always the thread
starts from the line 1. So many threads are created and it goes to a
infinite loop. Can anyone tell me what is going wrong
Saturday, 31 August 2013
Java Comparator compareToIgnoreCase
Java Comparator compareToIgnoreCase
I am trying to sort an array of strings using compareToIgnoreCase.
The string contain names ex: Billy Jean
When I try to compare them I get a null pointer exception. I think this is
because of the space between the first and last name. How can I compare
whole name?
Thanks
class CompareStudentNames implements Comparator{
//Sorts the students by name ignoring case.
@Override
public int compare(Object o1, Object o2) {
String name1 = ((Student)o1).getName();
String name2 = ((Student)o2).getName();
return (name1.compareToIgnoreCase(name2));
}
}
I am trying to sort an array of strings using compareToIgnoreCase.
The string contain names ex: Billy Jean
When I try to compare them I get a null pointer exception. I think this is
because of the space between the first and last name. How can I compare
whole name?
Thanks
class CompareStudentNames implements Comparator{
//Sorts the students by name ignoring case.
@Override
public int compare(Object o1, Object o2) {
String name1 = ((Student)o1).getName();
String name2 = ((Student)o2).getName();
return (name1.compareToIgnoreCase(name2));
}
}
Slow response time for `$.mobile.loading()` on mobile devices
Slow response time for `$.mobile.loading()` on mobile devices
On my site, I have a button B which onClick triggers the following code:
$.mobile.loading( 'show', {});
bigJSONrequest(); // synchronous request (NO AJAX)
setTimeout(function()
$('.landing').slideUp('fast', function() {
$.mobile.loading( 'hide', {});
}); }, 1500);
The page-loading widget (triggered by shows up $.mobile.loading)
immediately on desktop computers.
But when I try this on a mobile device (even with fast WiFi connection),
there is a rather large delay until the $.mobile.loading widget appears.
In fact, when I click button B, the network spinner on my iPhone triggers
immediately. Shouldn't the call to $.mobile.loading be entirely
client-side?
How can I make the $.mobile.loading show up faster on mobile devices?
Example: I wanted to make a JSFiddle but it proved to cumbersome. Feel
free to visit here, from your desktop and mobile device and see for
yourself.
On my site, I have a button B which onClick triggers the following code:
$.mobile.loading( 'show', {});
bigJSONrequest(); // synchronous request (NO AJAX)
setTimeout(function()
$('.landing').slideUp('fast', function() {
$.mobile.loading( 'hide', {});
}); }, 1500);
The page-loading widget (triggered by shows up $.mobile.loading)
immediately on desktop computers.
But when I try this on a mobile device (even with fast WiFi connection),
there is a rather large delay until the $.mobile.loading widget appears.
In fact, when I click button B, the network spinner on my iPhone triggers
immediately. Shouldn't the call to $.mobile.loading be entirely
client-side?
How can I make the $.mobile.loading show up faster on mobile devices?
Example: I wanted to make a JSFiddle but it proved to cumbersome. Feel
free to visit here, from your desktop and mobile device and see for
yourself.
Application crashes while starting the new thread
Application crashes while starting the new thread
I have a thread class when I start the thread and create the instance of
thread class in the main class my app get crash. My main activity code for
creating the thread is:
broadcast broadcastobject=new broadcast(messages);
broadcastobject.start();
My thread class is :
public class broadcast extends Thread {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public broadcast(String to) {
// TODO Auto-generated constructor stub
str = to;
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
@Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// socket.setSoTimeout(TIMEOUT_MS);
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(),
str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My log cat error is:
09-01 08:23:47.949: D/gralloc_goldfish(1720): Emulator without GPU
emulation detected.
09-01 08:24:01.941: W/System.err(1720): java.net.SocketException: socket
failed: EACCES (Permission denied)
09-01 08:24:01.941: W/System.err(1720): at
libcore.io.IoBridge.socket(IoBridge.java:573)
09-01 08:24:01.979: W/System.err(1720): at
java.net.PlainDatagramSocketImpl.create(PlainDatagramSocketImpl.java:91)
09-01 08:24:01.979: W/System.err(1720): at
java.net.DatagramSocket.createSocket(DatagramSocket.java:131)
09-01 08:24:01.979: W/System.err(1720): at
java.net.DatagramSocket.<init>(DatagramSocket.java:78)
09-01 08:24:01.989: W/System.err(1720): at
soft.b.peopleassist.broadcast.run(broadcast.java:65)
09-01 08:24:01.989: W/System.err(1720): Caused by:
libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
09-01 08:24:01.999: W/System.err(1720): at
libcore.io.Posix.socket(Native Method)
09-01 08:24:01.999: W/System.err(1720): at
libcore.io.BlockGuardOs.socket(BlockGuardOs.java:169)
09-01 08:24:01.999: W/System.err(1720): at
libcore.io.IoBridge.socket(IoBridge.java:558)
09-01 08:24:02.009: W/System.err(1720): ... 4 more
09-01 08:24:02.149: W/dalvikvm(1720): threadid=11: thread exiting with
uncaught exception (group=0x409961f8)
09-01 08:24:02.149: E/AndroidRuntime(1720): FATAL EXCEPTION: Thread-114
09-01 08:24:02.149: E/AndroidRuntime(1720): java.lang.NullPointerException
09-01 08:24:02.149: E/AndroidRuntime(1720): at
soft.b.peopleassist.broadcast.run(broadcast.java:92)
09-01 08:24:03.329: W/IInputConnectionWrapper(1720): showStatusIcon on
inactive InputConnection
I have a thread class when I start the thread and create the instance of
thread class in the main class my app get crash. My main activity code for
creating the thread is:
broadcast broadcastobject=new broadcast(messages);
broadcastobject.start();
My thread class is :
public class broadcast extends Thread {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public broadcast(String to) {
// TODO Auto-generated constructor stub
str = to;
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
@Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// socket.setSoTimeout(TIMEOUT_MS);
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(),
str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My log cat error is:
09-01 08:23:47.949: D/gralloc_goldfish(1720): Emulator without GPU
emulation detected.
09-01 08:24:01.941: W/System.err(1720): java.net.SocketException: socket
failed: EACCES (Permission denied)
09-01 08:24:01.941: W/System.err(1720): at
libcore.io.IoBridge.socket(IoBridge.java:573)
09-01 08:24:01.979: W/System.err(1720): at
java.net.PlainDatagramSocketImpl.create(PlainDatagramSocketImpl.java:91)
09-01 08:24:01.979: W/System.err(1720): at
java.net.DatagramSocket.createSocket(DatagramSocket.java:131)
09-01 08:24:01.979: W/System.err(1720): at
java.net.DatagramSocket.<init>(DatagramSocket.java:78)
09-01 08:24:01.989: W/System.err(1720): at
soft.b.peopleassist.broadcast.run(broadcast.java:65)
09-01 08:24:01.989: W/System.err(1720): Caused by:
libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
09-01 08:24:01.999: W/System.err(1720): at
libcore.io.Posix.socket(Native Method)
09-01 08:24:01.999: W/System.err(1720): at
libcore.io.BlockGuardOs.socket(BlockGuardOs.java:169)
09-01 08:24:01.999: W/System.err(1720): at
libcore.io.IoBridge.socket(IoBridge.java:558)
09-01 08:24:02.009: W/System.err(1720): ... 4 more
09-01 08:24:02.149: W/dalvikvm(1720): threadid=11: thread exiting with
uncaught exception (group=0x409961f8)
09-01 08:24:02.149: E/AndroidRuntime(1720): FATAL EXCEPTION: Thread-114
09-01 08:24:02.149: E/AndroidRuntime(1720): java.lang.NullPointerException
09-01 08:24:02.149: E/AndroidRuntime(1720): at
soft.b.peopleassist.broadcast.run(broadcast.java:92)
09-01 08:24:03.329: W/IInputConnectionWrapper(1720): showStatusIcon on
inactive InputConnection
Rails - Is .first guaranteed to be the first created, or just the first fetched?
Rails - Is .first guaranteed to be the first created, or just the first
fetched?
Let's assume I have many User records - if I call User.first is that
guaranteed to be the first user that existed in the database or should I
sort by created_at to make sure that the ordering is by created_at? Please
note that I am using mongoid and not ActiveRecord.
fetched?
Let's assume I have many User records - if I call User.first is that
guaranteed to be the first user that existed in the database or should I
sort by created_at to make sure that the ordering is by created_at? Please
note that I am using mongoid and not ActiveRecord.
Copy ogg from raw to SD card, need a helping hand
Copy ogg from raw to SD card, need a helping hand
I need some help. I've made an app that lets you play a list of
notification tones, and also copy a selected tone to SD (on context_menu).
Only thing is it's not doing that last part, mainly because I'm not sure
what to use to get the actual filename of the relevant ogg file for the
saveas method. At the moment it just says "filename". Also I think my path
and baseDir for external storage may be a bit skeewiff.
Can anyone here just give me a clue how I could could go about this? Or
even better show me what code to use?
Here's the main activity, there's also a Sound and soundAdapter class but
don't really see the need to post them too.
public class MainActivity extends ListActivity {
private ArrayList<Sound> mSounds = null;
private SoundAdapter mAdapter = null;
static MediaPlayer mMediaPlayer = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerForContextMenu(getListView());
this.getListView().setSelector(R.drawable.selector);
//create a simple list
mSounds = new ArrayList<Sound>();
Sound s = new Sound();
s.setDescription("Orbis");
s.setSoundResourceId(R.raw.orbis);
mSounds.add(s);
s = new Sound();
s.setDescription("Orion");
s.setSoundResourceId(R.raw.orion);
mSounds.add(s);
s = new Sound();
s.setDescription("Zinger");
s.setSoundResourceId(R.raw.zinger);
mSounds.add(s);
mAdapter = new SoundAdapter(this, R.layout.list_row, mSounds);
setListAdapter(mAdapter);
}
@Override
public void onListItemClick(ListView parent, View v, int position, long id){
Sound s = (Sound) mSounds.get(position);
MediaPlayer mp = MediaPlayer.create(this, s.getSoundResourceId());
mp.start();
}@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
public boolean saveas(int mSounds, String fName){
byte[] buffer=null;
InputStream fIn =
getBaseContext().getResources().openRawResource(mSounds);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path= "/sdcard/notifications/";
String filename=fName+".ogg";
String baseDir =
Environment.getExternalStorageDirectory().getAbsolutePath();
String completePath = baseDir + File.separator + "music" +
File.separator + "halon" + File.separator + filename;
boolean exists = (new File(completePath)).exists();
if (!exists){new File(completePath).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(completePath);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(completePath))));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()),
values);
return true;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)
item.getMenuInfo();
Sound sound = (Sound) getListAdapter().getItem(info.position);
int length = mSounds.size(); // get the length of mSounds object
String[] names = new String[length]; // creates a fixed array with
strings
for(int i = 0; i < length; i++) {
// add sound name to string array
names[i] = mSounds.get(i).getDescription(); // returns the string
name
}
switch(item.getItemId()) {
case R.id.copytosd:
Toast.makeText(this, "Applying " +
getResources().getString(R.string.copy) +
" for " + names[(int)info.id],
Toast.LENGTH_SHORT).show();
saveas(sound.getSoundResourceId(),"filename");
return true;
default:
return super.onContextItemSelected(item);
}
}}
I need some help. I've made an app that lets you play a list of
notification tones, and also copy a selected tone to SD (on context_menu).
Only thing is it's not doing that last part, mainly because I'm not sure
what to use to get the actual filename of the relevant ogg file for the
saveas method. At the moment it just says "filename". Also I think my path
and baseDir for external storage may be a bit skeewiff.
Can anyone here just give me a clue how I could could go about this? Or
even better show me what code to use?
Here's the main activity, there's also a Sound and soundAdapter class but
don't really see the need to post them too.
public class MainActivity extends ListActivity {
private ArrayList<Sound> mSounds = null;
private SoundAdapter mAdapter = null;
static MediaPlayer mMediaPlayer = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerForContextMenu(getListView());
this.getListView().setSelector(R.drawable.selector);
//create a simple list
mSounds = new ArrayList<Sound>();
Sound s = new Sound();
s.setDescription("Orbis");
s.setSoundResourceId(R.raw.orbis);
mSounds.add(s);
s = new Sound();
s.setDescription("Orion");
s.setSoundResourceId(R.raw.orion);
mSounds.add(s);
s = new Sound();
s.setDescription("Zinger");
s.setSoundResourceId(R.raw.zinger);
mSounds.add(s);
mAdapter = new SoundAdapter(this, R.layout.list_row, mSounds);
setListAdapter(mAdapter);
}
@Override
public void onListItemClick(ListView parent, View v, int position, long id){
Sound s = (Sound) mSounds.get(position);
MediaPlayer mp = MediaPlayer.create(this, s.getSoundResourceId());
mp.start();
}@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
public boolean saveas(int mSounds, String fName){
byte[] buffer=null;
InputStream fIn =
getBaseContext().getResources().openRawResource(mSounds);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path= "/sdcard/notifications/";
String filename=fName+".ogg";
String baseDir =
Environment.getExternalStorageDirectory().getAbsolutePath();
String completePath = baseDir + File.separator + "music" +
File.separator + "halon" + File.separator + filename;
boolean exists = (new File(completePath)).exists();
if (!exists){new File(completePath).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(completePath);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(completePath))));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()),
values);
return true;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)
item.getMenuInfo();
Sound sound = (Sound) getListAdapter().getItem(info.position);
int length = mSounds.size(); // get the length of mSounds object
String[] names = new String[length]; // creates a fixed array with
strings
for(int i = 0; i < length; i++) {
// add sound name to string array
names[i] = mSounds.get(i).getDescription(); // returns the string
name
}
switch(item.getItemId()) {
case R.id.copytosd:
Toast.makeText(this, "Applying " +
getResources().getString(R.string.copy) +
" for " + names[(int)info.id],
Toast.LENGTH_SHORT).show();
saveas(sound.getSoundResourceId(),"filename");
return true;
default:
return super.onContextItemSelected(item);
}
}}
What's the deal with MSVCR DLL?
What's the deal with MSVCR DLL?
What is it for ?
Why are their various versions of it ? What are the available versions and
what each of them match what ?
Why it seems to cause licence problems ? E.G : I some tools such as py2exe
can't bundle them but you still need them to run the resulting exe.
How to solve that if you want to distribute a software for Windows :
technically : how to make sure the user has one ? If not how to provide
one ? For all version of Windows.
legally : does it work the same for free software ? For profit software ?
Is there something specific to do ?
What is it for ?
Why are their various versions of it ? What are the available versions and
what each of them match what ?
Why it seems to cause licence problems ? E.G : I some tools such as py2exe
can't bundle them but you still need them to run the resulting exe.
How to solve that if you want to distribute a software for Windows :
technically : how to make sure the user has one ? If not how to provide
one ? For all version of Windows.
legally : does it work the same for free software ? For profit software ?
Is there something specific to do ?
Is there any standard for naming controllers and partial files with AngularJS?
Is there any standard for naming controllers and partial files with
AngularJS?
I have been using the following:
file /content/app/admin/controllers/content-controller.js
angular.module('admin').controller('AdminContentController',
file /content/app/home/partials/overviewItem.html
I copied the idea of a hyphen in the name of the controller but now I am
not sure if it is needed. I'd like some suggestions maybe it's better to
just call the file content.js?
AngularJS?
I have been using the following:
file /content/app/admin/controllers/content-controller.js
angular.module('admin').controller('AdminContentController',
file /content/app/home/partials/overviewItem.html
I copied the idea of a hyphen in the name of the controller but now I am
not sure if it is needed. I'd like some suggestions maybe it's better to
just call the file content.js?
Friday, 30 August 2013
PHP Excel Memory Limit of 2GB Exhausted reading a 286KB file
PHP Excel Memory Limit of 2GB Exhausted reading a 286KB file
My code is very simple test code:
$Reader = new SpreadsheetReader($_path_to_files . 'ABC.xls');
$i = 0;
foreach ($Reader as $Row)
{ $i++;
print_r($Row);
if($i>10) break;
}
And it is only to print 10 rows. And that is taking 2 Gigabytes of memory?
The error is occuring at line 253 in excel_reader2.php
Inside class OLERead, inside function read($sFilenName)
Here is the code causing my exhaustion:
if ($this->numExtensionBlocks != 0) {
$bbdBlocks = (BIG_BLOCK_SIZE - BIG_BLOCK_DEPOT_BLOCKS_POS)/4;
}
for ($i = 0; $i < $bbdBlocks; $i++) { // LINE 253
$bigBlockDepotBlocks[$i] = GetInt4d($this->data, $pos);
$pos += 4;
}
My code is very simple test code:
$Reader = new SpreadsheetReader($_path_to_files . 'ABC.xls');
$i = 0;
foreach ($Reader as $Row)
{ $i++;
print_r($Row);
if($i>10) break;
}
And it is only to print 10 rows. And that is taking 2 Gigabytes of memory?
The error is occuring at line 253 in excel_reader2.php
Inside class OLERead, inside function read($sFilenName)
Here is the code causing my exhaustion:
if ($this->numExtensionBlocks != 0) {
$bbdBlocks = (BIG_BLOCK_SIZE - BIG_BLOCK_DEPOT_BLOCKS_POS)/4;
}
for ($i = 0; $i < $bbdBlocks; $i++) { // LINE 253
$bigBlockDepotBlocks[$i] = GetInt4d($this->data, $pos);
$pos += 4;
}
Thursday, 29 August 2013
Passing order-dependent array into ActiveRecord's find() method
Passing order-dependent array into ActiveRecord's find() method
Simple statement of the problem:
The ActiveRecord documentation shows that you can pass several values into
the object find() method, as follows:
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
My issue is that the objects returned are insensitive to the order of the
values you pass in.
For instance, Person.find(1, 2, 6) returns exactly the same thing as
Person.find(6, 1, 2).
Is there any way to make this kind of search order sensitive?
It feels like there should be a way to pass in an array of id and get an
array of Person objects back in the same order...
Broader context, for those interested in reading on:
Really what I'm looking to do more generally, is find the "most viewed"
Person objects for a given time period.
Here's what I've got:
@most_viewed = View.where('created_at < ?', Time.now -
1.week).group(:person_id).order('count_person_id
desc').count('person_id').keys
This returns an (ordered!) array of id values for Person objects, in
descending order of number of Views each Person has received in the last
week.
My thinking was, if I could pass this array of ids into the Person.find
method, then I'm home free! But maybe there's another way entirely to do
it more easily. I'm open to all thoughts.
Thanks!
Simple statement of the problem:
The ActiveRecord documentation shows that you can pass several values into
the object find() method, as follows:
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
My issue is that the objects returned are insensitive to the order of the
values you pass in.
For instance, Person.find(1, 2, 6) returns exactly the same thing as
Person.find(6, 1, 2).
Is there any way to make this kind of search order sensitive?
It feels like there should be a way to pass in an array of id and get an
array of Person objects back in the same order...
Broader context, for those interested in reading on:
Really what I'm looking to do more generally, is find the "most viewed"
Person objects for a given time period.
Here's what I've got:
@most_viewed = View.where('created_at < ?', Time.now -
1.week).group(:person_id).order('count_person_id
desc').count('person_id').keys
This returns an (ordered!) array of id values for Person objects, in
descending order of number of Views each Person has received in the last
week.
My thinking was, if I could pass this array of ids into the Person.find
method, then I'm home free! But maybe there's another way entirely to do
it more easily. I'm open to all thoughts.
Thanks!
Rails select helper, prompt: 'Select' is hidden after other option is selected
Rails select helper, prompt: 'Select' is hidden after other option is
selected
I have a select tag with prompt: 'Select' option. It generates this option
<option value="" style="display: none;">Select</option>
When any other option is chosen, this is automatically hidden. Why the
style is hidden? I would want to get back to the original Select state
after selecting any other options. What am i doing wrong? If the style is
not hidden, my problem is solved, how to get over it?
selected
I have a select tag with prompt: 'Select' option. It generates this option
<option value="" style="display: none;">Select</option>
When any other option is chosen, this is automatically hidden. Why the
style is hidden? I would want to get back to the original Select state
after selecting any other options. What am i doing wrong? If the style is
not hidden, my problem is solved, how to get over it?
Wednesday, 28 August 2013
NuGet: Difference in behavior between Update-Package and nuget.exe update?
NuGet: Difference in behavior between Update-Package and nuget.exe update?
I'm using NuGet to create a 'web framework' package containing code,
master pages, css, javascript, etc.
In an attempt to speed up the build / test process I'm running nuget.exe
update packages.config but I've noticed that it behaves differently than
the package manager console's Update-Package command.
nuget.exe update seems to leave the previous version of the package still
installed, resulting in multiple versions of the package installed
Update-Package actually uninstalls the package then reinstalls it, this is
cleaner but slower
My questions are:
1. Is there documentation about the difference / relationship between
these commands
2. Is the nuget.exe update behavior of installing multiple versions a bug?
3. Is there a better method for creating a package in one project and
updating it in another project in a fast & automated manner?
I'm using NuGet to create a 'web framework' package containing code,
master pages, css, javascript, etc.
In an attempt to speed up the build / test process I'm running nuget.exe
update packages.config but I've noticed that it behaves differently than
the package manager console's Update-Package command.
nuget.exe update seems to leave the previous version of the package still
installed, resulting in multiple versions of the package installed
Update-Package actually uninstalls the package then reinstalls it, this is
cleaner but slower
My questions are:
1. Is there documentation about the difference / relationship between
these commands
2. Is the nuget.exe update behavior of installing multiple versions a bug?
3. Is there a better method for creating a package in one project and
updating it in another project in a fast & automated manner?
NetBeans Android package support does not exist
NetBeans Android package support does not exist
I'm just starting with Android programming and learning from their
official site, but they use Eclipse and I use NetBeans. Anyway, I've
downloaded latest tools and APIs and support libs AND loaded
android-support-v4.jar into Libraries folder. Than I could finally import
that package and NavUtils object wasn't red anymore. Now, when I try to
compile and build the project, it says: package android.support.v4.app
does not exist, and also: cannot find symbol
NavUtils.navigateUpFromSameTask(this);. Has anyone had this problem too?
Thanks!
I'm just starting with Android programming and learning from their
official site, but they use Eclipse and I use NetBeans. Anyway, I've
downloaded latest tools and APIs and support libs AND loaded
android-support-v4.jar into Libraries folder. Than I could finally import
that package and NavUtils object wasn't red anymore. Now, when I try to
compile and build the project, it says: package android.support.v4.app
does not exist, and also: cannot find symbol
NavUtils.navigateUpFromSameTask(this);. Has anyone had this problem too?
Thanks!
Parsing multi line text into a CSV
Parsing multi line text into a CSV
pI have a question on parsing a log file into a CSV. The log contains
multiple paragraphs such as the following:/p precodeAB param1: [C of type
1, Dlt;Egt; of type 2, F of type 3] param2: blah param3: [blah blah]
/code/pre pEach of these paragraphs have no spaces between their lines,
but each paragraph is separated from the next paragraph by a blank line.
Essentially, I want to extract information regarding AC. So is there a way
I can parse this into a CSV that looks like the following:/p
precodeAB,C,,1 AB,D,E,2 AB,F,,3 /code/pre pAny ideas? Pearl, Python, SED?
I'm really stumped here, I've never had to parse multiple lines like this,
especially looping on AB like this./p
pI have a question on parsing a log file into a CSV. The log contains
multiple paragraphs such as the following:/p precodeAB param1: [C of type
1, Dlt;Egt; of type 2, F of type 3] param2: blah param3: [blah blah]
/code/pre pEach of these paragraphs have no spaces between their lines,
but each paragraph is separated from the next paragraph by a blank line.
Essentially, I want to extract information regarding AC. So is there a way
I can parse this into a CSV that looks like the following:/p
precodeAB,C,,1 AB,D,E,2 AB,F,,3 /code/pre pAny ideas? Pearl, Python, SED?
I'm really stumped here, I've never had to parse multiple lines like this,
especially looping on AB like this./p
Is there a program who lock switching, between programs?
Is there a program who lock switching, between programs?
When I have a program running like Windows Media Player. I want to lock
it, so I can't back go to the desktop and use other programs or switch to
other programs. Like full screen, no taskbar.
When I have a program running like Windows Media Player. I want to lock
it, so I can't back go to the desktop and use other programs or switch to
other programs. Like full screen, no taskbar.
subversion load fails with "no such revision"
subversion load fails with "no such revision"
I'm trying to learn how to migrate a Subversion repo, and am running into
an issue that doesn't make sense to me. I've used svndumpfilter to split
out a sub-project, and have removed some path prefixes. Several hundred
commits now import correctly, but then I'm getting the following error:
<<< Started new transaction, based on original revision 19190
* editing path : branches/features/DynamicSource ... done.
* editing path : branches/features/DynamicSource/src/build.properties
... done.
* editing path :
branches/features/DynamicSource/src/client/default.htm ...done.
* editing path :
branches/features/DynamicSource/src/client/js/AdHocController.js ...
done.
* editing path :
branches/features/DynamicSource/src/client/js/Report.js ... done.
svnadmin: E160006: No such revision 19098
* adding path :
branches/features/DynamicSource/src/client/js/Enums.js ...
OK, so I go into the dump file to look at revisions 19190 and 19098. First
of all, revision 19098 does exist in the dump file and was imported
without a problem. Revision 19190 is a merge. Within 19190, here's that
last file's info, which seems to be causing the issue:
Node-copyfrom-rev: 19100
Node-copyfrom-path: trunk/src/client/js/Enums.js
Text-copy-source-md5: 2db7f8d9c0ba4750d88ce0722731aad6
Node-path: branches/features/DynamicSource/src/client/js/Enums.js
Node-action: add
Text-copy-source-sha1: 8f930509f8dbc17c5e82cd40aa5a76454d3d812c
Node-kind: file
Content-length: 0
Confusingly, revision 19100 does NOT exist in this filtered file. But the
error's not referring to 19100, it's referring to 19098!
What do I do to get this file to load?
Thanks!
I'm trying to learn how to migrate a Subversion repo, and am running into
an issue that doesn't make sense to me. I've used svndumpfilter to split
out a sub-project, and have removed some path prefixes. Several hundred
commits now import correctly, but then I'm getting the following error:
<<< Started new transaction, based on original revision 19190
* editing path : branches/features/DynamicSource ... done.
* editing path : branches/features/DynamicSource/src/build.properties
... done.
* editing path :
branches/features/DynamicSource/src/client/default.htm ...done.
* editing path :
branches/features/DynamicSource/src/client/js/AdHocController.js ...
done.
* editing path :
branches/features/DynamicSource/src/client/js/Report.js ... done.
svnadmin: E160006: No such revision 19098
* adding path :
branches/features/DynamicSource/src/client/js/Enums.js ...
OK, so I go into the dump file to look at revisions 19190 and 19098. First
of all, revision 19098 does exist in the dump file and was imported
without a problem. Revision 19190 is a merge. Within 19190, here's that
last file's info, which seems to be causing the issue:
Node-copyfrom-rev: 19100
Node-copyfrom-path: trunk/src/client/js/Enums.js
Text-copy-source-md5: 2db7f8d9c0ba4750d88ce0722731aad6
Node-path: branches/features/DynamicSource/src/client/js/Enums.js
Node-action: add
Text-copy-source-sha1: 8f930509f8dbc17c5e82cd40aa5a76454d3d812c
Node-kind: file
Content-length: 0
Confusingly, revision 19100 does NOT exist in this filtered file. But the
error's not referring to 19100, it's referring to 19098!
What do I do to get this file to load?
Thanks!
Why can't I save files to my iOS apps /Documents directory?
Why can't I save files to my iOS apps /Documents directory?
I am writing an app that can access the iOS root system, the user should
be able to save files to his document directory. I am using this code to
save the file to the document directory.
For Text:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:@"%@/%@",
documentsDirectory, [self.filePath lastPathComponent]]
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
For other files:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:@"%@/%@",
documentsDirectory,[self.filePath lastPathComponent]]
atomically:YES];
My problem is I can save .txt files, but not other files, If I save for
example .plist files with the save text methods, the contact is replaced
by the directory path of the file. When I save a picture, or any other
file it isn't readable. Is there a good method to save files without
destroying them?
--David
I am writing an app that can access the iOS root system, the user should
be able to save files to his document directory. I am using this code to
save the file to the document directory.
For Text:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:@"%@/%@",
documentsDirectory, [self.filePath lastPathComponent]]
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
For other files:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:@"%@/%@",
documentsDirectory,[self.filePath lastPathComponent]]
atomically:YES];
My problem is I can save .txt files, but not other files, If I save for
example .plist files with the save text methods, the contact is replaced
by the directory path of the file. When I save a picture, or any other
file it isn't readable. Is there a good method to save files without
destroying them?
--David
Printing PDF/Doc/Docx from MAC OS X application?
Printing PDF/Doc/Docx from MAC OS X application?
Is there any way to print .doc, .docx, .pdf files without opening native
application in cocoa,
Is there any way to invoke NSPrintPanel from my application which will
probable invoke print
dialog with given file.
I am new to the COCOA programming, any help will by highly appreciable.
Is there any way to print .doc, .docx, .pdf files without opening native
application in cocoa,
Is there any way to invoke NSPrintPanel from my application which will
probable invoke print
dialog with given file.
I am new to the COCOA programming, any help will by highly appreciable.
Foreach two array
Foreach two array
I was playing around with some code that I got here and what this code
does is auto generate new input for User ID and Location once the settings
is saved instead of having all input field already available (20 the
least). The code below output User ID, User ID and so on then Location
location and so on. What I am having problem is how to make it output User
ID, Location then User Id, Location... I know that it is only possible by
by combining the them in one foreach (not sure if that is really the
case).
public function form( $instance ) {
$user_id = isset ( $instance['user_id'] ) ? $instance['user_id'] :
array();
$user_id_num = count( $user_id );
$user_id[ $user_id_num + 1 ] = '';
$user_id_html = array();
$user_id_counter = 0;
foreach ( $user_id as $name => $value )
{
$user_id_html[] = sprintf(
'User ID<br/><input type="text" name="%1$s[%2$s]" value="%3$s"
class="widefat">',
$this->get_field_name( 'user_id' ),
$user_id_counter,
esc_attr( $value )
);
$user_id_counter += 1;
}
$user_loc = isset ( $instance['user_loc'] ) ? $instance['user_loc'] :
array();
$user_loc_num = count( $user_loc );
$user_loc[ $user_loc_num + 1 ] = '';
$user_loc_html = array();
$user_loc_counter = 0;
foreach ( $user_loc as $name => $value )
{
$user_loc_html[] = sprintf(
'Location<br/> <input type="text" name="%1$s[%2$s]"
value="%3$s" class="widefat">',
$this->get_field_name( 'user_loc' ),
$user_loc_counter,
esc_attr( $value )
);
$user_loc_counter += 1;
}
Now my question is.. How will I combine this code so that the arrays
doesn't work independently so when I enter new User ID and did not enter
Location, It will auto generate new input field for new User ID and
Location. Sorry Newbie here. :D
I was playing around with some code that I got here and what this code
does is auto generate new input for User ID and Location once the settings
is saved instead of having all input field already available (20 the
least). The code below output User ID, User ID and so on then Location
location and so on. What I am having problem is how to make it output User
ID, Location then User Id, Location... I know that it is only possible by
by combining the them in one foreach (not sure if that is really the
case).
public function form( $instance ) {
$user_id = isset ( $instance['user_id'] ) ? $instance['user_id'] :
array();
$user_id_num = count( $user_id );
$user_id[ $user_id_num + 1 ] = '';
$user_id_html = array();
$user_id_counter = 0;
foreach ( $user_id as $name => $value )
{
$user_id_html[] = sprintf(
'User ID<br/><input type="text" name="%1$s[%2$s]" value="%3$s"
class="widefat">',
$this->get_field_name( 'user_id' ),
$user_id_counter,
esc_attr( $value )
);
$user_id_counter += 1;
}
$user_loc = isset ( $instance['user_loc'] ) ? $instance['user_loc'] :
array();
$user_loc_num = count( $user_loc );
$user_loc[ $user_loc_num + 1 ] = '';
$user_loc_html = array();
$user_loc_counter = 0;
foreach ( $user_loc as $name => $value )
{
$user_loc_html[] = sprintf(
'Location<br/> <input type="text" name="%1$s[%2$s]"
value="%3$s" class="widefat">',
$this->get_field_name( 'user_loc' ),
$user_loc_counter,
esc_attr( $value )
);
$user_loc_counter += 1;
}
Now my question is.. How will I combine this code so that the arrays
doesn't work independently so when I enter new User ID and did not enter
Location, It will auto generate new input field for new User ID and
Location. Sorry Newbie here. :D
Tuesday, 27 August 2013
Why writing to a FILE stream return random number?
Why writing to a FILE stream return random number?
I have the following code to open a buffer in the memory and write some
data to it:
int main() {
char buf[1000] = {0};
FILE * os = fmemopen(buf, 1000, "w");
fprintf(os, "%d", 100);
fclose(os);
printf("%d\n", buf);
return 0;
}
The output is some random numbers such as : 895734416 or a negative
number... why is this happening?
I have the following code to open a buffer in the memory and write some
data to it:
int main() {
char buf[1000] = {0};
FILE * os = fmemopen(buf, 1000, "w");
fprintf(os, "%d", 100);
fclose(os);
printf("%d\n", buf);
return 0;
}
The output is some random numbers such as : 895734416 or a negative
number... why is this happening?
SwingWorker method process() shows error
SwingWorker method process() shows error
I am trying to learn SwingWorker but encountered the following error . I
don't know how to solve this problem. Error is shown in the comment part
of the code. package learnswingworker;
import java.awt.List;
import java.util.ArrayList;
import javax.swing.SwingWorker;
public class Try extends SwingWorker<ArrayList<Integer>, Integer>{
@Override
protected ArrayList<Integer> doInBackground() throws Exception {
ArrayList<Integer> primeNumbers = new ArrayList<Integer>();
Integer i=4;
boolean divisibleYet = false;
while(true){
for(Integer k=2;k<=(i/2);k++){
if(i%k==0){
divisibleYet=true;
}
}
if(!divisibleYet){
publish(i);
}
i++;
divisibleYet=false;
}
}
@Override // Shows ERROR ::: Method does not Override or
Implement a method from a supertype.
protected void process(List<Integer> chunks){ // Shows ERROR :::
Type List does not take parameters.
}
}
I am trying to learn SwingWorker but encountered the following error . I
don't know how to solve this problem. Error is shown in the comment part
of the code. package learnswingworker;
import java.awt.List;
import java.util.ArrayList;
import javax.swing.SwingWorker;
public class Try extends SwingWorker<ArrayList<Integer>, Integer>{
@Override
protected ArrayList<Integer> doInBackground() throws Exception {
ArrayList<Integer> primeNumbers = new ArrayList<Integer>();
Integer i=4;
boolean divisibleYet = false;
while(true){
for(Integer k=2;k<=(i/2);k++){
if(i%k==0){
divisibleYet=true;
}
}
if(!divisibleYet){
publish(i);
}
i++;
divisibleYet=false;
}
}
@Override // Shows ERROR ::: Method does not Override or
Implement a method from a supertype.
protected void process(List<Integer> chunks){ // Shows ERROR :::
Type List does not take parameters.
}
}
mod_rewrite url with 2 params or more
mod_rewrite url with 2 params or more
URL: http://example.com/good_game/osmp/
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)(.*)$ /?service=$1&terminal=$2 [L,QSA]
i receive
Array ( [service] => good_game [terminal] => /osmp/ )
i need
Array ( [service] => good_game [terminal] => osmp )
and what RewriteRule i need for multiparams?
URL: http://example.com/good_game/osmp/
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)(.*)$ /?service=$1&terminal=$2 [L,QSA]
i receive
Array ( [service] => good_game [terminal] => /osmp/ )
i need
Array ( [service] => good_game [terminal] => osmp )
and what RewriteRule i need for multiparams?
Browser showing blank page for Primefaces
Browser showing blank page for Primefaces
I have a problem with primefaces-3.5.jar with eclipse 4.3
I am creating a web application using JSF with Prime faces as UI component
Library
My application shows no error at run-time and no error at Compile-time and
deployed successfully
But the problem is i cannot get the output in browser , the browser
showing empty page, whatever the component i added in that page is not
displayed.
And i configured everything correctly with hope
I added Primefaces-3.5.jar under \WEB-INF\lib directory
Configured the primefaces namespace as xmlns:p="http:\\primefaces.org\ui"
And i configured the url-pattern too for *.xhtml in web.xml
Login.xhtml
Output
Shows Like this
Any solution for this..
I have a problem with primefaces-3.5.jar with eclipse 4.3
I am creating a web application using JSF with Prime faces as UI component
Library
My application shows no error at run-time and no error at Compile-time and
deployed successfully
But the problem is i cannot get the output in browser , the browser
showing empty page, whatever the component i added in that page is not
displayed.
And i configured everything correctly with hope
I added Primefaces-3.5.jar under \WEB-INF\lib directory
Configured the primefaces namespace as xmlns:p="http:\\primefaces.org\ui"
And i configured the url-pattern too for *.xhtml in web.xml
Login.xhtml
Output
Shows Like this
Any solution for this..
openstreetmap with less details
openstreetmap with less details
Is it possible to speed up mapping with OSM by removing features and
details (minor roads, bus stops, etc) -- or is that somewhat irrelevant to
the tile download and rendering process.
aka, Are the SVG details added/removed on client or server side.
Further how are those 'church: invisible' type of instructions set
TIA
Is it possible to speed up mapping with OSM by removing features and
details (minor roads, bus stops, etc) -- or is that somewhat irrelevant to
the tile download and rendering process.
aka, Are the SVG details added/removed on client or server side.
Further how are those 'church: invisible' type of instructions set
TIA
Monday, 26 August 2013
Scrape multiple webpages with changing URL with Python
Scrape multiple webpages with changing URL with Python
I am scraping a website with a URL structure like this:
www.website.com/data?page=1
I would like to write a program that uses iteration to scrape data off all
of the pages, which start at 1 and end at various numbers, depending on
the data fields I select on the form.
I thought I could cut up the URL and use an iterator to increase that
page, but I can't concatenate a str and int object. Any advice?
I am scraping a website with a URL structure like this:
www.website.com/data?page=1
I would like to write a program that uses iteration to scrape data off all
of the pages, which start at 1 and end at various numbers, depending on
the data fields I select on the form.
I thought I could cut up the URL and use an iterator to increase that
page, but I can't concatenate a str and int object. Any advice?
Java function that accepts address and returns longitude and latitude coordinates
Java function that accepts address and returns longitude and latitude
coordinates
I am looking for a simple java function that can accept an address and
return the longitude and latitude coordinates for that address. Based on
my research this is what i found thus far:
I am abit unsure how to implements this. I am not sure what order i will
need to call the different methods.
E.g. would i have to do this? :
String address = 'Some Place, Venezuela';
Geocoder geo = new Geocoder();
String url = geo.encode(address);
String encodeUrl = geo.urlEncode(url);
GLatLng latLng = geo.decode(encodeUrl);
If there are others that you have used feel free to share it.
/*
*
*
==============================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a
copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
under
* the License.
*/
package org.wicketstuff.gmap.geocoder;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.StringTokenizer;
import org.wicketstuff.gmap.api.GLatLng;
/**
* Geocoder. See:
http://www.google.com/apis/maps/documentation/services.html#
Geocoding_Direct
*
* @author Thijs Vonk
*/
public class Geocoder implements Serializable
{
private static final long serialVersionUID = 1L;
// Constants
public static final String OUTPUT_CSV = "csv";
public static final String OUTPUT_XML = "xml";
public static final String OUTPUT_KML = "kml";
public static final String OUTPUT_JSON = "json";
private final String output = OUTPUT_CSV;
public Geocoder()
{
}
public GLatLng decode(String response) throws GeocoderException
{
StringTokenizer gLatLng = new StringTokenizer(response, ",");
String status = gLatLng.nextToken();
gLatLng.nextToken(); // skip precision
String latitude = gLatLng.nextToken();
String longitude = gLatLng.nextToken();
if (Integer.parseInt(status) != GeocoderException.G_GEO_SUCCESS)
{
throw new GeocoderException(Integer.parseInt(status));
}
return new GLatLng(Double.parseDouble(latitude),
Double.parseDouble(longitude));
}
/**
* builds the google geo-coding url
*
* @param address
* @return
*/
public String encode(final String address)
{
return "http://maps.google.com/maps/geo?q=" + urlEncode(address) +
"&output=" + output;
}
/**
* @param address
* @return
* @throws IOException
*/
public GLatLng geocode(final String address) throws IOException
{
InputStream is = invokeService(encode(address));
if (is != null)
{
try
{
String content =
org.apache.wicket.util.io.IOUtils.toString(is);
return decode(content);
}
finally
{
is.close();
}
}
return null;
}
/**
* fetches the url content
*
* @param address
* @return
* @throws IOException
*/
protected InputStream invokeService(final String address) throws
IOException
{
URL url = new URL(address);
return url.openStream();
}
/**
* url-encode a value
*
* @param value
* @return
*/
private String urlEncode(final String value)
{
try
{
return URLEncoder.encode(value, "UTF-8");
}
catch (UnsupportedEncodingException ex)
{
throw new RuntimeException(ex.getMessage());
}
}
}
coordinates
I am looking for a simple java function that can accept an address and
return the longitude and latitude coordinates for that address. Based on
my research this is what i found thus far:
I am abit unsure how to implements this. I am not sure what order i will
need to call the different methods.
E.g. would i have to do this? :
String address = 'Some Place, Venezuela';
Geocoder geo = new Geocoder();
String url = geo.encode(address);
String encodeUrl = geo.urlEncode(url);
GLatLng latLng = geo.decode(encodeUrl);
If there are others that you have used feel free to share it.
/*
*
*
==============================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a
copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
under
* the License.
*/
package org.wicketstuff.gmap.geocoder;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.StringTokenizer;
import org.wicketstuff.gmap.api.GLatLng;
/**
* Geocoder. See:
http://www.google.com/apis/maps/documentation/services.html#
Geocoding_Direct
*
* @author Thijs Vonk
*/
public class Geocoder implements Serializable
{
private static final long serialVersionUID = 1L;
// Constants
public static final String OUTPUT_CSV = "csv";
public static final String OUTPUT_XML = "xml";
public static final String OUTPUT_KML = "kml";
public static final String OUTPUT_JSON = "json";
private final String output = OUTPUT_CSV;
public Geocoder()
{
}
public GLatLng decode(String response) throws GeocoderException
{
StringTokenizer gLatLng = new StringTokenizer(response, ",");
String status = gLatLng.nextToken();
gLatLng.nextToken(); // skip precision
String latitude = gLatLng.nextToken();
String longitude = gLatLng.nextToken();
if (Integer.parseInt(status) != GeocoderException.G_GEO_SUCCESS)
{
throw new GeocoderException(Integer.parseInt(status));
}
return new GLatLng(Double.parseDouble(latitude),
Double.parseDouble(longitude));
}
/**
* builds the google geo-coding url
*
* @param address
* @return
*/
public String encode(final String address)
{
return "http://maps.google.com/maps/geo?q=" + urlEncode(address) +
"&output=" + output;
}
/**
* @param address
* @return
* @throws IOException
*/
public GLatLng geocode(final String address) throws IOException
{
InputStream is = invokeService(encode(address));
if (is != null)
{
try
{
String content =
org.apache.wicket.util.io.IOUtils.toString(is);
return decode(content);
}
finally
{
is.close();
}
}
return null;
}
/**
* fetches the url content
*
* @param address
* @return
* @throws IOException
*/
protected InputStream invokeService(final String address) throws
IOException
{
URL url = new URL(address);
return url.openStream();
}
/**
* url-encode a value
*
* @param value
* @return
*/
private String urlEncode(final String value)
{
try
{
return URLEncoder.encode(value, "UTF-8");
}
catch (UnsupportedEncodingException ex)
{
throw new RuntimeException(ex.getMessage());
}
}
}
How do I center my images in Facebox?
How do I center my images in Facebox?
I am using Facebox and the popups are centered for text but when I include
images they are not being centered on Safari and Chrome. On Firefox it's
fine.
What can I do to make it centered on Chrome and Safari?
This is how a popup with an image looks like for me:
<div id="example1" style="display:none;">
<a class="close" onclick="$.facebox.close();">
</a>
<img src="/images/ok.png" class="ok">
</div>
JQuery Trigger:
<a href="#example1" class="some_link" rel="facebox">View Example</a>
I am using Facebox and the popups are centered for text but when I include
images they are not being centered on Safari and Chrome. On Firefox it's
fine.
What can I do to make it centered on Chrome and Safari?
This is how a popup with an image looks like for me:
<div id="example1" style="display:none;">
<a class="close" onclick="$.facebox.close();">
</a>
<img src="/images/ok.png" class="ok">
</div>
JQuery Trigger:
<a href="#example1" class="some_link" rel="facebox">View Example</a>
Usage of a COUNT(DISTINCT field) with a GROUP BY clause in Django
Usage of a COUNT(DISTINCT field) with a GROUP BY clause in Django
I want to use a COUNT(DISTINCT field) with a GROUP BY clause in Django. As
I understand, the COUNT(DISTINCT... can only be achieved by using an extra
for the query set.
My simplified model is :
class Site(models.Model):
name = models.CharField(max_length=128, unique=True)
class Application(models.Model):
name = models.CharField(max_length=64)
version = models.CharField(max_length=13, db_index=True)
class User(models.Model):
name = models.CharField(max_length=64)
site = models.ForeignKey(Site, db_index=True)
class Device(models.Model):
imei = models.CharField(max_length=16, unique=True)
applications = models.ManyToManyField(Application, null=True,
db_index=True, through='ApplicationUsage')
user = models.ForeignKey(User, null=True, db_index=True)
class ApplicationUsage(models.Model):
activity = models.DateField(db_index=True)
application = models.ForeignKey(Application)
device = models.ForeignKey(Device)
My goal is to have a liste of Site objects with a count of distinct device
for each site given an application usage time period, something like
stats_site.name deviceCount
ALBI 32
AMPLEPUIS 42
...
I try this code :
qs =
models.Site.objects.filter(user__device__applicationusage__activity__range=[startDay,
endDay])\
.extra(select={'deviceCount' : 'COUNT(DISTINCT
`stats_device`.`id`)'})\
.values('name', 'deviceCount')\
The generated SQL is :
SELECT (COUNT(DISTINCT stats_device.id)) AS deviceCount, stats_site.name
FROM stats_site
INNER JOIN stats_user ON (stats_site.id = stats_user.site_id)
INNER JOIN stats_device ON (stats_user.id = stats_device.user_id)
INNER JOIN stats_applicationusage ON (stats_device.id =
stats_applicationusage.device_id)
WHERE stats_applicationusage.activity BETWEEN '2013-07-01' AND '2013-07-03'
And the result is obviously wrong since it lacks the GROUP BY clause,
which should be GROUP BY stats_site.name
The problem is: I don't know how to add the correct GROUP BY using the
annotate function or other.
Can you help me ? Thanks.
I want to use a COUNT(DISTINCT field) with a GROUP BY clause in Django. As
I understand, the COUNT(DISTINCT... can only be achieved by using an extra
for the query set.
My simplified model is :
class Site(models.Model):
name = models.CharField(max_length=128, unique=True)
class Application(models.Model):
name = models.CharField(max_length=64)
version = models.CharField(max_length=13, db_index=True)
class User(models.Model):
name = models.CharField(max_length=64)
site = models.ForeignKey(Site, db_index=True)
class Device(models.Model):
imei = models.CharField(max_length=16, unique=True)
applications = models.ManyToManyField(Application, null=True,
db_index=True, through='ApplicationUsage')
user = models.ForeignKey(User, null=True, db_index=True)
class ApplicationUsage(models.Model):
activity = models.DateField(db_index=True)
application = models.ForeignKey(Application)
device = models.ForeignKey(Device)
My goal is to have a liste of Site objects with a count of distinct device
for each site given an application usage time period, something like
stats_site.name deviceCount
ALBI 32
AMPLEPUIS 42
...
I try this code :
qs =
models.Site.objects.filter(user__device__applicationusage__activity__range=[startDay,
endDay])\
.extra(select={'deviceCount' : 'COUNT(DISTINCT
`stats_device`.`id`)'})\
.values('name', 'deviceCount')\
The generated SQL is :
SELECT (COUNT(DISTINCT stats_device.id)) AS deviceCount, stats_site.name
FROM stats_site
INNER JOIN stats_user ON (stats_site.id = stats_user.site_id)
INNER JOIN stats_device ON (stats_user.id = stats_device.user_id)
INNER JOIN stats_applicationusage ON (stats_device.id =
stats_applicationusage.device_id)
WHERE stats_applicationusage.activity BETWEEN '2013-07-01' AND '2013-07-03'
And the result is obviously wrong since it lacks the GROUP BY clause,
which should be GROUP BY stats_site.name
The problem is: I don't know how to add the correct GROUP BY using the
annotate function or other.
Can you help me ? Thanks.
Can't install Ubuntu one on Ubuntu 12.04.2
Can't install Ubuntu one on Ubuntu 12.04.2
I'm installing ubuntuone on Ubuntu 12.04.2. In the middle of installation
a message pops up saying that:
ubuntuone-control-panel-qt: Depends:python(<2.8) but 2.7.3-0ubuntu2 is to
be installed
And few other lines. My understanding is that I've to install
ubuntuone-control-panel-qt. And that in turns require installing
ubunutu-sso-client but that require removing softare-center, ubuntu-dektop
etc.
What should I do now?
Thanks
I'm installing ubuntuone on Ubuntu 12.04.2. In the middle of installation
a message pops up saying that:
ubuntuone-control-panel-qt: Depends:python(<2.8) but 2.7.3-0ubuntu2 is to
be installed
And few other lines. My understanding is that I've to install
ubuntuone-control-panel-qt. And that in turns require installing
ubunutu-sso-client but that require removing softare-center, ubuntu-dektop
etc.
What should I do now?
Thanks
Passing long long int with ARM GCC
Passing long long int with ARM GCC
I'm working in bare metal on the Raspberry Pi, and I have found that if I
try to pass an unsigned long long integer to my printf function, the value
is truncated, and replaced with garbage.
I'm trying to figure out why this is happening. I have confirmed that the
stack is setup on a good boundary (0x8000). This is written in C, so GCC
should handle pushing/poping to pass values to printf, so I don't think it
is a simple alignment problem.
Does the Raspberry Pi definitely use EABI (not OABI)? I'm currently using
arm-none-eabi-gcc as the compiler.
Any ideas?
Thanks
I'm working in bare metal on the Raspberry Pi, and I have found that if I
try to pass an unsigned long long integer to my printf function, the value
is truncated, and replaced with garbage.
I'm trying to figure out why this is happening. I have confirmed that the
stack is setup on a good boundary (0x8000). This is written in C, so GCC
should handle pushing/poping to pass values to printf, so I don't think it
is a simple alignment problem.
Does the Raspberry Pi definitely use EABI (not OABI)? I'm currently using
arm-none-eabi-gcc as the compiler.
Any ideas?
Thanks
Sunday, 25 August 2013
Elimate Unwanted Space After Image Link
Elimate Unwanted Space After Image Link
After I added links to two images at the bottom of this site :
http://bit.ly/12D6erM
Unwanted "space" occurred just below the images. I've tried searching for
it via Chrome's WebDev Tools but haven't had any luck finding which
property to change. How can I eliminate this space?
After I added links to two images at the bottom of this site :
http://bit.ly/12D6erM
Unwanted "space" occurred just below the images. I've tried searching for
it via Chrome's WebDev Tools but haven't had any luck finding which
property to change. How can I eliminate this space?
Should perl's File::Glob always be post-filtered through utf8::decode?
Should perl's File::Glob always be post-filtered through utf8::decode?
The output of the following minimal example shows that (on my linux
machine) File::Glob seems to have the unexpected side-effect of converting
a utf8 string to non-utf8:
#!/usr/bin/perl
use utf8;
use strict;
my $x = "påminnelser";
my $y = glob $x;
print "x=",utf8::is_utf8($x),"=\n";
print "y=",utf8::is_utf8($y),"=\n";
This is causing wrong behavior in my program. On linux, it looks like I
can fix it by applying utf8::decode() after File::Glob. Is this the right
way to fix this? Is this a bug in File::Glob? Will my fix produce correct
results on other systems such as Windows?
The output of the following minimal example shows that (on my linux
machine) File::Glob seems to have the unexpected side-effect of converting
a utf8 string to non-utf8:
#!/usr/bin/perl
use utf8;
use strict;
my $x = "påminnelser";
my $y = glob $x;
print "x=",utf8::is_utf8($x),"=\n";
print "y=",utf8::is_utf8($y),"=\n";
This is causing wrong behavior in my program. On linux, it looks like I
can fix it by applying utf8::decode() after File::Glob. Is this the right
way to fix this? Is this a bug in File::Glob? Will my fix produce correct
results on other systems such as Windows?
Parsing a string with NumberFormat
Parsing a string with NumberFormat
From the this java API
parse
public abstract Number parse(String source, ParsePosition parsePosition)
Returns a Long if possible (e.g., within the range [Long.MIN_VALUE,
Long.MAX_VALUE] and with no decimals), otherwise a Double. If IntegerOnly
is set, will stop at a decimal point (or equivalent; e.g., for rational
numbers "1 2/3", will stop after the 1). Does not throw an exception; if
no object can be parsed, index is unchanged!
(or equivalent; e.g., for rational numbers "1 2/3", will stop after the 1)
What are they talkng about? is it something possible at all parsing such a
String? However I have tried also with setParseIntegerOnly(false); and it
parses only 1. What did they mean with that statement that I must have
missed? Thanks in advance.
From the this java API
parse
public abstract Number parse(String source, ParsePosition parsePosition)
Returns a Long if possible (e.g., within the range [Long.MIN_VALUE,
Long.MAX_VALUE] and with no decimals), otherwise a Double. If IntegerOnly
is set, will stop at a decimal point (or equivalent; e.g., for rational
numbers "1 2/3", will stop after the 1). Does not throw an exception; if
no object can be parsed, index is unchanged!
(or equivalent; e.g., for rational numbers "1 2/3", will stop after the 1)
What are they talkng about? is it something possible at all parsing such a
String? However I have tried also with setParseIntegerOnly(false); and it
parses only 1. What did they mean with that statement that I must have
missed? Thanks in advance.
How to config CKEditor-4 inline editors?
How to config CKEditor-4 inline editors?
I have a standard installation (like samples):
<meta charset="utf-8"></meta>
<script src="../ckeditor.js"></script>
With HTML content with many <div contenteditable="true"> blocks. I need to
configure each editor by an external configX.js file,
<script>
CKEDITOR.on( 'instanceCreated', function( event ) {
var editor = event.editor, element = editor.element;
if ( element.is( 'h1', 'h2', 'h3' ) ) {
// WHERE PUT THIS ITEM?
customConfig: '/custom/ckconfigType1.js';
} else {
// WHERE PUT THIS ITEM?
customConfig: '/custom/ckconfigType2.js';
}
});
</script>
So, my problem is
How to do a customConfig in this context?
Where the "best complete documentation", about config menus
(editor.config.toolbarGroups) without online configuration-tool, where I
can understand how to put and remove menu itens with correct names?
I have a standard installation (like samples):
<meta charset="utf-8"></meta>
<script src="../ckeditor.js"></script>
With HTML content with many <div contenteditable="true"> blocks. I need to
configure each editor by an external configX.js file,
<script>
CKEDITOR.on( 'instanceCreated', function( event ) {
var editor = event.editor, element = editor.element;
if ( element.is( 'h1', 'h2', 'h3' ) ) {
// WHERE PUT THIS ITEM?
customConfig: '/custom/ckconfigType1.js';
} else {
// WHERE PUT THIS ITEM?
customConfig: '/custom/ckconfigType2.js';
}
});
</script>
So, my problem is
How to do a customConfig in this context?
Where the "best complete documentation", about config menus
(editor.config.toolbarGroups) without online configuration-tool, where I
can understand how to put and remove menu itens with correct names?
connect menustrip1 to database with entity framework in winform application
connect menustrip1 to database with entity framework in winform application
I have a form that you control your Menustrip the menu item with the name
of a movie I Now I want the database was mutilated movies Menu Submenu
(Action, Crime, Horror, etc.) I appreciate your help The database via
Entity Framework patch
I have a form that you control your Menustrip the menu item with the name
of a movie I Now I want the database was mutilated movies Menu Submenu
(Action, Crime, Horror, etc.) I appreciate your help The database via
Entity Framework patch
Saturday, 24 August 2013
Is a REST API the standard way of setting up server connectivity for an app?
Is a REST API the standard way of setting up server connectivity for an app?
I've never made an app before, and I'm new to back-end work as well-- I'm
learning both simultaneously. What I'm trying to figure out is whether a
REST API is the standard method of exchanging data with the server for
most apps in apps, or whether there's some other way I might not yet be
aware of.
I've never made an app before, and I'm new to back-end work as well-- I'm
learning both simultaneously. What I'm trying to figure out is whether a
REST API is the standard method of exchanging data with the server for
most apps in apps, or whether there's some other way I might not yet be
aware of.
How to choose what object to lock on in Java?
How to choose what object to lock on in Java?
I have read answers to similar questions about the correct ways to use
synchronized. However, they dont seem to explain why this issue occurred.
Even though I added synchronized to my getValue and setValue method, i
still get outputs like the following. Why does this happen?
output:
making doing get [new line] set
Code:
package src;
public class StackNode {
private Object value;
private StackNode next;
private final Object lock = new Object();
public StackNode() {
setValue(null);
setNext(null);
}
public StackNode(Object o) {
value = 0;
next = null;
}
public StackNode(StackNode node) {
value = node.getValue();
next = node.getNext();
}
public synchronized Object getValue() {
System.out.print(" Doing ");
System.out.println(" get ");
System.out.flush();
return value;
}
public synchronized void setValue(Object value) {
System.out.print(" making ");
System.out.println(" set ");
System.out.flush();
this.value = value;
}
public synchronized StackNode getNext() {
return next;
}
public synchronized void setNext(StackNode next) {
this.next = next;
}
}
@Test
public void getSetValueTest() throws InterruptedException{
node.setValue("bad");
Runnable setValue = new Runnable(){
@Override
public void run() {
node.setNext(new StackNode());
node.setValue("new");
}
};
Runnable getValue = new Runnable(){
@Override
public void run() {
Assert.assertEquals("new", node.getValue());
}
};
List<Thread> set = new ArrayList<Thread> ();
List<Thread> get = new ArrayList<Thread> ();
for (int i = 0; i < 30000; i++){
set.add( new Thread(setValue));
get.add(new Thread(getValue));
}
for (int i = 0; i < 30000; i++){
set.get(i).start();
get.get(i).start();
}
for (int i = 0; i < 30000; i++){
set.get(i).join();
get.get(i).join();
}
}
I have read answers to similar questions about the correct ways to use
synchronized. However, they dont seem to explain why this issue occurred.
Even though I added synchronized to my getValue and setValue method, i
still get outputs like the following. Why does this happen?
output:
making doing get [new line] set
Code:
package src;
public class StackNode {
private Object value;
private StackNode next;
private final Object lock = new Object();
public StackNode() {
setValue(null);
setNext(null);
}
public StackNode(Object o) {
value = 0;
next = null;
}
public StackNode(StackNode node) {
value = node.getValue();
next = node.getNext();
}
public synchronized Object getValue() {
System.out.print(" Doing ");
System.out.println(" get ");
System.out.flush();
return value;
}
public synchronized void setValue(Object value) {
System.out.print(" making ");
System.out.println(" set ");
System.out.flush();
this.value = value;
}
public synchronized StackNode getNext() {
return next;
}
public synchronized void setNext(StackNode next) {
this.next = next;
}
}
@Test
public void getSetValueTest() throws InterruptedException{
node.setValue("bad");
Runnable setValue = new Runnable(){
@Override
public void run() {
node.setNext(new StackNode());
node.setValue("new");
}
};
Runnable getValue = new Runnable(){
@Override
public void run() {
Assert.assertEquals("new", node.getValue());
}
};
List<Thread> set = new ArrayList<Thread> ();
List<Thread> get = new ArrayList<Thread> ();
for (int i = 0; i < 30000; i++){
set.add( new Thread(setValue));
get.add(new Thread(getValue));
}
for (int i = 0; i < 30000; i++){
set.get(i).start();
get.get(i).start();
}
for (int i = 0; i < 30000; i++){
set.get(i).join();
get.get(i).join();
}
}
Beamer: How to place graphics at the bottom of a frame
Beamer: How to place graphics at the bottom of a frame
I want to achieve that included graphics are always on the bottom of the
frame, so that their position isn't influenced by the length of the text
above.
I tried the figure enviroment without success and the \vfill also doesn't
give the wished success.
Here is some similar example source:
\frame{
\only<1-3>{Blablabla1}
\only<4>{Blablabla2}
\only<5>{Blablabla3}
\only<6>{Blablabla4}
\only<7>{Blablabla5}
\only<8>{Blablabla6}
\only<9>{Blablabla7}
\vfill
\visible<3->{%
\includegraphics<1-3>[width=\linewidth]{img/1.png}
\includegraphics<4>[width=\linewidth]{img/2.png}
\includegraphics<5>[width=\linewidth]{img/3.png}
\includegraphics<6>[width=\linewidth]{img/4.png}
\includegraphics<7>[width=\linewidth]{img/5.png}
\includegraphics<8>[width=\linewidth]{img/6.png}
\includegraphics<9>[width=\linewidth]{img/7.png}
\includegraphics<10>[width=\linewidth]{img/8.png}
}
}
I want to achieve that included graphics are always on the bottom of the
frame, so that their position isn't influenced by the length of the text
above.
I tried the figure enviroment without success and the \vfill also doesn't
give the wished success.
Here is some similar example source:
\frame{
\only<1-3>{Blablabla1}
\only<4>{Blablabla2}
\only<5>{Blablabla3}
\only<6>{Blablabla4}
\only<7>{Blablabla5}
\only<8>{Blablabla6}
\only<9>{Blablabla7}
\vfill
\visible<3->{%
\includegraphics<1-3>[width=\linewidth]{img/1.png}
\includegraphics<4>[width=\linewidth]{img/2.png}
\includegraphics<5>[width=\linewidth]{img/3.png}
\includegraphics<6>[width=\linewidth]{img/4.png}
\includegraphics<7>[width=\linewidth]{img/5.png}
\includegraphics<8>[width=\linewidth]{img/6.png}
\includegraphics<9>[width=\linewidth]{img/7.png}
\includegraphics<10>[width=\linewidth]{img/8.png}
}
}
How do I convert a delimited list to a multicolumn table in excel?
How do I convert a delimited list to a multicolumn table in excel?
I have a list like this:
Friut;Taste;Color;Other;Apple;Good;Red and Blue;1;Orange;Really
Good;Orange;12
And I want to convert it by selecting every 4 delimitations and turning
them into rows like this:
Fruit Taste Color Other
Apple Good Red and G.1
Orange Really Go.Orange 12
How is this possible with Libreoffice (preferred), Openoffice, or Excel?
I have a list like this:
Friut;Taste;Color;Other;Apple;Good;Red and Blue;1;Orange;Really
Good;Orange;12
And I want to convert it by selecting every 4 delimitations and turning
them into rows like this:
Fruit Taste Color Other
Apple Good Red and G.1
Orange Really Go.Orange 12
How is this possible with Libreoffice (preferred), Openoffice, or Excel?
rotating the view for android x86 on VMWare
rotating the view for android x86 on VMWare
How to I rotate the view on android x86 installed in VMWare? Pressing
Ctrl+F12 rotated it so that the back and home buttons went to the left of
the screen, but now pressing Ctrl+F11 or ctrl+F12 only keep it in
landscape mode, with either the home button being towards the left or the
right of the screen. How do i bring it back to portrait mode, that is, the
home button at the bottom of the scree?
How to I rotate the view on android x86 installed in VMWare? Pressing
Ctrl+F12 rotated it so that the back and home buttons went to the left of
the screen, but now pressing Ctrl+F11 or ctrl+F12 only keep it in
landscape mode, with either the home button being towards the left or the
right of the screen. How do i bring it back to portrait mode, that is, the
home button at the bottom of the scree?
Reference to cells in another document
Reference to cells in another document
How can I include in the range of a VLOOKUP cells located in another
Google Docs Spreadsheet?
How can I include in the range of a VLOOKUP cells located in another
Google Docs Spreadsheet?
Friday, 23 August 2013
Undefined property error
Undefined property error
Hai i have installed cloud zoom model and its not working properly and its
giving error message like (Undefined property: stdClass::$cz_verion in
cloud_zoom_library() (line 38 of
/home/drupalpro/websites/tragigrupp.dev/profiles/commerce_kickstart/modules/contrib/cloud_zoom/cloud_zoom.module).
And i all so installed all related j query libraries in libraries folder.
and one more thing is i tried in localhost server its working properly but
not in my main server (both server having same drupal7 version and theme
).
Thank you .
Hai i have installed cloud zoom model and its not working properly and its
giving error message like (Undefined property: stdClass::$cz_verion in
cloud_zoom_library() (line 38 of
/home/drupalpro/websites/tragigrupp.dev/profiles/commerce_kickstart/modules/contrib/cloud_zoom/cloud_zoom.module).
And i all so installed all related j query libraries in libraries folder.
and one more thing is i tried in localhost server its working properly but
not in my main server (both server having same drupal7 version and theme
).
Thank you .
career in kernel device driver [on hold]
career in kernel device driver [on hold]
first of all let me tell abt me..i had completed engineering in
electronics and coomunication .i wish to pursue my career in kernel device
driver programming..for that i had startd sudying c and linux as
well....but now i am in great confusion...i think am not in the correct
route..
so as you guys are experienced in this field let me know what all things i
should study for that and also what is the present scope of the same..
it will be great if you show me where i can get the resources for the
above mentioned
waiting for your valuable guidance
first of all let me tell abt me..i had completed engineering in
electronics and coomunication .i wish to pursue my career in kernel device
driver programming..for that i had startd sudying c and linux as
well....but now i am in great confusion...i think am not in the correct
route..
so as you guys are experienced in this field let me know what all things i
should study for that and also what is the present scope of the same..
it will be great if you show me where i can get the resources for the
above mentioned
waiting for your valuable guidance
3X3 square by the circle, what is the value of pi?
3X3 square by the circle, what is the value of pi?
There are a circle and a square. to have the same area, we need to have
this shape.
The square is cut in $9$ squares, what will be the value of $\pi$ to have
$A=\pi*R²$ is this algebraique structure?
There are a circle and a square. to have the same area, we need to have
this shape.
The square is cut in $9$ squares, what will be the value of $\pi$ to have
$A=\pi*R²$ is this algebraique structure?
Batch converting straight quotes to smart quotes from MySQL database
Batch converting straight quotes to smart quotes from MySQL database
I have a MySQL table with about 250 blog entries, all using straight
quotes (" and ') instead of smart quotes (" " and ' '). I need to take
those entries and somehow do a batch find-and-replace to replace all
straight quotes with smart quotes. Problem is these fields also contain
HTML, so I need to ensure all quotes within <> tags are ignored.
I've exported the appropriate fields and opened up in Sublime Text
thinking I could do regex find-and-replace. It's there that I hit a wall,
though.
Suggestions?
I have a MySQL table with about 250 blog entries, all using straight
quotes (" and ') instead of smart quotes (" " and ' '). I need to take
those entries and somehow do a batch find-and-replace to replace all
straight quotes with smart quotes. Problem is these fields also contain
HTML, so I need to ensure all quotes within <> tags are ignored.
I've exported the appropriate fields and opened up in Sublime Text
thinking I could do regex find-and-replace. It's there that I hit a wall,
though.
Suggestions?
java.lang.ClassCastException: java.lang.StackOverflowError cannot be cast to java.lang.Exception
java.lang.ClassCastException: java.lang.StackOverflowError cannot be cast
to java.lang.Exception
Actually m facing the below mentioned error while executing my java program
Exception in thread "pool-1-thread-1" java.lang.ClassCastException:
java.lang.StackOverflowError cannot be cast to java.lang.Exception
Actually i have a java class called Test_A where it contains following
methods called Login() and Logout() and have a another java class called
Test_B where it contains method VerifyValidUser().
class Test_A {
Test_B b = new Test_B();
public void login()
{
driver.findElement(By.name("userName")).sendKeys(userName);
driver.findElement(By.name("password")).sendKeys(password);
driver.findElement(By.name("login")).click();
b.verifyLoginValidUser();
}
public void logout()
{
driver.findElement(By.linkText("SIGN-OFF")).click();
}
}
class Test_B {
Test_A a = new Test_A()
public void verifyLoginValidUser()
{
if(isElementPresent(By.linkText("SIGN-OFF")))
{
}
a.logout();
} }
So while executing the above code it throws me above metioned error message
Can anyone tel me the reason behind it
Thanks
to java.lang.Exception
Actually m facing the below mentioned error while executing my java program
Exception in thread "pool-1-thread-1" java.lang.ClassCastException:
java.lang.StackOverflowError cannot be cast to java.lang.Exception
Actually i have a java class called Test_A where it contains following
methods called Login() and Logout() and have a another java class called
Test_B where it contains method VerifyValidUser().
class Test_A {
Test_B b = new Test_B();
public void login()
{
driver.findElement(By.name("userName")).sendKeys(userName);
driver.findElement(By.name("password")).sendKeys(password);
driver.findElement(By.name("login")).click();
b.verifyLoginValidUser();
}
public void logout()
{
driver.findElement(By.linkText("SIGN-OFF")).click();
}
}
class Test_B {
Test_A a = new Test_A()
public void verifyLoginValidUser()
{
if(isElementPresent(By.linkText("SIGN-OFF")))
{
}
a.logout();
} }
So while executing the above code it throws me above metioned error message
Can anyone tel me the reason behind it
Thanks
Server running SVN 1.6, and client running SVN 1.7
Server running SVN 1.6, and client running SVN 1.7
I have a local server setup with SVN 1.6. If the client machine has SVN
1.7, will that be a problem?
p.s. This is with reference to Xcode, and iOS application development.
I have a local server setup with SVN 1.6. If the client machine has SVN
1.7, will that be a problem?
p.s. This is with reference to Xcode, and iOS application development.
Thursday, 22 August 2013
How can i write some text the diagram - Highcharts?
How can i write some text the diagram - Highcharts?
How can i write some text on the yellow part and this should be seen only
when i click on this part? http://jsfiddle.net/r6p7E/14/
mouseOut: function () { var serie = this.points;
$.each(serie, function (i, e) {
if (!this.selected) {
this.graphic.attr({
fill: '#242c4a'
});
}
else {
this.graphic.attr({
fill: '#fefe0f',
});
}
});
}`
How can i write some text on the yellow part and this should be seen only
when i click on this part? http://jsfiddle.net/r6p7E/14/
mouseOut: function () { var serie = this.points;
$.each(serie, function (i, e) {
if (!this.selected) {
this.graphic.attr({
fill: '#242c4a'
});
}
else {
this.graphic.attr({
fill: '#fefe0f',
});
}
});
}`
Learning Javascript, why do these two functions behave differently?
Learning Javascript, why do these two functions behave differently?
Learning Javascript and can't figure out why these two functions are
different. I saw this example (I added names to the functions):
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
setTimeout((function myBind(msg) {
return function myAlert() { alert(msg); }
})(txt[i]), 1000);
}​
I see that a function that calls alert is being returned. So I thought,
why not just return it directly:
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
setTimeout( function() { alert(txt[i]);} ,1000);
}​
This ends up alerting 'undefined.' I understand that it's because it's
trying to access txt[3] because after one second the loop has finished and
i has been set to 3, but I don't understand how the original setup avoided
this problem.
Learning Javascript and can't figure out why these two functions are
different. I saw this example (I added names to the functions):
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
setTimeout((function myBind(msg) {
return function myAlert() { alert(msg); }
})(txt[i]), 1000);
}​
I see that a function that calls alert is being returned. So I thought,
why not just return it directly:
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
setTimeout( function() { alert(txt[i]);} ,1000);
}​
This ends up alerting 'undefined.' I understand that it's because it's
trying to access txt[3] because after one second the loop has finished and
i has been set to 3, but I don't understand how the original setup avoided
this problem.
Why are my 3d shapes in OpenGL/GLFW C++ missing faces
Why are my 3d shapes in OpenGL/GLFW C++ missing faces
So when i make a 3d triangle it just misses faces as shown below (with
quad) any shape i try misses faces and you can just see straight through,
(mind this is my first time using both OpenGL and GLFW)
The shape code is from a tutorial as ive tryed many shape codes to see if
that was the issue and it seems it is not.
#include <glfw3.h>
#include <stdio.h>
#include <iostream>
using namespace std;
/* Begin Void prototyping */
void error_callback(int error, const char* description);
static void key_callback(GLFWwindow* window, int key, int scancode, int
action, int mods);
int main(void)
{
GLFWwindow* window;
/* Initializes error call-backs */
glfwSetErrorCallback(error_callback);
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); //
fullscreen glfwGetPrimaryMonitor() (first NULL)
if (!window)
{
glfwTerminate();
return -1;
}
/* Makes OpenGL context current */
glfwMakeContextCurrent(window);
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Receives input events */
glfwSetKeyCallback(window, key_callback);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
float ratio;
int width, height;
glfwGetFramebufferSize(window, &width, &height);
ratio = width / (float) height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);
glBegin(GL_TRIANGLES); // Start Drawing A
Triangle
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle
(Front)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of
Triangle (Front)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of
Triangle (Front)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle
(Right)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of
Triangle (Right)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of
Triangle (Right)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle
(Back)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of
Triangle (Back)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of
Triangle (Back)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle
(Left)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of
Triangle (Left)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of
Triangle (Left)
glEnd(); // Done Drawing
The Pyramid
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
/*
Calls back the program if a GLFW function fail and logs it
*/
void error_callback(int error, const char* description)
{
fputs(description, stderr);
}
/* Gives keys events */
static void key_callback(GLFWwindow* window, int key, int scancode, int
action, int mods)
{
switch(key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_W:
cout << "W works!!!" << endl;
break;
case GLFW_KEY_A:
cout << "A works!!!" << endl;
break;
case GLFW_KEY_S:
cout << "S works!!!" << endl;
break;
case GLFW_KEY_D:
cout << "D works!!!" << endl;
break;
}
}
Ive been trying to fix it for hours i just dont know what too do now
Im using OpenGL 3+ with GLFW and C++
So when i make a 3d triangle it just misses faces as shown below (with
quad) any shape i try misses faces and you can just see straight through,
(mind this is my first time using both OpenGL and GLFW)
The shape code is from a tutorial as ive tryed many shape codes to see if
that was the issue and it seems it is not.
#include <glfw3.h>
#include <stdio.h>
#include <iostream>
using namespace std;
/* Begin Void prototyping */
void error_callback(int error, const char* description);
static void key_callback(GLFWwindow* window, int key, int scancode, int
action, int mods);
int main(void)
{
GLFWwindow* window;
/* Initializes error call-backs */
glfwSetErrorCallback(error_callback);
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); //
fullscreen glfwGetPrimaryMonitor() (first NULL)
if (!window)
{
glfwTerminate();
return -1;
}
/* Makes OpenGL context current */
glfwMakeContextCurrent(window);
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Receives input events */
glfwSetKeyCallback(window, key_callback);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
float ratio;
int width, height;
glfwGetFramebufferSize(window, &width, &height);
ratio = width / (float) height;
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);
glBegin(GL_TRIANGLES); // Start Drawing A
Triangle
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle
(Front)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of
Triangle (Front)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of
Triangle (Front)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle
(Right)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of
Triangle (Right)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of
Triangle (Right)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle
(Back)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of
Triangle (Back)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of
Triangle (Back)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle
(Left)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of
Triangle (Left)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of
Triangle (Left)
glEnd(); // Done Drawing
The Pyramid
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
/*
Calls back the program if a GLFW function fail and logs it
*/
void error_callback(int error, const char* description)
{
fputs(description, stderr);
}
/* Gives keys events */
static void key_callback(GLFWwindow* window, int key, int scancode, int
action, int mods)
{
switch(key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_W:
cout << "W works!!!" << endl;
break;
case GLFW_KEY_A:
cout << "A works!!!" << endl;
break;
case GLFW_KEY_S:
cout << "S works!!!" << endl;
break;
case GLFW_KEY_D:
cout << "D works!!!" << endl;
break;
}
}
Ive been trying to fix it for hours i just dont know what too do now
Im using OpenGL 3+ with GLFW and C++
IsValid(object value, ValidationContext validationContext) is not called
IsValid(object value, ValidationContext validationContext) is not called
I wrote a custom attribute:
public class VerifyOrderAttribute : RequiredAttribute {
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
if (DoesOrderExist((string)value))
return ValidationResult.Success;
ValidationResult vr = new ValidationResult("Order does not exist");
return vr;
//return base.IsValid(value, validationContext);
}
private bool DoesOrderExist(string sOrderSequence)
{
PullParts.PartProcessor o = new PullParts.PartProcessor();
bool result = o.CheckOrder(sOrderSequence);
return result;
}
}
I use VerifyOrder attribute with my property:
[Required(ErrorMessage= "Order number is required")]
[RegularExpression(@"\d{2}-\d{6}-\d{2}", ErrorMessage="Order number must
be in format XX-XXXXXX-XX")]
[VerifyOrder(ErrorMessage="Order number does not exist")]
public global::System.String OrderNumber
{
get
{
return _OrderNumber;
}
set
{
_OrderNumber = value;
}
}
private global::System.String _OrderNumber;
at my view, I called ValidationMessageFor():
<div >
<label class="span2" >*Order Number:</label>
@Html.TextBoxFor(x => x.Request.OrderNumber, new { @class = "span3" })
@Html.ValidationMessageFor(x => x.Request.OrderNumber)
</div>
it looks like ValidationMessageFor does not call IsValid() for my custom
attribute. I want my custom attribute VerifyOrder to work just like
Required attribute. What do I need to do?
thanks in advance.
I wrote a custom attribute:
public class VerifyOrderAttribute : RequiredAttribute {
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
if (DoesOrderExist((string)value))
return ValidationResult.Success;
ValidationResult vr = new ValidationResult("Order does not exist");
return vr;
//return base.IsValid(value, validationContext);
}
private bool DoesOrderExist(string sOrderSequence)
{
PullParts.PartProcessor o = new PullParts.PartProcessor();
bool result = o.CheckOrder(sOrderSequence);
return result;
}
}
I use VerifyOrder attribute with my property:
[Required(ErrorMessage= "Order number is required")]
[RegularExpression(@"\d{2}-\d{6}-\d{2}", ErrorMessage="Order number must
be in format XX-XXXXXX-XX")]
[VerifyOrder(ErrorMessage="Order number does not exist")]
public global::System.String OrderNumber
{
get
{
return _OrderNumber;
}
set
{
_OrderNumber = value;
}
}
private global::System.String _OrderNumber;
at my view, I called ValidationMessageFor():
<div >
<label class="span2" >*Order Number:</label>
@Html.TextBoxFor(x => x.Request.OrderNumber, new { @class = "span3" })
@Html.ValidationMessageFor(x => x.Request.OrderNumber)
</div>
it looks like ValidationMessageFor does not call IsValid() for my custom
attribute. I want my custom attribute VerifyOrder to work just like
Required attribute. What do I need to do?
thanks in advance.
An exception occurred when I tried to add more columns
An exception occurred when I tried to add more columns
I'm making a GUI project, using MVC design pattern. This program contains
JTable component, for which I've created a class MyTableModel which
extends AbstractTableModel. As you can see below in MyModelClass, I have
two methods addColumn & removeColumn , which have normally add/remove
columns from table, until, I have come to the point, when I have to add 3
initial columns with 8 combinations into my constructor, and then try
add/remove columns. Here you can see screenshot of program.
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: 3
at mvc.TTableModel.getValueAt(TTableModel.java:79)
at mvc.TTableModel.getColumnClass(TTableModel.java:84)
at javax.swing.JTable.getColumnClass(JTable.java:2697)
at javax.swing.JTable.getCellRenderer(JTable.java:5682)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2113)
at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2016)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1812)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
at javax.swing.JComponent.paintComponent(JComponent.java:778)
at javax.swing.JComponent.paint(JComponent.java:1054)
at javax.swing.JComponent.paintChildren(JComponent.java:887)
at javax.swing.JComponent.paint(JComponent.java:1063)
at javax.swing.JViewport.paint(JViewport.java:731)
at javax.swing.JComponent.paintChildren(JComponent.java:887)
at javax.swing.JComponent.paint(JComponent.java:1063)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5221)
at
javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1512)
at
javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1443)
at javax.swing.RepaintManager.paint(RepaintManager.java:1236)
at javax.swing.JComponent._paintImmediately(JComponent.java:5169)
at javax.swing.JComponent.paintImmediately(JComponent.java:4980)
at javax.swing.RepaintManager$3.run(RepaintManager.java:796)
at javax.swing.RepaintManager$3.run(RepaintManager.java:784)
at java.security.AccessController.doPrivileged(Native Method)
at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:784)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:757)
at
javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:706)
at javax.swing.RepaintManager.access$1000(RepaintManager.java:62)
at
javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1651)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:697)
at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91).
Code snippet
public class TTableModel extends AbstractTableModel implements
ThreeInputConstants{
private ArrayList<Object> columnList;
private List<boolean[]> data;
public TTableModel() {
this.columnList = new ArrayList<>();
this.data = new ArrayList<>();
// adds p, q, r
columnList.add(THREE_INPUT_TITLES[0]);
columnList.add(THREE_INPUT_TITLES[1]);
columnList.add(THREE_INPUT_TITLES[2]);
for (int i = 0; i < 8; i++) {
boolean[] tempArray = new boolean[3];
tempArray[0] = P_CONST[i];
tempArray[1] = Q_CONST[i];
tempArray[2] = R_CONST[i];
data.add(i, tempArray);
}
}
public void printListTemp() {
System.out.println("Column list: " + columnList);
System.out.println("Data: " + data);
}
public void addColumn(String header) {
this.columnList.add(header);
this.fireTableStructureChanged();
}
public void removeColumn(int columnIndex) {
if (columnIndex >= 0 && columnIndex < getColumnCount()) {
this.columnList.remove(columnIndex + INPUT_COLUMN_COUNT);
this.fireTableStructureChanged();
}
}
@Override
public String getColumnName(int columnIndex) {
return columnList.get(columnIndex).toString();
}
@Override
public int getColumnCount() {
return columnList.size();
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public void setValueAt(Object value, int row, int column) {
//data[row][column] = value;
data.get(row)[column] = (boolean) value;
this.fireTableCellUpdated(row, column);
}
@Override
public Object getValueAt(int row, int column) {
return data.get(row)[column];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
}
public interface ThreeInputConstants {
public static final Object THREE_INPUT_TITLES[] = {
"p", "q", "r"
};
public static final boolean P_CONST[] = {
true, true, true, true,
false, false, false, false
};
public static final boolean Q_CONST[] = {
true, true, false, false,
true, true, false, false,
};
public static final boolean R_CONST[] = {
true, false, true, false,
true, false, true, false,
};
}
I'm making a GUI project, using MVC design pattern. This program contains
JTable component, for which I've created a class MyTableModel which
extends AbstractTableModel. As you can see below in MyModelClass, I have
two methods addColumn & removeColumn , which have normally add/remove
columns from table, until, I have come to the point, when I have to add 3
initial columns with 8 combinations into my constructor, and then try
add/remove columns. Here you can see screenshot of program.
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: 3
at mvc.TTableModel.getValueAt(TTableModel.java:79)
at mvc.TTableModel.getColumnClass(TTableModel.java:84)
at javax.swing.JTable.getColumnClass(JTable.java:2697)
at javax.swing.JTable.getCellRenderer(JTable.java:5682)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2113)
at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2016)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1812)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
at javax.swing.JComponent.paintComponent(JComponent.java:778)
at javax.swing.JComponent.paint(JComponent.java:1054)
at javax.swing.JComponent.paintChildren(JComponent.java:887)
at javax.swing.JComponent.paint(JComponent.java:1063)
at javax.swing.JViewport.paint(JViewport.java:731)
at javax.swing.JComponent.paintChildren(JComponent.java:887)
at javax.swing.JComponent.paint(JComponent.java:1063)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5221)
at
javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1512)
at
javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1443)
at javax.swing.RepaintManager.paint(RepaintManager.java:1236)
at javax.swing.JComponent._paintImmediately(JComponent.java:5169)
at javax.swing.JComponent.paintImmediately(JComponent.java:4980)
at javax.swing.RepaintManager$3.run(RepaintManager.java:796)
at javax.swing.RepaintManager$3.run(RepaintManager.java:784)
at java.security.AccessController.doPrivileged(Native Method)
at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:784)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:757)
at
javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:706)
at javax.swing.RepaintManager.access$1000(RepaintManager.java:62)
at
javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1651)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:697)
at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91).
Code snippet
public class TTableModel extends AbstractTableModel implements
ThreeInputConstants{
private ArrayList<Object> columnList;
private List<boolean[]> data;
public TTableModel() {
this.columnList = new ArrayList<>();
this.data = new ArrayList<>();
// adds p, q, r
columnList.add(THREE_INPUT_TITLES[0]);
columnList.add(THREE_INPUT_TITLES[1]);
columnList.add(THREE_INPUT_TITLES[2]);
for (int i = 0; i < 8; i++) {
boolean[] tempArray = new boolean[3];
tempArray[0] = P_CONST[i];
tempArray[1] = Q_CONST[i];
tempArray[2] = R_CONST[i];
data.add(i, tempArray);
}
}
public void printListTemp() {
System.out.println("Column list: " + columnList);
System.out.println("Data: " + data);
}
public void addColumn(String header) {
this.columnList.add(header);
this.fireTableStructureChanged();
}
public void removeColumn(int columnIndex) {
if (columnIndex >= 0 && columnIndex < getColumnCount()) {
this.columnList.remove(columnIndex + INPUT_COLUMN_COUNT);
this.fireTableStructureChanged();
}
}
@Override
public String getColumnName(int columnIndex) {
return columnList.get(columnIndex).toString();
}
@Override
public int getColumnCount() {
return columnList.size();
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public void setValueAt(Object value, int row, int column) {
//data[row][column] = value;
data.get(row)[column] = (boolean) value;
this.fireTableCellUpdated(row, column);
}
@Override
public Object getValueAt(int row, int column) {
return data.get(row)[column];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
}
public interface ThreeInputConstants {
public static final Object THREE_INPUT_TITLES[] = {
"p", "q", "r"
};
public static final boolean P_CONST[] = {
true, true, true, true,
false, false, false, false
};
public static final boolean Q_CONST[] = {
true, true, false, false,
true, true, false, false,
};
public static final boolean R_CONST[] = {
true, false, true, false,
true, false, true, false,
};
}
Regex.Replace from char position to another char position
Regex.Replace from char position to another char position
Good afternoon. I am a VB.Net programmer that has made every attempt to
implement regular expressions into my applications as much as possible. I
choose regex over Net methods because practice makes perfect. This is only
for my regex knowledge benefit.
Take a string like this for example ignoring the quotes.
":1Af404080A83hfndsgt4u47", the part of the string i am looking at is
these 8 values. "04080A83" These can change. The values are not important
but the position. Starting from 0 the first char position will be 5 to 12.
I know we can match any char until {5} but it possible to replace a range.
Example {5,12}. Final output would be "":1Af4Hello123hfndsgt4u47""
Hello123
Thank you for your time. It might not be possible like i said for my own
Benita.
Good afternoon. I am a VB.Net programmer that has made every attempt to
implement regular expressions into my applications as much as possible. I
choose regex over Net methods because practice makes perfect. This is only
for my regex knowledge benefit.
Take a string like this for example ignoring the quotes.
":1Af404080A83hfndsgt4u47", the part of the string i am looking at is
these 8 values. "04080A83" These can change. The values are not important
but the position. Starting from 0 the first char position will be 5 to 12.
I know we can match any char until {5} but it possible to replace a range.
Example {5,12}. Final output would be "":1Af4Hello123hfndsgt4u47""
Hello123
Thank you for your time. It might not be possible like i said for my own
Benita.
how to display image and other detail from the database using php
how to display image and other detail from the database using php
my db table table name 'store'
id | regno | name | image
------------------------------
1 | 101 | xxxxx | myimage
Here i able to search the particular image from the db but i need to
display all the details such as regno, name, and image in same form please
any body help me
table.php
<form action ="table.php" method="post">
search :<input type="text" name="search">
<input type="submit" name="submit">
</form>
<?php
echo $search =$_POST['search'];
?>
<table align="center" cellspacing="0" cellpadding="5" bgcolor="#ffffff"
border=1 bordercolor="#2696b8">
<tr>
<td align="center" width="45" height="45"><img src="image.php?reg=<?php
echo $search?>">
</tr>
</table>
image.php
<?php
mysql_connect("localhost","root","")or die(mysql_error());
mysql_select_db("databaseimage") or die(mysql_error());
$sql ="select * from store where reg= '".intval($_GET['reg'])."' ";
$result = mysql_query($sql) or die(mysql_error());
header('Content-Type: image/png');
echo mysql_result($result, 0);
if($result){
$row = mysql_fetch_row($result);
echo $row['image'];
}
else
{
echo readfile('/your/path/error/image.png');
}?>
in this query i cannot able to display the image please help me
my db table table name 'store'
id | regno | name | image
------------------------------
1 | 101 | xxxxx | myimage
Here i able to search the particular image from the db but i need to
display all the details such as regno, name, and image in same form please
any body help me
table.php
<form action ="table.php" method="post">
search :<input type="text" name="search">
<input type="submit" name="submit">
</form>
<?php
echo $search =$_POST['search'];
?>
<table align="center" cellspacing="0" cellpadding="5" bgcolor="#ffffff"
border=1 bordercolor="#2696b8">
<tr>
<td align="center" width="45" height="45"><img src="image.php?reg=<?php
echo $search?>">
</tr>
</table>
image.php
<?php
mysql_connect("localhost","root","")or die(mysql_error());
mysql_select_db("databaseimage") or die(mysql_error());
$sql ="select * from store where reg= '".intval($_GET['reg'])."' ";
$result = mysql_query($sql) or die(mysql_error());
header('Content-Type: image/png');
echo mysql_result($result, 0);
if($result){
$row = mysql_fetch_row($result);
echo $row['image'];
}
else
{
echo readfile('/your/path/error/image.png');
}?>
in this query i cannot able to display the image please help me
Wednesday, 21 August 2013
RuntimeException: Unable to start activity Component
RuntimeException: Unable to start activity Component
On this activity i want to show data from SQLite to Listview but it's
still runTime error. Can you check this logcat error to tell me what
happened and how i can do please ?
this is my logcat : i can get data from SQLite now
08-22 12:04:31.011: W/KeyCharacterMap(444): No keyboard for id 0
08-22 12:04:31.021: W/KeyCharacterMap(444): Using default keymap:
/system/usr/keychars/qwerty.kcm.bin
08-22 12:05:35.842: I/item_nickname(444): mao
08-22 12:05:35.842: I/item_fname(444): ho
08-22 12:05:35.842: I/item_lname(444): koj
08-22 12:05:35.842: I/item_nickname(444): YYY
08-22 12:05:35.842: I/item_fname(444): GGG
08-22 12:05:35.851: I/item_lname(444): UUU
08-22 12:05:35.851: I/item_nickname(444): DDD
08-22 12:05:35.851: I/item_fname(444): HHH
08-22 12:05:35.851: I/item_lname(444): TTT
08-22 12:05:35.861: I/item_nickname(444): RICKY
08-22 12:05:35.861: I/item_fname(444): SAMA
08-22 12:05:35.861: I/item_lname(444): SUZA
08-22 12:05:35.861: I/item_nickname(444): LLLL
08-22 12:05:35.861: I/item_fname(444): bbb
08-22 12:05:35.861: I/item_lname(444): MMM
08-22 12:05:35.861: I/item_nickname(444): XXX
08-22 12:05:35.861: I/item_fname(444): VVV
08-22 12:05:35.871: I/item_lname(444): CCC
08-22 12:05:35.871: I/item_nickname(444): UUU
08-22 12:05:35.871: I/item_fname(444): LLL
08-22 12:05:35.871: I/item_lname(444): PPP
08-22 12:05:35.871: I/item_nickname(444): lang
08-22 12:05:35.871: I/item_fname(444): rong
08-22 12:05:35.871: I/item_lname(444): lang
08-22 12:05:35.881: I/item_nickname(444): white
08-22 12:05:35.881: I/item_fname(444): sim
08-22 12:05:35.881: I/item_lname(444): same
08-22 12:05:35.881: I/item_nickname(444): NONG
08-22 12:05:35.881: I/item_fname(444): Bome
08-22 12:05:35.881: I/item_lname(444): NING
08-22 12:05:35.891: D/AndroidRuntime(444): Shutting down VM
08-22 12:05:35.891: W/dalvikvm(444): threadid=1: thread exiting with
uncaught exception (group=0x40015560)
08-22 12:05:35.911: E/AndroidRuntime(444): FATAL EXCEPTION: main
08-22 12:05:35.911: E/AndroidRuntime(444): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.example.sqlite/com.example.sqlite.FriendsListActivity}:
java.lang.IndexOutOfBoundsException: Invalid index 11, size is 11
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.os.Handler.dispatchMessage(Handler.java:99)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.os.Looper.loop(Looper.java:123)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.main(ActivityThread.java:3683)
08-22 12:05:35.911: E/AndroidRuntime(444): at
java.lang.reflect.Method.invokeNative(Native Method)
08-22 12:05:35.911: E/AndroidRuntime(444): at
java.lang.reflect.Method.invoke(Method.java:507)
08-22 12:05:35.911: E/AndroidRuntime(444): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-22 12:05:35.911: E/AndroidRuntime(444): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-22 12:05:35.911: E/AndroidRuntime(444): at
dalvik.system.NativeStart.main(Native Method)
08-22 12:05:35.911: E/AndroidRuntime(444): Caused by:
java.lang.IndexOutOfBoundsException: Invalid index 11, size is 11
08-22 12:05:35.911: E/AndroidRuntime(444): at
java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
08-22 12:05:35.911: E/AndroidRuntime(444): at
java.util.ArrayList.get(ArrayList.java:311)
08-22 12:05:35.911: E/AndroidRuntime(444): at
com.example.sqlite.FriendsListActivity.showAllList(FriendsListActivity.java:56)
08-22 12:05:35.911: E/AndroidRuntime(444): at
com.example.sqlite.FriendsListActivity.onCreate(FriendsListActivity.java:41)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-22 12:05:35.911: E/AndroidRuntime(444): ... 11 more
08-22 12:05:41.911: I/Process(444): Sending signal. PID: 444 SIG: 9
This is my code FriendsListActivity
package com.example.sqlite;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sqlite.db.FriendsDB;
import com.example.sqlite.entry.FriendEntry;
public class FriendsListActivity extends Activity {
private Context context;
private FriendsDB db;
private SimpleAdapter sAdap;
private ArrayList<FriendEntry> friends;
private TextView hellotext;
private ListView hellolistview;
ArrayList<HashMap<String, String>> MyArrList = new
ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.friendlist_layout);
context = this;
db = new FriendsDB(context);
friends = new ArrayList<FriendEntry>();
showAllList();
}
public void showAllList(){
//view matching
hellotext = (TextView) findViewById(R.id.hellotext);
hellolistview = (ListView) findViewById(R.id.hellolistview);
//select data
friends = db.selectAll();
if(friends.size()==0){
Toast.makeText(context,"You dont have any
friend.",Toast.LENGTH_SHORT).show();
}else{
for (int i = 1;i<=friends.size();i++){
// set value for friends
map = new HashMap<String, String>();
map.put("item_nickname", friends.get(i).getNickname());
map.put("item_fname", friends.get(i).getFname());
map.put("item_lname", friends.get(i).getLname());
Log.i("item_nickname", friends.get(i).getNickname());
Log.i("item_fname", friends.get(i).getFname());
Log.i("item_lname", friends.get(i).getLname());
}
//adapter
hellolistview.setAdapter(new adapter());
}
}
private class adapter extends BaseAdapter{
private Holder holder;
@Override
public int getCount() {
// TODO Auto-generated method stub
return friends.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
//create
if( view == null){
view =
LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_layout,null);
holder = new Holder();
holder.nickname = (TextView)
view.findViewById(R.id.item_nickname);
holder.fname = (TextView)view.findViewById(R.id.item_fname);
holder.lname = (TextView)view.findViewById(R.id.item_lname);
view.setTag(holder);
}else{
holder = (Holder) view.getTag();
}
//assign
holder.nickname.setText(map.get("item_nickname"));
holder.fname.setText(map.get("item_fname"));
holder.lname.setText(map.get("item_lname"));
return view;
}
private class Holder{
public TextView nickname;
public TextView fname;
public TextView lname;
}
}
}
Thank you
On this activity i want to show data from SQLite to Listview but it's
still runTime error. Can you check this logcat error to tell me what
happened and how i can do please ?
this is my logcat : i can get data from SQLite now
08-22 12:04:31.011: W/KeyCharacterMap(444): No keyboard for id 0
08-22 12:04:31.021: W/KeyCharacterMap(444): Using default keymap:
/system/usr/keychars/qwerty.kcm.bin
08-22 12:05:35.842: I/item_nickname(444): mao
08-22 12:05:35.842: I/item_fname(444): ho
08-22 12:05:35.842: I/item_lname(444): koj
08-22 12:05:35.842: I/item_nickname(444): YYY
08-22 12:05:35.842: I/item_fname(444): GGG
08-22 12:05:35.851: I/item_lname(444): UUU
08-22 12:05:35.851: I/item_nickname(444): DDD
08-22 12:05:35.851: I/item_fname(444): HHH
08-22 12:05:35.851: I/item_lname(444): TTT
08-22 12:05:35.861: I/item_nickname(444): RICKY
08-22 12:05:35.861: I/item_fname(444): SAMA
08-22 12:05:35.861: I/item_lname(444): SUZA
08-22 12:05:35.861: I/item_nickname(444): LLLL
08-22 12:05:35.861: I/item_fname(444): bbb
08-22 12:05:35.861: I/item_lname(444): MMM
08-22 12:05:35.861: I/item_nickname(444): XXX
08-22 12:05:35.861: I/item_fname(444): VVV
08-22 12:05:35.871: I/item_lname(444): CCC
08-22 12:05:35.871: I/item_nickname(444): UUU
08-22 12:05:35.871: I/item_fname(444): LLL
08-22 12:05:35.871: I/item_lname(444): PPP
08-22 12:05:35.871: I/item_nickname(444): lang
08-22 12:05:35.871: I/item_fname(444): rong
08-22 12:05:35.871: I/item_lname(444): lang
08-22 12:05:35.881: I/item_nickname(444): white
08-22 12:05:35.881: I/item_fname(444): sim
08-22 12:05:35.881: I/item_lname(444): same
08-22 12:05:35.881: I/item_nickname(444): NONG
08-22 12:05:35.881: I/item_fname(444): Bome
08-22 12:05:35.881: I/item_lname(444): NING
08-22 12:05:35.891: D/AndroidRuntime(444): Shutting down VM
08-22 12:05:35.891: W/dalvikvm(444): threadid=1: thread exiting with
uncaught exception (group=0x40015560)
08-22 12:05:35.911: E/AndroidRuntime(444): FATAL EXCEPTION: main
08-22 12:05:35.911: E/AndroidRuntime(444): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.example.sqlite/com.example.sqlite.FriendsListActivity}:
java.lang.IndexOutOfBoundsException: Invalid index 11, size is 11
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.os.Handler.dispatchMessage(Handler.java:99)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.os.Looper.loop(Looper.java:123)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.main(ActivityThread.java:3683)
08-22 12:05:35.911: E/AndroidRuntime(444): at
java.lang.reflect.Method.invokeNative(Native Method)
08-22 12:05:35.911: E/AndroidRuntime(444): at
java.lang.reflect.Method.invoke(Method.java:507)
08-22 12:05:35.911: E/AndroidRuntime(444): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-22 12:05:35.911: E/AndroidRuntime(444): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-22 12:05:35.911: E/AndroidRuntime(444): at
dalvik.system.NativeStart.main(Native Method)
08-22 12:05:35.911: E/AndroidRuntime(444): Caused by:
java.lang.IndexOutOfBoundsException: Invalid index 11, size is 11
08-22 12:05:35.911: E/AndroidRuntime(444): at
java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
08-22 12:05:35.911: E/AndroidRuntime(444): at
java.util.ArrayList.get(ArrayList.java:311)
08-22 12:05:35.911: E/AndroidRuntime(444): at
com.example.sqlite.FriendsListActivity.showAllList(FriendsListActivity.java:56)
08-22 12:05:35.911: E/AndroidRuntime(444): at
com.example.sqlite.FriendsListActivity.onCreate(FriendsListActivity.java:41)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-22 12:05:35.911: E/AndroidRuntime(444): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-22 12:05:35.911: E/AndroidRuntime(444): ... 11 more
08-22 12:05:41.911: I/Process(444): Sending signal. PID: 444 SIG: 9
This is my code FriendsListActivity
package com.example.sqlite;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sqlite.db.FriendsDB;
import com.example.sqlite.entry.FriendEntry;
public class FriendsListActivity extends Activity {
private Context context;
private FriendsDB db;
private SimpleAdapter sAdap;
private ArrayList<FriendEntry> friends;
private TextView hellotext;
private ListView hellolistview;
ArrayList<HashMap<String, String>> MyArrList = new
ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.friendlist_layout);
context = this;
db = new FriendsDB(context);
friends = new ArrayList<FriendEntry>();
showAllList();
}
public void showAllList(){
//view matching
hellotext = (TextView) findViewById(R.id.hellotext);
hellolistview = (ListView) findViewById(R.id.hellolistview);
//select data
friends = db.selectAll();
if(friends.size()==0){
Toast.makeText(context,"You dont have any
friend.",Toast.LENGTH_SHORT).show();
}else{
for (int i = 1;i<=friends.size();i++){
// set value for friends
map = new HashMap<String, String>();
map.put("item_nickname", friends.get(i).getNickname());
map.put("item_fname", friends.get(i).getFname());
map.put("item_lname", friends.get(i).getLname());
Log.i("item_nickname", friends.get(i).getNickname());
Log.i("item_fname", friends.get(i).getFname());
Log.i("item_lname", friends.get(i).getLname());
}
//adapter
hellolistview.setAdapter(new adapter());
}
}
private class adapter extends BaseAdapter{
private Holder holder;
@Override
public int getCount() {
// TODO Auto-generated method stub
return friends.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
//create
if( view == null){
view =
LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_layout,null);
holder = new Holder();
holder.nickname = (TextView)
view.findViewById(R.id.item_nickname);
holder.fname = (TextView)view.findViewById(R.id.item_fname);
holder.lname = (TextView)view.findViewById(R.id.item_lname);
view.setTag(holder);
}else{
holder = (Holder) view.getTag();
}
//assign
holder.nickname.setText(map.get("item_nickname"));
holder.fname.setText(map.get("item_fname"));
holder.lname.setText(map.get("item_lname"));
return view;
}
private class Holder{
public TextView nickname;
public TextView fname;
public TextView lname;
}
}
}
Thank you
Netbeans git plugin shows all files deleted
Netbeans git plugin shows all files deleted
I updated my Netbeans to 7.3.1, and opened the existing projects in my
local git repo.
The Netbeans git plugin shows that all the files are deleted.
Anyone knows why and how to fix this?
The name of this plugin is called "Git", version 1.8.2.1.
I am more than happy to provide any additional information needed to
figure out this issue.
I updated my Netbeans to 7.3.1, and opened the existing projects in my
local git repo.
The Netbeans git plugin shows that all the files are deleted.
Anyone knows why and how to fix this?
The name of this plugin is called "Git", version 1.8.2.1.
I am more than happy to provide any additional information needed to
figure out this issue.
Re-mounting root partition on a live server
Re-mounting root partition on a live server
We've got a handful of apache/PHP/mysql servers running here, and I've
noticed that not one of them have the noatime option specified in any of
their fstabs. Given that the PHP applications running on them tend to
spider out into dozens of includes for every request I figure we should be
able to decrease a bit of the load on the filesystem by turning off atime
tracking.
I've checked around and no one either needs to know the access times on
anything, or was even aware that that was a thing, so what I would like to
do is simply:
mount -o remount,noatime /
However, there are 2 concerns:
MySQL dying because the filesystem disappeared for a microsecond. In which
case I'd just stop it temporarily.
The OS dying because of the same.
I'm not crazy about the prospect of rebooting these machines since most of
them have several times more uptime as I've been with this company, and
who knows what is going to go sideways on a reboot.
So, is there any actual, fact-based reason why I should not remount the
root partition while the server is running?
We've got a handful of apache/PHP/mysql servers running here, and I've
noticed that not one of them have the noatime option specified in any of
their fstabs. Given that the PHP applications running on them tend to
spider out into dozens of includes for every request I figure we should be
able to decrease a bit of the load on the filesystem by turning off atime
tracking.
I've checked around and no one either needs to know the access times on
anything, or was even aware that that was a thing, so what I would like to
do is simply:
mount -o remount,noatime /
However, there are 2 concerns:
MySQL dying because the filesystem disappeared for a microsecond. In which
case I'd just stop it temporarily.
The OS dying because of the same.
I'm not crazy about the prospect of rebooting these machines since most of
them have several times more uptime as I've been with this company, and
who knows what is going to go sideways on a reboot.
So, is there any actual, fact-based reason why I should not remount the
root partition while the server is running?
single iteration sharing the iterator
single iteration sharing the iterator
I have a lot of data, usually in a file. I want to compute some quantities
so I have this kind of functions:
def mean(iterator):
n = 0
sum = 0.
for i in iterator:
sum += i
n += 1
return sum / float(n)
I have also many other similar functions (var, size, ...)
Now I have an iterator iterating throught the data: iter_data. I can
compute all the quantities I want: m = mean(iter_data); v = var(iter_data)
and so on, but the problem is that I am iterating many times and this is
expensive in my case. Actually the I/O is the most expensive part.
So the question is: can I compute my quantities m, v, ... iterating only
one time over iter_data keeping separate the functions mean, var, ... so
that it is easy to add new ones?
What I need is something similar to boost::accumulators
I have a lot of data, usually in a file. I want to compute some quantities
so I have this kind of functions:
def mean(iterator):
n = 0
sum = 0.
for i in iterator:
sum += i
n += 1
return sum / float(n)
I have also many other similar functions (var, size, ...)
Now I have an iterator iterating throught the data: iter_data. I can
compute all the quantities I want: m = mean(iter_data); v = var(iter_data)
and so on, but the problem is that I am iterating many times and this is
expensive in my case. Actually the I/O is the most expensive part.
So the question is: can I compute my quantities m, v, ... iterating only
one time over iter_data keeping separate the functions mean, var, ... so
that it is easy to add new ones?
What I need is something similar to boost::accumulators
relations() in Yii, do not understand the example from the book
relations() in Yii, do not understand the example from the book
I read a book Pactpub Web Application Development with Yii and PHP Nov
2012. Faced with such a problem, I can not understand the logic behind the
use of relations (). Here diagram tables in the database:
You need to insert code in the model:
Issue model:
...
'requester' => array(self::BELONGS_TO, 'User', 'requester_id'),
'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),
'project' => array(self::BELONGS_TO, 'Project', 'project_id'),
);
...
Project model:
...
'issues' => array(self::HAS_MANY, 'Issue', 'project_id'),
'users' => array(self::MANY_MANY, 'User',
'tbl_project_user_assignment(project_id, user_id)'),
...
I can not understand that we add? If the model Issue understand
everything, then the model Project - I do not understand that we are
adding. Help to understand ...
I read a book Pactpub Web Application Development with Yii and PHP Nov
2012. Faced with such a problem, I can not understand the logic behind the
use of relations (). Here diagram tables in the database:
You need to insert code in the model:
Issue model:
...
'requester' => array(self::BELONGS_TO, 'User', 'requester_id'),
'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),
'project' => array(self::BELONGS_TO, 'Project', 'project_id'),
);
...
Project model:
...
'issues' => array(self::HAS_MANY, 'Issue', 'project_id'),
'users' => array(self::MANY_MANY, 'User',
'tbl_project_user_assignment(project_id, user_id)'),
...
I can not understand that we add? If the model Issue understand
everything, then the model Project - I do not understand that we are
adding. Help to understand ...
Unable to generate Provisioning Profile
Unable to generate Provisioning Profile
I am unable to generate Provisioning Profile for my app. Even thought I am
following the Apple developer website's instructions, I end up stuck with
the loading wheel turning for ever after hitting the 'Generate' button.
Has anybody ever had the same problem?
Some help would be greatly appreciated since my app is ready and this sole
issue is preventing me from distributing my app. Thank you for you
condolence !
I am unable to generate Provisioning Profile for my app. Even thought I am
following the Apple developer website's instructions, I end up stuck with
the loading wheel turning for ever after hitting the 'Generate' button.
Has anybody ever had the same problem?
Some help would be greatly appreciated since my app is ready and this sole
issue is preventing me from distributing my app. Thank you for you
condolence !
Tuesday, 20 August 2013
How to make Thunderbird keep multiple versions of a draft?
How to make Thunderbird keep multiple versions of a draft?
I'd like to save multiple (successive) versions of a long letter I'm
composing in the message window. The problem (for me) is that pressing the
"Save" button can only replace the previously saved composition (of my
message). Also auto-save rewrites the draft(s), which seems preventable
with an addon.
So my original question is: How could I make a new draft/concept without
overwriting a previously existing version (which I'd like to keep for
myself)?
I've found out that saving to "templates" creates successive version.
Though this seems counter-intuitive to the suspected meaning of
'templates'. So can I get the same behaviour for the standard "concepts"
folder?
I also wonder, is there any way to save successive versions noted by the
auto-save..? Or (not to make my question too XY), is there some better (or
at least good) approach for keeping track of the genesis of my message?
I'd like to save multiple (successive) versions of a long letter I'm
composing in the message window. The problem (for me) is that pressing the
"Save" button can only replace the previously saved composition (of my
message). Also auto-save rewrites the draft(s), which seems preventable
with an addon.
So my original question is: How could I make a new draft/concept without
overwriting a previously existing version (which I'd like to keep for
myself)?
I've found out that saving to "templates" creates successive version.
Though this seems counter-intuitive to the suspected meaning of
'templates'. So can I get the same behaviour for the standard "concepts"
folder?
I also wonder, is there any way to save successive versions noted by the
auto-save..? Or (not to make my question too XY), is there some better (or
at least good) approach for keeping track of the genesis of my message?
What does lsboxd process do on os x?
What does lsboxd process do on os x?
My firewall asked me for a connection from lsboxd (module
com.apple.ls.boxd, ) to one another computer in my network to the port tcp
548. What does it do? I found that it is a part of sandbox technology of a
OS X, but what is it more specifically? I found it in my launchctl list
output:
com.apple.LaunchServices.lsboxd
My firewall asked me for a connection from lsboxd (module
com.apple.ls.boxd, ) to one another computer in my network to the port tcp
548. What does it do? I found that it is a part of sandbox technology of a
OS X, but what is it more specifically? I found it in my launchctl list
output:
com.apple.LaunchServices.lsboxd
Getting the Nth instance of an element
Getting the Nth instance of an element
I have a column filled with data that has a path. I'd like to get the last
element in the path, the second last element, and the first element. For
example, for the following data:
\Product\Release\Iteration
\Product\Folder1\Folder2\Anotherfolder\Release2\Iteration5
\Product
\Product\Somefolder\Release3\Iteration5
I'd like to get the following in cells
In cell B1: "Product", cell C1: "Release", cell D1: "Iteration"
In cell B2: "Product", cell C2: "Release2", cell D2: "Iteration5"
In cell B3: "Product", cell C3: blank, cell D3: blank
In cell B4: "Product", cell C4: "Release3", cell D4: "Iteration5"
Getting the first and the last component is easy. I'm mostly just
struggling with getting the second to last component (column C in the
example above).
I have a column filled with data that has a path. I'd like to get the last
element in the path, the second last element, and the first element. For
example, for the following data:
\Product\Release\Iteration
\Product\Folder1\Folder2\Anotherfolder\Release2\Iteration5
\Product
\Product\Somefolder\Release3\Iteration5
I'd like to get the following in cells
In cell B1: "Product", cell C1: "Release", cell D1: "Iteration"
In cell B2: "Product", cell C2: "Release2", cell D2: "Iteration5"
In cell B3: "Product", cell C3: blank, cell D3: blank
In cell B4: "Product", cell C4: "Release3", cell D4: "Iteration5"
Getting the first and the last component is easy. I'm mostly just
struggling with getting the second to last component (column C in the
example above).
FFT and inverse of FFT
FFT and inverse of FFT
I am a computer programmer who work on a Telecommunication project.
In our project I have to change a series of complex number to their
Fourier transform.so I need an efficient FFT code for C89 standard.
I am using the following code and it works well enough:
short FFT(short int dir,long m,double *x,double *y)
{
long n,i,i1,j,k,i2,l,l1,l2;
double c1,c2,tx,ty,t1,t2,u1,u2,z;
/* Calculate the number of points */
n = 1;
for (i=0;i<m;i++)
n *= 2;
/* Do the bit reversal */
i2 = n >> 1;
j = 0;
for (i=0;i<n-1;i++) {
if (i < j) {
tx = x[i];
ty = y[i];
x[i] = x[j];
y[i] = y[j];
x[j] = tx;
y[j] = ty;
}
k = i2;
while (k <= j) {
j -= k;
k >>= 1;
}
j += k;
}
/* Compute the FFT */
c1 = -1.0;
c2 = 0.0;
l2 = 1;
for (l=0;l<m;l++) {
l1 = l2;
l2 <<= 1;
u1 = 1.0;
u2 = 0.0;
for (j=0;j<l1;j++) {
for (i=j;i<n;i+=l2) {
i1 = i + l1;
t1 = u1 * x[i1] - u2 * y[i1];
t2 = u1 * y[i1] + u2 * x[i1];
x[i1] = x[i] - t1;
y[i1] = y[i] - t2;
x[i] += t1;
y[i] += t2;
}
z = u1 * c1 - u2 * c2;
u2 = u1 * c2 + u2 * c1;
u1 = z;
}
c2 = sqrt((1.0 - c1) / 2.0);
if (dir == 1)
c2 = -c2;
c1 = sqrt((1.0 + c1) / 2.0);
}
/* Scaling for forward transform */
if (dir == 1) {
for (i=0;i<n;i++) {
x[i] /= n;
y[i] /= n;
}
}
return(true);
}
But this code, just support arrays with the size of 2^m.like CLRS book code.
Our arrays which should be transformed, are not in this range and adding
zero will be expensive, so I am looking for another solution which help me
to have input in any size.
Something like what IT++ and matlab do. but as we want it in pure C using
them is impossible.Moreover, IT++ code was blocked as I checked
I am a computer programmer who work on a Telecommunication project.
In our project I have to change a series of complex number to their
Fourier transform.so I need an efficient FFT code for C89 standard.
I am using the following code and it works well enough:
short FFT(short int dir,long m,double *x,double *y)
{
long n,i,i1,j,k,i2,l,l1,l2;
double c1,c2,tx,ty,t1,t2,u1,u2,z;
/* Calculate the number of points */
n = 1;
for (i=0;i<m;i++)
n *= 2;
/* Do the bit reversal */
i2 = n >> 1;
j = 0;
for (i=0;i<n-1;i++) {
if (i < j) {
tx = x[i];
ty = y[i];
x[i] = x[j];
y[i] = y[j];
x[j] = tx;
y[j] = ty;
}
k = i2;
while (k <= j) {
j -= k;
k >>= 1;
}
j += k;
}
/* Compute the FFT */
c1 = -1.0;
c2 = 0.0;
l2 = 1;
for (l=0;l<m;l++) {
l1 = l2;
l2 <<= 1;
u1 = 1.0;
u2 = 0.0;
for (j=0;j<l1;j++) {
for (i=j;i<n;i+=l2) {
i1 = i + l1;
t1 = u1 * x[i1] - u2 * y[i1];
t2 = u1 * y[i1] + u2 * x[i1];
x[i1] = x[i] - t1;
y[i1] = y[i] - t2;
x[i] += t1;
y[i] += t2;
}
z = u1 * c1 - u2 * c2;
u2 = u1 * c2 + u2 * c1;
u1 = z;
}
c2 = sqrt((1.0 - c1) / 2.0);
if (dir == 1)
c2 = -c2;
c1 = sqrt((1.0 + c1) / 2.0);
}
/* Scaling for forward transform */
if (dir == 1) {
for (i=0;i<n;i++) {
x[i] /= n;
y[i] /= n;
}
}
return(true);
}
But this code, just support arrays with the size of 2^m.like CLRS book code.
Our arrays which should be transformed, are not in this range and adding
zero will be expensive, so I am looking for another solution which help me
to have input in any size.
Something like what IT++ and matlab do. but as we want it in pure C using
them is impossible.Moreover, IT++ code was blocked as I checked
Mysql AND WHERE selection
Mysql AND WHERE selection
i have te make a slection but cannot get it to work with the WHERE LIKE
function. What is wrong with the line below?
$result = mysql_query("SELECT * FROM games WHERE soort='nieuws' AND
gamenaam='$spelnaam' AND platform LIKE '%wiiu%' AND ORDER BY id DESC");
It worked until i added
AND platform LIKE '%wiiu%'
The platform column contains cells with multiple values that come from a
selection box form. So it writes, wiiu, ps4, xbox360, pc etc....Must be
simple but i tried like a million times...
i have te make a slection but cannot get it to work with the WHERE LIKE
function. What is wrong with the line below?
$result = mysql_query("SELECT * FROM games WHERE soort='nieuws' AND
gamenaam='$spelnaam' AND platform LIKE '%wiiu%' AND ORDER BY id DESC");
It worked until i added
AND platform LIKE '%wiiu%'
The platform column contains cells with multiple values that come from a
selection box form. So it writes, wiiu, ps4, xbox360, pc etc....Must be
simple but i tried like a million times...
...oracle group by syntax for beginners
MySQL OOP Library Class C#
MySQL OOP Library Class C#
In php I used the built-in library of OOP mysqli. I really like it. Has
now become a question of using it in c#. Are there already such as
libraries for c #??? I've searched but found nothing. I am a Russian
translation of google, you know.
In php I used the built-in library of OOP mysqli. I really like it. Has
now become a question of using it in c#. Are there already such as
libraries for c #??? I've searched but found nothing. I am a Russian
translation of google, you know.
Monday, 19 August 2013
Remove Duplicates in Excel 2013 keep row with most data in place
Remove Duplicates in Excel 2013 keep row with most data in place
I have a spreadsheet that looks something like this:
Full Name | Email | Phone Number
--------- ------- -----------
Billy Bob bob@gmail.com 8019929102
Sally Sue sue@gmail.com 8013439403
Billy Bob 8013432343
bob@gmail.com
Sally Sue
Joe So joe@gmail.com
I want to remove duplicates based on email and keep the row that has the
most complete data (the most columns filled). After I do email i'll look
for duplicates based on Full Name and then phone number etc..
This is going to be done on almost 500,000 rows of data.
I have a spreadsheet that looks something like this:
Full Name | Email | Phone Number
--------- ------- -----------
Billy Bob bob@gmail.com 8019929102
Sally Sue sue@gmail.com 8013439403
Billy Bob 8013432343
bob@gmail.com
Sally Sue
Joe So joe@gmail.com
I want to remove duplicates based on email and keep the row that has the
most complete data (the most columns filled). After I do email i'll look
for duplicates based on Full Name and then phone number etc..
This is going to be done on almost 500,000 rows of data.
Htacces Apache END Flag alternative
Htacces Apache END Flag alternative
I wrote a small framework (PHP) for small projects, which in all should be
redirected to index.php?path=$1, except the defined paths. With the END
flag this is not problematic. But the END flag exists still since Apache
2.3 and the script should work also on apache 2.2 servers.
Has anyone an idea how I can realize this without the END flag?
RewriteEngine on
# Define static redicts
RewriteRule ^image/(.+)$ public/image/$1 [END,QSA]
RewriteRule ^css/(.+)$ public/css/$1 [END,QSA]
RewriteRule ^js/(.+)$ public/js/$1 [END,QSA]
RewriteRule ^lib/js/core/(.+)$ core/lib/js/$1 [END,QSA]
RewriteRule ^lib/js/(.+)$ public/lib/js/$1 [END,QSA]
RewriteRule ^cache/(.+)$ public/cache/$1 [END,QSA]
RewriteRule ^download/(.+)$ public/download/$1 [END,QSA]
# Define custom redicts
RewriteRule ^page/([0-9]+)$ index.php?path=index.php&page=$1 [END,QSA]
# Define all other redicts
RewriteRule ^(.+)$ index.php?path=$1 [L,QSA]
I wrote a small framework (PHP) for small projects, which in all should be
redirected to index.php?path=$1, except the defined paths. With the END
flag this is not problematic. But the END flag exists still since Apache
2.3 and the script should work also on apache 2.2 servers.
Has anyone an idea how I can realize this without the END flag?
RewriteEngine on
# Define static redicts
RewriteRule ^image/(.+)$ public/image/$1 [END,QSA]
RewriteRule ^css/(.+)$ public/css/$1 [END,QSA]
RewriteRule ^js/(.+)$ public/js/$1 [END,QSA]
RewriteRule ^lib/js/core/(.+)$ core/lib/js/$1 [END,QSA]
RewriteRule ^lib/js/(.+)$ public/lib/js/$1 [END,QSA]
RewriteRule ^cache/(.+)$ public/cache/$1 [END,QSA]
RewriteRule ^download/(.+)$ public/download/$1 [END,QSA]
# Define custom redicts
RewriteRule ^page/([0-9]+)$ index.php?path=index.php&page=$1 [END,QSA]
# Define all other redicts
RewriteRule ^(.+)$ index.php?path=$1 [L,QSA]
theymeleaf inline javascript framework issue
theymeleaf inline javascript framework issue
<script th:inline="javascript" type="text/javascript">
//expose list data to javascript
var listObject = /*[[${listObject}]]*/ [];
</script>
the replacement text printed into the file is different than what Jackson
library's ObjectMapper does.
With Thymeleaf in above example, listObject will be
{
"dataType":{
"$type":"DataType",
"$name":"STRING"
},
"friendlyName":"Customer Key"
}
If I print the object with ObjectMapper(which is also used with Spring
@RequestBody/@ResponseBody), it will be
{
"dataType":"STRING",
"friendlyName":"Customer Key"
}
Is there a way I can force thymeleaf to be compatible with ObjectMapper.
<script th:inline="javascript" type="text/javascript">
//expose list data to javascript
var listObject = /*[[${listObject}]]*/ [];
</script>
the replacement text printed into the file is different than what Jackson
library's ObjectMapper does.
With Thymeleaf in above example, listObject will be
{
"dataType":{
"$type":"DataType",
"$name":"STRING"
},
"friendlyName":"Customer Key"
}
If I print the object with ObjectMapper(which is also used with Spring
@RequestBody/@ResponseBody), it will be
{
"dataType":"STRING",
"friendlyName":"Customer Key"
}
Is there a way I can force thymeleaf to be compatible with ObjectMapper.
How to create a custom gallery having images of a particular url folder Android
How to create a custom gallery having images of a particular url folder
Android
I want to create a gallery of the images which are put up in the url
folder:[http://10.0.2.2/www/Bardo/images/] I have spent a lot of time
looking for many solutions, but no success..
Android
I want to create a gallery of the images which are put up in the url
folder:[http://10.0.2.2/www/Bardo/images/] I have spent a lot of time
looking for many solutions, but no success..
Sunday, 18 August 2013
How do I read data from Isodep using android nfc?
How do I read data from Isodep using android nfc?
I want to read data from a nfc tag using IsoDep technology.How do I go
about doing it?
I want to read data from a nfc tag using IsoDep technology.How do I go
about doing it?
Creating a timer in Visual C#
Creating a timer in Visual C#
I am new to C# and I am wondering if any one can explain the process of
creating a timer in Visual C# that counts up hours, minutes and seconds
until the user's values for hours, minutes and seconds are met. Is this
possible. if not, please offer an alternative solution. Thank you.
I am new to C# and I am wondering if any one can explain the process of
creating a timer in Visual C# that counts up hours, minutes and seconds
until the user's values for hours, minutes and seconds are met. Is this
possible. if not, please offer an alternative solution. Thank you.
Default to using small med packs in Dead Space 3?
Default to using small med packs in Dead Space 3?
Everytime I hit q to use a medpack, it seems to use the largest one I
have. However, I've got a bunch of small medpacks taking up space.
Is it possible to change the default behavior to use a small med back first?
Everytime I hit q to use a medpack, it seems to use the largest one I
have. However, I've got a bunch of small medpacks taking up space.
Is it possible to change the default behavior to use a small med back first?
Noun for "act of striving"
Noun for "act of striving"
Is there a noun for the act of striving?
Many English verbs use the same word for the infinitive (e.g. to fall) and
for the act of performing that action (e.g. a fall), but I haven't found
whether strive can be used as the act of striving. Is there a synonym that
could work?
Is there a noun for the act of striving?
Many English verbs use the same word for the infinitive (e.g. to fall) and
for the act of performing that action (e.g. a fall), but I haven't found
whether strive can be used as the act of striving. Is there a synonym that
could work?
Live streaming::Crystal Palace vs Tottenham England Premier League Soccer online 18 Aug 2013
Live streaming::Crystal Palace vs Tottenham England Premier League Soccer
online 18 Aug 2013
Watch here: http://is.gd/ysjgYF FREE Tottenham v Crystal Palace Live
Stream August 18,2013, Soccer Match Crystal Palace vs Tottenham live
stream soccer online on pc here, just follow our streaming link. FWatch
Tottenham v Crystal Palace live, Tottenham v Crystal Palace Live.Enjoy
Crystal Palace vs Tottenham live stream Free Soccer Game Online HD on your
Pc. Ensure that you must be 100% satisfied in out service so don't be
hesitated just click the link bellow and start watching and enjoy
more.best of luck. Crystal Palace vs Tottenham Soccer Link
Watch Here:: http://tinyurl.com/keqef87
CLICK HERE FOR LIVE live Soccer TV England - Premier League Match Details:
Crystal Palace vs Tottenham Date: Sunday August 18 ,2013 Time: 16:30
Status: Live* England - Premier League
Watch Live Soccer On Your PC CLICK HERE FOR LIVE Soccer TV CHANNELS The
Following TV are Broadcast on ESPN, TEN Action, STAR Sports, TEN Sports
and many TV are broadcast Leeds Crystal Palace vs Tottenham live Soccer
Game Video TV channel on PC. Crystal Palace vs Tottenham live, Crystal
Palace vs Tottenham live online England - Premier League, Crystal Palace
vs Tottenham live online on PC, Crystal Palace vs Tottenham live online on
your PC or laptop, Swansea City vs Queens Park R. live stream, Arsenal vs
Liverpool live sop cast, Crystal Palace vs Tottenham p2p live stream. To
watch this game live play just click here. Watch and enjoy Crystal Palace
vs Tottenham live online broadcast here, You can enjoy the action live
streaming on your PC via Internet TV channels. Crystal Palace vs Tottenham
match live video..
online 18 Aug 2013
Watch here: http://is.gd/ysjgYF FREE Tottenham v Crystal Palace Live
Stream August 18,2013, Soccer Match Crystal Palace vs Tottenham live
stream soccer online on pc here, just follow our streaming link. FWatch
Tottenham v Crystal Palace live, Tottenham v Crystal Palace Live.Enjoy
Crystal Palace vs Tottenham live stream Free Soccer Game Online HD on your
Pc. Ensure that you must be 100% satisfied in out service so don't be
hesitated just click the link bellow and start watching and enjoy
more.best of luck. Crystal Palace vs Tottenham Soccer Link
Watch Here:: http://tinyurl.com/keqef87
CLICK HERE FOR LIVE live Soccer TV England - Premier League Match Details:
Crystal Palace vs Tottenham Date: Sunday August 18 ,2013 Time: 16:30
Status: Live* England - Premier League
Watch Live Soccer On Your PC CLICK HERE FOR LIVE Soccer TV CHANNELS The
Following TV are Broadcast on ESPN, TEN Action, STAR Sports, TEN Sports
and many TV are broadcast Leeds Crystal Palace vs Tottenham live Soccer
Game Video TV channel on PC. Crystal Palace vs Tottenham live, Crystal
Palace vs Tottenham live online England - Premier League, Crystal Palace
vs Tottenham live online on PC, Crystal Palace vs Tottenham live online on
your PC or laptop, Swansea City vs Queens Park R. live stream, Arsenal vs
Liverpool live sop cast, Crystal Palace vs Tottenham p2p live stream. To
watch this game live play just click here. Watch and enjoy Crystal Palace
vs Tottenham live online broadcast here, You can enjoy the action live
streaming on your PC via Internet TV channels. Crystal Palace vs Tottenham
match live video..
Java file list error
Java file list error
Hi i am creating an application that installs files into a selected jar. I
can't figure out how to fix the error in my list(Dir); method, It
recognizes all files and directories but when it tries to change its
directory (list(DIRECTORY);) it changes it to /originalDirectory/subFolder
i want to add a / after subFolder i've tried to do DIRECTORY + "/". But it
doesn't work any ideas? please.
My code:
public class DisplayContent extends JPanel implements ActionListener {
public DisplayContent() {
handleGraphics();
}
public String chosenDir = null;
public JButton btnInstall;
public JButton btnDone;
public boolean done = false;
private void handleGraphics() {
setLayout(null);
JLabel paneTitle = new JLabel();
paneTitle.setFont(new Font("Comic Sans MS", Font.BOLD, 20));
paneTitle.setBounds(55, 6, 330, 62);
paneTitle.setBackground(new Color(237, 237, 237));
paneTitle.setText("The Halo Ultimate Mod Installer");
add(paneTitle);
btnInstall = new JButton("Click Me To Install The Halo Ultimate
Mod");
btnInstall.setBounds(16, 134, 414, 47);
btnInstall.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
install(chosenDir);
} catch (IOException e) {
e.printStackTrace();
}
done = true;
btnDone.setVisible(true);
btnInstall.setVisible(false);
}
});
add(btnInstall);
btnDone = new JButton("Finish Installation of Halo Ultimate Mod");
btnDone.setBounds(16, 134, 414, 47);
btnDone.setVisible(false);
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
installFinish(chosenDir);
} catch (IOException e) {
e.printStackTrace();
}
}
});
add(btnDone);
final JButton forgeFolder = new JButton("Select Forge Jar File!
Important!");
forgeFolder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
chosenDir = getSelectedDir(forgeFolder);
}
});
forgeFolder.setBounds(16, 80, 414, 47);
add(forgeFolder);
}
public static String[] splitDir;
public void install(String dir) throws IOException {
JarFile Jar = new JarFile(new File(dir));
String jar = dir;
String absolutePath = new File("").getAbsolutePath();
File halo = new File(absolutePath + "/mods/");
splitDir = dir.split(".jar");
getMod(jar, halo, Jar);
System.out.print(" --- NEW DIR2 --- " + absolutePath);
System.out.print(" --- NEW DIR --- " + chosenDir);
}
public String jarName;
public String getSelectedDir(Component parent){
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode( JFileChooser.FILES_ONLY );
if( fc.showOpenDialog( parent ) == JFileChooser.APPROVE_OPTION )
{
jarName = fc.getSelectedFile().getName();
return fc.getSelectedFile().getAbsolutePath();
}
return null;
}
public void actionPerformed(ActionEvent e) {}
public void getMod(String jar, File src, JarFile jarFile) {
File folder = new File(splitDir[0] + "/assets");
try {
extractJar(jarFile, splitDir[0], folder, src);
} catch (IOException e) {
e.printStackTrace();
}
}
public void installFinish(String dir) throws IOException {
File Jar = new File(dir);
File Jar2 = new File(dir);
Jar.delete();
File Dir = new File(splitDir[0]);
File[] files = Dir.listFiles();
list(splitDir[0]);
}
public void extractJar(JarFile jar, String dest, File destCopy, File
src) throws IOException {
java.util.Enumeration enu = jar.entries();
while (enu.hasMoreElements() == true) {
java.util.jar.JarEntry file = (java.util.jar.JarEntry)
enu.nextElement();
java.io.File f = new java.io.File(dest +
java.io.File.separator + file.getName());
System.out.println(file.getName());
if(!f.exists())
{
f.getParentFile().mkdirs();
}
if (file.isDirectory()) { // if its a directory, create it
f.mkdir();
continue;
}
java.io.InputStream is = jar.getInputStream(file); // get the
input stream
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
while (is.available() > 0) { // write contents of 'is' to 'fos'
fos.write(is.read());
}
fos.close();
is.close();
}
boolean copied = false;
while (enu.hasMoreElements() == false && copied == false) {
copyFolder(src, destCopy);
copied = true;
}
}
public void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + "
to " + dest);
}
}
public void list(String directoryName) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
//files.add(file);
try {
createJar(chosenDir, chosenDir, file.getParent() +
"/");
} catch (IOException e) {
e.printStackTrace();
}
} else if (file.isDirectory()) {
list(file.getAbsolutePath() + "/" + file.getName() +
"/");
}
}
}
public boolean createJar(String jarName, String jarPath, String
subDirectoryPath)
throws IOException
{
//String jarName = jarName;
boolean status = false;
JarFile finalJarFile = null;
JarOutputStream jar = new JarOutputStream(new
FileOutputStream(jarName),new Manifest());
System.out.println(jarName + " created.");
try {
// Allocate a buffer for reading the input files.
byte[] buffer = new byte[1024];
int bytesRead;
File folder = new File(subDirectoryPath);
String fileList[] = folder.list();
// Loop through the file list.
for (int i = 1; i < fileList.length; i ++)
{
// Get the file name.
String fileName = fileList[i];
System.out.println("filename is "+fileName);
try
{
// Open the file.
FileInputStream file = new FileInputStream(subDirectoryPath +
fileName);
try
{
// Create a jar entry and add it to the jar.
JarEntry entry = new JarEntry(fileName);
jar.putNextEntry(entry);
// Read the file and write it to the jar.
while ((bytesRead = file.read(buffer)) != -1)
{
jar.write(buffer, 0, bytesRead);
}
System.out.println(entry.getName() + " added.");
}
catch (Exception ex)
{
System.out.println(ex);
}
finally
{
file.close();
}
}
catch (IOException ex)
{
System.out.println(ex);
}
}
}
finally {
jar.close();
status = true;
System.out.println(jarName + " closed.");
}
return status;
}
}
Hi i am creating an application that installs files into a selected jar. I
can't figure out how to fix the error in my list(Dir); method, It
recognizes all files and directories but when it tries to change its
directory (list(DIRECTORY);) it changes it to /originalDirectory/subFolder
i want to add a / after subFolder i've tried to do DIRECTORY + "/". But it
doesn't work any ideas? please.
My code:
public class DisplayContent extends JPanel implements ActionListener {
public DisplayContent() {
handleGraphics();
}
public String chosenDir = null;
public JButton btnInstall;
public JButton btnDone;
public boolean done = false;
private void handleGraphics() {
setLayout(null);
JLabel paneTitle = new JLabel();
paneTitle.setFont(new Font("Comic Sans MS", Font.BOLD, 20));
paneTitle.setBounds(55, 6, 330, 62);
paneTitle.setBackground(new Color(237, 237, 237));
paneTitle.setText("The Halo Ultimate Mod Installer");
add(paneTitle);
btnInstall = new JButton("Click Me To Install The Halo Ultimate
Mod");
btnInstall.setBounds(16, 134, 414, 47);
btnInstall.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
install(chosenDir);
} catch (IOException e) {
e.printStackTrace();
}
done = true;
btnDone.setVisible(true);
btnInstall.setVisible(false);
}
});
add(btnInstall);
btnDone = new JButton("Finish Installation of Halo Ultimate Mod");
btnDone.setBounds(16, 134, 414, 47);
btnDone.setVisible(false);
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
installFinish(chosenDir);
} catch (IOException e) {
e.printStackTrace();
}
}
});
add(btnDone);
final JButton forgeFolder = new JButton("Select Forge Jar File!
Important!");
forgeFolder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
chosenDir = getSelectedDir(forgeFolder);
}
});
forgeFolder.setBounds(16, 80, 414, 47);
add(forgeFolder);
}
public static String[] splitDir;
public void install(String dir) throws IOException {
JarFile Jar = new JarFile(new File(dir));
String jar = dir;
String absolutePath = new File("").getAbsolutePath();
File halo = new File(absolutePath + "/mods/");
splitDir = dir.split(".jar");
getMod(jar, halo, Jar);
System.out.print(" --- NEW DIR2 --- " + absolutePath);
System.out.print(" --- NEW DIR --- " + chosenDir);
}
public String jarName;
public String getSelectedDir(Component parent){
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode( JFileChooser.FILES_ONLY );
if( fc.showOpenDialog( parent ) == JFileChooser.APPROVE_OPTION )
{
jarName = fc.getSelectedFile().getName();
return fc.getSelectedFile().getAbsolutePath();
}
return null;
}
public void actionPerformed(ActionEvent e) {}
public void getMod(String jar, File src, JarFile jarFile) {
File folder = new File(splitDir[0] + "/assets");
try {
extractJar(jarFile, splitDir[0], folder, src);
} catch (IOException e) {
e.printStackTrace();
}
}
public void installFinish(String dir) throws IOException {
File Jar = new File(dir);
File Jar2 = new File(dir);
Jar.delete();
File Dir = new File(splitDir[0]);
File[] files = Dir.listFiles();
list(splitDir[0]);
}
public void extractJar(JarFile jar, String dest, File destCopy, File
src) throws IOException {
java.util.Enumeration enu = jar.entries();
while (enu.hasMoreElements() == true) {
java.util.jar.JarEntry file = (java.util.jar.JarEntry)
enu.nextElement();
java.io.File f = new java.io.File(dest +
java.io.File.separator + file.getName());
System.out.println(file.getName());
if(!f.exists())
{
f.getParentFile().mkdirs();
}
if (file.isDirectory()) { // if its a directory, create it
f.mkdir();
continue;
}
java.io.InputStream is = jar.getInputStream(file); // get the
input stream
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
while (is.available() > 0) { // write contents of 'is' to 'fos'
fos.write(is.read());
}
fos.close();
is.close();
}
boolean copied = false;
while (enu.hasMoreElements() == false && copied == false) {
copyFolder(src, destCopy);
copied = true;
}
}
public void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + "
to " + dest);
}
}
public void list(String directoryName) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
//files.add(file);
try {
createJar(chosenDir, chosenDir, file.getParent() +
"/");
} catch (IOException e) {
e.printStackTrace();
}
} else if (file.isDirectory()) {
list(file.getAbsolutePath() + "/" + file.getName() +
"/");
}
}
}
public boolean createJar(String jarName, String jarPath, String
subDirectoryPath)
throws IOException
{
//String jarName = jarName;
boolean status = false;
JarFile finalJarFile = null;
JarOutputStream jar = new JarOutputStream(new
FileOutputStream(jarName),new Manifest());
System.out.println(jarName + " created.");
try {
// Allocate a buffer for reading the input files.
byte[] buffer = new byte[1024];
int bytesRead;
File folder = new File(subDirectoryPath);
String fileList[] = folder.list();
// Loop through the file list.
for (int i = 1; i < fileList.length; i ++)
{
// Get the file name.
String fileName = fileList[i];
System.out.println("filename is "+fileName);
try
{
// Open the file.
FileInputStream file = new FileInputStream(subDirectoryPath +
fileName);
try
{
// Create a jar entry and add it to the jar.
JarEntry entry = new JarEntry(fileName);
jar.putNextEntry(entry);
// Read the file and write it to the jar.
while ((bytesRead = file.read(buffer)) != -1)
{
jar.write(buffer, 0, bytesRead);
}
System.out.println(entry.getName() + " added.");
}
catch (Exception ex)
{
System.out.println(ex);
}
finally
{
file.close();
}
}
catch (IOException ex)
{
System.out.println(ex);
}
}
}
finally {
jar.close();
status = true;
System.out.println(jarName + " closed.");
}
return status;
}
}
Subscribe to:
Comments (Atom)