text stringlengths 8 267k | meta dict |
|---|---|
Q: How can i use long-clicks in MonoDroid? in the moment i'm using long-clicks this way:
button.SetOnLongClickListener(new MyLongClickListener());
public class MyLongClickListener : View.IOnLongClickListener
{
public bool OnLongClick(View v)
{
//do something pretty cool
return true;
}
public IntPtr Handle
{
get { throw new NotImplementedException(); }
}
}
But writing a class just to do an easy one or two-liner in the OnLongClick-method seems not to be very smart. So i'm wondering if there is a better solution?
A: The approach of writing a listener class is the way to do it in Java, which is why it's exposed as such in Mono for Android. That said, in Mono for Android you can assign a delegate of type LongClickHandler to the LongClick property if you'd prefer that. if you'd prefer that.
view.LongClick = onLongClick;
private bool onLongClick(View view)
{
// do some stuff
return true;
}
or
view.LongClick = (clickedView) =>
{
// do some stuff
return true;
};
A: See this example code:
[Activity(Label = "My Activity", MainLauncher = true)]
public class Activity1 : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.layout.main);
Button button = FindViewById<Button>(Resource.id.button);
TextView view = FindViewById<TextView>(Resource.id.text);
button.Click += (s, args) => view.Text = "Clicked!";
button.LongClick += (s, args) =>
{
view.Text = "Long click!";
args.ReturnValue = false;
};
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: cakephp: how to destroy cakephp cookies on page refresh and on closing browser window How to destroy cakephp cookies on page refresh or when I close the browser window?
my code:
merry_parents_controller.php
$this->Cookie->write('MerryParent.id',$this->MerryParent->id,false,0);
echo 'cookie MerryParent.id: '.$this->Cookie->read('MerryParent.id');
$this->set('id',$this->Cookie->read('MerryParent.id'));
thanks.
A: Using 0 as the last parameter will mean the cookie will be deleted when the session finishes (browser is closed).
i.e, $this->cookie->time = 0;
If you want to destroy cookies all the time (no idea why), add functionality to do so in your AppController's beforeFilter(), i.e $this->cookie->delete('MerryParent'); (will delete entire MerryParent key).
A: It seems to me that you want to imitate the behavior of flash messages. If that's right, you may be interested in this part of SessionHelper source code.
If I should simplify it for you, it would look like this (in a controller):
$key = 'MerryParent.id';
$value = '';
if ($this->Session->check($key)) {
$value = $this->Session->read($key);
$this->Session->delete($key);
}
If this is not any helpful, please describe more of what you're trying to accomplish. Maybe there is a better way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can a list passed to a function be modofied by another thread in Java? Integer getElement( List<Integer> list ) {
int i = Random.getInt( list.size() );
return list.get( i );
}
The question: while this function has been called from a thread, IS there a way the list passed to this function can be modified by another thread?
A: The list being passed into your function is a reference to a list object. If any other threads have references to the same list object, then this is not thread safe.
A: No. java.util.List doesn't guarantee thread safety. The list can be changed between list.size() and list.get() by another thread. Moreover memory inconsistency is also a problem.
I could think three ways to solve it:
*
*Use immutable list. Collections.unmodifiableList(list) is fine, Guava's ImmuntableList is better.
*Synchronized the list. but you have to synchronize the list instance all over the program.
*List in java.util.concurrent. It's a sophisticated concurrency solution.
A: > Integer getElement( List<Integer> list ) {
>
> int i = Random.getInt( list.size() );
>
> return list.get( i );
>
> }
The question: while this function method has been called from a thread, IS
there a way the list passed to this function can be modified by
another thread?
(first Java doesn't have "functions", it has "methods")
It DEPENDS on the List implementation. Integer is immutable and if you're List implementation is immutable and correctly implemented, then the list cannot be modified and is completely threadsafe.
If you're List implementation is not immutable, then, yes, the list can be modified by another thread.
An example of an immutable List implementation would be, in the excellent Google Guava API, the ImmutableList which extends Java List and which is fully threadsafe. There are other examples of fully immutable List implementation and they are fully threadsafe (and of course are typically meant to be used with completely threadsafe objects, like the fully immutable Integer class).
A:
Is a list passed to a function thread safe in Java?
A list 'passed to a function' is the same as any other list. It is threadsafe if the list is already threadsafe, or if no other thread can see the list.
A: As other have explained there is no way (or it is at least very difficult) for getElement to ensure that the List cannot be modified while the method is accessing it. If another Thread modified is to reduce it size less then random int generated on fist line then the second line will throw IndexOutOfBoundsException.
The only option is to ensure that all threads that have access to the List only do synchronized access. That is:
Integer getElement( List<Integer> list ) {
synchronized(list) {
int i = Random.getInt( list.size() );
return list.get( i );
}
}
// some method that modifies the list
void modify(List<Integer> list ) {
synchronized(list) {
....
}
}
Note that even though getElement will succeed there is no guarantee that the element will still exist in the list when the caller uses that element. To ensure that, the callers also need to synchronize:
// Thread 1
synchronized (list) {
Integer someElement = getElement(list);
use(someElement);
// use can be outside the synchronized block if it is ok to use
// an element that is no longer in the list
}
//Thread 2
synchronized (list) {
modify(list); // call some function that modifies the list
}
A less error-prone approach is to implement a List class that requires it to be locked before it can be accessed. The usage would be as follows:
try {
list.lock();
Integer someElement = getElement(list);
use(someElement);
} finally {
list.unlock();
}
This looks somewhat like the previous approach (and will look even more so with try-with-resources) the difference is that the List methods get/set etc throw an exception if they are being accessed without acquiring a lock.
EDIT: This of course applies only when using mutable lists. The scenario is entirely different when using immutable lists, though you will still need some synchronization mechanism if the element need to be in the list when it is used.
A:
Is a list passed to a function thread safe in Java?
The question: while this function has been called from a thread, IS there a way the list passed to this function can be modified by another thread?
This is about thread-safety and specifically about the list instance. It depends on the concrete class of the list instance is (it's concurrent and mutability behaviors). If that instance is mutable, it matters on the visibility/exposure of that list.
I've modified your example in hopes of better understanding the question and provide more concrete solutions:
private void method1 {
final List<Integer> list = new ArrayList<Integer>();
list.add(Integer.valueOf(1));
// Add the hypothetical mutator from another Thread
new Thread(new Runnable(){
public void run() {
list.clear(); // if this where to happen between first & second access in getElement an IndexOutOfBoundsException would occur
}
}).start();
Integer someInt = getElement(list);
}
// this is not thread-safe
private Integer getElement(List<Integer> list) {
int len = list.size(); // first access to list
int idx = Random.getInt(len);
Integer retval = list.get(idx); // second access to list
return retval;
}
Two ways:
*
*concurrent instances
*immutable
concurrent list instances:
*
*java.util.concurrent.CopyOnWriteArrayList
*java.util.Collections.synchronizedList()
Given the above code, here are some options on how to make getElement thread-safe.
immutable
Best: make list immutable (so that synchronization not necessary)
final List<Integer> list1 = Arrays.asList(1);
// or Guava's ImmutableList
final List<Integer> list2 = ImmutableList.of(1);
// the reference to the underlying mutable list is now hidden
final List<Integer> list3 = getList();
private List<Integer> getList() {
List<Integer> list = new ArrayList<Integer>();
list.add(1); // mutate the list
return Collection.unmodifiableList(list);
}
Con: causes a new problem to solve with the mutator. Understanding the whole problem would be needed to resolve that.
concurrent
1) Defensive copy in getElement() in combination with concurrent instance.
private Integer getElement(Collection<Integer> list) {
final List<Integer> copy;
synchronized (list) { // needed if Collections.synchronized*()
copy = new ArrayList<Integer>(list);
}
return copy.get(Random.getInt(list.size()));
}
Con: performance to copy
2) Rewrite getElement() so that it only uses an iterator with a concurrent instance
// This is just top-of-the-head,
private <T> T getElement(Iterable<T> list) {
synchronized(list) { // needed if Collections.synchronized*()
for(T elem : list) {
// not even distribution of results, look for better algorithm
if (Random.nextBoolean()) {
// this is the one
return elem;
}
}
}
return getElement(list); // put in a better fail-safe than this
}
Con: current implementation does not provide a uniform distribution
There isn't an easy way to solve concurrency.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Poco Process don't exit When using Poco's Process::launch(command,args) I noticed that on a Linux machine the implementation process doesn't die.
When looking at the process it gets a waiting channel of do_exit and a zombie status (Ubuntu).
Somehow it doesn't go away.
Is this normal behaviour?
A: you should get the process handle.
Poco::ProcessHandle handle = Process::launch(command,args)
then use handle to kill or wait
handle.wait; // wait untill process finshes job
Process.kill(handle); // kill process
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Compiler requirement for override and final I can remember that during the discussion about general attributes which finally lead to the new contextual keywords override and final it was suggested that compiler support for these ore some may be optional (I guess it would read in the standard text as "behavior is implementation-specific). But I can not find any trace about this optionality in the FDIS and the corrections afterwards.
But since not finding it is not proof, I have to ask: Is the support as described in 2.11p2, 9.2 and 10.3 of the FDIS for override and final obligatory for a conforming compiler?
Is it for example required that a conforming compiler rejects
class Foo {
void func() override; // Error: not virtual, 9.2p9
};
Or is it still conforming by ignoring override?
A: Yes, it's required that override is not ignored by a conforming implementation. First, override can only appear in the declaration of a virtual member function.
9.2/9:
[...] A virt-specifier-seq shall appear only in the declaration of a virtual member function.
Second, a virtual function which doesn't override a member function of a base class but is marked override makes the program ill-formed.
10.3/7:
If a virtual function is marked with the virt-specifier override and does not override a member function of a base class, the program is ill-formed.
As both are diagnosable rules of the standard it is illegal for a conforming compiler to ignore violations. (1.4/1)
The same reasoning applies to final and the relevant requirements are in 9 [class]/3 and 10.3 [class.virtual]/4.
A: The use of override and final is optional for the programmer, but nowhere does it say that the compiler can ignore them.
This might have been different for the earlier proposals which used attributes instead of keywords. Attributes leave a lot more freedom to the compiler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: IIS7.5 Application Pool, process identity and environment I have web application that have to access local resources, files/folders, to be able to do git clone/pull/push. I've created a separate Application Pool with Process Identity == my own account (Administrator of machine).
But, if I do:
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
The return value:
"C:\\Windows\\system32\\config\\systemprofile\\AppData\\Local"
so, it looks like system profile is still used. git clone and other git operations hangs up, seems like fail to find .ssh keys etc.
The interesting thing, that it worked fine before Windows SP1 update (at least I blame update, since nothing more changed on machine).
A: If already not having it, try setting:
<identity impersonate="false"/>
in web.config
EDIT
I was wrong, you need to have your app pool identity with access to local folder here:
System.Security.Principal.WindowsIdentity.GetCurrent()
EDIT 2
I have found solution. To run application AS you, you need to turn on impersonation after all (app pool setting does not apply on my IIS7.5), but AS A SPECIFIC USER. So, to enable this, you need to turn impersonation on in web.config AND specify user:
<identity impersonate="true" password="o1j2813n" userName="obrad" />
You can also set this through inetmgr:
Either way, after setting this,
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
gives:
C:\Users\obrad\AppData\Local
Another update:
I have been searching for a way to do the same without putting my password in web.config, and can confirm that I get local user folder also when basic impersonation is on
<identity impersonate="true"/>
But under condition that application connects (under app settings -> Connect as...) as me:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Change value of a select list using onclick in href I want to change the select box value using the onClick function of .
<form>
<select id="action">
<option value="a">Add</option>
<option value="b">Delete</option>
</select>
</form>
<a href="#" onClick="">Add</a>
<a href="#" onClick="">Delete</a>
A: <form>
<select id="action">
<option value="a">Add</option>
<option value="b">Delete</option>
</select>
</form>
<a href="#" onClick="document.getElementById('action').value='a'">Add</a>
<a href="#" onClick="document.getElementById('action').value='b'">Delete</a>
OR U can also call this Java Script function for doing this =
function changeval()
{
if(document.getElementById('action').value =='b')
document.getElementById('action').value='a'
else
document.getElementById('action').value='b'
}
<a href="#" onClick="changeval()">Add</a>
<a href="#" onClick="changeval()">Delete</a>
A: I think this is where you are looking for:
<script type="text/javascript">
function changeValue(selectBox, value) {
selectedItem = selectBox[selectBox.selectedIndex];
selectedItem.value = value;
}
</script>
In the onclick you place"
changeValue(document.getElementById("action"), "your value");
from: http://www.webdeveloper.com/forum/showthread.php?t=160118
A: <form>
<select id="action">
<option value="a">Add</option>
<option value="b">Delete</option>
</select>
</form>
<a href="#" onClick="action.value='a'">Add</a>
<a href="#" onClick="action.value='b'">Delete</a>
A: I used a jquery .click and gave an id to the select element
This is the html code
<select id="carsList">
<option value="volvo" id="#volvoOption">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi" id="#audiOption">Audi</option>
</select>
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRgoru_AtWqrY6DWtmVlOvtYoxpdGHlheWUKgn0jpy0R7Z2VjjjDBh78cx1" id="volvoLogo">
<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQBKzqqECaAC5n-cij4sToayeEAjQqAzYcIrRDj1MeP5vo5OlUCvq_CPWHx" id="audiLogo">
And this is the jquery code I used
$( document ).ready(function() {
$("#volvoLogo").click(function(){
$("#carsList option[value='volvo']").attr('selected', 'selected');
});
$("#audiLogo").click(function(){
$("#carsList option[value='audi']").attr('selected', 'selected');
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Internet Explorer Flash blocks My problem is -
i am accessing flash content in IE.I am getting this error all the time.
Error - Alternate HTML content should be placed here. This content requires the Adobe Flash Player. Get Flash .
I installed Adobe Flash Player,but again it's showing same message.
A: This error occurs because you do not have the correct Flash player version installed.
Keep in mind that Flash Player for IE is not the same as Flash Player for other browsers.
Also, try to embed your swf with SWFObject as described here:
SWF object - why should I use it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I remove default markers? I'm using Google Map API V3 and I noticed there are a lot of markers which are here even though I don't need them. For examples, some schools or other places with InfoWindows appearing when clicking on them.
Is there any way I can remove them or is it just not possible?
A: The only markers that should show up on the map are those you add yourself. Care to share your code or a page where we can see this happening?
Update: ok, these aren't really 'markers' in the normal sense of the word, they're just points of interest, which happen to behave like markers in that you can click on them and see infowindows. It seems to me that these might be of the class MapTypeStyleFeatureType, probably of types like poi.medical, poi.park, transit.station.rail and so on. I wonder if you could use the MapTypeStyle. Maybe something like this:
var myStyles =[
{
featureType: "poi",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
var myOptions = {
zoom: 10,
center: homeLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: myStyles
};
You might also want to look at the Styled Map Wizard
Update, July 2016: The Maps API also now has an option you can specify in the MapOptions, clickableIcons, which if you set to false, the icons for these POIs will appear but clicking them doesn't open Google's infowindows. This saves you having to set the styles to hide the icons unless you want to, if all you need to do is prevent the clicks opening the infowindows.
Just set clickableIcons: false in the options you initialise the Map with.
A: You might have a look at custom styled maps.
There is also a wizard that helps to build the options array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "76"
} |
Q: Generating textual images using QImage (qt) I am trying to create images from text using QImage.
As per the documentation here:
http://doc.qt.io/qt-5/qimage.html#Format-enum
We cannot use QImage::Format_Indexed8 with QImage.
I cannot use QImage::Format_Mono or QImage::Format_MonoLSB due to its low quality.
My question is:
*
*What is the best way to create textual image (batch processing) so
that we can get decent quality with minimum file size?
*Is there is any way to do image compression through QT once the image is created to reduce the file size?
A: Here is a sample code that does it:
QImage image(100, 50, QImage::Format_ARGB32_Premultiplied);
QPainter painter(&image);
painter.fillRect(image.rect(), Qt::yellow);
painter.drawText(image.rect(), Qt::AlignCenter | Qt::AlignVCenter, "hello, world");
image.save("output.png");
It creates this image:
The output format is PNG, so it will have good compression without losing any quality.
A: There's this example, which shows you how to use QPainter::drawText and work with fonts:
http://doc.qt.io/archives/qt-4.7/painting-fontsampler.html
QImage::save has support for a variety of formats and quality levels:
http://doc.qt.io/archives/qt-4.7/qimage.html#reading-and-writing-image-files
Although QImage is in QtCore, QPainter and the text drawing routines are in QtGUI. So on a Linux system this will require an X server to be running:
http://www.qtcentre.org/threads/1758-QPainter-in-console-apps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What are the risks of having secure=false in a crossdomain.xml The allow-access-from node has an optional attribute 'secure'. So say the crossdomain.xml on mysite.com has:
<allow-access-from domain="subdomain.example.com" secure="false">
If this is set to true (default), a flash client retrieved over HTTP cannot access data on the mysite.com over HTTPS.
I can only think of one risk in setting secure to false: A user with a poisoned host file or DNS server might be diverted to a flash client on a fake http://subdomain.example.com. This flash client can now access sensitive data on mysite.com (assuming our user is logged in to mysite.com).
Are there any further risks? I assume the data is still encrypted, as the client is connecting to an https server, so it is protected on the transport.
I've read the Flash security white paper, and it didn't go into any details on risks:
http://www.adobe.com/devnet/flashplayer/articles/flash_player10_security_wp.html
Thanks!
A: While any data sent to your SWF will be secure (assuming it's connected to via HTTPS), data sent to the SWF from a third party would not be secure via this setup as you already know.
For example, I log in to your swf with my social security number. The connection to the SWF is secure so I'm "safe" there. However, your SWF sends the login data to your server via HTTP to verify my credentials. Upon receiving valuable data from your server with an unsecured connection, security is compromised.
You're safe if the data is not-important, but by rule of thumb I would always connect HTTPS to HTTPS when it's possible.
Regards-
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Adding two unsigned char variables and result is int There is code:
#include <iostream>
int main(){
unsigned char a = 4, b = 255;
int g = (unsigned char)a + (unsigned char)b;
std::cout << g << std::endl;
return 0;
}
Result:
259
Why the result is 259, not 3? If there are added two unsigned char variables, there should be overflow, result should be 3 and then it should convert from unsigned char 3 to int 3.
A: The addition operation will first promote its operands to int, before doing the addition. This is how C works. If you want to truncate, you need to assign it back into a narrower type, such as unsigned char.
A: Integer arithmetic is never performed on data types smaller than int. For example, for types smaller than int e.g. if two types char and short int are added, they are promoted to int before any arithmetic operation and result is an integer type. If one of the types happened to be larger than int e.g long long int and int then int gets promoted to long long int and the result is long long int.
(§ 4.5/1) - An rvalue of type char, signed char, unsigned char, short
int, or unsigned short
int can be converted to an rvalue of type int if int can represent
all the values of the source type; otherwise, the source rvalue can be
converted to an rvalue of type unsigned int.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Is it normal that my program needs admin rights even to open a file? When I install my .NET program to C:\Program Files and I run it, it doesn't ask for Admin Rights (Win7), but it can't open any file in the application's directory unless I give admin rights to it manually. If it's not on C, it works well.
I know I can add a custom manifest file to my application to ask the user for admin rights, but it'd ask it always, even when it's not required.
I read on SO that that the software shouldn't write anything to Program Files after it has been installed, but it can't even read a file (for example, language files). I have a database file too, which is read and written by the program, so where should I place this file?
So I'm wondering if it is normal not to have access to read a file without admin rights. How can I make the program ask for admin rights only if it's necessary?
EDIT I'm logged on as system admin.
A: A normal User does not have write privileges in the Progrem Files folder. You should be able to read (content) files however. How do you open you for-reading files?
The proper way is to use a designated folder. Using WinForms that would be something like
string dataFolder = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: BOM before doctype due to PHP file management functions I have asked here why my page was not working in IE. The answer was that i had a byte just before the doctype.
However, i check it and re-check it, there is no a white space before doctype, i saved the document as ANSI, as UTF-8 without BOM (all of the with notepad) and it does not go away.
But, i was able to collect some interesting data. My website uses for displaying the content templates. If i select the header (where the problem is) and display it directly in IE, it works!
So i think the bit is added when the files are read from php and displayed.
PHP codes for displaying the content:
function gettemplate ($templatename) {
$filename = './templates/'. $templatename . ".tpl";
return ReadFromFile($filename);
}
The extension of the files is .tpl but it works exactly the same as if it was .html (i have checked it)
How can i solve this issue?
A: When I do a hexdump of your Page:
$ GET http://juancarlosoleacañizares.es/ | hd | head -n 1
00000000 ef bb bf ef bb bf 3c 21 44 4f 43 54 59 50 45 20 |......<!DOCTYPE |
I see two BOM-Markers (two times EF BB BF) which is unusual. Have you checked if the .php-files themselves have BOM-Markers?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Order / sort links in number order using jquery I have a list of links with number ids in the titles, using jQuery how can I order them in id order Highest to lowest
e.g.
<a href="link.html" title="5601">Link</a>
<a href="link.html" title="6001">Link</a>
<a href="link.html" title="7801">Link</a>
<a href="link.html" title="5618">Link</a>
<a href="link.html" title="4101">Link</a>
<a href="link.html" title="2001">Link</a>
to
<a href="link.html" title="7801">Link</a>
<a href="link.html" title="6001">Link</a>
<a href="link.html" title="5618">Link</a>
<a href="link.html" title="5601">Link</a>
<a href="link.html" title="4101">Link</a>
<a href="link.html" title="2001">Link</a>
A: How about this: http://james.padolsey.com/javascript/sorting-elements-with-jquery/
Using this, you could do something along The Lines of
$("a").sortElements(function(a, b){
return $(a).attr("title") < $(b).attr("title") ? 1 : -1;
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Invoke Enumerable.Where (or other overloaded generic method) using reflection There are 2 overloads (or method signatures) of the "Where" method in Enumerable class:
namespace System.Linq {
public static class Enumerable {
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
}
So
var where = typeof(Enumerable).GetMethod("Where")
throws an exception stating an ambiguous match because, of course, there is more than one method with the name "Where", so I tried to differentiate by the parameters:
var types = new[] {
typeof(IEnumerable<>),
typeof(Func<,>)};
var where = typeof(Enumerable).GetMethod("Where", types);
This however doesn't match either of the method signatures, and I'm not sure why.
Generalized question: How do you invoke an overloaded generic method via reflection without iterating over all the methods in the class w/ the same name (i.e., using System.Type.GetMethod(System.String, System.Type[])?
Please help me fix it! Thanks!
A: You can't accomplish this with only GetMethod() because it has limitations with generics. This is how you would do it with GetMethod() properly.
Type enumerableType = typeof(Enumerable);
MemberInfo[] members = enumerableType.GetMember("Where*");
MethodInfo whereDef = (MethodInfo)members[0]; // Where<TSource>(IEnumerable<TSource, Func<TSource,Boolean>)
Type TSource = whereDef.GetGenericArguments()[0]; // TSource is the only generic argument
Type[] types = { typeof(IEnumerable<>).MakeGenericType(TSource), typeof(Func<,>).MakeGenericType(TSource, typeof(Boolean)) };
MethodInfo method = enumerableType.GetMethod("Where", types);
The best way is to just iterate over members since it already contains both MethodInfo definitions for Where<TSource>.
A: You might be interested to see a code snippet I posted in this other answer:
It's a more general way to get any generic method via an extension method, with clean syntax that looks like:
var where = typeof(Enumerable).GetMethod(
"Where",
typeof(IQueryable<Refl.T1>),
typeof(Expression<Func<Refl.T1, bool>>
);
Notice the Refl.T1 that takes the place of a generic type parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Missing PHP array grandchild I have some code for building a HTML table from PHP.
<?php
function new_table($class)
{
$table = array('class' => $class, 'tr' => array());
return $table;
}
function new_tr(&$table, $class)
{
$tr = array('class' => $class, 'td' => array());
$table['tr'][] = $tr;
return $tr;
}
function new_td(&$tr, $class, $content)
{
$td = array('class' => $class, 'content' => $content);
$tr['td'][] = $td;
return $td;
}
?>
Usage:
$table = new_table('admin whoami');
$tr = new_tr($table, 'head');
new_td($tr, 'field', 'Field');
new_td($tr, 'value', 'Value');
$tr = new_tr($table, 'body');
new_td($tr, 'field', 'Name');
new_td($tr, 'value', $my_name);
echo '--- tr ---'.chr(10);
var_dump($tr);
echo '--- table ---'.chr(10);
var_dump($table);
And the result:
--- tr ---
array(2) {
["class"]=>
string(4) "body"
["td"]=>
array(2) {
[0]=>
array(2) {
["class"]=>
string(5) "field"
["content"]=>
string(4) "Name"
}
[1]=>
array(2) {
["class"]=>
string(5) "value"
["content"]=>
string(5) "user0"
}
}
}
--- table ---
array(2) {
["class"]=>
string(12) "admin whoami"
["tr"]=>
array(2) {
[0]=>
array(2) {
["class"]=>
string(4) "head"
["td"]=>
array(0) {
}
}
[1]=>
array(2) {
["class"]=>
string(4) "body"
["td"]=>
array(0) {
}
}
}
}
If you note, var_dump($tr) correctly dumps the tr, including child td elements.
However, var_dump($table), while correctly var_dumping the tr elements, does not var_dump the grandchild td elements -- note the empty array ["td"]=> array(0) { }
Do you know why this might be happening?
Does it have something to do with the returned $tr element being a copy, not a reference, of a $table['tr'] element? In which case, why does adding a tr to the table work, when adding a td to a tr doesn't?
Thanks!
A: The problem lies in your new_tr() function:
function new_tr(&$table, $class)
{
$tr = array('class' => $class, 'td' => array());
$table['tr'][] = $tr;
return $tr;
}
The way you created $tr here, means it's a regular variable that will be copied when necessary. It does get added to $table, because that is a reference.
PHP uses copy on write, so when the code returns the $tr you add to $table and the $tr you return are actually still one and the same variable.
But when you go and write to it in new_td(), PHP determines it needs to make a copy because it's not a reference to something. So at this point the $tr in your calling script and the corresponding $tr in your $table array are actually two separate variables/values. So new_td() got a copy of that $tr, instead of the exact same one you created in new_tr().
To fix this, you need to make the new_tr function actually create a reference to the TR and also return the TR it created as a reference:
// Return the created TR as a reference by adding the ampersand here.
function &new_tr(&$table, $class)
{
$tr = array('class' => $class, 'td' => array());
// The TR in $table needs to be a reference to the value we're returning
// because we want to modify this exact variable instead of some copy.
$table['tr'][] =& $tr;
return $tr;
}
Now when you run it and your code calls new_td($tr), it is actually modifying the variable that you added to $table:
$table = new_table('admin whoami');
$tr =& new_tr($table, 'head');
new_td($tr, 'field', 'Field');
// EDIT: Note how you need to create a reference here aswell. This is to
// make $tr a reference to the return value of new_tr() instead of a value copy.
$tr =& new_tr($table, 'body');
echo '--- table ---'.chr(10);
var_dump($table);
results in:
--- table ---
array(2) {
["class"]=>
string(12) "admin whoami"
["tr"]=>
array(2) {
[0]=>
array(2) {
["class"]=>
string(4) "head"
["td"]=>
array(1) {
[0]=>
array(2) {
["class"]=>
string(5) "field"
["content"]=>
string(5) "Field"
}
}
}
[1]=>
&array(2) {
["class"]=>
string(4) "body"
["td"]=>
array(0) {
}
}
}
}
A: $table['tr'][] = $tr;
This line will add the created tr to the array, but note that once you return $tr, it lives it's own life. When you modify it, the value won't be updated in the table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Relational querying in mongo I have the following models in my app and I am using mongoid
User, Account, Office and Leads
A user has many accounts and an account belongs to a user
An account has many offices and an office belongs to an account
An office has many leads and a lead belongs to an office
Now I want to query such that I want to get the leads belonging to the offices of accounts of a user, like `
@accounts = Account.where(:user => user)
Now I want to get the leads of the offices belonging to @accounts. Is there a decent way to accomplish it? or I have to iterate over each account and get the offices belonging to that account and then ultimately find the leads.
I could persist the account information in the leads itself so that they contain both the account and office information so that I can query in one shot. But is that the right way?
Suggestions?
A: If these are "contains" relationships consider embedding rather than linking. For example if all leads belong to one office you could embed them therein:
{ office:"...", leads : [ { ... }, { ... } ] }
Likewise the offices could be embedded in an account document. And so forth.
However whether the above makes sense depends on the operations you plan to do (if fully embedded a query such as "give me all leads" if more work). Also there is a maximum document size of 16MB.
Likely some combination of embedding and linking is appropriate. When linking you have to do it client side as you mentioned. See the schema design and "reaching into objects" pages on mongodb.org.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to detect the back button I've set up a page where I'm using the following code so when you click on a link the content and URL changes without refreshing:
window.history.pushState("object or string", "title", "/photo.php");
But when a user clicks on the back button the content doesn't change back. How to detect the back button?
A: You can use onpopstate, like this. It will be fired when the navigation buttons are used, too.
http://jsfiddle.net/54LfW/4/
window.onpopstate = function(e) { // executed when using the back button for example
alert("Current location: " + location.href); // location.href is current location
var data = e.state;
if(data) {
alert(JSON.stringify(e.state)); // additional data like your "object or string"
}
};
A: This answer is already given, but I will try to explain what I understand using pushState
Consider your url is "google.com/gmail"
1.Make currentURL as temp URL, so your browser will show this URL. At this step, there will be one URL in the stack i.e google.com/gmail#!/tempURL.
history.replaceState(null, document.title, location.pathname+"#!/tempURL");
2.Push the previousURL as new state so now your browser will show previousURL i.e google.com/gmail.
history.pushState(null, document.title, location.pathname);
Current state of the stack
First element : google.com/gmail
Last element : google.com/gmail#!/tempURL
3.Now add listener to listen event
window.addEventListener("popstate", function() {
if(location.hash === "#!/tempURL") {
history.replaceState(null, document.title, location.pathname);
//replaces first element of last element of stack with google.com/gmail so can be used further
setTimeout(function(){
location.replace("http://www.yahoo.com/");
},0);
}
}, false);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can i use IP address in URL properties of Windows Media Player in VB6.0? I am trying to make a client server connection in vb 6.0 and stream video in server machine from a client machine.. my doubt is, can i keep the URL in properties of Windows media player as an "IP address" of client machine???
eg.
Const FILE_TO_OPEN = "\\127.0.0.1\C:\Users\Public\Videos\Sample Videos\Wildlife.wmv"
Wmp1.URL = FILE_TO_OPEN
(instead of 127.0.0.1 ,any IP address in the network can be used)
So far what i have created is, i have connected the server and client using winsock... after connecting i need to access the video file present in client's machine and play that video in wmp of server machine.
If i use it without IP address, that is, if i play a video present in the same machine its working(without connecting client-server)
eg.
Const FILE_TO_OPEN = "C:\Users\Public\Videos\Sample Videos\Wildlife.wmv"
Wmp1.URL = FILE_TO_OPEN
If i cannot use IP ADDRESS IN THAT PLACE, WHAT ELSE AND HOW CAN I USE IT??? any suggestions are welcome... thanks in advance!!
A: Your question isn't that clear what you actually want to achieve but UNC paths can be used to access any SMB/Samba/Windows share over the network.
You can use IP addresses in place of any (resolvable) name in a UNC, but the UNC path you gave is most likely invalid.
If you're referring to a local path, you can either use the local machine name and public share name or just use a local path.
If your data is available over some other transport (HTTP, RTSP, carrier pigeon, etc) then you need to use an appropriate URL and scheme.
Update:
On rereading it, it sounds liek you want to transfer the video using your own socker ("server and client using winsock") for whihc media player won;t have any idea about unless you make it use one of the standards like HTTP, RTP or SMB. Your best bet is to use one of these known formats.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to get list of Css class use in the HTML file? I need list of classes used in an html file. Is there any tool where i can get list of classes in the HTML file?
A: If you've got jQuery on the page, run this code:
var classArray = [];
$('*').each(function(){if(this.className!=""){classArray.push(this.className)}})
The variable classArray will contain all the classes specified on that HTML page.
A: Pure Javascript Code will list all the unique classes.
var lst=[];
document.querySelectorAll("[class]").forEach( (e)=>{
e.getAttribute("class").split(" ").forEach( (cls)=>{if( cls.length>0 && lst.indexOf(cls)<0) lst.push(cls);}
);
});
console.log(lst.sort());
A: This should work and it doesn't need jquery:
const used = new Set();
const elements = document.getElementsByTagName('*');
for (let { className = '' } of elements) {
for (let name of className.split(' ')) {
if (name) {
used.add(name);
}
}
}
console.log(used.values());
A: Take a look at Dust Me Selectors.
It's not exactly what you are looking for, it shows a list of UNused selectors. However, I imagine you could use the inverse of the list it provides.
Here is the link: http://www.sitepoint.com/dustmeselectors/
A: I know this is an old question, but got here through google so I suspect more people can get here too.
The shortest way, using querySelectorAll and classList (which means, browser support could be an issue: IE10 for classList and IE8 for querySelectorAll ), and with duplicates, would be:
var classes = 0,
elements = document.querySelectorAll('*');
for (var i = 0; i < elements.length; i++) {
classes = classes + elements[i].classList.length;
}
I made a jsFiddle with a fallback for classList (which has the "lowest" browser support) that also counts all elements, all classes and all elements with classes if you're not using classList.
I didn't add a unique detection though, might get to it some day.
A: Quickly list classes from console (ignoring 'ng-*' angular classes)
(global => {
// get all elements
const elements = document.getElementsByTagName('*');
// add only unique classes
const unique = (list, x) => {
x != '' && list.indexOf(x) === -1 && x.indexOf('ng-') !== 0 && list.push(x);
return list;
};
// trim
const trim = (x) => x.trim();
// add to variable
global.allClasses = [].reduce.call(elements, (acc, e) => e.className.split(' ').map(trim).reduce(unique, acc), []).sort();
console.log(window.allClasses);
})(window);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Accessing WebService Exception (SOAP-Fault) in Struts2 application I'm developing a WebService with JAX-WS. In this WebService, I have a "DatabaseQueryFault" as SOAP-Fault:
<wsdl:operation name="executeCustomQuery">
<wsdl:input message="tns:executeCustomQueryRequest"></wsdl:input>
<wsdl:output message="tns:executeCustomQueryResponse"></wsdl:output>
<wsdl:fault name="DatabaseQueryFault" message="tns:DatabaseQueryFault"></wsdl:fault>
</wsdl:operation>
<xsd:element name="databaseQueryFault" type="tns:databaseQueryFault" />
<xsd:complexType name="databaseQueryFault">
<xsd:sequence>
<xsd:element name="reason" type="xsd:string" minOccurs="0" />
</xsd:sequence>
</xsd:complexType>
The implementing Java-method has this header
public QueryResponseResultset executeCustomQuery(ExecuteCustomQuery parameters)
throws RemoteException, DatabaseQueryFault {
Every time an exception is thrown, for example a SQLException, I "transform" it into an DatabaseQueryFault:
} catch (Exception e) {
throw new DatabaseQueryFault(e.getMessage());
}
This works very fine until here: if I send an incorrect query, I get a soap response containing the DatabaseQueryFault including all the data
<soapenv>
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server.generalException</faultcode>
<faultstring></faultstring>
<detail>
<ns1:databaseQueryFault xmlns:ns1="http://daga/knowledgebase/webservice">
<reason>Unknown column 'test14' in 'field list'</reason>
</ns1:databaseQueryFault>
<ns2:exceptionName xmlns:ns2="http://xml.apache.org/axis/">
daga.knowledgebase.webservice.DatabaseQueryFault
</ns2:exceptionName>
<ns3:stackTrace xmlns:ns3="http://xml.apache.org/axis/">
But now there comes the problem :-) My WebService Client is a Struts2 web app. There I use the native exception handling of struts2 (struts.xml):
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="error" />
</global-exception-mappings>
Now I want to access the details of my soap error within my jsp error page, but the fields are empty:
<p>
<s:property value="exception" /><br />
<s:property value="exception.message" /><br />
<s:property value="exception.reason" />
</p>
How can I access the data of my WebService exception in my jsp file?
A: Well, you don't have direct access to a real exception, unless you create and throw one.
Whether you handle this case with S2 exception handling (I'm kind of "meh" on that in this case) or not, you'll need to turn the return message into something of value to the user. You could transform the XML into something human-readable, or create an exception capturing the relevant information that's specific to your app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to animate each line of text with jquery? Is it possible to reveal text one line at at time in jquery? I know it can be done in flash I have an example here http://iliketoplay.dk/#/blog/deff. On the video playing, the mouse clicks a circle which opens a box that contains text but each line of text is displayed one at a time with a really cool looking effect. Can it be recreated?
A: This shouldn't be a problem, but the solution depends on your input format. You need to chunk up the text in lines which can be done like this:
var lines = text.split("\n");
Then you can do something with each line as you desire, e.g:
var timer,
displayLine = function(){
var nextLine = lines.shift();
if(nextLine){
var newLine = $('<span class="initState">' + nextLine + '</span>');
$('#someContainer').append(newLine);
newLine.animate({ [PUT SOME ANIMATION HERE] }, 1000);
}
timer = setTimeout(displayLine,3000);
}
}
timer = setTimeout(displayLine,3000);
See a complete example here: http://jsfiddle.net/7dd52/
A: You just use div for each line and then animate that certain ...
<div class="first">first line</div>
<div class="second">second</div>
$(".first").animate({'left':'-15px'}, 1000);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Get Changes in Visits from Google Analytics Api I'm, trying to download some Google Analytics data from their API.
I can download my visitors number.
When you use the Google Analytics webpage you can see a percents of Changes in visits, but how do I get that info from their API?
I could try to calculate it by my self, but I have no idea of what algorithm they use.
More info about the API can be found here. Data Feed Query Explorer
edit
Final formula
Visits over the last 30 days
StartDate = today.Year, today.Month - 1, today.Day
EndDate = today.Year, today.Month, today.Day - 1
Visits between 31 and 60 days ago
StartDate = today.Year, today.Month - 2, today.Day
EndDate = today.Year, today.Month -1, today.Day - 1
A: Quoting from my answer here,
The formula is pretty simple (excluding today's data):
(Visits over the last 30 days - Visits between 31 and 60 days ago) /
(Visits between 31 and and 60 days ago).
You can see it in action in the interface if you go to the default dashboard, where it shows you the last 30 days, then on the calendar, click "Compare to past" and select the default amount. It'll show you the numbers used for each calculation and the calculations as they appears in that account list.
The API does not, however, expose pre-calculated numbers (for example, they don't compute bounce rate for you; they just give you the pieces for it.)
So, you'd need to do two API requests to get this data. One for ga:visits in the last 30 days, and then one for ga:visits in the 30 days prior.
Then, when you get it, just subtract, divide, and multiply by 100, and you'll have the percent you're looking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: z-index set to highest but still appears beneath z-index is set to 350 but when you hover over the twitter image the popup still appears beneath? I would be forever grateful if you could take a look at the html and css:
Thanks a million.
Kelly.
A: Change this:
#home .carousel {
width: 475px;
float: left;
display: block;
overflow: hidden;
background: ...
}
to this
#home .carousel {
width: 475px;
float: left;
display: block;
overflow: visible;
background: ...
}
It seems to solve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android: reading Preferences in code Is there a way to perform an action related to a Preference in a PreferenceActivity? I've been using this:
CheckBoxPreference thing = (CheckBoxPreference) findPreference("thing");
thing.setChecked(true);
The first line runs okay but the second line results in a NullPointerException. These lines are inside the onCreate() method in my code. Ideally I want to use an onClicked() signal so that I can run certain methods when preferences are changed. Does anyone know what I'm doing wrong?
A: I think you should be using an onSharedPreferenceChangedListener which you can set on a PreferenceScreen
http://developer.android.com/reference/android/preference/PreferenceScreen.html
A: thing is NULL -- > maybe then prefference with 'thing' refference doesn't exist
I recomend you to read this Question
A: public Preference findPreference (CharSequence key), so what is the thing argument ⇒ try findPreference("thing")
Update: That blog entry may be of use to you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: HTML5 Canvas Fill Complicated Shape I have the following snipper of code:
context.beginPath();
context.moveTo(284 + xoff, 119 + yoff);
context.bezierCurveTo(46 + xoff, 189 + yoff, 39 + xoff, 60 + yoff, 243 + xoff, 29 + yoff);
context.moveTo(284 + xoff, 119 + yoff);
context.bezierCurveTo(239 + xoff, 130 + yoff, 104 + xoff, 105 + yoff, 243 + xoff, 29 + yoff);
context.strokeStyle = "#e2252c"; // line color
context.stroke();
context.closePath();
Everytime I fill this shape despite the outline being a kind of saturn ring, the fill seems to fill it in as a half oval, is there a way you can make fill only fill between the lines I have set. I have tried clipping but this didn't work ever. Am I missing something?
A: The issue here is that you are jumping around. Think of creating your path like working with an Etch-a-Sketch. You can't draw one line, then jump over to another point and draw another. Instead you have to draw one, then continue from where you stopped. In order for this to work, you need to do the following:
*
*beginPath
*moveTo
*bezierCurve for first line to opposite end point
*bezierCurve back to to the point that you did the moveTo to
*stroke
*fill
The following worked for me (just my second curve needs to be tweaked to meet your needs):
context.beginPath();
context.moveTo(284 + xoff, 119 + yoff);
context.bezierCurveTo(46 + xoff, 189 + yoff, 39 + xoff, 60 + yoff, 243 + xoff, 29 + yoff);
context.bezierCurveTo(46 + xoff, 189 + yoff, 39 + xoff, 60 + yoff, 284 + xoff, 119 + yoff);
context.closePath();
context.strokeStyle = "#e2252c"; // line color
context.fillStyle = "#2C6BA1";
context.stroke();
context.fill();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JButton with Image inside the JTable. How to make it animated? I'm encountering a bit of trouble here.
My purpose is to add GIF image into a Button, and send that button into the JTable.
First of all, I made a jtable with customized code.
private javax.swing.JTable Tbl_Monkey = new javax.swing.JTable();
Tbl_Monkey.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null, null, null, null, null, null}
},
new String [] {
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"
}
) {
boolean[] canEdit = new boolean [] {
true, false, false, false, false, false, false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
@Override
public Class getColumnClass(int columnIndex) {
return JButton.class;
}
});
Tbl_Monkey.setDefaultRenderer(JButton.class, new JButtonTableRenderer());
And also I made its customized JTable renderer.
public class JButtonTableRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
return (JButton) value;
}
}
After that, I set the Icon (GIF) of the JButton then passing it right into the JTable by using DefaultTableModel,
And it fits perfectly into the JTable,
but the animated GIF is not animating.
DefaultTableModel oDtb = (DefaultTableModel) Tbl_Monkey.getModel();
oDtb.addRow(oTheObjectArrayofJButton);
I realized if I just make the JButton outside of the JTable, the Icon (GIF) would animates.
But if I put the JButton inside the JTable, it doesn't animate. Unless if I click that Button... then the animation came, but that only 1 frame. I should re-click to get the animation of that GIF on the clicked button. THat's not good....
How to solve it out?
A: I believe the cause of your problem is that JTable use JButton to render the cell, unless you are editing the given cell which then makes JTable use JButton as the cell editor.
When JTable use JButton as cell renderer, it probably just tells JButton to draw itself in the given cell, and that's it. I'm not quite sure which approach SWING takes with regard to drawing the animated GIF on JButtons, but i would think that there is a thread doing some background work. However, in the case of JTable, we're not dealing with a real button and thus it's not repainted.
I don't have a true and tried suggestion as to how you can solve your problem other than recommending another post which goes on about nearly the same issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NodeJS+MySQL instead of PHP+MySQL. Is it ok? I've read about NodeJS but couldn't find its dis/advantages. Can i replace a PHP/MySQL application with NodeJS/MySQL? is it good idea?
Please consider a PHP CMS. Can NodeJS do as well as PHP? Is NodeJS only suitable for some lightweight actions?
If it is ok, which MySQL module is the best one?
A: You can. Its fast.
Benchmarking :
http://zgadzaj.com/benchmarking-nodejs-basic-performance-tests-against-apache-php
Interaction with MySQL is pretty complex. If you have a firm background on node.js it shouldn't be a problem.
But the PHP developers have made interaction with MySQL the easiest and cleanest.
http://www.giantflyingsaucer.com/blog/?p=2596
http://utahjs.com/2010/09/22/nodejs-and-mysql-introduction/
For me, I'd use PHP / MySQL
A: It would be helpful if you wrote a bit detail about your php application. The decision will depend on lot many things, like -
*
*How vast is your application? It will impact the time you need to port a php application to node. You may also have to consider you expertise on async style programming in javascript.
*You wrote you are at the optimization step. Php is there for a long time. It should be easier to apply optimization techniques than rewriting everything in a different platform at this late stage, of course I'm assuming that time is a crucial factor for you, as it is in software industry.
*How slow your application is? Is it executing slowly or not scaling up with increased load? Language performance is hardly the bottleneck for web applications. Have you tried optimizing your queries, adding proper indexing to your db, trying a better web server and/or caching? Look around, you'll get several times more resource on how to optimize php applications than how to do something in node.
*Have you considered investing on hardware? May that be a cheaper option than redoing everything?
To be short, node is still exploring its possibilities, if you want to learn it, now is the best time. But if that learning involves messing with production level applications, my suggestion is no. node will not magically improve the performance of your application, it was not built for that purpose.
To answer your another question- most people prefer Felixge's MySQL driver: https://github.com/felixge/node-mysql
And here is another alternative: https://github.com/sidorares/nodejs-mysql-native
A: Before getting into Node.js hype, read the following article.
Basically, Node.js HAS issues.
It's a server, but you can connect to MySQL via Node and send data to the user. There are many pitfalls, one of them being that you must know JS and you'll have to format your output via JS instead of PHP.
However, your bottleneck will almost never be PHP, unless you do some stuff that PHP wasn't designed for (like loading 1 million entries in an array and doing various searches using that array and what not).
What you'll find to be your bottleneck (in case of a busy website) is the HTTP server since you'll probably exceed memory due to each connection requiring certain amount of memory and of course - your DB will be (most likely) I/O bound (hdd bound).
In this whole process, PHP will be the least of your worries. Using programs written in C or for Node won't help speed things up, as you'll have to scale your database system - which is a whole different story (plus you'll need to scale your HTTP server setup).
Basically - stick with PHP/MySQL, forget about Node, at least for now.
Update: since this answer is accepted and technology caught up, it's good to warn new people: Node.js became popular beyond anyone's wildest dreams and I personally find it awesome. I'm lucky enough to be able to use both node and php interchangeably.
Node has great community and awesome packages, package managers and task runners. Anyone familiar with JS is able to work with node instantly. It's great, extremely useful and I see node as something that will propel JavaScript to do what Java was originally designed for (this is opinion based on anecdotal evidence and not a fact).
Bottom line: when choosing a technology, one should choose the one that they're familiar or expressive with. Both PHP and Node.js are great in its own way, there is no definitive way of determining which one is "better".
A: If you have a large existing mysql database that you need to interact with full of legacy code that will be a nightmare to convert to nosql then yes.
Otherwise no, use couch/mongo/redis/riak/cassandra/etc.
Pick a solid noSQL database that fits your requirements.
As for whether node can do what php/mysql can do yes. You can develop websites with it.
Does node have the equivelant of drupal or wordpress that holds your hand and does everything for you? No.
A: You can use https://github.com/masuidrive/node-mysql or https://github.com/sdepold/sequelize . it's one of the best mysql driver for nodejs
A: I am not well experienced in NodeJS. But my points are,
*
*Nodejs is built for creating real-time applications like Chat, Online gaming etc., Because it is really fast.
*NodeJS is a server. So you cannot compare with php, Meaning that you need to go for the third party modules to perform some tasks such as expressjs, node-mysql etc.,
*Creating application with NodeJS is really simple like php-mysql
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Filemaker type environment for MySQL development I have experience of developing FileMaker and MySQL. Im used to developing MySQL longhand in php which is fine, but slow. Conversely, environments like FileMaker are very fast to write and deploy scripts and reports. Is there anything similar to FileMaker that allows me to quickly write queries and reports in MySQL and deploy?
A: Actually, I think the best option might actually be FileMaker. Using the appropriate ODBC driver and FileMaker's External SQL Sources feature, you can use FileMaker to create a front-end to a MySQL database. After using this technology, MySQL tables will appear as FileMaker tables within FileMaker, and you can design layouts (data entry, queries and reports) just as if the tables existed within FileMaker.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: not able to locate entry point for a method in dll? Hi I have a class and I wrote few methods in it. Then I created dll for that class. Now i commented out few methods and then again created dll for the class. But now when i am loading the dll in one of the exe I get the error poped out like this,"NOt able to locate entry point for abc method in xyz dll".
A: Did you recompile the exe?
If not, then please, recompile it, because something has changed in the DLL API.
If yes, then you probably are linking with the old LIB file instead of the new one, and something has changed in the DLL API.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: g++ compile and link options naive question perhaps, are there separate lists of compile and link options for g++, I mean a list that shows which options are for compiling and which are for linking. gcc manual says these are the link options
http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html#Link-Options
and the options other than these are compile options? I am confused while reading the Definite Guide to GCC.
A: There is a grouped list of all options. With overall options such as -c and -o and specific c++ options.
A: If you read the manual for gcc (what you referring to with your link seems to be a version of it, but check man gcc on your machine too), you will find that it has well labelled sections such as "C++ Language Options", "Language Independent Options", "Linker Options" etc. I think this is pretty clear.
A: These option apply specifically in the way described on the linking stage, and some other options may affect the input/output and general behaviour while linking too. So I would say No, options other than this set are not exclusively compile options.
Consider that you also have options for the preprocessor and other stages of compilation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rails 3.1. Cocoon link_to_add_association example needed pls show any example of using Cocoon's 'link_to_add_association' with html_options.
https://github.com/nathanvda/cocoon
Documentation says:
html_options: extra html-options (see link_to) There are two extra options that allow to conrol the placement of the new link-data:
data-association-insertion-node : the jquery selector of the node
data-association-insertion-position : insert the new data before or after the given node.
But i can not understand what to do, if i want insert partial just before my "add element" link. Not just after parent's div begin. This not gonna work:
<%= link_to_add_association "add element", f, :production_years,
:position => "after_all" %>
A: I will admit that is a bit obscure, and maybe I should provide an example in the code.
In your application.js you should write something like:
$(document).ready(function() {
$("a.add_fields").
data("association-insertion-position", 'before').
data("association-insertion-node", 'this');
});
where a.add_fields will select your clickable link. I have only recently updated the readme with a better explanation how the insertion can be handled.
Hope this helps.
A: If you want to do it using data-attributes you can do:
<%= link_to_add_association 'Add Item', f, :items, :data => {"association-insertion-method" => "before" } %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get subarray from array? I have var ar = [1, 2, 3, 4, 5] and want some function getSubarray(array, fromIndex, toIndex), that result of call getSubarray(ar, 1, 3) is new array [2, 3, 4].
A:
const array_one = [11, 22, 33, 44, 55];
const start = 1;
const end = array_one.length - 1;
const array_2 = array_one.slice(start, end);
console.log(array_2);
A:
I have var ar = [1, 2, 3, 4, 5] and want some function
getSubarray(array, fromIndex, toIndex), that result of call
getSubarray(ar, 1, 3) is new array [2, 3, 4].
Exact Solution
function getSubarray(array, fromIndex, toIndex) {
return array.slice(fromIndex, toIndex+1);
}
Let's Test the Solution
let ar = [1, 2, 3, 4, 5]
getSubarray(ar, 1, 3)
// result: [2,3,4]
Array.prototype.slice()
The slice() method returns a shallow copy of a portion of an array
into a new array object selected from start to end (end not included)
where start and end represent the index of items in that array. The
original array will not be modified.
Basically, slice lets you select a subarray from an array.
For example, let's take this array:
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
Doing this:
console.log(animals.slice(2, 4));
Will give us this output:
// result: ["camel", "duck"]
Syntax:
slice() // creates a shallow copy of the array
slice(start) // shows only starting point and returns all values after start index
slice(start, end) // slices from start index to end index
See shallow copy reference
A: Take a look at Array.slice(begin, end)
const ar = [1, 2, 3, 4, 5];
// slice from 1..3 - add 1 as the end index is not included
const ar2 = ar.slice(1, 3 + 1);
console.log(ar2);
A: For a simple use of slice, use my extension to Array Class:
Array.prototype.subarray = function(start, end) {
if (!end) { end = -1; }
return this.slice(start, this.length + 1 - (end * -1));
};
Then:
var bigArr = ["a", "b", "c", "fd", "ze"];
Test1:
bigArr.subarray(1, -1);
< ["b", "c", "fd", "ze"]
Test2:
bigArr.subarray(2, -2);
< ["c", "fd"]
Test3:
bigArr.subarray(2);
< ["c", "fd","ze"]
Might be easier for developers coming from another language (i.e. Groovy).
A: The question is actually asking for a New array, so I believe a better solution would be to combine Abdennour TOUMI's answer with a clone function:
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
const copy = obj.constructor();
for (const attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
// With the `clone()` function, you can now do the following:
Array.prototype.subarray = function(start, end) {
if (!end) {
end = this.length;
}
const newArray = clone(this);
return newArray.slice(start, end);
};
// Without a copy you will lose your original array.
// **Example:**
const array = [1, 2, 3, 4, 5];
console.log(array.subarray(2)); // print the subarray [3, 4, 5, subarray: function]
console.log(array); // print the original array [1, 2, 3, 4, 5, subarray: function]
[http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "353"
} |
Q: database in phone gap for blackberry I am using javascript for creating database in phonegap for blackBerry os4.6
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
function successCB() {
alert("success!");
}
</script>
but am not getting it.Please tell me the solution how to do .
Thanks in Advance
A: use try-catch construction to intercept exceptions which may occur upon opening the database.
Check this link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: same method name in parent and child class?
Possible Duplicate:
why do we need the new keyword and why is the default behavior to hide and not override?
I have a parent and a child class. Both have a method with the same name and compiler allow it. I couldn't understand it. Why compiler has not shown an error in child class if parent has a methoed with the same name. I am not using new virtual or override with methods. Kindly help me understanding this why compiler did not shows an error in child class ?
class BaseClass
{
public string SayHi()
{
return ("Hi");
}
}
class DerivedClass : BaseClass
{
public string SayHi()
{
return (base.SayHi() + " from derived");
}
}
A: The base method must be declared as virtual if you want to override it in a child class:
class BaseClass
{
public virtual string SayHi()
{
return ("Hi");
}
}
class DerivedClass : BaseClass
{
public override string SayHi()
{
return (base.SayHi() + " from derived");
}
}
If the base method is not declared as virtual you will actually get a compiler warning telling you that you are trying to hide this base method. If this is your intent you need to use the new keyword:
class BaseClass
{
public string SayHi()
{
return ("Hi");
}
}
class DerivedClass : BaseClass
{
public new string SayHi()
{
return (base.SayHi() + " from derived");
}
}
UPDATE:
To better see the difference between the two take a look at the following examples.
The first one using a base virtual method which is overriden in the child class:
class BaseClass
{
public virtual string SayHi()
{
return ("Hi");
}
}
class DerivedClass : BaseClass
{
public override string SayHi()
{
return (base.SayHi() + " from derived");
}
}
class Program
{
static void Main()
{
BaseClass d = new DerivedClass();
// the child SayHi method is invoked
Console.WriteLine(d.SayHi()); // prints "Hi from derived"
}
}
The second hiding the base method:
class BaseClass
{
public string SayHi()
{
return ("Hi");
}
}
class DerivedClass : BaseClass
{
public new string SayHi()
{
return (base.SayHi() + " from derived");
}
}
class Program
{
static void Main()
{
BaseClass d = new DerivedClass();
// the base SayHi method is invoked => no polymorphism
Console.WriteLine(d.SayHi()); // prints "Hi"
}
}
A: Since the method is not virtual, there is no problem to have the same name.
Which one is called depends merely on the type of the reference.
BaseClass o = new DerivedClass();
o. SayHi();
will return "Hi".
If you declare the parent method a virtual, then you either have to override it in the subclass or make it new (which is the default).
If you override it the above code will return "Hi from derived".
If you make it new that is the same as if it was not virtual.
A: It is called Name hiding. Please read MSDN article on - Hiding through inheritance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: PCRE regex escaping dot for delimiter I'm trying to extract the title from a remote page, this is the regula expression I'm using:
$remote_page_title = preg_match( '#<title>(.*)</title>#i', $remote_page_body, $new_item_title );
die( html_entity_decode( $new_item_title[1] ) );
The fact is that, if the title contains a #, it is considered as closing delimiter breaking the regex. Is there any way I can escape the dot character to backslash #?
Thanks.
A: Normally this shouldn't be breaking your regex. Either try different delimiter or try using a greedy match (.+).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get parameters for currently running queries in PostgreSQL We wrote a small tool which displays all currently running queries. We get the currently running queries from pg_stat_activity.
The problem is: We dont know the parameters which were given to the query. We can only see the placeholders $1, $2, etc.
Is there any way to get the parameters for a currently running query?
The only workaround could be to enable the query log and parse the parameters from the query log, but this would be a very dirty and slow solution.
A: I don't think it's possible. I have faced the same issue.
A: I use to run all the queries through stored procedures/functions. This way you can add code to make a log at the start of every function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Problem with Fetching the data from Database I'm trying to fetch the details from Database for uploading the files from DDMS to ftp server. Normally, i can done this without using SQLiteDatabase.
But, now i need to upload the files using the ftp server Host, Port, Username, Password which are stored in Database. I've considered this Example to this function. I've this exception when using this method :
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
How can i Clear this error? And how can i pass the values from database to my FTP.
A: 1 is the number of records in your database.
First query your request in database class
and then in you activity
receive cursor
as
Cursor c=db.data();
(data is a method used for query and db is your object of database class)
c.moveToFirst();
while (c.isAfterLast() == false) {
//upload your database
c.moveToNext();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why some of the tables output data in primary key ASC but some not without specifying the order? If I don't specify by what order should the data be output, what's the order mysql output data? What's the factor? Why some of them are ASC but some are DESC judging by their PK?
A: There is no order without the outermost ORDER BY.
*
*A table is just a set of records and sets have no order
*Any pattern you see is arbitrary, not reliable and not repeatable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: php define and after use unset vars (not working) I'm having memory problems with my server (server down right now) so I need to find a way of free memory after use.
My app uses mysql records witch i use as defined variables.
I was guessing I could fill in a array, use values when needed and at the end unset all, but my test doesn't work...
here is my example code, hope you can help, thanks
A: If your server is down the problem can't be a PHP script because there is a memory_limit setting for php script.
Also after the exit of your script every memory allocated is freed automatically
A: You're defining named constants which you then try to store in an array. Why? And what does this have to do with mysql?
What you are calling 'define' variables doesn't define any variables, it creates constants. Read about define and named constants in the PHP manual.
It doesn't make any sense at all to try defining constants with query results.
In PHP you rarely have to thing about memory yourself at all since after every roundtrip the allocated memory of a script will be freed. So your problem is somewhere else. Might be that your memory limit, script execution time or other configuration parameters are not set correctly in the context of your app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating dynamic matrix table using a formula with PHP I am trying to get my head around creating a matrix type table created dynamically using a formula and some predefined numbers, I know a little php but this is far beyond my scope.
Ok I have numerous static widths (mm) eg : 100 , 200, 300, 400, 500 .... up to say 1200.
I also have numerous heights (mm )eg : 50, 60, 70, 80 ... up to say 1500
I have a price start point of £15, this would relate to the minimum width and height, 100 x 50
I then have a formula to multiply the preceding row cell by 1.6 to give a new price.
How would I be able to create a matrix table on the fly using this data? What I am trying to achieve as an example is as below.
width=> 100 200 300 400 500 600
Drop v
50 £15 £24 £38 £61 £98 £157
60 £24 £38 £61 £98 £157 £251
70 £38 £61 £98 £157 £251 £401
80 £61 £98 £157 £251 £401 £643
90 £98 £157 £251 £401 £643 £1028
100 £157 £251 £401 £643 £1028 £1646
I also need to assign all the values to a table in mysql defined as below for each permutation. The records already exist for each width and height permitation.
eg
width : 100
height : 50
price : 15
So I need to get all the prices in a workable array to do an insert into the relevant record in database.
I hope this makes sense and someone can point me in the right direction.
A: Here's how you build the values matrix when the first value is 15.
<?php
$initVal = 15;
$rows = 6;
$cols = 6;
$matrix = array();
for($i = 0; $i < $rows; $i++) {
if($i != 0)
$initVal = round($matrix[$i-1][0]*1.6);
$matrix[$i] = array();
for($j = 0; $j < $cols; $j++) {
if($j == 0)
$matrix[$i][$j] = $initVal;
else
$matrix[$i][$j] = round($matrix[$i][$j-1]*1.6);
}
}
print_r($matrix);
?>
A: 100,200,...........1200---->12 columns
50,60,70,..........1500---->145 rows
echo "<table id='tb'>";
$height=50;
$i=0;
for($i=0;$i<145;$i++)
{
echo "<tr height='".$height."'>";
echo "<td width='100px'>".$value1."</td>";
echo "<td width='200px'>".$value2."</td>";
echo "<td width='300px'>".$value3."</td>";
echo "<td width='400px'>".$value4."</td>";
echo "<td width='500px'>".$value5."</td>";
echo "<td width='600px'>".$value6."</td>";
echo "<td width='700px'>".$value7."</td>";
echo "<td width='800px'>".$value8."</td>";
echo "<td width='900px'>".$value9."</td>";
echo "<td width='1000px'>".$value10."</td>";
echo "<td width='1100px'>".$value11."</td>";
echo "<td width='1200px'>".$value12."</td>";
echo "</tr>";
$height=$height+10;
//here '$value1 to $value12' is caluculated values
}
echo "</table>";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MYSQL dynamic field with content from other fields let's say I have 2 columns in a table, a and b (both plain text).
Is there any way to create a third column c in the same table, with the content of those other columns a and b?
Example:
a/0 = "Peter", b/0 = "Griffin" => c/0 = "Peter Griffin" (space if a != empty)
a/1 = "", b/1 = "The Giant Chicken" => c/1 = "The Giant Chicken" (no delimiter)
This dynamic column c would obviously have to be a read-only field, because there is no way to determine if a space is a delimiter or a regular character.
I use a simple PHP function for getting the contents of a field, so I could have this function check if field c is requested and, if so, return a, maybe a space and b...
But I feel like this isn't the best place to do this check - is there a way to have SQL run this combine procedure?
A: Concatenate them with a simple select
select trim(concat_ws(' ',a,b)) from table
You can adapt my select to an update statement if you need it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: map datatable to model quickly I have a simple problem which I think must have a simple answer... well maybe. :)
I'm writing a MVC3 application. I have an existing database from the previous version of the application, so it's a data driven app. Instead of using EF to access the data and LINQ expressions, I'd prefer to use stored procedures / SQL commands.
What I want to do is run a SQL command, which returns a datatable object and then map this to a model which contains exactly the same fields. Sadly, I'm doing this by hand right now, iterating through the data rows. There must be some better approach?
Thanks for any tips... and for not sniggering at my newbie question.
A: AutoMapper should do the job, check it out here: AutoMapper
there are also plenty of questions and answers about it here on SO:
AutoMapper: Mapping between a IDataReader and DTO object
Automapper Mapping
AutoMapper issue
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Efficiently average the second column by intervals defined by the first column There are two numeric columns in a data file. I need to calculate the average of the second column by intervals (such as 100) of the first column.
I can program this task in R, but my R code is really slow for a relatively large data file (millions of rows, with the value of first column changing between 1 to 33132539).
Here I show my R code. How could I tune it to be faster? Other solutions that are perl, python, awk or shell based are appreciated.
Thanks in advance.
(1) my data file (tab-delimited, millions of rows)
5380 30.07383\n
5390 30.87\n
5393 0.07383\n
5404 6\n
5428 30.07383\n
5437 1\n
5440 9\n
5443 30.07383\n
5459 6\n
5463 30.07383\n
5480 7\n
5521 30.07383\n
5538 0\n
5584 20\n
5673 30.07383\n
5720 30.07383\n
5841 3\n
5880 30.07383\n
5913 4\n
5958 30.07383\n
(2) what I want to get, here interval = 100
intervals_of_first_columns, average_of_2nd column_by_the_interval
100, 0\n
200, 0\n
300, 20.34074\n
400, 14.90325\n
.....
(3) R code
chr1 <- 33132539 # set the limit for the interval
window <- 100 # set the size of interval
spe <- read.table("my_data_file", header=F) # read my data in
names(spe) <- c("pos", "rho") # name my data
interval.chr1 <- data.frame(pos=seq(0, chr1, window)) # setup intervals
meanrho.chr1 <- NULL # object for the mean I want to get
# real calculation, really slow on my own data.
for(i in 1:nrow(interval.chr1)){
count.sub<-subset(spe, chrom==1 & pos>=interval.chr1$pos[i] & pos<=interval.chr1$pos[i+1])
meanrho.chr1[i]<-mean(count.sub$rho)
}
A: You don't really need to set up an output data.frame but you can if you want. Here is how I would have coded it, and I guarantee it will be fast.
> dat$incrmt <- dat$V1 %/% 100
> dat
V1 V2 incrmt
1 5380 30.07383 53
2 5390 30.87000 53
3 5393 0.07383 53
4 5404 6.00000 54
5 5428 30.07383 54
6 5437 1.00000 54
7 5440 9.00000 54
8 5443 30.07383 54
9 5459 6.00000 54
10 5463 30.07383 54
11 5480 7.00000 54
12 5521 30.07383 55
13 5538 0.00000 55
14 5584 20.00000 55
15 5673 30.07383 56
16 5720 30.07383 57
17 5841 3.00000 58
18 5880 30.07383 58
19 5913 4.00000 59
20 5958 30.07383 59
> with(dat, tapply(V2, incrmt, mean, na.rm=TRUE))
53 54 55 56 57 58 59
20.33922 14.90269 16.69128 30.07383 30.07383 16.53692 17.03692
You could have done even less setup (skip the incrmt variable with this code:
> with(dat, tapply(V2, V1 %/% 100, mean, na.rm=TRUE))
53 54 55 56 57 58 59
20.33922 14.90269 16.69128 30.07383 30.07383 16.53692 17.03692
And if you want the result to be available for something:
by100MeanV2 <- with(dat, tapply(V2, V1 %/% 100, mean, na.rm=TRUE))
A: use strict;
use warnings;
my $BIN_SIZE = 100;
my %freq;
while (<>){
my ($k, $v) = split;
my $bin = $BIN_SIZE * int($k / $BIN_SIZE);
$freq{$bin}{n} ++;
$freq{$bin}{sum} += $v;
}
for my $bin (sort { $a <=> $b } keys %freq){
my ($n, $sum) = map $freq{$bin}{$_}, qw(n sum);
print join("\t", $bin, $n, $sum, $sum / $n), "\n";
}
A: Given the size of your problem, you need to use data.table which is lightening fast.
require(data.table)
N = 10^6; M = 33132539
mydt = data.table(V1 = runif(N, 1, M), V2 = rpois(N, lambda = 10))
ans = mydt[,list(avg_V2 = mean(V2)),'V1 %/% 100']
This took 20 seconds on my Macbook Pro with specs 2.53Ghz 4GB RAM. If you don't have any NA in your second column, you can obtain a 10x speedup by replacing mean with .Internal(mean).
Here is the speed comparison using rbenchmark and 5 replications. Note that data.table with .Internal(mean) is 10x faster.
test replications elapsed relative
f_dt() 5 113.752 10.30736
f_tapply() 5 147.664 13.38021
f_dt_internal() 5 11.036 1.00000
Update from Matthew :
New in v1.8.2, this optimization (replacing mean with .Internal(mean)) is now automatically made; i.e., regular DT[,mean(somecol),by=] now runs at the 10x faster speed. We'll try and make more convenience changes like this in future, so that users don't need to know as many tricks in order to get the best from data.table.
A: The first thing that comes in mind is a python generator, which is memory efficient.
def cat(data_file): # cat generator
f = open(data_file, "r")
for line in f:
yield line
Then put some logic in another function (and supposing that you save the results in a file)
def foo(data_file, output_file):
f = open(output_file, "w")
cnt = 0
suma = 0
for line in cat(data_file):
suma += line.split()[-1]
cnt += 1
if cnt%100 == 0:
f.write("%s\t%s\n" %( cnt, suma/100.0)
suma = 0
f.close()
EDIT : The above solution assumed that the numbers in the first column are ALL numbers from 1 to N. As your case does not follow this pattern ( from the extra details in the comments), here is the correct function:
def foo_for_your_case(data_file, output_file):
f = open(output_file, "w")
interval = 100
suma = 0.0
cnt = 0 # keep track of number of elements in the interval
for line in cat(data_file):
spl = line.split()
while int(spl[0]) > interval:
if cnt > 0 : f.write("%s\t%s\n" %( interval, suma/cnt)
else: f.write("%s\t0\n" %( interval )
interval += 100
suma = 0.0
cnt = 0
suma += float(spl[-1])
cnt += 1
f.close()
A: Based on your code, I would guess that this would work the full data set (depending on your system's memory):
chr1 <- 33132539
window <- 100
pos <- cut(1:chr1, seq(0, chr1, window))
meanrho.chr1 <- tapply(spe$rho, INDEX = pos, FUN = mean)
I think you want a factor that defines groups of intervals for every 100 within the first column (rho), and then you can use the standard apply family of functions to get means within groups.
Here is the data you posted in reproducible form.
spe <- structure(list(pos = c(5380L, 5390L, 5393L, 5404L, 5428L, 5437L,
5440L, 5443L, 5459L, 5463L, 5480L, 5521L, 5538L, 5584L, 5673L,
5720L, 5841L, 5880L, 5913L, 5958L), rho = c(30.07383, 30.87, 0.07383,
6, 30.07383, 1, 9, 30.07383, 6, 30.07383, 7, 30.07383, 0, 20,
30.07383, 30.07383, 3, 30.07383, 4, 30.07383)), .Names = c("pos",
"rho"), row.names = c(NA, -20L), class = "data.frame")
Define the intervals with cut, we just want every 100th value (but you might want the details tweaked as per your code for your real data set).
pos.index <- cut(spe$pos, seq(0, max(spe$pos), by = 100))
Now pass the desired function (mean) over each group.
tapply(spe$rho, INDEX = pos.index, FUN = mean)
(Lots of NAs since we didn't start at 0, then)
(5.2e+03,5.3e+03] (5.3e+03,5.4e+03] (5.4e+03,5.5e+03] (5.5e+03,5.6e+03] (5.6e+03,5.7e+03] (5.7e+03,5.8e+03] (5.8e+03,5.9e+03]
20.33922 14.90269 16.69128 30.07383 30.07383 16.53692
(Add other arguments to FUN, such as na.rm as necessary, e.g:)
## tapply(spe$rho, INDEX = pos.index, FUN = mean, na.rm = TRUE)
See ?tapply applying over groups in a vector (ragged array), and ?cut for ways to generate grouping factors.
A: Here is a Perl program that does what I think you want. It assumes the rows are sorted by the first column.
#!/usr/bin/perl
use strict;
use warnings;
my $input_name = "t.dat";
my $output_name = "t_out.dat";
my $initial_interval = 1;
my $interval_size = 100;
my $start_interval = $initial_interval;
my $end_interval = $start_interval + $interval_size;
my $interval_total = 0;
my $interval_count = 0;
open my $DATA, "<", $input_name or die "$input_name: $!";
open my $AVGS, ">", $output_name or die "$output_name: $!";
my $rows_in = 0;
my $rows_out = 0;
$| = 1;
for (<$DATA>) {
$rows_in++;
# progress indicator, nice for big data
print "*" unless $rows_in % 1000;
print "\n" unless $rows_in % 50000;
my ($key, $value) = split /\t/;
# handle possible missing intervals
while ($key >= $end_interval) {
# put your value for an empty interval here...
my $interval_avg = "empty";
if ($interval_count) {
$interval_avg = $interval_total/$interval_count;
}
print $AVGS $start_interval,"\t", $interval_avg, "\n";
$rows_out++;
$interval_count = 0;
$interval_total = 0;
$start_interval = $end_interval;
$end_interval += $interval_size;
}
$interval_count++;
$interval_total += $value;
}
# handle the last interval
if ($interval_count) {
my $interval_avg = $interval_total/$interval_count;
print $AVGS $start_interval,"\t", $interval_avg, "\n";
$rows_out++;
}
print "\n";
print "Rows in: $rows_in\n";
print "Rows out: $rows_out\n";
exit 0;
A: Oneliner in Perl is simple and efficient as usual:
perl -F\\t -lane'BEGIN{$l=33132539;$i=100;$,=", "}sub p(){print$r*$i,$s/$n if$n;$r=int($F[0]/$i);$s=$n=0}last if$F[0]>$l;p if int($F[0]/$i)!=$r;$s+=$F[1];$n++}{p'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: validating $_POST's contain with PHP. that must be number I'd like to validate $_POST's contain, that must be number. How can i check out $_POST's contain with PHP?
for example (what i want as the result):
1876 //true
2.34 // false
erfka // false
1djs33 // false
A: ctype_digit is your friend. It checks that only digits are contained in the variable, not periods or anything other. ctype_digit doesn't even allow negative numbers, but just digits.
It actually also checks that there is a number contained. The empty string is evaluated to false with ctype_digit.
A: It will be better to use ctype_digit!
A: Try using PHP is_numeric function
A: Try with this code -
if(strpos($_POST['number'],'.') === false && is_numeric($_POST['number']))
echo 'Its a numeriac int value';
else
echo 'not a numeric value';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Firemonkey - use HD or 3D? Just been doing a bit of playing with FireMonkey.
If I create a HD application, then I can add buttons etc as normal.
If I create a 3D application, when I add buttons/memo to the form they don't show up.
This is XE2 running Windows 7 under VMWare Fusion (with 3d graphics enabled).
Is there any reason for an app to use an HD form if it's not for graphics/games and it's just a 'business' app with buttons/edits/memos?
What is the difference between them and why does it matter?
Reading Delphi XE2: Why FireMonkey apps are HD? didn't help.
A: HD (or IMO better: 2D) and 3D apps serve different purposes.
The HD apps are more or less like the GUI apps we know, except that the graphics are very flexible and can be animated, etc. That can be used for "business apps" as well as for most other purposes a GUI is used.
The 3D apps show a 2D view of a 3D world. They deal with cubes, spheres, meshes, etc. and merely serve a 3D graphical purpose. You can make nice animations or interactive apps with it, but not necessarily "business apps" as we know them.
One can use 2D (HD) items in 3D, but it takes a little more work. I haven't investigated much time into this, but they must be placed onto something flat in 3D space, AFAIK. The form is not considered as a flat space anymore, so you can't just put a button on a form. You put shapes in space, you must light them, etc.
As Robert Love said in the SO answer you linked to, FireMonkey can do more than just nice HD traditional user interfaces. It leverages the posiblities of the GPU in more than one way.
A: AFAIK, HD applications can manage 3D objects, animations, ... If you plan to create a "business" application, you should choose HD.
3D appllications are more optimized to manage 3D. Useful if you plan to just create 3D stuff.
Source XE2 World Tour
A: You can use HD Application that you can use Button, and many object for your application. If you want to add 3D object just for animation, try to use TViewport3D that can be use as container for 3D object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Populating a String and ListView from database I'm trying to populate a ListView from my SQLite database. I know how to do it using arrays. I need some modifications in the query class of my database class.
I need the complete library and class code for the query and the constructor of the databases. I'm also looking for the code to generate the ListView activity using a query from my own database as the code suggests below:
package com.sqlite.www;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper {
//The Android s default system path of your application database.
private static String DB_PATH = "/data/data/com.sqlite.www/databases/";
private static String DB_NAME = "TheProjectDatabase.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
}
Here's where the database is created:
public class SQLiteActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DataBaseHelper myDbHelper ;
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
}
}
Any suggestions on how to solve this problem?
A: SimpeCursorAdapter might be de adapter which you are looking for.
Update based on comment (how to query data)
private Cursor queryData() {
return myDataBase.query(
"tableName",
new String[] {"list", "of", "colums", "to", "select"},
"columnName = ?", // your where condition
new String[] {"your ? repleacements"},
null, // no group by
null, // no having
null); // on order by
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Objective-C: help me parse this JSON I have the following JSON object being returned from my webserver. I can't figure out how to parse it... I basically want to extract the uname and the profilePic for each of the drivers (there are two drivers in this example). I'm not interested in the rest of the stuff.
Here is the JSON:
{
"0": {
"uname": "Eamorr",
"fname": "Bill",
"lname": "Byrne",
"phoneNumber": "087-2342404",
"roofSignNumber": "32984",
"reputation": 0,
"vehicleMake": "Toyota",
"vehicleModel": "Carina",
"vehicleNumPassengers": "4",
"profilePic": "XE7F654O05RC3I33P44A",
"online": 1,
"lat": "52.27114461",
"lng": "-9.70294471",
"status": "done!",
"sex": "M",
"picList": ["W725CY1XR63PW480Z694", "XBA2078W4Z3JROQMSN16", "0H0XDD27J9J9RV28KKR4", "84G09NCP537G1KM6O4R8", "FM12F2J12AWL8C8XX2F5", "5AU4FLJ50PN0R210AP8J", "5588ORG95RF10B757NY7", "4z54cz5c565410r2wq2u", "3502IXTI31MSX6Z01NWC", "XE7F654O05RC3I33P44A", "A828K8M0E5576C1AK6HU", "M5EHX8MQMHZ6PJ1NNYH7", "8RIS3245542E2I9TLOD4", "3V5F7HNZNN642O29347Y", "YU2CT34A7769XG2LV38G"],
"last5comments": [{
"comment": "asdf2",
"fromUname": "Anonymous",
"time": 1314036666
}, {
"comment": "qwerty",
"fromUname": "Eamorr",
"time": 1314550970
}, {
"comment": "qwerty",
"fromUname": "Eamorr",
"time": 1314551143
}, {
"comment": "hi",
"fromUname": "Eamorr2",
"time": 1315157494
}, {
"comment": "Hello",
"fromUname": "Anonymous",
"time": 1315394983
}],
"numPagesComments": 13
},
"1": {
"uname": "Eamorr2",
"fname": "Steve",
"lname": "McCloskey",
"phoneNumber": "087-3234404",
"roofSignNumber": "32431",
"reputation": 0,
"vehicleMake": "Toyota",
"vehicleModel": "avensis",
"vehicleNumPassengers": "4",
"profilePic": -1,
"online": "0",
"lat": "52.28783634",
"lng": "-9.66791791",
"status": "",
"sex": "M",
"picList": [],
"last5comments": [{
"comment": "asdf",
"fromUname": "Anonymous",
"time": 1296655686
}, {
"comment": "I'm off in the middle of the Atlantic again",
"fromUname": "Anonymous",
"time": 1296843759
}, {
"comment": "Hi",
"fromUname": "Eamorr",
"time": 1299098148
}, {
"comment": "Hi",
"fromUname": "Eamorr",
"time": 1299098148
}, {
"comment": "Hi",
"fromUname": "Eamorr",
"time": 1299098148
}],
"numPagesComments": 2
}
}
And here's what I've tried to code up (to no avail...):
//NSDictionary *obj=[parser objectWithString:[request responseString] error:nil];
NSArray *obj=[parser objectWithString:[request responseString] error:nil];
NSLog([obj objectAtIndex:0]);
/*for(int i=0;i<obj.count;i++){
NSDictionary *driver=[obj objectAtIndex:i];
for (NSDictionary *dict in driver) {
[unames addObject:[dict objectForKey:@"uname"]];
[profilePics addObject:[dict objectForKey:@"profilePic"]];
}
}
I hope someone can help.
Solution:
SBJsonParser *parser=[[SBJsonParser alloc]init];
//NSDictionary *obj=[parser objectWithString:[request responseString] error:nil];
NSDictionary *obj=[parser objectWithString:[request responseString] error:nil];
for(int i=0;i<[obj count];i++){
NSDictionary *obj2=[obj objectForKey:[NSString stringWithFormat:@"%d",i]];
NSLog(@"%@",[obj2 objectForKey:@"uname"]);
}
A: Use SBJSON https://github.com/stig/json-framework
SBJSON *jsonReader = [[[SBJSON alloc] init] autorelease];
NSDictionary *responce = [jsonReader objectWithString:[request responseString]];
NSString *uName1 = [[responce objectForKey:@"0"] objectForKey:@"uname"];
NSString *image1 = [[responce objectForKey:@"0"] objectForKey:@"profilePic"];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: how to implement a 'game paused' screen with buttons I'm trying to create a 'game paused' screen that overlays on top of my game. The game itself runs in a GameView (extending SurfaceView). I would like the paused screen to have a layout with a number of ImageViews for buttons or animations, but I don't know how to put that layout on the screen without getting rid of the GameView behind it.
A: Using a relative layout and hide/unhide could be possible.
A: you can also do this
Instead of opening a new axtivity stop the current drawing loop and draw your pause screen and add button and images in by drawing itself.
A: See my another answer how programmatically show an overlay layout on top of the current activity. Activity's layout.xml does not need to know anything about the overlay skin. You can put overlay semi-transparent, cover only part of the screen, one or more textview and buttons on it...
How to overlay a button programmically?
*
*create res/layout/paused.xml RelativeLayout template or use any layout toplevel
*create a function to show overlay skin
*key is to get handle to layout.xml, use LayoutInflater class to parse xml to view object, add overlay view to current layout structure
*My example uses a timer to destroy overlay object by completely removing it from the view structure. This is probably what you want as well to get rid of it without a trace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is faster in Java for reading/parsing console input, Scanner or BufferedReader? I have to craft a data processor able to process more than 2.5MB/s of input from STDIN, and output a number to STDOUT. What is faster, to use a BufferedReader and then conversions to data types or a Scanner and nextInt() or nextFloat()?
EMPIRICAL TEST RESULTS: BufferedReader and conversion is a little bit faster, but nothing too significant.
Thankyou!
A: The answer is most likely that it doesn't matter which way you do it from a performance perspective. (And there's no way that someone can type at 2.5Mb per second at the console!)
If you include everything that goes on at the OS level and elsewhere when reading from the console, orders of magnitude more CPU cycles will be expended in getting the bytes from the user typing at the console than are spent parsing the characters. If you are reading from a file (via stdin), we are no longer talking orders of magnitude difference, but I'd still be surprised if the two approaches were significantly different ... overall.
But the best thing you can do is try it out. It shouldn't take more than a few minutes to write a benchmark that roughly approximates to what you are doing, and see which alternative is faster ... and by how much. (Make sure that you measure total elapsed time, not just user-space CPU time for the Java application.)
A: BufferedReader reads the stream. While a Scanner breaks its input into tokens.
2.5MB/s is more suitable for the BufferedReader. It has a larger buffer than Scanner. 8 to 1
BufferedReader >>>>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: ASP.NET web service throw System.Net.WebException when upload file I have a a web service in asp.net which need to upload files to another server. The code run well when I play under Debug mode in Visual Studio. But when I host in IIS and call it, it throw System.Net.WebException. Here is my code:
[WebMethod]
public string UploadFileToServer(string m_fileName, string m_username, string m_url)
{
string m_localFilePath = _currentDirectory + "\\" + m_username + "\\" + m_fileName;
FileStream m_localFileStream = File.Open(m_localFilePath, FileMode.Open, FileAccess.Read);
var reader = new BinaryReader(m_localFileStream);
byte[] m_rawBytes = new byte[m_localFileStream.Length];
reader.Read(m_rawBytes, 0, m_rawBytes.Length);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_url);
request.Method = "POST";
request.KeepAlive = false;
Stream m_requestStream = request.GetRequestStream();
m_requestStream.Write(m_rawBytes, 0, m_rawBytes.Length);
m_requestStream.Close();
m_localFileStream.Close();
HttpWebResponse m_response = (HttpWebResponse)request.GetResponse();
StreamReader m_reader = new StreamReader(m_response.GetResponseStream());
string s = m_reader.ReadToEnd();
return s;
}
catch (Exception ex)
{
return ex.ToString() + ex.Message;
}
}
It is very frustrated for me and it's not possible to turn it on my Visual Studio all the time. Any suggestion or solutions? Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem creating multiple child processes Im new at process creation etc..so probably a basic question.
Im creating a fixed number of child processes, each doing nothing but printing their pid. The problem is in the output that i get. Have a look:
int main(){
pid_t pid=0;
int i=0,status=0;
for(i=0;i<3;i++){
pid=fork();
switch(pid){
case 0:{ //Child
printf("\nChild pid: %d",getpid());
exit(0);
break;
}
case -1: {//Error
printf("Error occured in fork");
exit(1);
break;
}
default:{
printf("\nParent id: %d",getpid());
printf("\nIts child id: %d",pid);
wait(NULL);
}
}
Output:
Child pid: 1450
Parent id: 1445
Its child id: 1450
Child pid: 1455Its child id: 1450
Parent id: 1445
Its child id: 1455
Child pid: 1460Its child id: 1455
Parent id: 1445
Its child id: 1460
The problem is I dont know why only the second print statement of the parent process is appearing and not the first, if any at all. I know im not waiting for my child processes to end( frankly i dont know how i would do that), but if the parent does execute before ending its child processes, why arent both its print statements appearing, and why is the \n being ignored in that line too.
Any help would be greatly appreciated.
Thx.
Update:If i replace wait(NULL) with printf("\n%d\n",wait(NULL)) It gives me a perfect output, without stray prints. Any idea what couldve fixed it? After all they both do the same thing.
A: The problem is that there are several processes writing to the same file (your console) at the same time without any concurrency control or any lock. That, and that the ttys are strange creatures, at best, make weird things happens. Over that, remember that printf is buffered.
Your output should be read this way:
Child pid: 1450 <- Child #1
Parent id: 1445 <- Parent #1.1
Its child id: 1450 <- Parent #1.2
Child pid: 1455[Its child id: 1450] <- Child #2 with garbage at the end
Parent id: 1445 <- Parent #2.1
Its child id: 1455 <- Parent #2.2
Child pid: 1460[Its child id: 1455] <- Child #3 with garbage at the end
Parent id: 1445 <- Parent #3.2
Its child id: 1460 <- Parent #3.2
You could try redirecting the output to a file, and see if not being a tty makes any difference.
Anyway, to do it the right wat, you should use any mechanism that guarantees multiprocess correctness.
UPDATE
Yes, now I see it. You have the '\n' at the beginning of your printing lines, not at the end, as is usual. Stdout is normally line-buffered, that means that the buffer is flushed to the device when it sees a '\n'. And since you have them at the beginning there is always one line in the buffer waiting for output.
Now, when you fork your process the output buffer gets duplicated and the last line from the parent is printed by the child (why it is printed after, and not before, is still a mystery to me).
Anyway, the new printf you added has a '\n' at the end, so it flushes the buffer, fork finds it empty and all goes fine. You could as well call fflush(stdout) but it is cumbersome.
The morale of the story is: "When you printf for debugging purposes always put a \n at the end of every line or you can get partial, mixed contents.
A: The problem is buffering and flushing of stdout.
Both lines are being printed, but not flushed to output at the time you expect.... depening on where the output is going to, (file, pipe, terminal, stderr etc) printf uses different buffer strategies.
I guess that in your case it only flushes on newline (check man setbuf)
Move the newline to the end of the rather than in the beginning, so for example....
printf("Parent id: %d\n",getpid());
printf("Its child id: %d\n",pid);
And be consistent with alway putting the \n at the end of printf for all your printfs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: F# vs OCaml: Stack overflow I recently found a presentation about F# for Python programmers, and after watching it, I decided to implement a solution to the "ant puzzle" on my own.
There is an ant that can walk around on a planar grid. The ant can move one space at a time left, right, up or down. That is, from the cell (x, y) the ant can go to cells (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the x and y coordinates are greater than 25 are inaccessible to the ant. For example, the point (59,79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 25. The question is: How many points can the ant access if it starts at (1000, 1000), including (1000, 1000) itself?
I implemented my solution in 30 lines of OCaml first, and tried it out:
$ ocamlopt -unsafe -rectypes -inline 1000 -o puzzle ant.ml
$ time ./puzzle
Points: 148848
real 0m0.143s
user 0m0.127s
sys 0m0.013s
Neat, my result is the same as that of leonardo's implementation, in D and C++. Comparing to Leonardo's C++ implementation, the OCaml version runs approx 2 times slower than C++. Which is OK, given that Leonardo used a queue to remove recursion.
I then translated the code to F# ... and here's what I got:
Thanassis@HOME /g/Tmp/ant.fsharp
$ /g/Program\ Files/FSharp-2.0.0.0/bin/fsc.exe ant.fs
Microsoft (R) F# 2.0 Compiler build 2.0.0.0
Copyright (c) Microsoft Corporation. All Rights Reserved.
Thanassis@HOME /g/Tmp/ant.fsharp
$ ./ant.exe
Process is terminated due to StackOverflowException.
Quit
Thanassis@HOME /g/Tmp/ant.fsharp
$ /g/Program\ Files/Microsoft\ F#/v4.0/Fsc.exe ant.fs
Microsoft (R) F# 2.0 Compiler build 4.0.30319.1
Copyright (c) Microsoft Corporation. All Rights Reserved.
Thanassis@HOME /g/Tmp/ant.fsharp
$ ./ant.exe
Process is terminated due to StackOverflowException
Stack overflow... with both versions of F# I have in my machine...
Out of curiosity, I then took the generated binary (ant.exe) and run it under Arch Linux/Mono:
$ mono -V | head -1
Mono JIT compiler version 2.10.5 (tarball Fri Sep 9 06:34:36 UTC 2011)
$ time mono ./ant.exe
Points: 148848
real 1m24.298s
user 0m0.567s
sys 0m0.027s
Surprisingly, it runs under Mono 2.10.5 (i.e. no stack overflow) - but it takes 84 seconds, i.e. 587 times slower than OCaml - oops.
So this program...
*
*runs fine under OCaml
*doesn't work at all under .NET/F#
*works, but is very slow, under Mono/F#.
Why?
EDIT: Weirdness continues - Using "--optimize+ --checked-" makes the problem disappear, but only under ArchLinux/Mono ; under Windows XP and Windows 7/64bit, even the optimized version of the binary stack overflows.
Final EDIT: I found out the answer myself - see below.
A: Let me try to summarize the answer.
There are 3 points to be made:
*
*problem: stack overflow happens on a recursive function
*it happens only under windows: on linux, for the problem size examined, it works
*same (or similar) code in OCaml works
*optimize+ compiler flag, for the problem size examined, works
It is very common that a Stack Overflow exception is the result of a recursive vall. If the call is in tail position, the compiler may recognize it and apply tail call optimization, therefore the recursive call(s) will not take up stack space.
Tail call optimization may happen in F#, in the CRL, or in both:
CLR tail optimization1
F# recursion (more general) 2
F# tail calls 3
The correct explanation for "fails on windows, not in linux" is, as other said, the default reserved stack space on the two OS. Or better, the reserved stack space used by the compilers under the two OSes. By default, VC++ reserves only 1MB of stack space. The CLR is (likely) compiled with VC++, so it has this limitation. Reserved stack space can be increased at compile time, but I'm not sure if it can be modified on compiled executables.
EDIT: turns out that it can be done (see this blog post http://www.bluebytesoftware.com/blog/2006/07/04/ModifyingStackReserveAndCommitSizesOnExistingBinaries.aspx)
I would not recommend it, but in extreme situations at least it is possible.
OCaml version may work because it was run under Linux.
However, it would be interesting to test also the OCaml version under Windows. I know that the OCaml compiler is more aggressive at tail-call optimization than F#.. could it even extract a tail recursive function from your original code?
My guess about "--optimize+" is that it will still cause the code to recur, hence it will still fail under Windows, but will mitigate the problem by making the executable run faster.
Finally, the definitive solution is to use tail recursion (by rewriting the code or by relying on aggressive compiler optimization); it is a good way to avoid stack overflow problem with recursive functions.
A: Executive summary:
*
*I wrote a simple implementation of an algorithm... that wasn't tail-recursive.
*I compiled it with OCaml under Linux.
*It worked fine, and finished in 0.14 seconds.
It was then time to port to F#.
*
*I translated the code (direct translation) to F#.
*I compiled under Windows, and run it - I got a stack overflow.
*I took the binary under Linux, and run it under Mono.
*It worked, but run very slowly (84 seconds).
I then posted to Stack Overflow - but some people decided to close the question (sigh).
*
*I tried compiling with --optimize+ --checked-
*The binary still stack overflowed under Windows...
*...but run fine (and finished in 0.5 seconds) under Linux/Mono.
It was time to check the stack size: Under Windows, another SO post pointed out that it is set by default to 1MB. Under Linux, "uname -s" and a compilation of a test program clearly showed that it is 8MB.
This explained why the program worked under Linux and not under Windows (the program used more than 1MB of stack). It didn't explain why the optimized version run so much better under Mono than the non-optimized one: 0.5 seconds vs 84 seconds (even though the --optimize+ appears to be set by default, see comment by Keith with "Expert F#" extract). Probably has to do with the garbage collector of Mono, which was somehow driven to extremes by the 1st version.
The difference between Linux/OCaml and Linux/Mono/F# execution times (0.14 vs 0.5) is because of the simple way I measured it: "time ./binary ..." measures the startup time as well, which is significant for Mono/.NET (well, significant for this simple little problem).
Anyway, to solve this once and for all, I wrote a tail-recursive version - where the recursive call at the end of the function is transformed into a loop (and hence, no stack usage is necessary - at least in theory).
The new version run fine under Windows as well, and finished in 0.5 seconds.
So, moral of the story:
*
*Beware of your stack usage, especially if you use lots of it and run under Windows. Use EDITBIN with the /STACK option to set your binaries to larger stack sizes, or better yet, write your code in a manner that doesn't depend on using too much stack.
*OCaml may be better at tail-recursion elimination than F# - or it's garbage collector is doing a better job at this particular problem.
*Don't despair about ...rude people closing your Stack Overflow questions, good people will counteract them in the end - if the questions are really good :-)
P.S. Some additional input from Dr. Jon Harrop:
...you were just lucky that OCaml didn't overflow as well.
You already identified that actual stack sizes vary between platforms.
Another facet of the same issue is that different language implementations
eat stack space at different rates and have different performance
characteristics in the presence of deep stacks. OCaml, Mono and .NET
all use different data representations and GC algorithms that impact
these results... (a) OCaml uses tagged integers to distinguish pointers,
giving compact stack frames, and will traverse everything on the stack
looking for pointers. The tagging essentially conveys just enough information
for the OCaml run time to be able to traverse the heap (b) Mono treats words
on the stack conservatively as pointers: if, as a pointer, a word would point
into a heap-allocated block then that block is considered to be reachable.
(c) I do not know .NET's algorithm but I wouldn't be surprised if it ate stack
space faster and still traversed every word on the stack (it certainly
suffers pathological performance from the GC if an unrelated thread has a
deep stack!)... Moreover, your use of heap-allocated tuples means you'll
be filling the nursery generation (e.g. gen0) quickly and, therefore,
causing the GC to traverse those deep stacks often...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
} |
Q: Sproutcore with Python Scipy I have a computational backend made in Python Scipy and the frontend and admin section will be made in Sproutcore. What do i need to make the sproutcore run the python engine.
I think i need a python framework that sits between sproutcore and scipy. This framework's only job will be to facilitate communication.
Other option is to use sproutcore on the server as well and a way for it to call the python scipy scripts, if that is even possible
Any advice on the correct approach?
Any recommendation on such a simple glue framework.
A: You can use any framework you like! I happen to like something like SimpleApi atop Flask (which you can run with nginx, apache2 or any wsgi-compliant server). This basically puts an TCP/IP listener on top of whatever python code you like.
I am guessing all you want to expose is essentially run(some_well_controlled_and_obviously_not_from_the_user_code).
Some problems you might encounter:
*
*where to put generated images, such that the front end can get them. This gets hairy with expiration, file sizes, etc. Beaker might help here?
*job queuing... some computations take a while. Now what? Make the user wait? AJAX-reload? Shovel that onto Celery or Zero-MQ?
Let me know how this comes along. This is definitely needed, and I have thought about starting a similar project myself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery - moving li element out of the parent ul, and retaining position I need to move li element out of its parent ul and into master parent ul.
I tried this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
$( init );
function init() {
// Move
$('ul#listcomments').append( $('.children>li') );
// Delete
$('.children').remove();
}
</script>
</head>
<body>
<ul id="listcomments">
<li>Comment 1</li>
<li>Comment 2</li>
<li>Comment 3</li>
<li>Comment 4</li>
<li>Comment 5 <ul class="children"><li>Child comment of #5 is this</li></ul></li>
<li>Comment 6</li>
<li>Comment 7</li>
<li>Comment 8</li>
</ul>
</body>
</html>
I want to achieve this:
* that is, make child li#5child to get out of ul and li and appear right below li.
<ul id="listcomments">
<li>Comment 1</li>
<li>Comment 2</li>
<li>Comment 3</li>
<li>Comment 4</li>
<li>Comment 5</li>
<li>Child comment of #5 is this</li>
<li>Comment 6</li>
<li>Comment 7</li>
<li>Comment 8</li>
</ul>
Instead I get:
* append drops li outside, but puts it at the very end of ul#listcomments
<ul id="listcomments">
<li>Comment 1</li>
<li>Comment 2</li>
<li>Comment 3</li>
<li>Comment 4</li>
<li>Comment 5 </li>
<li>Comment 6</li>
<li>Comment 7</li>
<li>Comment 8</li>
<li>Child comment of #5 is this</li>
</ul>
I hope this explains it better than using words. It's pretty simple as a concept, but with my limited skills, I couldn't come up with anything better.
help! :)
*notice: naming and numbering of lis is arbitrary. And child comment can appear within any # li. Content is dynamically generated.
A: Try this one:
<script type="text/javascript">
$( init );
function init() {
$('.children').each(function() {
// save
$a=$(this).children('li');
// Move
$($a.parent().parent()).after($a);
// Delete
$(this).remove();
});
}
</script>
This will solve your problem no matter how many ul child elements exist, and no matter how many li child elements they have.
A: Try to use method .after().
Replace $('ul#listcomments').append( $('.children>li') ); to
$($('.children')[0].parentNode).after($('.childer > li'));
A: You can also use the unwrap() method:
$(".children > li").unwrap();
A: I think you could use this
var a = $('ul.children').html();
//grab the li
$('ul.children').remove();
//remove the ul
$('ul#listcomments li:eq(4)').after(a);
//add the li after the 5th li in the parent list
Working Example: http://jsfiddle.net/jasongennaro/aDWJF/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Which is better/more efficient in coffeescript when running a for loop? There are two functionally equivalent ways of writing the following function in javascript, which is better or more efficient, and why?
(str) ->
s = 0
for i in [0...str.length]
s += str.charCodeAt i
s
or
(str) ->
s = 0
for i in str
s += i.charCodeAt 0
s
Aside: Can you suggest any other methods of doing this?
Edit: According to JSPerf, the first is faster: http://jsperf.com/coffee-for-loop-speed-test - why is this?
A: The first is both more elegant and more efficient. The second copies each character of the string to a separate string unnecessarily, before converting it to a charCode.
A: Are you familiar with functional programming? Coffeescript + Underscore.js working together are pretty awesome. You can use either the native Array#reduce defined on ECMAScript 5 or the underscore function. Example for the first:
(s.charCodeAt(0) for s in "hello").reduce((acc, x) -> acc + x) # 532
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are the best methods and algorithms available in Machine Learning for automatically detecting and extracting EVENTS from E-mails Can Someone tell me about the available algorithms in machine learning and which is the best one to extract events from email,please provide suitable links also...thanks in advance :D
A: Use NLP grammar tools for that purpose i.e GATE/JAPE or GExp. You can find calendar event parser for russian based on Gexp here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Detect combination of letter, numbers special characters between round brackets I would to know how to detect letters, combination letters and numbers between rounded brackets. In my examples below, it must not detect the year.
Detect:
Sample (test 2011)
Sample (test-2011)
Sample (test)
Do NOT detect
Sample (2011)
A: example that would match your test-samples in JavaScript regex:
^\([a-z\- ]+[0-9]*\)$
^ matches start, and $ end
\( \) matches the brackets once
[a-z\- ]+ matches literals, blank and - once or more times
[0-9]* matches 0 to 9 zero or more times
edit
nevertheless, you should be more specific, and look at some kind of documentation too (especially, since there are thousand info pages for regular expressions around)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: help me understand HTTP requests when surfing glype proxies i have a basic understanding of how HTTP works and is similar to what is described here
But my problem is when using glype based proxies for example(i have no experience with others) and you carry out these steps:
*
*Configure your browser to use a proxy eg one at 213.229.83.205
*enter an ip address like google.com into address bar
The request looks like
Get http://www.google.com /HTTP 1.0
host: www.google.com
So how does apache know what php script it should foward this request to?
A: Assuming glype is just a regular proxy server it's quite simple. After configuring your browser to use a proxy (by providing it's IP address), each request made by your browser first checks with the proxy server to see if it has a cached copy of the requested URL (which in this case is http://www.google.com index page). If it does, the proxy returns it, otherwise the browser requests the document from the real server (google.com, in your example) and saves a copy on the proxy server so the next request doesn't have to get it from the real server.
The idea is that when lots of users are repeatedly requesting the same document from a remote source, a proxy server, typically for a local network will be able to serve the content (the document and images and other stuff) more quickly. That was probably true ten or twenty years ago when large companies had many users and limited bandwidth. Today, proxy servers are of little value in normal web browsing -- most web pages (like the Google home page) are dynamic, and send headers that instruct proxies to not cache the content. Further, browsers cache stuff now, and in most cases, bandwidth is available. To be sure, this is not true everywhere in the world and for all web pages, but mostly proxy servers whose purpose is to cache data are a vestige of the past.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remove contents of tags using html5lib or bleach I've been using the excellent bleach library for removing bad HTML.
I've got a load of HTML documents which have been pasted in from Microsoft Word, and contain things like:
<STYLE> st1:*{behavior:url(#ieooui) } </STYLE>
Using bleach (with the style tag implicitly disallowed), leaves me with:
st1:*{behavior:url(#ieooui) }
Which isn't helpful. Bleach seems only to have options to:
*
*Escape tags;
*Remove the tags (but not their contents).
I'm looking for a third option - remove the tags and their contents.
Is there any way to use bleach or html5lib to completely remove the style tag and its contents? The documentation for html5lib isn't really a great deal of help.
A: It turned out lxml was a better tool for this task:
from lxml.html.clean import Cleaner
def clean_word_text(text):
# The only thing I need Cleaner for is to clear out the contents of
# <style>...</style> tags
cleaner = Cleaner(style=True)
return cleaner.clean_html(text)
A: I was able to strip the contents of tags using a filter based on this approach: https://bleach.readthedocs.io/en/latest/clean.html?highlight=strip#html5lib-filters-filters. It does leave an empty <style></style> in the output, but that's harmless.
from bleach.sanitizer import Cleaner
from bleach.html5lib_shim import Filter
class StyleTagFilter(Filter):
"""
https://bleach.readthedocs.io/en/latest/clean.html?highlight=strip#html5lib-filters-filters
"""
def __iter__(self):
in_style_tag = False
for token in Filter.__iter__(self):
if token["type"] == "StartTag" and token["name"] == "style":
in_style_tag = True
elif token["type"] == "EndTag":
in_style_tag = False
elif in_style_tag:
# If we are in a style tag, strip the contents
token["data"] = ""
yield token
# You must include "style" in the tags list
cleaner = Cleaner(tags=["div", "style"], strip=True, filters=[StyleTagFilter])
cleaned = cleaner.clean("<div><style>.some_style { font-weight: bold; }</style>Some text</div>")
assert cleaned == "<div><style></style>Some text</div>"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Google Maps API click events 'addDomListener' for selectbox I have a select box that when I select a country the map gets updated.
Everything works fine, but I want to eliminate the first event (clicking on the select box before the actual select).
var geocoder;
var mapOptions;
var map;
function new_initialize() {
geocoder = new google.maps.Geocoder();
mapOptions = { center: new google.maps.LatLng(0, 0), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var myCountry = document.getElementById('country');
google.maps.event.addDomListener(myCountry, 'click', function() {
// get the value of the select box #country and set the map center to this
codeAddress(this.value);
});
}
google.maps.event.addDomListener(window, 'load', new_initialize);
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location });
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
A: I'd say in your event handler, just do a check on the value, and only call codeAddress() if there is a value (assuming your first has an empty value attribute)
var myCountry = document.getElementById('country');
google.maps.event.addDomListener(myCountry, 'click', function() {
if (this.value != "") {
// get the value of the select box #country and set the map center to this
codeAddress(this.value);
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Embeded DB for Firemonkey apps Creating a client application, want the whole DB to be embed in the software or in a single standalone dll (ie sqlite), not something like mysql.
Whats built into XE2 which would work 'out of the box' and not need thirdparty tools?
Other than TClientDataSet / xml files :)
A: Firebird is available with XE2... For a single user usage, you don't need to run a service to access it (but you'll need the firebird client and the vendor dll to access it).
A: You can use my SQLite wrapper (also some more info in my blog) which supports multiple platforms. In Windows you'll need to deploy sqlite3.dll with your application, there is no need for this on OSX. You can get sources from the svn. Example usage:
uses
SQLiteTable3,
{$IFDEF DELPHI16_UP}
System.SysUtils;
{$ELSE}
SysUtils;
{$ENDIF}
procedure Demo;
var
slDBpath: string;
db: TSQLiteDatabase;
pstm TSQLitePreparedStatement;
begin
slDBpath := IncludeTrailingPathDelimiter(GetHomePath) + 'test.db';
db := TSQLiteDatabase.Create(slDBpath);
try
if db.TableExists('testtable') then
begin
pstm := TSQLitePreparedStatement.Create(db,
'insert into testtable (name,number) values (?,?)', //sql statement
['NewRec', 99.99]); //parameter values
try
pstm.ExecSQL;
finally
pstm.Free;
end;
end;
finally
db.Free;
end;
end;
A: Also you may look at NexusDB Embedded, which is native Delphi solution, and doesn't require any Dlls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is monodroid slower? I have heard an android software can be developed by using C#. (monodroid)
But when I research it, someone indicated it will be more slow to run.
What do you think? Is it real? Is it effective using C#?
A: We don't know.
In all seriousness, it would be really handy if someone could port the Android Linpack app to Mono for Android so we could get a performance comparison between the two.
Here's what I do know:
*
*There's a currently ~3s startup penalty overhead when first loading the app on a G1 (your mileage will vary depending on hardware). This is due to initializing the Mono runtime and loading up the referenced assemblies. We do want to improve this in the future.
*Mono, and Mono for Android, JITs everything. Dalvik, meanwhile, has a JIT cache of variable size (currently 1MB on ARMv7) and an interpreter, so depending on your app it's possible (probable) that not everything will be JITed.
*Mono for Android uses JNI to invoke Android/Java code.
Then there's koush's performance comparsion between Mono and Dalvik in 2009. This predates the Dalvik JIT, but on identical hardware, Mono was spanking Dalvik.
So what does that all mean? I have absolutely no idea. (Again, a port of Linpack to Mono for Android would be wonderful! hint hint, nudge nudge)
That said, there is some performance advice to suggest:
*
*Use a splash screen during app startup. This provides immediate feedback during app startup, which is what most users care about.
*If at all possible, minimize transitions between Mono and Java code. JNI will never win any performance medals, so if you can do more code in Mono without intermediate calls to Java methods, do so.
*Minimize the number of Java.Lang.Object instances that are kept alive concurrently. Cross-VM GC references can cause performance issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: apache mod_proxy www.domain.com fails, domain.com works - whats wrong? I have a apache setup that redirect to my app running on tomcat. Loading http://domain.com works fine. However http://www.domain.com gives me a 404 error.
What am I missing?
NameVirtualHost www.domain.com:80
<VirtualHost www.domain.com:80>
ServerName www.domain.com
ProxyPass /svn !
ProxyPass / ajp://127.0.0.1:8009/appname/
ProxyPassReverse / ajp://127.0.0.1:8009/appname/
ProxyPassReverseCookiePath /appname/
</VirtualHost>
Following the first comment I have altered by code to be:
<VirtualHost www.domain.com:80>
ServerName www.domain.com
ServerAlias www.domain.com domain.com
ProxyPass /svn !
ProxyPass / ajp://127.0.0.1:8009/appname/
ProxyPassReverse / ajp://127.0.0.1:8009/appname/
ProxyPassReverseCookiePath /appname/
</VirtualHost>
In the apache logs I see a 404 error "GET / HTTP/1.1" 200 16060"
In the browser I see an apache tomcat 404 error (tomcat 6.0.28)
I see nothing in the tomcat logs
A: Use ServerAlias.
<VirtualHost www.domain.com:80>
ServerName www.domain.com
ServerAlias www.domain.com domain.com
ProxyPass /svn !
ProxyPass / ajp://127.0.0.1:8009/appname/
ProxyPassReverse / ajp://127.0.0.1:8009/appname/
ProxyPassReverseCookiePath /appname/
</VirtualHost>
Edit:
When facing that kind of problems, you can directly hit tomcat on its HTTP port (see server.xml) and check if the problem occurs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WPF / EF4 Application Installer I have written a WPF Application with a datalayer using Entity Framework 4 (EF4, using SQL Server, not Compact Edition). How can I ensure that everything the App needs gets installed at the customer? Is there a standard way to install EF4 with a Windows Installer?
EDIT: found an article about that problem: Using SQL Server Compact 4.0 with Desktop Private Deployment and a Setup project (MSI) (part 2). I might change some stuff (like autokey creation) and use CE
Similar question: Do I need to install SQL Server Compact Edition on all client's desktops?
maybe interisting for people doing something similar: SQLCE is a compact database that is click once deployable...
A: Once your program is compiled, there is no need to 'install entity framework' on client machines. Entity framework is just a framework to aid you with using SQL while coding.
Perhaps what you're asking is how to install your application and set it up to work with the database? Then:
*
*Using an installer program, move the files over for your application and do any setup.
*Install sql server, and run your *.edmx.sql script that is automatically generated by your model.
*Connect the two by modifying your app.config file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unable to parse atom feed using jQuery I'm using jFeed to parse atom feed and trying to display the title. I had written success and error functions but it's not getting into either success or error function.
Below is my code. Please let me know what's going wrong with below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript/jquery.jfeed.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//read the atom feed
$.getFeed({
type:"GET",
url:"http://www.google.co.in/trends/hottrends/atom/hourly",
success:function(feed)
{
alert(feed.title);
},
error:function(error)
{
alert(error);
}
});
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
A: $.getFeed doesn't take "type" and "error" parameters.
From the jfeed source:
jQuery.getFeed = function(options) {
options = jQuery.extend({
url: null,
data: null,
success: null
}, options);
if(options.url) {
$.ajax({
type: 'GET',
url: options.url,
data: options.data,
dataType: 'xml',
success: function(xml) {
var feed = new JFeed(xml);
if(jQuery.isFunction(options.success)) options.success(feed);
}
});
}
so you are most likely getting an error.
Try sending a simple Ajax request to see what error you are getting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Solution to travelling salesman problem using nearest neighbour algorithm in one LINQ query? Given
List<Point> cities = /* ... */ ;
double distance(Point a, Point b) { /* ... */ };
is there a single LINQ query that returns the travelling salesman shortest route by nearest neighbour algorithm as a List<int> of the indices of cities?
A: I don't think you can do everything in a single query, some parts of the algorithms will have to be implemented separately.
Here's a brute-force implementation that examines all city permutations and returns the shortest path that visits all the cities:
var bestPath =
cities.Permutations()
.MinBy(
steps => steps.Aggregate(
new { Sum = 0, Previous = default(Point) },
(acc, c) =>
new
{
Sum = acc.Sum + (acc.Previous != null ? Distance(c, acc.Previous) : 0 ),
Previous = c
},
acc => acc.Sum));
The Permutations extension method is defined as follows:
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source)
{
var query =
from item in source
from others in source.SkipOnce(item).Permutations()
select new[] { item }.Concat(others);
return query.DefaultIfEmpty(Enumerable.Empty<T>());
}
public static IEnumerable<T> SkipOnce<T>(this IEnumerable<T> source, T itemToSkip)
{
bool skipped = false;
var comparer = EqualityComparer<T>.Default;
foreach (var item in source)
{
if (!skipped && comparer.Equals(item, itemToSkip))
skipped = true;
else
yield return item;
}
}
Of course there are much better approaches to solve this problem, but this one works... Most of it is in a single query, the only parts that are implemented separately are not specific to the problem at hand and can be reused for other tasks.
EDIT: oops, I just realized I also used the non-standard MinBy method; you can find it in the MoreLinq project
A: If you just need Nearest Neighbour algorithm in one single LINQ query, you can do in this way:
var nearestNeighTour = cities.Skip(1).Aggregate(
new List<int>() { 0 },
(list, curr) =>
{
var lastCity = cities[list.Last()];
var minDist = Enumerable.Range(0, cities.Count).Where(i => !list.Contains(i)).Min(cityIdx => distance(lastCity, cities[cityIdx]));
var minDistCityIdx = Enumerable.Range(0,cities.Count).Where(i => !list.Contains(i)).First(cityIdx => minDist == distance(lastCity, cities[cityIdx]));
list.Add(minDistCityIdx );
return list;
});
Even if I think it's more readable using for-loops
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Output form submit success into page instead of redirect I'm using a WordPress sidebar widget for email capture for my newsletter. The plugin has been written to redirect to a 'success page' after submission, which isn't great because I'd rather it just output a success message in a div under the form after submission so the visitor stays on the page. How can I do that? I was thinking of something like a meta refresh on the success page back to the page the visitor was on, but that's pretty clunky when I'm pretty sure I've seen on-page email capture forms where the success message is just output into the page somewhere without a redirect.
If you don't mind, I'm going to copy quite a bit of the plugin's code here as I'm not exactly sure what needs to be tweaked here to get the kind of onsubmit I'm looking for. Or if there's any other way you could tell me to do this, I'd really appreciate your help with this. Thanks a lot.
<?php
function wp_email_capture_form($error = 0) {
$url = get_option('home');
$url = addLastCharacter($url);
?>
<div id="wp_email_capture"><form name="wp_email_capture" method="post" action="<?php echo $url; ?>">
<?php
if (isset($_GET["wp_email_capture_error"])) {
$error = sanitize($_GET["wp_email_capture_error"]);
echo "<div style='width:80%;background-color: #FFCCCC; margin: 5px;font-weight'>Error: ". $error ."</div>";
}
?>
<label class="wp-email-capture-name">Name:</label> <input name="wp-email-capture-name" type="text" class="wp-email-capture-name"><br/>
<label class="wp-email-capture-email">Email:</label> <input name="wp-email-capture-email" type="text" class="wp-email-capture-email"><br/>
<input type="hidden" name="wp_capture_action" value="1">
<input name="Submit" type="submit" value="Submit" class="wp-email-capture-submit">
</form>
</div>
<?php
if (get_option("wp_email_capture_link") == 1) {
echo "<p style='font-size:10px;'>Powered by <a href='http://www.gospelrhys.co.uk/plugins/wordpress-plugins/wordpress-email-capture-plugin' target='_blank'>WP Email Capture</a></p>\n";
}
}
function wp_email_capture_form_page($error = 0) {
$url = get_option('home');
$url = addLastCharacter($url);
$display .= "<div id='wp_email_capture_2'><form name='wp_email_capture_display' method='post' action='" . $url ."'>\n";
if (isset($_GET["wp_email_capture_error"])) {
$error = sanitize($_GET["wp_email_capture_error"]);
$display .= "<div style='width:80%;background-color: #FFCCCC; margin: 5px;font-weight'>Error: ". $error ."</div>\n";
}
$display .= "<label class='wp-email-capture-name'>Name:</label> <input name='wp-email-capture-name' type='text' class='wp-email-capture-name'><br/>\n";
$display .= "<label class='wp-email-capture-email'>Email:</label> <input name='wp-email-capture-email' type='text' class='wp-email-capture-email'><br/>\n";
$display .= "<input type='hidden' name='wp_capture_action' value='1'>\n";
$display .= "<input name='Submit' type='submit' value='Submit' class='wp-email-capture-submit'></form></div>\n";
if (get_option("wp_email_capture_link") == 1) {
$display .= "<p style='font-size:10px;'>Powered by <a href='http://www.gospelrhys.co.uk/plugins/wordpress-plugins/wordpress-email-capture-plugin' target='_blank'>WP Email Capture</a></p>\n";
}
return $display;
}
function wp_email_capture_display_form_in_post($content) {
$get_form = wp_email_capture_form_page();
$content = str_replace("[wp_email_capture_form]", $get_form, $content);
return $content;
}
?>
A: Here's my first attempt at a Stack Overflow answer:
Your form action currently directs to a different page, but you need it to lead back to the page you're already on. You can do this with a blank action attribute, like so:
<form action="">
Once you've done this, you can use the $_POST data on that same page. In the page div where you want the output, try something like this:
if($_POST['wp_capture_action'] == 1)
{
// The form has been submitted, so
// print the success/failure message here
}
else
{
// The form hasn't been submitted, so print
// the form here.
}
I hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Run windows phone 7.1 Emulator on Windows8 I'm having some problems with WindowsPhone 7.1 Emulator on Window 8 CTP; it looks like the emulator has some dependencies from OS version.
When I attempt to deploy it in Visual Studio, I receive the following error:
Error 1 Connection failed because of invalid command-line arguments. 0 0
I know that the CTP version of Win8 is not the best os for development now, but this question is interesting for me and our user group.
Online help message:
Windows Phone Emulator has been blocked from running because it might prevent your computer from starting correctly in the future.
Your version of Windows Phone Emulator isn't compatible with this version of Windows.
For information about possible solutions to this problem, go online to the following Knowledge Base (KB) article:
Click to go online to the Microsoft website for the KB article
Which version of Windows am I using?
You are using Windows 8.
A: It didn't work for me but some people said to worked for them
Now you can download WP 7.1.1 SDK that run on windows 8 :)
Here is the link
http://www.microsoft.com/download/en/details.aspx?id=29233
A: As you quoted,
Your version of Windows Phone Emulator isn't compatible with this version of Windows.
It seems to me that all you can do is wait for an update, or (somehow) find the emulator's source code and try to recompile it.
A: If you have a 32-bit version of Windows 8, you can safely run the Windows Phone 7.1 emulator in compatibility mode. Right click on the executable and click the compatibility tab. Check the 'Run the program in compatibility mode for' checkbox and select "Windows 7" from the list. Click Apply and away you go.
A: try install Windows phone sdk 7.1.1 -> http://www.microsoft.com/download/en/details.aspx?id=29233
but mostly people got error install when installing xna, before you install windows phone sdk you must install gwlivesetup from http://www.microsoft.com/en-us/download/details.aspx?id=5549. After that you must install or reinstall your WP SDK. Maybe it can help you.
A: The emulator just isn't supported on Win 8 as of yet.
What ever you do DO NOT try running the emulator with Administrative priviledges or you will see just how incompatible the emualtor is as you will get to see the new "chic" looking Windows 8 Blue screen of death.
There is definately a problem with the virual host used to run the emulator itself as other virtual solutions are still able to work like Virtual Box.
You can run the emualtor in a limited fashion using Virtualbox on a Win 8 machine but you will have no access to the toolbox or be able to run XNA
A: Just to let you know. It is really incompatible with Win8 due to the lack of some APIs in the new OS. It will be update in the future.
You can still develop using a real WP7 device if you have one, to debug and test our applications just fine in Win8.
A: I have installed VS2011 for windows phone in win 8 like this.
*
*Update .Net framework to version 3.5
*Insall Games for Windows Marketplace Client Setup for the xna to work in win 8
*Install Visual studio 2011.
*Install a patch for VS2011 to work with win8
And voila! :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: virtualenvwrapper functions unavailable in shell scripts So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the mkvirtualenv function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't run without these libraries.
I am trying to add a bin/run-app executable shell script which would be in my path (symlink actually). Now, inside this script, I need to switch to the virtualenv before I can run this program. So I put this in
#!/bin/bash
# cd into the project directory
workon "$(cat .venv)"
python main.py
A file .venv contains the virtualenv name. But when I run this script, I get workon: command not found error.
Of course, I have the virtualenvwrapper.sh sourced in my bashrc but it doesn't seem to be available in this shell script.
So, how can I access those virtualenvwrapper functions here? Or am I doing this the wrong way? How do you launch your python tools, each of which has its own virtualenv!?
A: I can't find the way to trigger the commands of virtualenvwrapper in shell. But this trick can help: assume your env. name is myenv, then put following lines at the beginning of scripts:
ENV=myenv
source $WORKON_HOME/$ENV/bin/activate
A: Just source the virtualenvwrapper.sh script in your script to import the virtualenvwrapper's functions. You should then be able to use the workon function in your script.
And maybe better, you could create a shell script (you could name it venv-run.sh for example) to run any Python script into a given virtualenv, and place it in /usr/bin, /usr/local/bin, or any directory which is in your PATH.
Such a script could look like this:
#!/bin/sh
# if virtualenvwrapper.sh is in your PATH (i.e. installed with pip)
source `which virtualenvwrapper.sh`
#source /path/to/virtualenvwrapper.sh # if it's not in your PATH
workon $1
python $2
deactivate
And could be used simply like venv-run.sh my_virtualenv /path/to/script.py
A: This is a super old thread and I had a similar issue. I started digging for a simpler solution out of curiousity.
gnome-terminal --working-directory='/home/exact/path/here' --tab --title="API" -- bash -ci "workon aaapi && python manage.py runserver 8001; exec bash;"
The --workingdirectory forces the tab to open there by default under the hood and the -ci forces it to work like an interactive interface, which gets around the issues with the venvwrapper not functioning as expected.
You can run as many of these in sequence. It will open tabs, give them an alias, and run the script you want.
Personally I dropped an alias into my bashrc to just do this when I type startdev in my terminal.
I like this because its easy, simple to replicate, flexible, and doesn't require any fiddling with variables and whatnot.
A: It's a known issue. As a workaround, you can make the content of the script a function and place it in either ~/.bashrc or ~/.profile
function run-app() {
workon "$(cat .venv)"
python main.py
}
A: If your Python script requires a particular virtualenv then put/install it in virtualenv's bin directory. If you need access to that script outside of the environment then you could make a symlink.
main.py from virtualenv's bin:
#!/path/to/virtualenv/bin/python
import yourmodule
if __name__=="__main__":
yourmodule.main()
Symlink in your PATH:
pymain -> /path/to/virtualenv/bin/main.py
In bin/run-app:
#!/bin/sh
# cd into the project directory
pymain arg1 arg2 ...
A: Apparently, I was doing this the wrong way. Instead of saving the virtualenv's name in the .venv file, I should be putting the virtualenv's directory path.
(cdvirtualenv && pwd) > .venv
and in the bin/run-app, I put
source "$(cat .venv)/bin/activate"
python main.py
And yay!
A: add these lines to your .bashrc or .bash_profile
export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
and reopen your terminal and try
A: You can also call the virtualenv's python executable directly. First find the path to the executable:
$ workon myenv
$ which python
/path/to/virtualenv/myenv/bin/python
Then call from your shell script:
#!/bin/bash
/path/to/virtualenv/myenv/bin/python myscript.py
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
} |
Q: XAML Storyboard Fadein - Fadeout Opacity Loop In my WPF application I have a ListBox which I'm customising the ItemTemplate. Within my ItemTemplate, I have a border for the Selected Item which I am using a StoryBoard to fade in/out from 0 - 1, then 1 - 0.
I'm now trying to figure out how to make it loop.
I tried to simply add a second Trigger Proprty for when the Opacity Value was 0 but this ended up applying to all items in the ListBox, not just the selected item.
<Storyboard x:Key="FadeUpAndFlash">
<DoubleAnimation From="0" To="1" Storyboard.TargetProperty="(UIElement.Opacity)" Duration="0:0:1" FillBehavior="Stop"/></Storyboard>
<Border x:Name="HighlightBorder" BorderBrush="Yellow" BorderThickness="3" Margin="0,0,5,0" CornerRadius="10" ClipToBounds="True">
<Border.Style>
<Style TargetType="{x:Type Border}">
<Setter Property="Opacity" Value="0"/>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" Value="True">
<DataTrigger.Setters>
<Setter Property="Opacity" Value="1"/>
</DataTrigger.Setters>
<DataTrigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource FadeUpAndFlash}" Name="AnimateImageBorder" />
</DataTrigger.EnterActions>
</DataTrigger>
<Trigger Property="Opacity" Value="1">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:2"/>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
Any ideas how I can get the Storyboard to loop?
A: Use AutoReverse="True" in your DoubleAnimation.
And RepeatBehavior="Forever" if you want to make it endless.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Not getting all the photos user is tagged in facebook I am comparing my results with the graph api explorer. I have a dummy account with 6 tagged pictures of mine.
From iOs using FBGraph i get access token with permission "user_photos"
On calling me/photos I get back only one photo.
If i generate access token from graph api explorer with same "user_photos" permission, i get back all 6 photos.
Can anyone enlighten me why do I not get all the photos I am tagged in.
Regards
A: you're not getting the photos from the albums, you're getting only the non-albumed photos.
get the albums list, with something like this,
- (NSMutableArray*)getAlbums{
NSLog(@"get pictures");
NSMutableArray* _albums = [[NSMutableArray alloc] init];
NSString* requestString = [NSString stringWithFormat:@"%@/%@/albums?access_token=%@",FACEBOOK_GRAPH_URL,[defaults valueForKey:@"facebook_id"],[defaults objectForKey:@"FBAccessTokenKey"]];
ASIHTTPRequest* request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:requestString]];
[request startSynchronous];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *dddd = (NSDictionary *) [parser objectWithString:[request responseString] error:nil];
NSDictionary *data = [dddd objectForKey:@"data"];
for(NSDictionary* k in data){
NSLog(@"album %@, count %@",[k valueForKey:@"id"],[k valueForKey:@"count"]);
if([k valueForKey:@"count"] && [[k valueForKey:@"count"] intValue] > 0)
[_albums addObject:[NSMutableDictionary dictionaryWithDictionary:k]];
}
for(NSMutableDictionary* album in _albums){
NSMutableArray* a = [self getPicturesForAlbum:[album valueForKey:@"id"]];
[album setValue:a forKey:@"photos"];
}
return _albums;
}
you'll get an NSArray of NSDictionaries, and in each a photos array as a dictionary just like you get them from facebook in the function you describe above.
- (NSMutableArray*)getPicturesForAlbum:(NSString*)albumNo{
NSLog(@"get pictures");
NSMutableArray* pics = [[NSMutableArray alloc] init];
NSString* requestString = [NSString stringWithFormat:@"%@/%@/photos?access_token=%@",FACEBOOK_GRAPH_URL,albumNo,[defaults objectForKey:@"FBAccessTokenKey"]];
ASIHTTPRequest* request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:requestString]];
[request startSynchronous];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *dddd = (NSDictionary *) [parser objectWithString:[request responseString] error:nil];
NSDictionary *data = [dddd objectForKey:@"data"];
for(NSDictionary* k in data){
for(id i in [k allKeys]){
if([i isEqualToString:@"source"]){
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setValue:[k valueForKey:i] forKey:@"photo"];
[dict setValue:[k valueForKey:@"created_time"] forKey:@"created_time"];
[dict setValue:[k valueForKey:@"picture"] forKey:@"thumb"];
if([k valueForKey:@"name"])
[dict setValue:[k valueForKey:@"name"] forKey:@"name"];
[pics addObject:dict];
}
}
}
return pics;
}
and then check for each album, which are the photos in it which you need.
hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to save uploaded images to a MongoDB collection, and retrieve it I want to save uploaded files such as a user's avatar image to user collection in MongoDB, I guess the steps are:
*
*user upload a image;
*use a FileHandler (IHttpHandler, Asp.net) to accept the file stream in web server;
*then I get that file binary and set it to a User class object
*finally save the object, so the user collection will get the file binary data.
Am I right about this? Could you give me any clue?
A: You should just use GridFS to do it - there is no reason why you should worry about files being too large or too small for it to make sense. GridFS was designed to store files so you should use it.
You could always store a reference to the GridFS file in a normal MongoDB document if you need to, and then load it out of GridFS when you need to use it.
See this thread: MongoDB GridFs with C#, how to store files such as images?
A: According to Mongo grid fs documentation. If your files are all smaller than the 16 MB BSON Document Size limit, consider storing each file in a single document instead of using GridFS. You may use the BinData data type to store the binary data. See your drivers documentation for details on using BinData.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Swing Painting issue? I have a JPanel extension called TPanel, which paints the word Tetris on the right hand side of the JFrame. The curr() method returns the current piece that is moving, and is bounded to the left side (x < 400) of the JFrame. Now for some reason when I add them both to the JFrame I can only see the second one I added, so basically it overrides the other one. I have tried the validate method and it doesn't work.
How do I show them both simultaneously?
Here's the code:
public Tetris()
{
// frame stuff
super("Tetris");
this.setSize(616,636);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_O…
// components
occ = new boolean [30][20];
rnd = new Random();
info = new TPanel();
for(int i=0;i<occ.length;i++)
for(int j=0; j< occ[i].length;j++)
occ [i][j] = false;
pieces.add(initPiece());
this.getContentPane().add(info);
this.getContentPane().add(curr());
this.getContentPane().validate();
repaint();
this.addKeyListener(this);
run();
}
A: *
*The default layout of a content pane is BorderLayout
*If a component is added to a BorderLayout with no constraint, it is placed in the CENTER.
*The CENTER position can only contain one component or container.
So as an immediate guess on how to fix the code snippet, try changing:
this.getContentPane().add(curr());
To:
this.getContentPane().add(curr(), BorderLayout.LINE_END);
Or better still:
add(curr(), BorderLayout.LINE_END);
A: *
*Strange code snippet, not compilable (for example setDefaultCloseOperation(EXIT_O…)
*getContentPane() is useless in Java 5 and higher, remove that
*You have set Focus for TPanel
*Look for KeyBindings instead of KeyListener, then your keys will be works correctly
*Add KeyBinding to TPanel
*I hope that you have Icons for Tetris,
*
*Put JLabels to the TPanel
*JLabel.setIcon(myTetrisIcon)
*Your code could be outside of EDT, more in "Concurency in Swing", wrap output to the GUI (code for Icon Repainting) into invokeLater()
*Use only javax.swing.Timer for animations
*Use revalidate() and repaint()
*But if is there custom painting in Swing then problem(s) should came from anywhere
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Redirecting 201109 to 2011/09 in nginx I'm trying to redirect /201109/ to the directory /2011/09/, but I'm not sure how to do it. This is what I have so far in nginx.conf:
rewrite ^/([0-9]{4})([0-9]{2})/(.*) http://www.domain.com/$2/$3/$4 permanent;
That results in an error:
nginx: [emerg] directive "rewrite" is not terminated by ";" in /usr/local/nginx/conf/nginx.conf:20
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
Any idea what to do? Thanks in advance!
A: It is the braces ("{" & "}") causing it to fail. As braces have specific meanings in Nginx, when you use them in nginx regexes, you need to enclose the regex string in double quotes.
So this should work for you:
rewrite "^/([0-9]{4})([0-9]{2})/(.*)" http://www.domain.com/$1/$2/$3 permanent;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Text (command line) based Java IDE Probably question title might looks strange for you, but I'll try to explain.
I do looking alternative of desktop eclipse, ideally what I need is to edit sources directly on my linux dev-server. On dev server I don't have any xwindows just command line. So I would like to login to server using Putty, develop, build, run, commit changes to source control system.
From text editor I would need:
*
*syntax highlight
*autocomletion (at least basic)
*quick navigation trough project files
*basic refactoring: change class name? move class to other
package,change method signature
*run build without need to leave editor window
*run svc/git commands without need to leave editor window
From the first glance emancs seems to be what I need, but I don't sure.
Thanks.
A: I think that you approach is not good. Developing directly on your devel server is not a good practice. But it's not the question...
Personally, my favorite text editor for programming is emacs. I'm also a Java developer. I'm using Eclim. According to the Eclim Website :
The primary goal of eclim is to bring Eclipse functionality to the Vim editor. The initial goal was to provide Eclipse’s java functionality in vim, but support for various other languages (c/c++, php, python, ruby, css, html, xml, etc.) have been added and several more are planned.
As I said, I use mainly Emacs. So, I'm using emacs-eclim (the Vim plugin is very cool and advanced) :
Eclim is an Eclipse plugin which exposes Eclipse features through a server interface. When this server is started, the command line utility eclim can be used to issue requests to that server.
Emacs-eclim uses the eclim server to integrate eclipse with emacs. This project wants to bring some of the invaluable features from eclipse to emacs.
If you use Emacs, you can also use the JDEE mode. Personally, I don't like this mode : too complicated, not enough maintained.
A: Sandro's answer is a good one for a true command-line tool. On unix, emacs and vim are really the only games in town when it comes to sophisticated command-line editors, so a good Java mode for one of those is what you want.
However, i want to point out that even if the server doesn't have an X server, you can still run graphical programs on it - they just have to connect to an X server on another machine, such as your desktop. Sounds weird, but that is actually the whole point of X windows: it was originally developed so that people could run programs on powerful time-shared machines, and access them from cheap, dumb graphical terminals (this was back in the early 80s when people thought that was a good idea).
These days, the easiest way to do this is to use SSH to connect to the remote machine, telling it to enable X11 forwarding. With the OpenSSH command-line SSH, this is as simple as adding the -X flag; i'm not sure how you do it with PuTTY, but i'm sure it's possible. Once you've logged in with X11 forwarding enabled, you can simply run X clients (such as Eclipse or IDEA), and they will connect to your local X server.
Oh - you will need a local X server. On Windows, you can install Xming
All of this takes a bit of work (although not a lot!), so if you just want to do occasional hacking, my all means go with Eclim. But if you are planning on doing a lot of remote development, and you don't have a lot of affection for curses interfaces, this might be the most comfortable route.
A: Do some reading about Tramp in Emacs as well. That allows you to run Emacs locally, but edit remote files as if they were local, using any of a variety of network protocols (but typically ssh). Shell commands initiated from a buffer editing a remote file will also execute on the remote server.
That's sort of the opposite of what you were asking for, and more useful when you don't want to have to set up Emacs and your custom configurations on another machine (or can't do so), but it's worth knowing about. If your local machine is running Windows, and you are using putty, you would need to use the plink method in Tramp.
I believe that vim has some similar functionality, also.
Or if you can mount the remote server's filesystem with sshfs, you would achieve a similar end result (local editor manipulating remote files), and potentially open up your options to utilise more familiar editors to do the work.
A: emacs and vim can do what you want. However unless you are familiar with these tools already, you should know that using them is nothing like using a GUI. I suggest you make it so you can edit source from your PC which are changed directly on your linux server. There are any number of ways you can do this.
I assume you don't have xwindows because this server is very limited??
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Modal dialogbox or form error in IIS I keep getting this error when I deploy my application in the server machine (Windows 7, IIS 7).
"Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application."
The problem is I dont have any MessageBox call inside the code. What I did is, generated a DLL from PowerBuilder 12 and added the DLL in a .NET website to generate some reports. Any solution to this? Let me know if you need me to provide any other information. I really need help on this.
Heres the stacktrace:
[InvalidOperationException: Showing a modal dialog box or form when
the application is not running in UserInteractive mode is not a valid
operation. Specify the ServiceNotification or DefaultDesktopOnly style
to display a notification from a service application.]
System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String
text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon,
MessageBoxDefaultButton defaultButton, MessageBoxOptions options,
Boolean showHelp) +2661926
System.Windows.Forms.MessageBox.Show(String text) +37
c__app_web_main.InitAssembly() +168 APP_WEB.n_app_web_main..ctor()
+18 ASP_TEST.getobject.GetData(String queryString) in
C:\Projects\ERP\ASP_TEST\ASP_TEST\getobject.aspx.cs:29
ASP_TEST.getobject.Page_Load(Object sender, EventArgs e) in
C:\Projects\ERP\ASP_TEST\ASP_TEST\getobject.aspx.cs:20
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object
o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,
EventArgs e) +35 System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+627
EDIT:
The problem occurs when I'm initializing the PB generated assembly, its throwing me an exception and trying to warn me with a messagebox. The assembly works fine in my local pc and my colleagues, so there has to be some security setting in IIS which is causing this problem.
A: I bet you that if you decompile the DLL using ILSpy you'll find references to Message.Box. You could probably recover the source code and remove the offending piece of code.
A: This problem was solved by signing the custom DLL generated from PowerBuilder 12 with a key .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Convert C++ to MIPS assembly This code is about to find maximum element from an array i want to convert this code into MIPS assembly code can anyone help me...Or just tell me how to initialize an array in MIPS.
void max_array()
{
int a[10]={2,3,421,4,32,4,3,1,4,5},max;
for(int i=0;i<9;i++)
{
cout<<a[i];
}
max=a[0];
for(int j=1;j<9;j++)
{
if (max<a[j])
{
max=a[j];
}
}
return max;
}
A: Here's an example
.data
array1: .space 12 # declare 12 bytes of storage to hold array of 3 integers
.text
__start: la $t0, array1 # load base address of array into register $t0
li $t1, 5 # $t1 = 5 ("load immediate")
sw $t1, ($t0) # first array element set to 5; indirect addressing
li $t1, 13 # $t1 = 13
sw $t1, 4($t0) # second array element set to 13
li $t1, -7 # $t1 = -7
sw $t1, 8($t0) # third array element set to -7
done
A: .data # variable decleration follow this line
array1: .word 2, 3, 421, 4, 32, 4, 3, 1, 4, 5 #10 element array is declared
max: .word 2
la $t0, array1 #load base address of array1
main: #indicated the start of the code
#to access an array element ($t0), 4($t0), 8($t0)..........
A: convert to mips
addi $t1, $0, 99
addi $t4, $0, 9
add $t3, $t2, $t1
sub $t3, $t3, $t4
loop: lw $s1, 0($t2)
lw $s2, 0($t3)
slt $s3, $s1, $s2
beq $s3, $0, label1
sub $s4, $s2, $s1
sw $s4,0($t3)
j label2
label1:
sub $s4, $s1, $s2
sw $s4,0($t3)
label2:
addi $t2, $t2, 4
addi $t3, $t3, 4
subi $t1, $t1,1
beq $t1, $0, loop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why doesn't my textbox show over my canvas element? I'd like to use Raphael.js and create some nice diagrams / SVG graphics for my site. I want users to be able to enter text content which would normally be via a <input type="text"> element in normal html.
Is there anyway that I can use this element on top of a <canvas> element, so that I can have my user enter text that way, or do I have to roll my own by listening for keystrokes and painting the characters onto the element?
Rephrasing Question
Why can't I see the text field if I do this:
<canvas style="background-color:blue;height:100px;width:100px>
<input type="text" style="background-color:white;z-index:101" />
</canvas>
and if this is not possible, what are the alternatives?
Many thanks
A: There needs to be some way to fallback to alternative content (like a static image or a text "Get a browser with canvas support") for older browsers that do not understand the canvas element. The children of the canvas element are designated for that purpose.
You can, however, position the input over the canvas with position:absolute (relative, or static):
<canvas style="background-color:blue;height:100px;width:100px">
</canvas>
<input type="text" style="z-index:101; position:absolute; top:10px; left:10px;"/>
Here's a live demo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What happened to Microsoft Blueprints? And what should I use instead? Microsoft had this project called Blueprints as a replacement for Guidance Automation but then, all of a sudden, it dissappeared. So my question is - what can I use instead?
A: Blueprints has been superseded by the Feature Builder Power Tool.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Initializing nested complex types using Reflection Code tree is like:
Class Data
{
List<Primitive> obj;
}
Class A: Primitive
{
ComplexType CTA;
}
Class B: A
{
ComplexType CTB;
Z o;
}
Class Z
{
ComplexType CTZ;
}
Class ComplexType { .... }
Now in List<Primitive> obj, there are many classes in which ComplexType object is 'null'. I just want to initialize this to some value.
The problem is how to traverse the complete tree using reflection.
Edit:
Data data = GetData(); //All members of type ComplexType are null.
ComplexType complexType = GetComplexType();
I need to initialize all 'ComplexType' members in 'data' to 'complexType'
A: If I understand you correctly perhaps something like this would do the trick:
static void AssignAllComplexTypeMembers(object instance, ComplexType value)
{
// If instance itself is null it has no members to which we can assign a value
if (instance != null)
{
// Get all fields that are non-static in the instance provided...
FieldInfo[] fields = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (FieldInfo field in fields)
{
if (field.FieldType == typeof(ComplexType))
{
// If field is of type ComplexType we assign the provided value to it.
field.SetValue(instance, value);
}
else if (field.FieldType.IsClass)
{
// Otherwise, if the type of the field is a class recursively do this assignment
// on the instance contained in that field. (If null this method will perform no action on it)
AssignAllComplexTypeMembers(field.GetValue(instance), value);
}
}
}
}
And this method would be called like:
foreach (var instance in data.obj)
AssignAllComplexTypeMembers(instance, t);
This code only works for fields of course. If you want properties as well you would have to have the loop iterate through all properties (which can be retreived by instance.GetType().GetProperties(...)).
Be aware though that reflection is not particularly efficient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Restrict servlet response I have a web server which has lot of hits from automated machines. Those machine sends their status on web server to store in db. Some of hits are useless so I want to avoid those request's responses because those useless responses generate lot of traffic on network. My question is that "How to restrict servlet response for unwanted traffic."
A: I'd return a sensible HTTP 4xx client error. Which one to choose depends on the "uselessness" of those requests.
If those requests are bad because of for example missing parameters, return HTTP 400 Bad Request.
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
If those requests are forbidden due to improper authorization, return HTTP 403 Forbidden.
response.sendError(HttpServletResponse.SC_FORBIDDEN);
If the client is smart enough, they will get logged and the responsible admin/developer should look into it and eventually fix it. This is a win-win sitution.
A: Your servlet is not forced to return anything if you don't want to. If you do not return a response, the connection will be closed and no traffic will be generated.
By the way, depending on your scenario, it could be possible to keep a long-lasting HTTP connection between the client (automated machines) and the web server. This way you do not need to open a new connection for each request and you can save some bytes, if the higher complexity is worth it.
A: First you should try to avoid these request, try an exclusion file in your server. If that does not work, just send a forbidden (403 status) as response for requests you identified as "useless" - normally by scanning the user agent header for specific bots.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to share code snippets among several installations of Xcode? Based in part on the advice in this response to a question on SO, I tried replacing /Developer/Library/Xcode/PrivatePlugIns/IDECodeSnippetLibrary.ideplugin with an alias to an exact copy in a Dropbox folder, but doing so caused Xcode 4.2 to crash due to an internal logic error.
I want to sync the snippets on my work and home machine. Right now I'm using Alfred for snippets, but it'd be nice to have Xcode handle the snippets, for convenient tab jumping and intellisense. Has anyone out there attempted something similar?
A: as i do and it work.
simply copy your code snippets in
~/Library/Developer/Xcode/UserData/CodeSnippets/
if your didn't made any custom code snippets before then you have to copy whole 'CodeSnippets'
dir to path
~/Library/Developer/Xcode/UserData/
now simply close the xcode from activity monitor and start it again you will get new code snippets.
/ use the following code to show hidden file /
apply this command one by one in teminal
defaults write com.apple.Finder AppleShowAllFiles TRUE
killall Finder
A: I guess sharing your own (not the system) snippets is fine. Then, try replacing
~/Library/Developer/Xcode/UserData/CodeSnippets with a symbolic link to your shared folder.
Something like: (in Terminal app)
cd ~/Library/Developer/Xcode/UserData
mv CodeSnippets /path/to/shared/folder/
ln -s /path/to/shared/folder/CodeSnippets CodeSnippets
Repeat in any Mac in which you want to access shared snippets.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How do I use facebook->getLoginStatusUrl()? I currently redirect the user to the url given and it returns the user back to the web page with 2 get arguments: 'session' and 'perms'.
The meaning of perms is obvious.
Session appears to be a JSON slash escaped array. After json_decode(slashcstrip($_GET['session'])) i find the following members: uid,session_key,secret,expires,base_domain,access_token, sig. What are secret and sig? How do I use them to validate the data?
Thanks!
A: The sdk validates the data for you using that session information. All you need to do is call $facebook->getUser() and check that you get back a user id.
A: $next_url = $facebook->getLoginStatusUrl($params); retrieve fb user Login Status
A: From what I understand the status URL is used to determined the status of a user. If you do an HTTP call to the the generated status URL facebook will redirect to one of the redirect urls based on the user status, you can use the request of the URL to update the user session on your application and take a handling action for the state of the user
ok_session => user has facebook session -> start app
no_user => unknown user, ask user to login
no_session => known user, ask to login
A: Follow these steps:
*
*You generate an url: $next_url = $facebook->getLoginStatusUrl();
*redirect the user to this url: header('Location: '.$next_url);
*the user will be returned by FB with session information about the login status
*the SDK will parse the returned info
*use $facebook->getUser(); to get the access_token and userid (if logged in)
So far so good.
The only problem is, this function (point 4) is broken since the transition to oAuth2.0 by Facebook API, see also this bug report:
http://developers.facebook.com/bugs/295348980494364
The returned $_GET['session'] is useless in the new oAuth2.0 SDK, it was used in the old PHP-SDK v2 (current is 3.1.1).
So please let FB know that you have the same issue by adding a reproduction.
Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to set my android app as a Lock Screen? I want to develop my custom Android Lock Screen. So that if I install that app in any phone, it replace the default lock screen. Any guidance?
A: I have done it with the help of this project.
This project will help anyone trying to develop similar app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: In IMetadataImport or MonoCecil, how can I find out out if a method in an internal class is accessible from other assembiles? One of the cases where a public method of an internal class might be accessible from outside the assembly is if the method implements interface methods or overrides virtual methods that are defined in a public base class.
Using IMetadataImport, how can find out if this is the case for a specific mdMethodDef?
Update: I'd also like to know how to do this in Mono.Cecil, as that might help me figure out how to do it in IMetaDataImport.
A: If I take this C# sample:
public interface ITest
{
void DoSomething();
}
public class Test : ITest
{
public void DoSomething()
{
}
}
Here, the Test class successfully implements the ITest interface, as defined in C# specification (for example 13.4.2 Interface mapping)
If you examine the result of this code in the compiled assembly (using a tool such as .NET Reflector or ILDASM), you will see this:
.method public hidebysig newslot virtual final instance void DoSomething() cil managed
{
.maxstack 8
L_0000: nop
L_0001: ret
}
And... yes...there is nothing here in the assembly metadata that will relate the DoSomething method in Test to the DoSomething method in ITest.
In VB.NET, it's different, you will need to add an Implements keyword to make sure it compiles:
Public Interface ITest
Sub DoSomething()
End Interface
Public Class Test
Implements ITest
Public Sub DoSomething() Implements ITest.DoSomething
End Sub
End Class
As you see, with VB.NET, you need to explicitely relate the method in the class with the method in the interface, and if you analyse what IL has been created in the assembly in the VB.NET case, you'll find this:
.method public newslot virtual final instance void DoSomething() cil managed
{
.override TestVB.ITest::DoSomething
.maxstack 8
L_0000: nop
L_0001: nop
L_0002: ret
}
So, with a VB-compiled assembly, the information is there, with a C#-compile assembly, it's not. It depends on the language. The CLR engine will in fact to the mapping at runtime.
If you can inject the assemblies in your process, this code can help you determine interface mapping:
InterfaceMapping im = typeof(Test).GetInterfaceMap(typeof(ITest));
But if you need to determine this only looking at metadata, you'll have to write that code yourself. It's not that easy, especially with generics. Also don't forget in C#, a public method can implicitely implement multiple interfaces.
A link that can help: Mono.Cecil something like Type.GetInterfaceMap?
A: Here's a bit of help wrt Cecil - it does not cover 100% of your question but it may get you close enough as-is or with a bit of additional work.
Many of Gendarme rules have to check methods (or types, fields) visibility so an extension method, IsVisible, was created to deal with most of required checks. And by most I mean there's one thing that is not (yet) implemented is support for the [InternalVisibleTo] attribute.
For methods looks in MethodRocks.cs, other files contains IsVisible extension methods for TypeDefinition and FieldDefinition and a lot of other extensions method you can find useful when working with Cecil.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Routed events and dependency properties .NET wrapper confusion I'm new to WPF and have a confusion about wrapping syntax of routed events and dependency properties
I've seen on many sources that routed events and dependency properties are wrapped like this
// Routed Event
public event RoutedEventHandler Click
{
add
{
base.AddHandler(ButtonBase.ClickEvent, value);
}
remove
{
base.RemoveHandler(ButtonBase.ClickEvent, value);
}
}
// Dependency Property
public Thickness Margin
{
set { SetValue(MarginProperty, value); }
get { return (Thickness)GetValue(MarginProperty); }
}
I have never seen add / remove / set / get sort of keywords in C#. Are these are part of C# language as Keywords and i never experienced or worked with them because i didn't worked in C# as pro i'm a C++ programmer? If not keywords then how they are handled by compiler if they are not part of C# and how they are working
A: I'm gonna try to sum it up for you:
Dependency property:
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), new UIPropertyMetadata(MyDefaultValue));
That's the full syntax, you don't have to memorize it, just use the "propdp" snippet in Visual Studio.
The "get" must return a value of the type it refers to (in my example, int). Whenever you call
int MyVar = MyProperty;
The code inside "get" is evaluated.
The set has a similar mechanism, only you have another keyword: "value" which will be the value you assign to MyVariable:
MyProperty = 1;
Will call the "set" of MyProperty and "value" will be "1".
Now for the RoutedEvents:
In C# (as in C++, correct me if i'm wrong), to subscribe to an event, you do
MyProperty.MyEvent += MyEventHandler;
That will call the "add" --> you're adding a handler to the stack.
Now since it is not automatically garbage-collected, and we want to avoid memory leaks, we do:
MyProperty.MyEvent -= MyEventHandler;
So that our object can be safely disposed of when we don't need it anymore.
That's when the "remove" expression is evaluated.
Those mechanism allow you to do multiple things on a single "get", a widely used example in WPF would be:
private int m_MyProperty;
public int MyProperty
{
get
{
return m_MyProperty;
}
set
{
if(m_MyProperty != value)
{
m_MyProperty = value;
RaisePropertyChanged("MyProperty");
}
}
}
Which, in a ViewModel that implements INotifyPropertyChanged, will notify the bindings in your View that the property has changed and need to be retrieved again (so they will call the "get")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Processing multiple nested templates using freemarker(or any other template engine) I am trying to use FreeMarker to write a complex web page using servlets.
The page has 3 basic components: the nav-bar on top, the advertising-bar on left and the main content section in middle. I have a separate servlet to draw each one of these. Each servlet just churns out a html5 section, and may or may not use freemarker.
All of the above are ofcourse inside the main web page which is templated with freemarker.
The problem is this.
The template of main page looks something like this(striped lots for simplicity):
<html>
<body>
<!--lots of stuff in between-->
<section-nav> <!--this should be filled by output of NavServlet.respond -->
<!--lots of stuff in between-->
<section-content> <!-- this comes from arbitrary servlet for actual content -->
<section-advertise> <!--this should be filled by output of AdvertiseServlet -->
</body>
</html
How to handle the above structure using FreeMarker?
If I do template.process() for the main page it would write both the html start and end tag, but what I want is give other servlets(nav, advertise etc.) a chance to produce content before the html end tag.
If we cant use FreeMarker for this, I could use others templating solutions as well.
A: You should implement TemplateDirectiveModel to create a custom directive in Java (as opposed to in FTL, i.e., with #macro). When called from a template (something like <@my.embed source="thisAndThatServlet" />), it will receive a Writer, and you write whatever you want into that. Thus, of course, you can include other servlets, or do whatever is doable in Java. (Nested Template.process calls are supported.) See the source code of freemarker.ext.servlet.IncludePage as an example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Don't I have to call super() in constructor when class extends Sprite in actionscript3? I always don't call super() when I extends Sprite.
But doesn't not calling super() cause any problem?
Till now, I don't have any problem and I have never seen code which call super() in constructor which class extends Sprite.
How about TextField?
I don't have any problem about TextField, too.
How to know whether I should call super() or not?
A: If you don't call super() explicitly, Flash will do it automatically before all other code in your constructor.
If you call super() explicitly, it will be called at the line on which you wrote it.
However, note that you can not set or get any this or super properties or call any methods before the super class is instantiated
A: If flash doesn't detect a call to super() in your child constructor then flash will implicitly call super() before your child's constructor. So:
public class Parent {
public function Parent() {
trace("Parent");
}
}
public class Child extends Parent {
public function Child() {
trace("Child");
}
}
new Child();
// Parent
// Child
So your child constructor essentially looks like this
public function Child() {
super(); // <-- Added by flash!
trace("Child");
}
So, no, omitting an explicit call to super() will not usually adversely affect your child's class.
So why would you want to explicitly call super()?
The first reason is flash will only ever automatically generate a parameterless call to super, meaning that if your parent classes constructor requires arguments, then you will need to explicitly call it with those arguments. If you omit the super(args...) call in this case, you will get a compiler error.
Second, if even your parent has a parameter-less constructor, you can use super() to control the order that the constructors execute. Flash will always insert the call before the childs constructor. So if you wanted to change that order. Then
public class Child extends Parent {
public function Child() {
trace("Child");
super()
}
}
would do it in the opposite order. Or you could do:
public class Child extends Parent {
public function Child() {
// work before initilizing parent
super()
// work after initilizing parent
}
}
Lastly, there is a very obscure way to not call your parents constructor by saying:
public class Child extends Parent {
public function Child() {
if(false) super()
}
}
Because flash sees there is a call, it doesn't insert one. However because its behind a if (false) it never gets called, so the parent class never gets initialized.
A: You can safetly exclude the call to the base constructor. If you do not call super() in the constructor, the compiler will add a call to the base constructor with no arguments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: sql server table data in Flash dynamic textbox using Asp.net i have dynamic text-fields in flash (AS 3) and button on my form. my backend is sql server and i want show data in text-fields on button click event. i m using asp.net as server side script.
I have Form in Flash and i want to fetch data in form on flash button click event from sql server .
Thanx
A: It will help you..
var urlRequest:URLRequest = new URLRequest("your aspx page url");
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
btn_submit.addEventListener(MouseEvent.CLICK, btn_submit_click);
function btn_submit_click(e:Event)
{
urlLoader.load(urlRequest);
}
function urlLoader_complete(e:Event)
{
txt_box.text = e.target.data.aspx_var;
}
you need to just print varible in your aspx page. like in PHP i am writing this(bcause i don't know aspx).
<?
echo "aspx_var=value";
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: QGraphicsView make scene scale to full width I subclassed QGraphicsView and show the widget in my layout. Within the view I naturally have QGraphicsScene.
I can retrieve the QGraphicsScene size perfectly fine (namely 2100x2970 like I set), however the geometry of the QGraphicsView widget is incorrect. Whenever I resize the main window, the layout changes and so does the view widget change. Of course, the size of QGraphicsScene is irrelevant and stays whatever it is. But the widget showing the scrollbars and the scene through the viewport just doesn't provide me with the correct widget width and height.
In the QtDesigner the QGraphicsView widget shows to have QWidget geometry of 1126x643. But I can never retrieve these values in the subclassed QGraphicsView class.
When I know the width (1126 or something else when main window is resized) I can calculate the scale factor for the view (scale factor = 1126 / 2100) to get the scene to cover the full width of the view widget.
In QGraphicsView:
qDebug("scene: %f %f", scene()->width(), scene()->height()); // works (2100x2970)
qDebug("geo: %f %f", geometry().width(), geometry().height()); // does not (0x2970)
A: Have you looked at QGraphicsView::fitInView()? This method will do the needed scale calculations for you automatically.
A: Apparently when using the wrong format in qDebug the output is unpredictable. When using:
qDebug("geo: %i %i", geometry().width(), geometry().height());
indeed the correct size is displayed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Contains and Replace string with image in android
Possible Duplicate:
webserivce messages in listview with smileys
How can i replace string with image coming from .net web service in android.
I get data as hi :). i need to replace that special charcter to corresponding image that s available in my drawable folder.
How can i achieve that. I have tried with contains and replace. But it was of no use.
Kindly guide me in this issue .
Thanks.
Regards,
Raghav Rajagopalan
A: You can use something called ImageGetter. You can refer to this answer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Random weighting in C# I'm creating a game in C#, and a crucial part of the game is randomness. It's essentially a wrestling simulator, where 'moves' are selected on a table depending on a number of factors, such as wrestlers attributes and current momentum.
Then out of all the moves that that match this criteria, a random one is selected to be executed using the Random object and Skip/Take in LINQ But this is really not enough. What I want to do is weight moves probability of being chosen (I already have a column on the moves table for this, for an integer between 1 and 100). How would I implement this weighting into my random row selection?
A: Some code would be helpful for me to understand exactly what you need, but I suggest using the Random .NET library function. Some documentation can be found here:
http://msdn.microsoft.com/en-us/library/system.random.aspx
This example generates 5 random integers
Random rand = new Random();
Console.WriteLine("Five random integer values:");
for (int ctr = 0; ctr <= 4; ctr++)
Console.Write("{0,15:N0}", rand.Next());
Console.WriteLine();
This will seed it with the current time to make it "more random". If you want reproducible tests, you can seed it with a constant while testing.
A: Add up the total weight of each possible move.
Divide each one by that total, so you've normalized the range to 0..1.
Get a random number in that range. Choose a consistent order for each move and pick the one that the random number is within.
A: this is not too difficult. I have no code to work with so I assume you have objects Move with an attribute Weight inside a array and all weights sum up to 100.0 (don't really matter).
Now you sort the array by weights decending, pick a random number between 0 and 99 and iterate through all this decreasing your random number. As soon as it not positive anymore you stop and pick the current index/move
var value = rnd.NextDouble()*100.0;
foreach(var move in moves.OrderByDescending(m => m.Weight))
{
value -= move.Weight;
if (value <= 0) return move;
}
of course you can cache the ordering or even the picks into a big array and use a random-index into this (for performance) but the priciple should be clear I hope.
As George suggested - here is a version where you can drop to assume that the weights sum up to 100:
double _weightSum;
...
// initialize the Sum somewhere
_weightSum = moves.SumBy(m => m.Weight);
Move GetRandomMove()
{
var value = rnd.NextDouble()*weightSum;
foreach(var move in moves.OrderByDescending(m => m.Weight))
{
value -= move.Weight;
if (value <= 0) return move;
}
}
A: I looked at doing basically the same thing as Carsten, but with Linq.
given moves is a collection of Moves each with an integer property of Weight
public Move PickRandomMove()
{
var allMovesWeight = moves.Sum(m => m.Weight);
// pick a unit of weight at random, then shift it along by the weight of the
// first move so that there will always be an element in the TakeWhile results
var randomPick = new Random().Next(0, allMovesWeight) + moves.First().Weight;
return moves.TakeWhile(move => (randomPick -= move.Weight) > 0).Last();
}
I suspect there's a clearer way of expressing how the TakeWhile is working, but hopefully you get the idea
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java process pegging CPU at 100% We have an application which is running normally in a variety environments. However, at one client site when the application invokes a child process (in this case CODEFIND.EXF - please see enclosed displayed) it pegs the processor at 100%. I need help in interpreting the display. Although the display seems to indicate that the parent process is consuming all the resources, could it in fact be due to the child process that the parent process invoked? How could I tell this?
Thank you,
Elliott
A: The display indicates that the culprit is java.exe. That indication is correct. The child process is not consuming CPU.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Passing arguments to views in Django from constrained choices I am looking for the best way to pass either of two arguments to the views from the URL, without allowing any additional arguments.
For example, with the following URLs:
(r'^friends/requests', 'app.views.pendingFriends'),
(r'^friends/offers', 'app.views.pendingFriends'),
If it's possible to pass the URL to the views, so that pendingFriends knows which URL it was called from, that would work. However, I can't see a way to do this.
Instead, I could supply the arguments (requests or offers) in the URL, to a single Django view,
(r'^friends/(?P<type>\w+', 'app.views.pendingFriends'),
The argument will tell pendingFriends what to do. However, this leaves open the possibility of other arguments being passed to the URL (besides requests and offers.)
Ideally I'd like the URL dispatcher to stop this happening (via a 404) before the invalid arguments get passed to the views. So my questions are (a) is this the best approach, (b) is there a way to constrain the arguments which are passed to the views in the URL to requests or offers?
Thanks
A: Remember that you have the full power of regexes to match URLs. You simply need to write a regex that accepts only what you want:
(r'^friends/(?P<type>requests|offers)', 'app.views.pendingFriends'),
If you want to list it twice, do it like this:
(r'^friends/(?P<type>requests)', 'app.views.pendingFriends'),
(r'^friends/(?P<type>offers)', 'app.views.pendingFriends'),
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: UINavigationBar displays incorrectly when combine with UITabBarController I'm trying to create Home Screen for UITabBarViewController with another UINavigationViewController and UIViewController Subclass.
In application,There are:
*
*two Tab for loading NewsController and VideoController
*HomeViewController that loads immediately when application finish launch.
This is my application shot screen.
HomeViewController
NavigationBar show a half
NewsViewController
This is my code.
//In TabBarWithHomeDelegate.m
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
homeViewController = [[HomeViewController alloc]init];
UINavigationController *nav = [[UINavigationController alloc]init];
nav.navigationItem.title = @"Tab 1 Data";
[nav pushViewController:homeViewController animated:NO];
[self.tabBarController setSelectedViewController:nav];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
//In NewsViewController.m for touching on home button
-(IBAction) homeButtonClick:(id)sender
{
TabBarWithHomeAppDelegate * appDelegate
= [[UIApplication sharedApplication] delegate];
UITabBarController * tabBarController = appDelegate.tabBarController;
[tabBarController setSelectedViewController:nil];
[tabBarController setSelectedViewController:appDelegate.homeViewController];
}
In addition, I have attached source code. I'm will be grad if you see that and help me to solve this. In fact, I try to do it myself almost 6 hours.
link to download source code.
A: Your HomeViewController is not assigned as a tab in your UITabBarController, so you should not call:
[tabBarController setSelectedViewController:appDelegate.homeViewController];
You should either make it a real tab or do something different. I would recommend calling
[tabBarController presentModalViewController:homeViewController animated:YES];
You will not be able to see the tab bar in this scenario so you will need a different way to dismiss the homeViewController. However, this is more correct as it doesn't really make sense for the user to see a tab bar controller with no tabs currently selected.
A: I just comment you code in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions and all works perfect:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cant go back until the whole page is loaded i have an auto generate php gallery that preload all the images while the thumbnails are loading.. it load one thumb and after preload the actual image with it.. the problem is that i cant go back until i click the stop loading button..
<script type="text/javascript">
if (document.images) {
img1 = new Image();
img1.src ="../album/1000";
}
</script>
this is the preloading script and this is the back button script:
<div id="topbar" style="display: block;">
<div id="leftnav">
<a href="../mindex.php">Go back</a></div></div>
the thing is i found how to stop the loading on clicking the go back button but it wont load my page or go to the href..
thanks ahead
A: Try Putting the part that loads the images in a function which is called just after the page is loaded. Something like this:
<script>
function load(){
// some loading script
}
</script>
<body onload="load();">
This means that your page will load all the html, but everything on the screen, and just then call the 'load' function. This could make the page look a little wired until everything is loaded. But the browser should respond.
A: Wow i cant believe it was that simple:\ i tried so many things!!!
my stupid solution is to add
<a href="your/link/" target="_self" onclick="window.stop();"></a>
to the link.. i forgot that i have this script who prevent my pages to open new tabs because its a web app..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: cleditor problem with jquery ui effect()? I'm using cleditor on one of my sites and I have run into a problem. When I use effect to animate some divs cleditor's wysiwyg editor stops working. The editor itself shows but I cant type anything into it. I can view/edit the source on the editor just fine.
Code I use to toggle between divs:
function emailwizardplace(pold, pnew) {
$("#wizard-" + pold).hide();
$("#wizard-" + pnew).effect('slide');
//$("#wizard-" + pnew).show(); <= This works without problems
}
Code for calling cleditor:
$("#tmessage").cleditor({
width: 680,
height: 400
});
As always any help is appreciated.
A: This seems to be a problem with the interaction between CLEditor and jQuery.UI. Have you tried this?
$("#tmessage").cleditor()[0].disable(false).refresh();
There's quite a bit of discussion in google groups on this problem. Here's one link that outlines the problem and what others have done. https://groups.google.com/forum/?fromgroups#!topic/cleditor/6W36CyPsaVU
Hope this helps.
A: function emailwizardplace(pold, pnew) {
$("#wizard-" + pold).hide();
$("#wizard-" + pnew).effect('slide');
$("#wizard-" + pnew).show('slide',function(){
$("#tmessage").cleditor({
width: 680,
height: 400
});
});
};
You have to place the call for the cleditor inside the .show()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Designing Crystal Reports issue
I need to design a crystal report in the above format as there are multiple "sqauad check" numbers and for each of those number there are multiple document details to be shown.how can i do
this with multiple detail sections? or do i have to use sub
reports.please give me an idea
A: You can insert groupings into crystal reports - I don't know your data-source so it's hard to tell but the picture looks like you have just to insert a group for the squad-check-no and use one detail to show the DocumentNumber, Document Titel, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.