text stringlengths 8 267k | meta dict |
|---|---|
Q: Rails 3.1, passing parameters for colection_select from controller I have this collection_select usage in my view:
<%= collection_select(:production_year, :id, @car_models, :id, :name, { :prompt => "Year" }, { :disabled => "disabled" } ) %>
But it seems, that i'll add much logic for this select box. So i want pass parameters for this collection_select from my controller. How can i do this?
Was trying to pass array with parameters, but got many errors. Pls show correct way for this.
A: In your controller: @collection_select_params = [ ... ]
And in your view: <%= collection_select(*@collection_select_params) %>
The * prefix will indicate to ruby that this array is to be passed as an args list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using sample() with sample space size = 1 I have a list of dates that I wish to sample from. Sometimes the sample space will just be a single date e.g. sample("10/11/11",1). The dates are stored as chron objects, so when I have just a single date in my sample space (and only then) sample treats this as a vector (1:date). The documentation for sample points this out:
If ‘x’ has length 1, is numeric (in the sense of ‘is.numeric’) and
‘x >= 1’, sampling _via_ ‘sample’ takes place from ‘1:x’. _Note_
that this convenience feature may lead to undesired behaviour when
‘x’ is of varying length in calls such as ‘sample(x)’. See the
examples.
But I didn't see a way to disable this feature. Is there a workaround or a way to stop it from treating objects of length one as numeric?
A: I would wrap it in an if statement, or wrap it inside another function. For example:
mysample <-
function(x, size, replace=FALSE, prob=NULL)
{
if(length(x)==1)
return(rep(x, size))
sample(x, size, replace, prob)
}
A: The sample documentation recommends this:
resample <- function(x, ...) x[sample.int(length(x), ...)]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Question about Timeline, does the user have to be connected? The reason I'm asking is because, right now we already have it setup to prompt users to share things if they're connected. But the biggest problem we have is that without the user being connected, it tries to make a popup window — which is blocked in most browsers. (vs. the iframe inline)
So, I'm trying to see what the benefit or difference in us implementing the new changes if we're already doing "timeline-like" sharing. I don't get it? Do we have to recode everything?
Last, off topic, but I'm confused about the way the referral API works actually, because the same code doesn't seem to invoke the API at all. Just display the user's name
A: You need to get the users "publish_actions" permission to add things to timeline. So in that sense, yes, they do need to be connected. But the advantage of that is that once you get "publish_actions" permission, the user never needs to be prompted... you just automatically share the actions they've taken by making api calls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Date object problem I'm doing a java program that will take an action based on the date and time.
the problem is that when I used the java.util.Date object i found that it is affected by the windows wall clock, i don't know what to do, I'm needing to the date to be never affected by anything, or if any one know how to take this action in another way
thank you very much
A: If you want a specific Date and Time you need to create an instance of Date with the date and time instance information you want instead of calling new Date() which will give you the current instance in time. Use the GregorianCalendar or some other Calendar sub-class.
If you want only the Date to be relevant you need to ZERO out the time ( hours, minutes, seconds, milliseconds ) off your Date object.
public static Date setTime(final Date date, final int hourOfDay, final int minute, final int second, final int ms)
{
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
gc.set(Calendar.HOUR_OF_DAY, hourOfDay);
gc.set(Calendar.MINUTE, minute);
gc.set(Calendar.SECOND, second);
gc.set(Calendar.MILLISECOND, ms);
return gc.getTime();
}
then on your Date instance of date do .setTime(date, 0, 0, 0, 0);
A: There's some ways ... You could set up a service somewhere on the web from which you grab a time. This way you make sure that all PCs you run this stuff on use the same time base.
Another way would be to use an NTP server... Here is an official release by the people who designed the NTP standard how you could use a Java Client to query an NTP server
A: When you say "never affected by anything", what exactly do you have in mind?
Since a user can (pretty much always) control their computer's internal clock, you will need to examine the date and time from an external source. Note that internal clocks often change with daylight saving hours too.
If you could use network time, or time from an internet server. NIST has such a service http://www.nist.gov/pml/div688/grp40/its.cfm. You should check out the network time protocol too.
But even this could theoretically be rerouted / changed by a devious person. So if you are after copy protection, or something security-related, you might need to rethink.
A: The java.util.Date class is getting the current time depending on the system clock. The system clock can be modified in multiple ways (the wall clock is one of those).
If you want the time without using the system clock, I recommend to try and fetch the time from Internet. Protocols such as NTP can do that. Some implementations exist in Java, see http://support.ntp.org/bin/view/Support/JavaSntpClient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Is this the proper way to open a file for input? Is this the proper way to open a file for input?
void BinaryTree::read(char * path, int line_number)
{
ifstream * file(path); //error: cannot convert ‘char*’ to ‘std::ifstream*’ in initialization
file->seekg(0, std::ios::beg);
int length = file.tellg();
char * buffer = new char[length];
file->getline(buffer, line_number);
printf("%d", length);
file->close();
}
I'm guessing not, because the compiler won't accept a char array, or a std::string for the ifstream constructor, yet when I read documentation, I see strings and/or char arrays being passed to ifstream constructors.
Is something wrong with my compiler or am I just using the wrong type in my parameter?
A: Dont use pointer. It is not needed here.
Try this:
ifstream file(path);
and then use it as:
//...
file.getline(buffer, line_number);//file->getline(buffer, line_number);
//...
A: ifstream * file(path); //error: cannot convert ‘char*’ to ‘std::ifstream*’ in initialization
The problem is that the construction of the object is not appropriate. You're probably trying to do the following (or something similar), indeed passing a char array to the constructor of the ifstream object:
ifstream file(path);
However, the introduction of an asterisk here changes the whole meaning. You're creating a pointer to an object ifstream, but not the object ifstream itself. And in order to construct a pointer, you would need another pointer to an ifstream object (i.e. a pointer of the same type).
ifstream file(path);
ifstream * ptr( &path );
This is not what you intended to do, anyway, you probably wanted to create an ifstream object referenced by a pointer:
ifstream * file = new ifstream( path );
//... more things...
file->close();
But remember that the object must free'd when it is not needed anymore. Objects referenced by pointers are not automatically free'd as it happens with normal (objects in the stack) objects.
ifstream * file = new ifstream( path );
//... more things...
file->close();
delete file;
Hope this helps.
A: No pointer needed, as @Nawaz said:
ifstream *file(path);
Potential memory leak:
char *buffer = new char[length];
You should delete[] it afterwards:
delete[] buffer;
...But, it's a lot easier to use std::string:
std::string buffer;
Final code:
std::string BinaryTree::read(std::string path, int line_number)
{
std::string buf;
ifstream file(path.c_str());
if(file.is_open())
{
// file.seekg(0, std::ios::beg); // @Tux-D says it's unnecessary.
file.getline(buf, line_number);
file.close();
}
return buf;
}
A: Couple of things I would change:
void BinaryTree::read(char * path, int line_number)
{
// Use an object not a pointer.
ifstream* file(path);
// When you open it by default it is at the beginning.
// So we can remove it.
file->seekg(0, std::ios::beg);
// Doing manually memory line management.
// Is going to make things harder. Use the std::string
int length = file.tellg();
char * buffer = new char[length];
file.getline(buffer, line_number);
// Printing the line use the C++ streams.
printf("%d", length);
// DO NOT manually close() the file.
// When the object goes out of scope it will be closed automatically
// http://codereview.stackexchange.com/q/540/507
file->close();
} // file closed here automatically by the iostream::close()
Simplified here:
void BinaryTree::read(char * path, int line_number)
{
ifstream file(path);
std::string line;
std::getline(file, line);
std::cout << line.size() << "\n";
}
A: You've got more problems than the ones mentioned above though:
*
*you're using file variously as a pointer and an object (file->seekg(...) and file.tellg())
*you're taking the position with the tellg after having moved to the start of the file with the seekg and then using that position to give you the size of the buffer. This will give you an empty buffer (at best a pointer to zero bytes, I think).
*you're then calling getline with the line_number parameter passed as an argument. This will cause getline to read at most line_number bytes but you've only allocated length bytes (which is zero as we've seen above). I guess that you want to read the line_number'th line but that takes a bit more work - you've gotta count up line_number newlines until you reach the right line.
*more generally do you want to open and close the file each time you get the next line - you might want to rethink your interface as a whole.
apologies if I've missed the point here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access a JMX Mbean from a tomcat website? I have a web service that exposes an mbean. I am able to view that mbean using jconsole. Now I need that function exposed on a new tomcat website.
A: Take a look at http://www.jolokia.org/ and http://directwebremoting.org/dwr/index.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery UI: Slider inside of a Tab? I want my tab content area to have a vertical scrollbar to the right using the jQuery UI Slider API. The tab content area will have a fixed height, and the vertical overflow needs to cause a jQuery UI Slider to appear to scroll through the content.
The specific issue I'm having trouble with is how to structure the HTML and what to style each element with in CSS.
A: Why do you want to use slider as a scroll bar?
Normally, you should simply pick a scroll bar plugin and go with it, instead of trying to make a control to do what it is not designed for.
This page lists a few jQuery plugins for scoll bars. Here are a few of them:
*
*jScrollPene (demo)
*jQuery Custom Content Scroller (demo)
*Tiny Scrollbar
But, if you insist using jQuery UI Slider, someone has already made this work, with a demo page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MSDN HMAC-SHA1 example not working Creating an HMAC steps by using CryptoAPI found here: http://msdn.microsoft.com/en-us/library/Aa379863
*
*To compute an HMAC
*
*Get a pointer to the Microsoft Cryptographic Service Provider
(CSP) by calling CryptAcquireContext.
*Create a handle to an HMAChash object by calling
CryptCreateHash. Pass CALG_HMAC in the Algid parameter. Pass the
handle of a symmetric key in the hKey parameter. This symmetric key
is the key used to compute the HMAC.
*Specify the type of hash to be used by calling
CryptSetHashParam with the dwParam parameter set to the value
HP_HMAC_INFO. The pbData parameter must point to an initialized
HMAC_INFO structure.
*Call CryptHashData to begin computing the HMAC of the data. The
first call to CryptHashData causes the key value to be combined using
the XOR operator with the inner string and the data. The result of
the XOR operation is hashed, and then the target data for the HMAC
(pointed to by the pbData parameter passed in the call to
CryptHashData) is hashed. If necessary, subsequent calls to
CryptHashData may then be made to finish the hashing of the target
data.
*Call CryptGetHashParam with the dwParam parameter set to
HP_HASHVAL. This call causes the inner hash to be finished and the
outer string to be combined using XOR with the key. The result of the
XOR operation is hashed, and then the result of the inner hash
(completed in the previous step) is hashed. The outer hash is then
finished and returned in the pbData parameter and the length in the
dwDataLen parameter.
I can not, for the life of me get this working. I have all the steps in order, and still can not even run my program. Errors while running:
Error in CryptImportKey 0x8009007
Error in CryptCreatHash 0x8009003
Error in CryptSetHashParam 0x00000057
Error in CryptHashData 0x00000057
Error in CryptGetHashParam 0x00000057
Can anyone help?
#include <iostream>
#include <windows.h>
#include <wincrypt.h>
using namespace std;
#define CALG_HMAC CALG_SHA1
int main()
{
//--------------------------------------------------------------------
// Declare variables.
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
HCRYPTKEY hKey = NULL;
BYTE DesKeyBlob[] = { 0x70,0x61,0x73,0x73,0x77,0x6F,0x72,0x64 };
HCRYPTHASH hHmacHash = NULL;
PBYTE pbHash = NULL;
DWORD dwDataLen = 20;
BYTE Data[] = {0x6D,0x65,0x73,0x73,0x61,0x67,0x65};
HMAC_INFO HmacInfo;
//--------------------------------------------------------------------
// Zero the HMAC_INFO structure
ZeroMemory(&HmacInfo, sizeof(HmacInfo));
HmacInfo.HashAlgid = CALG_HMAC;
HmacInfo.pbInnerString = (BYTE*)0x36;
HmacInfo.cbInnerString = 0;
HmacInfo.pbOuterString = (BYTE*)0x5C;
HmacInfo.cbOuterString = 0;
// Step 1
if (!CryptAcquireContext(
&hProv, // handle of the CSP
NULL, // key container name
NULL, // CSP name
PROV_RSA_FULL, // provider type
CRYPT_VERIFYCONTEXT)) // no key access is requested
{
printf(" Error in AcquireContext 0x%08x \n",
GetLastError());
}
//--------------------------------------------------------------------
//Step 2
//in step two, we need the hash key used to be imported?
//imports the key used... as hKey1
if(!CryptImportKey(
hProv,
DesKeyBlob,
sizeof(DesKeyBlob),
0,
CRYPT_EXPORTABLE,
&hKey ))
{
printf("Error in !CryptImportKey 0x%08x \n",
GetLastError());
}
if (!CryptCreateHash(
hProv, // handle of the CSP
CALG_HMAC, // hash algorithm to use
hKey, // hash key this shoudl point to a key used to compute the HMAC?
0, // reserved
&hHmacHash // address of hash object handle
)){
printf("Error in CryptCreateHash 0x%08x \n",
GetLastError());
}
// Step 3
if (!CryptSetHashParam(
hHmacHash,//hProv,//hHash,//hHmacHash, // handle of the HMAC hash object
HP_HMAC_INFO, // setting an HMAC_INFO object
(BYTE*)&HmacInfo, // the HMAC_INFO object
0)) // reserved
{
printf("Error in CryptSetHashParam 0x%08x \n",
GetLastError());
}
//Step 4
if (!CryptHashData(
hHmacHash, // handle of the HMAC hash object
Data, // message to hash
sizeof(Data), // number of bytes of data to add
0)) // flags
{
printf("Error in CryptHashData 0x%08x \n",
GetLastError());
}
//Step 5
if (!CryptGetHashParam(
hHmacHash, // handle of the HMAC hash object
HP_HASHVAL, // query on the hash value
pbHash, // pointer to the HMAC hash value
&dwDataLen, // length, in bytes, of the hash
0))
{
printf("Error in CryptGetHashParam 0x%08x \n", GetLastError());
}
// Print the hash to the console.
printf("The hash is: ");
for(DWORD i = 0 ; i < dwDataLen ; i++)
{
printf("%2.2x ",pbHash[i]);
}
printf("\n");
int a;
std::cin >> a;
return 0;
}
A: You might (?1) need to specify what hash algorithm you want to use.
#define CALG_HMAC CALG_SHA1 // or CALG_MD5 etc
Edit
*
*Why do you initialize dwDataLen = 20 (instead of 0)?
*Why did you change the hash algorithm from SHA1
*Why do you not exit on ErrorExit anymore (that alone will prevent the crash instead of proper error message)
*You use CryptImportKey instead of CryptDeriveKey -- no such thing even exists in the sample on MSDN. It can't be a coincidence that CryptImportKey is the call failing with 0x80090005 (NTE_BAD_DATA). The key is not supported by your CSP!
*For that to work, you need key access so you'd at least need to change CRYPT_VERIFY_CONTEXT into something else (don't know what); I tried using
.
if (!CryptAcquireContext(
&hProv,
NULL,
MS_STRONG_PROV, // allow 2048 bit keys, in case you need it
PROV_RSA_FULL,
CRYPT_MACHINE_KEYSET)) // just a guess
Now my program results in 0x80090016: Keyset does not exist. This might simply be because I don't have that keyset, or because I'm running on Linux under Wine.
Hope this helps.
1 Compiled on Linux using:
i586-mingw32msvc-g++ -m32 -O2 -g test.cpp -o test.exe
It did crash when run (without parameters) but that might be wine incompatibility (or the fact that I haven't read the source to see what it does :))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What is the difference between branch-0.2 and origin/branch-0.2 in Git? I cloned a Git repository and when I do a 'git checkout' I see branch-0.2 and origin/branch-0.2 in the list of the branches. What is the difference between the two branches? I read a couple of articles, but I'm not clear on what the difference is.
A: origin/branch-0.2 is the local reference to branch-0.2 in the remote named origin. It is also called a remote-tracking branch. You can synchronise it (for manual merging later using git merge) with the remote by running: git fetch origin branch-0.2. In order to fetch and merge at the same time, you can use: git pull origin branch-0.2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to wait for threads with low latency in go? I've been trying to create a simple event loop wrapper in Go. But I got stumped, how was I supposed to keep track of operations in the current thread?
I wanted CurrentTick to run a function, and even if the calling function quits, not start the next tick until all functions run by CurrentTick quit. I thought I might use a mutex to monitor the number of threads, but I realized if I kept checking that over and over it would throttle the CPU. If I used time.Sleep it would be latent. How would you solve the problem?
package eventloop
import (
"reflect"
)
type eventLoop *struct{
functions []reflect.Value
addFunc chan<-/*3*/ reflect.Value
mutex chan/*1*/ bool
threads int
}
func NewEventLoop() eventLoop {
var funcs chan reflect.Value
loop := eventLoop{
[]Reflect.Value{},
funcs = make(chan reflect.Value, 3),
make(chan bool, 1),
0,
}
go func(){
for {
this.mutex <- 1
if threads == 0 {
}
}
}
}
func (this eventLoop) NextTick(f func()) {
this.addFunc <- reflect.ValueOf(f)
}
func (this eventLoop) CurrentTick(f func()) {
this.mutex <- 1
threads += 1
<-this.mutex
go func() {
f()
this.mutex <- 1
threads -= 1
<-this.mutex
}()
}
A: If I understand your intent, I think you're overcomplicating things. I'd do it like this:
package eventloop
type EventLoop struct {
nextFunc chan func()
curFunc chan func()
}
func NewEventLoop() *EventLoop {
el := &EventLoop{
// Adjust the capacities to taste
make(chan func(), 3),
make(chan func(), 3),
}
go eventLoop(el)
return el
}
func (el *EventLoop) NextTick(f func()) {
el.nextFunc <- f
}
func (el *EventLoop) CurrentTick(f func()) {
el.curFunc <- f
}
func (el *EventLoop) Quit() {
close(el.nextFunc)
}
func eventLoop(el *EventLoop) {
for {
f, ok := <-el.nextFunc
if !ok {
return
}
f()
drain: for {
select {
case f := <-el.curFunc:
f()
default:
break drain
}
}
}
}
Depending on your use, you may need to add some synchronization to make sure all tasks in the loop finish before your program exits.
A: I figured it out myself, after a lot of problems and random issues including using 15 as length instead of capacity... Seems you just have a thread send a message after you decrement the counter. (the loop.tick part could be inlined, but I'm not worried about that)
package eventloop
type eventLoop struct{
functions []func()
addFunc chan/*3*/ func()
mutex chan/*1*/ bool
threads int
waitChannel chan bool
pauseState chan bool
}
func (this *eventLoop) NextTick (f func()) {
this.addFunc <- f
}
func (this *eventLoop) tick () {
this.mutex <- true
for this.threads != 0 {
<-this.mutex
<-this.waitChannel
this.mutex <- true
}
<-this.mutex
L1: for {
select {
case f := <-this.addFunc:
this.functions = append(this.functions,f)
default: break L1
}
}
if len(this.functions) != 0 {
this.functions[0]()
if len(this.functions) >= 2 {
this.functions = this.functions[1:]
} else {
this.functions = []func(){}
}
} else {
(<-this.addFunc)()
}
}
func (this *eventLoop) CurrentTick (f func()) {
this.mutex <- true
this.threads += 1
<-this.mutex
go func() {
f()
this.mutex <- true
this.threads -= 1
<-this.mutex
this.waitChannel <- true
}()
}
func NewEventLoop () *eventLoop {
funcs := make(chan func(),3)
loop := &eventLoop{
make([]func(),0,15), /*functions*/
funcs, /*addFunc*/
make(chan bool, 1), /*mutex for threads*/
0, /*Number of threads*/
make(chan bool,0), /*The "wait" channel*/
make(chan bool,1),
}
go func(){
for { loop.tick() }
}()
return loop
}
Note: this still has lots of other problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add footer view dynamically I have created a ListView and added header with addHeaderView, then I called setListAdapter in my ListActivity. Any idea how can I dynamically addFooterView after I called setListAdapter?
ANSWER:
I added both header view and footer view (actually buttons) into my list view,
but both of them I wrapped into a FrameLayout using wrap_content height, then when I do not need to be the header button to be shown I just setVisibility(View.GONE) and FrameLayout wraps to 0 height and vissualy it is not visible (same effect as if I would call removeHeaderView), and if I need to show it again I setVisibilty(View.VISIBLE) and it is shown (same effect as addHeaderView - which is of course not possible after calling setting list adapter)
Discussed here:
Hide footer view in ListView?
A: View header = getLayoutInflater().inflate(R.layout.header, null);
View footer = getLayoutInflater().inflate(R.layout.footer, null);
ListView listView = getListView();
listView.addHeaderView(header);
listView.addFooterView(footer);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice,
android.R.id.text1, names));
A: You Have to do like this
View header = (View)getLayoutInflater().inflate(R.layout.header,null);
SimpleAdapter myAdapter=new SimpleAdapter(this,myList,R.layout.transactionvalues,
new String[] {"transaction_date_time","user_name","site_name","machine_name"},new int[] {R.id.Date_Time,R.id.User,R.id.Site,R.id.Machine});
if(header == null){
lst.removeHeaderView(header);
}else
{
lst.addHeaderView(header,null,false);
}
lst.setAdapter(myAdapter);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to set RGBA Color of a Pixel of an UIImage I am looking for a possibility to set (change) the RGBA color of a Pixel of an UIImage for my Iphone Application. (I actually want to implement some floodfill stuff)
So I need something like this:
-(void) setPixelColorOfImage: (UIImage*) img atXCord: (int) x atYCord: (int) y
withRedColor: (CGFloat) red blueColor: (CGFloat) blue greenColor: (CGFloat) green
alpha: (CGFloat) alpha {
// need some code her
}
Because this method will be called quite often, it shouldn't be too slow.
Please help.
A: UIImage is not (externally) mutable, so you must copy, then edit, then convert to UIImage.
Copy
*
*create a CGBitmapContext
*draw the source image onto it
Edit
*
*get a hold of the context's pixel buffer
*mutate that pixel buffer
Convert to UIImage
*
*copy a CGImage representation of the context
*create a new UIImage from the CGImage
fwiw, the form can also be used on osx (using NSImage).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to add function to an object in javascript that can access its variables I am trying to do some javascript test driven development, and would like to replace a dao with a mock one.
Lets say I have an object myObject that has a private var dao that I would like to create a setter for:
var dao = new RealDao();
function funcUsesDao() {
dao.doStuff();
}
Then in another file I have a handle to an instance of this object and want to add a setter so I can do the following:
var mockDao = {function doStuff() { /*mock code */}};
myObject.setDao(mockDao);
myObject.funcUsesDao(); should use mock dao
Environment specifics are this is node.js and the object I have a handle to is obtained by doing var myObject = require('../myObject');
A: You would use a constructor for the class, setting the dao to RealDao and then in the setDao you would set that dao to the new dao. Alternately in the constructor you would put a reference to dao, and on null, assign it to a new RealDao(). (at least, that's been my understanding of how people generally assign new interfaces for testing .. via the constructor)
//something like this
function Dao(interface){
this.dao = interface || new RealDao();
}
Otherwise, what you listed above is accurate. you just have to provide the setDao method as you indicated in your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: changing one char in a c string I am trying to understand why the following code is illegal:
int main ()
{
char *c = "hello";
c[3] = 'g'; // segmentation fault here
return 0;
}
What is the compiler doing when it encounters char *c = "hello";?
The way I understand it, its an automatic array of char, and c is a pointer to the first char. If so, c[3] is like *(c + 3) and I should be able to make the assignment.
Just trying to understand the way the compiler works.
A: there's a difference between these:
char c[] = "hello";
and
char *c = "hello";
In the first case the compiler allocates space on the stack for 6 bytes (i.e. 5 bytes for "hello" and one for the null-terminator.
In the second case the compiler generates a static const string called "hello" in a global area (aka a string literal, and allocates a pointer on the stack that is initialized to point to that const string.
You cannot modify a const string, and that's why you're getting a segfault.
A: String constants are immutable. You cannot change them, even if you assign them to a char * (so assign them to a const char * so you don't forget).
To go into some more detail, your code is roughly equivalent to:
int main() {
static const char ___internal_string[] = "hello";
char *c = (char *)___internal_string;
c[3] = 'g';
return 0;
}
This ___internal_string is often allocated to a read-only data segment - any attempt to change the data there results in a crash (strictly speaking, other results can happen as well - this is an example of 'undefined behavior'). Due to historical reasons, however, the compiler lets you assign to a char *, giving you the false impression that you can modify it.
Note that if you did this, it would work:
char c[] = "hello";
c[3] = 'g'; // ok
This is because we're initializing a non-const character array. Although the syntax looks similar, it is treated differently by the compiler.
A: You can't change the contents of a string literal. You need to make a copy.
#include <string.h>
int main ()
{
char *c = strdup("hello"); // Make a copy of "hello"
c[3] = 'g';
free(c);
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How can I checkout a project from CVS? I have never used cvs in my life (only git, svn) - can anyone tell me how in the world I can get the source/jar of this bundle to my local Ubuntu box?
http://dev.eclipse.org/viewcvs/viewvc.cgi/org.eclipse.equinox/compendium/bundles/org.eclipse.equinox.http/?root=RT_Project
I've installed "cvs" into ubuntu, but "cvs co" command complains about some "CVSROOT" not being set.
EDIT: Thanks to duffymo I've set up my CVSROOT variable, now when I try to "cvs co" I get the following:
penguin:~/Downloads$ cvs co dev.eclipse.org:/cvsroot/rt
cvs checkout: cannot find module `dev.eclipse.org:/cvsroot/rt' - ignored
A: Have a look at this: maybe it'll help.
http://ubuntuforums.org/archive/index.php/t-1216619.html
A: Turns out everything is much easier than I thought.
Simply bring up the "CVS Repositories" view in Eclipse, right click on it (yes - on the empty window!) and click "Paste connection" link, which looks something like this:
http://wiki.eclipse.org/CVS_Howto#Anonymous_CVS
Thanks to Eclipse doc:
http://wiki.eclipse.org/CVS_Howto#Anonymous_CVS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Removing a Warden strategy - how to ensure original devise_authenticable strategy is gone I created my own Warden strategy for using with Devise. It's very similar to Devise::Strategies::DatabaseAuthenticatable and actually it inherits from it and re-implements authenticate!
My issue though is that I want to make sure the original devise_authenticable Warden strategy is gone. That is not in the list of strategies Warden will try because it's actually a security problem. Is that possible?
A: According to my manual inspection and tests, this in the devise.rb initializer achieves the goal:
config.warden do |manager|
strategies = manager.default_strategies(:scope => :user)
strategies[strategies.index(:database_authenticatable)] = :alternative_strategy
end
And the strategy is implemented this way (not part of this question, but I found conflicting information out there and this one is the one that worked for me using Rails 3.1, devise 1.4.7 and warden 1.0.5):
class AlternativeStrategy < Devise::Strategies::Authenticatable
def authenticate!
end
end
Warden::Strategies.add(:alternative_strategy, AlternativeStrategy)
A: I just implemented this as well. Devise will try each strategy in its list until one succeeds.
For me, rather than replace the :database_authenticatable strategy in place, I just added my strategy to the beginning of the list and popped :database_authenticatable off the end of the existing list.
config.warden do |manager|
# Exiles::Devise::Strategies::BySite implemented in lib/. It matches the stub in Pablo's answer
manager.strategies.add( :by_site_auth, Exiles::Devise::Strategies::BySite )
# add my strategy to the beginning of the list.
manager.default_strategies(:scope => :user).unshift :by_site_auth
# remove the default database_authenticatable strategy from the list
manager.default_strategies(:scope => :user).pop
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How does StringBuilder's capacity change? When I have an empty StringBuilder with a capacity of 5 and I write "hello, world!" to it, does the C# standard specify the new capacity of the StringBuilder? I have a vague memory that it's twice the new string's length (to avoid changing the capacity with every new appended string).
A: The C# standard will not specify the behavior of a BCL library class as it has nothing to do with the language specification.
As far as I know the actual behavior is not defined in any specification and is implementation specific.
AFAIK, The MS implementation will double the capacity once the current capacity has been reached.
See this and this previous SO questions.
Update:
This has been changed in .NET 4.0. as described by Hans in his answer. Now ropes are used, adding additional 8000 characters at a time.
MSDN, however is very careful to point out that the actual behavior is implementation specific:
The StringBuilder dynamically allocates more space when required and increases Capacity accordingly. For performance reasons, a StringBuilder might allocate more memory than needed. The amount of memory allocated is implementation-specific.
A: Depends what version of .NET you're talking about. Prior to .NET 4, StringBuilder used the standard .NET strategy, doubling the capacity of the internal buffer every time it needs to be enlarged.
StringBuilder was completely rewritten for .NET 4, now using ropes. Extending the allocation is now done by adding another piece of rope of up to 8000 chars. Not quite as efficient as the earlier strategy but avoids trouble with big buffers clogging up the Large Object Heap. Source code is available from the Reference Source if you want to take a closer look.
A: New StringBuilder (.NET 4.5 or higher) allocates an internal buffer m_ChunkChars requested by the capacity parameter:
public StringBuilder(int capacity)
{
...
m_ChunkChars = new char[capacity];
...
}
So, if capacity is smaller than 40K chars it goes on the Small Object Heap. However (contrary to popular belief), StringBuilder will still allocate on the Large Object Heap if, later, we call sb.Append(...some string larger than 40K chars...); A possible fix can be found here:
https://github.com/amikunov/Large-Object-Heap-Fix-For-.NET-String-Builder
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Doctrine2: Mapping a parent class field from a child, how? I'm wondering if this can be done using Doctrine annotations:
Say you have a parent class (a mapped superclass):
abstract class AbstractParent {
protected $foo;
}
which as two child classes:
class ConcreteChild1 extends AbstractParent {
/**
* @OneToOne(targetEntity="SomeEntity")
*/
// How can I map this to foo above?
}
class ConcreteChild2 extends AbstractParent {
/**
* @OneToOne(targetEntity="SomeOtherEntity")
*/
// How can I map this to foo above?
}
SomeEntity and SomeOtherEntity both share the same parent interface (SomeEntityInterface) but I don't want to just map the $foo field on the mapped superclass AbstractParent to this parent interface (SomeEntityInterface) as doctrine incurs a performance overhead (it loses lazy loading for mapping a class high in a hierarchy) (i.e. I don't want to use Single Table or Class Table Inheritance).
With YML the solution is simple as you can still map foo even though its on a parent class:
ConcreteChild1:
type: entity
oneToOne:
foo:
targetEntity: SomeEntity
and
ConcreteChild2:
type: entity
oneToOne:
foo:
targetEntity: SomeOtherEntity
So must I use YML or is there something I'm missing that would allow me to map $foo through an annotation?
Thanks greatly in advance, I know this is a bit of a hard one to follow!
A: Well, it depends. Do you do what you're doing in YML with annotations, you'd just define $foo in each concrete class and annotate it there, just like you do in your YML.
If $foo always pointed to the same type of entity, you could use @MappedSuperclass on your your abstract base class, and then you define the relationship there.
That can also work if SomeEntity and SomeOtherEntity were both subclasses of SomeCommonFooAncestor, in which case you could use @MappedSuperclass and say that AbstractParent has a @OneToOne(targetEntity="SomeCommonFooAncestor"). However, there are serious performance considerations with that approach for @OneToOne and @ManyToOne relationships (but you might be okay with that)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: solr: multivalued geospatial search - returning closest point Is there a way in Solr to have a document that:
*
*contains multiple lat/long pairs
*ask to return the closest point to a given (user-supplied) lat/long pair
*sort/filter based on that 'closest point'.
I was looking at:
*
*http://wiki.apache.org/solr/SpatialSearchDev
*https://issues.apache.org/jira/browse/SOLR-2155 (which talks about multivalued points)
But not sure if that would give me what I want.
Thanks for any pointers.
A: For future ref:
Use experimental Lucene Spatial Playground,
For detailed use-case and solution see: https://issues.apache.org/jira/browse/SOLR-2155?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=13114703#comment-13114703
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: var_dump($_POST); is empty but not var_dump($_POST); die; i have found some similar topics on this issue, but nothing for my case:
i send some post data via form, but the $_POST array is always empty (not null). but when i add a "die;" or "exit;" after var_dump($_POST); i can see all data sent.
maybe its relevant to know, that this is inside a (shopware) plugin which is called on "onPreDispatch".
thanks for any help
A: Your (shopware) plugin probably uses output buffering. Which means it will gather all the ecoes and prints until you call ob_flush() which prints all the buffer.
die() function, apart from everything else, also flushes the buffer when called.
So, if you do ob_flush() after your echo you should get the needed result.
A: the problem was the redirect, which resetted the post although it was after i read the parameters in the request.
i did not know, that shopware saves the desired data (paymentID) in the database. so i switched my plugin back to "onPostDispatch" (this way it will be called after all other actions, one of them saves the data in db). now i can just read the db and get the same data, which was initially in the post array.
i tried to be "the first" who reads the post, but could not work it out. now i am the last who reads it and it works fine.
thanks for all answers! the clue here was "redirect".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Images latitude and longitude like "Places" iphone app I'm trying to find out what are the coordinates of a photo chosen from the photo library via "UIImagePickerController".
I present the imagePickerController:
[self presentModalViewController:imagePickerController animated:YES];
and then:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
selectedImage.image = image;
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
}
I looked in the documentation about the "editingInfo" dictionary but I think is not the right way.
Help me please!
Thank all very much!
Oscar
A: take a look at this so-thread. This should be done with the asset-lib-framework
A: imagePickerController:didFinishPickingImage:editingInfo: is deprecated, you should use - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info instead, although I don't believe it'll help you getting the coordinates (info contains the UIImagePickerControllerMediaMetadata key, but documentation says it only works when source is set to UIImagePickerControllerSourceTypeCamera).
If you want to get the coordinates where a photo was shot you need to use ALAssetsLibrary, but will require to make your own picker (retrieve and arrange assets on your own, there should be some examples out there on how to do this). You can either use the valueForProperty: method from ALAsset class, or the metadata method from ALAssetRepresentation (which I believe returns a NSDictionary with the keys listed here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Value from TextBox\Combobox to Range UserForm1.TextBox1.Value = "G4"
Set CodeRange = Range(UserForm1.TextBox1.Value, Cells(Rows.Count, "G").End(xlUp))
Gives: methog range of object _global failed
Pls some help how to convert value from form to range.
A: Your code looks okay to me, although slightly unorthodox. Have you dimensioned CodeRange as a range?
If the activehseet is a chart sheet you will get that error.
You should also fully qualify your reference with the worksheet or activesheet.
With WorkSheeets("Sheet1")
Set CodeRange = .Range(UserForm1.TextBox1.Value, .Cells(Rows.Count, "G").End(xlUp))
End With
If your code is residing in the Userform module then you can use the Me keyword instead of Userfrom1.
I prefer to get ranges from the user using a input box like this:
Sub HTH()
Dim rRange As Range
On Error Resume Next
rRange = Application.InputBox(Prompt:= _
"Please select a range with your Mouse to be bolded.", _
Title:="SPECIFY RANGE", Type:=8)
On Error GoTo 0
If Not rRange Is Nothing Then
'// Your code here
End If
End Sub
A: Decimal sphvalue = Decimal.Parse(cmbo_sph.SelectedValue.ToString());
txt_sph.Text = sphvalue.ToString();
Decimal cylvalue = Decimal.Parse(cmbo_cyl.SelectedValue.ToString());
txt_cyl.Text = cylvalue.ToString();
try
{
SqlConnection searchconnnection = new SqlConnection("DataSource=ANI\\SQLEXPRESS;Initial Catalog=divinei;Integrated Security=True");
searchconnnection.Open();
SqlCommand searchcommand = new SqlCommand("SELECT CL_sphValue,CL_CylValue FROM ConvertCharts where SP_sphValue=" + Decimal.Parse(txt_sph.Text) + " and Sp_CylValue=" + Decimal.Parse(txt_cyl.Text) + " ", searchconnnection);
searchcommand.ExecuteNonQuery();
SqlDataReader convertreader = searchcommand.ExecuteReader();
while (convertreader.Read())
{
sphtxt.Text = convertreader[0].ToString();
cyltxt.Text = convertreader[1].ToString();
}
}
catch (Exception ex)
{
ex.ToString();
}`enter code here`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mod_rewrite, not rewriting when making a change My mod_rewriting seems to be being messed up by this one line at the end of my .htaccess file, and I can't for the life of me work out why.
RewriteEngine ON
Options FollowSymLinks
# User profile with username specified
RewriteRule ^([a-z0-9_.-]{1,30}+)$ profile.php?username=$1 [NC,L]
I want to match usernames, but allow them to have a-z 0-9 (no case) and also allow underscores, dots and hyphens.
It works fine without the '_.-'
I've tried escaping them too, but to no avail.
EDIT:
It seems that the problem with the rewrite, is that it is causing my 'styles.css' file to be rewritten, even though I've got it set to NOT rewrite, if the file or directory exists.
Here's the whole .htaccess file...
RewriteEngine ON
Options FollowSymLinks
# Only rewrite for folders and directories that don't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Remove www.
RewriteCond %{HTTP_HOST} ^www.nitpicker.me$ [NC]
RewriteRule ^(.*)$ http://nitpicker.me/$1 [R=301]
# Remove the trailing slash if there is one
RewriteRule ^(.+)/$ $1
# Main pages
RewriteRule ^(stream|settings|comment|profile)(.php)?$ $1.php [QSA,L]
# Find friends page
RewriteRule ^friends$ findfriends.php [L]
RewriteRule ^subject-([0-9]+)$ page.php?subject_id=$1 [QSA,L]
RewriteRule ^nit-([0-9]+)$ comment.php?nit_id=$1
RewriteRule ^search-([a-z0-9]+)$ search.php?term=$1 [NC,L]
# The initial sign up page with invite code
RewriteRule ^signup(-([a-z0-9]+))?$ signup.php?invite=$2 [NC,L]
# Trending page
RewriteRule ^(newest|trending|most_picked) trending.php?select=$1 [QSA,L]
# User profile with username specified
RewriteRule ^([a-z0-9\-_\.]{1,30}+)$ profile.php?username=$1 [NC,L]
How can I get it to stop it rewriting my '/styles.css' file?
A: use this:
# User profile with username specified
RewriteCond %{REQUEST_URI} !^.*\.css.*$ [NC]
RewriteRule ^([a-z0-9\-_\.]{1,30}+)$ profile.php?username=$1 [NC,L]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Javascript scoping query using jQuery $.ajax I am trying to write simple function that checks to see if a designer name exists in the database. I am using jQuery's ajax function to try to do this:
function checkDesignerName(name)
{
var designer_name = $('input[name="name"]').val();
var designer_exists = false;
var temp = $.ajax( { type: "GET",
url: "/api/check_brand_exists/",
data : {name : designer_name },
success: function(data) {
designer_exists = $.parseJSON(data);
return designer_exists;
}}).statusText;
return designer_exists;
}
I have read about javascript scoping, and but still can't seem to find my bug, which is checkDesignerName always returns false. Do I need to use a closure for this function to work correctly?
Thanks
A: It's the nature of AJAX which is asynchronous that you seem to have troubles with understanding.
At this stage:
return designer_exists;
your AJAX call hasn't yet finished. It's only inside the success callback, which happens much later, that you can use the results. You cannot have a function which returns some result and this result depends on an AJAX call. You can only exploit the results of an AJAX call iniside the success callback:
function checkDesignerName(name)
{
var designer_name = $('input[name="name"]').val();
$.ajax({
type: "GET",
url: "/api/check_brand_exists/",
data : { name : designer_name },
success: function(data) {
var designer_exists = $.parseJSON(data);
// Here and only here you know whether this designer exists
alert(designer_exists);
}
});
}
You could of course perform a synchronous call to the server which is something totally not recommended as it will freeze the client browser and piss the user off your site during the AJAX request by setting the async: false flag:
function checkDesignerName(name)
{
var designer_name = $('input[name="name"]').val();
var designer_exists = false;
$.ajax({
type: "GET",
url: "/api/check_brand_exists/",
async: false,
data : { name : designer_name },
success: function(data) {
designer_exists = $.parseJSON(data);
}
});
return designer_exists;
}
I am mentioning this just for completeness of the answer, not as something that you should ever be doing.
Now because it seems that you are doing some kind of validation logic here, here's what I would recommend you as an ultimate solution: the jquery.validate plugin. It has this great remote rule support that will do exactly what you need here.
A: $.ajax is a async call. It means the statement return designer_exists gets executed even before success function is executed. That is the reason it always returns false.
A: *
*your success function don't see designer_exists variable
*return action runs before success function will run
You may run sync request or redesign code to callbacks logic.
For sync request your code will be:
var designer_exists = false;
function checkDesignerName(name)
{
designer_exists = false;
var designer_name = $('input[name="name"]').val();
$.ajax( { async:false,
type: "GET",
url: "/api/check_brand_exists/",
data : {name : designer_name },
success: function(data) {
designer_exists = $.parseJSON(data);
}}).statusText;
return designer_exists;
}
A: As Dimitrov correctly noted it's asynchronous. If you want to encapsulate the ajax call within the function you could pass in the success callback.
function checkDesignerName(name, successCallback)
and then you assign it to the jQuery ajax success function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: On OS X, can I see how a website renders on an iPhone? I am running OS X Lion with XCode installed and want to know how a website renders on an iPhone. Are there any utilities that do that?
A: Launch the iOS Simulator from the iOS SDK.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extending class documentation and live templates I am playing with code documentation and live templates and I quite don't get it.
I've read Dr.Bob's article about generating documentation and wiki articles about live templates but I have one problem with class description.
By class description I understand the IDE behaviour when I point my mouse cursor over class declaration.
For example, I have such class with it's description:
type
{$REGION 'TMyClass'}
/// <summary>
/// Summary works
/// </summary>
/// <remarks>
/// Remarks works
/// </remarks>
/// <exception cref="www.some.link">This works</exception>
/// <list type="bullet">
/// <item>
/// <description>description does not work</description>
/// </item>
/// <item>
/// <description>description does not work</description>
/// </item>
/// </list>
/// <permission cref="www.some.link">This works</permission>
/// <example>
/// <code>
/// Code example does not work
/// </code>
/// </example>
{$ENDREGION}
TMyClass = class
private
a, b, c: Integer;
public
end;
And later in the code I have such declaration:
var
MyObject: TMyClass;
When I put mouse cursor over the class type I have such description:
As you see not every html tag was rendered by the IDE engine. I would really want to know how to render additional tags, especially tag with code example. Is it possible?
I am using Delphi 2009 Proffesional.
A: Only limited set of tags is supported. The best documentation about this stuff I'm aware of is the DevJET Software's Delphi Documentation Guidelines (at the end of the "Table of Contents" there is link to the PDF).
A: The tags Help Insight supports are described in the online help and the Delphi docwiki. They are a subset of the tags C#'s help tags support. No other tags than the ones listed on the Embarcadero site seem to be supported (I have tried them). The only other things that work (and are required) are "<", ">" and """.
Update
There seem to be some products that allow you to use the full syntax as e.g. described in the Delphi Documentation Guidelines linked to by @ain. But that requires you to buy a commercial product like DevJet's Documentation Insight, which should not be confused with the Help Insight the IDE supports since Delphi 2006.
As you found out, and I did too, only the subset described in the Delphi docwiki is supported by the bare IDE without commercial products. There is also the documentation that is supported by the Modelling interface, but that is different again. In the normal IDE, you can only use the tags you and I already found.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: JQuery blockUI plugin - can't remove iFrame I have upload image form implemented. When user click submit to upload image to server I display modal window with Jquery.BlockUI plugin. In that modal view I display iFrame with uploading information data. Problem is when I add iFrame it displays fine, however it stays on body after closing modal view. I don't know how to remove it from body?
$(function () {
$("#Form").ajaxForm({
iframe: true,
dataType: "html",
url: "/Images/Upload",
target: "body",
type: "POST",
success: function (result) {
//$.unblockUI();
$('body.divAI').unblock();
},
beforeSubmit: function () {
$('body').append('<div id="divAI" style="cursor: default;"><div style="background-color: #404040; height: 23px;"><div style="width: 250px; text-align: left; padding-top: 3px;"><span style="font-weight: bold; color: White; padding: 3px; height: 23px; font-size: 10pt; text-align: left; font-family: Verdana;">Add Item</span></div></div><iframe id="ifAI" scrolling="no" height="200" width="425" src="Images/InFrame" frameborder="0"></iframe></div>');
$.blockUI({ message: $("#divAI"), css: {
width: '425px',
height: '225px',
left: ($(window).width() - 425) / 2 + 'px',
top: '10%'
}
});
},
error: function (response) {
$.unblockUI();
}
});
});
A: Have you tried $("iframe").remove(); before closing the modal? You could also target the iframe by id if there are more iframe's on the page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android : GreenDroid-GoogleAPIs fails with StackOverflow Exception during Import I just tried to Import the GreenDroid-Librarys for my new Android Application.
Now, I encounter a confusing Error. I first Import the GreenDroid-Core Library and everything is fine.
But when I, after that, try to Import the GreenDroid-GoogleAPI Library into my workspace I get a java.lang.StackOverflowError.
The detailed Error is as followed:
Failed to call IProjectListener.projectOpened
java.lang.StackOverflowError
I´m not sure if this is a problem with my Eclipse or with the Library per se.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Android register touch events on visible portion of image? I've currently been thinking about how I could register only touch events on the visible (non-transparent) parts of a .PNG image.
-I've been testing around with AndEngine and it seems they have multiple options: I've tried any I could find to no avail.
-I could very possibly create my own method of checking a given touched area's transparency I suppose, but not sure how much work/overhead that might create with 15-20 objects on screen being able to be touched..
Any help is much appreciated!
A: One simple way to do it would be to grab the the pixel color at the touch location. Then you can check if the pixel is transparent:
int color = Bitmap.getPixel(x,y); // x and y are the location of the touch event in Bitmap space
int alpha = Color.getAlpha(color);
boolean isTransparent = (alpha==0);
Note: Depending on how you implement your touch listener will might need to convert the x,y location of the touch event to the x,y coordinates of the image view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Help with SimpleGeo Javascript SDK I'm new to Javascript and I'm trying to eventually make something that will get the users location in using the getLocation API with HTML5, and use simpleGeo to get the building of the coordinates.
So far I'm trying to get SimpleGeo working and I have this:
var client = new simplegeo.ContextClient('YUpXKUcaTr2ZE5T5vkhaDRAXWbDbaZts');
function displayData(err, data) {
if (err) {
console.error(err);
} else {
console.log(JSON.stringify(data));
}
}
client.getLocation({enableHighAccuracy: true}, function(err, position) {
if (err) {
// Could not retrieve location information. Check err for more information
} else {
// Latitude and longitude available in position.coords
var lat = position.coords.latitude;
var lon = position.coords.longitude;
$('#header').html('<p>your latitude is: ' + lat + '. And your longitude is: ' + lon + '.</p>');
}
});
client.getNearbyAddress(37.765850, -122.437094), function(err, position) {
if (err) {
$('#header').html('<p>Sorry we couldn't locate an address.</p>)
} else {
$('#header').html('<p>Your Street number is ' + street_number + '</p>');
}
});
However this says unexpected identifier in the JS console in Chrome. Any help would be appreciated. :)
A: I am actually the Developer Advocate @ SimpleGeo. Your function displayData doesn't look like it is doing anything. Also var street_number isn't defined. Are you looking to get the user's address?
Here is an example that returns the user's neighborhood:
<script type="text/javascript">
var client = new simplegeo.ContextClient('YOUR_JSONP_TOKEN');
$(document).ready(function() {
client.getLocation({enableHighAccuracy: true}, function(err, position) {
// get the user's context for the found location
client.getContext(position.coords.latitude, position.coords.longitude,
function(err, data) {
if (err)
(typeof console == "undefined") ? alert(err) : console.error(err);
else {
for (var i = 0, ii = data.features.length; i < ii ; i++) {
// switch on the category
switch(data.features[i]["classifiers"][0]["category"]) {
// Return the Neighborhood as an example
case "Neighborhood":
$("#neighborhood").val(data.features[i]["name"]);
break;
}
}
}
});
});
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing UIButton backgroundImage when selected on a UITabBar So I have a UIButton in the middle of my UITabBar in order to mimic, instagram's UITabBar
Here's the code (code can also be taken from github here).
@interface BaseViewController : UITabBarController
{
}
// Create a view controller and setup it's tab bar item with a title and image
-(UIViewController*) viewControllerWithTabTitle:(NSString*)title image:(UIImage*)image;
// Create a custom UIButton and add it to the center of our tab bar
-(void) addCenterButtonWithImage:(UIImage*)buttonImage highlightImage:(UIImage*)highlightImage;
@end
#import "BaseViewController.h"
@implementation BaseViewController
// Create a view controller and setup it's tab bar item with a title and image
-(UIViewController*) viewControllerWithTabTitle:(NSString*) title image:(UIImage*)image
{
UIViewController* viewController = [[[UIViewController alloc] init] autorelease];
viewController.tabBarItem = [[[UITabBarItem alloc] initWithTitle:title image:image tag:0] autorelease];
return viewController;
}
// Create a custom UIButton and add it to the center of our tab bar
-(void) addCenterButtonWithImage:(UIImage*)buttonImage highlightImage:(UIImage*)highlightImage
{
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button setBackgroundImage:highlightImage forState:UIControlStateHighlighted];
[button setBackgroundImage:highlightImage forState:UIControlStateSelected];
CGFloat heightDifference = buttonImage.size.height - self.tabBar.frame.size.height;
if (heightDifference < 0)
button.center = self.tabBar.center;
else
{
CGPoint center = self.tabBar.center;
center.y = center.y - heightDifference/2.0;
button.center = center;
}
[self.view addSubview:button];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
@end
If you fork the github link above and run the DailyBoothViewController example, pressing the middle button will have it highlighted. Now what I want is that for the highlight to stay when the button is pressed, in other words I want to change the backgroundImage of the button when the state of the button is selected. I did do that via code, however it isn't changing the button image. Why is this?
A: According to the Apple documentation for UIControlState:
Selected state of a control. For many controls, this state has no effect on behavior or appearance. But other subclasses (for example, the UISegmentedControl class) may have different appearance depending on their selected state. You can retrieve and set this value through the selected property.
And when you check the selected property, similar thing is mentioned. Hence for UIButton this property has to be set explicitly in the Action button of the button.
As for the button the following must be done,
[button setBackgroundImage:highlightImage forState:(UIControlStateHighlighted|UIControlStateSelected)];
[button setBackgroundImage:highlightImage forState:UIControlStateSelected];
And in the action method of this button, have the following code:
buttonState = !buttonState;
[(UIButton *)sender setSelected:buttonState];
Where buttonState should be a BOOL iVar in the corresponding class. In this case, the button state toggles the selected state. Hence the image for the selected state is set as desired.
Also note that we are getting the highlighted image for (UIControlStateHighlighted|UIControlStateSelected), because, when you select the button, this is an intermediate state.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IdDNSResolver QueryResult.count delphi xe2 i am using delphi xe2
i am sending 2 txt record in single request but my application is only recieving 1
IdDNSResolver QueryResult.count =1
i have checked manually by using nslookup server is returning 2 records.
what could be the problem..
edit.. nslookup response for the txt query
charly0 text = "ABAAAADACgAAAEAAABAAAAACAAABAAAAAAAAAAQAAAAAAAAAANANAAAEAAAAAAAAAgAAAAAAEAAAQAAAAAAQAAAQAAAAAAAAEAAAAAAAAAAAAAAAAPAKADInAAAA4AsAAOgBAAAAAAAAAAAAAAAAAAAAAAAAQAsAcJMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwCwAYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ09ERQAAAABkqwoAABAAAACsCgAABAAAAAAAAAAAAAAAAAAAIAAAYERBVEEAAAAAAB4AAADACgAAHgAAALAKAAAAAAAAAAAAAAAAAEAAAMBCU1MAAAAAAIkIAAAA4AoA"
charly0 text =
"AAAAAADOCgAAAAAAAAAAAAAAAAAAAADALmlkYXRhAAAyJwAAAPAKAAAoAAAAzgoAAAAAAAAAAAAAAAAAQAAAwC50bHMAAAAACAAAAAAgCwAAAAAAAPYKAAAAAAAAAAAAAAAAAAAAAMAucmRhdGEAABgAAAAAMAsAAAIAAAD2CgAAAAAAAAAAAAAAAABAAABQLnJlbG9jAABwkwAAAEALAACUAAAA+AoAAAAAAAAAAAAAAAAAQAAAUC5yc3JjAAAAAOgBAADgCwAA6AEAAIwLAAAAAAAAAAAAAAAAAEAAAFAAAAAAAAAAAAAAAAAA0A0AAAAAAAB0DQAAAAAAAAAAAAAAAABAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: position input after closest span, if it exists, in jquery I currently have this function which appends an "input" to the #cursor-start div:
var $cursorStart= $("#cursor-start");
$("#main-edit").click( function() {
var cursorExists = $("#cursor").length;
if (!cursorExists){
$cursorStart.append("<input type='text' id = 'cursor' />");
$("#cursor").markCursor();
}
if (cursorExists){
$("#cursor").focus();
}
What I want to do now is add the input after the closest span if it exitst. There are other functions called enterText and markCursor that are called when typing:
jQuery.fn.markCursor = function(e){
$(this).focus();
$(this).keyup(function(e) {
$cursorStart.enterText(e);
});
};
jQuery.fn.enterText = function(e){
var $cursor = $("#cursor");
if( $cursor.val() && e.keyCode != 32 ){
var character = $("#cursor").val();
$cursor.val("");
character = character.split("").join("</span><span class='text'>");
$("<span class = 'text'>"+character+"</span>").insertBefore($cursor);
}
});
I want now to position the input depending on where the user clicks, would .offset() or .position() be of help here?
HTML :
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
clicking near a and b would result in an input after "a"
A: Instead of listening for clicks on #main-edit, listen for the clicks on the spans themselves:
$('#main-edit span').click(function() {
$(this).after('<input type="text" id="cursor" />');
});
Or use delegate:
$('#main-edit').delegate('span', 'click', function() {
$(this).after('<input type="text" id="cursor" />');
});
And here's the fiddle: http://jsfiddle.net/YxfWX/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: use php to change a html elements inner text I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
A: You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
A: If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
A: Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
A: You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Lighttpd config error I have this config error:
$ sudo /etc/init.d/lighttpd restart
Stopping web server: lighttpd.
Starting web server: lighttpdDuplicate config variable in conditional 0 global: fastcgi.server
2011-09-25 19:12:13: (configfile.c.855) source: /etc/lighttpd/lighttpd.conf line: 178 pos: 10 parser failed somehow near here: (EOL)
failed!
Here's my config file: http://pastebin.com/kzW1kCP5
May I know what went wrong? Thanks!
A: According to the error message, you have another fastcgi.server configuration directive somewhere. As it's not in the main configuration file, it's probably imported from another file. See what you can find in /etc/lighttpd/conf-available and /etc/lighttpd/conf-enabled.
Serverfault.com would maybe have been a better place for this question. As a matter of fact, there's a question over there which is very similar to yours.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display chinese characters on Windows XP My WPF application needs to display chinese characters.
Things work perfectly when running on Windows 7.
However, when running the exact same application on Windows XP, the UI shows a series on squares instead of the chinese characters.
In both cases, no chinese system package was installed.
Do you have any suggestion?
A: There's no issue with .net or XP. The problem is with the font. You need to make sure that you are using a font which contains all the glyphs that you wish to display.
A: You will need to install fonts that can display Chinese glyphs, not present by default. IIRC, Control Panel + Regional and Languages Options, Language tab, Install files for East Asian languages checkbox. Ask at superuser.com if you need more help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: upload a javascript File object through an iFrame I'm trying to create a drag and drop file upload UI. The problem is that I have to submit the files using an old fashioned multipart form. Is it possible to take the File objects you get from a drop event and somehow insert them into a form so they can be submitted to an iFrame like file inputs?
A: If you have to submit via a multi-part form, then no, there's no cross-browser way to do this. Browsers will not let JavaScript code update the value of any "file" input elements, for reasons that should be obvious (security - if your code code set a "file" input to any path, well ...).
There are newer ways of handling files, but in general there's still no way to create or copy a "file" element with a value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with populating textviews from DB rowid I am trying to make a program that has 2 views. The first view is a list populated from a database. What i want is, when i click an item of the list then i want the program to open the secound view and fill some textviews with data from the database according to the item i clicked. What i have done for now is looking like this:
The first view:
public class MainActivity extends ListActivity {
private static final int ACTIVITY_VIEW = 1;
private DbAdapter mDbHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDbHelper = new DbAdapter(this);
mDbHelper.open();
fillData();
}
private void fillData()
{
Cursor contactCursor = mDbHelper.fetchAllContact();
startManagingCursor(contactCursor);
String[] from = new String[]{DbAdapter.KEY_FIRST};
int[] to = new int[]{R.id.contactlist};
SimpleCursorAdapter contactsfirst = new SimpleCursorAdapter(this, R.layout.list, contactCursor, from, to);
setListAdapter(contactsfirst);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, PersonPage.class);
i.putExtra(DbAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_VIEW);
}
That should open this view, but it doesent:
public class PersonPage extends Activity
{
private EditText mFirstText;
private EditText mLastText;
private EditText mPhoneText;
private EditText mMPhoneText;
private EditText mRoomText;
private EditText mInitialText;
private Button mBackButton;
private Long mRowId;
String back = new String("Back");
String na = new String("N/A");
private DbAdapter mDbHelper;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mDbHelper = new DbAdapter(this);
mDbHelper.open();
setContentView(R.layout.personpage);
mFirstText = (EditText) findViewById(R.id.first);
mLastText = (EditText) findViewById(R.id.last);
mPhoneText = (EditText) findViewById(R.id.phone);
mMPhoneText = (EditText) findViewById(R.id.mphone);
mRoomText = (EditText) findViewById(R.id.room);
mInitialText = (EditText) findViewById(R.id.initial);
mBackButton = (Button) findViewById(R.id.back);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(DbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(DbAdapter.KEY_ROWID)
: null;
populateFields();
mBackButton.setOnClickListener(new TextView.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(PersonPage.this, MainActivity.class);
PersonPage.this.startActivity(i);
}
});
}
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchContact(mRowId);
startManagingCursor(note);
mFirstText.setText(note.getString(
note.getColumnIndexOrThrow(DbAdapter.KEY_FIRST)));
mLastText.setText(note.getString(
note.getColumnIndexOrThrow(DbAdapter.KEY_LAST)));
mPhoneText.setText(note.getString(
note.getColumnIndexOrThrow(DbAdapter.KEY_PHONE)));
mMPhoneText.setText(note.getString(
note.getColumnIndexOrThrow(DbAdapter.KEY_MPHONE)));
mRoomText.setText(note.getString(
note.getColumnIndexOrThrow(DbAdapter.KEY_ROOM)));
mInitialText.setText(note.getString(
note.getColumnIndexOrThrow(DbAdapter.KEY_INITIAL)));
}
}
Can anyone of you help me find the problem?
A: Your onListItemClick() should look like this..
@Override
public void onListItemClick(ListView list, View view, int position, long id){
Intent i = new Intent(meeting_list.this, ACTIVITY.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
In the next activity just retrieve the ID.
Also put a log message to log the ID to insure it is being passed
Here to the passing activity retrieve it.
ID = getIntent().getStringExtra(ACTIVITY.ID_EXTRA);
//USe this to load the data with a cursor
public void load(){
Cursor c = helper.getByID(meetingId);
There should be a method in your database to getById(). Like this..
public Cursor getByID(String id){
String [] args={id};
return(getReadableDatabase().rawQuery("SELECT _id, meetingTitle, meetingDescrip, meetingAdress, meetingDateTime, lat, lon, type FROM meetings WHERE _ID=?", args));
Just substitute your return arg's for mine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Writing huge Mongo result set to disk w/ Python in a resource friendly way There is a Mongo collection with >5 Million items. I need to get a "representation" (held in a variable, or put into a file on disk, anything at this point) of a single attribute of all of the 'documents'.
My query is something like this:
cursor = db.collection.find({"conditional_field": {"subfield": True}}, {"field_i_want": True})
My first, silly, attempt was to Pickle 'cursor', but I quickly realized it doesn't work like that.
In this case, "field_i_want" contains an Integer. And as an example of something I've tried, I did this, and practically locked up the server for several minutes:
ints = [i['field_i_want'] for i in cursor]
... to just get a list of the integers. This hogged CPU resources on the server for far too long.
Is there a remotely simple way to retrieve these results into a list, tuple, set, pickle, file, something, that won't totally hog the cpu?
Ideally I could dump the results to be read back in later. But I'd like to be as kind as possible while dumping them.
A: I think that streaming the results is likely to help here:
with open("/path/to/storage/file", "w") as f:
for row in cursor:
f.write(row['your_field'])
Don't hold everything in memory if you don't have to.
A: Though accepted already, I'd add that you might consider adding an index too. It's easy to think we've exhausted mongo's 'bandwidth' but it's 'mongo' for a reason! Depending on the structure of your database, 5 million responses can be perfectly fast; it sounds like in total your data will be around 5 million integers? For simplicity, we'll assume field_i_want and so on are variables holding the field names. If you do:
db.collection.ensure_index([(conditional_field, DESCENDING), (field_i_want, ASCENDING)])
for example, you'll be able to execute a 'covered query,' like this:
db.collection.find({conditional_field:True},fields={field_i_want:1, _id:-1})
Sometimes pymongo will arbitrarily decide it needs to translate the dictionary-syntax of mongodb into a list, as in the case of ensure_index and fields, above. I believe you can use a dictionary for fields, which is necessary for covered queries, but if not you'd need to look into how to do covered queries with the awkward syntax using a list. The important thing with a covered query is to only return the fields that are part of your index. So you don't want "_id" because though "_id" is automatically indexed, it's not part of the index that will be used. There will be no time at all executing the query with a covered query. It will simply hand you all the data you want instantly. If you'd rather have it as a list than a list of dictionaries ('documents'), you can just take the response and do something like:
[y for x,y in myquery.items()]
Mongo is already a binary representation and it's good at storage, so this may be one of those questions where the best answer is to keep honing the question. If you just want a dump, you can use the utilities that come with mongo and can be found in the same directory as your mongod binary. This would allow you to get your data into json, stored as a file (though again, it's currently stored as a file in bson).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get and set wchar_t chars from c++ to MySQL to c++ I have a database (Mysql) with some fields in UTF-8 (I can change that if needed).
I use an old MySQL 'Communicator' or its predecessor, I wrote the code ~3 years ago and all I know today is that I link with libmysql.lib and #include "mysql.h" (do tell if you want me to dig up more).
The thing is I don't have a clue about how to insert and read non-ASCII.
I know about MultiByteToWideChar but some code compiles under Linux (gcc) so that won't work I guess.
What is the standard procedure when it comes to getting and setting std::wstrings (or wchar_t*) from/to a MySQL database when the code should run on Linux and Windows ?
A: Use the mysql_set_character_set() API to change the connection character set to "utf8". Convert your wstrings to UTF-8 (there's no library function, but you can write it fairly easily, or use iconv), and pass UTF-8 pointers to MySQL.
This API isn't present in older versions of MySQL C++ API (>5.0.7), so check your header first.
Note: on Win32 with Visual Studio, the wchar_t datatype is short, not int. You can change the connection charset to "ucs2" and pass wchar_t pointers directly, by just casting them to char*.
A: I recommend that you store your data in MySQL in UTF-8 form, rather than try to convince it to take Windows-native UTF-16. If your text is mostly Western, UTF-8 encoding will be more compact, and it will be more likely to work with the C-and-Unix nature of MySQL.
There are Visual C++ specific examples in MySQL++ that show how to do this. See CExampleDlg::ToUTF8() and the functions that call it in examples/vstudio/mfc/mfc_dlg.cpp, for example.
There's a chapter in the MySQL++ user manual that gives the whys and wherefores behind all this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Animated reloadData on UITableView How would you anime - reloadData on UITableView? Data source is on UIFetchedResultsController so I can't play with – insertSections:withRowAnimation:, – deleteSections:withRowAnimation: wrapped in – beginUpdates, – endUpdates.
EDIT:
I want to call - reloadData after NSFetchedResultsController refetch.
A: You cannot animate reloadData. You will have to use the table view's insert..., delete..., move... and reloadRows... methods to make it animate.
This is pretty straightforward when using an NSFetchedResultsController. The documentation for NSFetchedResultsControllerDelegate contains a set of sample methods that you just have to adapt to your own code:
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath]
atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
}
A: I did category method.
- (void)reloadData:(BOOL)animated
{
[self reloadData];
if (animated) {
CATransition *animation = [CATransition animation];
[animation setType:kCATransitionPush];
[animation setSubtype:kCATransitionFromBottom];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[animation setFillMode:kCAFillModeBoth];
[animation setDuration:.3];
[[self layer] addAnimation:animation forKey:@"UITableViewReloadDataAnimationKey"];
}
}
A: I created a UITableView category method based on solution from this link.
It should reload all the table sections. You can play with UITableViewRowAnimation options for different animation effects.
- (void)reloadData:(BOOL)animated
{
[self reloadData];
if (animated)
{
[self reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.numberOfSections)] withRowAnimation:UITableViewRowAnimationBottom];
}
}
A: typedef enum {
UITableViewRowAnimationFade,
UITableViewRowAnimationRight,
UITableViewRowAnimationLeft,
UITableViewRowAnimationTop,
UITableViewRowAnimationBottom,
UITableViewRowAnimationNone,
UITableViewRowAnimationMiddle,
UITableViewRowAnimationAutomatic = 100
} UITableViewRowAnimation;
and the method:
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
A: You can make a basic animation of reLoadData using:
// Reload table with a slight animation
[UIView transitionWithView:tableViewReference
duration:0.5f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^(void) {
[tableViewReference reloadData];
} completion:NULL];
A: You can simply call this lines when you want to reload the entire table with an animation:
NSRange range = NSMakeRange(0, [self numberOfSectionsInTableView:self.tableView]);
NSIndexSet *sections = [NSIndexSet indexSetWithIndexesInRange:range];
[self.tableView reloadSections:sections withRowAnimation:UITableViewRowAnimationFade];
A: You might want to use:
Objective-C
/* Animate the table view reload */
[UIView transitionWithView:self.tableView
duration:0.35f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^(void)
{
[self.tableView reloadData];
}
completion:nil];
Swift
UIView.transitionWithView(tableView,
duration:0.35,
options:.TransitionCrossDissolve,
animations:
{ () -> Void in
self.tableView.reloadData()
},
completion: nil);
Animation options:
TransitionNone
TransitionFlipFromLeft
TransitionFlipFromRight
TransitionCurlUp
TransitionCurlDown
TransitionCrossDissolve
TransitionFlipFromTop
TransitionFlipFromBottom
Reference
A: Swift 5.1 version of answer @user500 (https://stackoverflow.com/users/620297/user500)
func reloadData(_ animated: Bool) {
reloadData()
guard animated else { return }
let animation = CATransition()
animation.type = .push
animation.subtype = .fromBottom
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
animation.fillMode = .both
animation.duration = 0.3
layer.add(animation, forKey: "UITableViewReloadDataAnimationKey")
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: PHP while loop - exclude most recent row? I have a PHP while loop that loads user comments - I need to exclude the most recent row in the database.
$sql = "SELECT c.trackid, c.comment, c.time, c.userid, u.id, u.username FROM
comments c
LEFT JOIN users u
ON u.id = c.userid
WHERE trackid='$trackid'
ORDER BY c.time DESC";
$i=1;
while ($row = mysql_fetch_assoc($result)) {
echo "<div class=\"commentDivs\">" . $row['time'] ."<br><br> " . $row['username'] . "<div class=\"userPostedComments\">" . $row['comment'] . "</div></div>";
}
How do I exclude the most recent row from the loop?
A: If your query returns results sorted by most recent descending, you can do this on the query's side by specifying OFFSET 1.
Alternately, you can use mysql_data_seek to move the row pointer however you need.
A: you can do it this way you will have to run 2 queries first to find the id of the latest comment ....
$sql = mysql_query("SELECT id FROM tbl_name ORDER BY id DESC");
$row = mysql_fetch_array($sql);
$latest_id = $row['id'];
This will give you the latest id and then you can run the next query like this
$sql1 = mysql_query("SELECT * FROM tbl_name WHERE id != '$latest_id' ORDER BY id DESC");
while($row1 = mysql_fetch_array($sql1))
{ }
and let us know what you trying to do , might be that will make your code more clean
A: SELECT c.trackid, c.comment, c.time, c.userid, u.id, u.username FROM
comments c
LEFT JOIN users u
ON u.id = c.userid
WHERE trackid='$trackid'
AND c.time != ( SELECT max(c.time) FROM comments WHERE u.id = c.userid )
ORDER BY c.time DESC
A: please provide the database structure and the sql query so we can help , you can use ORDER BY id or store the time as DATETIME and ORDER BY time in the sql query
A: You could use something as
$rows = array();
while ($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
then you can easily use $rows as an array, and can step in a for-loop until count($rows)-1
like
for($i = 0; $i < count($rows) - 1 ; $i++)
{
print '<div class="commentDivs">' . $rows[$i]['time'] .'<br><br> ' . $rows[$i]['username'] . '<div class="userPostedComments">' . $rows[$i]['comment'] . '</div></div>';
}
EDIT: or you can jump over the specific line, if you hav not ordert them by the time...
or if you have it ordert DESC by the time yust modify my loop-header to
for($i = 1; $i < count($rows) ; $i++)
A: Here is a simple solution, using your current query:
for($i=1; $i < mysql_num_rows($result); $i++) {
mysql_data_seek($result, $i);
$row = mysql_fetch_assoc($result);
echo "<div class=\"commentDivs\">" . $row['time'] ."<br><br> " . $row['username'] . "<div class=\"userPostedComments\">" . $row['comment'] . "</div></div>";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: possible to create ebook programmatically? I am investigating whether it is possible to generate an ebook, say, a Kindle book, programmatically. are there any libraries, open source or proprietary? in particular, for python.
A: An ebook or epub is just xhtml with some meta info and stuff. Every page is a xhtml file.
Here is a tutorial on How to Make an ePub eBook by Hand.
A: Many but especially see calibre which can take text in various forms or HTML and convert to epub, mobi etc.
A: For .epub, as others have said, any tool that can generate XHTML will work - partially. You may also need the ability to generate a .gz file, IIRC, since I think the outermost container for EPUB is of that format, but Python has support for that in the standard library. I think IBM developerWorks had a tutorial on how to generate EPUB format ebooks, maybe in Python. Search on their site for it. Liza Daly, founder of ThreePress, who specializes in publishing-related development (in Python) and is the creator of O'Reilly Bookworm, a web-based EPUB reading application, may also have some tools for generating EPUB on her site.
My own xtopdf toolkit (written in Python), which requires the open-source version of the Reportlab toolkit (also in Python) can be used to generate simple PDF ebooks from a set of text files, where each file represents a chapter of the book. In the xtopdf package (.zip / .gz file), there is a script called PDFBook.py which does this.
You can get xtopdf from here:
http://sourceforge.net/projects/xtopdf/
And this page has a guide to installing xtopdf and to using that PDFBook.py script:
http://www.mail-archive.com/python-list@python.org/msg100069.html
So if you can generate those chapter files as text, programmatically (which should be possible), you can combine that ability with the PDFBook.py program, to do what you need - programmatically generate ebooks - for the case of PDF ebooks.
If you need any help using xtopdf, feel free to contact me via my web site's contact page - dancingbison dot com slash contact dot html - use my Gmail address given there. The (hosted) site goes down for short periods sometimes, so if you can't access it, just try again sometime later.
HTH,
Vasudev Ram
A: Amazon provides kindlegen which is a command line program for generating an ebook from XML/HTML sources.
I generated books for Stack Overflow content using a set of scripts available here (the code is a mix of Python, Java, and XSLT).
Another example is rss2mobi which generates ebooks from a Google Reader feed (this one is all Python).
A: creating an ebook in python is almost trivial if you want to do it in epub format.
if you want a link to something simple and working, have a look at txt2epub (and provide feedback if you please).
it is called txt 2 epub, but it also handles rst files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Really Confused about ajax image upload Over the last couple of weeks I have asked a couple of questions on this subject. It seems as though the harder I try to figure this out, the further away from a solution I appear to be. That may just be a function of me being an idiot
Here is a brief summary of what I have learned so far:
A) There is really no AJAX upload functionality. You are really just updating an Ipage form element. It appears like AJAX, but it truly isn't.
B) There is no AjaxUpload plugin by valumns. At least not named that. After looking at several tutorials on ajax upload that each refer to the AjaxUpload.js plugin and getting absolutely bubkis because on his page, it is not named AjaxUpload.js, it is name something else. If it is even there at all. I didn't feel like going through the hassle of renaming it, and just freaking seeing what happens, because that usually just results in an ugly orgy of errors on obsenities.
C) Alot of the solutions appear to use CAKE. Not really sure what the hell that is, but it looks like some kind of PHP design pattern based off of the popular MVC design pattern. Not really sure though.
D) this appears to be a really hard task. Not something that would take a couple of lines of code and prayer.
D1) The PHP code seems simple enough. Just call the function that moves files...
D2) The jquery seems a little bit trickier. Here is where you are calling the above php function. I want to call this when I click inside the text box for the upload... A simple
$('form#inputId').change(function (){//insert the code to call php function here});
should do that right? The trick is what I write inside of those curly brackets?
That would be the sum-total of what I understand about the subject... This is what I have...
<?php
$link = mysql_connect('greetmeet.ipagemysql.com', 'greetmeet', 'Maverick$41');
mysql_select_db(first_1) or die("Opps, You are pretty Got-Damned Stupid! Did you realize that?!?!?");
$target = './Uploads/';
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
$path = "uploads/";
$Email = $_SESSION['user_email']; //This should be a session ID. Must talk this over with Fellow Coder That Nigga, LJeezy West...
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE user_pics SET profile_pic='$actual_image_name' WHERE Email='$Email'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
That would be the php function that I want to call that would move the file to my server and then put the link in the database.
my Again, my jquery code is pretty confusing, and probably all wrong. I just doin't know what to do there. I just want something really simple for now. Nothing fancy, Just upload the photo with preview and then on submit finalize everything. Is there anyway that I could do this by putting the picture directly in mysql btw?
Also,
This tutorial seemed usefull...
http://www.akchauhan.com/upload-image-using-hidden-iframe/
But really hard to understand...
And this is an example of a pluggin that uses AjaxUpload... Where is the AjaxUpload.js file?
http://www.zurb.com/playground/ajax_upload
A: I suggest using the plugin "ajaxfileupload.js".
This is quite easy to use.
Please check the link below for its instructions and download:
http://www.phpletter.com/Our-Projects/AjaxFileUpload/
Note: This is not using any flash. That is the good aspect of it.
A: In the tutorial you mentioned you may get lost in the links because the component that is used stopped to be maintaned. Anyway, you find the project here. What you want is the file ajaxupload.js in the root folder of the project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disable postback at click on a button I want do disable postback after clicking a <asp:Button>. I've tried to do that by assigning onclick="return false", but in the button doesn't work.
How can I fix this?
A: onclick is used to wire up your server side events. You need to use the OnClientClick handler such as <asp:button OnClientClick="return false;" />
A: I could fix that using an UpdatePanel which includes the implicated controls/elements.
A: It worked for me like this:
In <body>:
function myfunction() {
return false;
}
and in <head>:
<asp:ImageButton ID="ImageButton1" runat="server" Height="52px" Width="58px" OnClientClick="myfunction(); return false;"/>
A: Use this:-
someID.Attributes.Add("onClick", "return false;");
A: onClientClick="return false"
That should do it! Onclick will refer to an ASP.net function, onClientClick will render as OnClick on the control in HTML.
A: Seeing as none of these answers helped me. I found a solution. Instead of using the ASP.NET button <asp:Button>, you should use the HTML button. It worked perfectly and looks exactly like the ASP.NET button. To get the HTML button to submit on server side, you use the attribute onserverclick.
<input id="btnState" class="AddButtons" runat="server" type="button" value="Add State" onclick="swap('one', 'two');" />
For my code, I was using JS to do something on the server side. The <asp:Button> would not stop doing a post back but as I said, the HTML button fixed my problem. Please mark as answer or vote up if this helped you out.
A: Put your asp button to inside the Updatepanel like
<asp:UpdatePanel ID="updPnl" runat="server" UpdateMode="Conditional" RenderMode="Block">
<ContentTemplate>
<asp:Button ID="btnID" runat="server" OnClick="btn_Click" />
</ContentTemplate>
</asp:UpdatePanel>
A: Since you want to do it after the postback, I presume you want to prevent double click postbacks? In this case you are best off having some sort of state maintaining variable that you set after the first click on the client side. As a simple example
var clicked = false;
function AllowOneClick(){
if(!clicked){
clicked = true;
return true;
}
return false;
}
You then set OnClientClick to return this method result on your button so OnclientClick="return AllowOneClick()"
This will of course only work for one button, but it should give you the general idea.
A: In my case none of the solutions above worked for me.
What I wanted was to first call a function on the client side and then halt the postback to the server. My solution was to simply add the return keyword before calling my client-side function, i.e.:
<asp:Button Runat=Server OnClientClick="return fyFunction;">
My client-side script contains return false in the last line of code.
A: by using UseSubmitBehavior="false" you can disable postbacks of onclick
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: NullReferenceException testing dataset in asp.net I have written a 3 layer web site which has singleton repository for accessing database. My repositories use dataset for connecting to and query from database.
I want to test the site using Visual Studio 2010 Test project but when I create TableAdapter of dataset in repository I got following error in test application:
System.NullReferenceException: Object reference not set to an instance
of an object.
the code work correctly when I use repository from the inside of site but in test application I got that error.
one of my repositories which I got that error is follow:
public sealed class VehicleRepository
{
private readonly int gateCode;
private readonly VehicleTableAdapter vehicleSet;
private readonly VehicleTypeTableAdapter vehicleTypeSet;
private static VehicleRepository instance;
private VehicleRepository()
{
var configureTable = new ConfigurationTableAdapter();
--->>> var configuration = configureTable.GetData().ToList();
if (configuration.Count == 0)
throw new UserInterfaceException("some message");
if (configuration.Count != 1)
throw new UserInterfaceException("some message");
gateCode = configuration[0].GateCode;
vehicleSet=new VehicleTableAdapter();
vehicleTypeSet=new VehicleTypeTableAdapter();
}
public static VehicleRepository GetInstance()
{
return instance ?? (instance = new VehicleRepository());
}
public Vehicle GetVehicleByPlaque(string plaque)
{
.....
}
private static Vehicle ConvertVehicleRowToVehicle(TransportCo.VehicleRow vehicleRow,TransportCo.VehicleTypeRow vehicleTypeRow)
{
....
}
public void SaveOrUpdate(Vehicle vehicle)
{
...
}
private static void UpdateVehicle(Vehicle vehicle)
{
...
}
}
I got the error in the --->>> line.
does anyone know the problem?
A: I suspect that if you break that line into two steps and look at what GetData returns, you'll see it is null.
A: One Common catch ya with databases and test is that usually the connection string is stored in the configuration file of the web site. The web.config is usually not in play when executing the tests. That can easily lead to a scenario like the one you describe. So even though you know that it works in production it doesn't say anything about whether the connection is setup up correctly in test
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I pass R variable into sqldf? I have some query like this:
sqldf("select TenScore from data where State_P = 'AndhraPradesh'")
But I have "AndhraPradesh" in a variable stateValue. How can I use this variable in a select query in R to get the same result as above.
Please show me the syntax.
A: See Example 5 on the sqldf GitHub page.
Example 5. Insert Variables
Here is an example of inserting evaluated variables into a query using gsubfn quasi-perl-style string interpolation. gsubfn is used by sqldf so it is already loaded. Note that we must use the fn$ prefix to invoke the interpolation functionality:
minSL <- 7
limit <- 3
species <- "virginica"
fn$sqldf("select * from iris where \"Sepal.Length\" > $minSL and species = '$species'
limit $limit")
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 7.1 3.0 5.9 2.1 virginica
## 2 7.6 3.0 6.6 2.1 virginica
## 3 7.3 2.9 6.3 1.8 virginica
A: You can also use fn$sqldf :
fn$sqldf("select TenScore from data where State_P = '$stateValue'")
A: You can use sprintf:
sqldf(sprintf("select TenScore from data where State_P = '%s'", stateValue))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: In the SECD Machine how does "rap" work? I am writing a simulator of the SECD machine in C# guided by the description on Wikipedia. I have the basic operations completed, but I am not sure how to implement the rap instruction.
At Wikipedia it says about rap:
rap works like ap, only that it replaces an occurrence of a dummy environment with the current one, thus making recursive functions possible
And for ap it says:
ap pops a closure and a list of parameter values from the stack. The closure is applied to the parameters by installing its environment as the current one, pushing the parameter list in front of that, clearing the stack, and setting C to the closure's function pointer. The previous values of S, E, and the next value of C are saved on the dump.
Here is my implementation of ap
public void ap()
{
Push(S, ref D);
Push(E, ref D);
Push(C, ref D);
List closure = Pop(ref S);
List paramlist = Pop(ref S);
E = closure.Tail;
Push(paramlist, ref E);
C = closure.Head;
S = List.Nil;
}
Note that List is my implementation of a Lisp style "cons" cell.
What confuses me is exactly how rap differs from ap? For example what exactly happens to the environment register (E)? I find the Wikipedia definition a bit ambiguous, and haven't been able to find anything else that explains it well.
A: SECD is not tail recursive, although you can build a tail recursive SECD machine (PDF).
The AP instruction is used to compile a 'let' binding whereas the RAP instruction is used to compile a 'letrec' binding.
'letrec' is different from 'let' because you can 'see' the environment where the recursive function is defined, so that you can call it recursively (so, for instance, you define a 'factorial' function and you can call it in the body of the function).
RAP modifies the environment by calling rplaca (similar to setcar! in Scheme). A previous DUM instruction adds a "dummy" car to the environment (which is never used), and RAP removes this "dummy" 'car' in the environment and replaces it with the appropriate one.
State transitions are like so:
((c'.e')v.s) e (AP.c) d =>
NIL (v.e') c' (s e c.d)
((c'.e')v.s) (?.e) (RAP.c) d =>
NIL (setcar! e',v) c' (s e c.d)
See also Revisiting SECD and the power of Lisp, quoting:
The RAP instruction is used to support recursive function calls and works by replacing a previously created dummy environment on the stack, called OMEGA, by one which contains all the functions that are visible in the recursive scope. The specification uses RPLACA to denote that replacement operation, and that is what we used in our Lisp implementation of SECD, too: ...
and
When trying to implement RAP in Erlang, I got stuck because there are no destructive operations on lists. Not in the standard API, and seemingly not in the system API either. So, the Erlang SECD looks nice, only it does not run.
A: You should really pick up a copy of Peter Henderson's wonderful little book "Functional Programming Application and Implementation". In it he meticulously describes and builds an SECD machine and Lispkit Lisp.
A: In addition to the excellent accepted answer, I wanted to provide more of an explanation of why rap is required.
The environment (the E in SECD) stores all of the persisted entities (functions, constants, variables, etc.). E is essentially a stack of lists. Things in E are loaded onto the stack S and then executed or used by commands in C. Everything in E is given an id so that it can be referenced later. This ID is typically a tuple (x,y), where x represents the location of the list on the stack, and y represents a position in that list.
In a typical function call, a new list is pushed on E and now any local variables can have IDs like (|E|, y), where |E| denotes the size of E. This is very problematic for recursive functions, however, because the stack size grows with each function call so there is no way to assign the local variables usable IDs.
To solve this problem, rap does most of the things ap does, but instead of pushing a new list onto the environment stack, it replaces whatever is at the head of the E with the new environment list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Control the clickable area of a link As you can see below I have a set of links quite close together and the clickable area of the links overlap:
I've tried playing with the padding and margin to no avail. How to I reduce the overlap?
A: It depends on your situation and isn't always possible, but if you could manage to get the links to be display: block, display: inline-block or position: absolute, you would be able to explicitly set their width and height.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ClassCastException android.view.viewgroup.$layoutParam TextView txt=new TextView(productlist.this);
txt.setText(author.get(groupPosition));
TextView txt1=new TextView(productlist.this);
txt1.setText(price.get(groupPosition));
txt.setLayoutParams(new LayoutParams(70, LayoutParams.WRAP_CONTENT));
txt1.setLayoutParams(new LayoutParams(70,LayoutParams.WRAP_CONTENT));
LinearLayout ll=new LinearLayout(productlist.this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// ll.setGravity(Gravity.CENTER);
ll.addView(txt);
ll.addView(txt1);
return ll;
hi, this is the code snippet for a group view in expandable ListView which gives error:
java.lang.ClassCastException android.view.viewgroup.$layoutParam
A: Make sure you import the correct LayoutParams.
*
*android.widget.LinearLayout.LayoutParams for LinearLayout
*android.view.ViewGroup.LayoutParams for TextView
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Sorting/Displaying by Numeric and then Alphabetically I have a list of these type of numbers with letters stored in a mySQL table
1
2a
2b
2c
3a
3b
4
5a
5b
10
Some have letters and some don't.
For the sample data above, I'd want it do display on the page like this
1
2a / 2b / 2c
3a / 3b
4
5a / 5b
10
and here is the basics of what I have so you can base your example off this which is just listing them on the page straight down
$sql = mysql_query("SELECT * FROM data") or die(mysql_error());
while($row = mysql_fetch_assoc($sql))
{
$dataID = $row['dataID'];
echo $dataID . "<br />";
}
I could probably do this with some substrings and if statements, but I have a feeling it can be done in a much better way... probably with regular expressions
A: Look at the natsort() function.
This function implements a sort algorithm that orders alphanumeric
strings in the way a human being would while maintaining key/value
associations. This is described as a "natural ordering".
A: A guy from here helped me out and gave me this nice chunk of code. Did the trick just right.
$query = "select dataID, dataID * 1 as ord FROM data order by ord, dataID";
$result = mysql_query($query);
$heading = null; // remember last heading, initialize to a value that will never exist as data
while(list($dataID,$ord) = mysql_fetch_row($result)){
if($heading != $ord){
// a new (or first) heading found
if($heading != null){
// not the first heading, close out the previous section
echo implode (' / ',$data) . '<br />';
}
$heading = $ord; // remember new heading
// start a new section
$data = array();
}
// handle each piece of data
$data[] = $dataID;
}
// close out the last section
echo implode (' / ',$data) . '<br />';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is my dictionary released in a NSArray? I've a tableviewcontroller which stores dictionary objects in an Array, when a row gets selected I push a new view controller on the navigation stack and I pass a dictionary object from the array in it's initializer, the dictionary object will be retained in a property of the new view controller. When I return back to my tableviewcontroller I release the dictionary object in the dealloc of the view controller. But when I scroll down/back in my tableviewcontroller, the dictionary that was passed to the view controller is deallocated in the tableviewcontroller's Array and the program crashes with the message:
BreakdanceSource[1351:607] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key title.'
When I remove the [dictionary release] from the dealloc function of the view controller, the program works and doesn't crash! It's weird because I thought the array also keeps ownership of it's objects so the dictionary shouldn't have been deallocated.
Why can't I release the dictionary object in my view controller? (I've removed the [dictionary release] now in the dealloc and the program works but won't I have a memory leak? )
I've tried this so far!:
imageshack.us/photo/my-images/813/screenshot20110926at610.png I've used the zombies tool and this is my result! What I don't get is that before the dealloc of my view controller the retain count is 1 which should've been 2. Because the array in the tableviewcontroller should own the dictionary and I've a property in my view controller which is @property (retain) NSDictionary* media. I don't know where my dictionary gets released, because now it only gets released in the view controller's dealloc
I've also tried to change the property @property (retain) to @property NSDictionary* media then I use media = [infoDictionary retain] and it doesn't crash.. did my property (retain) not retain it?
A: Yes NSMutableArray increases the retain count of an object that is added to it and correspondingly decreases the retain count when the NSMutableArray is released. That does not stop something else from decrementing the retain count to the point of an objects release. So, there must be another release/autorelease of the object.
Use Instruments Allocation tool, set the retain count option, find the object and you will see where the extra release is happening. See this SO answer for info on using Instruments in this manner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTTP PUT file and data In my RESTful API say I have a picture the user can update via a PUT request.
And let's say each of these pictures has a custom name the user can assign them so they can easily browse them.
What I'd like to do is send a put request that contains the updated file AND the new name for the picture, but I'm not sure how to have PHP separate the updated file from the new name when reading from php://input
Does anyone know how to do this?
A: Place scalar parameters (i. e. old name, new name) into the query string.
A: Have a look at AtomPub ( https://www.rfc-editor.org/rfc/rfc5023 ), especially edit-media links. It does not quite give you what you want, but maybe you can adapt it.
It should be semantically ok to PUT a multipart doc to an atom entry where the first part of the multipart is an atom entry XML to update the title. The content element of that entry could point to the second multipart part (the image data) using a cid: URI ( https://www.rfc-editor.org/rfc/rfc2392 )
The Slug header (also in RFC 5023) might also be a start to investigate.
There might also be some older headers around Content-Disposition: and Title: you might search for.
Another option is to just come up with a new resource that has the appropriate semantics and POST or PATCH a multipart or structured doc to that.
Jan
A: Why don't you use the url for the filename?
PUT /images/new_image.jpg
A: The correct format if you want to have multiple content types in the same request body is to use multipart mime to wrap them all into the same request body. Supporting something as complicated as multipart mime might be a bit hard to justify in this case though.
A: Upon consideration, I think what you need is a POST request with multipart/form-data. This allows for both file and some scalar data items, without the overhead of Base64 or URLEncode on the file data.
A: Use the SLUG header to do this:
In other words the Slug header provides a means for a client to suggest the URI for a newly created resource.
URIs can only use a limited set of characters, if the Slug uses characters outside the legal URI character set, then the server must escape those characters.
Two or more clients might attempt to create a resource with the same Slug at the same time, the server must give each resource a unique URI, so the server may choose to decorate the slug with additional characters to ensure each resource is uniquely named.
References
*
*Slug HTTP Header
*Text.Atom.Pub.Export
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Read string without parsing in Python xml.dom As you probably know, Pythons xml.dom readString() throws an exception, if there is anything wrong with the xml code.
I am currently writing a simple xmpp chat server, and as you probably also know, one of the first client request message does not close the stream:stream tag, until it does not get a reply.
Is there any way to use pythons xml.dom without "parsing" the xmlcode or should I write my own xml parser?
A: DOM parsers always need to read the entire XML file. You want a SAX parser.
A: Any reason you're not using an already established XMPP library like xmpppy? (See also)
A: The parser that is likely to give you the best experience is xml.parsers.expat. In your StartElementHandler create a DOM element, and add it to the current element as a child, then set the current element to the new element. In your EndElementHandler, pop the current element to that element's parent. If the parent was null, you have a stanza. Do careful testing of namespaces; you're liable to get the attributes wrong the first time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: My file output is being duplicated. Every new println includes all the previous. (Code included) Exactly what I'm doing,
FileOutputStream out;
PrintStream outputfile;
try{
out = new FileOutputStream("Project1.txt");
outputfile = new PrintStream(out);
int a[ ] = { 4, -3, 5, -2, -1, 2, 6, -2 };
int maxSum;
Formatter fmt = new Formatter();
//Setup table column titles
outputfile.println(fmt.format("%12s %12s %12s %12s %12s %12s%n", "Algorithm", "n", "time", "time/n^3", "time/n^2", "time/(n*log(n))"));
outputfile.println(fmt.format("%12s %12s %12s %12s %12s %12s%n%n", "_________", "_", "(ms)", "x100,000", "x10,000", "x10,000"));
// Algorithm 1
for( int n = 256; n <= 2049; n *= 2 ){
int alg = 1;
long timing;
maxSum = maxSubSum1( a );
timing = getTimingInfo( n, alg );
double time = (((double)timing)/1000000.0);
outputfile.println(fmt.format("%12s %12d %12f %12f %12f %12f%n", "Alg. 1", n, time, (time/(((long)n)*n*n))*100000.0, (time/(n*n))*10000, (time/((double)n*Math.log((double)n)))*10000));
}
}
catch(Exception e)
{
System.err.println("Error in writing to file");
}
Some output I am getting that I am referring to,
Algorithm n time time/n^3 time/n^2 time/(n*log(n))
Algorithm n time time/n^3 time/n^2 time/(n*log(n))
_________ _ (ms) x100,000 x10,000 x10,000
Algorithm n time time/n^3 time/n^2 time/(n*log(n))
_________ _ (ms) x100,000 x10,000 x10,000
Alg. 1 256 4.335838 0.025844 0.661596 30.543418
A: Perhaps you are making it more complicated than it needs to be.
out.printf("%s%n", "A");
out.printf("%s%n", "B");
or
out.println("A");
out.println("B");
outputs
A
B
A: Use String.format() instead of fmt.format(). Or call Formatter's constructor with out and remove the outputfile.println() calls:
out = new FileOutputStream("Project1.txt");
Formatter fmt = new Formatter(out);
fmt.format("%12s %12s %12s %12s %12s %12s%n",
"Algorithm", "n", "time", "time/n^3", "time/n^2", "time/(n*log(n))");
fmt.format("%12s %12s %12s %12s %12s %12s%n%n",
"_________", "_", "(ms)", "x100,000", "x10,000", "x10,000");
...
fmt.flush();
out.close();
A new Formatter() (created with noarg constructor) use an internal StringBuilder and appends every results of format() calls to it. Furthermore, every format() returns the formatter object itself (return this;). Then outputfile.println() calls the returned formatter's toString() method which returns the whole content of the internal StringBuilder. So, any subsequent calls of format() increases the StringBuilder's size and you print the whole buffer after every format() call.
A: When you construct a new Formatter, the destination of the formatted output is a StringBuilder. Therefore, every time you call outputfile.println(...), the current content of the StringBuilder is flushed to the output stream.
To fix this problem, all you need to do is this:
Formatter fmt = new Formatter(out);
fmt.format("%12s %12s %12s %12s %12s %12s%n", "Algorithm", "n", "time", "time/n^3", "time/n^2", "time/(n*log(n))");
Notice that you will not need to use a PrintStream object any more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sqlite3 inserts to non-indexed table taking longer as table gets larger Without getting into too much detail, I have a process in my iOS app that parses XML and inserts (sometimes up to 10s or 100s of) thousands of records into an Sqlite3 table.
For speed, I have no indexes on the table, and I'm inserting records into an in memory temporary table first then moving them over to the final table in batches of 400. Neither the temporary table or filesystem table have any indexes.
The problem I'm noticing is that at the beginning of the process, it takes about a 10th of a second to flush the 400 records to disk. Then with each flush, it takes longer and longer, where after a minute or two, it's taking 3 seconds to flush the 400 records. The longer it goes, the longer it takes. Each flush takes about a 1 to 2 tenths of a second longer than the previous one.
Since I'm not using any indexes, can anyone explain why this is happening and recommend a solution?
Update 1:
I tried setting PRAGMA syncronous = OFF; and while that sped things up a little, it still get a fraction of a second slower with every INSERT SELECT to the point where it is multiple seconds for every flush after a few thousand rows. I'll keep trying other optimizations to see if I can get to the bottom of this...
Update 2:
Clarification on what I'm doing: I'm inserting the records as they are parsed into a temporary table that's in memory until the count reaches 400 as counted by an int in Objective-C code. Once the record count is 400, I'm doing a single INSERT SELECT to move the rows into the table on disk, then I'm doing a DELETE * from the memory table. I'm timing each part. Sqlite3 optimizes DELETE * when it has no WHERE clause so that it's like dropping and recreating the table, and it is very quick, less than 100th of a second. It's only the INSERT SELECT from the memory table to the disk table that is decreasing in speed each time. That query starts out taking about 0.1 seconds, and after each batch of 400 records that is inserted, the query takes about .1 to .2 seconds longer than the last one, until it's eventually taking multiple seconds to move the 400 rows from memory to disk each time.
Update 3: Here are my table creation statements and the statement I'm using to move records from memory to disk. There are no keys at all. And yes my sqlite is configured so that the temporary table is in memory not disk.
The temporary table in memory:
*
*CREATE TEMPORARY TABLE allSongsTemp (title TEXT, songId TEXT, artist TEXT, album TEXT, genre TEXT, coverArtId TEXT, path TEXT, suffix TEXT, transcodedSuffix TEXT, duration INTEGER, bitRate INTEGER, track INTEGER, year INTEGER, size INTEGER);
The table on disk:
*
*CREATE TABLE allSongsUnsorted (title TEXT, songId TEXT, artist TEXT, album TEXT, genre TEXT, coverArtId TEXT, path TEXT, suffix TEXT, transcodedSuffix TEXT, duration INTEGER, bitRate INTEGER, track INTEGER, year INTEGER, size INTEGER);
The queries to flush the memory records to disk:
*
*INSERT INTO allSongsUnsorted SELECT * FROM allSongsTemp;
*DELETE * FROM allSongsTemp;
The query that is taking longer and longer each time is #3, the INSERT SELECT. The DELETE takes about 1/100th of a second each time.
A: Read up on transactions, and why you should use them. If you do individual inserts then each insert must go through a start/end transaction cycle, with considerable overhead. When doing bulk insert/update operations always do a start transaction first.
A: What do your keys look like, and do you have any unique columns/constraints on this table? A definition (with changed column names if the real names are too revealing) would help diagnose the problem, but my guess would be a sneak unique constraint somewhere in your table definition.
A: Larry Lustig called it in the comments to the question, but doesn't seem to be around anymore to create an answer.
Dropping and re-creating the table instead of doing DELETE * did the trick. It seems that though the delete was quick, it was causing some kind of fragmentation in memory that was slowing down each subsequent read. Unless I misread the sqlite3 docs, a DELETE * is supposed to be optimized as a DROP; CREATE; but it seems that may not be exectly the case for temporary memory tables (or maybe even filesystem tables, but I would need to test that to verify as this issue could very well only affect memory tables).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android HttpClient memory leak? I was looking at code for a sample Android application. Within the code, the application creates an HttpClient, but I never see anywhere where the connection is closed. So I was wondering does this code create a memory leak? If not, can you explain why?
The link to the sample code is at:
http://developer.android.com/resources/samples/SampleSyncAdapter/src/com/example/android/samplesync/client/NetworkUtilities.html
A: HttpClient relies on a ClientConnectionManager to handle opening and closing connections. It (HttpClient) is a utility class that is supposed to allow you to forget about lots of details like closing connections.
"That's not a bug. It's a feature!"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rectangle Auto Blit I have a container rectangle and element rectangle, both are specified only in height and width. Using PHP I need to figure out what positions and orientation would allow for the most possible blits of the element within the container having absolutely no overlap.
An Example :
$container = array(5000,2000);
$element = array(300,200);
The output should be an array of "blit" arrays (or objects) like so
$blit_object = array($x,$y,$rotation_degrees);
A: Well, since no one is answering me, I am just going to show my "trial and error" solution in case anyone else ever needs it.
It calculates the two basic layout options and sees which one has the most and uses that.
function MakeBlits($container,$element)
{
$container_x = $container[0];
$container_y = $container[1];
$options = array();
for($i = 0;$i<=1;$i++)
{
if($i == 0)
{
$element_x = $element[0];
$element_y = $element[1];
}
else
{
$element_x = $element[1];
$element_y = $element[0];
}
$test_x = floor($container_x/$element_x);
$test_y = floor($container_y/$element_y);
$test_remainder_x = $container_x - $test_x*$element_x;
$test_remainder_y = $container_y - $test_y*$element_y;
$test_x2 = 0;
$test_x3 = 0;
$test_y2 = 0;
$test_y3 = 0;
if($test_remainder_x > $element_y)
{
$test_x2 = floor($test_remainder_x/$element_y);
$test_y2 = floor($container_y/$element_x);
}
if($test_remainder_y > $element_x)
{
$test_x3 = floor($container_x/$element_y);
$test_y3 = floor($test_remainder_y/$element_x);
}
$options[] = array(
'total'=>($test_x*$test_y)+($test_x2*$test_y2)+($test_x3*$test_y3),
'x'=>$test_x,
'y'=>$test_y,
'x2'=>$test_x2,
'y2'=>$test_y2,
'x3'=>$test_x3,
'y3'=>$test_y3
);
}
if($options[0]['total']>=$options[1]['total'])
{
$option = $options[0];
$rotate = 0;
$width = $element[0];
$height = $element[1];
}
else
{
$option = $options[1];
$rotate = -90;
$width = $element[1];
$height = $element[0];
}
$blit_objects = array();
for($i=0;$i<$option['x'];$i++)
{
for($j=0;$j<$option['y'];$j++)
{
$blit_objects[] = array(
'x'=>$i*$width,
'y'=>$j*$height,
'rotation'=>$rotate);
}
}
for($k = 0;$k < $option['x2'];$k++)
{
for($l = 0;$l < $option['y2'];$l++)
{
$blit_objects[] = array(
'x'=>$i*$width + $k*$height,
'y'=>$l*$width,
'rotation'=>$rotate+90);
}
}
for($k = 0;$k < $option['x3'];$k++)
{
for($l = 0;$l < $option['y3'];$l++)
{
$blit_objects[] = array(
'x'=>$k*$height,
'y'=>$j*$height+$l*$width,
'rotation'=>$rotate+90);
}
}
return $blit_objects;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: connecting three NSStrings Right i have three NSStrings that i want to put together to make one long nsstring (to use as a URL). I have used stringByAppedingString which lets me put two of the together but i do not know how to put three together. Basically what i want to end up with is http://graph.facebook.com/517418970/picture?type=large but i need them in three separate components so i can change the number in the URl
@implementation FacebookPicturesViewController
- (IBAction) nextImagePush {
NSString *prefix = @"http://graph.facebook.com/";
NSString *profileId = @"517418970";
NSString *suffix = @"/picture?type=large";
NSString *url = [prefix stringByAppendingString:suffix];
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
[imageView setImage:img];
imageCount++;
if (imageCount >= [imageArray count]){
imageCount = 0;
}
}
- (void) viewDidLoad {
imageArray = [[NSArray alloc] initWithObjects:@"image1", @"image2", nil];
imageCount = 0;
}
A: You could just do it in two steps:
NSString* partialUrl= [prefix stringByAppendingString:profileID];
NSString* fullUrl= [partialUrl stringByAppendingString:suffix];
Alternatively, you could use a format:
NSString* url= [NSString stringWithFormat:@"%@%@%@", prefix, profileID, suffix];
A: As a general solution for when you don't know ahead of time just how many strings you have to combine, you can stick them in an NSArray and use the array to join them together. So in this case:
NSArray *elementsInURL = [NSArray arrayWithObjects:prefix, profileID, suffix, nil];
NSString *combined = [elementsInURL componentsJoinedByString:@""];
A: You want + (id)stringWithFormat:(NSString *)format, …
Full docs are here
A: I'd handle the concatenation like this:
NSString *prefix = @"http://graph.facebook.com/";
NSString *profileId = @"517418970";
NSString *suffix = @"/picture?type=large";
NSString *URL = [[prefix stringByAppendingString:profileId]
stringByAppendingString:suffix];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ Factory pattern using templates for self registering My questions correspond to the answer from Johannes in Is there a way to instantiate objects from a string holding their class name? and the recent comment from Spencer Rose. Since I cannot add a comment there, I decided to start a new question.
Johannes suggestion is what I need. I implemented it in exact the same way but I have an unresolved external symbol linker error using VS2008 which seems to have something to do with the map. I am trying since days to solve it. Today I read the comment from Spencer and added the line he suggests
BaseFactory::map_type BaseFactory::map = new map_type();
to the Base.hpp. Now I get a LNK2005 error
Derivedb.obj : error LNK2005:
"private: static class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class Base * (__cdecl*)(void),struct std::less<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const ,class Base * (__cdecl*)(void)> > > * BaseFactory::map"
(?map@BaseFactory@@0PAV?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@P6APAVBase@@XZU?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@P6APAVBaser@@XZ@std@@@2@@std@@A)
already defined in Switcher.obj
Project.exe : fatal error LNK1169: one or more multiply defined symbols found)
instead of the LNK2001 error
(Switcher.obj : error LNK2001: unresolved external symbol "private: static class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class Base * (__cdecl*)(void),struct std::less<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const ,class Base * (__cdecl*)(void)> > > * BaseFactory::map" (?map@BaseFactory@@0PAV?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@P6APAVBase@@XZU?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@P6APAVBase@@XZ@std@@@2@@std@@A)
1>Derivedb.obj : error LNK2001: unresolved external symbol "private: static class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class Base * (__cdecl*)(void),struct std::less<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const ,class Base * (__cdecl*)(void)> > > * BaseFactory::map" (?map@BaseFactory@@0PAV?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@P6APAVBase@@XZU?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@P6APAVBase@@XZ@std@@@2@@std@@A)
1>Project.exe : fatal error LNK1120: 1 unresolved externals)
which means that I may have defined it twice??
Please could Spencer or somebody post the improved base.hpp code. It is such an important solution that it surely will be helpful for many more novice C++ programmers.
Second question: --> This problem is solved! Thanks!
I need some function declarations in base.hpp. Those should have been abstract in the base class and implemented in the subclasses (e.g. Derivedb.cpp ). But
public:
virtual ReadInFile(std::string path, std::string filename) = 0;
in base.hpp gave a compiler error. Removing "= 0" resolved the compiler error. But now I have another unresolved external symbol LNK2001 error
Derivedb.obj: error LNK2001: unresolved external symbol
"public: virtual __thiscall Base::ReadInFile(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)"
(?ReadInFile@Base@@UAE_NPAV@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@1@Z).
I call it in another cpp file
Base* importer = BaseFactory::createInstance("DerivedB");
importer->ReadInFile(m_path, m_filename);
Maybe it is not clear which function (base or subclass) need to be called since it is not abstract in the base class??? Is there any way of solving this problem? Thank you!
A: From the LNK2005 error, your BaseFactory class has a static field called map, right?
Static fields in C++ have to be "declared" inside the class's header file, and "implemented" in the class's source file.
Here is a simplified example of how to set this up. In this case, in the BaseFactory.h file, you should have the static field declared:
class BaseFactory
{
private:
static int map;
};
And in the BaseFactory.cpp file, the static field gets implemented:
int BaseFactory::map = 392;
The error message from the linker is saying that the BaseFactory::map static field got implemented in both the Derivedb.cpp file and the Switcher.cpp files.
Even if the implementation (... BaseFactory::map = ...) isn't in either of those files, you'll get the same error if you put the implementation in the BaseFactory.h header file. The C++ preprocessor just blindly includes code headers, and the linker can't tell whether the implementation is in the Switcher.cpp file or some file that Switcher.cpp included.
Just like methods need to be declared in .h files and implemented in .cpp files, the same goes for static fields.
A: map is the name of a template class in the STL, and therefore a poor choice for a variable name. This may or may not be related to the duplicate definition error you are getting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Xcode: Why doesn't my app save the UITextField? I have an app where I switch to a view with a TableView using presentModalViewController. The View with the TableView is however not at UITableViewController but a regular UIViewController. I have written UITextFields into the UITableViewCells. I use this action to save what the user inputs:
- (IBAction)saveTextField:(id)sender {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:TextField.text forKey:@"keyTextField"];
[userDefaults synchronize]; }
I call this method with this code:
[TextField addTarget:self action:@selector(hideKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
When I dismiss the ViewController using dismissModalViewController and then when I presents it again I call the NSUserDefaults in the ViewDidLoad with this code:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
TextField.text = [userDefaults objectForKey:@"keyTextField"];
Problem is that it doesn't work. And I can't figure out the problem. Any help would be appreciated.
Thanks in advance :)
A: The target has to be the same as your method, meaning that if you have - (void)saveTextField:(id)sender then you code to add the target need to be
[TextField addTarget:self action:@selector(saveTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
Check usin NSLog if your action is being run.
A: Instead of setting a target, can't you do that saving with the textFieldDidEndEditing: delegate method?
A: use this code in view did load
NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
TextField.text=[user stringForKey:@"keyTextField"];
A: To begin with: thanks to all of you for your effort and time :)
Turns out the problem wasn't with the code that saves and loads it. The problem was that I only created one UITextfield which I then put into every UITableViewCell and that was the problem. So I created individual UITextFields for every UITableViewCells and that fixed the problem :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to integrate maven 2 in an existing netbeans project? How to integrate maven 2 in an existing netbeans project ?
I dont want to do it by creating a new maven web app project and moving my files manually to
the new project(as I have versions of this project in my subversion repositories which I wont be able to link if I create new project), rather I need to integrate that in my already existing netbeans project. How do I go about it ? Would creating a pom.xml work ?
Maven 2 already installed on my machine.
A: What about creating a new Maven Web Project and moving the pom.xml back to your existing Web Project? I mean:
*
*Backup your projects
*Create a new project with name MavenWebTest
*Close your original project
*Move the pom.xml from the MavenWebTest project to your original project's folder
*Modify the pom.xml's project specific settings (e.g. project name, dependencies)
*Delete the build.xml and the whole nbproject folder
*Move and rename the web folder to src/main/webapp (webapp is the new name) (use svn mv if you use Subversion)
*Move src/java to src/main/java (svn mv here too)
*Open you project again in Netbeans. It should be a Maven project now.
*Delete the unnecessary MavenWebTest project
Anyway, creating an empty pom.xml also should work. You have to list your dependencies in the pom.xml and you have to set the project's name. Maybe other fine tunings also required to get the same result as Netbeans create without Maven. If you create the pom.xml with Netbeans (the MavenWebTest above) I suppose that most of Netbeans specific stuff already will be there.
If you are new to Maven I suggest you to check the free pdf/html books on Sonatype's website.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Observablecollection in Listbox is not updating I have a Silverlight Listbox bound to Observablecollection which shows up fine (first time) but when I try to update it through the code behind, the change does not reflect in UI. I have used MVVM pattern . Pl have a look and at view and viewmodel.
<UserControl x:Class="GridOperations.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:GridOperations.ViewModel"
mc:Ignorable="d"
d:DesignHeight="700" d:DesignWidth="700">
<UserControl.DataContext>
<local:ShowUserListViewModel/>
</UserControl.DataContext>
<UserControl.Resources>
<local:ShowUserListViewModel x:Key="viewModelKey"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<ListBox VerticalAlignment="Top" Margin="0,20,0,0" x:Name="lstBox" ItemsSource="{Binding UserList}" Width="700" Height="150" Background="AliceBlue">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBlock Margin="30,0,0,0" Text="{Binding UserId}" HorizontalAlignment="Left"/>
<TextBlock Margin="30,0,0,0" Text="{Binding Path=UserName, Mode=TwoWay}" Grid.Column="1" HorizontalAlignment="Left"/>
<Button Margin="30,0,0,0" Grid.Column="2" Content="Edit" Height="20" HorizontalAlignment="Left" Command="{Binding Source={StaticResource viewModelKey}, Path=UpdateUserCommand}" />
<Button Margin="10,0,0,0" Grid.Column="3" Content="Del" Height="20" HorizontalAlignment="Left" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
public class ShowUserListViewModel : INotifyPropertyChanged
{
public ShowUserListViewModel()
{
mUserList = new ObservableCollection<User>();
mUserList.Add(new User() { UserId = Guid.NewGuid().ToString(), UserName = "testuser1", IsAdmin = true });
mUserList.Add(new User() { UserId = Guid.NewGuid().ToString(), UserName = "testuser2", IsAdmin = true });
this.UpdateUserCommand = new DelegateCommand(this.UpdateUser);
}
public ICommand UpdateUserCommand { get; private set; }
private ObservableCollection<User> mUserList;
public ObservableCollection<User> UserList
{
get
{
return mUserList;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void UpdateUser()
{
this.UserList.Add(new User() { UserId = Guid.NewGuid().ToString(), UserName = "test", IsAdmin = false });
}
}
A: Firstly, you should avoid putting a collection property writable. IE, replace this code :
private ObservableCollection<User> mUsers = new ObservableCollection<User>();
public ObservableCollection<User> Users
{
get
{
return mUsers;
}
set
{
mUsers = value;
RaisePropertyChangedEvent("Users");
}
}
by this code :
private ObservableCollection<User> mUsers = new ObservableCollection<User>();
public ObservableCollection<User> Users
{
get
{
return mUsers;
}
}
Then, when you add an item to the collection, you don't have to tell the collection has changed (the collection property hasn't changed in itself), but it's the responsibility of the collection itself (via INotifyCollectionChanged) :
So, the "onclick" method can be simply like this:
private void OnClick(User userInstanceToEdit)
{
this.Users.Add(new User() { UserId = Guid.NewGuid().ToString(), UserName = "test", IsAdmin = false });
}
Finally, I would replace the ListBox.ItemsSource declaration with this one, as two ways is not required :
<ListBox x:Name="lstBox" ItemsSource="{Binding Users}"
A: Got a hint from this post Stackoverflow
Basically I need to use Datacontext with Listbox control (even after setting the Datacontext at UserControl level). The only line that required change is:
<ListBox x:Name="lstBox" ItemsSource="{Binding Users}" DataContext="{StaticResource viewModelKey}" Width="750" Background="AliceBlue">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I set custom messages for Zend_File_Transfer_Adapter_Http validators I'm using Zend_File_Transfer for PHP file uploads and I want to add custom messages for validators.
This is how I do it:
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->addValidator('Size', false, array(
'max' => $userLimits->photos->max_size * 1024 * 1024,
'messages' => "'%value%' adlı dosya en fazla '%max%' olmalıdır"));
$upload->addValidator('Extension', false, array(
'case' => 'jpg,jpeg',
'messages' => "'%value%' jpg veya jpeg formatında olmalıdır"));
if (!$upload->isValid()) {
throw new Zf_Model_Exception('Hata: '.implode('<br>', $upload->getMessages()));
}
$files = $upload->getFileInfo();
It's ok upto here... The problem is, what if I want to change the Zend_Validate_File_Upload messages? File upload validator is added in the contructor of the Zend_File_Transfer_Adapter_Http class by default.
I couldn't see a way to access the file upload validator from "$upload" instance...
Removing the validator and adding it back with custom messages is not an option since it's avoided in the code...
So am I missing something here?
A: Just for the records, that's how I did it:
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->getValidator('Upload')->setMessages(array(
Zend_Validate_File_Upload::INI_SIZE => "'%value%' adlı dosya çok büyük",
Zend_Validate_File_Upload::FORM_SIZE => "'%value%' adlı dosya çok büyük",
Zend_Validate_File_Upload::PARTIAL => "'%value%' adlı dosya yüklenemedi",
Zend_Validate_File_Upload::NO_FILE => "'%value%' adlı dosya yüklenemedi",
Zend_Validate_File_Upload::NO_TMP_DIR => "'%value%' adlı dosya yüklenemedi",
Zend_Validate_File_Upload::CANT_WRITE => "'%value%' adlı dosya yüklenemedi",
Zend_Validate_File_Upload::EXTENSION => "'%value%' adlı dosya yüklenemedi",
Zend_Validate_File_Upload::ATTACK => "'%value%' adlı dosya yüklenemedi",
Zend_Validate_File_Upload::FILE_NOT_FOUND => "'%value%' adlı dosya bulunamadı",
Zend_Validate_File_Upload::UNKNOWN => "'%value%' adlı dosya yüklenemedi"
));
A: Set the messages option to an array, and use the error message constants from the validator to override the message. Here is an example for email address:
$element->addValidator('EmailAddress', false, array(
'messages' => array(
Zend_Validate_EmailAddress::INVALID_FORMAT => "'%value%' is not a valid email address. Example: you@yourdomain.com",
Zend_Validate_EmailAddress::INVALID_HOSTNAME => "'%hostname%' is not a valid hostname for email address '%value%'"
)
));
You can find those by looking at the source for the validator, or from the api docs.
A: $file->getValidator('Count')->setMessage('You can upload only one file');
$file->getValidator('Size')->setMessage('Your file size cannot upload file size limit of 512 kb');
$file->getValidator('Extension')->setMessage('Invalid file extension, only valid image with file format jpg, jpeg, png and gif are allowed.');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Validate Textfield after each character entered I have searched for an answer but cant find an answer related to this.
I am trying to validate every input into a textfield but not sure how to go about it, the idea is to check a username exist on a server so I would assume I need to post to the server each time something is entered and if success do whatever.
Could someone please advise I would be grateful.
A: Implement the delegate method textField:shouldChangeCharactersInRange:replacementString: to be informed about every change to the text. Return YES or NO depending on whether you want to accept the change or not.
It is probably a very bad idea to ask the server for approval of every single key press since that would create an intolerable lag and lead to a very bad user experience.
A: What Ole is saying is absolutely correct. I'll just give you an example of what he's saying.
First conform your class to the UITextFieldDelegate protocol. Then make sure in viewDidLoad (or similar) that you set the delegate to your class:
myTextField.delegate = self;
Next you can implement the method that Ole was mentioning. However, in your case you're not validating whether the user can enter anything or not, you just want to know what he entered so you can validate it online.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
[self verifyTheUserWithUsername:[textField.text stringByReplacingCharactersInRange:range withString:string]];
//do your appropriate check here
return YES; //we allow the user to enter anything
}
A: You can use addTarget:action:forControlEvents: with UIControlEventValueChanged (e.g: [textfield addTarget:self action:@selector(usernameChanged:) forControlEvents:UIControlEventValueChanged). This will inform you AFTER the text changes (so when you receive usernameChanged: you'll have the last modifications).
It's probably a good idea that instead of sending a request to the server each time the username changes you either send a request when the textfield looses caption or when some time passes from the last change (you can use a NSTimer for this).
You should use a single asynchronous request. If the request is active and the textfield is edited again you should cancel the request and set it to nil (since there's no reason to check the old username). If the request succeeds show up an icon, or whatever you want to do when you get the result from the server.
Edit:
Not sure if UIControlEventValueChanged worked on previous versions of iOS or if it was a mistake from my side, but it doesn't seem to work any longer. UIControlEventEditingChanged should be used instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android USB Vendor IDs for unknown brand Refer to http://developer.android.com/guide/developing/device.html#VendorIds, I want to buy a unknown brand Android device, such as http://app-4-android.blogspot.com/2011/09/ainol-novo-8-android-22-8-in-tablet.html, How can I get the USB Vendor ID? Can it be used to develop Android App?
Please advise.
A: you can use google vid 18d1. It worked for me.
A: try lsusb command on linux terminal, this show you the vendor id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: unix open file for write given file descriptor I want to open a file for write and I have been given the file descriptor for that file.
I know that fdopen can be used to write to the file as follows:
FILE * fp;
fp = fdopen(filedes, "a+");
fwrite("\n", sizeof(char), 1, fp);
Is there any other way to achive the same, i.e., write to a file given a file descriptor?
Thanks
A:
Is there any other way to achive the same, i.e., write to a file given
a file descriptor
You can write directly using the system call write(2).
write(fd, "\n", 1);
A: You can write a buffer of data to a file descriptor with the write system call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert recursive binary tree traversal to iterative I was asked to write the iterative version, but I wrote the recursive version i.e.
void inorderTraverse(BinaryTree root)
{
if(root==NULL)
printf("%d",root->id);
else
{
inorderTraverse(root->left);
printf("%d",root->id);
inorderTraverse(root->right);
}
}
I'm not looking for the code, I want to understand how this can be done. Had it been just the last recursive call, I would have done
void inorderTraverse(BinaryTree root)
{
while(root!=NULL)
{
printf("%d",root->id);
root=root->right;
}
}
But how do I convert to an iterative program when there are two recursive calls?
Here are the type definitions.
struct element{
struct element* parent;
int id;
char* name;
struct element* left;
struct element* right;
};
typedef element* BinaryTree;
This is what I thought of, am I on the right track?
temp=root;
while(1)
{
while(temp!=NULL)
{
push(s,temp);
temp=temp->left;
continue;
}
temp=pop(s);
if(temp==NULL)
return;
printf("%d\t",temp->data);
temp=temp->right;
}
A: The problem you're seeing is that you need to "remember" the last place you were iterating at.
When doing recursion, the program internally uses "the stack" to remember where to go back to.
But when doing iteration, it doesn't.
Although... does that give you an idea?
A: I can't think of a really elegant way to do this iteratively off-hand.
One possibility might be using a 'mark algorithm', where you start out with all nodes 'unmarked' and 'mark' nodes as they're handled. The markers can be added to the object model or kept in a seperate entity.
Pseudocode:
for (BinaryTree currentNode = leftmostNode(root); currentNode != null; currentNode = nextNode(currentNode)):
print currentNode;
currentNode.seen = true;
sub nextNode(BinaryTree node):
if (!node.left.seen):
return leftmostNode(node.left)
else if (!node.seen)
return node
else if (!node.right.seen)
return leftmostNode(node.right)
else
return nextUnseenParent(node)
sub leftmostNode(BinaryTree node):
while (node.left != null)
node = node.left
return node;
sub nextUnseenParent(BinaryTree node):
while (node.parent.seen)
node = node.parent
return node.parent
A: I take it for granted, that iterating down from the parent nodes to the left nodes is not a problem. The problem is to know what to do when going up from one node to the parent: should you take the right child node or should you go up one more parent?
The following trick will help you:
Before going upwards remember the current node. Then go upwards. Now you can compare: Have you been in the left node: Then take the right node. Otherwise go up one more parent node.
You need only one reference/pointer for this.
A: There is a general way of converting recursive traversal to iterator by using a lazy iterator which concatenates multiple iterator suppliers (lambda expression which returns an iterator). See my Converting Recursive Traversal to Iterator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Stream to Image and back I'm taking a Stream convert it to Image, process that image, then return a FileStream.
Is this a performance problem? If not, whats the optimized way to convert and return back a stream?
public FileStream ResizeImage(int h, int w, Stream stream)
{
var img = Image.FromStream(stream);
/* ..Processing.. */
//converting back to stream? is this right?
img.Save(stream, ImageFormat.Png);
return stream;
}
The situation in which this is running: User uploads image on my site (controller gives me a Stream, i resize this, then send this stream to rackspace (Rackspace takes a FileStream).
A: You basically want something like this, don't you:
public void Resize(Stream input, Stream output, int width, int height)
{
using (var image = Image.FromStream(input))
using (var bmp = new Bitmap(width, height))
using (var gr = Graphics.FromImage(bmp))
{
gr.CompositingQuality = CompositingQuality.HighSpeed;
gr.SmoothingMode = SmoothingMode.HighSpeed;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.DrawImage(image, new Rectangle(0, 0, width, height));
bmp.Save(output, ImageFormat.Png);
}
}
which will be used like this:
using (var input = File.OpenRead("input.jpg"))
using (var output = File.Create("output.png"))
{
Resize(input, output, 640, 480);
}
A: That looks as simple as it can be. You have to read the entire image contents to be able to process it and you have to write the result back.
FileStreams are the normal .NET way to handle files, so for normal purposes your approach is okay.
The only thing I don't understand is why you return the FileStream again - it is the same object as was passed by a parameter.
If you are doing a lot of images and only modify parts of the data, memory mapped files could improve performance. However it is a more advanced concept to use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to find location within list? I suspect this is a basic question(but I tried to google and search SO with no luck).
I have a list: [1, 2,3,4]
and I want to know where in the list the value of 3 is..but without using a for loop to go through the entire list. Is that possible? I'm already going through a very large list and want to minimize the number of loops through the entire list.
Is this possible?
A: [1, 2, 3, 4].index(3) # --> 2
.index() will raise an IndexError if it cannot find the value you are looking for.
Keep in mind if you are doing lots of .index() look-ups on large lists, that it can be very slow -- Python has to brute-force loop through the lists just like you were doing.
A: This really is a very basic question. You should look up the docs, e.g. here: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange
So your solution is:
[1,2,3,4].index(3)
# 2
Where 2 is the index, so:
[1,2,3,4][2]
# 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What happens when objects in the scene are outside the range between the near and far planes? From my understanding, the objects would get clipped. Is this correct? And how would this affect performance? Does OpenGL ES then just stop processing the polygons which are in front of the near plane or behind the far plane?
A: Your understanding is correct, these are clipped away. But keep in mind that this clipping happens after the vertex processing stage (transform and lighting in ES1, vertex shader in ES2). So only the rasterization and fragment stages (texturing in ES1, fragment shader in ES2) profit from this. The vertex stage always processes all polygons you send to the GL for drawing, as only after that you know their coordinates inside (or outside) the viewing volume (normalized device coordinates).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to define two relationships to the same table in SQLAlchemy I’ve looked all over the SQLAlchemy tutorial and other similar questions but I seem to be struggling to get this join to work:
The scenario: I have a pages table represented by the Page model. Pages can be created by an user and edited by an user, but not necessarily the same one. My Page model looks like this (abridged):
class Page(Base):
__tablename__ = 'pages'
id = Column(Integer, primary_key = True)
slug = Column(Text)
title = Column(Text)
direct_link = Column(Text)
body = Column(Text)
category_id = Column(Integer, ForeignKey('categories.id'))
published_on = Column(DateTime)
publishing_user_id = Column(Integer, ForeignKey('users.id'))
last_edit_on = Column(DateTime)
last_edit_user_id = Column(Integer, ForeignKey('users.id'))
# Define relationships
publish_user = relationship('User', backref = backref('pages', order_by = id), primaryjoin = "Page.publishing_user_id == User.id")
edit_user = relationship('User', primaryjoin = "Page.last_edit_user_id == User.id")
category = relationship('Category', backref = backref('pages', order_by = id))
My users are stored in the users table represented by the User model. As I said I’ve been all over the SQLAlchemy docs looking for this, I’ve tried to make it look as similar to their example as possible, but no to no avail. Any help would be greatly appreciated.
A: Try foreign_keys option:
publish_user = relationship(User, foreign_keys=publishing_user_id,
primaryjoin=publishing_user_id == User.id,
backref=backref('pages', order_by=id))
edit_user = relationship(User, foreign_keys=last_edit_user_id,
primaryjoin=last_edit_user_id == User.id)
A: As of version 0.8, SQLAlchemy can resolve the ambiguous join using only the foreign_keys keyword parameter to relationship.
publish_user = relationship(User, foreign_keys=[publishing_user_id],
backref=backref('pages', order_by=id))
edit_user = relationship(User, foreign_keys=[last_edit_user_id])
Documentation at http://docs.sqlalchemy.org/en/rel_0_9/orm/join_conditions.html#handling-multiple-join-paths
A: I think you almost got it right; only instead of Model names you should use Table names when defining primaryjoin. So instead of
# Define relationships
publish_user = relationship('User', backref = backref('pages', order_by = id),
primaryjoin = "Page.publishing_user_id == User.id")
edit_user = relationship('User',
primaryjoin = "Page.last_edit_user_id == User.id")
use:
# Define relationships
publish_user = relationship('User', backref = backref('pages', order_by = id),
primaryjoin = "pages.publishing_user_id == users.id")
edit_user = relationship('User',
primaryjoin = "pages.last_edit_user_id == users.id")
A: The example in this documentation
http://docs.sqlalchemy.org/en/rel_0_9/orm/join_conditions.html#handling-multiple-join-paths isn't for one-to-many.... I think.
In the one-to-many case here's what worked for me:
class Pipeline(Base):
__tablename__ = 'pipelines'
id = Column(UUID(as_uuid=True), primary_key=True, unique=True, default=uuid.uuid4)
...
input_resources = relationship("Resource", foreign_keys="Resource.input_pipeline_id")
output_resources = relationship("Resource", foreign_keys="Resource.output_pipeline_id")
...
class Resource(Base):
__tablename__ = 'resources'
id = Column(UUID(as_uuid=True), primary_key=True, unique=True, default=uuid.uuid4)
....
input_pipeline_id = Column(UUID(as_uuid=True), ForeignKey("pipelines.id"))
output_pipeline_id = Column(UUID(as_uuid=True), ForeignKey("pipelines.id"))
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: UIView animation for CGAffineTransformMake not working I have a simple transform animation that moves a UITableViewCell 70 pixels to the left. In the if part, the animation works just fine and I get a smooth transition. However, when the function is called again to put the cell back in its original position, which is the else part, I get no animation. It just returns back to normal but without animation. How can I fix this?
if([[slideArray objectAtIndex:indexPath.row] intValue]==0)
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.4];
selectedCell.transform=CGAffineTransformMakeTranslation(-70, 0);
[UIView commitAnimations];
[slideArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithInt:1]];
}
else
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.4];
selectedCell.transform=CGAffineTransformMakeTranslation(0, 0);
[UIView commitAnimations];
[slideArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithInt:0]];
}
A: try the following animation in else condition this will work fine if you alreadyb have perform translation of if condition....
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.4];
selectedCell.transform=CGAffineTransformMakeTranslation(70, 0);
[UIView commitAnimations];
[slideArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithInt:0]];
if above code not working for you than try the following
[UIView animateWithDuration:0.5
delay:0
options:UIViewAnimationOptionBeginFromCurrentState
animations:(void (^)(void)) ^{
myImageView.transform=CGAffineTransformMakeTranslation(-70, 0);
}
completion:^(BOOL finished){
myImageView.transform=CGAffineTransformIdentity;
}];
[slideArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithInt:0]];
let me know if any issues ..
regards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Filter contentresolver query by date and time - Android I'm using the "MediaStore.Images.Media.EXTERNAL_CONTENT_URI" to query for photos stored on the sd-card. Now I only want photos that were added after some specific date. I'm using the "contentResolver.query()" method to query but I don't understand how to filter by Date_ADDED or DATE_MODIFIED. Can this be done?
Thanks for help!
A: You should be able to do something like this:
Date date = ...;
contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.MediaColumns.DATE_ADDED + ">?",
new String[]{"" + date},
MediaStore.MediaColumns.DATE_ADDED + " DESC");
That will find all images with DATE_ADDED after the specified date, sorted by DATE_ADDED from most recent to oldest.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Adding Google Guava to Android project - significantly slows down the build After adding Google Guava r09 to our Android project the build time increased significantly, especially the DEX generation phase. I understand that DEX generation takes all our classes + all jars we depend on and translates them to DEX format. Guava is a pretty big jar around 1.1MB
*
*Can it be the cause for the build slowdown?
*Are there anything can be done to speed this up?
P.S. Usually I build from Intellij, but I also tried building with Maven - same results.
Thanks
Alex
A: For what it's worth, my gut is that this isn't the cause. It's hard to take a long time doing anything with a mere 1.1MB of bytecode; I've never noticed dex taking any significant time. But let's assume it is the issue for sake of argument.
If it matters enough, you could probably slice up the Guava .jar to remove whole packages you don't use. It is composed of several pieces that aren't necessarily all inter-related.
I don't think this is going to speed things up, but maybe worth mentioning: if you run the build through Proguard (the optimizer now bundled with the SDK), it can remove unused classes before you get to DEX (and, do a bunch of other great optimization on the byte code). But of course that process probably takes longer itself than dex-ing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Recreating a shell-like interpreter within python? Before I sit down and start hacking it out, I thought I'd come here and see if you all had any tips or even if something like this has been done before.
I want to re-create a basic shell like syntax within a python program. In other words, when people run the file with python, they will be greeted with a little prompt
>>
For simple things, using an option parser to say
opt.parse_args(input.split(" "))
Works just fine, but now I would like to not only escape special characters like spaces with the '\' character, but also treat quoted strings as a single argument, like in a unix shell.
Does there exist anything that might already help with this?
Thanks for any suggestions!
- Chase
A: Have you seen shlex from the standard library? Check out this example.
A: Start with the shlex module:
$ pydoc shlex
Help on module shlex:
NAME
shlex - A lexical analyzer class for simple shell-like syntaxes.
You can use it like this:
>> import shlex
>> shlex.split('This "is a" test.')
['This', 'is a', 'test']
This just splits things up into logical tokens; it won't do anything like variable expansion and so forth. That's still up to you, as is actually running commands.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can i read the first XML comment in PHP? How can I read the first and only comment in PHP:
<?xml version="1.0" encoding="UTF-8"?>
<!-- read this -->
<root>
</root>
using DOMDOcument object?
$xml = new DOMDocument();
$libxml_error = 'Il file %s non risulta ben formato (%s).';
// Per evitare i warning nel caso di xml non ben formato occorre sopprimere
// gli errori
if (!@$xml -> load($xml_file_path)) $error = sprintf($libxml_error,
$xml_file_path, libxml_get_last_error()->message);
// Read the fist comment in xml file
A: What about this:
$xpath = new DOMXPath($xml);
foreach ($xpath->query('//comment()') as $comment) {
var_dump($comment->textContent);
}
Since you probably only want the first one:
$xpath = new DOMXPath($xml);
$results = $xpath->query('//comment()');
$comment = $results[0];
var_dump($comment);
Source: How to retrieve comments from within an XML Document in PHP
A: How to get the comments from XML file - look for instructions here:
How to retrieve comments from within an XML Document in PHP
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove file extension I have this:
$name = $_FILES['file']['name'];
$skin_name = $_POST['nameXXXXXC'];
$price = $_POST['amount'];
$by = $_COOKIE['userName'];
$KS84JMCN = substr($name, 0,strrpos($name,'.'));
mysql_query("
INSERT INTO `Skins`(
`Name`,
`Skin_Name`,
`Price`,
`Made_By`
) VALUES (
'$KS84JMCN',
'$name',
'$price',
'$by'
)");
But it's not removing the file extension, in the database, under 'Name' is the file name but with .png at the end, so it's not removing the file extension.
A: $name = 'lol.lol.jpg';
echo pathinfo($name, PATHINFO_FILENAME); // lol.lol
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: OpenGL, disabling a texture unit, glActiveTexture and glBindTexture How do I turn off a texture unit, or at least prevent its state changing when I bind a texture? I'm using shaders so there's no glDisable for this I don't think. The problem is that the chain of events might look something like this:
Create texture 1 (implies binding it)
Use texture 1 with texture unit 1
Create texture 2 (implies binding it)
Use texture 2 with texture unit 2
, but given glActiveTexture semantics, it seems this isn't possible, because the create of texture 2 will become associated with the state of texture unit 1, as that was the last unit I called glActiveTexture on. i.e. you have to write:
Create texture 1
Create texture 2
Use texture 1 with texture unit 1
Use texture 2 with texture unit 2
I've simplified the example of course, but the fact that creating and binding a texture can incidentally affect the currently active texture unit even when you are only binding the texture as part of the creation process is something that makes me somewhat uncomfortable. Unless of course I've made an error here and there's something I can do to disable state changes in the current glActiveTexture?
Thanks for any assistance you can give me here.
A: This is pretty much something you just have to learn to live with in OpenGL. GL functions only affect the current state. So to modify an object, you must bind it to the current state, and modify it.
In general however, you shouldn't have a problem. There is no reason to create textures in the same place where you're binding them for use. The code that actually walks your scene and binds textures for rendering should never be creating textures. The rendering code should establish all necessary state for each rendering (unless it knows that all necessary state was previously established in this rendering call). So it should be binding all of the textures that each object needs. So previously created textures will be evicted.
And in general, I would suggest unbinding textures after creation (ie: glBindTexture(..., 0)). This prevents them from sticking around.
And remember: when you bind a texture, you also unbind whatever texture was currently bound. So the texture functions will only affect the new object.
However, if you want to rely on an EXT extension, there is EXT_direct_state_access. It is supported by NVIDIA and AMD, so it's fairly widely available. It allows you to modify objects without binding them, so you can create a texture without binding it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: FFmpeg decoding H264 I am decoding a H264 stream using FFmpeg on the iPhone. I know the H264 stream is valid and the SPS/PPS are correct as VLC, Quicktime, Flash all decode the stream properly. The issue I am having on the iPhone is best shown by this picture.
It is as if the motion vectors are being drawn. This picture was snapped while there was a lot of motion in the image. If the scene is static then there are dots in the corners. This always occurs with predictive frames. The blocky colors are also an issue.
I have tried various build settings for FFmpeg such as turning off optimizations, asm, neon, and many other combinations. Nothing seems to alter the behavior of the decoder. I have also tried the Works with HTML, Love and Peace releases, and also the latest GIT sources. Is there maybe a setting I am missing, or maybe I have inadvertently enabled some debug setting in the decoder.
Edit
I am using sws_scale to convert the image to RGBA. I have tried various different pixel formats with the same results.
sws_scale(convertCtx, (const uint8_t**)srcFrame->data, srcFrame->linesize, 0, codecCtx->height, dstFrame->data, dstFrame->linesize);
I am using PIX_FMT_YUV420P as the source format when setting up my codec context.
A: What you're looking at is ffmpeg's motion vector visualization. Make sure that none of the following debug flags are set:
avctx->debug & FF_DEBUG_VIS_QP
avctx->debug & FF_DEBUG_VIS_MB_TYPE
avctx->debug_mv
Also, keep in mind that decoding H264 video using the CPU will be MUCH slower and less power-efficient on iOS than using the hardware decoder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I troubleshoot Delayed Job procs that are failing silently? I will start Delayed Job with the following command:
script/delayed_job -n 4 start
Then at the end of the day I will check to see how many processes I have left, and there might be two. Or zero.
I can't figure out what is causing the procs to die. The logs are huge, I don't see how I can use them to figure it out. Is there something I can do to troubleshoot Delayed Job in this fashion?
A: Some starting points to consider:
*
*wrap your calls into a rescue block and send yourself an email when something crashes.
*create an at exit handler to see if the program exits normally.
*use some kind of processing monitor to see when your processes end. Something like god perhaps, even though I'm not familiar with it.
Hope this is a good start, good luck with figuring it out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Session doesn't get cleared I have a google chrome extension talking to a PHP script via XHR. I have a flag in the PHP script to check if a button is clicked in a popup if proper POST data is sent. If this button is clicked, the current session needs to be destroyed and when new data is entered by clicking the add button it shouldn't be appending data to an existing session but start a new one instead. It's currently just re-appending the data to the array. It's as if the clear session command is being ignored, however the IF statement is being called correctly to the console. How do I get the clear session statement to clear the session?
PHP script:
<?php $json = $_POST['data'];
if($json['button'] == "clear"){
session_unset();
session_destroy();
echo 'session destroyed!'; //being called to console
exit();
}
if (!isset ($_COOKIE[ini_get($_SESSION['data'])])) {
session_start();
}
if(!isset($_SESSION['data'])){
$_SESSION['data'] = $json;
} elseif (isset($_SESSION['data'])){
array_push($_SESSION['data'], $json);
}
print_r($_SESSION['data']);
?>
A: You must call session_start() first:
if($json['button'] == "clear")
{
session_start(); // <-- first
session_unset();
session_destroy();
echo 'session destroyed!'; //being called to console
exit();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android- Get hash code from server my app connected to the server , once the server receive the data , it will send a hash code as response ... my questions is how to get this hashcode ?
I use the following code to POST data :
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://somepostaddress.com";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "kris"));
params.add(new BasicNameValuePair("pass", "xyz"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
A: Use EntityUtils.toString(HttpEntity), this returns the response as a String.
A: URL url = new URL(url_str);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream();
This is what i did for GET, it should work for POST too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass selected uitableviewcell variable to previous viewcontroller? This is the first time I have tried to do this and I understand the concept of what I am trying to do but just not 100% sure on how to execute it.
I have a main view and a sub view.. the main view has several custom uitableviewcells each with a single textlabel. when the cell is selected it loads the subview onto the navigational stack, their is a list of standard uitableviews that I have loaded with values from the database.
When you select one of these uitableviewcells in the sub view, I want to capture that value pop the current view from the stack and then load the selected value of the subview into the main tableviews cell that was originally selected..
In the sub view I am thinking something along the lines of
MainViewController *mvc = [[MainViewController alloc] initWithNibName:@"MainViewController" objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:mvc animated:YES];
[mvc release];
But this obviously this isnt passing any values around...
A: You want to use delegation, if you don't know how to use it, this link might help:
http://cocoadevcentral.com/articles/000075.php
So the general idea is that your main view will be the delegate of your subview, and the subview will tell it's delegate when a cell was tapped and pass in that variable (for example: [delegate cellChanged:cell];), then the main view (the delegate of the subview) will handle that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do i include a variable in a nsurl iphone this is what i have
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
responseData = [[NSMutableData data] retain];
results = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search/json?location=38.69747988499999,-121.3570182875&radius=9900&types=bar&sensor=false&key=fake_key"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
return YES;
}
and with the url i would like to have a variable in there for the location. basically my app is getting the location and i would like to implement this into the url so i can find the bars that are around.... how would i do this
i was thinking
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
responseData = [[NSMutableData data] retain];
results = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search/json?location=%@,%@&radius=9900&types=bar&sensor=false&key=fake_key", longitude,latitude]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
return YES;
}
but it didnt work
please help
A: Use +stringWithFormat from NSString:
[NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%@,%@&radius=9900&types=bar&sensor=false&key=fake_key", longitude,latitude]]
A: So I am seeing a lot of people using NSURL and I believe that if they were to look at an ASIFormDataRequest they would find that it is much safer and much easier to use. In order to use an ASIFormDataRequest you must download it from here http://allseeing-i.com/ASIHTTPRequest/How-to-use
However once that is downloaded it makes life much easier. The reason I point this out is because it forces everything to conform to a protocol so you would know if you are having issues because of an %f or an %@ because it forces you to use a string. It make it a lot easier for debugging. Here is some example code of how to use an ASIFormData Request
NSURL *url = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search/json"];
ASIFormDataRequest *request_ror = [ASIFormDataRequest requestWithURL:url];
[request_ror setRequestMethod:@"POST"];
[request_ror setPostValue:[NSString stringWithFormat:@"%f", longitude] forKey:@"longitude"];
[request_ror setValidatesSecureCertificate:NO];
[request_ror setTimeOutSeconds:30];
[request_ror setDelegate:self];
[request_ror startAsynchronous];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to avoid casting from interface to class In trying to design a collision detection component for a game, I came up with the following solution. I define an interface ICollideable that looks something like:
interface ICollideable
{
Sprite Sprite { get; }
int Damage { get; }
void HandleCollision(ICollideable collidedWith);
}
Basically, any game objects that want to participate in collision detection have to implement this interface, then register themselves with the detector, which maintains a list of ICollideables. When it detects a collision, it calls the HandleCollision method on the object and passes in a reference to the object it collided with.
I like this, because it lets me keep all my collision algorithms in one place, and lets the game objects themselves decide how to handle the collision. But because of the latter, I find I am having to check the underlying object type. For example, I don't want Players to collide with each other, so in the Player class there might be something like:
void HandleCollision(ICollideable collidedWith)
{
if (!(collidedWith is Player)) { // do stuff }
}
and so on, and I am wondering if this is telling me that I have a bad design and what the alternatives might be.
Second question, further along the lines of the first. For scoring purposes, if an Enemy is destroyed by a Projectile, someone needs to know the "Owning Player" member of the Projectile class. However, none of my other collideables have or need this property, so I find myself wanting to do (in the Enemy HandleCollision):
void HandleCollision(ICollideable collidedWith)
{
if (collidedWith is Projectile) {
Health -= collidedWith.Damage;
if (Health <= 0) {
Player whoDestroyedMe = (collidedWith as Projectile).FiredBy
// ...
}
}
}
I haven't a clue as to how to handle this with a better design. Any insights would be appreciated.
EDIT: I wanted to pull focus towards the second question, because my gut tells me a way of handling this will solve the first question. As for the first question, I thought of a way to abstract this behavior. I could define an enum:
enum Team
{
Player,
Enemy,
Neither
}
and have ICollideables implement this property. Then the collision detector simply doesn't register collisions between collideables on the same "Team". So, Player and Player Projectiles would be on one team, Enemy and Enemy Projectiles on the other, and the environment (which can damage both) can be on neither. It doesn't have to be an enum, could be an int or a string or anything, with the idea that objects with the same value for this property do not collide with each other.
I like this idea of modeling behavior with a simple attribute. For instance, if I want to turn "allow friendly fire" on, all I have to do is create Projectiles with a Team value other than the Player's Team value. However, I still may have cases where this is not enough. For example, a Player may have shields that are temporarily impervious to projectiles but will not protect against a direct collision with an enemy, and so on.
A: I think you're going the wrong way altogether in handling the collision inside of the class of one of the colliders. I would put this logic into a third object, outside of the entity objects. You could do all of the checking of the types in this third object, and even handle most of the logic there too. Why should a Ship or a Projectile have a monopoly over the logic that happens when one hits the other?
The following is how I might handle this, although it means using an object for each style of collision (Ship vs Ship, Ship vs Projectile, Ship vs Asteroid, etc.) You might be more comfortable putting all that logic into a single object, or even a single method on that object.
public interface ICollisionHandler
{
bool HandleCollision(Entity first, Entity second);
}
public class PlayerShipVsProjectile : ICollisionHandler
{
private GameOptions options;
public PlayersOwnShipHandler(GameOptions options)
{
this.options = options;
}
public bool HandleCollision(Entity first, Entity second)
{
// Exactly how you go about doing this line, whether using the object types
// or using a Type property, or some other method, is not really that important.
// You have so much more important things to worry about than these little
// code design details.
if ((!first is Ship) || (!second is Projectile)) return false;
Ship ship = (Ship)first;
Projectile projectile = (Projectile)second;
// Because we've decided to put this logic in it's own class, we can easily
// use a constructor parameter to get access to the game options. Here, we
// can have access to whether friendly fire is turned on or not.
if (ship.Owner.IsFriendlyWith(projectile.Shooter) &&
!this.options.FriendlyFire) {
return false;
}
if (!ship.InvulnerableTypes.Contains(InvulnerableTypes.PROJECTILE))
{
ship.DoDamage(projectile.Damage);
}
return true;
}
}
Like this, you can then do...
// Somewhere in the setup...
CollisionMapper mapper = new CollisionMapper();
mapper.AddHandler(new ShipVsProjectile(gameOptions));
mapper.AddHandler(new ShipVsShip(gameOptions));
// Somewhere in your collision handling...
mapper.Resolve(entityOne, entityTwo);
The implementation of CollisionMapper is left as an exercise for the reader. Remember that you might need to have Resolve call the ICollisionHandler's "Handle" method twice, with the second time reversing the entities (otherwise your collision handler objects will need to check for the reverse situation, which might be ok as well).
I feel this makes the code easier to read. A single object describes exactly what will happen when two entities collide, rather than trying to put all this info into one of the entity objects.
A: For the first case, I would add the following extra method to ICollidable:
bool CanCollideWith(ICollidable collidedWith)
As the name suggests, it would return true or false depending upon whether it can collide with the passed in object.
Your Player.HandleCollision method would just do its stuff because the calling method could do that test and not even call the method if it wasn't required.
A: How about something like this?
Collidable.cs
abstract class Collidable
{
public Sprite Sprite { get; protected set; }
public int Damage { get; protected set; }
protected delegate void CollisionAction(Collidable with);
protected Dictionary<Type, CollisionAction> collisionTypes = new Dictionary<Type, CollisionAction>();
public void HandleCollision(Collidable with)
{
Type collisionTargetType = with.GetType();
CollisionAction action;
bool keyFound = collisionTypes.TryGetValue(collisionTargetType, out action);
if (keyFound)
{
action(with);
}
}
}
Bullet.cs
class Bullet: Collidable
{
public Bullet()
{
collisionTypes.Add(typeof(Player), HandleBulletPlayerCollision);
collisionTypes.Add(typeof(Bullet), HandleBulletBulletCollision);
}
private void HandleBulletPlayerCollision(Collidable with)
{
Console.WriteLine("Bullet collided with {0}", with.ToString());
}
private void HandleBulletBulletCollision(Collidable with)
{
Console.WriteLine("Bullet collided with {0}.", with.ToString());
}
}
Player.cs
class Player : Collidable
{
public Player()
{
collisionTypes.Add(typeof(Bullet), HandlePlayerBulletCollision);
collisionTypes.Add(typeof(Player), HandlePlayerPlayerCollision);
}
private void HandlePlayerBulletCollision(Collidable with)
{
Console.WriteLine("Player collided with {0}.", with.ToString());
}
private void HandlePlayerPlayerCollision(Collidable with)
{
Console.WriteLine("Player collided with {0}.", with.ToString());
}
}
A: I think this is a good question @idlewire and I have to say that I don't think there is anything fundamentally wrong with your original solution. In asking whether object Foo should be allowed to cast the ICollideable to a Bar, the important question is only: is undesirable to have Foo knowing anything at all about Bar? If the answer is 'no' because Foo already knows about Bars (for behaviours other than collisions, perhaps) then I see no problem in the cast and, as you say, it allows you to better encapsulate the behaviour of both.
Where you need to be wary is only where this would introduces a dependency between two things you'd like kept apart - which would make re-use of either without the other (in a different game application for example) impossible. There you might want to either have more specific sub-interfaces from ICollideable (e.g. IElastic and IInelastic), or use properties on the interface as you have proposed with the Enum.
In short, I think your original posting shows good evidence of OO thinking, not bad.
A: Sometimes the simplest method is the best method. Unless you want to separate your collision interactions into numerous subtypes, you could instead place a bool IsPlayer property within the Interface.
The upside here is that you have a cheaper, and type safe method of determination over casting.
If (isplayer == true)
{
Handlethisway;
}
The downside is that you're still having to do some sort of state checking, but this is more efficient.
To avoid any state checks, you'd need to do the following: Make an ICollidablePlayer Interface which accepts generic Icollideable and handles them differently. Since the Icollideable is your injected dependency, the ICollideablePlayer dependencies are inherent. The objects of Icollideable would have no knowledge of this separate process, and interact with each other in the same manner.
ICollideablePlayer:ICollideable
{
//DependenciesHere
HandlePlayerCollision(ICollideable)
{
HandleDifferently
{
}
ICollideable
{
//DependenciesHere
HandleCollision(ICollideable)
}
}
}
In an interaction, the ICollideable will treat the player as any other ICollideable, but the ICollideablePlayer will reject the interaction when it does the check itself.
For things like shields and all that, You're talking about state changes which implies that those such things should be properties within either of those Interfaces such that something like bool ColliderOff to temporarily change the state.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How to normalize benchmark results to obtain distribution of ratios correctly? To give a bit of the context, I am measuring the performance of virtual machines (VMs), or systems software in general, and usually want to compare different optimizations for performance problem. Performance is measured in absolute runtime for a number of benchmarks, and usually for a number of configurations of a VM variating over used number of CPU cores, different benchmark parameters, etc. To get reliable results, each configuration is measure like 100 times. Thus, I end up with quite a number of measurements for all kind of different parameters where I am usually interested in the speedup for all of them, comparing the VM with and the VM without a certain optimization.
What I currently do is to pick one specific series of measurements. Lets say the measurements for a VM with and without optimization (VM-norm/VM-opt) running benchmark A, on 1 core.
Since I want to compare the results of the different benchmarks and number of cores, I can not use absolute runtime, but need to normalize it somehow. Thus, I pair up the 100 measurements for benchmark A on 1 core for VM-norm with the corresponding 100 measurements of VM-opt to calculate the VM-opt/VM-norm ratios.
When I do that taking the measurements just in the order I got them, I obviously have quite a high variation in my 100 resulting VM-opt/VM-norm ratios. So, I thought, ok, let's assume the variation in my measurements come from non-deterministic effects and the same effects cause variation in the same way for VM-opt and VM-norm. So, naively, it should be ok to sort the measurements before pairing them up. And, as expected, that reduces the variation of course.
However, my half-knowledge tells me that is not the best way and perhaps not even correct.
Since I am eventually interested in the distribution of those ratios, to visualize them with beanplots, a colleague suggested to use the cartesian product instead of pairing sorted measurements. That sounds like it would account better for the random nature of two arbitrary measurements paired up for comparison. But, I am still wondering what a statistician would suggest for such a problem.
In the end, I am really interested to plot the distribution of ratios with R as bean or violin plots. Simple boxplots, or just mean+stddev tell me too few about what is going on. These distributions usually point at artifacts that are produced by the complex interaction on these much to complex computers, and that's what I am interested in.
Any pointers to approaches of how to work with and how to produce such ratios in a correct way a very welcome.
PS: This is a repost, the original was posted at https://stats.stackexchange.com/questions/15947/how-to-normalize-benchmark-results-to-obtain-distribution-of-ratios-correctly
A: I found it puzzling that you got such a minimal response on "Cross Validated". This does not seem like a specific R question, but rather a request for how to design an analysis. Perhaps the audience there thought you were asking too broad a question, but if that is the case then the [R] forum is even worse, since we generally tackle problems where data is actually provided. We deal with the requests for implementation construction in our language. I agree that violin plots are preferred to boxplots for the examination of distributions (when there is sufficient data and I am not sure that 100 samples per group makes the grade in that instance), but in any case that means the "R answer" is that you just need to refer to the proper R help page:
library(lattice)
?xyplot
?panel.violin
Further comments would require more details and preferably some data examples constructed in R. You may want to refer to the page where "great question design is outlined".
One further graphical method: If you are interested in the ratios of two paired variates but do not want to "commit" to just x/y, then you can examine them by plotting and then plotting iso-ratio lines by repeatedly using abline(a=0, b= ). I think 100 samples is pretty "thin" for doing density estimates, but there are 2d density methods if you can gather more data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mongo - most efficient way to $inc values in this schema I'm a Mongo newbie, and trying to make this schema work.
Its intended for logging events as they happen on a high traffic website - just incrementing the number of times a certain action happens.
{
_id: "20110924",
Vals:[
{ Key: "SomeStat1": Value: 1},
{ Key: "SomeStat2": Value: 2},
{ Key: "SomeStat3": Value: 3}
]
}
,
{
_id: "20110925",
Vals:[
{ Key: "SomeStat1": Value: 3},
{ Key: "SomeStat8": Value: 13},
{ Key: "SomeStat134": Value: 63}
]
}, etc.
So _id here is the date, then an array of the different stats, and the number of times they've occurred. There may be no stats for that day, and the stat keys can be dynamic.
I'm looking for the most efficient way to achieve these updates, avoiding race conditions...so ideally all atomic.
I've got stuck when trying to do the $inc. When I specify that it should upsert, it tries to match the whole document as the conditional, and it fails on duplicate keys. Similarly for $addToSet - if I addToSet with { Key:"SomeStat1" }, it won't think it's a duplicate as it's matching against the entire document, and hence insert it alongside the existing SomeStat1 value.
What's the best approach here? Is there a way to control how $addToSet matches? Or do I need a different schema?
Thanks in advance.
A: You're using a bad schema, it's impossible to do atomic updates on it. Do it like this:
{
_id: "20110924",
Vals: {
SomeStat1: 1,
SomeStat2: 2,
SomeStat3: 3,
}
}
or you can skip The Vals subdocument and embed the stats in the main document.
A: Take a look at this article which explains the issues around serializing a Dictionary using the MongoDB C# driver. See also this work item on the C# driver.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php conditional regex problem I'm having a tough time sorthing this out. I'm working with a custom plugin system that presents things like this:
<plugin:class:method var1='hello', var2='yes' />
But, ':method' and the variables do not have to exist - only the 'class' is required. For instace, this should still be ok:
<plugin:class />
The problem I'm having is how to I get the regex to conditionally return things when the method and/or variables do not exist. So far, I can get results when all the pieces exist, but not otherwise - this is where I'm at (struggling on the first conditional):
$f = "/<plugin:(?P<class>\w+)(?(?=^:)?P<method>\w+)\s+(.*)\/>/sUi";
Things are working very well with the following code, it's simply a matter of being able to return all the pieces with the conditionals:
preg_replace_callback($f, array($this, 'processing'), $text);
Hope this makes some sense - and is even possible. Thanks.
A: The easiest and most maintainable way to do this would be to just get the whole plugin:class:method string with a simple /plugin:\S+/ expression, then explode(':', $string).
So, instead of the code above, you'd have something like:
$f = "/<plugin:(\S+)\s+(.*?)\/>/sUi";
if (preg_match($f, $string, $matches)) {
$parts = explode($matches[1]);
if (!in_array('method', $parts))
{
// do whatever needs done if "method" is not present
}
// ...
}
A: Shouldn't (?=^:) be (?!:) ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Could not load file or assembly 'AjaxControlToolkit, <tt:TooltipExtender ID="teAutoServiceShutdown" TargetControlID="cbAutoServiceShutdown"
Parser Error Message: Could not load file or assembly 'AjaxControlToolkit, Version=3.0.20820.16598, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
what to do?
A: I know this question is nearly a year old, but I just ran into this problem myself. I solved it by simply doing "Build -> Clean Solution" which I guess cleared the assembly cache.
A: Few possible ways:
*
*Read How the Runtime Locates Assemblies and then try to figure out whether an assembly is referenced correctly and is in any of the expected path (basically you can manually go through the assembly resolving steps yourself and see whether you are able to find reference yourself ;) )
*Remove a reference from project file (and I believe web.config), cleanup solution, add reference again
*Build project manually using msbuild YourSolution.sln /v:diag > log.txt command line and then see generated log.txt file for any issues while an assembly reference resolving
*Use filemon tool to see where Visual Studio trying to find a file
A: The build Output window should give you a fix/workaround for this problem.
Clean and rebuild the solution.
Examine the contents of the Output window, look for this text:
Consider app.config remapping of assembly "AjaxControlToolkit, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e" from Version "4.1.40412.0" [C:\Visual Studio\App\Lib\bin\Debug\AjaxControlToolkit.dll]
Following this there will be a fragment you can paste into the <assemblyBinding> section of your web.config.
C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3247:
Found conflicts between different versions of the same dependent assembly.
In Visual Studio, double-click this warning (or select it and press Enter) to fix the conflicts;
otherwise, add the following binding redirects to the "runtime" node in the application configuration file:
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="AjaxControlToolkit" culture="neutral" publicKeyToken="28f01b0e84b6d53e" />
<bindingRedirect oldVersion="0.0.0.0-16.1.0.0" newVersion="16.1.0.0" />
</dependentAssembly>
</assemblyBinding>
Once you paste that in and rebuild it should automatically reference the version of the Toolkit specified as the newVersion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: using $_SESSION['fb_'.APP_ID.'_user_id'] I'm developing a fb application with php sdk 3.0 and I've noticed that Facebook starts a session that contain the app_ID like that: $_SESSION['fb_'.APP_ID.'_user_id'];
This session store the facebook uid of the connected user.
Is this a feature of PHP SDK or is not recommended to work with this session?
To explain: After login successfully to my fb app, I use this function to see the php sessions print_r($SESSION); and there is a session $_SESSION['fb_173620963485_user_id'] = 123456;WHERE 173620963485 is my appID and 123456 is my fb uid.
Is recommended to work with this session: $_SESSION['fb_173620963485_user_id'] ?
A: You don't use this session for anything. Period.
A: You should never need to touch the $_SESSION['fb_..._user_id'] variable. Use the SDK like the documentation states and you will be much better off. If you want access to the user ID, just use:
$uid = $facebook->getUser();
Take the time and read the documentation, and that should help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: ActionLink does not create the right link This is super straight forward, but somehow it is not working. Can you please take a look?
on my page I have:
<%= Html.ActionLink("My Recipes", "Index", "Recipes")%>
and i have the following controller:
namespace MyWebSite.Controllers
{
public class RecipesController : Controller
{
//
// GET: /Recipes/
public ActionResult Index()
{
return View();
}
the html that is generated is:
<a href="">My Recipes</a>
while I expect it to be:
<a href="/Recipes/Index">My Recipes</a>
My controller is named: RecipesController.cs and is in the Controllers folder with all my other controllers?
Whats wrong?
Many thanks!
A: You seem to have messed up with your routes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Clearing Inner Float I'm developing a web page that has an outer floated left column and a regular right column.
The right column then contains a list of items where each item has a floated left column and a regular right column.
My problem is when a list item's right column isn't tall enough, the next list item is indented to be to the right of the previous item's left column.
Convoluted? Okay, well I've posted the basic layout online.
I then removed items from a sublist so that one list item's right column isn't tall enough.
Finally, I tried correcting the problem using clear:both. The problem is that this clears the very outer floating div.
Is there any way to clear a floated element without clearing another, outer floated element?
A: In addition to your clear: both style, add an overflow: hidden or overflow: auto style to .MainRightCol to give it its own block formatting context:
.MainRightCol {
background-color:#f5f5f5;
overflow:auto;
}
This prevents the clear: both from clearing the .MainLeftCol float, because
The 'clear' property does not consider floats inside the element itself or in other block formatting contexts.
and the context which .MainLeftCol lives in is body's (or the viewport's, I'm not exactly sure), so that's outside of .MainRightCol's and its .ListItem children's, which you apply the clear to.
See the updated demo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to show output after executing stored procedure in mssql and php $server = 'x.x.x.x\SQLEXPRESS';
// Connect to MSSQL
$link = mssql_connect($server, 'username', 'password');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else
{
echo "Connected!";``
}
$selected = mssql_select_db('dbname', $link)
or die("Couldn't open database ")
$proc = mssql_init('sp_Index', $link);
$proc_result = mssql_execute($proc);
how to show result from $proc_result. my stored procedure is sp_index. i dont know the structure sp_index
A: What about mssql_fetch_array()?
while ($row = mssql_fetch_array($proc_result)
{
// Do your thing with $proc['column_name']
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "Recent Solutions" List with multiple versions of MonoDevelop I'm working on Ubuntu 11.04, and am using MonoDevelop 2.4 for my C# and other CLI development. I'm using this version since it's provided in the repos. But I just built MonoDevelop 2.6, mostly to play around with, see what's new, and also 'cause that's the version when I work on Windows.
All around, the two play nice together, but there's one place where they share some data that I'd rather they didn't share - the "Recent Projects" list on the welcome page. Preferrably, I'd like to have 2.4 only show projects used with that version, while 2.6 should show the projects pertaining to it. But as things are right now, any project made or used by 2.4 show up in the list for 2.6 and vice versa.
Does anyone know how to change this? I don't know my way around Ubuntu all that well yet, and I'm not familiar with the innards of MonoDevelop either, so sorry if it's something that should be obvious.
A: After digging through the MonoDevelop 2.6.0.1 source code straight since yestercday, I finally found the necessary code change. I guess I'll put this up for the sake of reference, in case anyone's interested.
It turns out that the "Welcome Page" in MonoDevelop is representd by the WelcomePage addin. In turn, the visual side of the addin is represented by the class MonoDevelop.WelcomePage.WelcomePageView. In here is a method GetRecentProjects() which actually retrieves the list of projects to display.
Through this method, control makes its way down to the DefaultPath property in the RecentFileStorage class, which gives the location where the recent projects xml is stored by default. It's defined as
public static string DefaultPath {
get {
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".recently-used");
}
}
The Environment.SpecialFolder.Personal enumerated value represents the current user's personal folder; in my case, it's /home/ken Note that no version info is present here. This means that the recent files list will always refer to the file /home/ken/.recently-used, regardless of which of version of MonoDevelop you're running. Also, the layout of the file does not accommodate multiple versions, so the only way is to redirect the location of this file. This is easily done, by changing the above property to something like
public static string DefaultPath {
get {
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MonoDevelop2_6", ".recently-used");
}
}
before building.
I personally think that these sorts of things should be separated, and since it's an easy change I'm probably going to push for some versioning information to be added to the path of the .recently-used file, or otherwise have it added to the contents of the file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Looping and finding empty array I'm working on project in which I have to create a search engine through jQuery. Everything has been going great until I started looping through the array.
I don't know whether I'm doing it wrong, but for some reason, when I use a conditional it does not output the statement I want it to say. If I change the conditional to say whether there's something in the array output this, it does. But if the array is empty it does absolutely nothing. Why is that?
for(var i = 0, j = response.length; i < j; i++){
var searchItemRes = response[i];
if(response.length === 0){
$('' + '<ul>' +
'<li><span>Nothing found, try again</span></li>' +
'</ul>'
).appendTo(searchResults);
}
$('' + '<ul>' +
'<li><img src="" /><span> '+searchItemRes.title+'</span></li>' +
'</ul>'
).appendTo(searchResults);
}
A: Consider this:
// declare local variables
var str, i, item;
// build the HTML source code string
if ( response.length === 0 ) {
str = '<ul><li><span>Nothing found. Please, try again.</span></li></ul>';
} else {
str = '<ul>';
for ( i = 0; i < response.length; i += 1 ) {
item = response[i];
str += '<li><img src=""><span> ' + item.title + '</span></li>';
}
str += '</ul>';
}
// append the string to the DOM
$( searchResults ).append( str );
First off, declare the local variables at the top of the function. As you can see, my code uses 3 local variables.
Next, I doubt that you want to create one UL (list-holder) for each result. It makes more sense to have one UL element which contains all the results (which is what I've implemented in the above code).
Also, I recommend manipulating the DOM only once at the end - the live-DOM should be touched as few times as possible. Therefore, the above code builds the HTML source code string "off-DOM", and only in the end appends (the whole thing) to the DOM.
A: for (var i = 0, j = response.length; i < j; i++){
var searchItemRes = response[i];
if (response.length === 0) {
$('<ul><li><span>Nothing found, try again</span></li></ul>').appendTo(searchResults);
}
...
}
That condition will never be executed. If i = 0 and j = response.length and it's iterating i < j then it won't iterate at all if response.length == 0 because 0 < 0 will just break out of the loop.
A: How can code that triggers on response.length == 0 ever execute inside a loop that iterates response.length times?
Perhaps you meant:
if (response.length === 0) {
$('<ul><li><span>Nothing found; try again</span></li></ul>').appendTo(searchResults);
}
else {
for (var i = 0, j = response.length; i < j; i++) {
var searchItemRes = response[i];
$('<ul>' +
'<li><img src="" /><span>' + searchItemRes.title + '</span></li>' +
'</ul>'
).appendTo(searchResults);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Unit testing datamodel : related entities I'm new to unit testing & TDD and after reading some articles i decided to start TDD in a small project of mine. it's a simple Theater Ticket Booking which uses NHibernate & also Repository pattern. i decided to first write some tests for my data model, so i started with simple CRUD operations on entities. the first problem that i faced was entities with many-to-one relations. for example i have a Show entity which has a many-to-one association to the Director entity (each Show has a Director), so for testing the Show.Create method i had to create a Director entity to assign him the Show first.
Since unit testing strongly discourage writing dependent tests, how could i get over this problem without making any dependency to such related entities?
A: I find it helps to think of TDD as writing an example of how to use something, and why the behavior is interesting.
So for instance, in your application you might have this behavior:
A show is associated with a director when it's created.
However, that's not very interesting. Why is this valuable? Where is it used? If you can show some aspect of behavior in which this is important, that's more interesting.
A show's reputation starts off with its director's reputation.
You can then write an example of this behavior:
Given a director with a reputation of 75%
When he creates a new show
Then the show should start with a reputation of 75%.
That would be more interesting behavior. We can actually create a show with that reputation, without using Hibernate. I sometimes put examples like this as comments in the test. (I'm using this as an example, since I have no idea why creating a show with a director is important to you!)
For something like NHibernate, either use full-stack scenarios that cover the entire application, or integration tests which just check the mappings by constructing a show with its director, or check manually that the application works. You can assume that NHibernate will continue to work if you're using it in the right way, so you need fewer tests around it compared to the code you're going to change.
My experience is that it's OK to create real domain objects (Show, Director, etc.) rather than mocking them out. However, if you have any complex calculations - for instance, perhaps there are complexities to calculating the reputation of a Show once it's been on for several nights - then you can inject a mock to help with that, and your behavior will change accordingly:
A show uses the reputation rules for its reputation
// Given the reputation rules
(mock out the reputation)
// When a show is created with a director
(create the show)
// And it's shown for 3 nights with varying reviews
(associate the reviews with the show)
// Then it should use the rules to calculate its reputation
(verify that when you get the reputation, the show asks the mock for help).
Hope this gives you an idea of where it might be useful to mock, and where it's likely that you don't have to. This becomes more natural the more you practice.
A: Just create an IDirector interface that you will put in the constructor of the Show Entity. That way you can create a mockup (test) implementation of your Director before assigning to the show. Just implement the IDirector interface yourself with some dummy data, or us Rhino Mocks. See http://haacked.com/archive/2006/06/23/usingrhinomockstounittesteventsoninterfaces.aspx for an example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Django Performance Tuning Tips? How do you tune Django for better performance? Is there some guide? I have the following questions:
*
*Is mod_wsgi the best solution?
*Is there some opcode cache like in PHP?
*How should I tune Apache?
*How can I set up my models, so I have fewer/faster queries?
*Can I use Memcache?
A: Comments on a few of your questions:
Is mod_wsgi the best solution?
Apache/mod_wsgi is adequate for most people because they will never have enough traffic to cause problems even if Apache hasn't been set up properly. The web server is generally never the bottleneck.
Is there some opcode cache like in PHP?
Python caches compiled code in memory and the processes persist across requests. You thus don't need a separate opcode caching product like PHP as that is what Python does by default. You just need to ensure you aren't using a hosting mechanism or configuration that would cause the processes to be thrown away on every request or too often. Don't use CGI for example.
How should I tune Apache?
Without knowing anything about your application or the system you are hosting it on one can't give easy guidance as how you need to set up Apache. This is because throughput, duration of requests, amount of memory used, amount of memory available, number of processors and much much more come into play. If you haven't even written your application yet then you are simply jumping the gun here because until you know more about your application and production load you can't optimally tune Apache.
A few simple suggestions though.
*
*Don't host PHP in same Apache.
*Use Apache worker MPM.
*Use mod_wsgi daemon mode and NOT embedded mode.
This alone will save you from causing too much grief for yourself to begin with.
If you are genuinely needing to better tune your complete stack, ie., application and web server, and not just prematurely optimising because you think you are going to have the next FaceBook even though you haven't really written any code yet, then you need to start looking at performance monitoring tools to work out what your application is doing. Your application and database are going to be the real source of your problems and not the web server.
The sort of performance monitoring tool I am talking about is something like New Relic. Even then though, if you are very early days and haven't got anything deployed even, then that itself would be a waste of time. In other words, just get your code working first before worrying about how to run it optimally.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Running a code behind routine from an I have a link that looks like a button from this html
<p class="link-styleContact"><a href="#"><span>Email Contact Form</span></a></p>
can I run a code behind file when this is clicked on by adding the routine name to the href? like below
<p class="link-styleContact"><a href="ContactFormClicked"
runat="server"><span>Email Contact Form</span></a></p>
A: You can use the LinkButton control instead and subscribe to the Click event.
It will appear as a link on the browser and you can have your code in the event handler.
aspx:
<asp:LinkButton id="myLink" Text="Hi" OnClick="LinkButton_Click" runat="server"/>
Code behind (VB.NET):
Sub LinkButton_Click(sender As Object, e As EventArgs)
' Your code here
End Sub
Code behind (C#):
void LinkButton_Click(Object sender, EventArgs e)
{
// your code here
}
Alternatively, you can use the HtmlAnchor control and set the ServerClick event handler. This is basically the a element with a runat="server" attribute:
aspx:
<a id="AnchorButton" onserverclick="HtmlAnchor_Click" runat="server">
Click Here
</a>
Code behind (VB.NET):
Sub HtmlAnchor_Click(sender As Object, e As EventArgs)
' your code here
End Sub
Code behind (C#):
void HtmlAnchor_Click(Object sender, EventArgs e)
{
// your code here
}
A: You could use the LinkButton control and handle the Click event.
A: If you want to stick with the <a> tag specifically, then some options:
You can use <a href="http://example.com" onclick="return foo()">, where foo() is a javascript function.
You can also use the page's onload event to handle it, like this:
<a href="http://example.com?e=foo">, and then in the pageload() event, do this: ...if request.querystring("e") = "foo" then...
But otherwise, as others have suggested, the <asp:linkbutton> control is a good choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Flash vs other methods, and, quick and easy I have a question about Flash. I am writing my first browser game, and I am trying to decide on a technology.
I have a few requirements:
*
*I don't want to have to pay to write code and a not-complete-crap free IDE would also be good.
*I want most (or > 70%) of "normal" computer users to have it installed, so, Unity's pretty much out.
*I don't really need performance too much
*I need 2D, not 3D
*Needs to be able to communicate with the server, and no extra downloads required.
*Preferably works with the Facebook platform, but, this isn't a requirment.
Now, I would go with Flash as it fills all of my requirements, but, to my understanding, I need to pay for CS5 to get coding with Flash. Is an alternative around this possible?
Are there any other alternatives I'm missing?
A: Flash, Silervlight or HTML5 will tick pretty much all of those boxes for you, however Silverlight is only installed on ~65% of computers at the moment.
HTML5 can be tough to develop with, so perhaps Flash is your best bet. See the following question which discusses Flash IDEs:
Flash Developer IDE
FlashDevelop is a free development environment for Flash.
A: To add onto what ColinE mentioned, FlashDevelop also provides you the ability to download and install the Flex SDK. However, if FlashDevelop as an IDE doesn't work for you, you can also download the Flex SDK yourself.
This is essentially the same thing that's included with Adobe's Flash Builder application, which is basically built on top of Eclipse. This should at least give you a start on creating things in Flash, though you'll be limited to ActionScript 3. I'd suggest sticking with AS3 as it provides a lot of power compared to AS2.
If you do choose to use the Flex SDK, I'll give you a bit of knowledge I've gained since I started using it for developing games. This may be a little long-winded but hopefully it'll answer some of the initial starter questions.
You can develop apps/games using the Flex library but this may increase the size of your SWF file. However, it's worth noting that it's not required to use the library. You can use the compiler (mxmlc) provided in the SDK to build against .as files as well.
From here, there's a few gotchas that might creep in when it comes to assets. Flex provides you the ability to embed assets within your class files. Out of the box, it allows for the embedding of a handful of formats, most notably PNG, TTF, XML and SWF. There's a lot that you'll be able to do with Flex from a code standpoint but it's not very pretty for creating the assets themselves. Primarily, I use the Flash IDE only for cases where a project requires a SWF asset, however, most of my projects tend to use PNG.
When using an embedded SWF asset, you may come across an issue where any code that's included in the asset, such as any hover or animation logic as ActionScript, gets stripped out of the copy embedded in the resulting project's SWF. A workaround for this is forcing the mimetype to "application/octet-stream" and using a Loader object's loadBytes() method.
Finally, you should be able to make some sort of progress provided you have some sort of ActionScript knowledge. There are plenty of resources out there but be aware that a fair amount of them still use AS2. The knowledge can be applied with some modifications but may require some extra legwork to implement. The language is fairly easy to work with.
With all that, I wish you luck. Flash gets a lot of flack these days but even with HTML5 nearing final, there's still a lot of features that it will never be able to touch without leveraging Flash in some way.
A: I believe your question is about which type of development you should use to get this game going, but I would also urge you to consider the future of each of these software sets, and choose based on what you would like more experience in.
Flash has been holding it's ground pretty well, but I've seen it less and less on major sites these days, and I believe HTML 5 is taking pretty good stabs at it. Even Pandora doesn't use flash anymore, and that was a pretty well designed little flash app (they still use AIR for Pandora One, but not their main site). Instead, like many other websites, it's using HTML and JavaScript.
So, while flash is slowly losing ground to HTML and JavaScript, where does Silverlight stand? Microsoft is still pushing their Silverlight technology, and based on Microsoft's support scheme, they'll still be using it for the next few years at least. At the same time, it's based on the .NET framework, so you'll be gaining some valuable WPF and .NET skills by using Silverlight.
There is no right or wrong decision here, it's really just based on which technology you see yourself using past this product, and which technology you want to learn.
I'd give it a shot in Silverlight, myself, but that's simply because I dislike flash, and there's already too many HTML and JavaScript developers.
edit:
Silverlight is a relatively small 30 second install. I generally hate installing new plugins, but Silverlight is relatively painless, imo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7548132",
"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.